Merge branch 'dev' into picture-feedback
This commit is contained in:
commit
34ad40778b
180 files changed
+13262
-5333
No files matched your search
@@ -7,6 +7,7 @@ services/admin/freight_rpa_source_admin_service.py
|
||||
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
||||
onhand_source_repository.validate_source_profile、audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
||||
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
|
||||
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
||||
"""
|
||||
|
||||
@@ -15,7 +16,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
@@ -38,7 +39,7 @@ from app.services.admin.freight_rpa_form_utils import (
|
||||
validate_report_path as _validate_report_path,
|
||||
)
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
||||
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
@@ -77,27 +78,50 @@ def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
|
||||
|
||||
|
||||
def _stored_username(profile: FreightRpaProfile) -> str | None:
|
||||
"""解密已保存的用户名,供管理端辨认账号。
|
||||
|
||||
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
|
||||
密码不走本函数。
|
||||
|
||||
Args:
|
||||
profile: 已持久化的货代登录连接。
|
||||
|
||||
Returns:
|
||||
str | None: 用户名明文;未配置或无法解密时为 None。
|
||||
"""
|
||||
if not profile.username_ciphertext:
|
||||
return None
|
||||
try:
|
||||
return decrypt_credential(profile.username_ciphertext)
|
||||
except (ServiceUnavailableError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
||||
'config_version': profile.config_version,
|
||||
'username': _stored_username(profile),
|
||||
'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
||||
"""密码等不可回显凭据只报告是否已配置。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
||||
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
|
||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
@@ -113,7 +137,11 @@ def delete_profile(profile_id: int) -> None:
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
||||
"""创建或更新货代登录连接。
|
||||
|
||||
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
|
||||
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
|
||||
"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
@@ -138,11 +166,14 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
if username is not None:
|
||||
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
|
||||
username_changed = False
|
||||
if username is not None and _stored_username(profile) != username:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
username_changed = True
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
if username_changed or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
|
||||
|
||||
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
||||
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款、验收款、质保款都可手动标为已付,并关闭该节点尚未发送的预警。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||
"""
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.services.contract_payment.erp_payment_service import (
|
||||
normalize_purchase_order_no,
|
||||
resolve_paid_node_dates,
|
||||
)
|
||||
from app.services.contract_payment.ledger_focus import stage_has_nothing_to_pay
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
@@ -52,6 +53,7 @@ class _AlertRecipient:
|
||||
oa_wecom_userid: str | None = None
|
||||
|
||||
|
||||
_ERP_PAID_STAGE_TYPES = {"prepayment", "shipment", "acceptance", "warranty"}
|
||||
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
|
||||
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
|
||||
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
|
||||
@@ -65,7 +67,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
|
||||
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
||||
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
||||
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
|
||||
ERP `apa_file` 的合格付款记录按金额匹配四个阶段,并停止已付款阶段尚未发送的后续轮次。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||
Args:
|
||||
today: 业务日期,未传时使用服务器日期。
|
||||
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
||||
@@ -85,14 +87,20 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
payable_orders = [
|
||||
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
|
||||
for node, contract in rows
|
||||
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in _ERP_PAID_STAGE_TYPES
|
||||
and normalize_purchase_order_no(contract.purchase_order_no)
|
||||
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||
]
|
||||
paid_records = fetch_paid_records(payable_orders)
|
||||
paid_node_dates: dict[int, str | None] = {}
|
||||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||||
for node, contract in rows:
|
||||
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||||
if (
|
||||
node.node_type in _ERP_PAID_STAGE_TYPES
|
||||
and purchase_order_no
|
||||
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||
):
|
||||
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
||||
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
||||
paid_node_dates.update(resolve_paid_node_dates(
|
||||
@@ -100,6 +108,11 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
paid_records.get(ledger_key, []),
|
||||
))
|
||||
for node, contract in rows:
|
||||
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||
# 金额和比例都为 0 时没有应付金额,关掉尚未发送的预警,不再按日期升级。
|
||||
resolved += _resolve_pending_alerts(node_id=node.id, reason="nothing_to_pay")
|
||||
skipped += 1
|
||||
continue
|
||||
anchor = _anchor_date(contract=contract, node=node)
|
||||
if anchor is None:
|
||||
skipped += 1
|
||||
@@ -113,7 +126,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
scheduled_date = anchor + timedelta(days=offset_days)
|
||||
if today < scheduled_date:
|
||||
continue
|
||||
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
|
||||
# ERP 合格付款按金额匹配四个阶段;同金额时按预付款、出货款、验收款、质保款的顺序占用。
|
||||
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
|
||||
if erp_paid:
|
||||
resolved += _resolve_pending_alerts(node_id=node.id)
|
||||
@@ -160,10 +173,10 @@ def _resolve_pending_alerts(*, node_id: int, reason: str = "erp_paid") -> int:
|
||||
|
||||
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
||||
"""
|
||||
把一个未付的预付款或出货款手动标为已付。
|
||||
把一个未付阶段手动标为已付。
|
||||
|
||||
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
验收款、质保款和已经付款的阶段不能标记。
|
||||
核心逻辑:预付款、出货款、验收款、质保款都可以标记。只改这一阶段,写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
金额和比例都为 0、已经付款、或不是进行中的阶段不能标记。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
@@ -186,8 +199,10 @@ def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, ope
|
||||
node = db.session.get(ContractPaymentNode, node_id)
|
||||
if node is None or node.contract_id != contract.id:
|
||||
raise NotFoundError("付款节点不存在")
|
||||
if node.node_type not in {"prepayment", "shipment"}:
|
||||
raise ValidationError("只有预付款和出货款可以手动标为已付")
|
||||
if node.node_type not in _ERP_PAID_STAGE_TYPES:
|
||||
raise ValidationError("该阶段不能标为已付")
|
||||
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||
raise ValidationError("该阶段没有应付金额,不能标为已付")
|
||||
if node.status == "paid":
|
||||
raise ValidationError("该阶段已是已付")
|
||||
if node.status != "active":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/erp_payment_service.py
|
||||
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款、出货款、验收款和质保款的付款完成事实来源。
|
||||
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
||||
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
"""
|
||||
@@ -17,7 +17,7 @@ from typing import Iterable
|
||||
from flask import current_app
|
||||
|
||||
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2, "acceptance": 3, "warranty": 4}
|
||||
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
||||
_SCHEMA_BY_COMPANY = {
|
||||
"无锡和宏智散热科技有限公司": "WZHHZ",
|
||||
@@ -100,7 +100,7 @@ def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[s
|
||||
"""
|
||||
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
||||
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款、出货款、验收款、质保款是否已经完成付款。
|
||||
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
||||
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
||||
某一账套查询失败只影响该账套,其它账套继续。
|
||||
@@ -234,14 +234,13 @@ def resolve_paid_node_dates(
|
||||
paid_rows: Iterable[ErpPaidRow],
|
||||
) -> dict[int, str | None]:
|
||||
"""
|
||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
|
||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款、验收款、质保款节点,并返回节点 ID 到付款日期的映射。
|
||||
|
||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
|
||||
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
|
||||
则把两者同时标记为已付款,并携带该笔付款日期。
|
||||
金额相同则按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||
若干阶段金额之和与该笔付款一致,则把这些阶段同时标记为已付款,并携带该笔付款日期。
|
||||
Args:
|
||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||
paid_rows: 该采购单的合格 ERP 付款记录。
|
||||
Returns:
|
||||
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
||||
@@ -268,14 +267,13 @@ def resolve_paid_node_ids(
|
||||
paid_amounts: Iterable[Decimal],
|
||||
) -> set[int]:
|
||||
"""
|
||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
|
||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款、验收款、质保款节点。
|
||||
|
||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
|
||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
|
||||
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
|
||||
(预付款、出货款在同一笔请款中一并请款的场景)。
|
||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;
|
||||
若单节点无匹配但若干阶段金额之和与该笔付款一致,则一并标记这些阶段为已付款。
|
||||
Args:
|
||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
||||
Returns:
|
||||
已付款节点 ID 集合。
|
||||
|
||||
@@ -4,11 +4,13 @@ backend/app/services/contract_payment/ledger_focus.py
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
金额和比例都为 0 的阶段不参与逾期、即将到期和本月应付。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -58,6 +60,37 @@ def node_due_reference(due_date: date | None, anchor_date: date | None) -> date
|
||||
return due_date or anchor_date
|
||||
|
||||
|
||||
def stage_has_nothing_to_pay(*, status: str | None, percentage: object, amount: object) -> bool:
|
||||
"""
|
||||
判断付款阶段是否没有应付金额。
|
||||
|
||||
核心逻辑:无此阶段,或比例与金额都是 0(空值按 0)。已付阶段不按 0 处理。
|
||||
与前台 isNothingToPay 一致,避免 0 元验收款、质保款把合同标成已逾期。
|
||||
Args:
|
||||
status: 节点状态。
|
||||
percentage: 付款比例,可为 Decimal、数字或字符串。
|
||||
amount: 应付金额,空值视为 0。
|
||||
Returns:
|
||||
无需付款时为 True。
|
||||
"""
|
||||
normalized = str(status or "").strip().lower()
|
||||
if normalized == "not_applicable":
|
||||
return True
|
||||
if normalized == "paid":
|
||||
return False
|
||||
return _is_zero(percentage) and _is_zero(amount)
|
||||
|
||||
|
||||
def _is_zero(value: object) -> bool:
|
||||
"""空值和 0 都视为没有金额或比例;无法解析的值不当成 0。"""
|
||||
if value is None or value == "":
|
||||
return True
|
||||
try:
|
||||
return Decimal(str(value)) == 0
|
||||
except (InvalidOperation, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def classify_ledger_status(
|
||||
*,
|
||||
contract_status: str | None,
|
||||
@@ -69,11 +102,11 @@ def classify_ledger_status(
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
金额和比例都为 0 的阶段不参与判断。其余进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
parse_status: 解析状态。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at / percentage / amount。
|
||||
today: 业务日。
|
||||
Returns:
|
||||
overdue / due / active / completed / needs_completion。
|
||||
@@ -83,7 +116,14 @@ def classify_ledger_status(
|
||||
return "needs_completion"
|
||||
if not node_list:
|
||||
return "needs_completion"
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
active = [
|
||||
node for node in node_list
|
||||
if str(node.get("status") or "").strip().lower() == "active" and not stage_has_nothing_to_pay(
|
||||
status=node.get("status"),
|
||||
percentage=node.get("percentage"),
|
||||
amount=node.get("amount"),
|
||||
)
|
||||
]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
@@ -106,7 +146,7 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
||||
"""
|
||||
合同是否有未付节点的到期日落在本自然月。
|
||||
|
||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
核心逻辑:只看 status=active 且仍有应付金额的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
Args:
|
||||
nodes: 轻量节点 dict。
|
||||
today: 业务日,用于确定自然月。
|
||||
@@ -118,6 +158,8 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
||||
for node in nodes:
|
||||
if str(node.get("status") or "").strip().lower() != "active":
|
||||
continue
|
||||
if stage_has_nothing_to_pay(status=node.get("status"), percentage=node.get("percentage"), amount=node.get("amount")):
|
||||
continue
|
||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||
if ref and month_start <= ref < month_end:
|
||||
return True
|
||||
@@ -131,6 +173,8 @@ def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
||||
"due_date": node.due_date,
|
||||
"anchor_date": node.anchor_date,
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
"percentage": node.percentage,
|
||||
"amount": node.amount,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -136,6 +136,47 @@ def resolve_account(
|
||||
)
|
||||
|
||||
|
||||
def resolve_direct_wecom(
|
||||
*,
|
||||
slot: str,
|
||||
label: str,
|
||||
name: str | None,
|
||||
wecom_userid: str | None,
|
||||
user: Any = None,
|
||||
oa_employee_id: int | None = None,
|
||||
missing_error: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把已经是企业微信 userid 的人员收成收件人。
|
||||
|
||||
核心逻辑:E8 矩阵的 zz、jfl 本身就是企微 userid,不再用工号对用户。
|
||||
系统里能对上这个 userid 时带上用户主键。对不上仍按该 userid 发送。
|
||||
Args:
|
||||
slot: to 或 cc。
|
||||
label: 直接主管或经副理。
|
||||
name: 展示姓名。
|
||||
wecom_userid: 企业微信 userid。
|
||||
user: 已按 wecom_userid 找到的系统用户。可空。
|
||||
oa_employee_id: HrmResource.id。
|
||||
missing_error: 没有 userid 时的失败原因。
|
||||
Returns:
|
||||
一名收件人。
|
||||
"""
|
||||
wecom = str(wecom_userid or "").strip()
|
||||
if not wecom:
|
||||
return make_person(slot=slot, label=label, name=name, oa_employee_id=oa_employee_id, error=missing_error)
|
||||
display = _user_name(user) or name
|
||||
bound = str(getattr(user, "wecom_userid", None) or "").strip() if user is not None else ""
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=display,
|
||||
user_id=getattr(user, "id", None) if user is not None else None,
|
||||
wecom_userid=bound or wecom,
|
||||
oa_employee_id=oa_employee_id,
|
||||
)
|
||||
|
||||
|
||||
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
||||
"""
|
||||
把预警配置里的固定岗位收成收件人。
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/equipment_acceptance/alert_service.py
|
||||
|
||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
依赖:同步服务、E10 人员目录、E8 人员矩阵、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10 和 E8,再按停留天数跨档。第 1 档主送使用部门担当,不按当前未办人。
|
||||
第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||
"""
|
||||
|
||||
@@ -35,6 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
|
||||
make_person,
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
resolve_direct_wecom,
|
||||
)
|
||||
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
|
||||
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||
@@ -47,9 +49,9 @@ _UNSENT = ("pending", "failed")
|
||||
|
||||
def generate_alerts() -> dict[str, Any]:
|
||||
"""
|
||||
同步 E10 后生成或更新待发送记录。
|
||||
同步两个来源后生成或更新待发送记录。
|
||||
|
||||
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
|
||||
核心逻辑:先拉最新快照,再按使用部门担当解析收件人。本函数不发企业微信。
|
||||
Returns:
|
||||
sync 摘要,以及 created、updated、cancelled 条数。
|
||||
"""
|
||||
@@ -78,9 +80,9 @@ def refresh_pending_alerts(
|
||||
created、updated、cancelled。
|
||||
"""
|
||||
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||
operators = _operators_by_order([order.id for order in orders])
|
||||
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||
e10_people, e10_deputies, e8_people, e8_matrix, e8_ok = _directories(orders, directory)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, e10_people, e10_deputies, e8_people))
|
||||
users_by_wecom = _users_by_wecom(_wecom_ids(e8_matrix))
|
||||
roles = _configured_users()
|
||||
thresholds = reminder_days()
|
||||
max_tier = 4 if is_round_4_enabled() else 3
|
||||
@@ -96,12 +98,16 @@ def refresh_pending_alerts(
|
||||
if order.monitor_status != WATCHING:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
continue
|
||||
if (order.oa_system or "e10") == "e8" and not e8_ok:
|
||||
continue
|
||||
for draft in _drafts(
|
||||
order,
|
||||
operators.get(order.id, []),
|
||||
people,
|
||||
deputies,
|
||||
e10_people,
|
||||
e10_deputies,
|
||||
e8_people,
|
||||
e8_matrix,
|
||||
users_by_job,
|
||||
users_by_wecom,
|
||||
roles,
|
||||
thresholds,
|
||||
max_tier=max_tier,
|
||||
@@ -282,82 +288,31 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
|
||||
def _drafts(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
operators: list[EquipmentAcceptanceOperator],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
e8_matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
roles: dict[str, User | None],
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
"""按使用部门担当展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
||||
if not due:
|
||||
return []
|
||||
handlers: list[dict[str, Any]] = []
|
||||
supervisors: list[dict[str, Any]] = []
|
||||
deputy_people: list[dict[str, Any]] = []
|
||||
if not operators:
|
||||
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
|
||||
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
|
||||
for operator in operators:
|
||||
fact = people.get(operator.user_id) or {}
|
||||
name = fact.get("name") or operator.handler_name
|
||||
job_num = fact.get("job_num") or operator.handler_job_num
|
||||
shown = name or "处理人"
|
||||
handlers.append(resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=operator.user_id,
|
||||
))
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
|
||||
else:
|
||||
supervisors.append(resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
))
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
|
||||
else:
|
||||
for item in found:
|
||||
deputy_people.append(resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
))
|
||||
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
applicant = resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(applicant_fact or {}).get("name") or order.applicant_name,
|
||||
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
|
||||
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
owner, supervisors, deputy_people = _owner_seats(
|
||||
order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom
|
||||
)
|
||||
applicant = _applicant(order, e10_people if (order.oa_system or "e10") != "e8" else e8_people, users_by_job)
|
||||
drafts: list[dict[str, Any]] = []
|
||||
if 1 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=1,
|
||||
threshold_days=thresholds[0],
|
||||
to_people=handlers,
|
||||
to_people=[owner],
|
||||
cc_people=[*supervisors, applicant],
|
||||
))
|
||||
if 2 in due:
|
||||
@@ -390,6 +345,159 @@ def _drafts(
|
||||
return drafts
|
||||
|
||||
|
||||
def _owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
e8_matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""第 1 档主送和其上级。E8 的上级来自部门矩阵,E10 来自 employee 和审批矩阵。"""
|
||||
if (order.oa_system or "e10") == "e8":
|
||||
return _e8_owner_seats(order, e8_people, e8_matrix, users_by_job, users_by_wecom)
|
||||
return _e10_owner_seats(order, e10_people, e10_deputies, users_by_job)
|
||||
|
||||
|
||||
def _e10_owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
users_by_job: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""E10 只取 sybmdd 这一名使用部门担当,不展开当前节点上的其他人。"""
|
||||
if not order.owner_oa_id:
|
||||
return (
|
||||
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||
)
|
||||
fact = people.get(order.owner_oa_id) or {}
|
||||
name = fact.get("name") or order.owner_name
|
||||
job_num = fact.get("job_num") or order.owner_job_num
|
||||
shown = name or "使用部门担当"
|
||||
owner = resolve_account(
|
||||
slot="to",
|
||||
label="使用部门担当",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=order.owner_oa_id,
|
||||
)
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors = [make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管")]
|
||||
else:
|
||||
supervisors = [resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
)]
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people = [make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理")]
|
||||
else:
|
||||
deputy_people = [
|
||||
resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
)
|
||||
for item in found
|
||||
]
|
||||
return owner, supervisors, deputy_people
|
||||
|
||||
|
||||
def _e8_owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""E8 的直接主管是矩阵 zz,经副理是 jfl。不是一行就不发这两个席位。"""
|
||||
if not order.owner_oa_id:
|
||||
return (
|
||||
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||
)
|
||||
fact = people.get(order.owner_oa_id) or {}
|
||||
name = fact.get("name") or order.owner_name
|
||||
job_num = fact.get("job_num") or order.owner_job_num
|
||||
shown = name or "使用部门担当"
|
||||
owner = resolve_account(
|
||||
slot="to",
|
||||
label="使用部门担当",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=order.owner_oa_id,
|
||||
)
|
||||
seat = matrix.get(str(fact.get("department_id") or ""))
|
||||
if not seat or not seat.get("ok"):
|
||||
return (
|
||||
owner,
|
||||
[make_person(slot="cc", label="直接主管", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||
[make_person(slot="to", label="经副理", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||
)
|
||||
return owner, [_matrix_seat(seat.get("zz"), "cc", "直接主管", shown, users_by_wecom)], [
|
||||
_matrix_seat(seat.get("jfl"), "to", "经副理", shown, users_by_wecom)
|
||||
]
|
||||
|
||||
|
||||
def _matrix_seat(
|
||||
seat: dict[str, Any] | None,
|
||||
slot: str,
|
||||
label: str,
|
||||
owner_name: str,
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> dict[str, Any]:
|
||||
"""矩阵人员按企微 userid 发送。空席位记失败。"""
|
||||
if not seat:
|
||||
return make_person(slot=slot, label=label, name=owner_name, error=f"{owner_name}没有{label}")
|
||||
wecom = str(seat.get("wecom_userid") or "")
|
||||
return resolve_direct_wecom(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=seat.get("name"),
|
||||
wecom_userid=wecom,
|
||||
user=users_by_wecom.get(wecom),
|
||||
oa_employee_id=seat.get("oa_id"),
|
||||
missing_error=f"{owner_name}没有{label}",
|
||||
)
|
||||
|
||||
|
||||
def _applicant(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
) -> dict[str, Any]:
|
||||
"""采购担当是申请人。E8 用工号 workcode,E10 用工号 JOB_NUM,都对系统用户。"""
|
||||
fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
job_num = (fact or {}).get("job_num") or order.applicant_job_num
|
||||
return resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(fact or {}).get("name") or order.applicant_name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
)
|
||||
|
||||
|
||||
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
||||
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
||||
row.acceptance_no = order.acceptance_no
|
||||
@@ -402,51 +510,103 @@ def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceO
|
||||
row.error_message = draft["error_message"]
|
||||
|
||||
|
||||
def _load_directory(
|
||||
def _directories(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None,
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]], dict[int, dict[str, Any]], dict[str, dict[str, Any]], bool]:
|
||||
"""分开取 E10 和 E8 的人员。E8 查询失败时本轮不改写 E8 待发送。"""
|
||||
if directory is not None:
|
||||
return directory[0], directory[1], {}, {}, True
|
||||
e10_people, e10_deputies = _load_e10_directory(orders)
|
||||
try:
|
||||
e8_people, e8_matrix = _load_e8_directory(orders)
|
||||
return e10_people, e10_deputies, e8_people, e8_matrix, True
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 directory skipped error=%s", type(exc).__name__)
|
||||
return e10_people, e10_deputies, {}, {}, False
|
||||
|
||||
|
||||
def _load_e10_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
||||
"""向 E10 要使用部门担当和申请人的主管、部门、经副理。不传入 E8 人员 ID。"""
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.user_id:
|
||||
ids.add(operator.user_id)
|
||||
for order in orders:
|
||||
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
||||
if (order.oa_system or "e10") == "e8" or order.monitor_status != WATCHING:
|
||||
continue
|
||||
if order.owner_oa_id:
|
||||
ids.add(order.owner_oa_id)
|
||||
if order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _load_e8_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""向 E8 要使用部门担当和申请人。人员 ID 只进 HrmResource。"""
|
||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for order in orders:
|
||||
if (order.oa_system or "e10") != "e8" or order.monitor_status != WATCHING:
|
||||
continue
|
||||
if order.owner_oa_id:
|
||||
ids.add(order.owner_oa_id)
|
||||
if order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_e8_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _job_numbers(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
) -> set[str]:
|
||||
"""收集要对系统用户的工号。"""
|
||||
"""收集要对系统用户的工号。E8 矩阵人员不走工号。"""
|
||||
found: set[str] = set()
|
||||
for order in orders:
|
||||
if order.owner_job_num:
|
||||
found.add(order.owner_job_num)
|
||||
if order.applicant_job_num:
|
||||
found.add(order.applicant_job_num)
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.handler_job_num:
|
||||
found.add(operator.handler_job_num)
|
||||
for fact in people.values():
|
||||
for fact in (*e10_people.values(), *e8_people.values()):
|
||||
if fact.get("job_num"):
|
||||
found.add(str(fact["job_num"]))
|
||||
if fact.get("superior_job_num"):
|
||||
found.add(str(fact["superior_job_num"]))
|
||||
for group in deputies.values():
|
||||
for group in e10_deputies.values():
|
||||
for item in group:
|
||||
if item.get("job_num"):
|
||||
found.add(str(item["job_num"]))
|
||||
return found
|
||||
|
||||
|
||||
def _wecom_ids(matrix: dict[str, dict[str, Any]]) -> set[str]:
|
||||
"""收集 E8 矩阵上的企业微信 userid,用来补系统用户主键。"""
|
||||
found: set[str] = set()
|
||||
for item in matrix.values():
|
||||
if not item.get("ok"):
|
||||
continue
|
||||
for key in ("zz", "jfl"):
|
||||
seat = item.get(key) or {}
|
||||
wecom = str(seat.get("wecom_userid") or "").strip()
|
||||
if wecom:
|
||||
found.add(wecom)
|
||||
return found
|
||||
|
||||
|
||||
def _users_by_wecom(wecom_ids: set[str]) -> dict[str, User]:
|
||||
"""按企业微信 userid 索引系统用户。"""
|
||||
if not wecom_ids:
|
||||
return {}
|
||||
rows = db.session.query(User).filter(User.wecom_userid.in_(wecom_ids)).all()
|
||||
return {str(row.wecom_userid): row for row in rows if row.wecom_userid}
|
||||
|
||||
|
||||
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
||||
"""用工号索引系统用户。"""
|
||||
if not job_nums:
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_group.py
|
||||
|
||||
用途:把 E8 验收单联表行收成与 E10 相同的快照草稿。
|
||||
依赖:e8_status、snapshot_rules、source_group。
|
||||
逻辑:同步服务在写库前调用。流程状态先翻译。人员 ID 仍是 E8 的 HrmResource.id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
as_datetime,
|
||||
as_int,
|
||||
can_accept_from_oa,
|
||||
is_returned_from_oa,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import (
|
||||
AcceptanceDraft,
|
||||
NodeDraft,
|
||||
OperatorDraft,
|
||||
)
|
||||
|
||||
_TERMINAL_FLOW = {3, 7}
|
||||
|
||||
|
||||
def group_e8_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
|
||||
"""
|
||||
按 requestid 合并 E8 联表行。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求的未办人收成一张单。
|
||||
计时起点读 syddjssj。可以验收读 sfkys。来源标记为 e8。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
(草稿列表, 因缺少 requestid 而跳过的行数)。
|
||||
"""
|
||||
skipped = 0
|
||||
buckets: dict[int, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
request_id = as_int(row.get("requestid"))
|
||||
if request_id is None:
|
||||
skipped += 1
|
||||
continue
|
||||
buckets.setdefault(request_id, []).append(row)
|
||||
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
|
||||
|
||||
|
||||
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
|
||||
"""同一流程的多行收成一条 E8 草稿。"""
|
||||
header = items[0]
|
||||
flow_status = e8_flow_status(header.get("currentnodetype"), header.get("currentstatus"))
|
||||
return AcceptanceDraft(
|
||||
oa_system="e8",
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
flow_no=_text(header.get("flow_no")),
|
||||
request_title=_text(header.get("request_title")),
|
||||
request_created_at=_e8_created_at(header),
|
||||
timer_started_at=as_datetime(header.get("syddjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
|
||||
flow_status_raw=flow_status,
|
||||
finished_at=_finished_at(header, flow_status),
|
||||
request_match_count=1,
|
||||
nodes=_nodes(items),
|
||||
operators=_operators(items),
|
||||
owner_oa_id=as_int(header.get("sybmdd")),
|
||||
owner_name=_text(header.get("owner_name")),
|
||||
owner_job_num=_text(header.get("owner_job_num")),
|
||||
equip_oa_id=None,
|
||||
equip_name=None,
|
||||
equip_job_num=None,
|
||||
applicant_oa_id=as_int(header.get("creater")),
|
||||
applicant_name=_text(header.get("applicant_name")),
|
||||
applicant_job_num=_text(header.get("applicant_job_num")),
|
||||
)
|
||||
|
||||
|
||||
def _e8_created_at(header: dict[str, Any]) -> datetime | None:
|
||||
"""
|
||||
拼出 E8 流程创建时间。
|
||||
|
||||
核心逻辑:createdate 是日期,createtime 是时分秒,两边分开存。
|
||||
只有日期时按当天 0 点。都空则没有创建时间。
|
||||
"""
|
||||
day = _text(header.get("createdate"))
|
||||
clock = _text(header.get("createtime"))
|
||||
if day is None:
|
||||
return None
|
||||
if clock is None:
|
||||
return as_datetime(day)
|
||||
return as_datetime(f"{day} {clock}")
|
||||
|
||||
|
||||
def _finished_at(header: dict[str, Any], flow_status: int | None) -> datetime | None:
|
||||
"""归档或撤销时,用最后操作时间作为结束时间。进行中不写。"""
|
||||
if flow_status not in _TERMINAL_FLOW:
|
||||
return None
|
||||
parsed = as_datetime(header.get("lastoperatedate"))
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
return None
|
||||
|
||||
|
||||
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
|
||||
"""当前节点只取 currentnodeid。没有节点 ID 时不造一行。"""
|
||||
found: dict[int, NodeDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("currentnodeid"))
|
||||
if node_id is None or node_id in found:
|
||||
continue
|
||||
found[node_id] = NodeDraft(
|
||||
node_id=node_id,
|
||||
node_name=_text(row.get("nodename")),
|
||||
node_type=None,
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
|
||||
"""当前未办人。查询已限定 isremark=0,这里只按人和节点去重。"""
|
||||
found: dict[tuple[int, int], OperatorDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("currentnodeid"))
|
||||
user_id = as_int(row.get("userid"))
|
||||
if node_id is None or user_id is None:
|
||||
continue
|
||||
key = (node_id, user_id)
|
||||
if key in found:
|
||||
continue
|
||||
found[key] = OperatorDraft(
|
||||
node_id=node_id,
|
||||
user_id=user_id,
|
||||
handler_name=_text(row.get("handler_name")),
|
||||
handler_job_num=_text(row.get("handler_job_num")),
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
"""去空白;空串视为没有值。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_query.py
|
||||
|
||||
用途:组装 E8 验收单只读 SQL。
|
||||
依赖:无。不连接数据库。
|
||||
逻辑:e8_repository 执行本文件的语句。表名固定,不拼接外部字符串。
|
||||
不复用合同付款只取归档日的查询。不取 currentnodetype=3 的归档单,空节点类型仍取。
|
||||
流程编号取 lcbh,标题取 requestname。创建时间取 createdate 加 createtime。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def build_e8_acceptance_sql() -> str:
|
||||
"""
|
||||
组装未归档的 E8 验收单查询。
|
||||
|
||||
核心逻辑:formtable_main_324.requestId 对 workflow_requestbase.requestid。
|
||||
当前节点用 currentnodeid,不用 lastnodeid。当前未办人是 isremark=0。
|
||||
currentnodetype=3 的归档单不取,空值仍取。申请人读 creater,不是 creator。
|
||||
流程编号读 lcbh,标题读 requestname。创建时间由 createdate 与 createtime 拼成。
|
||||
Returns:
|
||||
一条 SELECT。
|
||||
"""
|
||||
return """
|
||||
SELECT
|
||||
f.ysddh AS ysddh,
|
||||
f.cgdh AS cgdh,
|
||||
f.htbh AS htbh,
|
||||
f.lcbh AS flow_no,
|
||||
f.syddjssj AS syddjssj,
|
||||
f.sfzfth AS sfzfth,
|
||||
f.sfkys AS sfkys,
|
||||
f.ycsm AS ycsm,
|
||||
f.sybmdd AS sybmdd,
|
||||
w.requestid AS requestid,
|
||||
w.requestname AS request_title,
|
||||
w.createdate AS createdate,
|
||||
w.createtime AS createtime,
|
||||
LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) AS currentnodetype,
|
||||
w.currentstatus AS currentstatus,
|
||||
w.currentnodeid AS currentnodeid,
|
||||
w.creater AS creater,
|
||||
w.lastoperatedate AS lastoperatedate,
|
||||
w.lastoperatetime AS lastoperatetime,
|
||||
n.nodename AS nodename,
|
||||
op.userid AS userid,
|
||||
owner.lastname AS owner_name,
|
||||
owner.workcode AS owner_job_num,
|
||||
applicant.lastname AS applicant_name,
|
||||
applicant.workcode AS applicant_job_num,
|
||||
handler.lastname AS handler_name,
|
||||
handler.workcode AS handler_job_num
|
||||
FROM formtable_main_324 AS f
|
||||
INNER JOIN workflow_requestbase AS w
|
||||
ON w.requestid = f.requestId
|
||||
LEFT JOIN workflow_nodebase AS n
|
||||
ON n.id = w.currentnodeid
|
||||
LEFT JOIN workflow_currentoperator AS op
|
||||
ON op.requestid = w.requestid
|
||||
AND op.nodeid = w.currentnodeid
|
||||
AND LTRIM(RTRIM(CAST(op.isremark AS nvarchar(10)))) = N'0'
|
||||
LEFT JOIN HrmResource AS owner
|
||||
ON owner.id = f.sybmdd
|
||||
LEFT JOIN HrmResource AS applicant
|
||||
ON applicant.id = w.creater
|
||||
LEFT JOIN HrmResource AS handler
|
||||
ON handler.id = op.userid
|
||||
WHERE w.currentnodetype IS NULL
|
||||
OR LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) <> N'3'
|
||||
""".strip()
|
||||
@@ -0,0 +1,213 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_repository.py
|
||||
|
||||
用途:只读拉取 E8 验收单,以及使用部门担当的直接主管和经副理。
|
||||
依赖:OASQLServerService、e8_query。不连接 E10,不把人员 ID 送进 eteams。
|
||||
逻辑:验收单一次联表。收件人再按 HrmResource.id 查部门和 Matrixtable_3。
|
||||
zz、jfl 就是企业微信 userid。矩阵不是一行时该部门失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
||||
from app.services.equipment_acceptance.snapshot_rules import as_int
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def fetch_e8_acceptance_rows() -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 E8 拉验收单联表结果。
|
||||
|
||||
核心逻辑:复用 OA_SQLSERVER_* 只读连接。失败不改走 E10。
|
||||
Returns:
|
||||
字段名为小写别名的字典行。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
connection = _open()
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(build_e8_acceptance_sql())
|
||||
columns = [str(col[0]).lower() for col in cursor.description]
|
||||
return [
|
||||
{columns[index]: raw[index] for index in range(len(columns))}
|
||||
for raw in cursor.fetchall()
|
||||
]
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 sql failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E8 设备验收数据失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def fetch_e8_alert_directory(
|
||||
person_ids: list[int],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""
|
||||
按使用部门担当和申请人的 HrmResource.id 取工号,并按部门取直接主管、经副理。
|
||||
|
||||
核心逻辑:工号是 workcode。Matrixtable_3.bm 必须只命中一行,zz 是直接主管,jfl 是经副理。
|
||||
这两个 ID 同时是企业微信 userid。没有人员时不连库。
|
||||
Args:
|
||||
person_ids: HrmResource.id。禁止传入 E10 的 employee.ID。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到矩阵结果)。矩阵结果含 ok、zz、jfl。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
ids = sorted({int(item) for item in person_ids if item is not None})
|
||||
if not ids:
|
||||
return {}, {}
|
||||
connection = _open()
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
people = _load_people(cursor, ids)
|
||||
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
|
||||
matrix = _load_matrix(cursor, departments)
|
||||
_fill_matrix_names(cursor, matrix)
|
||||
return people, matrix
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 directory failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E8 直接主管和经副理失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _open():
|
||||
"""打开 E8 ecology 连接。异常收成业务错误,不把连接串写进日志。"""
|
||||
try:
|
||||
return OASQLServerService._connect()
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 connect failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"连接 E8 SQL Server 失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
|
||||
|
||||
def _load_people(cursor: Any, person_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
"""取出姓名、工号和部门。"""
|
||||
found: dict[int, dict[str, Any]] = {}
|
||||
for chunk in _chunks(person_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT id, lastname, workcode, departmentid
|
||||
FROM HrmResource
|
||||
WHERE id IN ({marks})
|
||||
""",
|
||||
chunk,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
person_id = as_int(raw[0])
|
||||
if person_id is None:
|
||||
continue
|
||||
found[person_id] = {
|
||||
"oa_id": person_id,
|
||||
"name": _clean(raw[1]),
|
||||
"job_num": _clean(raw[2]),
|
||||
"department_id": _clean(raw[3]),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _load_matrix(cursor: Any, department_ids: list[str]) -> dict[str, dict[str, Any]]:
|
||||
"""按部门取矩阵。不是正好一行就记失败,不挑其中一行。"""
|
||||
grouped: dict[str, list[tuple[Any, Any]]] = {}
|
||||
if not department_ids:
|
||||
return {}
|
||||
for chunk in _chunks(department_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
params = [int(item) if str(item).isdigit() else item for item in chunk]
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT bm, zz, jfl
|
||||
FROM Matrixtable_3
|
||||
WHERE bm IN ({marks})
|
||||
""",
|
||||
params,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
department_id = _clean(raw[0])
|
||||
if not department_id:
|
||||
continue
|
||||
grouped.setdefault(department_id, []).append((raw[1], raw[2]))
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
for department_id, rows in grouped.items():
|
||||
if len(rows) != 1:
|
||||
found[department_id] = {"ok": False, "zz": None, "jfl": None}
|
||||
continue
|
||||
zz_id = as_int(rows[0][0])
|
||||
jfl_id = as_int(rows[0][1])
|
||||
found[department_id] = {
|
||||
"ok": True,
|
||||
"zz": _seat(zz_id),
|
||||
"jfl": _seat(jfl_id),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _fill_matrix_names(cursor: Any, matrix: dict[str, dict[str, Any]]) -> None:
|
||||
"""给直接主管和经副理补姓名。查不到姓名仍保留企微 userid。"""
|
||||
ids = sorted({
|
||||
seat["oa_id"]
|
||||
for item in matrix.values()
|
||||
if item.get("ok")
|
||||
for seat in (item.get("zz"), item.get("jfl"))
|
||||
if seat and seat.get("oa_id") is not None
|
||||
})
|
||||
if not ids:
|
||||
return
|
||||
names = _load_people(cursor, ids)
|
||||
for item in matrix.values():
|
||||
if not item.get("ok"):
|
||||
continue
|
||||
for key in ("zz", "jfl"):
|
||||
seat = item.get(key)
|
||||
if not seat:
|
||||
continue
|
||||
fact = names.get(seat["oa_id"]) or {}
|
||||
if fact.get("name"):
|
||||
seat["name"] = fact["name"]
|
||||
|
||||
|
||||
def _seat(person_id: int | None) -> dict[str, Any] | None:
|
||||
"""矩阵里的人员 ID 直接作为企业微信 userid。"""
|
||||
if person_id is None:
|
||||
return None
|
||||
return {
|
||||
"oa_id": person_id,
|
||||
"name": None,
|
||||
"wecom_userid": str(person_id),
|
||||
}
|
||||
|
||||
|
||||
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
|
||||
"""把 IN 列表拆开。"""
|
||||
return [values[index:index + size] for index in range(0, len(values), size)]
|
||||
|
||||
|
||||
def _clean(value: Any) -> str | None:
|
||||
"""去掉空白。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_status.py
|
||||
|
||||
用途:把 E8 流程状态收成与 E10 相同的 flow_status_raw。
|
||||
依赖:无。不读数据库。
|
||||
逻辑:同步分组在落库前调用。currentstatus 优先于 currentnodetype。
|
||||
E8 没有作废和强制结束,不写成 5 或 4。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# 与 E10 的审批中、归档、撤销对齐。暂停按 E10 的 flowstatus=7,同样停表。
|
||||
_APPROVING = 1
|
||||
_ARCHIVED = 3
|
||||
_REVOKED = 7
|
||||
_APPROVING_NODE_TYPES = {"0", "1", "2"}
|
||||
_PAUSE_OR_REVOKE = {0, 1}
|
||||
|
||||
|
||||
def e8_flow_status(currentnodetype: Any, currentstatus: Any) -> int | None:
|
||||
"""
|
||||
把 E8 的节点类型和暂停/撤销收成本地流程状态。
|
||||
|
||||
核心逻辑:currentstatus 为空才看 currentnodetype。0 暂停、1 撤销都写成 7。
|
||||
空、0、1 以外不写成审批中,返回空,调用方不把这张单放进进行中。
|
||||
Args:
|
||||
currentnodetype: workflow_requestbase.currentnodetype。0/1/2 审批中,3 归档。
|
||||
currentstatus: workflow_requestbase.currentstatus。空是正常,0 暂停,1 撤销。
|
||||
Returns:
|
||||
1、3 或 7。无法识别时为 None。
|
||||
"""
|
||||
status = _blank_to_none(currentstatus)
|
||||
if status is not None:
|
||||
code = _as_int(status)
|
||||
if code in _PAUSE_OR_REVOKE:
|
||||
return _REVOKED
|
||||
return None
|
||||
node_type = _blank_to_none(currentnodetype)
|
||||
if node_type in _APPROVING_NODE_TYPES:
|
||||
return _APPROVING
|
||||
if node_type == "3":
|
||||
return _ARCHIVED
|
||||
return None
|
||||
|
||||
|
||||
def _blank_to_none(value: Any) -> str | None:
|
||||
"""空白当成没有值。数字也收成去掉空白的文本。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _as_int(value: str) -> int | None:
|
||||
"""整数字符串收成 int。带小数或字母的不猜。"""
|
||||
try:
|
||||
if "." in value:
|
||||
return None
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -126,12 +126,12 @@ def _open_connection(settings: EquipmentAcceptanceSqlSettings):
|
||||
|
||||
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""
|
||||
读取处理人的直接主管,并按部门查出经副理。
|
||||
读取使用部门担当的直接主管,并按部门查出经副理。
|
||||
|
||||
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
||||
人员 ID 必须是整数。没有人员时不连库。
|
||||
人员 ID 必须是 E10 的 employee.ID。没有人员时不连库。
|
||||
Args:
|
||||
employee_ids: 当前处理人和申请人的 employee.ID。
|
||||
employee_ids: 使用部门担当和申请人的 employee.ID。禁止传入 E8 的 HrmResource.id。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/app/services/equipment_acceptance/query_sql.py
|
||||
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
||||
依赖:无 Flask。库名只允许字母、数字和下划线。
|
||||
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
||||
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
不取 flowstatus=3 的归档单。flowstatus 为空仍取。
|
||||
流程编号读 requestmark,标题读 requestname,创建时间读 createdatetime。不读第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -68,8 +69,8 @@ def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
|
||||
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
||||
|
||||
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
||||
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。
|
||||
流程编号取 requestmark,标题取 requestname,创建时间取 createdatetime。不查询第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。归档(flowstatus=3)不取,空状态仍取。
|
||||
Args:
|
||||
catalogs: 已解析的库名。
|
||||
Returns:
|
||||
@@ -104,6 +105,9 @@ SELECT
|
||||
applicant.USERNAME AS applicant_name,
|
||||
applicant.JOB_NUM AS applicant_job_num,
|
||||
r.requestid,
|
||||
r.requestmark AS flow_no,
|
||||
r.requestname AS request_title,
|
||||
r.createdatetime,
|
||||
r.flowstatus,
|
||||
r.finishdatetime,
|
||||
c.nodeid,
|
||||
@@ -135,6 +139,7 @@ LEFT JOIN {operate} AS op
|
||||
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
||||
WHERE ISNULL(f.delete_type, 0) = 0
|
||||
AND r.requestid IS NOT NULL
|
||||
AND (r.flowstatus IS NULL OR r.flowstatus <> 3)
|
||||
""".strip()
|
||||
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ def classify_monitor_status(
|
||||
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
||||
|
||||
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
||||
审批中、可以验收、未退回、已有计时起点才是计时中。
|
||||
审批中、未退回、已有计时起点,且可以验收不是明确为否时计时。空和是都监控。
|
||||
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
||||
Args:
|
||||
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
||||
@@ -204,8 +204,8 @@ def classify_monitor_status(
|
||||
return STOPPED_REVOKED
|
||||
if not timer_started:
|
||||
return NOT_STARTED
|
||||
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
||||
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
# [STEP 2] 可以验收只有明确为否才停表,空和是都继续计时。0、1、空以外不猜。
|
||||
if can_accept in (1, None) and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
return WATCHING
|
||||
return EXCLUDED
|
||||
|
||||
|
||||
@@ -42,12 +42,16 @@ class NodeDraft:
|
||||
|
||||
@dataclass
|
||||
class AcceptanceDraft:
|
||||
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
|
||||
"""一张验收单在一次同步中的快照草稿。含流程编号、标题和创建时间。不含第二合同编号和验收日期。"""
|
||||
|
||||
oa_system: str
|
||||
request_id: int
|
||||
acceptance_no: str | None
|
||||
purchase_order_no: str | None
|
||||
contract_no: str | None
|
||||
flow_no: str | None
|
||||
request_title: str | None
|
||||
request_created_at: datetime | None
|
||||
timer_started_at: datetime | None
|
||||
can_accept: int | None
|
||||
cannot_accept_note: str | None
|
||||
@@ -73,7 +77,7 @@ def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDr
|
||||
按流程实例 requestid 合并联表结果。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||
不读取流程编号、第二合同编号和验收日期。
|
||||
流程编号和标题随行写入。不读取第二合同编号和验收日期。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
@@ -94,10 +98,14 @@ def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> Acceptance
|
||||
"""同一流程实例的多行收成一条草稿。"""
|
||||
header = items[0]
|
||||
return AcceptanceDraft(
|
||||
oa_system="e10",
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
flow_no=_text(header.get("flow_no")),
|
||||
request_title=_text(header.get("request_title")),
|
||||
request_created_at=as_datetime(header.get("createdatetime")),
|
||||
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/sync_service.py
|
||||
|
||||
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
|
||||
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
|
||||
停表时取消该单未发送的预警。操作人不保存 isremark。
|
||||
用途:把 E10 和 E8 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、sqlalchemy.or_、equipment_acceptance 模型、snapshot_rules、source_group、e8_group、oa_repository、e8_repository。
|
||||
逻辑:两个来源分开拉取。一边失败不改另一边的快照,也不把失败来源标成消失。
|
||||
只保留未归档单据。归档单不写入;该来源本次结果里没有的本地单删除,并取消未发送预警。
|
||||
主表按 oa_system + request_id 更新,并写入流程编号和标题。子表整批替换。停表时取消未发送预警。
|
||||
列表查询由 api/equipment_acceptance 调用。单号关键字同时匹配流程编号、验收单号和采购单号,再与申请人取交集。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
@@ -25,12 +30,15 @@ from app.models.equipment_acceptance import (
|
||||
from app.services.equipment_acceptance.config_service import first_reminder_day
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
MONITOR_STATUSES,
|
||||
STOPPED_ARCHIVED,
|
||||
classify_monitor_status,
|
||||
dwell_days,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
_ARCHIVED_FLOW = 3
|
||||
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
||||
_STOPPED_STATUSES = (
|
||||
"stopped_returned",
|
||||
@@ -42,34 +50,107 @@ _STOPPED_STATUSES = (
|
||||
)
|
||||
|
||||
|
||||
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
def sync_acceptance_snapshots(
|
||||
rows: list[dict[str, Any]] | None = None,
|
||||
*,
|
||||
e8_rows: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
同步验收单快照。
|
||||
同步 E10 和 E8 验收单快照。
|
||||
|
||||
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
||||
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
||||
核心逻辑:未传入行时分别读两个来源。一边查询失败只跳过这一边,不把已有快照标成消失。
|
||||
只保留未归档单据。该来源本次没返回的本地单删掉。只传入 rows 时只同步 E10,方便既有测试注入联表行。
|
||||
Args:
|
||||
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
||||
rows: 已取好的 E10 联表行。None 时访问 E10。
|
||||
e8_rows: 已取好的 E8 联表行。与 rows 同时为 None 时才访问 E8。
|
||||
Returns:
|
||||
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
||||
两边合计的写入、跳过、消失和取消条数,以及 e10、e8 各自的结果。
|
||||
"""
|
||||
if rows is None:
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
rows = fetch_acceptance_rows()
|
||||
drafts, skipped = group_acceptance_rows(rows)
|
||||
fetch_live = rows is None and e8_rows is None
|
||||
e10_rows, e10_ok, e10_error = _source_rows("e10", rows, fetch_live)
|
||||
e8_input, e8_ok, e8_error = _source_rows("e8", e8_rows, fetch_live)
|
||||
as_of = datetime.now(_SHANGHAI).date()
|
||||
e10_result = _apply_source("e10", e10_rows, e10_ok, e10_error, as_of, group_acceptance_rows)
|
||||
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
||||
|
||||
e8_result = _apply_source("e8", e8_input, e8_ok, e8_error, as_of, group_e8_rows)
|
||||
db.session.commit()
|
||||
cancelled = e10_result["cancelled"] + e8_result["cancelled"]
|
||||
counts: Counter[str] = Counter(e10_result["by_status"])
|
||||
counts.update(e8_result["by_status"])
|
||||
return {
|
||||
"upserted": e10_result["upserted"] + e8_result["upserted"],
|
||||
"skipped_without_request_id": (
|
||||
e10_result["skipped_without_request_id"] + e8_result["skipped_without_request_id"]
|
||||
),
|
||||
"absent": e10_result["absent"] + e8_result["absent"],
|
||||
"cancelled": cancelled,
|
||||
"by_status": dict(counts),
|
||||
"e10": e10_result,
|
||||
"e8": e8_result,
|
||||
}
|
||||
|
||||
|
||||
def _source_rows(
|
||||
source: str,
|
||||
injected: list[dict[str, Any]] | None,
|
||||
fetch_live: bool,
|
||||
) -> tuple[list[dict[str, Any]] | None, bool, str | None]:
|
||||
"""取一个来源的行。注入的行视为成功。实时查询失败时不标消失。"""
|
||||
if injected is not None:
|
||||
return injected, True, None
|
||||
if not fetch_live:
|
||||
return None, False, None
|
||||
try:
|
||||
if source == "e10":
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
return fetch_acceptance_rows(), True, None
|
||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_acceptance_rows
|
||||
|
||||
return fetch_e8_acceptance_rows(), True, None
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance %s sync skipped error=%s", source, type(exc).__name__)
|
||||
return None, False, type(exc).__name__
|
||||
|
||||
|
||||
def _apply_source(
|
||||
source: str,
|
||||
rows: list[dict[str, Any]] | None,
|
||||
ok: bool,
|
||||
error: str | None,
|
||||
as_of,
|
||||
grouper,
|
||||
) -> dict[str, Any]:
|
||||
"""把一个来源的未归档草稿写入。该来源这次没返回的本地单删除。"""
|
||||
if not ok or rows is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"error": error,
|
||||
"upserted": 0,
|
||||
"skipped_without_request_id": 0,
|
||||
"absent": 0,
|
||||
"cancelled": 0,
|
||||
"by_status": {},
|
||||
}
|
||||
drafts, skipped = grouper(rows)
|
||||
counts: Counter[str] = Counter()
|
||||
request_ids: list[int] = []
|
||||
cancelled = 0
|
||||
for draft in drafts:
|
||||
# [STEP] 归档单不落本地。查询已排除;这里再挡一层,避免注入行把归档单写回来。
|
||||
if draft.flow_status_raw == _ARCHIVED_FLOW:
|
||||
continue
|
||||
draft.oa_system = source
|
||||
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
||||
request_ids.append(order.request_id)
|
||||
counts[order.monitor_status] += 1
|
||||
cancelled += cancelled_now
|
||||
absent = _mark_absent(request_ids)
|
||||
db.session.commit()
|
||||
absent, cancelled_missing = _drop_missing(request_ids, source)
|
||||
cancelled += cancelled_missing
|
||||
return {
|
||||
"ok": True,
|
||||
"error": None,
|
||||
"upserted": len(drafts),
|
||||
"skipped_without_request_id": skipped,
|
||||
"absent": absent,
|
||||
@@ -84,17 +165,23 @@ def list_acceptance_orders(
|
||||
focus: str | None,
|
||||
page: int,
|
||||
page_size: int,
|
||||
keyword: str | None = None,
|
||||
applicant: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出本地快照。
|
||||
|
||||
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
||||
核心逻辑:focus 按全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
keyword 在流程编号、验收单号、采购单号里任一包含即命中,再与申请人姓名取交集。
|
||||
已归档不列出。已逾期是计时中且签核天数超过第 1 档。
|
||||
汇总不看当前状态分组,但跟着单号关键字和申请人走,也不计归档。
|
||||
Args:
|
||||
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
||||
focus: watching、overdue、stopped、not_started 或空。
|
||||
page: 从 1 开始。
|
||||
page_size: 每页条数,上限 100。
|
||||
keyword: 流程编号、验收单号或采购单号的包含匹配。空白表示不筛。
|
||||
applicant: 申请人姓名的包含匹配。空白表示不筛。
|
||||
Returns:
|
||||
items、total、page、page_size、summary。
|
||||
|
||||
@@ -106,7 +193,11 @@ def list_acceptance_orders(
|
||||
reminder_day = first_reminder_day()
|
||||
page = max(1, page)
|
||||
page_size = min(100, max(1, page_size))
|
||||
query = db.session.query(EquipmentAcceptanceOrder)
|
||||
query = _apply_search(
|
||||
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||
keyword=keyword,
|
||||
applicant=applicant,
|
||||
)
|
||||
if ledger_focus:
|
||||
query = _apply_focus(query, ledger_focus, reminder_day)
|
||||
elif status:
|
||||
@@ -131,7 +222,7 @@ def list_acceptance_orders(
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"summary": _ledger_summary(reminder_day),
|
||||
"summary": _ledger_summary(reminder_day, keyword=keyword, applicant=applicant),
|
||||
}
|
||||
|
||||
|
||||
@@ -160,20 +251,25 @@ def get_acceptance_order(order_id: int) -> dict[str, Any]:
|
||||
|
||||
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
||||
"""
|
||||
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
|
||||
按来源和流程实例更新主表,并替换该单的节点和操作人。
|
||||
|
||||
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
||||
E10 与 E8 的 request_id 可以相同,必须连 oa_system 一起查。
|
||||
Returns:
|
||||
更新后的验收单,以及本次改成已取消的发送记录条数。
|
||||
"""
|
||||
order = (
|
||||
db.session.query(EquipmentAcceptanceOrder)
|
||||
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
||||
.filter(
|
||||
EquipmentAcceptanceOrder.oa_system == draft.oa_system,
|
||||
EquipmentAcceptanceOrder.request_id == draft.request_id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if order is None:
|
||||
order = EquipmentAcceptanceOrder(
|
||||
oa_system=draft.oa_system,
|
||||
request_id=draft.request_id,
|
||||
monitor_status="excluded",
|
||||
synced_at=now,
|
||||
@@ -185,6 +281,9 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
||||
order.acceptance_no = draft.acceptance_no
|
||||
order.purchase_order_no = draft.purchase_order_no
|
||||
order.contract_no = draft.contract_no
|
||||
order.flow_no = draft.flow_no
|
||||
order.request_title = draft.request_title
|
||||
order.request_created_at = draft.request_created_at
|
||||
order.timer_started_at = draft.timer_started_at
|
||||
order.can_accept = draft.can_accept
|
||||
order.cannot_accept_note = draft.cannot_accept_note
|
||||
@@ -254,12 +353,45 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
||||
return order, cancelled
|
||||
|
||||
|
||||
def _mark_absent(request_ids: list[int]) -> int:
|
||||
"""把这次没拉到的单据标成源里不存在。"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
|
||||
def _drop_missing(request_ids: list[int], oa_system: str) -> tuple[int, int]:
|
||||
"""
|
||||
删除这个来源里本次未归档结果没有的本地单。
|
||||
|
||||
核心逻辑:查询已不含归档。本地还在、结果里没有的单,视为已归档或已从 OA 消失。
|
||||
先取消未发送预警,再删主表。节点和操作人随外键级联删除。已发送记录保留,只解开验收单外键。
|
||||
不改另一个来源。查询失败的来源不会进到这里。
|
||||
Returns:
|
||||
删除张数,以及取消的未发送条数。
|
||||
"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.oa_system == oa_system)
|
||||
if request_ids:
|
||||
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
||||
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
||||
gone = query.all()
|
||||
if not gone:
|
||||
return 0, 0
|
||||
from app.services.equipment_acceptance.alert_service import cancel_unsent
|
||||
|
||||
cancelled = 0
|
||||
for order in gone:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
db.session.delete(order)
|
||||
return len(gone), cancelled
|
||||
|
||||
|
||||
def _without_archived(query):
|
||||
"""
|
||||
列表和汇总都不展示已归档。
|
||||
|
||||
核心逻辑:状态已是归档的不显示。流程原值已是 3 的也不显示,
|
||||
避免退回或无法验收优先落成别的状态后,归档单仍留在列表里。
|
||||
"""
|
||||
return query.filter(
|
||||
EquipmentAcceptanceOrder.monitor_status != STOPPED_ARCHIVED,
|
||||
or_(
|
||||
EquipmentAcceptanceOrder.flow_status_raw.is_(None),
|
||||
EquipmentAcceptanceOrder.flow_status_raw != _ARCHIVED_FLOW,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _clean_focus(focus: str | None) -> str | None:
|
||||
@@ -290,9 +422,65 @@ def _apply_focus(query, focus: str, reminder_day: int):
|
||||
)
|
||||
|
||||
|
||||
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
||||
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
||||
base = db.session.query(EquipmentAcceptanceOrder)
|
||||
def _clean_search(value: str | None) -> str | None:
|
||||
"""去掉首尾空白。空白视为不筛选。过长时只保留前 100 字,避免把整段说明送进 LIKE。"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
return text[:100]
|
||||
|
||||
|
||||
def _contains_pattern(text: str) -> str:
|
||||
"""
|
||||
把用户输入收成包含匹配,并把 LIKE 通配符当成普通字符。
|
||||
|
||||
核心逻辑:% 和 _ 要能搜出单号里的原字符,不能变成任意匹配。
|
||||
|
||||
Args:
|
||||
text: 已经去掉空白的搜索词。
|
||||
|
||||
Returns:
|
||||
带前后百分号、且转义过的模式。
|
||||
"""
|
||||
escaped = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
return f"%{escaped}%"
|
||||
|
||||
|
||||
def _apply_search(query, *, keyword: str | None, applicant: str | None):
|
||||
"""
|
||||
按单号关键字和申请人收窄查询。
|
||||
|
||||
核心逻辑:关键字在流程编号、验收单号、采购单号三者取并集;申请人再与这个结果取交集。
|
||||
比较不区分大小写。空值不加入条件。
|
||||
"""
|
||||
number = _clean_search(keyword)
|
||||
if number:
|
||||
pattern = _contains_pattern(number)
|
||||
query = query.filter(or_(
|
||||
EquipmentAcceptanceOrder.flow_no.ilike(pattern, escape="\\"),
|
||||
EquipmentAcceptanceOrder.acceptance_no.ilike(pattern, escape="\\"),
|
||||
EquipmentAcceptanceOrder.purchase_order_no.ilike(pattern, escape="\\"),
|
||||
))
|
||||
person = _clean_search(applicant)
|
||||
if person:
|
||||
query = query.filter(
|
||||
EquipmentAcceptanceOrder.applicant_name.ilike(_contains_pattern(person), escape="\\"),
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def _ledger_summary(
|
||||
reminder_day: int,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
applicant: str | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""统计未归档单据的进行中、已逾期、不再提醒、未开始。不看状态分组,但跟着单号和申请人走。"""
|
||||
base = _apply_search(
|
||||
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||
keyword=keyword,
|
||||
applicant=applicant,
|
||||
)
|
||||
return {
|
||||
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
||||
"overdue": base.filter(
|
||||
@@ -359,9 +547,13 @@ def _order_payload(
|
||||
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
||||
payload: dict[str, Any] = {
|
||||
"id": order.id,
|
||||
"oa_system": order.oa_system,
|
||||
"acceptance_no": order.acceptance_no,
|
||||
"purchase_order_no": order.purchase_order_no,
|
||||
"contract_no": order.contract_no,
|
||||
"flow_no": order.flow_no,
|
||||
"request_title": order.request_title,
|
||||
"request_created_at": utc_iso(order.request_created_at),
|
||||
"timer_started_at": utc_iso(order.timer_started_at),
|
||||
"dwell_days": order.dwell_days,
|
||||
"can_accept": order.can_accept,
|
||||
|
||||
@@ -4,6 +4,8 @@ backend/app/services/file_assets/storage.py
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
||||
读写删走 MINIO_ENDPOINT(容器内网)。浏览器预签走 MINIO_PUBLIC_BASE_URL,
|
||||
因为签名包含 Host,不能把 host.docker.internal 交给浏览器后再替换。
|
||||
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
||||
"""
|
||||
|
||||
@@ -13,6 +15,7 @@ import io
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import BinaryIO
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
@@ -24,16 +27,75 @@ _LOGGER = logging.getLogger(__name__)
|
||||
_cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
def resolve_presign_endpoint(
|
||||
public_base: str,
|
||||
fallback_endpoint: str,
|
||||
fallback_secure: bool,
|
||||
) -> tuple[str, bool]:
|
||||
"""把浏览器可访问的 MinIO 基址收成预签名客户端的 endpoint 与 secure。
|
||||
|
||||
核心逻辑:SigV4 把 Host 写进签名。正式环境容器用 host.docker.internal:9000
|
||||
读写,浏览器必须打开 MINIO_PUBLIC_BASE_URL(如 http://ai.well-trust.com:9000)。
|
||||
基址为空或解析不出主机时退回内网端点。80/443 省略端口,交给 Minio 客户端按协议补。
|
||||
|
||||
Args:
|
||||
public_base: MINIO_PUBLIC_BASE_URL,可带或不带协议。
|
||||
fallback_endpoint: 容器内访问用的 host:port。
|
||||
fallback_secure: 内网端点是否走 HTTPS。
|
||||
|
||||
Returns:
|
||||
(endpoint, secure)。endpoint 形如 ai.well-trust.com:9000。
|
||||
"""
|
||||
raw = (public_base or "").strip()
|
||||
if not raw:
|
||||
return fallback_endpoint, fallback_secure
|
||||
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
|
||||
host = parsed.hostname
|
||||
if not host:
|
||||
return fallback_endpoint, fallback_secure
|
||||
if ":" in host:
|
||||
host = f"[{host}]"
|
||||
secure = parsed.scheme.lower() == "https"
|
||||
port = parsed.port
|
||||
if port and not ((secure and port == 443) or (not secure and port == 80)):
|
||||
return f"{host}:{port}", secure
|
||||
return host, secure
|
||||
|
||||
|
||||
class FileAssetStorage:
|
||||
"""私有业务文件 MinIO 存储客户端。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""分别建立内网读写客户端与浏览器预签名客户端。
|
||||
|
||||
核心逻辑:两端点主机与协议相同时共用一个客户端。预签名客户端只在
|
||||
生成 URL 时做本地签名,不靠它访问内网 MinIO。
|
||||
"""
|
||||
endpoint = str(_cfg.MINIO_ENDPOINT or "").strip()
|
||||
access_key = _cfg.MINIO_ACCESS_KEY
|
||||
secret_key = _cfg.MINIO_SECRET_KEY
|
||||
secure = bool(_cfg.MINIO_SECURE)
|
||||
self.client = Minio(
|
||||
_cfg.MINIO_ENDPOINT,
|
||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
||||
secure=_cfg.MINIO_SECURE,
|
||||
endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=secure,
|
||||
)
|
||||
# [STEP 1] 预签名单独用浏览器主机。只改 URL 字符串会使签名失效。
|
||||
presign_endpoint, presign_secure = resolve_presign_endpoint(
|
||||
str(_cfg.MINIO_PUBLIC_BASE_URL or ""),
|
||||
endpoint,
|
||||
secure,
|
||||
)
|
||||
if presign_endpoint == endpoint and presign_secure == secure:
|
||||
self.presign_client = self.client
|
||||
else:
|
||||
self.presign_client = Minio(
|
||||
presign_endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=presign_secure,
|
||||
)
|
||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||
|
||||
def _ensure_bucket_exists(self) -> None:
|
||||
@@ -120,6 +182,19 @@ class FileAssetStorage:
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def _bind_presign_region(self) -> None:
|
||||
"""把内网客户端已探到的 region 抄给预签名客户端。
|
||||
|
||||
核心逻辑:minio-py 在签名前会请求 GetBucketLocation。若用公网客户端发这次请求,
|
||||
容器里可能访问不到浏览器入口,或每次下载多一次公网探测。
|
||||
bucket 检查已经通过内网客户端写入 _region_map;这里只复用该结果。
|
||||
尚未探测到时用 MinIO 默认 us-east-1。
|
||||
"""
|
||||
if self.presign_client is self.client:
|
||||
return
|
||||
region = self.client._region_map.get(self.bucket_name) or "us-east-1"
|
||||
self.presign_client._region_map[self.bucket_name] = region
|
||||
|
||||
def presigned_get_url(
|
||||
self,
|
||||
storage_key: str,
|
||||
@@ -129,7 +204,9 @@ class FileAssetStorage:
|
||||
) -> str:
|
||||
"""生成短期受控下载 URL。
|
||||
|
||||
核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
核心逻辑:先把内网探到的 region 绑到 presign_client,再用它签名。
|
||||
主机来自 MINIO_PUBLIC_BASE_URL。签名在本地完成,不再向公网探测 bucket 区域。
|
||||
对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
download_name 非空时把 response-content-disposition 签进 URL,
|
||||
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
||||
|
||||
@@ -139,16 +216,17 @@ class FileAssetStorage:
|
||||
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
||||
|
||||
Returns:
|
||||
带过期签名的 GET URL。
|
||||
带过期签名的 GET URL,主机是浏览器可访问的 MinIO 地址。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
self._bind_presign_region()
|
||||
response_headers = None
|
||||
if download_name:
|
||||
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
||||
response_headers = {
|
||||
'response-content-disposition': f'attachment; filename="{safe}"',
|
||||
}
|
||||
return self.client.presigned_get_object(
|
||||
return self.presign_client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
|
||||
@@ -3,8 +3,9 @@ services/freight_rpa/common/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
|
||||
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
|
||||
密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
|
||||
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
|
||||
ciphertext: 数据库中保存的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
str: 仅供 RPA 执行内存使用的明文。
|
||||
str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
|
||||
@@ -44,6 +44,7 @@ from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
@@ -659,6 +660,72 @@ def latest_usable_inbound_file(
|
||||
return _inbound_file_view(report)
|
||||
|
||||
|
||||
def latest_usable_inbound_files_by_source(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, InboundFileView]:
|
||||
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
|
||||
|
||||
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
|
||||
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
|
||||
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
|
||||
只留 created_at/id 最新一条。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.all()
|
||||
)
|
||||
picked: dict[str, InboundFileView] = {}
|
||||
for report in rows:
|
||||
view = _inbound_file_view(report)
|
||||
if view.source_code not in picked:
|
||||
picked[view.source_code] = view
|
||||
return picked
|
||||
|
||||
|
||||
def expired_inbound_source_codes(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> set[str]:
|
||||
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
|
||||
|
||||
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
|
||||
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
至少有一份失效未清理入站归档的 source_code 集合。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
.with_entities(FreightRpaInboundUnitRun.source_code)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]) for row in rows}
|
||||
|
||||
|
||||
def read_inbound_file_bytes(file_id: int) -> bytes:
|
||||
"""按 file_id 读取入站归档文件的对象字节。
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
services/freight_rpa/upload/crane_recheck.py
|
||||
|
||||
用途:Crane 发货单进入分配中之后的状态回查。
|
||||
依赖:ShippingUploadAttempt、freight_rpa.upload.trigger_io、page_contract。
|
||||
逻辑:自动上传只排一次 10 分钟后的回查;手动刷新另写一条 status_check trigger,
|
||||
不顺延、不取消那一次定时。两条回查都只让 Worker 重新登录并按 Pull Request # 看行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingExportArtifact, ShippingNotice, ShippingUploadAttempt
|
||||
from app.services.freight_rpa.upload.page_contract import crane_recheck_due_at
|
||||
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||
|
||||
CRANE_ALLOCATING_CODE = 'CRANE_ALLOCATING'
|
||||
|
||||
|
||||
def is_crane_allocating(attempt: ShippingUploadAttempt | None) -> bool:
|
||||
"""当前尝试是否停在 Crane 已接收、尚未分配完成。"""
|
||||
return (
|
||||
attempt is not None
|
||||
and attempt.status == 'running'
|
||||
and attempt.error_code == CRANE_ALLOCATING_CODE
|
||||
)
|
||||
|
||||
|
||||
def _evidence(attempt: ShippingUploadAttempt) -> dict[str, Any]:
|
||||
raw = attempt.success_evidence_json
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _recheck(evidence: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = evidence.get('crane_recheck')
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def remember_crane_allocating(
|
||||
attempt: ShippingUploadAttempt,
|
||||
artifact: ShippingExportArtifact,
|
||||
callback_id: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> ShippingUploadAttempt:
|
||||
"""把尝试标成分配中,并在首次进入时记下唯一一次定时回查。
|
||||
|
||||
核心逻辑:due_at 只在还没有时写入。后续回查回调仍是分配中时,不改到期时间,
|
||||
也不把定时标记成已触发。
|
||||
|
||||
Args:
|
||||
attempt: 本次上传尝试。
|
||||
artifact: 已提交的发货 Excel。
|
||||
callback_id: 本次回调幂等键。重复的同一个键直接返回。
|
||||
now: 测试注入的当前时间。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 仍为 running、错误码为 CRANE_ALLOCATING 的尝试。
|
||||
"""
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('last_callback_id') == callback_id or attempt.callback_id == callback_id:
|
||||
return attempt
|
||||
recheck = _recheck(evidence)
|
||||
if not recheck.get('due_at'):
|
||||
pull_request_no = str(artifact.file_name or '').rsplit('.', 1)[0] or str(artifact.file_name or '')
|
||||
recheck = {
|
||||
'due_at': crane_recheck_due_at(now).isoformat(timespec='seconds'),
|
||||
'fired': False,
|
||||
'pull_request_no': pull_request_no,
|
||||
}
|
||||
evidence['crane_recheck'] = recheck
|
||||
evidence['last_callback_id'] = callback_id
|
||||
evidence['manual_refresh_inflight'] = False
|
||||
attempt.success_evidence_json = evidence
|
||||
attempt.status = 'running'
|
||||
attempt.error_code = CRANE_ALLOCATING_CODE
|
||||
attempt.error_message = None
|
||||
attempt.finished_at = None
|
||||
if not attempt.callback_id:
|
||||
attempt.callback_id = callback_id
|
||||
artifact.status = 'uploading'
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
def _write_status_check(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
pull_request_no: str,
|
||||
kind: str,
|
||||
) -> str | None:
|
||||
"""写入一条只查状态的上传 trigger。文件复制失败时返回 None。"""
|
||||
# 定时回查的回调键固定,重复心跳不会写成两次有效回调。
|
||||
# 手动刷新每次使用新键,避免上一次「仍在分配」把这一次回调当成重复而跳过。
|
||||
callback_id = f'crane-recheck:{attempt.id}:scheduled'
|
||||
trigger_filename = f'upload_recheck_{task_no}_scheduled.json'
|
||||
if kind == 'manual':
|
||||
callback_id = f'crane-recheck:{attempt.id}:manual:{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
trigger_filename = f'upload_recheck_{task_no}_manual.json'
|
||||
_queue, trigger_path, _callback = write_upload_trigger(
|
||||
task_no,
|
||||
export_file_path,
|
||||
{'mode': 'status_check', 'recheck_kind': kind, 'pull_request_no': pull_request_no},
|
||||
attempt_id=int(attempt.id),
|
||||
artifact_id=int(attempt.artifact_id),
|
||||
connector_type='crane',
|
||||
upload_config={'enabled': True},
|
||||
login_url=str(upload_source.get('login_url') or '').strip() or None,
|
||||
credential_envelope=upload_source.get('credential_envelope') if isinstance(upload_source.get('credential_envelope'), dict) else None,
|
||||
callback_id=callback_id,
|
||||
business_no=pull_request_no,
|
||||
trigger_filename=trigger_filename,
|
||||
)
|
||||
return trigger_path
|
||||
|
||||
|
||||
def fire_scheduled_crane_recheck(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
now: datetime | None = None,
|
||||
) -> bool:
|
||||
"""到期后写入唯一一次定时回查。未到期、已触发或不是分配中时不写文件。
|
||||
|
||||
Returns:
|
||||
bool: 本次是否新写了 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
return False
|
||||
evidence = _evidence(attempt)
|
||||
recheck = _recheck(evidence)
|
||||
if recheck.get('fired') or not recheck.get('due_at'):
|
||||
return False
|
||||
due_at = datetime.fromisoformat(str(recheck['due_at']))
|
||||
if due_at > (now or datetime.utcnow()):
|
||||
return False
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='scheduled',
|
||||
)
|
||||
if not trigger_path:
|
||||
return False
|
||||
recheck['fired'] = True
|
||||
evidence['crane_recheck'] = recheck
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return True
|
||||
|
||||
|
||||
def request_manual_crane_refresh(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
) -> str:
|
||||
"""手动刷新:立刻写一条状态回查,不改定时回查的到期时间和已触发标记。
|
||||
|
||||
Raises:
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还没回调。
|
||||
ValidationError: 共享目录写不出 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
raise ConflictError(
|
||||
'Crane upload is not waiting for allocation',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('manual_refresh_inflight'):
|
||||
raise ConflictError(
|
||||
'A Crane status refresh is already queued',
|
||||
code='SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT',
|
||||
)
|
||||
recheck = _recheck(evidence)
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
due_at = recheck.get('due_at')
|
||||
fired = bool(recheck.get('fired'))
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='manual',
|
||||
)
|
||||
if not trigger_path:
|
||||
raise ValidationError(
|
||||
'Crane status refresh trigger directory is unavailable',
|
||||
code='SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE',
|
||||
)
|
||||
evidence['manual_refresh_inflight'] = True
|
||||
evidence['crane_recheck'] = {**recheck, 'due_at': due_at, 'fired': fired, 'pull_request_no': pull_request_no}
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return trigger_path
|
||||
|
||||
|
||||
def materialize_due_crane_rechecks(now: datetime | None = None) -> int:
|
||||
"""心跳时把已到期且尚未触发的 Crane 定时回查写成 trigger。
|
||||
|
||||
Returns:
|
||||
int: 新写入的 trigger 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
moment = now or datetime.utcnow()
|
||||
written = 0
|
||||
attempts = ShippingUploadAttempt.query.filter_by(status='running', error_code=CRANE_ALLOCATING_CODE).all()
|
||||
for attempt in attempts:
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
notice = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None
|
||||
if artifact is None or notice is None or not artifact.file_path:
|
||||
continue
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
|
||||
snapshot = task_rpa_inventory_source(notice) or {}
|
||||
source_code = str(snapshot.get('source_code') or '').strip()
|
||||
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
|
||||
if not isinstance(upload_source, dict) or str(upload_source.get('connector_type') or '').lower() != 'crane':
|
||||
continue
|
||||
if fire_scheduled_crane_recheck(
|
||||
attempt, upload_source, task_no=str(notice.task_no),
|
||||
export_file_path=str(artifact.file_path), now=moment,
|
||||
):
|
||||
written += 1
|
||||
if written:
|
||||
db.session.commit()
|
||||
return written
|
||||
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
services/freight_rpa/upload/page_contract.py
|
||||
|
||||
用途:货代发货 Excel 上传的平台页面契约。入口路径、文件控件和成功条件由代码固定。
|
||||
依赖:标准库 urllib。
|
||||
逻辑:系统连接只保存是否启用自动上传;Worker 用登录地址的主机拼出上传页。
|
||||
DBS 上传后当页即可判定;Crane 先进入分配中,10 分钟后再查一次。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
CRANE_RECHECK_DELAY = timedelta(minutes=10)
|
||||
DBS_UPLOAD_PATH = '/main/portal/frame/WMSUpload2'
|
||||
CRANE_UPLOAD_HASH = '/#/shipping-order-upload'
|
||||
|
||||
|
||||
def build_upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""按平台把登录地址的主机拼成上传页。
|
||||
|
||||
核心逻辑:页面路径属于连接器代码。管理端不再保存上传入口 URL。
|
||||
|
||||
Args:
|
||||
connector_type: dbs 或 crane。
|
||||
login_url: 系统连接上的 HTTPS 登录地址。
|
||||
|
||||
Returns:
|
||||
str: 该平台固定上传页。
|
||||
|
||||
Raises:
|
||||
ValueError: 连接类型或登录地址无法构成上传页。
|
||||
"""
|
||||
kind = str(connector_type or '').strip().lower()
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
host = parsed.netloc.strip()
|
||||
if parsed.scheme.lower() != 'https' or not host or not parsed.hostname:
|
||||
raise ValueError('login_url must be HTTPS with a host')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}{DBS_UPLOAD_PATH}'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}{CRANE_UPLOAD_HASH}'
|
||||
raise ValueError(f'unsupported connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def classify_crane_order_row(order_status: str, order_status_description: str) -> str:
|
||||
"""判断 Crane 发货单行处于分配中、已分配,还是都不是。
|
||||
|
||||
Args:
|
||||
order_status: Order Status 列文本。
|
||||
order_status_description: Order Status Description 列文本。
|
||||
|
||||
Returns:
|
||||
str: allocated、allocating 或 other。
|
||||
"""
|
||||
status = ' '.join(str(order_status or '').split()).lower()
|
||||
description = ' '.join(str(order_status_description or '').split()).lower()
|
||||
if status == 'processing' and description == 'shipping order allocated':
|
||||
return 'allocated'
|
||||
if status == 'processing' and description == 'allocating the shipping order':
|
||||
return 'allocating'
|
||||
return 'other'
|
||||
|
||||
|
||||
def crane_recheck_due_at(now: datetime | None = None) -> datetime:
|
||||
"""自动上传进入分配中之后,唯一一次定时回查的到期时间。"""
|
||||
return (now or datetime.utcnow()) + CRANE_RECHECK_DELAY
|
||||
@@ -76,6 +76,7 @@ def write_upload_trigger(
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
trigger_filename: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
@@ -84,7 +85,7 @@ def write_upload_trigger(
|
||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
|
||||
平台页面动作由 Worker 连接器代码固定;upload_config 只携带是否启用自动上传。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
@@ -100,6 +101,7 @@ def write_upload_trigger(
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
trigger_filename: 触发文件名。状态回查使用独立文件名,避免覆盖正在上传的 trigger。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
@@ -113,14 +115,21 @@ def write_upload_trigger(
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
status_check = str((payload or {}).get('mode') or '') == 'status_check'
|
||||
if not src.is_file() and not status_check:
|
||||
return None, None, None
|
||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||
emit_no = str(business_no or '').strip() or task_no
|
||||
suffix = str(src.suffix or '.xlsx').lower()
|
||||
dest = queue / f"{emit_no}{suffix}"
|
||||
shutil.copy2(src, dest)
|
||||
if src.is_file():
|
||||
shutil.copy2(src, dest)
|
||||
queued_file = str(dest)
|
||||
elif status_check:
|
||||
queued_file = ''
|
||||
else:
|
||||
return None, None, None
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
@@ -135,10 +144,10 @@ def write_upload_trigger(
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": str(dest),
|
||||
"file_path": queued_file,
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
trigger_path = trigger_dir / (trigger_filename or f"upload_{task_no}.json")
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
@@ -36,6 +36,7 @@ from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLed
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_record_ids_scope_union,
|
||||
pending_ledger_query,
|
||||
ledger_external_doc_no,
|
||||
transfer_type_code_of,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
@@ -100,6 +101,8 @@ class BacklogItemDTO:
|
||||
result_code: Optional[str] = None
|
||||
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -207,7 +210,7 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
|
||||
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
|
||||
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
|
||||
|
||||
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
|
||||
keyword 与前端池内筛选同字段集(单号/外部单号/料号/品名/来源,2026-10-16 随
|
||||
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
||||
|
||||
Args:
|
||||
@@ -222,12 +225,19 @@ def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: st
|
||||
query = query.filter_by(source_code=source_code)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
query = (
|
||||
query.outerjoin(
|
||||
TransferMovementLedger,
|
||||
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||
)
|
||||
.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferMovementLedger.external_doc_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
@@ -266,6 +276,7 @@ def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[Ba
|
||||
item_id=item.id,
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
material_no=item.material_no,
|
||||
status=item.status,
|
||||
reason=item.result_message or item.result_code or "",
|
||||
@@ -303,7 +314,10 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
current = now or datetime.utcnow()
|
||||
rows = (
|
||||
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.all()
|
||||
)
|
||||
@@ -330,7 +344,7 @@ def list_backlog_page(
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
|
||||
keyword: 可选关键字(单号/外部单号/料号/品名/来源,子串大小写不敏感)。
|
||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
@@ -345,7 +359,10 @@ def list_backlog_page(
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.options(joinedload(TransferInvoiceItem.matching))
|
||||
base.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
|
||||
@@ -124,6 +124,8 @@ class MatchingItemDTO:
|
||||
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||
# 无匹配或快照未写类型时为空串。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号(WMS Order #)。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -63,6 +63,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
@@ -805,12 +806,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
|
||||
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
|
||||
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
|
||||
行内附带 invoice_no 溯源(逗号连接,供测试替身/排障;ERP 契约无此字段,
|
||||
真实绑定未映射即透传为惰性键)。
|
||||
行内附带 invoice_no 与 external_doc_no 溯源(各自逗号连接,供清单展示与排障;
|
||||
ERP 契约无这两字段,真实绑定未映射即透传为惰性键)。
|
||||
|
||||
Returns:
|
||||
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
|
||||
quantity/unit/invoice_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
quantity/unit/invoice_no/external_doc_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
||||
for item in items:
|
||||
@@ -831,6 +832,9 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
quantity = total.quantize(_QUANTITY_QUANT)
|
||||
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
|
||||
invoices = ",".join(sorted({item.invoice_no for item in group}))
|
||||
external_docs = ",".join(sorted({
|
||||
doc for item in group if (doc := ledger_external_doc_no(item))
|
||||
}))
|
||||
lines.append({
|
||||
"line_no": index,
|
||||
"material_no": key[0],
|
||||
@@ -840,6 +844,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
"quantity": float(quantity),
|
||||
"unit": unit,
|
||||
"invoice_no": invoices,
|
||||
"external_doc_no": external_docs,
|
||||
"quantity_text": f"{quantity:.6f}",
|
||||
})
|
||||
return lines
|
||||
@@ -1273,6 +1278,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
|
||||
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
|
||||
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
|
||||
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
取消匹配即释放;ADR 0007 匹配顶替在圈档前取消被新范围盖住、尚未写 ERP 的旧匹配)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
|
||||
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
|
||||
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
|
||||
@@ -295,11 +295,12 @@ def _dedupe_ledger_records_for_item_birth(
|
||||
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
|
||||
|
||||
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
|
||||
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
|
||||
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
|
||||
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
|
||||
占用定义(规格 §9 + grain 互斥 + ADR 0007):存在已挂上匹配的有效 item
|
||||
(所属匹配未取消,或该行是人工关闭;行非 blocked_file_removed)且满足其一
|
||||
——(a) ledger_record_id 直指本档;(b) 与本档同匹配 grain
|
||||
(source/invoice=doc_no/material/movement_date)。没有挂上匹配的明细不占用。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档。取消匹配即释放,
|
||||
人工关闭除外;成功终态不释放。
|
||||
|
||||
Args:
|
||||
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
|
||||
@@ -308,9 +309,8 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
|
||||
"""
|
||||
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
|
||||
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
|
||||
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
|
||||
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
|
||||
# 【ADR 0007】没有挂上匹配的明细不占货(直指与 grain 都不算)。
|
||||
# 人工关闭在所属匹配被顶替之后仍然占用。
|
||||
grain_match = and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
|
||||
@@ -328,17 +328,21 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
]
|
||||
if exclude_matching_id is None:
|
||||
# 匹配创建:任何未取消匹配(含无归属的历史行)的有效引用都算占用。
|
||||
# 匹配创建:必须已挂上匹配。未取消的匹配占用;人工关闭在匹配被顶替后仍占用。
|
||||
item_conditions.append(TransferInvoiceItem.matching_id.isnot(None))
|
||||
item_conditions.append(or_(
|
||||
TransferInvoiceItem.matching_id.is_(None),
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
))
|
||||
else:
|
||||
# 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。
|
||||
item_conditions.append(and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.matching_id != exclude_matching_id,
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
or_(
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
),
|
||||
))
|
||||
occupancy = (
|
||||
db.session.query(TransferInvoiceItem.id)
|
||||
@@ -611,6 +615,23 @@ def matching_transform_rules(matching: TransferMatching) -> tuple[TransformRule,
|
||||
return parse_transform_rules(scope.get("transform_rules"))
|
||||
|
||||
|
||||
def ledger_external_doc_no(item: TransferInvoiceItem) -> str:
|
||||
"""读取明细行对应异动档上的外部单号。
|
||||
|
||||
核心逻辑:外部单号只在档上(WMS Order #),明细行经 ledger_record_id 指向档。
|
||||
没有档、或档上为空时返回空串,列表显示占位。
|
||||
|
||||
Args:
|
||||
item: 明细行。ledger_record 可已预加载;未预加载时按外键懒加载。
|
||||
Returns:
|
||||
外部单号;没有则空串。
|
||||
"""
|
||||
record = item.ledger_record
|
||||
if record is None:
|
||||
return ""
|
||||
return str(record.external_doc_no or "").strip()
|
||||
|
||||
|
||||
def item_external_lot_no(item: TransferInvoiceItem) -> str:
|
||||
"""行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。
|
||||
|
||||
@@ -1242,6 +1263,116 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
return lines[0].get("file_sha256")
|
||||
|
||||
|
||||
def _source_set(codes: list[str] | None) -> tuple[str, ...]:
|
||||
"""把来源编码收成可比较的集合。
|
||||
|
||||
核心逻辑:去掉空白后排序,使 [B, A] 与 [A, B] 视为同一组来源。
|
||||
Args:
|
||||
codes: 来源编码列表;None 当空。
|
||||
Returns:
|
||||
排序后的来源编码元组。
|
||||
"""
|
||||
return tuple(sorted(str(code).strip() for code in (codes or []) if str(code).strip()))
|
||||
|
||||
|
||||
def _date_range_covers(new_from: str | None, new_to: str | None, old_from: str | None, old_to: str | None) -> bool:
|
||||
"""新异动日期范围是否把旧范围整个盖住。
|
||||
|
||||
核心逻辑:任一侧缺少起或止,都视为没盖住(无日期范围的旧匹配不被顶替)。
|
||||
日期是 YYYY-MM-DD,字符串序与日历序一致。
|
||||
Args:
|
||||
new_from / new_to: 本次匹配的异动日期起止。
|
||||
old_from / old_to: 旧匹配快照上的异动日期起止。
|
||||
Returns:
|
||||
新范围包含旧范围时为 True。
|
||||
"""
|
||||
if not new_from or not new_to or not old_from or not old_to:
|
||||
return False
|
||||
return str(new_from) <= str(old_from) and str(new_to) >= str(old_to)
|
||||
|
||||
|
||||
def _matching_has_erp_activity(items: list[TransferInvoiceItem]) -> bool:
|
||||
"""匹配是否已经写出单据,或有行正在写、结果未知。
|
||||
|
||||
核心逻辑:有外部单号,或行状态为执行中、结果未知、成功,就不顶替,
|
||||
避免把在途 ERP 写入拆成两张单。
|
||||
Args:
|
||||
items: 该匹配名下的明细。
|
||||
Returns:
|
||||
存在上述活动时为 True。
|
||||
"""
|
||||
active = {
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
}
|
||||
return any(
|
||||
(item.external_document_no or "").strip() or item.status in active
|
||||
for item in items
|
||||
)
|
||||
|
||||
|
||||
def _supersede_covered_matchings(
|
||||
*,
|
||||
transfer_type: str,
|
||||
source_codes: list[str],
|
||||
movement_date_from: str | None,
|
||||
movement_date_to: str | None,
|
||||
exclude_matching_id: int,
|
||||
) -> None:
|
||||
"""圈档前顶替被新范围盖住、尚未写 ERP 的旧匹配(ADR 0007)。
|
||||
|
||||
核心逻辑:同一调拨类型、同一组来源、旧日期范围被新范围整个盖住,且名下没有
|
||||
ERP 单据、没有正在写或结果未知的行,则匹配改为 cancelled,名下明细一并取消。
|
||||
盖不住或已在写 ERP 的旧匹配保持原样,清单不列举它们的编号。
|
||||
|
||||
Args:
|
||||
transfer_type: 本次匹配的调拨类型编码。
|
||||
source_codes: 本次来源集合。
|
||||
movement_date_from / movement_date_to: 本次异动日期范围;缺一则不顶替任何人。
|
||||
exclude_matching_id: 刚落库、尚未圈档的本次匹配,不能把自己顶掉。
|
||||
"""
|
||||
new_sources = _source_set(source_codes)
|
||||
if not new_sources:
|
||||
return
|
||||
candidates = (
|
||||
TransferMatching.query
|
||||
.filter(TransferMatching.id != exclude_matching_id)
|
||||
.filter(TransferMatching.status != _MATCHING_STATUS_CANCELLED)
|
||||
.all()
|
||||
)
|
||||
for matching in candidates:
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
if str(scope.get("transfer_type") or "") != transfer_type:
|
||||
continue
|
||||
if _source_set(scope.get("source_codes")) != new_sources:
|
||||
continue
|
||||
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
covered = _date_range_covers(
|
||||
movement_date_from,
|
||||
movement_date_to,
|
||||
scope.get("movement_date_from"),
|
||||
scope.get("movement_date_to"),
|
||||
)
|
||||
# 匹配状态 success 只表示没有可执行行(全阻断也会落成 success),
|
||||
# 不能当成已经写出 ERP。是否写过只看行上的单据号和执行状态。
|
||||
if (
|
||||
not covered
|
||||
or matching.status == status_machine.TransferStatus.EXECUTING.value
|
||||
or _matching_has_erp_activity(items)
|
||||
):
|
||||
continue
|
||||
matching.status = _MATCHING_STATUS_CANCELLED
|
||||
for item in items:
|
||||
# 人工关闭是仓库人员的裁定,顶替不把它改回可圈状态。
|
||||
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
|
||||
continue
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = "superseded by a new matching"
|
||||
|
||||
|
||||
def create_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
@@ -1259,6 +1390,7 @@ def create_matching(
|
||||
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
|
||||
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
|
||||
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
|
||||
【ADR 0007】圈档前顶替被本次日期范围盖住、尚未写 ERP 的同类型同来源旧匹配。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
@@ -1299,6 +1431,14 @@ def create_matching(
|
||||
)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
# [ADR 0007] 先释放被盖住的旧匹配,本次圈档才能看到那批货。
|
||||
_supersede_covered_matchings(
|
||||
transfer_type=config.code,
|
||||
source_codes=list(source_codes),
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
exclude_matching_id=matching.id,
|
||||
)
|
||||
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
@@ -1404,6 +1544,7 @@ def restore_matching(
|
||||
# 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。
|
||||
rows_all = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.ledger_record))
|
||||
.filter(TransferInvoiceItem.matching_id == matching.id)
|
||||
.order_by(
|
||||
TransferInvoiceItem.movement_date.asc().nulls_last(),
|
||||
@@ -1531,6 +1672,7 @@ def _item_dto(
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
lot_no=item.lot_no or "",
|
||||
movement_warehouse_code=item.movement_warehouse_code or "",
|
||||
@@ -1600,7 +1742,10 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
||||
rows = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
|
||||
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
|
||||
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
|
||||
|
||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.matching_service import item_external_lot_no
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
@@ -71,6 +74,7 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"material_name": item.material_name,
|
||||
"specification": item.specification,
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": getattr(item, "external_doc_no", "") or "",
|
||||
"lot_no": item.lot_no,
|
||||
"movement_date": item.movement_date,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
@@ -177,6 +181,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
||||
"invoice_no": line["invoice_no"],
|
||||
"external_doc_no": line.get("external_doc_no") or "",
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
@@ -222,6 +227,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"items": [
|
||||
{
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": ledger_external_doc_no(item),
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
||||
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
||||
调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
|
||||
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
|
||||
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
|
||||
入站可用条件同口径)。
|
||||
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
|
||||
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
|
||||
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
|
||||
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
|
||||
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
|
||||
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
||||
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
||||
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
||||
@@ -28,10 +29,9 @@ from typing import Any, Callable
|
||||
from sqlalchemy import and_, not_, or_
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.freight_rpa_inbound_report import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
|
||||
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
|
||||
from app.models.freight_rpa_outbound_report import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
@@ -39,12 +39,12 @@ from app.models.freight_rpa_outbound_report import (
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
||||
expired_inbound_file_condition,
|
||||
expired_inbound_source_codes,
|
||||
get_outbound_config,
|
||||
has_expired_inbound_file,
|
||||
latest_usable_inbound_file,
|
||||
latest_usable_inbound_files_by_source,
|
||||
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
@@ -288,13 +288,13 @@ def _project_file_status(
|
||||
|
||||
|
||||
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
||||
"""一次取出这批来源各自最新的可用归档。
|
||||
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
||||
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
||||
@@ -359,13 +359,13 @@ def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str,
|
||||
|
||||
|
||||
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
||||
"""一次找出仍有失效未清理归档的来源编码。
|
||||
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
||||
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 失效文件条件。
|
||||
@@ -412,19 +412,17 @@ def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict
|
||||
.all()
|
||||
)
|
||||
}
|
||||
inbound_files = _latest_files_by_source(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_files = {
|
||||
code: _FileFact(
|
||||
file_id=view.file_id,
|
||||
original_filename=view.original_filename,
|
||||
sha256=view.sha256,
|
||||
parse_failed_at=view.parse_failed_at,
|
||||
)
|
||||
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
|
||||
}
|
||||
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
||||
inbound_expired = _expired_source_codes(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
|
||||
outbound_files = _latest_files_by_source(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/app/services/integrations/wecom/notify.py
|
||||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||||
文本卡片标题默认加上「AI智能体」来源;密码重置和权限变更保持原标题。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,6 +25,17 @@ _TOKEN_CACHE = {
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
# 企微 textcard 没有发送者栏,用来源前缀让收件人看出是 AI 智能体推送。
|
||||
_AGENT_SOURCE_PREFIX = 'AI智能体 · '
|
||||
_TEXT_CARD_TITLE_LIMIT = 120
|
||||
# 账号与权限通知不是智能体推送,标题不加来源。
|
||||
_NO_AGENT_SOURCE_EVENTS = frozenset({
|
||||
'password_reset',
|
||||
'permission_batch_updated',
|
||||
'permission_request_approved',
|
||||
'permission_request_rejected',
|
||||
})
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
@@ -141,19 +153,54 @@ def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _with_agent_source_title(title: str, *, enabled: bool = True) -> str:
|
||||
"""
|
||||
给企微 textcard 标题加上「AI智能体」来源,并限制在 120 字以内。
|
||||
|
||||
核心逻辑:前缀放在最前,超长时截断业务标题,避免来源被切掉。
|
||||
已带相同前缀时不重复添加。enabled 为 False 时只做长度截断。
|
||||
Args:
|
||||
title: 业务侧传入的卡片标题。
|
||||
enabled: 为 False 时保持原标题,用于密码重置和权限变更。
|
||||
Returns:
|
||||
实际发给企业微信的标题。
|
||||
"""
|
||||
text = (title or '').strip()
|
||||
if not enabled:
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
if text.startswith(_AGENT_SOURCE_PREFIX):
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
return f'{_AGENT_SOURCE_PREFIX}{text}'[:_TEXT_CARD_TITLE_LIMIT]
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
*,
|
||||
with_agent_source: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企业微信文本卡片。
|
||||
|
||||
核心逻辑:默认在标题前加上「AI智能体」来源。审计记录仍保存调用方传入的业务标题。
|
||||
Args:
|
||||
wecom_userid: 企业微信 userid。
|
||||
title: 业务标题。
|
||||
description: 卡片正文。
|
||||
jump_url: 点击跳转地址。
|
||||
with_agent_source: 为 False 时标题不加来源。
|
||||
Returns:
|
||||
企业微信 message/send 的 JSON 响应。
|
||||
"""
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'title': _with_agent_source_title(title, enabled=with_agent_source),
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
@@ -200,6 +247,7 @@ def send_wecom_event_message(
|
||||
|
||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||
标题在发送时加上「AI智能体」来源;密码重置和权限变更不加。审计 title 保持业务标题。
|
||||
Args:
|
||||
event_type: 通知事件开关名。
|
||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||
@@ -239,7 +287,13 @@ def send_wecom_event_message(
|
||||
else:
|
||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = final_jump_url
|
||||
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
||||
data = send_wecom_textcard_message(
|
||||
target_userid,
|
||||
title,
|
||||
content,
|
||||
final_jump_url,
|
||||
with_agent_source=event_type not in _NO_AGENT_SOURCE_EVENTS,
|
||||
)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
@@ -2,18 +2,24 @@
|
||||
|
||||
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
|
||||
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
||||
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
依赖:auto_transfer、recovery_service、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
|
||||
transfer_type_config_service.get_enabled(缺省类型口径)、
|
||||
date_policy(业务日与日期解析)。
|
||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
|
||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
|
||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;【调拨类型 2026-10-23】
|
||||
job_params.transfer_types 为 multi_select,留空=全部启用中的类型配置,
|
||||
按类型逐轮 run_auto_transfer(恢复复核与类型无关,循环外只跑一次);
|
||||
类型配置为空/读取失败 fail-closed 硬失败,不静默跳过;可选异动日期范围
|
||||
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
|
||||
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
|
||||
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
|
||||
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
|
||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
|
||||
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
|
||||
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(全部
|
||||
类型均无 run_no 且无 errors)置 domain_notification_managed 保持静默
|
||||
(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
返回:七元组位序=(total, success, failed, skipped, details, errors, step_logs),
|
||||
warnings 无对应槽位——恢复/来源汇总写 step_logs(dict),不得挤占 errors 位。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,11 +27,13 @@ from __future__ import annotations
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
||||
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
@@ -52,6 +60,33 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
def _wanted_transfer_types(params: dict[str, Any], errors: list[str]) -> list[str]:
|
||||
"""提取结构化 transfer_types;留空回落为全部启用中的类型配置(fail-closed)。
|
||||
|
||||
Args:
|
||||
params: 排程结构化参数(job_params.transfer_types 可为列表/字符串/缺省)。
|
||||
errors: 错误累积列表(类型配置读取失败/为空时写入,由调用方硬失败)。
|
||||
Returns:
|
||||
去空白后的类型编码列表;配置为空或脏配置读取失败时为空列表(已落错误)。
|
||||
"""
|
||||
values = params.get("transfer_types") or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
codes = [str(item).strip() for item in values if str(item).strip()]
|
||||
if codes:
|
||||
return codes
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
try:
|
||||
codes = [dto.code for dto in get_enabled()]
|
||||
except AppError as exc:
|
||||
errors.append(f"调拨类型配置读取失败: {exc}")
|
||||
return []
|
||||
if not codes:
|
||||
errors.append("无启用中的调拨类型配置(须先在管理端调拨类型页创建并启用)")
|
||||
return codes
|
||||
|
||||
|
||||
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
||||
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
|
||||
|
||||
@@ -77,12 +112,14 @@ def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: li
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
|
||||
"""自动调拨:恢复(一次)→ 按类型逐轮「匹配(严格相等)+ 执行」;通知走排程「启用通知」。
|
||||
|
||||
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
|
||||
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
|
||||
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
|
||||
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
|
||||
核心逻辑:不自建领域汇总通知(收件人取排程表单底部「启用通知」配置);
|
||||
仅在空数据日(全部类型均无 run_no 且无 errors)置 domain_notification_managed
|
||||
抑制框架完成卡(C5 空数据日静默);有 run_no 或硬失败时框架卡照常发送/兜底。
|
||||
调拨类型留空=全部启用类型逐轮执行(D8:类型=平台配置,排程不隐式假设单一
|
||||
类型;配置为空/读取失败 fail-closed 硬失败);历史恢复与类型无关,循环外
|
||||
只跑一次(重复恢复会对同一批行重复建 Attempt 并重复外部查询)。
|
||||
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
||||
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
||||
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
|
||||
@@ -90,7 +127,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params: source_codes/recover_history/
|
||||
task: 排程任务(job_params: transfer_types/source_codes/recover_history/
|
||||
receipt_from_offset_days/receipt_to_offset_days)。
|
||||
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
||||
Returns:
|
||||
@@ -101,60 +138,99 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
recover_history = bool(params.get("recover_history", True))
|
||||
business_date = str(business_date_now())
|
||||
|
||||
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。
|
||||
param_errors: list[str] = []
|
||||
# [STEP 1] 配置解析与 T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。硬失败以 failed_count=1 落终态
|
||||
# failed(total=0 且 errors 非空会被框架判 success「无待处理数据」,不可用)。
|
||||
errors: list[str] = []
|
||||
transfer_types = _wanted_transfer_types(params, errors)
|
||||
movement_date_from = _offset_to_date(
|
||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
|
||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", errors)
|
||||
movement_date_to = _offset_to_date(
|
||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
|
||||
if param_errors:
|
||||
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", errors)
|
||||
if errors:
|
||||
return (1, 0, 1, 0, [], errors, [
|
||||
{"step": "config", "status": "failed", "detail": f"sources={len(source_codes)}"},
|
||||
])
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
|
||||
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
|
||||
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
|
||||
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
|
||||
transfer_type = str(params.get("transfer_type") or "").strip() or None
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=recover_history,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
|
||||
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
||||
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not outcome.run_no and not outcome.errors:
|
||||
# [STEP 2] 恢复复核只跑一次:扫全部 blocked_recoverable 行(与类型无关),
|
||||
# result_unknown / manually_closed 在服务内只读隔离/永久排除。恢复失败计一个
|
||||
# failed 单元——否则「恢复失败+各类型均空数据日」total=0 会被框架判 success。
|
||||
recovery = RecoveryOutcome()
|
||||
recovery_failed = False
|
||||
if recover_history:
|
||||
try:
|
||||
recovery = run_daily_recovery(business_date=business_date, deps=deps)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
recovery_failed = True
|
||||
errors.append(f"recovery_failed: {exc}")
|
||||
step_logs: list[dict[str, Any]] = [{
|
||||
"step": "recovery",
|
||||
"status": "failed" if recovery_failed else ("success" if recover_history else "skipped"),
|
||||
"detail": {
|
||||
"recovered": recovery.recovered_count,
|
||||
"still_blocked": recovery.still_blocked_count,
|
||||
"skipped_result_unknown": recovery.skipped_result_unknown,
|
||||
"skipped_manually_closed": recovery.skipped_manually_closed,
|
||||
},
|
||||
}]
|
||||
failed_units = 1 if recovery_failed else 0
|
||||
|
||||
# [STEP 3] 按类型逐轮自动调拨:单类型失败不阻断其余类型(run_auto_transfer
|
||||
# 内部捕获进 outcome.errors)。
|
||||
results: list[dict[str, Any]] = []
|
||||
success_runs = 0
|
||||
failed_runs = 0
|
||||
for code in transfer_types:
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=False,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=code,
|
||||
)
|
||||
errors.extend(outcome.errors)
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"transfer_type": code,
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
})
|
||||
if outcome.run_status in {"success", "partial_failed"}:
|
||||
success_runs += 1
|
||||
else:
|
||||
failed_runs += 1
|
||||
elif outcome.errors:
|
||||
failed_runs += 1
|
||||
|
||||
# [STEP 4] 空数据日静默门禁:全部类型均无 run 且无错误(C5)时置标记抑制
|
||||
# 框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not results and not errors:
|
||||
run.response_summary_json = {
|
||||
**(run.response_summary_json or {}),
|
||||
"domain_notification_managed": True,
|
||||
}
|
||||
results: list[dict[str, Any]] = []
|
||||
errors: list[str] = list(outcome.errors)
|
||||
recovery = outcome.recovery
|
||||
warnings: list[str] = [
|
||||
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
|
||||
]
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
step_logs.append({
|
||||
"step": "auto_transfer", "status": "skipped",
|
||||
"detail": "no executable items; execution and notification skipped",
|
||||
})
|
||||
elif not outcome.errors:
|
||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
||||
warnings.append("no executable items; execution and notification skipped")
|
||||
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
|
||||
|
||||
summary_text = (
|
||||
f"sources={len(source_codes)} types={len(transfer_types)} "
|
||||
f"runs={len(results)} recovered={recovery.recovered_count} "
|
||||
f"still_blocked={recovery.still_blocked_count}"
|
||||
)
|
||||
return (
|
||||
success + recovery.recovered_count,
|
||||
success,
|
||||
recovery.still_blocked_count,
|
||||
success_runs + failed_runs + recovery.recovered_count + failed_units,
|
||||
success_runs,
|
||||
failed_runs + failed_units + recovery.still_blocked_count,
|
||||
0,
|
||||
results,
|
||||
warnings,
|
||||
errors,
|
||||
step_logs + [
|
||||
{"step": "summary", "status": "failed" if errors else "success", "detail": summary_text},
|
||||
],
|
||||
)
|
||||
@@ -5,7 +5,8 @@ backend/app/services/schedule/job_options.py
|
||||
依赖:models.Agent、shipping_notice.onhand_source_repository。
|
||||
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
||||
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
|
||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources;
|
||||
在途调拨注册键为 transfer_types(启用中的调拨类型配置)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -78,6 +79,20 @@ def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
def _transfer_types_options() -> list[dict[str, Any]]:
|
||||
"""启用中的调拨类型(value=类型编码;供在途自动调拨排程选类型,留空=全部)。"""
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
return [
|
||||
{
|
||||
"label": (dto.names or {}).get("zh-CN") or dto.code,
|
||||
"value": dto.code,
|
||||
"description": dto.description or None,
|
||||
}
|
||||
for dto in get_enabled()
|
||||
]
|
||||
|
||||
|
||||
def _hxops_users_options() -> list[dict[str, Any]]:
|
||||
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
||||
from app.models import User
|
||||
@@ -118,6 +133,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"freight_rpa_sources": _freight_rpa_sources_options,
|
||||
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
|
||||
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
|
||||
"transfer_types": _transfer_types_options,
|
||||
"hxops_users": _hxops_users_options,
|
||||
"users": _users_options,
|
||||
}
|
||||
|
||||
@@ -606,10 +606,21 @@ def _register_builtin_platform_jobs() -> None:
|
||||
handler=run_in_transit_transfer_schedule,
|
||||
description=(
|
||||
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
||||
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
|
||||
"缺收料文件时自动触发收料 RPA。调拨类型留空=全部启用类型逐轮执行。"
|
||||
"执行时间建议配置在期望调拨时点之前。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "transfer_types",
|
||||
"type": "multi_select",
|
||||
"label": "调拨类型",
|
||||
"label_key": "admin.schedule.form.transferTypeCodes",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "transfer_types",
|
||||
"help": "留空=全部启用中的调拨类型;按类型逐轮匹配并执行,恢复复核只跑一次。",
|
||||
},
|
||||
{
|
||||
"key": "source_codes",
|
||||
"type": "multi_select",
|
||||
|
||||
@@ -46,26 +46,56 @@ from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def _released_line_indexes_for_task(order_task_id: int) -> set[int]:
|
||||
"""按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(order_task_id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||
ShippingOrderReviewLineDecision.line_index.isnot(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {int(row.line_index) for row in rows}
|
||||
|
||||
|
||||
def _notice_source_code(task: ShippingNotice) -> str | None:
|
||||
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
|
||||
|
||||
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
|
||||
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
|
||||
已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found
|
||||
(如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性
|
||||
裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源
|
||||
(回归 OT-20261027-4BD4CEFF)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||
codes = [
|
||||
str(row[0]).strip().upper()
|
||||
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
|
||||
for row in db.session.query(
|
||||
ShippingNoticeLineOnhandMatch.source_code,
|
||||
ShippingNoticeLineOnhandMatch.match_result,
|
||||
ShippingNoticeLineOnhandMatch.line_index,
|
||||
).filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
||||
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
|
||||
).distinct().all()
|
||||
if row[0]
|
||||
).all()
|
||||
if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes))
|
||||
]
|
||||
codes = list(dict.fromkeys(codes))
|
||||
return codes[0] if len(codes) == 1 else None
|
||||
|
||||
|
||||
@@ -87,19 +117,31 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
|
||||
|
||||
|
||||
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。
|
||||
|
||||
已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时
|
||||
库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||
ids = [
|
||||
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
|
||||
int(row[0]) for row in db.session.query(
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id,
|
||||
ShippingNoticeLineOnhandMatch.match_result,
|
||||
ShippingNoticeLineOnhandMatch.line_index,
|
||||
).filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
|
||||
).distinct().all()
|
||||
).all()
|
||||
if row[0] is not None and (
|
||||
row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)
|
||||
)
|
||||
]
|
||||
ids = list(dict.fromkeys(ids))
|
||||
return ids[0] if len(ids) == 1 else None
|
||||
|
||||
|
||||
@@ -799,8 +841,14 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||
# [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是
|
||||
# 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空,
|
||||
# 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
order_task_id_for_decisions = int(
|
||||
getattr(source_notice, 'order_task_id', None) or source_notice.id
|
||||
)
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if source_notice.id is not None:
|
||||
@@ -808,7 +856,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||
)
|
||||
@@ -835,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
|
||||
@@ -2520,7 +2520,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
|
||||
raw_result = str(payload.get('result') or '').strip().lower()
|
||||
if raw_result in {'success', 'failed', 'unknown'}:
|
||||
if raw_result in {'success', 'failed', 'unknown', 'allocating'}:
|
||||
result_status = raw_result
|
||||
else:
|
||||
result_status = 'success' if success else 'failed'
|
||||
@@ -2614,6 +2614,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
|
||||
)
|
||||
|
||||
if completed.status == 'running' and completed.error_code == 'CRANE_ALLOCATING':
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="running",
|
||||
message='货代已接收文件,正在分配,稍后自动回查一次',
|
||||
progress_percent=90,
|
||||
detail='Processing + Allocating the Shipping Order',
|
||||
)
|
||||
log_task_event(task, 'upload_rpa_allocating', {'artifact_id': completed.artifact_id, 'attempt_id': completed.id})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='running',
|
||||
task=task,
|
||||
message='货代已接收文件,正在分配',
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if completed.status == 'unknown':
|
||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||
set_task_step_progress(
|
||||
|
||||
@@ -414,7 +414,11 @@ def _shortage_release_required_fields(
|
||||
source_code=resolved_source_code, enabled=True,
|
||||
).first()
|
||||
template = getattr(source, 'excel_template', None) if source is not None else None
|
||||
profile = getattr(source, 'parsing_profile', None) if source is not None else None
|
||||
# [s18 改名] 解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系
|
||||
# (与 freight_rpa.parsing_profile.require_source_profile 同口径);
|
||||
# 站点行 getattr 读法会静默得 None,曾致短缺放行(自动+人工)全部失败。
|
||||
release_config = getattr(source, 'onhand_report_config', None) if source is not None else None
|
||||
profile = release_config.parsing_profile if release_config is not None else None
|
||||
if template is None or profile is None:
|
||||
raise ConflictError(
|
||||
'Inventory source export template is unavailable',
|
||||
|
||||
@@ -1951,16 +1951,19 @@ def list_freight_notice_groups_for_task(
|
||||
.first()
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
||||
projected_upload_status = project_notice_upload_status(notice)
|
||||
hide_allocating_error = projected_upload_status == 'allocating'
|
||||
items.append({
|
||||
'business_no': business_no,
|
||||
'po_number': po_number,
|
||||
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
|
||||
'upload_status': project_notice_upload_status(notice),
|
||||
'upload_status': projected_upload_status,
|
||||
'upload_mode': upload_mode,
|
||||
'upload_attempt': upload_attempt,
|
||||
'upload_error_code': getattr(latest_attempt, 'error_code', None),
|
||||
'upload_error_code': None if hide_allocating_error else getattr(latest_attempt, 'error_code', None),
|
||||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
||||
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
|
||||
# 分配中的内部错误码不是失败原因,不能把这一行显示成需人工。
|
||||
'upload_error_message': None if hide_allocating_error else ((getattr(latest_attempt, 'error_message', None) or '')[:500] or None),
|
||||
'export_file_name': getattr(artifact, 'file_name', None),
|
||||
'available_actions': available_actions,
|
||||
'lines': _notice_line_summary_for_task(notice),
|
||||
|
||||
@@ -75,6 +75,14 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
|
||||
return existing
|
||||
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
|
||||
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
|
||||
allocating = ShippingUploadAttempt.query.filter_by(
|
||||
artifact_id=artifact.id, status='running', error_code='CRANE_ALLOCATING',
|
||||
).first()
|
||||
if allocating is not None:
|
||||
raise ConflictError(
|
||||
'Crane has accepted the file and is still allocating; refresh status instead of uploading again',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
|
||||
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
|
||||
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
|
||||
@@ -123,7 +131,7 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
||||
task: 正式 Notice,或可解析到 Notice 的 OT。
|
||||
|
||||
Returns:
|
||||
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||
uploaded | allocating | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||
"""
|
||||
attempt = latest_upload_attempt(task)
|
||||
if attempt is not None:
|
||||
@@ -131,6 +139,8 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
||||
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
|
||||
if status == 'succeeded':
|
||||
return 'uploaded'
|
||||
if status == 'running' and str(getattr(attempt, 'error_code', None) or '') == 'CRANE_ALLOCATING':
|
||||
return 'allocating'
|
||||
if status in _UPLOAD_IN_FLIGHT_TOKENS:
|
||||
return 'uploading'
|
||||
if status == 'pending':
|
||||
@@ -221,9 +231,9 @@ def _normalize_callback_result(result: str | None, success: bool) -> str:
|
||||
"""
|
||||
if result is not None:
|
||||
normalized = str(result or '').strip().lower()
|
||||
if normalized not in {'success', 'failed', 'unknown'}:
|
||||
if normalized not in {'success', 'failed', 'unknown', 'allocating'}:
|
||||
raise ValidationError(
|
||||
'result must be success, failed or unknown',
|
||||
'result must be success, failed, unknown or allocating',
|
||||
code='SHIPPING.UPLOAD_RESULT_INVALID',
|
||||
)
|
||||
return normalized
|
||||
@@ -243,7 +253,7 @@ def complete_attempt(
|
||||
callback_id: 回调幂等键(唯一)。
|
||||
freight_ref_no: 成功时货代回执号。
|
||||
error_message: 失败/未知时的脱敏错误信息。
|
||||
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
|
||||
result: success / failed / unknown / allocating。allocating 表示 Crane 已接收且仍在分配。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 已更新状态的 Attob。
|
||||
@@ -266,10 +276,16 @@ def complete_attempt(
|
||||
if artifact.status in {'superseded', 'invalidated'}:
|
||||
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
|
||||
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
|
||||
if str(result or '').strip().lower() == 'allocating':
|
||||
return attempt
|
||||
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
|
||||
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
result_status = _normalize_callback_result(result, success)
|
||||
if result_status == 'allocating':
|
||||
from app.services.freight_rpa.upload.crane_recheck import remember_crane_allocating
|
||||
|
||||
return remember_crane_allocating(attempt, artifact, callback)
|
||||
attempt.callback_id = callback
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
task = db.session.get(ShippingNotice, artifact.task_id)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/upload_config_validation.py
|
||||
|
||||
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
|
||||
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
|
||||
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
|
||||
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
|
||||
用途:系统连接只保存「是否启用发货 Excel 自动上传」。
|
||||
依赖:app.core.errors.ValidationError;标准库 hashlib/json。
|
||||
逻辑:页面路径、选择器和成功文案由连接器代码固定,管理端提交的这些字段一律丢弃。
|
||||
upload_config 快照只保留 enabled,供本次上传审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,192 +15,34 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
|
||||
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
|
||||
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
|
||||
'dbs': ('dbschenker.com',),
|
||||
'crane': ('craneww.com',),
|
||||
}
|
||||
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
|
||||
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
|
||||
|
||||
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
|
||||
ALLOWED_KEYS = frozenset({
|
||||
'enabled', 'entry_url', 'file_input_selector',
|
||||
'submit_mode', 'submit_selector',
|
||||
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
|
||||
})
|
||||
|
||||
MAX_ENTRY_URL_LENGTH = 500
|
||||
MAX_SELECTOR_LENGTH = 200
|
||||
MAX_SUCCESS_TEXTS = 10
|
||||
MAX_SUCCESS_TEXT_LENGTH = 200
|
||||
MIN_TIMEOUT_SECONDS = 1
|
||||
MAX_TIMEOUT_SECONDS = 600
|
||||
DEFAULT_TIMEOUT_SECONDS = 120
|
||||
|
||||
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
|
||||
_BLOCKED_SELECTOR_MARKERS = (
|
||||
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
|
||||
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
|
||||
)
|
||||
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
|
||||
|
||||
|
||||
def _reject(message: str, *, field: str) -> None:
|
||||
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
|
||||
|
||||
|
||||
def _normalize_text(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
|
||||
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
|
||||
url = _normalize_text(value)
|
||||
if not url:
|
||||
if required:
|
||||
_reject('entry_url is required', field='entry_url')
|
||||
return None
|
||||
if len(url) > MAX_ENTRY_URL_LENGTH:
|
||||
_reject('entry_url is too long', field='entry_url')
|
||||
if not url.lower().startswith('https://'):
|
||||
_reject('entry_url must be HTTPS', field='entry_url')
|
||||
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
|
||||
scheme_rest = url[8:]
|
||||
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
|
||||
host = authority.split('@')[-1].split(':')[0].strip().lower()
|
||||
if not host:
|
||||
_reject('entry_url host is invalid', field='entry_url')
|
||||
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
|
||||
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
|
||||
_reject(
|
||||
f'entry_url host not allowed for {connector_type}',
|
||||
field='entry_url',
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
|
||||
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
|
||||
selector = _normalize_text(value)
|
||||
if not selector:
|
||||
if required:
|
||||
_reject(f'{field} is required', field=field)
|
||||
return None
|
||||
if len(selector) > MAX_SELECTOR_LENGTH:
|
||||
_reject(f'{field} is too long', field=field)
|
||||
lowered = selector.lower()
|
||||
for marker in _BLOCKED_SELECTOR_MARKERS:
|
||||
if marker in lowered:
|
||||
_reject(f'{field} contains script semantics', field=field)
|
||||
for char in _BLOCKED_SELECTOR_CHARS:
|
||||
if char in selector:
|
||||
_reject(f'{field} contains an invalid character', field=field)
|
||||
return selector
|
||||
|
||||
|
||||
def _validate_success_texts(value: Any) -> list[str]:
|
||||
if value in (None, ''):
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
_reject('success_texts must be a list', field='success_texts')
|
||||
if len(value) > MAX_SUCCESS_TEXTS:
|
||||
_reject('success_texts is too long', field='success_texts')
|
||||
result: list[str] = []
|
||||
for item in value:
|
||||
text = _normalize_text(item)
|
||||
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
|
||||
_reject('success_texts contains an invalid item', field='success_texts')
|
||||
if text not in result:
|
||||
result.append(text)
|
||||
return result
|
||||
|
||||
|
||||
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
|
||||
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
|
||||
"""只保留 enabled。页面参数即使随旧表单提交也不落库。
|
||||
|
||||
Args:
|
||||
connector_type: 连接类型,仅允许 dbs / crane。
|
||||
raw: 管理端提交的原始上传配置对象。
|
||||
raw: 管理端提交的上传配置。None 或空串表示未配置。
|
||||
|
||||
Returns:
|
||||
dict | None: 规范化受限 JSON;未配置时返回 None。
|
||||
dict | None: ``{"enabled": bool}``;未配置时返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
|
||||
enabled=true 但缺少上传或结果判定所需字段。
|
||||
ValidationError: 连接类型非法或上传配置不是对象。
|
||||
"""
|
||||
normalized_connector = _normalize_text(connector_type).lower()
|
||||
normalized_connector = str(connector_type or '').strip().lower()
|
||||
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
|
||||
_reject('connector_type must be dbs or crane', field='connector_type')
|
||||
if raw in (None, ''):
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
_reject('upload_config must be an object', field='upload_config_json')
|
||||
unknown = set(raw) - ALLOWED_KEYS
|
||||
if unknown:
|
||||
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
|
||||
|
||||
enabled = raw.get('enabled') is True
|
||||
|
||||
config: dict[str, Any] = {
|
||||
'enabled': enabled,
|
||||
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
|
||||
'file_input_selector': _validate_css_selector(
|
||||
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
|
||||
),
|
||||
'submit_mode': _normalize_text(raw.get('submit_mode')),
|
||||
'submit_selector': _validate_css_selector(
|
||||
raw.get('submit_selector'), field='submit_selector', required=False,
|
||||
),
|
||||
'result_mode': _normalize_text(raw.get('result_mode')),
|
||||
'result_selector': _validate_css_selector(
|
||||
raw.get('result_selector'), field='result_selector', required=False,
|
||||
),
|
||||
'success_texts': _validate_success_texts(raw.get('success_texts')),
|
||||
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
|
||||
}
|
||||
|
||||
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
|
||||
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
|
||||
if config['result_mode'] not in ALLOWED_RESULT_MODES:
|
||||
_reject('result_mode must be page_notice or history_record', field='result_mode')
|
||||
if config['submit_mode'] == 'auto_after_file':
|
||||
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
|
||||
config['submit_selector'] = None
|
||||
|
||||
try:
|
||||
timeout = int(config['timeout_seconds'])
|
||||
except (TypeError, ValueError):
|
||||
_reject('timeout_seconds must be an integer', field='timeout_seconds')
|
||||
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
|
||||
_reject(
|
||||
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
|
||||
field='timeout_seconds',
|
||||
)
|
||||
config['timeout_seconds'] = timeout
|
||||
|
||||
if enabled:
|
||||
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
|
||||
if not config['file_input_selector']:
|
||||
_reject('enabled upload requires file_input_selector', field='file_input_selector')
|
||||
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
|
||||
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
|
||||
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
|
||||
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
|
||||
if normalized_connector == 'crane':
|
||||
if config['result_mode'] == 'page_notice':
|
||||
if not config['result_selector'] or not config['success_texts']:
|
||||
_reject(
|
||||
'enabled crane page_notice upload requires result_selector and success_texts',
|
||||
field='result_selector',
|
||||
)
|
||||
elif config['result_mode'] == 'history_record' and not config['result_selector']:
|
||||
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
|
||||
|
||||
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
|
||||
return config
|
||||
return {'enabled': raw.get('enabled') is True}
|
||||
|
||||
|
||||
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
|
||||
|
||||
@@ -44,7 +44,7 @@ class DmsArchiveAdapter:
|
||||
"""
|
||||
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
|
||||
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
|
||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
|
||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有原名则跳过。带「(重命名)」的副本改回原名,同一目录多出来的该后缀文件删除。
|
||||
"""
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
|
||||
@@ -4,10 +4,12 @@ backend/app/services/voucher_check/dms_client.py
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
||||
文档库复制后 LeafName 写成「原名.pdf(重命名)」,扩展名另存。改回「原名.pdf」会被判同名,必须改成不含扩展名的「原名」;多余副本用 Item/Recycle 删除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
@@ -23,6 +25,65 @@ _LOCK = threading.Lock()
|
||||
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
|
||||
|
||||
ARCHIVE_ROOT_LEAF = "所有归档"
|
||||
# 文档库同名冲突或复制后自动改名。标记前后可能有空格,后面有时还有 (1)。
|
||||
_DMS_RENAME_RE = re.compile(
|
||||
r"\s*[((]\s*重命名\s*[))]\s*(?:\(\s*\d+\s*\)|(\s*\d+\s*))?"
|
||||
)
|
||||
|
||||
|
||||
def canonical_leaf_name(name: str) -> str:
|
||||
"""
|
||||
去掉文档库自动加上的「重命名」标记,还原业务文件名。
|
||||
核心逻辑:`发票.pdf(重命名).pdf` 或带空格的 `发票.pdf (重命名) .pdf` 去掉标记后会多出一个扩展名,再折成 `发票.pdf`。
|
||||
"""
|
||||
text = str(name or "").strip()
|
||||
cleaned = _DMS_RENAME_RE.sub("", text)
|
||||
if cleaned == text:
|
||||
return text
|
||||
return re.sub(r"(\.[A-Za-z0-9]{1,8})\s*\1$", r"\1", cleaned).strip()
|
||||
|
||||
|
||||
def dms_stored_leaf_name(filename: str) -> str:
|
||||
"""
|
||||
算出文档库改名接口要写入的 LeafName。
|
||||
核心逻辑:库里真实名字是「发票.pdf(重命名)」,扩展名在附件上。改成「发票.pdf」会和自己判成同名;改成「发票」后界面仍显示「发票.pdf」。
|
||||
"""
|
||||
name = str(filename or "").strip()
|
||||
suffix = Path(name).suffix
|
||||
if suffix and name.lower().endswith(suffix.lower()) and len(name) > len(suffix):
|
||||
return name[: -len(suffix)]
|
||||
return name
|
||||
|
||||
|
||||
def row_display_name(row: dict[str, Any]) -> str:
|
||||
"""
|
||||
还原文档库界面上的文件名。
|
||||
核心逻辑:LeafName 没有以附件扩展名结尾时,界面会把扩展名补在后面。
|
||||
"""
|
||||
leaf = str((row or {}).get("LeafName") or "").strip()
|
||||
attachment = (row or {}).get("MainFileAttachment") or {}
|
||||
if not isinstance(attachment, dict):
|
||||
attachment = {}
|
||||
ext = str(attachment.get("Extension") or "").strip()
|
||||
if ext and not ext.startswith("."):
|
||||
ext = f".{ext}"
|
||||
if ext and leaf and not leaf.lower().endswith(ext.lower()):
|
||||
return f"{leaf}{ext}"
|
||||
return leaf
|
||||
|
||||
|
||||
def leaf_names_match(actual: str, wanted: str) -> bool:
|
||||
"""
|
||||
判断目录里的文件名是否就是要找的那一份。
|
||||
核心逻辑:完全一致,或实际名字只是想要的名字加上了文档库「重命名」。
|
||||
"""
|
||||
left = str(actual or "").strip()
|
||||
right = str(wanted or "").strip()
|
||||
if not left or not right:
|
||||
return False
|
||||
if left == right:
|
||||
return True
|
||||
return canonical_leaf_name(left) == right
|
||||
|
||||
|
||||
def _extract_item_id(payload: dict[str, Any]) -> str:
|
||||
@@ -265,14 +326,22 @@ class SalesDmsClient:
|
||||
|
||||
@classmethod
|
||||
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
|
||||
"""在父目录下按 LeafName 找非文件夹条目,找不到返回 None。"""
|
||||
"""
|
||||
在父目录下按 LeafName 找非文件夹条目,找不到返回 None。
|
||||
核心逻辑:优先完全同名。库内名字可能是「原名.pdf(重命名)」或已改回的「原名」,都按界面显示名认成同一份。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not wanted:
|
||||
return None
|
||||
renamed: dict[str, Any] | None = None
|
||||
for row in cls.list_files(folder_id=parent_folder_id):
|
||||
if str(row.get("LeafName") or "").strip() == wanted:
|
||||
leaf = str(row.get("LeafName") or "").strip()
|
||||
shown = row_display_name(row)
|
||||
if leaf == wanted or shown == wanted:
|
||||
return row
|
||||
return None
|
||||
if renamed is None and (leaf_names_match(leaf, wanted) or leaf_names_match(shown, wanted)):
|
||||
renamed = row
|
||||
return renamed
|
||||
|
||||
@classmethod
|
||||
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
|
||||
@@ -387,6 +456,121 @@ class SalesDmsClient:
|
||||
failure_message="文档库复制文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def rename_item(cls, *, item_id: str, leaf_name: str) -> dict[str, Any]:
|
||||
"""
|
||||
把文档库条目改成指定文件名。
|
||||
核心逻辑:POST Item/Rename,与文档库列表「重命名」一致,只改 LeafName、不另存一份。
|
||||
"""
|
||||
item = str(item_id or "").strip()
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not item:
|
||||
raise ValidationError("重命名条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not wanted:
|
||||
raise ValidationError("重命名文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/Rename",
|
||||
{"ItemID": item, "LeafName": wanted},
|
||||
timeout=30,
|
||||
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
failure_message="文档库去掉重命名后缀失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _restore_exact_leaf(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
wanted: str,
|
||||
row: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
所有归档要求界面上不带「(重命名)」。
|
||||
核心逻辑:先确认这份就是目标文件。改名只写不含扩展名的 LeafName;写成「原名.pdf」会和「原名.pdf(重命名)」判成同名。
|
||||
"""
|
||||
leaf = str(row.get("LeafName") or "").strip()
|
||||
shown = row_display_name(row)
|
||||
target = dms_stored_leaf_name(wanted)
|
||||
if leaf in {wanted, target} or shown == wanted:
|
||||
return row
|
||||
if canonical_leaf_name(leaf) != wanted and canonical_leaf_name(shown) != wanted:
|
||||
raise ServiceUnavailableError(
|
||||
"目标目录文件名与归档文件名不一致",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted, "actual_name": leaf},
|
||||
)
|
||||
cls.rename_item(item_id=str(row.get("ID") or ""), leaf_name=target)
|
||||
for item in cls.list_files(folder_id=parent_folder_id):
|
||||
item_leaf = str(item.get("LeafName") or "").strip()
|
||||
if item_leaf in {wanted, target} or row_display_name(item) == wanted:
|
||||
return item
|
||||
raise ServiceUnavailableError(
|
||||
"去掉重命名后缀后未找到原文件名",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def recycle_items(cls, *, item_ids: list[str]) -> dict[str, Any]:
|
||||
"""
|
||||
按文档库列表「删除」把条目放进回收站。
|
||||
核心逻辑:POST Item/Recycle,ItemID 为数组;不调用彻底删除,误删可从回收站恢复。
|
||||
"""
|
||||
ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()]
|
||||
if not ids:
|
||||
raise ValidationError("删除条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/Recycle",
|
||||
{"ItemID": ids},
|
||||
timeout=30,
|
||||
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
failure_message="文档库删除多余重命名文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _drop_extra_renamed_copies(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
wanted: str,
|
||||
keep_item_id: str,
|
||||
) -> None:
|
||||
"""
|
||||
删掉同一目录里多出来的「(重命名)」副本。
|
||||
核心逻辑:只删文件名还原后等于目标原名、且仍带重命名标记的条目;原名和其他文件不动。
|
||||
"""
|
||||
keep = str(keep_item_id or "").strip()
|
||||
extras: list[str] = []
|
||||
for row in cls.list_files(folder_id=parent_folder_id):
|
||||
item_id = str(row.get("ID") or "").strip()
|
||||
leaf = str(row.get("LeafName") or "").strip()
|
||||
shown = row_display_name(row)
|
||||
if not item_id or item_id == keep or ("重命名" not in leaf and "重命名" not in shown):
|
||||
continue
|
||||
if canonical_leaf_name(leaf) == wanted or canonical_leaf_name(shown) == wanted:
|
||||
extras.append(item_id)
|
||||
if extras:
|
||||
cls.recycle_items(item_ids=extras)
|
||||
|
||||
@classmethod
|
||||
def _settle_archived_file(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
wanted: str,
|
||||
row: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
归档落盘后收成一个界面上不带后缀的原名。
|
||||
核心逻辑:先删掉其余「(重命名)」副本,再把留下的那份改成不含扩展名的 LeafName。先改名会被文档库判成同名。
|
||||
"""
|
||||
cls._drop_extra_renamed_copies(
|
||||
parent_folder_id=parent_folder_id,
|
||||
wanted=wanted,
|
||||
keep_item_id=str(row.get("ID") or "").strip(),
|
||||
)
|
||||
return cls._restore_exact_leaf(parent_folder_id=parent_folder_id, wanted=wanted, row=row)
|
||||
|
||||
@classmethod
|
||||
def copy_file_skip_same_name(
|
||||
cls,
|
||||
@@ -397,10 +581,10 @@ class SalesDmsClient:
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
"""
|
||||
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
||||
核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。
|
||||
核心逻辑:先按 LeafName 查目标。已有原名则跳过复制;只有「(重命名)」副本时改回原名。没有再 Copy。收尾时同一目录多出来的该后缀副本删除。
|
||||
|
||||
Returns:
|
||||
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。
|
||||
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有文件(必要时已去掉重命名后缀并删除多余副本)。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
source = str(source_item_id or "").strip()
|
||||
@@ -414,18 +598,21 @@ class SalesDmsClient:
|
||||
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
||||
|
||||
try:
|
||||
cls.copy_items(item_ids=[source], dest_folder_id=dest)
|
||||
except ServiceUnavailableError as exc:
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
||||
if _is_name_conflict(exc.message):
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
return (
|
||||
cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing),
|
||||
True,
|
||||
)
|
||||
raise
|
||||
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
@@ -435,7 +622,7 @@ class SalesDmsClient:
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
return dest_row, False
|
||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=dest_row), False
|
||||
|
||||
@classmethod
|
||||
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/voucher_check/notification.py
|
||||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||
卡片标题为「销售开票附件缺件」,不写业务方代号和批次号;
|
||||
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
|
||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
@@ -47,7 +47,7 @@ def _missing_type_line(item: dict[str, Any]) -> str:
|
||||
|
||||
def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]:
|
||||
"""
|
||||
组装销售开票附件缺件 textcard。
|
||||
组装销售开票附件缺件 textcard,标题为「销售开票附件缺件提醒」。
|
||||
核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节,
|
||||
颜色标签会挤掉后面的缺件类型。
|
||||
|
||||
@@ -62,7 +62,7 @@ def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[s
|
||||
"请尽快补齐。完整清单见详情里的 Excel。",
|
||||
]
|
||||
)
|
||||
return "销售开票附件缺件", body
|
||||
return "销售开票附件缺件提醒", body
|
||||
|
||||
|
||||
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/query_service.py
|
||||
|
||||
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
|
||||
依赖: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。
|
||||
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细可按状态和 invoice 号筛选行,by_file_type 仍是整批;强制重检写入 run_options.mode=force_all。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -545,10 +545,14 @@ def list_run_items(
|
||||
*,
|
||||
run_id: int,
|
||||
result: str | None = None,
|
||||
invoice_no: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
|
||||
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。
|
||||
|
||||
核心逻辑:result 精确匹配状态;invoice_no 按包含、忽略大小写筛行。文件类型汇总不跟着这两个条件缩。
|
||||
"""
|
||||
run = ScheduleRun.query.get(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||
@@ -574,6 +578,12 @@ def list_run_items(
|
||||
result_filter = str(result).strip() if result else ""
|
||||
if result_filter:
|
||||
items = [row for row in items if row.get("result") == result_filter]
|
||||
invoice_filter = str(invoice_no).strip().casefold() if invoice_no else ""
|
||||
if invoice_filter:
|
||||
items = [
|
||||
row for row in items
|
||||
if invoice_filter in str(row.get("invoice_no") or "").casefold()
|
||||
]
|
||||
total = len(items)
|
||||
sliced = items[(page - 1) * page_size : page * page_size]
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user