Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
c1e32c9ca6
121 files changed
+6539
-697
No files matched your search
@@ -103,12 +103,14 @@ def create_app(config_name='default'):
|
||||
try:
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
ensure_default_voucher_check_schedule,
|
||||
ensure_default_voucher_po_print_schedule,
|
||||
register_voucher_check_schedule_hooks,
|
||||
)
|
||||
register_voucher_check_schedule_hooks()
|
||||
ensure_default_voucher_check_schedule()
|
||||
ensure_default_voucher_po_print_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
|
||||
logger.warning('Failed to ensure accounting-voucher-check / po-print schedules: %s', exc)
|
||||
try:
|
||||
from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules
|
||||
ensure_default_contract_payment_schedules()
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.core.response import ok
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentAlertBatch,
|
||||
ContractPaymentAttachment,
|
||||
@@ -41,6 +42,8 @@ from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||
|
||||
CONTRACT_PAYMENT_AGENT_CODE = "contract_payment"
|
||||
|
||||
|
||||
def _attachment_parse_priority(attachment: ContractPaymentAttachment) -> tuple[int, int]:
|
||||
"""
|
||||
@@ -74,35 +77,45 @@ def _require_user():
|
||||
return user
|
||||
|
||||
|
||||
def _user_has_contract_payment_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的合同付款预警 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=CONTRACT_PAYMENT_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_contract_payment_access():
|
||||
"""
|
||||
确保当前用户已登录且具备合同付款预警访问权限。
|
||||
|
||||
核心逻辑:登录校验之后读取 `contract_payment.access`;admin 角色默认具备,
|
||||
其他角色需在用户管理中显式授予。无权限时返回业务 403,而不是静默空数据。
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=contract_payment` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证且具备合同付款预警访问权限的用户。
|
||||
已认证且具备合同付款预警 Agent 授权(或 admin)的用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有 `contract_payment.access`。
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_access_contract_payment():
|
||||
raise ForbiddenError(
|
||||
'Contract payment access required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
return user
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
code='CONTRACT_PAYMENT.FORBIDDEN',
|
||||
)
|
||||
|
||||
|
||||
def _require_contract_payment_admin():
|
||||
"""
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
|
||||
Args:
|
||||
@@ -262,7 +275,7 @@ def get_ledger_summary():
|
||||
Args:
|
||||
无。
|
||||
Returns:
|
||||
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
|
||||
标准成功 envelope,含 due、overdue、active、due_this_month。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.services.training_config_service import get_published_config, list_trai
|
||||
from app.services.lean_training_service import (
|
||||
LEAN_TRAINING_TYPE,
|
||||
create_or_update_weekly_task,
|
||||
export_dashboard_excel,
|
||||
get_current_weekly_task,
|
||||
get_weekly_task_for_admin,
|
||||
list_dashboard,
|
||||
@@ -275,3 +276,16 @@ def get_admin_lean_training_dashboard():
|
||||
_require_lean_training_manager()
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
return ok(list_dashboard(raw_task_id))
|
||||
|
||||
|
||||
@training_admin_bp.route("/lean-training/dashboard/export", methods=["GET"])
|
||||
def export_admin_lean_training_dashboard():
|
||||
_require_lean_training_manager()
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
file_data, file_name = export_dashboard_excel(raw_task_id)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/workspace/voucher_check.py
|
||||
|
||||
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
|
||||
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录)。
|
||||
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
|
||||
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
|
||||
逻辑:对话与检核任务页共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,7 +37,7 @@ def _require_admin():
|
||||
def workspace_voucher_runs():
|
||||
"""
|
||||
分页查看检核任务列表。
|
||||
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
|
||||
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
data = query_service.list_runs(
|
||||
@@ -69,6 +69,16 @@ def workspace_voucher_force_run():
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/latest", methods=["GET"])
|
||||
def workspace_voucher_latest_run():
|
||||
"""
|
||||
读取最近一次立账凭证检核批次(含排队/执行中)。
|
||||
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
|
||||
"""
|
||||
_require_user()
|
||||
return ok(query_service.get_latest_run())
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
|
||||
def workspace_voucher_run_items(run_id: int):
|
||||
"""
|
||||
@@ -89,7 +99,7 @@ def workspace_voucher_run_items(run_id: int):
|
||||
def workspace_voucher_notifications():
|
||||
"""
|
||||
分页查看企微缺件汇总发送记录。
|
||||
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
|
||||
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
|
||||
"""
|
||||
_require_user()
|
||||
data = query_service.list_notifications(
|
||||
|
||||
@@ -96,8 +96,6 @@ class User(Base):
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
# 合同付款预警工作台:admin 默认开;不新建角色,可给采购同事单独授予
|
||||
'contract_payment.access': self.role == 'admin',
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
@@ -105,7 +103,7 @@ class User(Base):
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训、合同付款等业务权限硬编码在多个模块。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -123,7 +121,7 @@ class User(Base):
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -145,10 +143,6 @@ class User(Base):
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def can_access_contract_payment(self) -> bool:
|
||||
"""判断当前用户是否可查看合同付款预警工作台并触发同步/扫描。"""
|
||||
return self.has_feature_permission('contract_payment.access')
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -12,5 +12,6 @@ from __future__ import annotations
|
||||
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
|
||||
'shipping_notice': 'shipping_notice',
|
||||
'file_check': 'file_check',
|
||||
'contract_payment': 'contract_payment',
|
||||
'in_transit_transfer': 'in_transit_transfer',
|
||||
}
|
||||
@@ -129,6 +129,22 @@ agent_types:
|
||||
file_upload: true
|
||||
human_confirm: false
|
||||
handler_config_schema: {}
|
||||
contract_payment:
|
||||
label: 合同付款预警
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: builtin
|
||||
models:
|
||||
- ContractPaymentContract
|
||||
- ContractPaymentAlert
|
||||
- ContractPaymentAlertBatch
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
streaming: false
|
||||
file_upload: false
|
||||
task_progress: false
|
||||
forced_capabilities:
|
||||
file_upload: false
|
||||
handler_config_schema: {}
|
||||
in_transit_transfer:
|
||||
label: 在途仓自动调拨
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/agent_registry/handlers/bootstrap.py
|
||||
|
||||
用途:应用启动时加载 HANDLER_REGISTRY。
|
||||
依赖:handlers.shipping_notice 等领域 handler 模块。
|
||||
依赖:handlers.shipping_notice、handlers.contract_payment 等领域 handler 模块。
|
||||
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
|
||||
"""
|
||||
|
||||
@@ -29,12 +29,14 @@ def load_handlers() -> None:
|
||||
|
||||
import importlib
|
||||
|
||||
import app.services.agent_registry.handlers.contract_payment as contract_payment_mod
|
||||
import app.services.agent_registry.handlers.file_check as file_check_mod
|
||||
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
|
||||
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
|
||||
|
||||
importlib.reload(file_check_mod)
|
||||
importlib.reload(shipping_mod)
|
||||
importlib.reload(contract_payment_mod)
|
||||
importlib.reload(in_transit_transfer_mod)
|
||||
|
||||
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/contract_payment.py
|
||||
|
||||
用途:合同付款预警 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
|
||||
依赖:agent_registry.handlers.base / registry。
|
||||
逻辑:Chat 主区渲染台账 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
|
||||
from app.services.agent_registry.handlers.registry import register_handler
|
||||
|
||||
|
||||
@register_handler('contract_payment')
|
||||
class ContractPaymentHandler(AgentHandler):
|
||||
"""
|
||||
合同付款预警业务 Handler。
|
||||
|
||||
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入合同摘要。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""第一期无领域 UI State;台账由独立 HTTP API 加载。"""
|
||||
return None
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,12 +20,12 @@ from app.models import ContractPaymentContract, ContractPaymentNode
|
||||
|
||||
LEDGER_FOCUS_DUE = "due"
|
||||
LEDGER_FOCUS_OVERDUE = "overdue"
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
|
||||
LEDGER_FOCUS_ACTIVE = "active"
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
|
||||
LEDGER_FOCUS_VALUES = {
|
||||
LEDGER_FOCUS_DUE,
|
||||
LEDGER_FOCUS_OVERDUE,
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION,
|
||||
LEDGER_FOCUS_ACTIVE,
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH,
|
||||
}
|
||||
_NEAR_DUE_DAYS = 7
|
||||
@@ -68,7 +68,7 @@ def classify_ledger_status(
|
||||
"""
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
|
||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
@@ -80,16 +80,16 @@ def classify_ledger_status(
|
||||
"""
|
||||
node_list = list(nodes)
|
||||
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
return "needs_completion"
|
||||
if not node_list:
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
return "needs_completion"
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
for node in node_list
|
||||
)
|
||||
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
return "completed" if has_paid else "needs_completion"
|
||||
refs = [
|
||||
ref
|
||||
for node in active
|
||||
@@ -99,7 +99,7 @@ def classify_ledger_status(
|
||||
return LEDGER_FOCUS_OVERDUE
|
||||
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
|
||||
return LEDGER_FOCUS_DUE
|
||||
return "active"
|
||||
return LEDGER_FOCUS_ACTIVE
|
||||
|
||||
|
||||
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
|
||||
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
@@ -154,7 +154,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
buckets: dict[str, set[int]] = {
|
||||
LEDGER_FOCUS_DUE: set(),
|
||||
LEDGER_FOCUS_OVERDUE: set(),
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
|
||||
LEDGER_FOCUS_ACTIVE: set(),
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
|
||||
}
|
||||
if not contracts:
|
||||
@@ -180,8 +180,8 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
buckets[LEDGER_FOCUS_DUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_OVERDUE:
|
||||
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
|
||||
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
|
||||
elif status == LEDGER_FOCUS_ACTIVE:
|
||||
buckets[LEDGER_FOCUS_ACTIVE].add(row.id)
|
||||
if has_unpaid_due_this_month(nodes, as_of):
|
||||
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
|
||||
return buckets
|
||||
@@ -195,7 +195,7 @@ def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
due / overdue / needs_completion / due_this_month 的计数。
|
||||
due / overdue / active / due_this_month 的计数。
|
||||
"""
|
||||
buckets = collect_ledger_focus(session=session, today=today)
|
||||
return {key: len(ids) for key, ids in buckets.items()}
|
||||
|
||||
@@ -10,8 +10,10 @@ backend/app/services/lean_training_service.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
from sqlalchemy import func, or_, select
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
@@ -30,6 +32,21 @@ LEAN_TRAINING_TYPE = "lean_management"
|
||||
MIN_SUMMARY_LENGTH = 50
|
||||
|
||||
|
||||
def _format_dashboard_datetime(value: str | None) -> str:
|
||||
"""将看板 ISO 时间统一为页面展示的年月日时分格式。"""
|
||||
text = str(value or "").strip()
|
||||
return text[:16].replace("T", " ") if text else ""
|
||||
|
||||
|
||||
def _dashboard_status_label(status: str | None) -> str:
|
||||
"""将看板状态转换为页面一致的中文文案。"""
|
||||
return {
|
||||
"completed": "已完成",
|
||||
"overdue": "已延期",
|
||||
"in_progress": "进行中",
|
||||
}.get(str(status or ""), str(status or ""))
|
||||
|
||||
|
||||
def _get_lean_config() -> TrainingConfig:
|
||||
"""读取已发布精益培训配置,未配置时阻止创建周任务。"""
|
||||
config = db.session.execute(
|
||||
@@ -441,3 +458,43 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
|
||||
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
|
||||
(completed if row["status"] == "completed" else incomplete).append(row)
|
||||
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
|
||||
|
||||
|
||||
def export_dashboard_excel(task_id: int | None) -> tuple[bytes, str]:
|
||||
"""导出指定精益培训期次的完整看板数据。
|
||||
|
||||
Args:
|
||||
task_id: 指定周任务 ID;为空时按看板规则导出最新一期。
|
||||
Returns:
|
||||
Excel 二进制内容与下载文件名;无可导出任务时抛出 NotFoundError。
|
||||
"""
|
||||
dashboard = list_dashboard(task_id)
|
||||
task = dashboard["task"]
|
||||
if not task:
|
||||
raise NotFoundError("Lean training weekly task not found")
|
||||
|
||||
workbook = Workbook()
|
||||
worksheet = workbook.active
|
||||
worksheet.title = "lean_training"
|
||||
worksheet.append(["期号", "培训周次", "截止时间", "工号", "姓名", "部门", "视频名称", "观看时间", "状态", "学习感悟", "完成时间"])
|
||||
rows = [*dashboard["completed"], *dashboard["incomplete"]]
|
||||
for row in rows:
|
||||
videos = row.get("videos") or []
|
||||
worksheet.append([
|
||||
task.get("week_index") or "",
|
||||
task.get("week_key") or "",
|
||||
_format_dashboard_datetime(task.get("due_at")),
|
||||
row.get("employee_id") or "",
|
||||
row.get("name") or "",
|
||||
row.get("department") or "",
|
||||
"\n".join(str(video.get("name") or "") for video in videos),
|
||||
"\n".join(_format_dashboard_datetime(video.get("watched_at")) for video in videos),
|
||||
_dashboard_status_label(row.get("status")),
|
||||
row.get("summary_text") or "",
|
||||
_format_dashboard_datetime(row.get("completed_at")),
|
||||
])
|
||||
|
||||
buffer = BytesIO()
|
||||
workbook.save(buffer)
|
||||
filename = f"lean_training_dashboard_{task['week_key']}.xlsx"
|
||||
return buffer.getvalue(), filename
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/schedule/job_registry.py
|
||||
|
||||
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、job_params。
|
||||
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
|
||||
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
|
||||
"""
|
||||
@@ -140,11 +140,12 @@ def _register_builtin_platform_jobs() -> None:
|
||||
run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
)
|
||||
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
|
||||
from app.services.schedule.voucher_po_print_job import run_voucher_po_print_schedule
|
||||
from app.services.schedule.contract_payment_job import (
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
)
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_PO_PRINT_JOB_PARAMS
|
||||
from app.services.schedule.contract_payment_job import (
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
@@ -388,6 +389,43 @@ def _register_builtin_platform_jobs() -> None:
|
||||
),
|
||||
defaults=dict(DEFAULT_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="accounting-voucher-po-print",
|
||||
label="立账凭证 PO 订单生成",
|
||||
label_key="admin.schedule.form.platformJobAccountingVoucherPoPrint",
|
||||
handler=run_voucher_po_print_schedule,
|
||||
description="每周二 05:00 按上月发票从 TGHX 取数,生成制式采购单 PDF 并上传到「PO订单」;早于 06:00 检核周批。",
|
||||
description_key="admin.schedule.form.accountingVoucherPoPrintHint",
|
||||
category="finance",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "scope_code",
|
||||
"type": "select",
|
||||
"label": "账套",
|
||||
"label_key": "admin.schedule.form.voucherCheckScope",
|
||||
"required": True,
|
||||
"default": "HXJM",
|
||||
"options": [{"value": "HXJM", "label": "HXJM"}],
|
||||
},
|
||||
{
|
||||
"key": "profile_code",
|
||||
"type": "text",
|
||||
"label": "业务方 Profile",
|
||||
"label_key": "admin.schedule.form.voucherCheckProfile",
|
||||
"required": True,
|
||||
"default": "sales",
|
||||
},
|
||||
{
|
||||
"key": "notify_failure_enabled",
|
||||
"type": "boolean",
|
||||
"label": "失败告警",
|
||||
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
),
|
||||
defaults=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-receipt-file",
|
||||
label="在途收料文件抓取",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
backend/app/services/schedule/voucher_po_print_job.py
|
||||
|
||||
用途:立账凭证 PO 订单生成 platform_job 薄封装。
|
||||
依赖:voucher_check.po_print_runner。
|
||||
逻辑:job_registry 注册 accounting-voucher-po-print 后由 schedule worker 调用;早于检核周批。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.po_print_runner import ScheduleExecuteResult, run_po_print_batch
|
||||
|
||||
|
||||
def run_voucher_po_print_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行立账凭证 PO 订单生成排程。
|
||||
核心逻辑:委托 po_print_runner;默认周二 05:00,检核周批 06:00 只扫目录。
|
||||
"""
|
||||
return run_po_print_batch(task, run)
|
||||
@@ -24,6 +24,11 @@ from app.services.training_config_service import get_published_config
|
||||
|
||||
TRAINING_STAGES = {"video", "summary", "exam", "result"}
|
||||
TRAINING_TYPES = {"onboarding", "safety"}
|
||||
VIDEO_ONLY_TRAINING_TYPES = {
|
||||
"overseas_regulations",
|
||||
"overseas_regulations_training",
|
||||
"overseas_training",
|
||||
}
|
||||
TRAINING_EXAM_MODES = {"unified", "per_level"}
|
||||
SAFETY_STAGES = {"company", "department", "team", "exam", "result"}
|
||||
SAFETY_LEVEL_KEYS = ("company", "department", "team")
|
||||
@@ -69,6 +74,21 @@ def _normalize_training_type(value: Any) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _is_overseas_regulations_training(training_type: str) -> bool:
|
||||
"""
|
||||
判断培训类型是否为出国规章视频培训。
|
||||
|
||||
Args:
|
||||
training_type: 已标准化的培训类型编码。
|
||||
Returns:
|
||||
是否应以完整观看视频作为一次培训完成。
|
||||
"""
|
||||
if training_type in VIDEO_ONLY_TRAINING_TYPES:
|
||||
return True
|
||||
published = get_published_config(training_type)
|
||||
return "出国规章培训" in str((published or {}).get("name") or "")
|
||||
|
||||
|
||||
def _normalize_training_version(value: Any, training_type: str) -> str:
|
||||
"""
|
||||
规范培训版本号,未传时按培训类型补默认值。
|
||||
@@ -538,7 +558,7 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
else:
|
||||
passed = bool(payload.get("passed")) or (stage == "result" and score >= pass_score)
|
||||
|
||||
if stage == "result" and question_bank and not answer_details:
|
||||
if stage == "result" and question_bank and not answer_details and not _is_overseas_regulations_training(training_type):
|
||||
raise ValidationError("answer_details is required when submitting result", details={"field": "answer_details"})
|
||||
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
||||
safety_stage = None
|
||||
@@ -661,19 +681,20 @@ def export_training_records_excel(records: Iterable[TrainingRecord]) -> tuple[by
|
||||
workbook = Workbook()
|
||||
worksheet = workbook.active
|
||||
worksheet.title = "training"
|
||||
worksheet.append(["入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态"])
|
||||
worksheet.append(["入职日期", "完成日期", "培训类型", "部门", "姓名", "工号", "分数", "考试次数", "状态"])
|
||||
|
||||
for record in records:
|
||||
worksheet.append(
|
||||
[
|
||||
record.join_date.isoformat() if record.join_date else "",
|
||||
record.completion_time.date().isoformat() if record.completion_time else "",
|
||||
record.training_type or "",
|
||||
record.department or "",
|
||||
record.name or "",
|
||||
record.employee_id or "",
|
||||
record.score if record.score is not None else "",
|
||||
record.attempt_count or 0,
|
||||
_derive_status(record),
|
||||
{"passed": "已通过", "failed": "未通过", "in_progress": "进行中"}.get(_derive_status(record), _derive_status(record)),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/__init__.py
|
||||
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。
|
||||
依赖:各 adapter 模块。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO 取数、OA 占位、归档)。
|
||||
依赖:各 adapter 模块;PO 制式 PDF 在 voucher_check.po_order;ERP 取数在 erp_po_repository。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例,不调用 erp_po_print.fetch。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.adapters.base import (
|
||||
|
||||
@@ -80,7 +80,7 @@ class DirectoryScanAdapter(Protocol):
|
||||
|
||||
|
||||
class AcquireAdapter(Protocol):
|
||||
"""把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。"""
|
||||
"""把外部单据打印后写入类型目录;PO 制式 PDF 见 po_order,ERP 取数见 erp_po_repository。"""
|
||||
|
||||
source_type: str
|
||||
wired: bool
|
||||
@@ -88,7 +88,7 @@ class AcquireAdapter(Protocol):
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
获取并落入类型目录。
|
||||
【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。
|
||||
【AI 触发时机】仅当 Adapter.wired=True 且独立抓取走本方法时调用;周任务不调用。PO 独立抓取请用 ErpPoPrintAdapter.fetch_documents,不要走 fetch。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/erp_po_print.py
|
||||
|
||||
用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。
|
||||
用途:ERP 反查 PO 后写入「PO订单」类型目录的 Adapter。
|
||||
依赖:adapters.base、erp_po_repository、voucher_check.po_order。
|
||||
逻辑:fetch_documents / publish_for_invoices 由独立排程 accounting-voucher-po-print(周二 05:00)调用。
|
||||
fetch() 仍占位,检核 runner(周二 06:00)不调用。render_given 只出本地 PDF。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Mapping, Sequence
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.services.voucher_check.config import VoucherCheckEngineConfig
|
||||
from app.services.voucher_check.po_order import PoOrderDocument, PoOrderPublishResult
|
||||
|
||||
|
||||
class ErpPoPrintAdapter:
|
||||
"""PO 打印占位;未接线时禁止生成假 PDF。"""
|
||||
"""PO 获取:ERP 取数与上传已就绪;周检核 fetch 仍不启用。"""
|
||||
|
||||
source_type = "erp_po_print"
|
||||
wired = False
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
预留:按 invoice 反查 PO 并打印到类型目录。
|
||||
【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。
|
||||
周检核入口仍关闭。
|
||||
【AI 触发时机】不要在周二检核 runner 中调用。独立抓取排程请用 fetch_documents / publish_for_invoices。
|
||||
"""
|
||||
raise ServiceUnavailableError(
|
||||
"ERP PO 打印尚未接线",
|
||||
"ERP PO 打印尚未接入周检核",
|
||||
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
|
||||
details={
|
||||
"adapter": self.source_type,
|
||||
@@ -34,3 +41,65 @@ class ErpPoPrintAdapter:
|
||||
"subject_count": len(subjects),
|
||||
},
|
||||
)
|
||||
|
||||
def fetch_documents(
|
||||
self,
|
||||
invoice_nos: Sequence[str],
|
||||
*,
|
||||
config: VoucherCheckEngineConfig | None = None,
|
||||
) -> list[PoOrderDocument]:
|
||||
"""
|
||||
按发票号从 ERP 组装制式采购单数据。
|
||||
【AI 触发时机】独立抓取 PO、已有 invoice 清单时调用;检核 runner 不要调用。周二 05:00 排程走本方法。
|
||||
"""
|
||||
from app.services.voucher_check.config import load_engine_config
|
||||
from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices
|
||||
|
||||
engine = config if config is not None else load_engine_config()
|
||||
return fetch_po_documents_for_invoices(engine, invoice_nos)
|
||||
|
||||
def render_given(
|
||||
self,
|
||||
document: PoOrderDocument | Mapping[str, Any],
|
||||
output_dir: str | Path,
|
||||
*,
|
||||
overwrite: bool = True,
|
||||
) -> Path:
|
||||
"""
|
||||
根据给定采购单数据生成 `{invoice}-{订单号}.pdf` 到本地目录。
|
||||
【AI 触发时机】只需核对版式、不上传文档库时调用。
|
||||
"""
|
||||
from app.services.voucher_check.po_order import save_po_order_pdf
|
||||
|
||||
return save_po_order_pdf(document, output_dir, overwrite=overwrite)
|
||||
|
||||
def upload_given(
|
||||
self,
|
||||
document: PoOrderDocument | Mapping[str, Any],
|
||||
*,
|
||||
period_month: date,
|
||||
) -> PoOrderPublishResult:
|
||||
"""
|
||||
生成制式 PDF 并上传到销售开票附件/{年}/{月}/PO订单/。
|
||||
【AI 触发时机】已拿到 invoice 与 PO 字段、需要写入文档库类型目录时调用。
|
||||
同名跳过;不要在周检核 runner 中调用。
|
||||
"""
|
||||
from app.services.voucher_check.po_order import publish_po_order_pdf
|
||||
|
||||
return publish_po_order_pdf(document, period_month=period_month)
|
||||
|
||||
def publish_for_invoices(
|
||||
self,
|
||||
invoice_nos: Sequence[str],
|
||||
*,
|
||||
period_month: date,
|
||||
config: VoucherCheckEngineConfig | None = None,
|
||||
) -> list[PoOrderPublishResult]:
|
||||
"""
|
||||
按发票号查 ERP、生成 PDF 并上传到当月「PO订单」目录。
|
||||
【AI 触发时机】独立抓取任务要写入文档库时调用;检核 runner 不要调用。周二 05:00 排程走本方法。
|
||||
"""
|
||||
results: list[PoOrderPublishResult] = []
|
||||
for document in self.fetch_documents(invoice_nos, config=config):
|
||||
results.append(self.upload_given(document, period_month=period_month))
|
||||
return results
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/hxjm_apa_subject.py
|
||||
|
||||
用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。
|
||||
用途:从 HXJM oma_file 拉取上一个月销售 invoice 清单。
|
||||
依赖:erp_repository.fetch_month_invoices、fingerprint。
|
||||
逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。
|
||||
逻辑:周任务 subject_adapter=hxjm_apa(历史注册名,实际查 oma_file);期间由 erp_repository 按上月计算。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,14 +17,14 @@ from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
|
||||
|
||||
class HxjmApaSubjectAdapter:
|
||||
"""HXJM apa08/apa09 主体 Adapter。"""
|
||||
"""HXJM oma_file 主体 Adapter(注册名 hxjm_apa,查询 oma10/oma02 及确认/作废/状况/类别过滤)。"""
|
||||
|
||||
source_type = "hxjm_apa"
|
||||
|
||||
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
|
||||
"""
|
||||
查询上月发票号集合并生成主体指纹。
|
||||
核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。
|
||||
查询上月已确认且未作废的发票号集合并生成主体指纹。
|
||||
核心逻辑:委托 fetch_month_invoices(oma_file.oma10/oma02,确认/未作废/状况码 1/类别 11-13);返回期间必须与传入 period_month 一致。
|
||||
|
||||
Args:
|
||||
period_month: 检核月首日,由 runner 预先算好。
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/config.py
|
||||
|
||||
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params。
|
||||
用途:解析立账凭证检核 / PO 生成环境变量与 ScheduleTask.job_params。
|
||||
依赖:Flask current_app.config、core.errors.ValidationError。
|
||||
逻辑:runner / erp_repository / 引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
|
||||
逻辑:runner / po_print_runner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
|
||||
ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。
|
||||
"""
|
||||
|
||||
@@ -24,6 +24,12 @@ DEFAULT_JOB_PARAMS: dict[str, Any] = {
|
||||
"notify_failure_enabled": True,
|
||||
}
|
||||
|
||||
DEFAULT_PO_PRINT_JOB_PARAMS: dict[str, Any] = {
|
||||
"profile_code": "sales",
|
||||
"scope_code": "HXJM",
|
||||
"notify_failure_enabled": True,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VoucherCheckEngineConfig:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/dms_client.py
|
||||
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
@@ -178,9 +179,44 @@ class SalesDmsClient:
|
||||
raise ServiceUnavailableError(
|
||||
data.get("Msg") or failure_message,
|
||||
code=failure_code,
|
||||
details={"dms_data": data.get("Data")} if data.get("Data") not in (None, "", {}) else {},
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def _post_multipart(
|
||||
cls,
|
||||
path: str,
|
||||
*,
|
||||
files: dict[str, Any],
|
||||
data: dict[str, Any] | None = None,
|
||||
timeout: int = 60,
|
||||
failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE",
|
||||
failure_message: str = "文档库上传失败",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
POST multipart 到现网 DMS(用于附件 Upload)。
|
||||
核心逻辑:不手工设 Content-Type,交给 requests 带 boundary;401/403 刷新会话后重试。
|
||||
"""
|
||||
url = f"{cls.base_url()}{path}"
|
||||
try:
|
||||
session = cls._session()
|
||||
response = session.post(url, files=files, data=data or {}, timeout=timeout)
|
||||
if response.status_code in {401, 403}:
|
||||
session = cls._session(refresh=True)
|
||||
response = session.post(url, files=files, data=data or {}, timeout=timeout)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
raise ServiceUnavailableError(failure_message, code=failure_code) from exc
|
||||
if int(payload.get("Code") or 0) != 0:
|
||||
raise ServiceUnavailableError(
|
||||
payload.get("Msg") or failure_message,
|
||||
code=failure_code,
|
||||
details={"dms_data": payload.get("Data")} if payload.get("Data") not in (None, "", {}) else {},
|
||||
)
|
||||
return payload
|
||||
|
||||
@classmethod
|
||||
def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
|
||||
"""
|
||||
@@ -400,3 +436,144 @@ class SalesDmsClient:
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
return dest_row, False
|
||||
|
||||
@classmethod
|
||||
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
|
||||
"""
|
||||
确保销售开票附件/{yyyy}/{MM}/{类型目录} 存在并返回 FolderID。
|
||||
【AI 触发时机】要把新生成的 PO PDF 写入类型目录时调用;年/月/类型目录没有就建。
|
||||
|
||||
Args:
|
||||
period_month: 检核月份(用年、月两位目录名)。
|
||||
type_folder: 类型目录名,销售 PO 固定为「PO订单」。
|
||||
"""
|
||||
wanted = str(type_folder or "").strip()
|
||||
if not wanted:
|
||||
raise ValidationError("类型目录名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
cls.ensure_configured()
|
||||
root = cls.root_folder_id()
|
||||
year_id = cls.ensure_folder(parent_folder_id=root, leaf_name=f"{period_month.year:04d}")
|
||||
month_id = cls.ensure_folder(parent_folder_id=year_id, leaf_name=f"{period_month.month:02d}")
|
||||
return cls.ensure_folder(parent_folder_id=month_id, leaf_name=wanted)
|
||||
|
||||
@classmethod
|
||||
def upload_attachment(cls, *, filename: str, content: bytes) -> dict[str, Any]:
|
||||
"""
|
||||
把文件二进制上传为未入目录的附件,返回 Data(须含 ID)。
|
||||
核心逻辑:现网「新建文件」先 Upload 附件,再 CreateFiles 挂到文件夹。
|
||||
"""
|
||||
name = str(filename or "").strip()
|
||||
if not name:
|
||||
raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
if not content:
|
||||
raise ValidationError("上传文件内容不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
payload = cls._post_multipart(
|
||||
"/Api/_api/DMS/Public/Attachment/Upload",
|
||||
files={"file": (name, content, "application/pdf")},
|
||||
timeout=120,
|
||||
failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
failure_message="文档库上传附件失败",
|
||||
)
|
||||
data = payload.get("Data")
|
||||
if not isinstance(data, dict) or not str(data.get("ID") or "").strip():
|
||||
raise ServiceUnavailableError(
|
||||
"文档库上传附件后未返回 AttachmentID",
|
||||
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def create_files(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
files: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把已上传附件登记到指定文件夹(现网 functionCreationFile)。
|
||||
核心逻辑:POST Item/CreateFiles;Files[].AttachmentID 来自 Attachment/Upload。
|
||||
"""
|
||||
dest = str(parent_folder_id or "").strip()
|
||||
if not dest:
|
||||
raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not files:
|
||||
raise ValidationError("上传文件列表不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/CreateFiles",
|
||||
{
|
||||
"LibraryID": cls.library_id(),
|
||||
"CategoryID": "",
|
||||
"ParentFolderID": dest,
|
||||
"Files": files,
|
||||
"TermID": [],
|
||||
"CheckedOutState": 0,
|
||||
"CheckedOutMemo": "",
|
||||
},
|
||||
timeout=60,
|
||||
failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
failure_message="文档库创建文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def upload_file_skip_same_name(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
leaf_name: str,
|
||||
content: bytes,
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
"""
|
||||
上传文件到类型目录;目标已有同名则跳过、不覆盖。
|
||||
核心逻辑:先 Page 查 LeafName;没有则 Upload 附件再 CreateFiles。CreateFiles 报同名视为跳过。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
dest = str(parent_folder_id or "").strip()
|
||||
if not dest:
|
||||
raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not wanted:
|
||||
raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
|
||||
attachment = cls.upload_attachment(filename=wanted, content=content)
|
||||
extension = str(attachment.get("Extension") or Path(wanted).suffix or ".pdf").strip()
|
||||
if extension and not extension.startswith("."):
|
||||
extension = f".{extension}"
|
||||
file_row = {
|
||||
"LeafName": wanted,
|
||||
"AttachmentID": str(attachment.get("ID") or "").strip(),
|
||||
"CheckedOutState": 0,
|
||||
"CheckedOutMemo": "",
|
||||
"Extension": extension,
|
||||
"FieldValues": [],
|
||||
}
|
||||
|
||||
try:
|
||||
cls.create_files(parent_folder_id=dest, files=[file_row])
|
||||
except ServiceUnavailableError as exc:
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
same_names = ((exc.details or {}).get("dms_data") or {}).get("SameLeafNames") or []
|
||||
if same_names or _is_name_conflict(exc.message):
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
raise
|
||||
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if dest_row:
|
||||
return dest_row, False
|
||||
# 部分现网 CreateFiles 后 LeafName 不含扩展名,再按无后缀查一次。
|
||||
stem = Path(wanted).stem
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=stem)
|
||||
if dest_row:
|
||||
return dest_row, False
|
||||
raise ServiceUnavailableError(
|
||||
"上传成功但类型目录未找到同名文件",
|
||||
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/erp_po_repository.py
|
||||
|
||||
用途:按销售发票从 HXJM.oma99 对 TGHX.pmm99,取出制式采购单字段。
|
||||
依赖:erp_repository.open_erp_connection、po_order.models、voucher_check.config。
|
||||
逻辑:独立抓取任务调用;不进周二 runner。oma99 为空时用 oma16 走 oga99(12/13)或 oea99(11)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any, Iterable, Mapping, Sequence
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.config import VoucherCheckEngineConfig
|
||||
from app.services.voucher_check.erp_repository import _erp_unavailable, is_sales_invoice_no, open_erp_connection
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine
|
||||
|
||||
INVOICE_SCHEMA = "HXJM"
|
||||
PO_SCHEMA = "TGHX"
|
||||
_BATCH_SIZE = 80
|
||||
|
||||
_TA_IMA02 = {"1": "无卤", "2": "不管控"}
|
||||
_TA_IMA03 = {"1": "RoHS", "0": "非环保", "9": "ERS"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InvoiceFlow:
|
||||
"""一张发票对应的多角流程序号。"""
|
||||
|
||||
invoice_no: str
|
||||
flow_no: str
|
||||
oma00: str = ""
|
||||
oma16: str = ""
|
||||
|
||||
|
||||
def _as_text(value: Any) -> str:
|
||||
"""TRIM 后收成字符串;None 当空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _chunks(items: Sequence[str], size: int) -> Iterable[list[str]]:
|
||||
"""按绑定 IN 列表切批,避免超长 SQL。"""
|
||||
for index in range(0, len(items), size):
|
||||
yield list(items[index : index + size])
|
||||
|
||||
|
||||
def _in_clause(prefix: str, values: Sequence[str]) -> tuple[str, dict[str, str]]:
|
||||
"""
|
||||
生成 :prefix0,:prefix1 绑定与参数。
|
||||
核心逻辑:占位符名由本函数生成,禁止把业务值拼进 SQL。
|
||||
"""
|
||||
binds: dict[str, str] = {}
|
||||
names: list[str] = []
|
||||
for index, value in enumerate(values):
|
||||
key = f"{prefix}{index}"
|
||||
names.append(f":{key}")
|
||||
binds[key] = value
|
||||
return ", ".join(names), binds
|
||||
|
||||
|
||||
def _format_date(value: Any) -> str:
|
||||
"""展示用日期:2016/5/28,月日不补零。"""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, datetime):
|
||||
value = value.date()
|
||||
if not isinstance(value, date):
|
||||
return _as_text(value)
|
||||
return f"{value.year}/{value.month}/{value.day}"
|
||||
|
||||
|
||||
def _format_decimal(value: Any, scale: int, *, thousands: bool = False) -> str:
|
||||
"""按 azi 小数位格式化;金额可带千分位。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
digits = max(0, int(scale or 0))
|
||||
quant = Decimal("1").scaleb(-digits)
|
||||
number = Decimal(str(value)).quantize(quant, rounding=ROUND_HALF_UP)
|
||||
if thousands:
|
||||
return f"{number:,.{digits}f}"
|
||||
if digits == 0:
|
||||
return str(int(number))
|
||||
return f"{number:.{digits}f}"
|
||||
|
||||
|
||||
def _format_qty(value: Any) -> str:
|
||||
"""采购量去掉无意义的尾随零。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
number = Decimal(str(value))
|
||||
if number == number.to_integral_value():
|
||||
return str(int(number))
|
||||
return format(number.normalize(), "f")
|
||||
|
||||
|
||||
def _join_address(*parts: Any) -> str:
|
||||
"""送货/账单地址:空段丢掉再拼接。"""
|
||||
chunks = [_as_text(part) for part in parts]
|
||||
return "".join(chunk for chunk in chunks if chunk)
|
||||
|
||||
|
||||
def _halogen_text(ta_ima02: Any, ta_ima03: Any) -> str:
|
||||
"""版面目前一列;优先环保等级(样张 RoHS),否则卤素管控。"""
|
||||
code3 = _as_text(ta_ima03)
|
||||
if code3 in _TA_IMA03:
|
||||
return _TA_IMA03[code3]
|
||||
code2 = _as_text(ta_ima02)
|
||||
return _TA_IMA02.get(code2, "")
|
||||
|
||||
|
||||
def _azi_scale(value: Any, default: int) -> int:
|
||||
"""币别小数位;空则用默认。"""
|
||||
text = _as_text(value)
|
||||
if not text:
|
||||
return default
|
||||
try:
|
||||
return max(0, int(Decimal(text)))
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def map_po_document(invoice_no: str, line_rows: Sequence[Mapping[str, Any]]) -> PoOrderDocument:
|
||||
"""
|
||||
把同一张 TGHX 采购单的明细行收成 PoOrderDocument。
|
||||
【AI 触发时机】ERP 已查出 pmm/pmn 行、生成 PDF 之前调用。
|
||||
|
||||
核心逻辑:头栏取首行;合计对 pmn88/pmn88t 求和;到货日用 pmn34;版本 pmnud02;
|
||||
原始编号优先 ta_ima11,否则 pmn24。不写 SQL。
|
||||
|
||||
Args:
|
||||
invoice_no: 销售发票号,只用于文件名。
|
||||
line_rows: 同一 pmm01 的有序明细(已是 dict,键为小写列名)。
|
||||
|
||||
Returns:
|
||||
可交给 save_po_order_pdf 的文档。
|
||||
|
||||
Raises:
|
||||
ValueError: 无明细或缺少 pmm01。
|
||||
"""
|
||||
if not line_rows:
|
||||
raise ValueError("采购单没有明细行")
|
||||
head = line_rows[0]
|
||||
po_no = _as_text(head.get("po_no") or head.get("pmm01"))
|
||||
if not po_no:
|
||||
raise ValueError("缺少采购单号")
|
||||
price_scale = _azi_scale(head.get("azi03"), 6)
|
||||
amount_scale = _azi_scale(head.get("azi04"), 2)
|
||||
total_scale = _azi_scale(head.get("azi05"), amount_scale)
|
||||
price_code = _as_text(head.get("price_term_code"))
|
||||
price_name = _as_text(head.get("price_term_name"))
|
||||
price_term = f"{price_code} {price_name}".strip()
|
||||
lines: list[PoOrderLine] = []
|
||||
untax_total = Decimal("0")
|
||||
tax_total = Decimal("0")
|
||||
for raw in line_rows:
|
||||
untax_amt = raw.get("pmn88")
|
||||
tax_amt = raw.get("pmn88t")
|
||||
if untax_amt not in (None, ""):
|
||||
untax_total += Decimal(str(untax_amt))
|
||||
if tax_amt not in (None, ""):
|
||||
tax_total += Decimal(str(tax_amt))
|
||||
origin_no = _as_text(raw.get("ta_ima11")) or _as_text(raw.get("pmn24"))
|
||||
lines.append(
|
||||
PoOrderLine(
|
||||
seq=_as_text(raw.get("pmn02") or (len(lines) + 1)),
|
||||
item_no=_as_text(raw.get("pmn04")),
|
||||
name=_as_text(raw.get("pmn041")),
|
||||
spec=_as_text(raw.get("ima021")),
|
||||
qty=_format_qty(raw.get("pmn20")),
|
||||
unit=_as_text(raw.get("pmn07")),
|
||||
arrive=_format_date(raw.get("pmn34")),
|
||||
origin_no=origin_no,
|
||||
version=_as_text(raw.get("pmnud02")),
|
||||
untax_price=_format_decimal(raw.get("pmn31"), price_scale),
|
||||
tax_price=_format_decimal(raw.get("pmn31t"), price_scale),
|
||||
untax_amt=_format_decimal(untax_amt, amount_scale, thousands=True),
|
||||
tax_amt=_format_decimal(tax_amt, amount_scale, thousands=True),
|
||||
halogen=_halogen_text(raw.get("ta_ima02"), raw.get("ta_ima03")),
|
||||
vendor_item=_as_text(raw.get("pmn06")),
|
||||
)
|
||||
)
|
||||
return PoOrderDocument(
|
||||
invoice_no=_as_text(invoice_no),
|
||||
po_no=po_no,
|
||||
po_date=_format_date(head.get("po_date") or head.get("pmm04")),
|
||||
po_type=_as_text(head.get("po_type") or head.get("smydesc")),
|
||||
pay_term=_as_text(head.get("pay_term") or head.get("pma02")),
|
||||
tax_type=_as_text(head.get("tax_type") or head.get("gec02")),
|
||||
price_term=price_term,
|
||||
currency=_as_text(head.get("currency") or head.get("pmm22")),
|
||||
ship_address=_join_address(
|
||||
head.get("ship031"),
|
||||
head.get("ship032"),
|
||||
head.get("ship033"),
|
||||
head.get("ship034"),
|
||||
head.get("ship035"),
|
||||
),
|
||||
bill_address=_join_address(
|
||||
head.get("bill031"),
|
||||
head.get("bill032"),
|
||||
head.get("bill033"),
|
||||
head.get("bill034"),
|
||||
head.get("bill035"),
|
||||
),
|
||||
vendor_code=_as_text(head.get("vendor_code") or head.get("pmm09")),
|
||||
vendor_name=_as_text(head.get("vendor_name") or head.get("pmc081")),
|
||||
vendor_tel=_as_text(head.get("vendor_tel") or head.get("pmc10")),
|
||||
vendor_fax=_as_text(head.get("vendor_fax") or head.get("pmc11")),
|
||||
vendor_addr=_as_text(head.get("vendor_addr") or head.get("pmc091")),
|
||||
company_name=_as_text(head.get("company_name") or head.get("zo02")),
|
||||
company_address=_as_text(head.get("company_address") or head.get("zo041")),
|
||||
company_phone=_as_text(head.get("company_phone") or head.get("zo05")),
|
||||
company_fax=_as_text(head.get("company_fax") or head.get("zo09")),
|
||||
maker="",
|
||||
untax_total=_format_decimal(untax_total, total_scale, thousands=True),
|
||||
tax_total=_format_decimal(tax_total, total_scale, thousands=True),
|
||||
lines=tuple(lines),
|
||||
)
|
||||
|
||||
|
||||
def _invoice_key_sql(placeholders: str) -> str:
|
||||
"""HXJM 应收头:发票号 → 类别、来源单、多角序号。"""
|
||||
return f"""
|
||||
SELECT DISTINCT
|
||||
TRIM(oma10) AS invoice_no,
|
||||
TRIM(oma00) AS oma00,
|
||||
TRIM(oma16) AS oma16,
|
||||
TRIM(oma99) AS oma99
|
||||
FROM {INVOICE_SCHEMA}.oma_file
|
||||
WHERE TRIM(oma10) IN ({placeholders})
|
||||
AND TRIM(omaconf) = 'Y'
|
||||
AND TRIM(omavoid) = 'N'
|
||||
AND TRIM(oma64) = '1'
|
||||
AND TRIM(oma00) IN ('11', '12', '13')
|
||||
"""
|
||||
|
||||
|
||||
def _fallback_sql(table: str, key_col: str, flow_col: str, placeholders: str) -> str:
|
||||
"""oma99 为空时,从出货单或订单借多角序号。"""
|
||||
return f"""
|
||||
SELECT TRIM({key_col}) AS doc_no,
|
||||
TRIM({flow_col}) AS flow_no
|
||||
FROM {INVOICE_SCHEMA}.{table}
|
||||
WHERE TRIM({key_col}) IN ({placeholders})
|
||||
"""
|
||||
|
||||
|
||||
def _po_detail_sql(placeholders: str) -> str:
|
||||
"""TGHX 采购单头身 + 码表,对照 apmr900;过滤作废/无效/BKR。"""
|
||||
s = PO_SCHEMA
|
||||
return f"""
|
||||
SELECT TRIM(pmm.pmm99) AS flow_no,
|
||||
TRIM(pmm.pmm01) AS po_no,
|
||||
pmm.pmm04 AS po_date,
|
||||
TRIM(smy.smydesc) AS po_type,
|
||||
TRIM(pma.pma02) AS pay_term,
|
||||
TRIM(gec.gec02) AS tax_type,
|
||||
TRIM(pmm.pmm41) AS price_term_code,
|
||||
TRIM(pnz.pnz02) AS price_term_name,
|
||||
TRIM(pmm.pmm22) AS currency,
|
||||
TRIM(pmm.pmm09) AS vendor_code,
|
||||
TRIM(pmc.pmc081) AS vendor_name,
|
||||
TRIM(pmc.pmc10) AS vendor_tel,
|
||||
TRIM(pmc.pmc11) AS vendor_fax,
|
||||
TRIM(pmc.pmc091) AS vendor_addr,
|
||||
TRIM(ship.pme031) AS ship031,
|
||||
TRIM(ship.pme032) AS ship032,
|
||||
TRIM(ship.pme033) AS ship033,
|
||||
TRIM(ship.pme034) AS ship034,
|
||||
TRIM(ship.pme035) AS ship035,
|
||||
TRIM(bill.pme031) AS bill031,
|
||||
TRIM(bill.pme032) AS bill032,
|
||||
TRIM(bill.pme033) AS bill033,
|
||||
TRIM(bill.pme034) AS bill034,
|
||||
TRIM(bill.pme035) AS bill035,
|
||||
TRIM(zo.zo02) AS company_name,
|
||||
TRIM(zo.zo041) AS company_address,
|
||||
TRIM(zo.zo05) AS company_phone,
|
||||
TRIM(zo.zo09) AS company_fax,
|
||||
pmn.pmn02 AS pmn02,
|
||||
TRIM(pmn.pmn04) AS pmn04,
|
||||
TRIM(pmn.pmn041) AS pmn041,
|
||||
TRIM(pmn.pmn06) AS pmn06,
|
||||
TRIM(pmn.pmn07) AS pmn07,
|
||||
pmn.pmn20 AS pmn20,
|
||||
TRIM(pmn.pmn24) AS pmn24,
|
||||
pmn.pmn31 AS pmn31,
|
||||
pmn.pmn31t AS pmn31t,
|
||||
pmn.pmn34 AS pmn34,
|
||||
pmn.pmn88 AS pmn88,
|
||||
pmn.pmn88t AS pmn88t,
|
||||
TRIM(pmn.pmnud02) AS pmnud02,
|
||||
TRIM(ima.ima021) AS ima021,
|
||||
TRIM(ima.ta_ima02) AS ta_ima02,
|
||||
TRIM(ima.ta_ima03) AS ta_ima03,
|
||||
TRIM(ima.ta_ima11) AS ta_ima11,
|
||||
azi.azi03 AS azi03,
|
||||
azi.azi04 AS azi04,
|
||||
azi.azi05 AS azi05
|
||||
FROM {s}.pmm_file pmm
|
||||
JOIN {s}.pmn_file pmn ON pmn.pmn01 = pmm.pmm01
|
||||
LEFT JOIN {s}.smy_file smy ON pmm.pmm01 LIKE TRIM(smy.smyslip) || '-%'
|
||||
LEFT JOIN {s}.pmc_file pmc ON TRIM(pmc.pmc01) = TRIM(pmm.pmm09)
|
||||
LEFT JOIN {s}.pma_file pma ON TRIM(pma.pma01) = TRIM(pmm.pmm20)
|
||||
LEFT JOIN {s}.gec_file gec ON TRIM(gec.gec01) = TRIM(pmm.pmm21) AND TRIM(gec.gec011) = '1'
|
||||
LEFT JOIN {s}.pnz_file pnz ON TRIM(pnz.pnz01) = TRIM(pmm.pmm41)
|
||||
LEFT JOIN {s}.azi_file azi ON TRIM(azi.azi01) = TRIM(pmm.pmm22)
|
||||
LEFT JOIN {s}.ima_file ima ON TRIM(ima.ima01) = TRIM(pmn.pmn04)
|
||||
LEFT JOIN {s}.pme_file ship ON TRIM(ship.pme01) = TRIM(pmm.pmm10)
|
||||
LEFT JOIN {s}.pme_file bill ON TRIM(bill.pme01) = TRIM(pmm.pmm11)
|
||||
LEFT JOIN {s}.zo_file zo ON zo.zo01 = '1'
|
||||
WHERE TRIM(pmm.pmm99) IN ({placeholders})
|
||||
AND TRIM(pmm.pmm18) != 'X'
|
||||
AND TRIM(pmm.pmmacti) = 'Y'
|
||||
AND NVL(TRIM(pmm.pmm02), ' ') != 'BKR'
|
||||
ORDER BY pmm.pmm01, pmn.pmn02
|
||||
"""
|
||||
|
||||
|
||||
def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]:
|
||||
"""把游标行收成小写键 dict。"""
|
||||
columns = [str(col[0]).lower() for col in (cursor.description or [])]
|
||||
return [dict(zip(columns, raw)) for raw in cursor]
|
||||
|
||||
|
||||
def _fetch_invoice_keys(cursor: Any, invoice_nos: Sequence[str]) -> list[dict[str, Any]]:
|
||||
"""分批查 HXJM 应收头。"""
|
||||
found: list[dict[str, Any]] = []
|
||||
for batch in _chunks(list(invoice_nos), _BATCH_SIZE):
|
||||
placeholders, binds = _in_clause("inv", batch)
|
||||
cursor.execute(_invoice_key_sql(placeholders), binds)
|
||||
found.extend(_rows_as_dicts(cursor))
|
||||
return found
|
||||
|
||||
|
||||
def _fetch_doc_flows(cursor: Any, table: str, key_col: str, flow_col: str, doc_nos: Sequence[str]) -> dict[str, str]:
|
||||
"""出货单/订单号 → 多角序号。"""
|
||||
mapping: dict[str, str] = {}
|
||||
unique = [item for item in dict.fromkeys(doc_nos) if item]
|
||||
for batch in _chunks(unique, _BATCH_SIZE):
|
||||
placeholders, binds = _in_clause("doc", batch)
|
||||
cursor.execute(_fallback_sql(table, key_col, flow_col, placeholders), binds)
|
||||
for row in _rows_as_dicts(cursor):
|
||||
doc_no = _as_text(row.get("doc_no"))
|
||||
flow_no = _as_text(row.get("flow_no"))
|
||||
if doc_no and flow_no:
|
||||
mapping[doc_no] = flow_no
|
||||
return mapping
|
||||
|
||||
|
||||
def resolve_invoice_flows(cursor: Any, invoice_nos: Sequence[str]) -> list[InvoiceFlow]:
|
||||
"""
|
||||
发票号 → 多角流程序号。
|
||||
核心逻辑:优先 TRIM(oma99);空则 12/13 查 oga99、11 查 oea99。同一发票多个序号会去重保留。
|
||||
"""
|
||||
wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)]
|
||||
if not wanted:
|
||||
return []
|
||||
keys = _fetch_invoice_keys(cursor, wanted)
|
||||
oga_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) in {"12", "13"} and not _as_text(row.get("oma99"))]
|
||||
oea_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) == "11" and not _as_text(row.get("oma99"))]
|
||||
oga_flows = _fetch_doc_flows(cursor, "oga_file", "oga01", "oga99", oga_docs) if oga_docs else {}
|
||||
oea_flows = _fetch_doc_flows(cursor, "oea_file", "oea01", "oea99", oea_docs) if oea_docs else {}
|
||||
|
||||
flows: list[InvoiceFlow] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for row in keys:
|
||||
invoice_no = _as_text(row.get("invoice_no"))
|
||||
oma00 = _as_text(row.get("oma00"))
|
||||
oma16 = _as_text(row.get("oma16"))
|
||||
flow_no = _as_text(row.get("oma99"))
|
||||
if not flow_no:
|
||||
if oma00 in {"12", "13"}:
|
||||
flow_no = oga_flows.get(oma16, "")
|
||||
elif oma00 == "11":
|
||||
flow_no = oea_flows.get(oma16, "")
|
||||
if not invoice_no or not flow_no:
|
||||
continue
|
||||
pair = (invoice_no, flow_no)
|
||||
if pair in seen:
|
||||
continue
|
||||
seen.add(pair)
|
||||
flows.append(InvoiceFlow(invoice_no=invoice_no, flow_no=flow_no, oma00=oma00, oma16=oma16))
|
||||
return flows
|
||||
|
||||
|
||||
def _fetch_po_lines(cursor: Any, flow_nos: Sequence[str]) -> list[dict[str, Any]]:
|
||||
"""按多角序号批量取 TGHX 采购明细。"""
|
||||
lines: list[dict[str, Any]] = []
|
||||
unique = [item for item in dict.fromkeys(flow_nos) if item]
|
||||
for batch in _chunks(unique, _BATCH_SIZE):
|
||||
placeholders, binds = _in_clause("flow", batch)
|
||||
cursor.execute(_po_detail_sql(placeholders), binds)
|
||||
lines.extend(_rows_as_dicts(cursor))
|
||||
return lines
|
||||
|
||||
|
||||
def fetch_po_documents_for_invoices(
|
||||
config: VoucherCheckEngineConfig,
|
||||
invoice_nos: Sequence[str],
|
||||
) -> list[PoOrderDocument]:
|
||||
"""
|
||||
按销售发票号从 ERP 组装制式采购单数据。
|
||||
【AI 触发时机】独立「抓取 PO」任务或周二 05:00 accounting-voucher-po-print 排程已有 invoice 清单、要生成 PDF 之前调用;不要在检核 runner 里调用。
|
||||
|
||||
核心逻辑:HXJM.oma99(空则 oga99/oea99)TRIM 后对 TGHX.pmm99;一票可多张 PO,每张一个文档。
|
||||
|
||||
Args:
|
||||
config: Oracle 只读连接。
|
||||
invoice_nos: 销售发票号;非 6 位以上字母数字的项会跳过。
|
||||
|
||||
Returns:
|
||||
PoOrderDocument 列表,按发票号、采购单号排序。找不到 PO 的发票不出现在结果里。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: Oracle 不可用。
|
||||
"""
|
||||
wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)]
|
||||
if not wanted:
|
||||
return []
|
||||
connection = None
|
||||
try:
|
||||
connection = open_erp_connection(config)
|
||||
cursor = connection.cursor()
|
||||
# [STEP 1] 发票 → 多角序号
|
||||
flows = resolve_invoice_flows(cursor, wanted)
|
||||
if not flows:
|
||||
return []
|
||||
# [STEP 2] 序号 → TGHX 采购单明细
|
||||
po_lines = _fetch_po_lines(cursor, [item.flow_no for item in flows])
|
||||
by_flow: dict[str, dict[str, list[dict[str, Any]]]] = defaultdict(lambda: defaultdict(list))
|
||||
for row in po_lines:
|
||||
flow_no = _as_text(row.get("flow_no"))
|
||||
po_no = _as_text(row.get("po_no"))
|
||||
if flow_no and po_no:
|
||||
by_flow[flow_no][po_no].append(row)
|
||||
# [STEP 3] 发票 × 采购单 交叉成文档
|
||||
documents: list[PoOrderDocument] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for flow in flows:
|
||||
for po_no, rows in by_flow.get(flow.flow_no, {}).items():
|
||||
key = (flow.invoice_no, po_no)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
documents.append(map_po_document(flow.invoice_no, rows))
|
||||
documents.sort(key=lambda item: (item.invoice_no, item.po_no))
|
||||
return documents
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _erp_unavailable(config, exc) from exc
|
||||
finally:
|
||||
if connection is not None:
|
||||
try:
|
||||
connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/erp_repository.py
|
||||
|
||||
用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。
|
||||
用途:从 Oracle HXJM 套账 oma_file 查询上一个自然月发票号集合;并提供共用只读连接。
|
||||
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
|
||||
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
|
||||
逻辑:runner 阶段 A 调用 fetch_month_invoices;采购单取数见 erp_po_repository,复用 open_erp_connection。
|
||||
只读 SELECT 已确认、未作废、状况码 1、帐款类别 11/12/13;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -16,16 +18,21 @@ from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.config import VoucherCheckEngineConfig
|
||||
|
||||
_TZ = ZoneInfo("Asia/Shanghai")
|
||||
_INVOICE_NO_RE = re.compile(r"^[A-Za-z0-9]{6,}$")
|
||||
|
||||
_INVOICE_SQL = """
|
||||
SELECT DISTINCT
|
||||
TRIM(apa08) AS invoice_no,
|
||||
TRUNC(apa09) AS invoice_date
|
||||
FROM apa_file
|
||||
WHERE apa09 >= :period_start
|
||||
AND apa09 < :next_period_start
|
||||
AND TRIM(apa08) IS NOT NULL
|
||||
ORDER BY TRUNC(apa09), TRIM(apa08)
|
||||
TRIM(oma10) AS invoice_no,
|
||||
TRUNC(oma02) AS invoice_date
|
||||
FROM oma_file
|
||||
WHERE oma02 >= :period_start
|
||||
AND oma02 < :next_period_start
|
||||
AND REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')
|
||||
AND TRIM(omaconf) = 'Y'
|
||||
AND TRIM(omavoid) = 'N'
|
||||
AND TRIM(oma64) = '1'
|
||||
AND TRIM(oma00) IN ('11', '12', '13')
|
||||
ORDER BY TRUNC(oma02), TRIM(oma10)
|
||||
"""
|
||||
|
||||
|
||||
@@ -37,6 +44,20 @@ class ErpInvoiceRow:
|
||||
invoice_date: date | None
|
||||
|
||||
|
||||
def is_sales_invoice_no(value: str | None) -> bool:
|
||||
"""
|
||||
判断 oma10 是否为可检核的销售发票号。
|
||||
核心逻辑:TRIM 后至少 6 位字母或数字(如 6975101806、EWZZ26090002)。现场 oma10 是手工录入,常被填成 0、空值或中文备注,那些不能当 invoice。
|
||||
|
||||
Args:
|
||||
value: oma10 原文。
|
||||
|
||||
Returns:
|
||||
True 表示可作为检核主体。
|
||||
"""
|
||||
return bool(_INVOICE_NO_RE.fullmatch(str(value or "").strip()))
|
||||
|
||||
|
||||
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
|
||||
"""
|
||||
按 Asia/Shanghai 计算当前自然月起止。
|
||||
@@ -79,6 +100,64 @@ def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, dat
|
||||
return period_month, current_month, period_start, next_start
|
||||
|
||||
|
||||
def open_erp_connection(config: VoucherCheckEngineConfig):
|
||||
"""
|
||||
打开立账凭证 Oracle 只读连接。
|
||||
核心逻辑:复用 Text2SQL 的 Instant Client 初始化;超时单位毫秒。调用方必须 close。
|
||||
|
||||
Args:
|
||||
config: 含 DSN/账号/超时的检核配置。
|
||||
|
||||
Returns:
|
||||
oracledb 连接。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 驱动缺失或连接失败。
|
||||
"""
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"Oracle 驱动不可用",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
) from exc
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
try:
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
connection = oracledb.connect(
|
||||
user=config.erp_username,
|
||||
password=config.erp_password,
|
||||
dsn=config.erp_dsn,
|
||||
)
|
||||
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
|
||||
return connection
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _erp_unavailable(config, exc) from exc
|
||||
|
||||
|
||||
def _erp_unavailable(config: VoucherCheckEngineConfig, exc: BaseException) -> ServiceUnavailableError:
|
||||
"""把 Oracle 异常收成统一错误码,日志只记类型不记密码。"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
current_app.logger.error(
|
||||
"[voucher-check] ERP query failed dsn=%s error_type=%s",
|
||||
config.erp_dsn,
|
||||
type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ServiceUnavailableError(
|
||||
"Oracle 查询失败",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
details={"error_type": type(exc).__name__},
|
||||
)
|
||||
|
||||
|
||||
def fetch_month_invoices(
|
||||
config: VoucherCheckEngineConfig,
|
||||
*,
|
||||
@@ -86,6 +165,7 @@ def fetch_month_invoices(
|
||||
) -> tuple[date, list[ErpInvoiceRow]]:
|
||||
"""
|
||||
查询上一个自然月发票清单。
|
||||
核心逻辑:从 oma_file 按帐款日期 oma02 取上月;发票号 oma10 须为至少 6 位字母或数字(排除 0、空值、中文备注);仅确认(omaconf='Y')、未作废(omavoid='N')、状况码 oma64='1'、帐款类别 oma00 为 11/12/13。
|
||||
|
||||
Args:
|
||||
config: 含 Oracle DSN/账号的检核配置。
|
||||
@@ -98,26 +178,9 @@ def fetch_month_invoices(
|
||||
ServiceUnavailableError: Oracle 不可用。
|
||||
"""
|
||||
period_month, _current_month, period_start, next_start = previous_period_bounds(now)
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"Oracle 驱动不可用",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
) from exc
|
||||
|
||||
from flask import current_app
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
connection = None
|
||||
try:
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
connection = oracledb.connect(
|
||||
user=config.erp_username,
|
||||
password=config.erp_password,
|
||||
dsn=config.erp_dsn,
|
||||
)
|
||||
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
|
||||
connection = open_erp_connection(config)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
_INVOICE_SQL,
|
||||
@@ -130,7 +193,7 @@ def fetch_month_invoices(
|
||||
seen: set[str] = set()
|
||||
for raw_no, raw_date in cursor:
|
||||
invoice_no = str(raw_no or "").strip()
|
||||
if not invoice_no or invoice_no in seen:
|
||||
if not is_sales_invoice_no(invoice_no) or invoice_no in seen:
|
||||
continue
|
||||
seen.add(invoice_no)
|
||||
invoice_date: date | None = None
|
||||
@@ -144,19 +207,7 @@ def fetch_month_invoices(
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
try:
|
||||
current_app.logger.error(
|
||||
"[voucher-check] ERP query failed dsn=%s error_type=%s",
|
||||
config.erp_dsn,
|
||||
type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
raise ServiceUnavailableError(
|
||||
"Oracle 查询失败",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
details={"error_type": type(exc).__name__},
|
||||
) from exc
|
||||
raise _erp_unavailable(config, exc) from exc
|
||||
finally:
|
||||
if connection is not None:
|
||||
try:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/notification.py
|
||||
|
||||
用途:立账凭证检核批次级企微汇总与技术失败告警。
|
||||
用途:立账凭证检核缺件汇总、以及检核 / PO 生成排程的技术失败告警。
|
||||
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。
|
||||
逻辑:检核批次一条缺件汇总;PO 生成只在技术失败时告警;未配置接收人不发送;domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -186,8 +186,14 @@ def send_failure_alert(
|
||||
error_code: str,
|
||||
error_message: str,
|
||||
enabled: bool,
|
||||
title: str | None = None,
|
||||
) -> None:
|
||||
"""批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。"""
|
||||
"""
|
||||
批次级技术失败告警(ERP/DMS/配置/上传异常),不计入缺件通知。
|
||||
|
||||
Args:
|
||||
title: 企微标题;默认「立账凭证检核失败」。PO 生成排程传入自己的标题。
|
||||
"""
|
||||
if not enabled:
|
||||
return
|
||||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||||
@@ -203,7 +209,7 @@ def send_failure_alert(
|
||||
if not users:
|
||||
return
|
||||
|
||||
title = f"立账凭证检核失败: {task.name}"
|
||||
title = title or f"立账凭证检核失败: {task.name}"
|
||||
description = (
|
||||
f"批次 {run.run_no}\n"
|
||||
f"失败阶段:{stage}\n"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/__init__.py
|
||||
|
||||
用途:立账凭证「PO订单」制式采购单 PDF 的对外入口。
|
||||
依赖:models、filename、save、publish。
|
||||
逻辑:调用方先组装 PoOrderDocument(ERP 取数见 erp_po_repository),save_po_order_pdf 只写本地;
|
||||
publish_po_order_pdf 再上传。周检核 runner / erp_po_print.fetch 不要调用本包。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.po_order.filename import build_po_order_filename
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine, parse_po_order_document
|
||||
from app.services.voucher_check.po_order.publish import PoOrderPublishResult, publish_po_order_pdf
|
||||
from app.services.voucher_check.po_order.sample import sample_po_order_document
|
||||
from app.services.voucher_check.po_order.save import save_po_order_pdf
|
||||
|
||||
__all__ = [
|
||||
"PoOrderDocument",
|
||||
"PoOrderLine",
|
||||
"PoOrderPublishResult",
|
||||
"build_po_order_filename",
|
||||
"parse_po_order_document",
|
||||
"publish_po_order_pdf",
|
||||
"sample_po_order_document",
|
||||
"save_po_order_pdf",
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/__main__.py
|
||||
|
||||
用途:用给定 JSON、对照样张或 ERP 发票号生成 `{invoice}-{订单号}.pdf`。
|
||||
依赖:save_po_order_pdf、sample_po_order_document;--invoice 另依赖 Flask 配置与 erp_po_repository。
|
||||
逻辑:python -m app.services.voucher_check.po_order --out-dir DIR [--json FILE|--sample|--invoice NO]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""
|
||||
命令行入口:JSON / 样张 / ERP 发票号 → 指定目录 PDF。
|
||||
【AI 触发时机】需要出 PO 订单 PDF、且不走周检核时运行本模块。
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description="生成 PO 订单制式 PDF")
|
||||
parser.add_argument("--out-dir", required=True, help="PDF 输出目录")
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
group.add_argument("--json", dest="json_path", help="采购单 JSON(含 invoice_no、po_no、lines)")
|
||||
group.add_argument("--sample", action="store_true", help="使用对照样张数据")
|
||||
group.add_argument("--invoice", help="从 ERP 按销售发票号取 TGHX 采购单(需应用配置)")
|
||||
args = parser.parse_args(argv)
|
||||
from app.services.voucher_check.po_order.save import save_po_order_pdf
|
||||
|
||||
if args.sample:
|
||||
from app.services.voucher_check.po_order.sample import sample_po_order_document
|
||||
|
||||
documents = [sample_po_order_document()]
|
||||
elif args.invoice:
|
||||
from app import create_app
|
||||
from app.services.voucher_check.config import load_engine_config
|
||||
from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
documents = fetch_po_documents_for_invoices(load_engine_config(), [args.invoice])
|
||||
if not documents:
|
||||
print("no purchase order for invoice", args.invoice, file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
payload = json.loads(Path(args.json_path).read_text(encoding="utf-8"))
|
||||
documents = [payload]
|
||||
for document in documents:
|
||||
print(save_po_order_pdf(document, args.out_dir))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/filename.py
|
||||
|
||||
用途:按销售 Profile 规则生成 PO 订单 PDF 文件名。
|
||||
依赖:core.errors.ValidationError。
|
||||
逻辑:固定 `{invoice}-{order_no}.pdf`;禁止路径字符,供落盘与后续目录扫描共用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
_UNSAFE_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]|(\.\.)')
|
||||
|
||||
|
||||
def build_po_order_filename(*, invoice_no: str, order_no: str) -> str:
|
||||
"""
|
||||
生成 `{invoice号}-{订单号}.pdf`。
|
||||
【AI 触发时机】保存或匹配 PO 订单 PDF 文件名时调用;不要自行拼接。
|
||||
|
||||
Args:
|
||||
invoice_no: 销售 invoice,禁止空串与路径字符。
|
||||
order_no: 采购单号(po_no),禁止空串与路径字符。
|
||||
|
||||
Returns:
|
||||
仅文件名,不含目录。
|
||||
|
||||
Raises:
|
||||
ValidationError: 缺号或含非法字符。
|
||||
"""
|
||||
invoice = str(invoice_no or "").strip()
|
||||
order = str(order_no or "").strip()
|
||||
if not invoice:
|
||||
raise ValidationError("缺少 invoice_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "invoice_no"})
|
||||
if not order:
|
||||
raise ValidationError("缺少 po_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "po_no"})
|
||||
if _UNSAFE_RE.search(invoice) or _UNSAFE_RE.search(order):
|
||||
raise ValidationError(
|
||||
"invoice 或订单号含非法路径字符",
|
||||
code="VOUCHER_CHECK.PO_PDF_INVALID",
|
||||
details=_unsafe_details(invoice, order),
|
||||
)
|
||||
return f"{invoice}-{order}.pdf"
|
||||
|
||||
|
||||
def _unsafe_details(invoice: str, order: str) -> dict[str, Any]:
|
||||
return {"invoice_no": invoice, "po_no": order}
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/fonts.py
|
||||
|
||||
用途:为制式采购单注册中文字体。
|
||||
依赖:reportlab;可选环境变量 VOUCHER_CHECK_PO_FONT_PATH。
|
||||
逻辑:优先系统宋体/Noto CJK(Docker 已装 fonts-noto-cjk),失败再回退 CID STSong-Light。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
|
||||
_FONT_FAMILY = "VoucherPoCjk"
|
||||
_CID_FALLBACK = "STSong-Light"
|
||||
_REGISTERED: str | None = None
|
||||
|
||||
_CANDIDATES: tuple[tuple[str, int], ...] = (
|
||||
(r"C:\Windows\Fonts\simsun.ttc", 0),
|
||||
(r"C:\Windows\Fonts\simsun.ttf", 0),
|
||||
(r"C:\Windows\Fonts\msyh.ttc", 0),
|
||||
("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", 0),
|
||||
("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0),
|
||||
("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 0),
|
||||
)
|
||||
|
||||
|
||||
def resolve_po_font() -> str:
|
||||
"""
|
||||
返回已注册的中文字体名,进程内只注册一次。
|
||||
核心逻辑:VOUCHER_CHECK_PO_FONT_PATH → 常见系统字体 → CID 内置宋体。
|
||||
"""
|
||||
global _REGISTERED
|
||||
if _REGISTERED:
|
||||
return _REGISTERED
|
||||
|
||||
env_path = str(os.getenv("VOUCHER_CHECK_PO_FONT_PATH") or "").strip()
|
||||
if env_path:
|
||||
registered = _try_ttf(Path(env_path), 0) or _try_ttf(Path(env_path), 2)
|
||||
if registered:
|
||||
_REGISTERED = registered
|
||||
return _REGISTERED
|
||||
|
||||
for raw, index in _CANDIDATES:
|
||||
registered = _try_ttf(Path(raw), index)
|
||||
if registered:
|
||||
_REGISTERED = registered
|
||||
return _REGISTERED
|
||||
|
||||
pdfmetrics.registerFont(UnicodeCIDFont(_CID_FALLBACK))
|
||||
_REGISTERED = _CID_FALLBACK
|
||||
return _REGISTERED
|
||||
|
||||
|
||||
def _try_ttf(path: Path, subfont_index: int) -> str | None:
|
||||
"""尝试把 TTF/TTC 注册为 VoucherPoCjk;文件不存在或 reportlab 拒收时返回 None。"""
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
pdfmetrics.registerFont(TTFont(_FONT_FAMILY, str(path), subfontIndex=subfont_index))
|
||||
return _FONT_FAMILY
|
||||
except Exception:
|
||||
return None
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/models.py
|
||||
|
||||
用途:制式采购单 PDF 的给定数据结构(与 ERP 查询解耦)。
|
||||
依赖:core.errors.ValidationError。
|
||||
逻辑:独立抓取任务拿到 invoice + PO 明细后填入本模型;renderer 只消费这些字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def _as_text(value: Any) -> str:
|
||||
"""把给定值收成版面用字符串,None 当空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _po_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError:
|
||||
return ValidationError(message, code="VOUCHER_CHECK.PO_PDF_INVALID", details=details or {})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoOrderLine:
|
||||
"""采购单明细行;金额/数量已格式化成展示字符串,渲染层不再重算。"""
|
||||
|
||||
seq: str
|
||||
item_no: str
|
||||
name: str = ""
|
||||
spec: str = ""
|
||||
extra_spec: str = ""
|
||||
qty: str = ""
|
||||
unit: str = ""
|
||||
arrive: str = ""
|
||||
origin_no: str = ""
|
||||
version: str = ""
|
||||
untax_price: str = ""
|
||||
tax_price: str = ""
|
||||
untax_amt: str = ""
|
||||
tax_amt: str = ""
|
||||
halogen: str = ""
|
||||
vendor_item: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoOrderDocument:
|
||||
"""
|
||||
一张采购单的给定数据。
|
||||
invoice_no 只用于文件名 `{invoice}-{po_no}.pdf`,不印在 Crystal 风格版面上。
|
||||
"""
|
||||
|
||||
invoice_no: str
|
||||
po_no: str
|
||||
po_date: str = ""
|
||||
po_type: str = ""
|
||||
pay_term: str = ""
|
||||
tax_type: str = ""
|
||||
price_term: str = ""
|
||||
currency: str = ""
|
||||
ship_address: str = ""
|
||||
bill_address: str = ""
|
||||
vendor_code: str = ""
|
||||
vendor_name: str = ""
|
||||
vendor_tel: str = ""
|
||||
vendor_fax: str = ""
|
||||
vendor_addr: str = ""
|
||||
company_name: str = ""
|
||||
company_address: str = ""
|
||||
company_phone: str = ""
|
||||
company_fax: str = ""
|
||||
maker: str = ""
|
||||
untax_total: str = ""
|
||||
tax_total: str = ""
|
||||
lines: tuple[PoOrderLine, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def parse_po_order_document(payload: Mapping[str, Any]) -> PoOrderDocument:
|
||||
"""
|
||||
把给定 dict/JSON 收成 PoOrderDocument。
|
||||
【AI 触发时机】调用方已从 ERP 或手工 JSON 拿到采购单字段、要生成 PDF 之前调用。
|
||||
|
||||
核心逻辑:只做必填校验与类型收口,不查库、不补默认公司名。
|
||||
|
||||
Args:
|
||||
payload: 须含 invoice_no、po_no;lines 为明细列表。其余键与样张字段同名。
|
||||
|
||||
Returns:
|
||||
可交给 save_po_order_pdf 的冻结文档。
|
||||
|
||||
Raises:
|
||||
ValidationError: invoice / 订单号缺失。
|
||||
"""
|
||||
if not isinstance(payload, Mapping):
|
||||
raise _po_invalid("采购单数据必须是对象")
|
||||
invoice_no = _as_text(payload.get("invoice_no") or payload.get("invoice"))
|
||||
po_no = _as_text(payload.get("po_no") or payload.get("order_no"))
|
||||
if not invoice_no:
|
||||
raise _po_invalid("缺少 invoice_no", details={"field": "invoice_no"})
|
||||
if not po_no:
|
||||
raise _po_invalid("缺少 po_no", details={"field": "po_no"})
|
||||
|
||||
raw_lines = payload.get("lines") or []
|
||||
if raw_lines and not isinstance(raw_lines, list):
|
||||
raise _po_invalid("lines 必须是数组", details={"field": "lines"})
|
||||
|
||||
lines: list[PoOrderLine] = []
|
||||
for index, raw in enumerate(raw_lines):
|
||||
if not isinstance(raw, Mapping):
|
||||
raise _po_invalid("明细行必须是对象", details={"field": "lines", "index": index})
|
||||
seq = _as_text(raw.get("seq") or raw.get("item_seq") or (index + 1))
|
||||
item_no = _as_text(raw.get("item_no") or raw.get("part_no"))
|
||||
lines.append(
|
||||
PoOrderLine(
|
||||
seq=seq,
|
||||
item_no=item_no,
|
||||
name=_as_text(raw.get("name")),
|
||||
spec=_as_text(raw.get("spec")),
|
||||
extra_spec=_as_text(raw.get("extra_spec")),
|
||||
qty=_as_text(raw.get("qty")),
|
||||
unit=_as_text(raw.get("unit")),
|
||||
arrive=_as_text(raw.get("arrive") or raw.get("arrive_date")),
|
||||
origin_no=_as_text(raw.get("origin_no")),
|
||||
version=_as_text(raw.get("version")),
|
||||
untax_price=_as_text(raw.get("untax_price")),
|
||||
tax_price=_as_text(raw.get("tax_price")),
|
||||
untax_amt=_as_text(raw.get("untax_amt")),
|
||||
tax_amt=_as_text(raw.get("tax_amt")),
|
||||
halogen=_as_text(raw.get("halogen")),
|
||||
vendor_item=_as_text(raw.get("vendor_item")),
|
||||
)
|
||||
)
|
||||
|
||||
return PoOrderDocument(
|
||||
invoice_no=invoice_no,
|
||||
po_no=po_no,
|
||||
po_date=_as_text(payload.get("po_date")),
|
||||
po_type=_as_text(payload.get("po_type")),
|
||||
pay_term=_as_text(payload.get("pay_term")),
|
||||
tax_type=_as_text(payload.get("tax_type")),
|
||||
price_term=_as_text(payload.get("price_term")),
|
||||
currency=_as_text(payload.get("currency")),
|
||||
ship_address=_as_text(payload.get("ship_address")),
|
||||
bill_address=_as_text(payload.get("bill_address")),
|
||||
vendor_code=_as_text(payload.get("vendor_code")),
|
||||
vendor_name=_as_text(payload.get("vendor_name")),
|
||||
vendor_tel=_as_text(payload.get("vendor_tel")),
|
||||
vendor_fax=_as_text(payload.get("vendor_fax")),
|
||||
vendor_addr=_as_text(payload.get("vendor_addr")),
|
||||
company_name=_as_text(payload.get("company_name")),
|
||||
company_address=_as_text(payload.get("company_address")),
|
||||
company_phone=_as_text(payload.get("company_phone")),
|
||||
company_fax=_as_text(payload.get("company_fax")),
|
||||
maker=_as_text(payload.get("maker")),
|
||||
untax_total=_as_text(payload.get("untax_total")),
|
||||
tax_total=_as_text(payload.get("tax_total")),
|
||||
lines=tuple(lines),
|
||||
)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/publish.py
|
||||
|
||||
用途:生成制式采购单 PDF 并上传到文档库当月「PO订单」目录。
|
||||
依赖:save_po_order_pdf、SalesDmsClient、filename。
|
||||
逻辑:先本地渲染,再 Attachment/Upload + CreateFiles;同名跳过。不进周检核 runner。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.services.voucher_check.adapters.base import ScannedFile
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.filename_match import match_filename
|
||||
from app.services.voucher_check.po_order.filename import build_po_order_filename
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
|
||||
from app.services.voucher_check.po_order.save import save_po_order_pdf
|
||||
|
||||
PO_TYPE_FOLDER = "PO订单"
|
||||
PO_FILENAME_TEMPLATE = "{invoice}-{order_no}.pdf"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoOrderPublishResult:
|
||||
"""一次制式采购单落库结果。"""
|
||||
|
||||
file: ScannedFile
|
||||
skipped_same_name: bool
|
||||
|
||||
|
||||
def publish_po_order_pdf(
|
||||
document: PoOrderDocument | Mapping[str, Any],
|
||||
*,
|
||||
period_month: date,
|
||||
type_folder: str = PO_TYPE_FOLDER,
|
||||
) -> PoOrderPublishResult:
|
||||
"""
|
||||
生成 `{invoice}-{订单号}.pdf` 并上传到销售开票附件/{年}/{月}/PO订单/。
|
||||
【AI 触发时机】已拿到给定采购单数据、需要写入文档库类型目录时调用。
|
||||
不要在周检核 runner 里调用。ERP 取数由 fetch_po_documents_for_invoices 或调用方完成。
|
||||
|
||||
核心逻辑:渲染到临时文件 → 确保年/月/PO订单目录 → 同名跳过否则 Upload+CreateFiles。
|
||||
|
||||
Args:
|
||||
document: PoOrderDocument 或同结构 dict。
|
||||
period_month: 类型目录所属自然月(用其年、月两位文件夹名)。
|
||||
type_folder: 默认「PO订单」,须与销售 Profile 一致。
|
||||
|
||||
Returns:
|
||||
文档库中的文件元数据;skipped_same_name 表示沿用已有同名文件。
|
||||
"""
|
||||
payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document)
|
||||
filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no)
|
||||
if match_filename(filename, template=PO_FILENAME_TEMPLATE, invoice_no=payload.invoice_no) is None:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError("生成的文件名不符合 {invoice}-{订单号}.pdf", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
|
||||
SalesDmsClient.ensure_configured()
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}"
|
||||
folder_id = SalesDmsClient.ensure_period_type_folder(period_month=period_month, type_folder=type_folder)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="hxops-po-") as tmp:
|
||||
local_path = save_po_order_pdf(payload, tmp, overwrite=True)
|
||||
content = Path(local_path).read_bytes()
|
||||
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id=folder_id,
|
||||
leaf_name=filename,
|
||||
content=content,
|
||||
)
|
||||
item_id = str(row.get("ID") or "").strip() or None
|
||||
return PoOrderPublishResult(
|
||||
file=ScannedFile(
|
||||
filename=str(row.get("LeafName") or filename).strip() or filename,
|
||||
item_id=item_id,
|
||||
folder_id=folder_id,
|
||||
path=str(row.get("Path") or f"{folder_path}/{filename}"),
|
||||
extra={
|
||||
"skipped_same_name": skipped,
|
||||
"version_id": row.get("VersionID"),
|
||||
"type_folder": type_folder,
|
||||
},
|
||||
),
|
||||
skipped_same_name=skipped,
|
||||
)
|
||||
@@ -0,0 +1,343 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/renderer.py
|
||||
|
||||
用途:按已确认的 Crystal / apmr900 对照样张画出制式采购单 PDF。
|
||||
依赖:reportlab、fonts、models、页眉 Logo。
|
||||
逻辑:无满格单元格;项次最左;表头三行折行;不查询 ERP。多页时续页只重复页眉与表头。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.lib.colors import HexColor
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
from app.services.voucher_check.po_order.fonts import resolve_po_font
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine
|
||||
|
||||
INK = HexColor("#111111")
|
||||
LINE = HexColor("#333333")
|
||||
DEFAULT_LOGO = Path(__file__).resolve().parent / "assets" / "welltrust-logo.png"
|
||||
ROW_H = 13 * mm
|
||||
HEADER_H = 11 * mm
|
||||
FOOT_Y = 18 * mm
|
||||
TOTALS_H = 16 * mm
|
||||
|
||||
|
||||
def render_po_order_pdf(document: PoOrderDocument, out_path: Path, *, logo_path: Path | None = None) -> None:
|
||||
"""
|
||||
把给定采购单画到 out_path(调用方已定文件名)。
|
||||
核心逻辑:先分页再逐页绘制,避免明细把合计和签核挤出页外。
|
||||
"""
|
||||
font = resolve_po_font()
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
page_w, page_h = A4
|
||||
left = 16 * mm
|
||||
right = page_w - 16 * mm
|
||||
pages = _paginate(document.lines, page_h)
|
||||
page_count = len(pages)
|
||||
c = canvas.Canvas(str(out_path), pagesize=A4)
|
||||
c.setTitle(f"采购单 {document.po_no}")
|
||||
c.setAuthor("HXOPS")
|
||||
logo = logo_path if logo_path is not None else DEFAULT_LOGO
|
||||
for index, page_lines in enumerate(pages):
|
||||
page_no = f"{index + 1}/{page_count}"
|
||||
is_last = index == page_count - 1
|
||||
_draw_page(
|
||||
c,
|
||||
document=document,
|
||||
lines=page_lines,
|
||||
font=font,
|
||||
left=left,
|
||||
right=right,
|
||||
page_h=page_h,
|
||||
page_no=page_no,
|
||||
show_po_fields=(index == 0),
|
||||
show_totals=is_last,
|
||||
logo_path=logo,
|
||||
)
|
||||
c.showPage()
|
||||
c.save()
|
||||
|
||||
|
||||
def _paginate(lines: tuple[PoOrderLine, ...], page_h: float) -> list[list[PoOrderLine]]:
|
||||
"""按版心高度切页;末页预留合计高度。"""
|
||||
remaining = list(lines)
|
||||
pages: list[list[PoOrderLine]] = []
|
||||
first = True
|
||||
if not remaining:
|
||||
return [[]]
|
||||
while remaining:
|
||||
last_max = _max_rows(page_h, first_page=first, last_page=True)
|
||||
if len(remaining) <= last_max:
|
||||
pages.append(remaining)
|
||||
break
|
||||
# 留至少一行给末页,避免把合计画进已排满的页。
|
||||
max_rows = _max_rows(page_h, first_page=first, last_page=False)
|
||||
take = min(max(1, max_rows), len(remaining) - 1)
|
||||
pages.append(remaining[:take])
|
||||
remaining = remaining[take:]
|
||||
first = False
|
||||
return pages or [[]]
|
||||
|
||||
|
||||
def _max_rows(page_h: float, *, first_page: bool, last_page: bool) -> int:
|
||||
"""估算一页能放下的明细行数。"""
|
||||
header_block = 86 * mm if first_page else 42 * mm
|
||||
reserved = FOOT_Y + 8 * mm + HEADER_H
|
||||
if last_page:
|
||||
reserved += TOTALS_H
|
||||
usable = page_h - header_block - reserved
|
||||
return max(1, int(usable // ROW_H))
|
||||
|
||||
|
||||
def _draw_page(
|
||||
c: canvas.Canvas,
|
||||
*,
|
||||
document: PoOrderDocument,
|
||||
lines: list[PoOrderLine],
|
||||
font: str,
|
||||
left: float,
|
||||
right: float,
|
||||
page_h: float,
|
||||
page_no: str,
|
||||
show_po_fields: bool,
|
||||
show_totals: bool,
|
||||
logo_path: Path,
|
||||
) -> None:
|
||||
y = page_h - 10 * mm
|
||||
y = _draw_letterhead(c, document, font, left, right, y, page_no, logo_path)
|
||||
if show_po_fields:
|
||||
y = _draw_po_fields(c, document, font, left, right, y)
|
||||
else:
|
||||
y -= 4 * mm
|
||||
_hline(c, left, right, y, 0.8)
|
||||
y -= 1 * mm
|
||||
y = _draw_table_header(c, font, left, right, y)
|
||||
y = _draw_table_rows(c, lines, font, left, y)
|
||||
if show_totals:
|
||||
_draw_totals(c, document, font, left, y)
|
||||
_draw_footer(c, font, left, right)
|
||||
|
||||
|
||||
def _draw_letterhead(
|
||||
c: canvas.Canvas,
|
||||
document: PoOrderDocument,
|
||||
font: str,
|
||||
left: float,
|
||||
right: float,
|
||||
y: float,
|
||||
page_no: str,
|
||||
logo_path: Path,
|
||||
) -> float:
|
||||
"""Logo 在左;右侧公司名、「采购单」、地址、电话;制表者/页次下一行靠右。"""
|
||||
logo_w = 52 * mm
|
||||
logo_h = 14 * mm
|
||||
logo_bottom = y - logo_h
|
||||
if logo_path.is_file():
|
||||
c.drawImage(
|
||||
str(logo_path),
|
||||
left,
|
||||
logo_bottom,
|
||||
width=logo_w,
|
||||
height=logo_h,
|
||||
mask="auto",
|
||||
preserveAspectRatio=True,
|
||||
anchor="sw",
|
||||
)
|
||||
text_x = left + 56 * mm
|
||||
block_mid = (text_x + right) / 2
|
||||
_text(c, font, block_mid, y - 3.5 * mm, document.company_name, 11, centre=True)
|
||||
_text(c, font, block_mid, y - 8.2 * mm, "采购单", 10, centre=True)
|
||||
fax = document.company_fax or ""
|
||||
_text(c, font, text_x, y - 13 * mm, f"地址:{document.company_address}", 8)
|
||||
_text(c, font, text_x, y - 17.5 * mm, f"公司电话:{document.company_phone} 公司传真:{fax}", 8)
|
||||
_text(c, font, right - 52 * mm, y - 22.5 * mm, f"制表者: {document.maker}", 8)
|
||||
_text(c, font, right, y - 22.5 * mm, f"页次: {page_no}", 8, right_align=True)
|
||||
y = min(logo_bottom, y - 24 * mm) - 2 * mm
|
||||
_hline(c, left, right, y, 0.8)
|
||||
return y - 6 * mm
|
||||
|
||||
|
||||
def _draw_po_fields(
|
||||
c: canvas.Canvas,
|
||||
document: PoOrderDocument,
|
||||
font: str,
|
||||
left: float,
|
||||
right: float,
|
||||
y: float,
|
||||
) -> float:
|
||||
"""左栏采购单号、右栏采购日期,与对照样张一致。"""
|
||||
col2 = left + 98 * mm
|
||||
val1 = left + 22 * mm
|
||||
val2 = col2 + 20 * mm
|
||||
po_label = f"{document.po_no} {document.po_type}".rstrip()
|
||||
_text(c, font, left, y, "采购单号:")
|
||||
_text(c, font, val1, y, po_label)
|
||||
_text(c, font, col2, y, "采购日期:")
|
||||
_text(c, font, val2, y, document.po_date)
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "付款条件:")
|
||||
_text(c, font, val1, y, document.pay_term)
|
||||
_text(c, font, col2, y, "税 种:")
|
||||
_text(c, font, val2, y, document.tax_type)
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "价格条件:")
|
||||
_text(c, font, val1, y, document.price_term)
|
||||
_text(c, font, col2, y, "币 种:")
|
||||
_text(c, font, val2, y, document.currency)
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "送货地址:")
|
||||
_text(c, font, val1, y, document.ship_address or " ")
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "帐单地址:")
|
||||
_text(c, font, val1, y, document.bill_address or " ")
|
||||
y -= 6 * mm
|
||||
_text(c, font, left, y, "供应厂商:")
|
||||
_text(c, font, val1, y, f"{document.vendor_code} {document.vendor_name}".strip())
|
||||
_text(c, font, left + 118 * mm, y, f"Tel: {document.vendor_tel}")
|
||||
y -= 5 * mm
|
||||
_text(c, font, val1, y, document.vendor_addr, 8)
|
||||
_text(c, font, left + 118 * mm, y, f"Fax: {document.vendor_fax}")
|
||||
y -= 4 * mm
|
||||
_hline(c, left, right, y, 0.8)
|
||||
return y - 1 * mm
|
||||
|
||||
|
||||
def _table_columns(left: float) -> dict[str, float]:
|
||||
return {
|
||||
"seq": left,
|
||||
"item": left + 8 * mm,
|
||||
"origin": left + 50 * mm,
|
||||
"arrive": left + 80 * mm,
|
||||
"qty": left + 108 * mm,
|
||||
"unit": left + 116 * mm,
|
||||
"price": left + 142 * mm,
|
||||
"amt": left + 164 * mm,
|
||||
"halo": left + 168 * mm,
|
||||
}
|
||||
|
||||
|
||||
def _draw_table_header(c: canvas.Canvas, font: str, left: float, right: float, y: float) -> float:
|
||||
"""Crystal 风格:无竖格,表头三行折行,项次最左。"""
|
||||
cols = _table_columns(left)
|
||||
table_top = y
|
||||
_hline(c, left, right, table_top, 0.7)
|
||||
h1 = table_top - 3.6 * mm
|
||||
h2 = table_top - 7.0 * mm
|
||||
h3 = table_top - 10.2 * mm
|
||||
_text(c, font, cols["seq"], h1, "项次", 7)
|
||||
_text(c, font, cols["item"], h1, "料件编号", 7)
|
||||
_text(c, font, cols["item"], h2, "品名/规格", 7)
|
||||
_text(c, font, cols["item"], h3, "厂商料号额外品名规格说明", 6.5)
|
||||
_text(c, font, cols["origin"], h1, "原始编号", 7)
|
||||
_text(c, font, cols["origin"], h2, "版本", 7)
|
||||
_text(c, font, cols["origin"], h3, "行序", 6.5)
|
||||
_text(c, font, cols["arrive"], h1, "到货日", 7)
|
||||
_text(c, font, cols["qty"] - 8 * mm, h1, "数 量", 7)
|
||||
_text(c, font, cols["unit"], h1, "单 位", 7)
|
||||
_text(c, font, cols["price"], h1, "税前单价", 7, right_align=True)
|
||||
_text(c, font, cols["price"], h2, "含税单价", 7, right_align=True)
|
||||
_text(c, font, cols["amt"], h1, "税前金额", 7, right_align=True)
|
||||
_text(c, font, cols["amt"], h2, "含税金额", 7, right_align=True)
|
||||
_text(c, font, cols["halo"], h1, "卤素", 7)
|
||||
_text(c, font, cols["halo"], h2, "管控", 7)
|
||||
_text(c, font, cols["halo"] + 10 * mm, h1, "环保", 7)
|
||||
_text(c, font, cols["halo"] + 10 * mm, h2, "等级", 7)
|
||||
c.setStrokeColor(LINE)
|
||||
c.setLineWidth(0.4)
|
||||
c.line(cols["price"] - 22 * mm, h2 - 1.2 * mm, cols["price"], h2 - 1.2 * mm)
|
||||
c.line(cols["amt"] - 22 * mm, h2 - 1.2 * mm, cols["amt"], h2 - 1.2 * mm)
|
||||
y = table_top - HEADER_H
|
||||
_hline(c, left, right, y, 0.5)
|
||||
return y
|
||||
|
||||
|
||||
def _draw_table_rows(c: canvas.Canvas, lines: list[PoOrderLine], font: str, left: float, y: float) -> float:
|
||||
"""每笔三行:料号/品名/规格,无斑马底、无竖线格。"""
|
||||
cols = _table_columns(left)
|
||||
for line in lines:
|
||||
r1 = y - 3.8 * mm
|
||||
r2 = y - 7.6 * mm
|
||||
r3 = y - 11.2 * mm
|
||||
_text(c, font, cols["seq"], r1, line.seq, 8)
|
||||
_text(c, font, cols["item"], r1, line.item_no, 8)
|
||||
_text(c, font, cols["item"], r2, line.name, 8)
|
||||
_text(c, font, cols["item"], r3, line.spec or line.extra_spec, 8)
|
||||
_text(c, font, cols["origin"], r1, line.vendor_item, 8)
|
||||
origin_second = line.origin_no or line.version
|
||||
_text(c, font, cols["origin"], r2, origin_second, 8)
|
||||
_text(c, font, cols["arrive"], r1, line.arrive, 8)
|
||||
_text(c, font, cols["qty"], r1, line.qty, 8, right_align=True)
|
||||
_text(c, font, cols["unit"], r1, line.unit, 8)
|
||||
_text(c, font, cols["price"], r1, line.untax_price, 8, right_align=True)
|
||||
_text(c, font, cols["price"], r2, line.tax_price, 8, right_align=True)
|
||||
_text(c, font, cols["amt"], r1, line.untax_amt, 8, right_align=True)
|
||||
_text(c, font, cols["amt"], r2, line.tax_amt, 8, right_align=True)
|
||||
_text(c, font, cols["halo"], r1, line.halogen, 8)
|
||||
y -= ROW_H
|
||||
return y
|
||||
|
||||
|
||||
def _draw_totals(c: canvas.Canvas, document: PoOrderDocument, font: str, left: float, y: float) -> None:
|
||||
"""合计靠右,金额带细框。"""
|
||||
cols = _table_columns(left)
|
||||
y -= 6 * mm
|
||||
box_w = 22 * mm
|
||||
box_h = 4.6 * mm
|
||||
_text(c, font, cols["price"] - 28 * mm, y, "税前金额总和:", 8)
|
||||
_rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h)
|
||||
_text(c, font, cols["amt"] - 1.2 * mm, y, document.untax_total, 8, right_align=True)
|
||||
y -= 6 * mm
|
||||
_text(c, font, cols["price"] - 28 * mm, y, "含税金额总和:", 8)
|
||||
_rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h)
|
||||
_text(c, font, cols["amt"] - 1.2 * mm, y, document.tax_total, 8, right_align=True)
|
||||
|
||||
|
||||
def _draw_footer(c: canvas.Canvas, font: str, left: float, right: float) -> None:
|
||||
"""核准/审核/经办横排;线左 (apmr900)、线右 (结束)。"""
|
||||
span = right - left
|
||||
_text(c, font, left + 10 * mm, FOOT_Y + 5 * mm, "核准", 10)
|
||||
_text(c, font, left + span / 2, FOOT_Y + 5 * mm, "审核", 10, centre=True)
|
||||
_text(c, font, right - 10 * mm, FOOT_Y + 5 * mm, "经办", 10, right_align=True)
|
||||
_hline(c, left, right, FOOT_Y, 0.7)
|
||||
_text(c, font, left, FOOT_Y - 1.1 * mm, "(apmr900)", 8)
|
||||
_text(c, font, right, FOOT_Y - 1.1 * mm, "(结束)", 8, right_align=True)
|
||||
|
||||
|
||||
def _text(
|
||||
c: canvas.Canvas,
|
||||
font: str,
|
||||
x: float,
|
||||
y: float,
|
||||
text: str,
|
||||
size: float = 9,
|
||||
*,
|
||||
colour=INK,
|
||||
right_align: bool = False,
|
||||
centre: bool = False,
|
||||
) -> None:
|
||||
c.setFillColor(colour)
|
||||
c.setFont(font, size)
|
||||
value = text or ""
|
||||
if centre:
|
||||
c.drawCentredString(x, y, value)
|
||||
elif right_align:
|
||||
c.drawRightString(x, y, value)
|
||||
else:
|
||||
c.drawString(x, y, value)
|
||||
|
||||
|
||||
def _hline(c: canvas.Canvas, x1: float, x2: float, y: float, width: float = 0.4) -> None:
|
||||
c.setStrokeColor(LINE)
|
||||
c.setLineWidth(width)
|
||||
c.line(x1, y, x2, y)
|
||||
|
||||
|
||||
def _rect(c: canvas.Canvas, x: float, y: float, w: float, h: float) -> None:
|
||||
c.setStrokeColor(LINE)
|
||||
c.setLineWidth(0.5)
|
||||
c.rect(x, y, w, h, stroke=1, fill=0)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/sample.py
|
||||
|
||||
用途:对照 apmr900 原件的样张数据,供单测与本地出样,不是正式业务数据。
|
||||
依赖:models.parse_po_order_document。
|
||||
逻辑:字段来自 e:\\Work\\Agent\\立账凭证\\采购单.pdf;invoice_no 仅用于文件名演示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
|
||||
|
||||
SAMPLE_PO_ORDER_PAYLOAD: dict[str, Any] = {
|
||||
"invoice_no": "INV-SAMPLE",
|
||||
"company_phone": "0512-63136988",
|
||||
"company_fax": "",
|
||||
"company_address": "江苏省苏州市吴江区经济开发区山湖西路789号",
|
||||
"company_name": "苏州和信精密科技有限公司",
|
||||
"maker": "AI",
|
||||
"po_date": "2016/5/28",
|
||||
"po_no": "5201-1605280003",
|
||||
"po_type": "原料采购单",
|
||||
"price_term": "A01 取核价单价",
|
||||
"ship_address": "",
|
||||
"pay_term": "月结一个月",
|
||||
"tax_type": "进项(17%含税)",
|
||||
"currency": "RMB",
|
||||
"bill_address": "",
|
||||
"vendor_name": "北川科技(苏州)有限公司",
|
||||
"vendor_code": "VCCD00013",
|
||||
"vendor_tel": "0512-62810369",
|
||||
"vendor_fax": "0512-62810368",
|
||||
"vendor_addr": "苏州市工业园区胜浦分区银胜路61号",
|
||||
"untax_total": "4,455.50",
|
||||
"tax_total": "5,212.94",
|
||||
"lines": [
|
||||
{
|
||||
"item_no": "3450541801",
|
||||
"seq": "1",
|
||||
"qty": "730",
|
||||
"unit": "PCS",
|
||||
"arrive": "2016/6/16",
|
||||
"untax_price": "3.350000",
|
||||
"untax_amt": "2,445.50",
|
||||
"halogen": "RoHS",
|
||||
"name": "FRAME CUBE CORNER",
|
||||
"spec": "H20*W36.5*L36.7",
|
||||
"tax_price": "3.919500",
|
||||
"tax_amt": "2,861.24",
|
||||
"origin_no": "3301-1605260004",
|
||||
"version": "-0001",
|
||||
"vendor_item": "3450541801",
|
||||
},
|
||||
{
|
||||
"item_no": "3450541801",
|
||||
"seq": "2",
|
||||
"qty": "600",
|
||||
"unit": "PCS",
|
||||
"arrive": "2016/6/16",
|
||||
"untax_price": "3.350000",
|
||||
"untax_amt": "2,010.00",
|
||||
"halogen": "RoHS",
|
||||
"name": "FRAME CUBE CORNER",
|
||||
"spec": "H20*W36.5*L36.7",
|
||||
"tax_price": "3.919500",
|
||||
"tax_amt": "2,351.70",
|
||||
"origin_no": "3301-1605100007",
|
||||
"version": "-0001",
|
||||
"vendor_item": "3450541801",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def sample_po_order_document() -> PoOrderDocument:
|
||||
"""返回对照样张用的采购单数据;正式任务必须改用真实给定数据。"""
|
||||
return parse_po_order_document(SAMPLE_PO_ORDER_PAYLOAD)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/save.py
|
||||
|
||||
用途:根据给定采购单数据生成 PDF,并按 `{invoice}-{订单号}.pdf` 保存到本地。
|
||||
依赖:filename、models、renderer。
|
||||
逻辑:不查 ERP。上传文档库请用 publish_po_order_pdf。周检核 runner 不要调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.services.voucher_check.po_order.filename import build_po_order_filename
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
|
||||
from app.services.voucher_check.po_order.renderer import render_po_order_pdf
|
||||
|
||||
|
||||
def save_po_order_pdf(
|
||||
document: PoOrderDocument | Mapping[str, Any],
|
||||
output_dir: str | Path,
|
||||
*,
|
||||
overwrite: bool = True,
|
||||
) -> Path:
|
||||
"""
|
||||
生成制式采购单 PDF 并保存。
|
||||
【AI 触发时机】已拿到销售 invoice 与一张 PO 的给定字段、需要落盘 PDF 时调用。
|
||||
不要在周检核 runner 里调用。ERP 取数见 erp_po_repository.fetch_po_documents_for_invoices。
|
||||
|
||||
核心逻辑:解析/校验文档 → `{invoice}-{po_no}.pdf` → Crystal 风格渲染到 output_dir。
|
||||
|
||||
Args:
|
||||
document: PoOrderDocument 或同结构 dict(须含 invoice_no、po_no)。
|
||||
output_dir: 本地目录;不存在则创建。上传文档库请改用 publish_po_order_pdf。
|
||||
overwrite: 为 False 且目标已存在时直接返回现有路径,不覆盖。
|
||||
|
||||
Returns:
|
||||
生成(或已存在)的 PDF 绝对路径。
|
||||
"""
|
||||
payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document)
|
||||
filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no)
|
||||
target = Path(output_dir).expanduser().resolve() / filename
|
||||
if target.exists() and not overwrite:
|
||||
return target
|
||||
render_po_order_pdf(payload, target)
|
||||
return target
|
||||
@@ -0,0 +1,206 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_print_runner.py
|
||||
|
||||
用途:立账凭证「PO 订单生成」周批:上月发票 → TGHX 取数 → 制式 PDF 上传到「PO订单」。
|
||||
依赖:config、erp_repository、ErpPoPrintAdapter、dms_client、notification。
|
||||
逻辑:独立排程 accounting-voucher-po-print 调用;不要从检核 runner 调用。
|
||||
同名跳过;找不到 PO 的发票记 skipped,不阻断其它票。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.config import load_engine_config
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.erp_repository import fetch_month_invoices
|
||||
from app.services.voucher_check.notification import send_failure_alert
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def _mark_domain_notification_managed(run: ScheduleRun) -> None:
|
||||
"""避免通用排程再发一条企微;本任务只在技术失败时告警。"""
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary["domain_notification_managed"] = True
|
||||
run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _write_summary(run: ScheduleRun, payload: dict[str, Any]) -> None:
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary["domain_notification_managed"] = True
|
||||
summary["voucher_po_print"] = payload
|
||||
run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def run_po_print_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
按上月销售发票生成制式采购单 PDF 并上传到文档库「PO订单」。
|
||||
【AI 触发时机】仅 accounting-voucher-po-print 排程(默认周二 05:00)调用;检核周批不要调用。
|
||||
|
||||
核心逻辑:fetch_month_invoices → fetch_documents → 逐张 upload_given(同名跳过)。
|
||||
不调用 ErpPoPrintAdapter.fetch,不写 voucher_check_runs。
|
||||
|
||||
Returns:
|
||||
ScheduleExecuteResult:(发票数, 新上传数, 失败数, 跳过数, details, errors, step_logs)
|
||||
跳过 = 同名已存在 + 发票没有对应 TGHX 采购单。
|
||||
"""
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
errors: list[str] = []
|
||||
details: list[dict[str, Any]] = []
|
||||
adapter = ErpPoPrintAdapter()
|
||||
current_app.logger.info(
|
||||
"[voucher-po-print] start name=%s path=accounting-voucher-po-print run_no=%s",
|
||||
getattr(task, "name", None) or "立账凭证 PO 订单生成",
|
||||
run.run_no,
|
||||
)
|
||||
_mark_domain_notification_managed(run)
|
||||
|
||||
try:
|
||||
config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {})
|
||||
SalesDmsClient.ensure_configured()
|
||||
period_month, invoices = fetch_month_invoices(config)
|
||||
except AppError as exc:
|
||||
send_failure_alert(
|
||||
task=task,
|
||||
run=run,
|
||||
stage="config_or_erp",
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
enabled=True,
|
||||
title=f"立账凭证 PO 生成失败: {task.name}",
|
||||
)
|
||||
raise
|
||||
|
||||
invoice_nos = [row.invoice_no for row in invoices]
|
||||
step_logs.append(
|
||||
{
|
||||
"step": "list_invoices",
|
||||
"status": "success",
|
||||
"detail": {"period": period_month.isoformat(), "invoice_count": len(invoice_nos)},
|
||||
}
|
||||
)
|
||||
if not invoice_nos:
|
||||
_write_summary(
|
||||
run,
|
||||
{
|
||||
"period": period_month.isoformat(),
|
||||
"invoice_count": 0,
|
||||
"uploaded": 0,
|
||||
"skipped_same_name": 0,
|
||||
"skipped_no_po": 0,
|
||||
"failed": 0,
|
||||
},
|
||||
)
|
||||
return (0, 0, 0, 0, [], [], step_logs)
|
||||
|
||||
try:
|
||||
documents = adapter.fetch_documents(invoice_nos, config=config)
|
||||
except AppError as exc:
|
||||
send_failure_alert(
|
||||
task=task,
|
||||
run=run,
|
||||
stage="erp_po",
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
enabled=config.notify_failure_enabled,
|
||||
title=f"立账凭证 PO 生成失败: {task.name}",
|
||||
)
|
||||
raise
|
||||
|
||||
covered = {item.invoice_no for item in documents}
|
||||
skipped_no_po = 0
|
||||
for invoice_no in invoice_nos:
|
||||
if invoice_no not in covered:
|
||||
skipped_no_po += 1
|
||||
details.append({"invoice_no": invoice_no, "status": "skipped_no_po"})
|
||||
|
||||
uploaded = 0
|
||||
skipped_same_name = 0
|
||||
failed = 0
|
||||
for document in documents:
|
||||
try:
|
||||
result = adapter.upload_given(document, period_month=period_month)
|
||||
if result.skipped_same_name:
|
||||
skipped_same_name += 1
|
||||
status = "skipped_same_name"
|
||||
else:
|
||||
uploaded += 1
|
||||
status = "uploaded"
|
||||
details.append(
|
||||
{
|
||||
"invoice_no": document.invoice_no,
|
||||
"po_no": document.po_no,
|
||||
"status": status,
|
||||
"filename": result.file.filename,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
errors.append(f"{document.invoice_no}/{document.po_no}: {type(exc).__name__}")
|
||||
details.append(
|
||||
{
|
||||
"invoice_no": document.invoice_no,
|
||||
"po_no": document.po_no,
|
||||
"status": "failed",
|
||||
"error_type": type(exc).__name__,
|
||||
}
|
||||
)
|
||||
current_app.logger.exception(
|
||||
"[voucher-po-print] upload failed invoice=%s po=%s",
|
||||
document.invoice_no,
|
||||
document.po_no,
|
||||
)
|
||||
|
||||
skipped = skipped_same_name + skipped_no_po
|
||||
if failed:
|
||||
send_failure_alert(
|
||||
task=task,
|
||||
run=run,
|
||||
stage="upload",
|
||||
error_code="VOUCHER_CHECK.PO_PRINT_PARTIAL",
|
||||
error_message=f"上传失败 {failed} 张,成功 {uploaded},跳过 {skipped}",
|
||||
enabled=config.notify_failure_enabled,
|
||||
title=f"立账凭证 PO 生成部分失败: {task.name}",
|
||||
)
|
||||
step_logs.append(
|
||||
{
|
||||
"step": "upload",
|
||||
"status": "failed" if failed else "success",
|
||||
"detail": {
|
||||
"uploaded": uploaded,
|
||||
"skipped_same_name": skipped_same_name,
|
||||
"skipped_no_po": skipped_no_po,
|
||||
"failed": failed,
|
||||
},
|
||||
}
|
||||
)
|
||||
_write_summary(
|
||||
run,
|
||||
{
|
||||
"period": period_month.isoformat(),
|
||||
"invoice_count": len(invoice_nos),
|
||||
"po_count": len(documents),
|
||||
"uploaded": uploaded,
|
||||
"skipped_same_name": skipped_same_name,
|
||||
"skipped_no_po": skipped_no_po,
|
||||
"failed": failed,
|
||||
},
|
||||
)
|
||||
current_app.logger.info(
|
||||
"[voucher-po-print] done period=%s invoices=%s uploaded=%s skipped=%s failed=%s",
|
||||
period_month.isoformat(),
|
||||
len(invoice_nos),
|
||||
uploaded,
|
||||
skipped,
|
||||
failed,
|
||||
)
|
||||
return (len(invoice_nos), uploaded, failed, skipped, details, errors, step_logs)
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/profiles/sales.py
|
||||
|
||||
用途:销售一期 Profile 定义(六类必检文件、类型目录、命名模板)。
|
||||
依赖:无外部 IO;由 profile_loader 发布快照。
|
||||
逻辑:周任务扫描 source_type=directory_scan;erp_po_print / oa_sales_release 仅登记,不在周二 runner 调用。
|
||||
逻辑:周任务扫描 source_type=directory_scan;subject_adapter=hxjm_apa 实际查 oma_file;erp_po_print.fetch / oa_sales_release 仅登记,不在检核 runner 调用。PO PDF 由独立排程 accounting-voucher-po-print(周二 05:00)写入类型目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/query_service.py
|
||||
|
||||
用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。
|
||||
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
|
||||
逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
|
||||
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
|
||||
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
|
||||
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,6 +20,7 @@ from app.models.voucher_check import (
|
||||
)
|
||||
from app.services.voucher_check.aggregator import aggregate_file_results
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
from app.services.voucher_check.schedule_seed import DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
|
||||
|
||||
|
||||
def parse_period_month(raw: str | None) -> date:
|
||||
@@ -38,9 +39,92 @@ def parse_period_month(raw: str | None) -> date:
|
||||
raise ValidationError(
|
||||
"period 格式须为 YYYY-MM",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"period": text},
|
||||
) from exc
|
||||
|
||||
|
||||
def parse_period_filter(raw: str | None) -> tuple[date | None, date | None]:
|
||||
"""
|
||||
将工作台列表 period 解析为 [start, end) 半开区间。
|
||||
核心逻辑:空值不过滤;YYYY 覆盖该自然年;YYYY-MM / YYYY-MM-DD 覆盖该自然月。
|
||||
|
||||
Args:
|
||||
raw: 查询参数 period,允许 YYYY、YYYY-MM、YYYY-MM-DD 或空。
|
||||
|
||||
Returns:
|
||||
(start, end);空 period 时为 (None, None)。
|
||||
|
||||
Raises:
|
||||
ValidationError: 格式无法解析。
|
||||
"""
|
||||
if not raw or not str(raw).strip():
|
||||
return None, None
|
||||
text = str(raw).strip()
|
||||
try:
|
||||
if len(text) == 4 and text.isdigit():
|
||||
year = int(text)
|
||||
return date(year, 1, 1), date(year + 1, 1, 1)
|
||||
start = parse_period_month(text)
|
||||
if start.month == 12:
|
||||
end = date(start.year + 1, 1, 1)
|
||||
else:
|
||||
end = date(start.year, start.month + 1, 1)
|
||||
return start, end
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(
|
||||
"period 格式须为 YYYY 或 YYYY-MM",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"period": text},
|
||||
) from exc
|
||||
except (TypeError, ValueError, OverflowError) as exc:
|
||||
raise ValidationError(
|
||||
"period 格式须为 YYYY 或 YYYY-MM",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"period": text},
|
||||
) from exc
|
||||
|
||||
|
||||
def _apply_period_filter(query, column, period: str | None):
|
||||
"""
|
||||
按 period 的年或月区间过滤 period_month 列。
|
||||
|
||||
Args:
|
||||
query: SQLAlchemy 查询。
|
||||
column: 期间列,通常为 VoucherCheckRun.period_month。
|
||||
period: YYYY、YYYY-MM,或空。
|
||||
|
||||
Returns:
|
||||
加上区间条件后的查询;period 为空时原样返回。
|
||||
"""
|
||||
start, end = parse_period_filter(period)
|
||||
if start is None or end is None:
|
||||
return query
|
||||
return query.filter(column >= start, column < end)
|
||||
|
||||
|
||||
def _period_value_in_filter(period_month: str | None, period: str | None) -> bool:
|
||||
"""
|
||||
判断 YYYY-MM 文本是否落在列表 period 筛选区间内。
|
||||
|
||||
Args:
|
||||
period_month: 批次期间,例如 2026-08。
|
||||
period: 与列表查询相同的 YYYY 或 YYYY-MM。
|
||||
|
||||
Returns:
|
||||
无需过滤或文本落在区间内时为 True。
|
||||
"""
|
||||
start, end = parse_period_filter(period)
|
||||
if start is None or end is None:
|
||||
return True
|
||||
if not period_month:
|
||||
return False
|
||||
try:
|
||||
row = datetime.strptime(str(period_month)[:7], "%Y-%m").date().replace(day=1)
|
||||
except ValueError:
|
||||
return False
|
||||
return start <= row < end
|
||||
|
||||
|
||||
def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]:
|
||||
return {
|
||||
"id": run.id,
|
||||
@@ -93,6 +177,238 @@ def _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _as_summary_dict(raw: Any) -> dict[str, Any]:
|
||||
"""把 JSON 字段收成 dict;非 dict 视为空。"""
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _iso_dt(value: datetime | None) -> str | None:
|
||||
"""将 datetime 转 ISO 文本,空值保持 None。"""
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def _latest_voucher_summary(schedule_run: ScheduleRun) -> dict[str, Any]:
|
||||
"""从排程 response_summary_json 取出 voucher_check 快照。"""
|
||||
summary = _as_summary_dict(schedule_run.response_summary_json)
|
||||
voucher = summary.get("voucher_check")
|
||||
return voucher if isinstance(voucher, dict) else {}
|
||||
|
||||
|
||||
def _latest_current_step(schedule_run: ScheduleRun) -> dict[str, Any]:
|
||||
"""从排程 response_summary_json 取出 runner 写入的 current_step。"""
|
||||
summary = _as_summary_dict(schedule_run.response_summary_json)
|
||||
current = summary.get("current_step")
|
||||
return current if isinstance(current, dict) else {}
|
||||
|
||||
|
||||
def _latest_run_mode(
|
||||
schedule_run: ScheduleRun,
|
||||
engine: VoucherCheckRun | None,
|
||||
voucher_summary: dict[str, Any],
|
||||
) -> str:
|
||||
"""
|
||||
解析最近一批的执行模式。
|
||||
核心逻辑:优先引擎批次 mode;否则读 api_request_json.run_options,再回退 summary。
|
||||
"""
|
||||
if engine and engine.mode:
|
||||
return str(engine.mode)
|
||||
request_json = _as_summary_dict(schedule_run.api_request_json)
|
||||
options = request_json.get("run_options")
|
||||
option_mode = options.get("mode") if isinstance(options, dict) else None
|
||||
return str(option_mode or voucher_summary.get("mode") or "incremental")
|
||||
|
||||
|
||||
def _latest_period_month(
|
||||
schedule_run: ScheduleRun,
|
||||
engine: VoucherCheckRun | None,
|
||||
voucher_summary: dict[str, Any],
|
||||
) -> str:
|
||||
"""最近一批的资料所属期间;无快照时回退上一个自然月。"""
|
||||
if engine and engine.period_month:
|
||||
return engine.period_month.strftime("%Y-%m")
|
||||
raw = voucher_summary.get("period")
|
||||
if raw:
|
||||
return str(raw)[:7]
|
||||
period_month, *_ = previous_period_bounds()
|
||||
return period_month.strftime("%Y-%m")
|
||||
|
||||
|
||||
def _latest_card_status(schedule_run: ScheduleRun, engine: VoucherCheckRun | None) -> str:
|
||||
"""
|
||||
将排程状态与引擎批次状态收成工作台卡片状态。
|
||||
核心逻辑:queued/running 必须保留,不能走建批前失败那条 technical_failed 映射。
|
||||
"""
|
||||
schedule_status = str(schedule_run.status or "")
|
||||
if schedule_status == "queued":
|
||||
return "queued"
|
||||
if schedule_status == "running":
|
||||
return "running"
|
||||
if schedule_status == "failed":
|
||||
return "technical_failed"
|
||||
if engine is not None:
|
||||
return str(engine.status or "completed")
|
||||
if schedule_status in {"success", "partial_failed"}:
|
||||
return "completed"
|
||||
return schedule_status or "queued"
|
||||
|
||||
|
||||
def _latest_progress_percent(
|
||||
*,
|
||||
card_status: str,
|
||||
step: str | None,
|
||||
processed: int,
|
||||
subject_count: int,
|
||||
) -> int:
|
||||
"""
|
||||
按 runner 步骤估算进度百分比。
|
||||
核心逻辑:无精确进度字段;scan_dms 用已处理 invoice / 总数插值,终态固定 100。
|
||||
"""
|
||||
if card_status in {"completed", "missing"}:
|
||||
return 100
|
||||
if not step and card_status == "queued":
|
||||
return 8
|
||||
if step == "scan_dms" and subject_count > 0:
|
||||
return min(86, 22 + int(64 * processed / subject_count))
|
||||
step_base = {
|
||||
"queued": 8,
|
||||
"fetch_erp": 18,
|
||||
"scan_dms": 22,
|
||||
"persist": 88,
|
||||
"notify": 94,
|
||||
"done": 100,
|
||||
}
|
||||
if step in step_base:
|
||||
return step_base[step]
|
||||
if card_status == "technical_failed":
|
||||
return 18
|
||||
if card_status == "running":
|
||||
return 12
|
||||
return 0
|
||||
|
||||
|
||||
def _serialize_latest_run(schedule_run: ScheduleRun, engine: VoucherCheckRun | None) -> dict[str, Any]:
|
||||
"""
|
||||
序列化工作台「最近一次检核」卡片。
|
||||
核心逻辑:进度与四指标来自 ScheduleRun.response_summary_json 与引擎快照;不跟列表 period 筛选。
|
||||
"""
|
||||
voucher_summary = _latest_voucher_summary(schedule_run)
|
||||
current_step = _latest_current_step(schedule_run)
|
||||
card_status = _latest_card_status(schedule_run, engine)
|
||||
step_code = str(current_step.get("step") or "") or None
|
||||
if not step_code and card_status == "queued":
|
||||
step_code = "queued"
|
||||
processed = int(current_step.get("processed_count") or 0)
|
||||
subject_count = int(
|
||||
(engine.subject_count if engine is not None else 0)
|
||||
or voucher_summary.get("subject_count")
|
||||
or 0
|
||||
)
|
||||
archived_file_count = int(
|
||||
(engine.archived_file_count if engine is not None else 0)
|
||||
or voucher_summary.get("archived_file_count")
|
||||
or 0
|
||||
)
|
||||
missing_file_count = int(
|
||||
(engine.missing_file_count if engine is not None else 0)
|
||||
or voucher_summary.get("missing_file_count")
|
||||
or 0
|
||||
)
|
||||
missing_invoice_count = int(
|
||||
(engine.missing_invoice_count if engine is not None else 0)
|
||||
or voucher_summary.get("missing_invoice_count")
|
||||
or 0
|
||||
)
|
||||
started_at = (engine.started_at if engine is not None else None) or schedule_run.started_at
|
||||
finished_at = (engine.finished_at if engine is not None else None) or schedule_run.finished_at
|
||||
if card_status in {"queued", "running"}:
|
||||
finished_at = None
|
||||
return {
|
||||
"schedule_run_id": schedule_run.id,
|
||||
"engine_run_id": engine.id if engine is not None else None,
|
||||
"run_no": schedule_run.run_no,
|
||||
"period_month": _latest_period_month(schedule_run, engine, voucher_summary),
|
||||
"mode": _latest_run_mode(schedule_run, engine, voucher_summary),
|
||||
"status": card_status,
|
||||
"progress_percent": _latest_progress_percent(
|
||||
card_status=card_status,
|
||||
step=step_code,
|
||||
processed=processed,
|
||||
subject_count=subject_count,
|
||||
),
|
||||
"subject_count": subject_count,
|
||||
"archived_file_count": archived_file_count,
|
||||
"missing_file_count": missing_file_count,
|
||||
"missing_invoice_count": missing_invoice_count,
|
||||
"processed_count": processed,
|
||||
"started_at": _iso_dt(started_at),
|
||||
"finished_at": _iso_dt(finished_at),
|
||||
"error_message": schedule_run.error_message,
|
||||
"current_step": {
|
||||
"step": step_code,
|
||||
"label": str(current_step.get("label") or "") or None,
|
||||
"processed_count": processed,
|
||||
}
|
||||
if step_code
|
||||
else None,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_latest_from_engine(engine: VoucherCheckRun) -> dict[str, Any]:
|
||||
"""
|
||||
无对应排程时,用引擎批次充当最近一次检核。
|
||||
核心逻辑:历史/测试数据可能只有 voucher_check_runs;终态进度为 100。
|
||||
"""
|
||||
card_status = str(engine.status or "completed")
|
||||
return {
|
||||
"schedule_run_id": engine.schedule_run_id,
|
||||
"engine_run_id": engine.id,
|
||||
"run_no": engine.run_no,
|
||||
"period_month": engine.period_month.strftime("%Y-%m") if engine.period_month else None,
|
||||
"mode": engine.mode,
|
||||
"status": card_status,
|
||||
"progress_percent": _latest_progress_percent(
|
||||
card_status=card_status,
|
||||
step="done" if card_status in {"completed", "missing"} else None,
|
||||
processed=int(engine.subject_count or 0),
|
||||
subject_count=int(engine.subject_count or 0),
|
||||
),
|
||||
"subject_count": int(engine.subject_count or 0),
|
||||
"archived_file_count": int(engine.archived_file_count or 0),
|
||||
"missing_file_count": int(engine.missing_file_count or 0),
|
||||
"missing_invoice_count": int(engine.missing_invoice_count or 0),
|
||||
"processed_count": int(engine.subject_count or 0),
|
||||
"started_at": _iso_dt(engine.started_at),
|
||||
"finished_at": _iso_dt(engine.finished_at),
|
||||
"error_message": None,
|
||||
"current_step": {"step": "done", "label": None, "processed_count": int(engine.subject_count or 0)}
|
||||
if card_status in {"completed", "missing"}
|
||||
else None,
|
||||
}
|
||||
|
||||
|
||||
def get_latest_run() -> dict[str, Any] | None:
|
||||
"""
|
||||
取立账凭证最近一次排程批次(按 ScheduleRun.id 倒序),不跟随列表 period/status。
|
||||
核心逻辑:有排程则 join 引擎快照与 response_summary_json;仅有引擎批次时回退引擎表。
|
||||
|
||||
Returns:
|
||||
卡片载荷;从未跑过任何批次时为 None。
|
||||
"""
|
||||
schedule_run = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
|
||||
.filter(ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if schedule_run is not None:
|
||||
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run.id).first()
|
||||
return _serialize_latest_run(schedule_run, engine)
|
||||
latest_engine = VoucherCheckRun.query.order_by(VoucherCheckRun.id.desc()).first()
|
||||
if latest_engine is None:
|
||||
return None
|
||||
return _serialize_latest_from_engine(latest_engine)
|
||||
|
||||
|
||||
def list_runs(
|
||||
*,
|
||||
period: str | None = None,
|
||||
@@ -105,12 +421,11 @@ def list_runs(
|
||||
工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。
|
||||
核心逻辑:正常场景读取 VoucherCheckRun 统计快照;若配置校验等错误发生在
|
||||
create_run 之前,则回退显示对应 ScheduleRun,保证强制重检结果可见。
|
||||
period 支持 YYYY(全年)或 YYYY-MM(单月)。
|
||||
"""
|
||||
page = max(1, int(page or 1))
|
||||
page_size = max(1, min(int(page_size or 50), 200))
|
||||
q = VoucherCheckRun.query
|
||||
if period:
|
||||
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
|
||||
q = _apply_period_filter(VoucherCheckRun.query, VoucherCheckRun.period_month, period)
|
||||
if profile_code:
|
||||
q = q.filter(VoucherCheckRun.profile_code == str(profile_code).strip())
|
||||
if status:
|
||||
@@ -120,7 +435,7 @@ def list_runs(
|
||||
fallback_query = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
|
||||
.filter(
|
||||
ScheduleTask.platform_api_path == "accounting-voucher-check",
|
||||
ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
|
||||
ScheduleRun.status == "failed",
|
||||
)
|
||||
)
|
||||
@@ -132,7 +447,7 @@ def list_runs(
|
||||
row
|
||||
for row in fallback_rows
|
||||
if row.id not in engine_schedule_run_ids
|
||||
and (not period or _serialize_schedule_fallback_run(row)["period_month"] == parse_period_month(period).strftime("%Y-%m"))
|
||||
and _period_value_in_filter(_serialize_schedule_fallback_run(row)["period_month"], period)
|
||||
]
|
||||
merged = [_serialize_engine_run(row) for row in engine_rows]
|
||||
merged.extend(_serialize_schedule_fallback_run(row) for row in fallback_rows)
|
||||
@@ -284,6 +599,7 @@ def list_notifications(
|
||||
"""
|
||||
分页查询企微缺件汇总发送记录。
|
||||
核心逻辑:以 voucher_check_notifications 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。
|
||||
period 支持 YYYY(全年)或 YYYY-MM(单月)。
|
||||
"""
|
||||
page = max(1, int(page or 1))
|
||||
page_size = max(1, min(int(page_size or 50), 200))
|
||||
@@ -291,8 +607,7 @@ def list_notifications(
|
||||
VoucherCheckRun,
|
||||
VoucherCheckNotification.run_id == VoucherCheckRun.id,
|
||||
)
|
||||
if period:
|
||||
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
|
||||
q = _apply_period_filter(q, VoucherCheckRun.period_month, period)
|
||||
status_filter = str(send_status or "").strip()
|
||||
if status_filter:
|
||||
q = q.filter(VoucherCheckNotification.send_status == status_filter)
|
||||
|
||||
@@ -3,7 +3,8 @@ backend/app/services/voucher_check/runner.py
|
||||
|
||||
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
|
||||
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
|
||||
逻辑:不调用 erp_po_print / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。
|
||||
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由独立排程 accounting-voucher-po-print 提前写入类型目录。
|
||||
命中文件复制到所有归档,同名跳过仍记 archived。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/schedule_seed.py
|
||||
|
||||
用途:确保 accounting-voucher-check 默认周批 ScheduleTask 存在(周二 06:00 Asia/Shanghai)。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批改成周二,并剥离 schema 外的旧 job_params。
|
||||
用途:确保立账凭证检核(周二 06:00)与 PO 订单生成(周二 05:00)默认 ScheduleTask 存在。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;检核排程剥离 schema 外的旧 job_params。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +19,7 @@ from sqlalchemy.orm.attributes import flag_modified
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_PO_PRINT_JOB_PARAMS
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -28,6 +28,11 @@ DEFAULT_VOUCHER_CHECK_PLATFORM_PATH = "accounting-voucher-check"
|
||||
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * 2"
|
||||
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(周批)"
|
||||
|
||||
DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-PO-PRINT"
|
||||
DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH = "accounting-voucher-po-print"
|
||||
DEFAULT_VOUCHER_PO_PRINT_CRON = "0 5 * * 2"
|
||||
DEFAULT_VOUCHER_PO_PRINT_NAME = "立账凭证 PO 订单生成(周批)"
|
||||
|
||||
_HOOKS_REGISTERED = False
|
||||
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
|
||||
|
||||
@@ -163,6 +168,113 @@ def ensure_default_voucher_check_schedule(
|
||||
return task
|
||||
|
||||
|
||||
def _pick_schedule_owner(sess: Any) -> Any | None:
|
||||
"""优先管理员,否则任意用户;尚无用户时返回 None。"""
|
||||
owner = (
|
||||
sess.query(User)
|
||||
.filter(User.role == "admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if owner is None:
|
||||
owner = sess.query(User).order_by(User.id.asc()).first()
|
||||
return owner
|
||||
|
||||
|
||||
def ensure_default_voucher_po_print_schedule(
|
||||
*,
|
||||
commit: bool = True,
|
||||
session: Any | None = None,
|
||||
) -> ScheduleTask | None:
|
||||
"""
|
||||
幂等确保默认 PO 订单生成周批排程存在(周二 05:00,早于检核 06:00)。
|
||||
核心逻辑:已存在同 schedule_no / platform_api_path 则跳过;新建时尽量复用检核任务的企微接收人。
|
||||
|
||||
Args:
|
||||
commit: 是否立即提交。
|
||||
session: 可选独立 Session。
|
||||
|
||||
Returns:
|
||||
新建或已存在的 ScheduleTask;尚无用户时返回 None。
|
||||
"""
|
||||
sess = session if session is not None else db.session
|
||||
existing = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
owner = _pick_schedule_owner(sess)
|
||||
if owner is None:
|
||||
_LOGGER.info("skip seed accounting-voucher-po-print schedule: no users yet")
|
||||
return None
|
||||
|
||||
check_task = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
notify_ids = []
|
||||
if check_task is not None and isinstance(check_task.notify_user_ids_json, list):
|
||||
notify_ids = list(check_task.notify_user_ids_json)
|
||||
|
||||
now = datetime.utcnow()
|
||||
next_run = compute_next_run_at(
|
||||
DEFAULT_VOUCHER_PO_PRINT_CRON,
|
||||
timezone_name="Asia/Shanghai",
|
||||
) or now
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO,
|
||||
name=DEFAULT_VOUCHER_PO_PRINT_NAME,
|
||||
schedule_type="platform_job",
|
||||
owner_user_id=int(owner.id),
|
||||
cron_expr=DEFAULT_VOUCHER_PO_PRINT_CRON,
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
wait_seconds=0,
|
||||
platform_api_path=DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH,
|
||||
job_params=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
|
||||
kb_sync_enabled=False,
|
||||
notify_user_ids_json=notify_ids,
|
||||
notify_enabled=True,
|
||||
enabled=True,
|
||||
next_run_at=next_run,
|
||||
created_by=int(owner.id),
|
||||
updated_by=int(owner.id),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
sess.add(task)
|
||||
if commit:
|
||||
try:
|
||||
sess.commit()
|
||||
except Exception:
|
||||
sess.rollback()
|
||||
existing = (
|
||||
sess.query(ScheduleTask)
|
||||
.filter(
|
||||
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
raise
|
||||
else:
|
||||
sess.flush()
|
||||
_LOGGER.info("seeded accounting-voucher-po-print schedule id=%s", task.id)
|
||||
return task
|
||||
|
||||
|
||||
def register_voucher_check_schedule_hooks() -> None:
|
||||
"""注册 User after_commit 补建钩子(幂等)。"""
|
||||
global _HOOKS_REGISTERED
|
||||
@@ -181,6 +293,7 @@ def register_voucher_check_schedule_hooks() -> None:
|
||||
factory = sessionmaker(bind=bind)
|
||||
with factory() as new_sess:
|
||||
ensure_default_voucher_check_schedule(commit=True, session=new_sess)
|
||||
ensure_default_voucher_po_print_schedule(commit=True, session=new_sess)
|
||||
except Exception:
|
||||
_LOGGER.exception("voucher-check schedule seed after_commit failed")
|
||||
|
||||
|
||||
Reference in new issue
Block a user