Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac3fc99883 | ||
|
|
5c6ccf9792 | ||
|
|
993e581135 | ||
|
|
b5fc2c6bb5 | ||
|
|
ec87c1fdaa | ||
|
|
9c7776b5cb | ||
|
|
393a8f6858 | ||
|
|
e35f01bbe9 | ||
|
|
0cc6506c0d | ||
|
|
5412ddc7a8 | ||
|
|
9f2b023a10 | ||
|
|
e750fa8602 | ||
|
|
8a814e7152 | ||
|
|
36f3cdb58c | ||
|
|
a0508de14f | ||
|
|
9376a7c348 | ||
|
|
2df9bdda0d | ||
|
|
387b3157fe | ||
|
|
54a4114daa | ||
|
|
59b37422ab | ||
|
|
89c8da2990 | ||
|
|
0cf3c24119 | ||
|
|
f9f5053f0b | ||
|
|
c4c3cf00ff | ||
|
|
6867aeb90c | ||
|
|
556d3fd3db | ||
|
|
d13c881efb | ||
|
|
161666c0e7 | ||
|
|
876a7ade7d | ||
|
|
42b271f92b | ||
|
|
aba608319a | ||
|
|
9959b06acd | ||
|
|
31591e663e | ||
|
|
5df204fdea | ||
|
|
ae882d5d04 | ||
|
|
453d910364 | ||
|
|
3d3fab9a9f | ||
|
|
13c33d063c | ||
|
|
d0e5c9c57e | ||
|
|
881863478e | ||
|
|
1ba38e1685 | ||
|
|
a06ff79d7c | ||
|
|
34fe0c4d78 | ||
|
|
20835dcfc0 | ||
|
|
f321e2ddd8 | ||
|
|
ab57ab3b1f | ||
|
|
76583c4e5a | ||
|
|
5772ded347 | ||
|
|
6c9fb16496 | ||
|
|
fe8659c62e | ||
|
|
6655ce8309 | ||
|
|
27e3d73cb1 | ||
|
|
85384bc973 | ||
|
|
97cb27c632 | ||
|
|
933ac8ebcc | ||
|
|
697e2c55c0 | ||
|
|
6440889bf6 | ||
|
|
acedbbc3ab | ||
|
|
15c89d1426 | ||
|
|
7fb9022bb7 | ||
|
|
04153b401e | ||
|
|
8593e7970b | ||
|
|
94bddbc8e5 |
No files matched your search
@@ -10,6 +10,8 @@ FLASK_ENV=development
|
||||
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=sync
|
||||
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
|
||||
INTEGRATION_CREDENTIAL_KEY=d8MCilouDvf6ubi-EWM2kZpiYCpH4kU7BSfOtBI0194=
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ FLASK_ENV=production
|
||||
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=rq
|
||||
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
|
||||
INTEGRATION_CREDENTIAL_KEY=YJGD6nLfYUrbzhAlzBJ4xXvyoHw0dIOxDfRIA3xOXWA=
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
@@ -107,6 +109,9 @@ WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
|
||||
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
|
||||
# 进度细化灰度(阶段 5;生产默认开启,回滚时按需关闭,禁止删除审计事实)
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
@@ -134,6 +139,9 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
|
||||
+5
-14
@@ -229,21 +229,15 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值)
|
||||
# 在途仓自动调拨 Agent(来源并发 / 行评估当日有效 24h / 老化阈值);
|
||||
# 外部系统端点与凭据由集成连接器客户端实例管理,不在环境变量中配置。
|
||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=3
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=3
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
|
||||
# 行级新鲜度 TTL:当天评估的行当天可执行;跨日由文件版本对账门禁兜底
|
||||
# (防错看 file_sha256 是否最新,不看墙上时钟),故从确认窗 10 分钟放宽为 24h。
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||
# ERP SOAP 地址与凭据仅由环境/Secret 注入(WSDL 冻结前留空 = fail-closed,禁止写入本文件)
|
||||
# IN_TRANSIT_TRANSFER_ERP_ENDPOINT=
|
||||
# IN_TRANSIT_TRANSFER_ERP_USERNAME=
|
||||
# IN_TRANSIT_TRANSFER_ERP_PASSWORD=
|
||||
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG=
|
||||
# 归档 bucket(MinIO;凭据复用 MINIO_*)
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
|
||||
|
||||
@@ -288,9 +282,6 @@ SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=120
|
||||
SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3
|
||||
SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
|
||||
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
|
||||
# L7 验收完成前禁止开启通用解析与通用自动冻结。
|
||||
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
|
||||
|
||||
@@ -10,6 +10,8 @@ FLASK_ENV=test
|
||||
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=rq
|
||||
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
|
||||
INTEGRATION_CREDENTIAL_KEY=S6LTZXSdli532953J5G90rWxs35plKEph8ds6rh8AKQ=
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/
|
||||
docs/FixedAssets_*.xlsx
|
||||
backend/data/freight_rpa/
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
|
||||
+3
-1
@@ -45,10 +45,12 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
# 注意:勿加 --no-cache-dir,否则 BuildKit 的 /root/.cache/pip 挂载无效,
|
||||
# 每次重建都全量下载 onnxruntime 等大包,镜像源抖动时极易 Read timed out。
|
||||
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
set -eux; \
|
||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||
PIP_ARGS="--retries ${PIP_RETRIES} --timeout ${PIP_TIMEOUT}"; \
|
||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||
fi; \
|
||||
|
||||
@@ -72,6 +72,13 @@ def create_app(config_name='default'):
|
||||
|
||||
register_blueprints(app)
|
||||
|
||||
# 能力声明是代码级契约:组合根在每次 create_app 时显式注册各域能力(幂等),
|
||||
# 保证管理端「能力清单」冷启动即可见,且测试 reset 注册表后建新 app 也能恢复。
|
||||
# 注意用 from-import:`import app.services...` 会把局部名 app 遮蔽成包模块。
|
||||
from app.services.in_transit_transfer import capabilities as _transfer_capabilities
|
||||
|
||||
_transfer_capabilities.register_transfer_capabilities()
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
|
||||
@@ -428,6 +428,21 @@ def get_shipping_inventory_configuration_catalog():
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_movement_fields():
|
||||
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
return _ok([
|
||||
{
|
||||
'code': field.code, 'value_type': str(field.value_type),
|
||||
'required': bool(field.required), 'is_identity': bool(field.is_identity),
|
||||
}
|
||||
for field in MOVEMENT_FIELDS
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
|
||||
@@ -3,8 +3,10 @@ backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
@@ -28,16 +30,22 @@ from app.models import (
|
||||
ContractPaymentContract,
|
||||
ContractPaymentNode,
|
||||
FileAsset,
|
||||
Job,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary, describe_batch_failure, mark_payment_node_paid
|
||||
from app.services.contract_payment.ledger_focus import (
|
||||
LEDGER_FOCUS_VALUES,
|
||||
apply_ledger_focus,
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, normalize_purchase_order_no
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.contract_payment.review_service import apply_manual_review
|
||||
from app.services.contract_payment.sync_service import (
|
||||
build_payment_plan,
|
||||
build_payment_plan_from_bytes,
|
||||
read_contract_attachment_bytes,
|
||||
)
|
||||
|
||||
|
||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||
@@ -151,7 +159,9 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"id": row.id,
|
||||
"contract_no": row.contract_no,
|
||||
"workflow_no": row.workflow_no,
|
||||
"purchase_order_no": row.purchase_order_no,
|
||||
"purchase_order_no": normalize_purchase_order_no(row.purchase_order_no) or None,
|
||||
"company_name": row.company_name,
|
||||
"erp_schema": erp_schema_for_company(row.company_name),
|
||||
"supplier_name": row.supplier_name,
|
||||
"total_amount": str(row.total_amount) if row.total_amount is not None else None,
|
||||
"currency": row.currency,
|
||||
@@ -192,8 +202,9 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"anchor_type": node.anchor_type,
|
||||
"anchor_date": node.anchor_date.isoformat() if node.anchor_date else None,
|
||||
"due_date": node.due_date.isoformat() if node.due_date else None,
|
||||
# ERP apa_file 付款日期;已付款时展示,未付为空。
|
||||
# 付款日期。paid_source=manual 表示人工标记,其余来自 ERP。
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
"paid_source": (node.evidence_json or {}).get("paid_source"),
|
||||
"status": node.status,
|
||||
} for node in nodes],
|
||||
"alerts": [{
|
||||
@@ -354,7 +365,8 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
|
||||
"""
|
||||
下载合同详情中已归档的原文附件。
|
||||
|
||||
核心逻辑:附件必须同时属于请求中的合同和本地 FileAsset,避免通过附件 ID 越权读取其他合同原文。
|
||||
核心逻辑:附件必须属于请求中的合同。本地 FileAsset 仍可读时直接返回;
|
||||
若临时清理已删除对象,则按 OA/DMS 附件 ID 重新下载后再返回。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
@@ -364,20 +376,19 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
|
||||
受控下载的附件二进制流。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同、附件或其保存的文件资产不存在。
|
||||
NotFoundError: 合同或附件不存在,或原文已被清理且无法从原系统重新下载。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
row = db.session.get(ContractPaymentContract, contract_id)
|
||||
attachment = db.session.query(ContractPaymentAttachment).filter_by(id=attachment_id, contract_id=contract_id).first()
|
||||
if not attachment or not attachment.file_asset_id:
|
||||
raise NotFoundError("合同原文附件不存在")
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
if not row or not attachment or not attachment.file_asset_id:
|
||||
raise NotFoundError("合同原文附件不存在")
|
||||
data = read_contract_attachment_bytes(row, attachment)
|
||||
return send_file(
|
||||
BytesIO(read_asset_bytes(asset)),
|
||||
mimetype=attachment.mime_type or asset.mime_type or "application/octet-stream",
|
||||
BytesIO(data),
|
||||
mimetype=attachment.mime_type or "application/octet-stream",
|
||||
as_attachment=True,
|
||||
download_name=attachment.file_name or asset.original_filename,
|
||||
download_name=attachment.file_name or "contract",
|
||||
)
|
||||
|
||||
|
||||
@@ -464,9 +475,55 @@ def enqueue_weekly_alert_send():
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
_CONTRACT_PAYMENT_JOB_TYPES = {
|
||||
JobType.CONTRACT_PAYMENT_SYNC.value,
|
||||
JobType.CONTRACT_PAYMENT_ALERT.value,
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY.value,
|
||||
}
|
||||
|
||||
|
||||
@contract_payment_bp.route("/jobs/<int:job_id>", methods=["GET"])
|
||||
def get_contract_payment_job(job_id: int):
|
||||
"""查询当前管理员提交的合同付款后台任务是否已经跑完。
|
||||
|
||||
核心逻辑:只返回本人创建的合同付款 Job,避免用任务号读到其它域的执行结果。
|
||||
周汇总发送的 result 含 sent / failed,供页面在刷新批次列表前判断这次有没有真正发出。
|
||||
|
||||
Args:
|
||||
job_id: jobs 表主键。
|
||||
|
||||
Returns:
|
||||
标准成功 envelope,含 status、message 与 result。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 任务不存在,或不属于当前管理员的合同付款任务。
|
||||
"""
|
||||
user = _require_contract_payment_admin()
|
||||
row = db.session.get(Job, job_id)
|
||||
if (
|
||||
row is None
|
||||
or row.domain != "procurement_contract"
|
||||
or row.job_type not in _CONTRACT_PAYMENT_JOB_TYPES
|
||||
or row.created_by_id != user.id
|
||||
):
|
||||
raise NotFoundError("任务不存在")
|
||||
return ok({
|
||||
"id": row.id,
|
||||
"status": row.status,
|
||||
"message": row.message,
|
||||
"result": row.result_json or {},
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alert-batches", methods=["GET"])
|
||||
def list_alert_batches():
|
||||
"""查询近期合同付款预警周汇总批次。"""
|
||||
"""查询近期合同付款预警周汇总批次。
|
||||
|
||||
核心逻辑:按创建时间倒序最多返回 100 条。失败批次附带 failure_reasons,
|
||||
供周汇总页点击图标展示;成功批次不返回原因,也不下发企微原始轨迹。
|
||||
Returns:
|
||||
标准成功 envelope,items 含批次摘要;失败项另含 failure_reasons。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
rows = db.session.query(ContractPaymentAlertBatch).order_by(ContractPaymentAlertBatch.created_at.desc()).limit(100).all()
|
||||
return ok({"items": [{
|
||||
@@ -475,6 +532,11 @@ def list_alert_batches():
|
||||
"summary": row.summary_json, "excel_file_name": row.excel_file_name,
|
||||
"excel_file_size": row.excel_file_size, "sent_at": row.sent_at.isoformat() if row.sent_at else None,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"failure_reasons": (
|
||||
describe_batch_failure(row.wecom_trace_json, fallback=row.error_message)
|
||||
if row.status == "failed"
|
||||
else []
|
||||
),
|
||||
} for row in rows]}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@@ -519,8 +581,8 @@ def reparse_contract_attachment(contract_id: int):
|
||||
"""
|
||||
使用已归档的合同原文附件重新生成付款解析结果。
|
||||
|
||||
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;服务端只读取该合同
|
||||
已保存的附件,优先盖章完成合同上传,覆盖付款节点、解析状态和问题列表,不调用 OA。
|
||||
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;优先读取该合同
|
||||
已保存的附件(盖章完成合同上传优先)。原文若已被临时清理删除,则按附件 ID 重新下载后再解析。
|
||||
Args:
|
||||
contract_id: 合同付款台账主键。
|
||||
Returns:
|
||||
@@ -543,12 +605,58 @@ def reparse_contract_attachment(contract_id: int):
|
||||
raise ValidationError("当前合同没有已归档的原文附件,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||
# [STEP 1] 使用同步链路同一附件优先级,保证人工重跑与首次解析的结果可复现。
|
||||
attachment = min(attachments, key=_attachment_parse_priority)
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
raise ValidationError("当前合同原文附件不存在,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=read_asset_bytes(asset))
|
||||
data = read_contract_attachment_bytes(row, attachment)
|
||||
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=data)
|
||||
return ok({
|
||||
"contract": _serialize_contract(row),
|
||||
"parse_result": result,
|
||||
"attachment_name": attachment.file_name,
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/manual-review", methods=["POST"])
|
||||
def manual_review_contract(contract_id: int):
|
||||
"""
|
||||
保存待确认合同的人工复核,并在校验通过后放入合同台账。
|
||||
|
||||
核心逻辑:与单合同重解析一样,持有合同付款 Agent 的用户即可提交,不要求平台管理员。
|
||||
服务层负责比例合计、金额核对和必填日期;本接口只转交请求体并返回更新后的合同。
|
||||
|
||||
Args:
|
||||
contract_id: 合同付款台账主键。
|
||||
|
||||
Returns:
|
||||
标准成功 envelope,含复核后的合同详情。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同不存在。
|
||||
ValidationError: 采购单号、金额、比例或日期不满足进入台账的条件。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
data = request.get_json() or {}
|
||||
row = apply_manual_review(contract_id, data, operator_id=getattr(user, "id", None))
|
||||
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
|
||||
def mark_contract_node_paid(contract_id: int, node_id: int):
|
||||
"""
|
||||
把未付的预付款或出货款手动标为已付。
|
||||
|
||||
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。只改这一阶段,并关闭尚未发送的预警。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
node_id: 付款节点主键。
|
||||
|
||||
Returns:
|
||||
标准成功 envelope,含更新后的合同详情。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同或节点不存在。
|
||||
ValidationError: 阶段不能标记,或付款日期无效。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
data = request.get_json() or {}
|
||||
row = mark_payment_node_paid(contract_id, node_id, data, operator_id=getattr(user, "id", None))
|
||||
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
|
||||
@@ -1,13 +1,19 @@
|
||||
"""backend/app/api/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
||||
Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
|
||||
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
|
||||
D18 废单不废行)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from functools import wraps
|
||||
from typing import Any
|
||||
|
||||
@@ -22,14 +28,24 @@ from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
execute_precheck,
|
||||
get_run,
|
||||
serialize_run_result,
|
||||
prepare_execution,
|
||||
retrigger_document,
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item, manual_close_items
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
restore_matching,
|
||||
)
|
||||
from app.services.in_transit_transfer.retry_service import (
|
||||
requery_items as retry_service_requery_items,
|
||||
requery_items_by_ids,
|
||||
retry_item,
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.retry_service import retry_item
|
||||
from app.services.in_transit_transfer.serializers import (
|
||||
DOCUMENT_STATUS_GROUPS,
|
||||
serialize_executed_order,
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
serialize_summary,
|
||||
@@ -69,13 +85,15 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
return ok(payload, request_id=getattr(g, "request_id", None), status=status)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
|
||||
@in_transit_transfer_bp.route("/matchings", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_precheck_api():
|
||||
"""创建或复用一次调拨预检(只读,不写 ERP)。
|
||||
def create_matching_api():
|
||||
"""创建或复用一次调拨匹配(只读,不写 外部系统)。
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
|
||||
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
||||
"receipt_date_from"/"receipt_date_to"(可选),
|
||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
||||
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
@@ -85,19 +103,29 @@ def create_precheck_api():
|
||||
raise ValidationError("source_codes is required")
|
||||
business_date = str(body.get("business_date") or business_date_now())
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
|
||||
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
|
||||
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_id>", methods=["GET"])
|
||||
@in_transit_transfer_bp.route("/items/executable", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_precheck_api(precheck_id: str):
|
||||
"""恢复预检进度与明细(页面刷新/会话恢复)。"""
|
||||
restored = restore_precheck(precheck_id)
|
||||
def executable_items_api():
|
||||
"""可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。"""
|
||||
return _ok(list_executable_items())
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_matching_api(matching_id: str):
|
||||
"""恢复匹配进度与明细(页面刷新/会话恢复;明细按 scope 实时圈行并装饰行级状态)。"""
|
||||
restored = restore_matching(matching_id, deps=transfer_deps.get_transfer_dependencies())
|
||||
return _ok({
|
||||
"summary": serialize_summary(restored["summary"]),
|
||||
"items": [serialize_item(item) for item in restored["items"]],
|
||||
@@ -105,35 +133,96 @@ def get_precheck_api(precheck_id: str):
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_id>/execute", methods=["POST"])
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_precheck_api(precheck_id: str):
|
||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
||||
|
||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
|
||||
"""
|
||||
def requery_items_api(matching_no: str):
|
||||
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
||||
if invoice_nos is not None and not isinstance(invoice_nos, list):
|
||||
raise ValidationError("invoice_nos must be a list")
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
deps=deps,
|
||||
selected_invoice_nos=invoice_nos,
|
||||
return _ok(retry_service_requery_items(
|
||||
matching_no=matching_no, deps=deps, invoice_nos=invoice_nos,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def download_source_receipt_files_api():
|
||||
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path as _Path
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
|
||||
raise ValidationError("source_codes is required")
|
||||
|
||||
buffer = io.BytesIO()
|
||||
included: list[str] = []
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for code in source_codes:
|
||||
code = str(code or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
|
||||
# 单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
continue
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
|
||||
archive.writestr(f"{code}-{safe_name}", data)
|
||||
included.append(code)
|
||||
if not included:
|
||||
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
|
||||
aggregate_type="in_transit_source",
|
||||
aggregate_id=",".join(included),
|
||||
actor_type="user",
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
actor_display=str(getattr(user, "name", "") or ""),
|
||||
request_id=getattr(g, "request_id", None),
|
||||
result="success",
|
||||
))
|
||||
db.session.commit()
|
||||
buffer.seek(0)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype="application/zip",
|
||||
as_attachment=True,
|
||||
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
|
||||
)
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
"result": serialize_run_result(outcome.result),
|
||||
}, status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
"""恢复 Run 最终结果(页面刷新/会话恢复)。"""
|
||||
"""恢复 Run 结果(页面刷新/会话恢复)。
|
||||
|
||||
返回体:result(单号聚合 + exceptions 既有口径)+ orders 调拨单清单
|
||||
(D9 融合卡数据源:调拨单清单=进度=结果,轮询即恢复最新单态)。
|
||||
"""
|
||||
return _ok(get_run(run_no))
|
||||
|
||||
|
||||
@@ -149,14 +238,14 @@ def cancel_run_api(run_no: str):
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_item_api(item_id: int):
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 外部系统,创建新 Attempt)。
|
||||
|
||||
请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。
|
||||
请求体:{"kind": "external_recheck"}(可选,默认 external_recheck)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
kind = body.get("kind") if isinstance(body, dict) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck"))
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "external_recheck"))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
|
||||
@@ -168,6 +257,300 @@ def manual_close_item_api(item_id: int):
|
||||
return _ok(manual_close_item(item_id=item_id, reason=reason))
|
||||
|
||||
|
||||
def _require_item_ids(body: Any) -> list[int]:
|
||||
"""解析并校验批量操作的 item_ids(非空整数列表)。"""
|
||||
raw = body.get("item_ids") if isinstance(body, dict) else None
|
||||
if not isinstance(raw, list) or not raw:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
try:
|
||||
return [int(x) for x in raw]
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("item_ids must be integers", code="TRANSFER.BATCH_ITEMS_REQUIRED") from exc
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/execute", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_items_api():
|
||||
"""按行提交执行(D8 异步:202 排队,单在提交时已组建,worker 逐单执行)。
|
||||
|
||||
请求体:{"item_ids": [int]}(匹配卡/待执行池勾选的真实明细行 id)。
|
||||
响应:202 envelope,data 为 {"run_no", "status": "queued"}(纯库内毫秒级:
|
||||
两道门禁(存在可执行 + 文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)+
|
||||
建 queued Run + 五元组分组建单 + 一次入队);
|
||||
门禁失败 400,error.details 携带对应 id 列表
|
||||
(invalid_item_ids / changed_item_ids)。
|
||||
进度与结果经 GET /runs/{run_no} 轮询恢复(融合卡数据源)。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = prepare_execution(
|
||||
item_ids=item_ids,
|
||||
deps=deps,
|
||||
actor_id=user.id,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/documents/<doc_no>/retrigger", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retrigger_document_api(run_no: str, doc_no: str):
|
||||
"""人工重新触发 result_unknown 单(D11 唯一出口,禁止关闭重建)。
|
||||
|
||||
语义:复用本单 doc_no/submit_timestamp,只触发末步(D7②,幂等安全);
|
||||
成功后单/行推进成功族并亮出原单号。人工动作,非自动重试。
|
||||
响应:202 envelope,data 为 {"run_no", "doc_no", "status": "queued"};
|
||||
非 result_unknown 单 → 400(TRANSFER.RETRIGGER_NOT_ALLOWED)。
|
||||
"""
|
||||
user = _require_user()
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = retrigger_document(
|
||||
run_no=run_no,
|
||||
doc_no=doc_no,
|
||||
deps=deps,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
return _ok(outcome, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def list_documents_api():
|
||||
"""已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。
|
||||
|
||||
Query:
|
||||
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表);
|
||||
page(默认 1);page_size(默认 20,上限 100)。
|
||||
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
|
||||
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
|
||||
列表 created_at 倒序分页,cancelled 不展示(无产生路径)。
|
||||
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferDocument, TransferInvoiceItem
|
||||
from sqlalchemy import func
|
||||
|
||||
def _parse_date(name: str):
|
||||
"""解析 YYYY-MM-DD 查询参数;空缺省返回 None,非法格式 400。"""
|
||||
raw = (request.args.get(name) or "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(raw, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{name} must be YYYY-MM-DD") from exc
|
||||
|
||||
def _parse_int(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int:
|
||||
"""解析整数查询参数(缺省回默认值;下限钳制必填,上限可选)。"""
|
||||
raw = (request.args.get(name) or "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{name} must be an integer") from exc
|
||||
value = max(minimum, value)
|
||||
if maximum is not None:
|
||||
value = min(maximum, value)
|
||||
return value
|
||||
|
||||
# [STEP 1] 参数校验:status_group 白名单外 400(fail-closed)。
|
||||
status_group = (request.args.get("status_group") or "").strip()
|
||||
if status_group and status_group not in DOCUMENT_STATUS_GROUPS:
|
||||
raise ValidationError(
|
||||
f"status_group must be one of {sorted(DOCUMENT_STATUS_GROUPS)}",
|
||||
)
|
||||
date_from = _parse_date("date_from")
|
||||
date_to = _parse_date("date_to")
|
||||
page = _parse_int("page", 1, minimum=1)
|
||||
page_size = _parse_int("page_size", 20, minimum=1, maximum=100)
|
||||
|
||||
# [STEP 2] 分组计数恒全量:GROUP BY status 对全部单统计,不受任何筛选影响。
|
||||
counts = dict(
|
||||
db.session.query(TransferDocument.status, func.count())
|
||||
.group_by(TransferDocument.status)
|
||||
.all()
|
||||
)
|
||||
groups = {
|
||||
group: sum(counts.get(status, 0) for status in statuses)
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items()
|
||||
}
|
||||
|
||||
# [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表;
|
||||
# cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。
|
||||
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
|
||||
if status_group:
|
||||
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
|
||||
if date_from:
|
||||
query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day))
|
||||
if date_to:
|
||||
window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1)
|
||||
query = query.filter(TransferDocument.created_at < window_end)
|
||||
total = query.count()
|
||||
docs = (
|
||||
query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 4] items 批量查回(防 N+1),按 document_id 分组后逐单投影。
|
||||
doc_ids = [doc.id for doc in docs]
|
||||
items_by_doc: dict[int, list] = {}
|
||||
if doc_ids:
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter(TransferInvoiceItem.document_id.in_(doc_ids))
|
||||
.order_by(TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
items_by_doc.setdefault(row.document_id, []).append(row)
|
||||
|
||||
return _ok({
|
||||
"groups": groups,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"orders": [serialize_executed_order(doc, items_by_doc.get(doc.id, [])) for doc in docs],
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents/<doc_no>/close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def close_document_api(doc_no: str):
|
||||
"""人工关闭失败单(D18:语义=A 废单不废行;首页已执行区块/融合卡共用)。
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可关;result_unknown → 400
|
||||
(D11:结果未知单唯一出口=重新触发,禁止「关闭后重建」双单路径);
|
||||
pending/executing → 400(在飞);原因必填;单不存在 404。
|
||||
行为:doc.status='cancelled' + closed_reason=reason;单内 items 全部脱离
|
||||
(document_id=NULL、status→ready_to_execute、清 result_code/result_message
|
||||
——原路由漂移行由执行期既有守卫重新把关);审计事件(actor/reason/
|
||||
前后状态/行数)。
|
||||
效果:cancelled 不在部分唯一索引未完结集 → 组锁释放,同组可另开新单。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferDocument, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
|
||||
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = str(body.get("reason") or "").strip() if isinstance(body, dict) else ""
|
||||
# [STEP 1] 原因必填(复用人工关闭既有错误码,查重不新增)。
|
||||
if not reason:
|
||||
raise ValidationError(
|
||||
"document close reason is required",
|
||||
code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
|
||||
)
|
||||
doc = TransferDocument.query.filter_by(doc_no=str(doc_no).strip()).first()
|
||||
if doc is None:
|
||||
raise NotFoundError("transfer document not found", code="TRANSFER.DOCUMENT_NOT_FOUND")
|
||||
|
||||
# [STEP 2] 状态门禁:result_unknown 走 retrigger(D11);在飞/已完结单拒绝。
|
||||
if doc.status == "result_unknown":
|
||||
raise ValidationError(
|
||||
"result_unknown order cannot be closed; use retrigger instead (D11)",
|
||||
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
|
||||
)
|
||||
if doc.status not in DOCUMENT_STATUS_GROUPS["failed"]:
|
||||
raise ValidationError(
|
||||
f"order status {doc.status} is not closeable (in-flight or settled)",
|
||||
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
# [STEP 3] D18 行脱离:单内 items 全部脱离单(document_id=NULL)回
|
||||
# ready_to_execute(可重新勾选组建新单),行级结果清空。
|
||||
before_status = doc.status
|
||||
items = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
for item in items:
|
||||
item.document_id = None
|
||||
item.status = ready_status
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
|
||||
# [STEP 4] 单 cancelled + closed_reason 可视留档;组锁随之释放。
|
||||
doc.status = "cancelled"
|
||||
doc.closed_reason = reason
|
||||
|
||||
# [STEP 5] 审计事件(actor/reason/前后状态/行数)后提交。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_DOCUMENT_CLOSED",
|
||||
aggregate_type="transfer_document",
|
||||
aggregate_id=doc.doc_no,
|
||||
run_no=doc.run.run_no if doc.run_id and doc.run else None,
|
||||
actor_type="user",
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
actor_display=str(getattr(user, "name", "") or ""),
|
||||
request_id=getattr(g, "request_id", None),
|
||||
result="success",
|
||||
before={"status": before_status},
|
||||
after={"status": doc.status, "reason": reason, "item_count": len(items)},
|
||||
))
|
||||
db.session.commit()
|
||||
return _ok({"doc_no": doc.doc_no, "status": doc.status, "released_items": len(items)})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents/<doc_no>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_document_api(doc_no: str):
|
||||
"""调拨单级重试(失败单一键恢复主路径)。
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400
|
||||
(D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。
|
||||
行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则
|
||||
自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍
|
||||
阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
"""
|
||||
from app.services.in_transit_transfer.retry_service import retry_document
|
||||
|
||||
user = _require_user()
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_document(
|
||||
doc_no=doc_no, deps=deps,
|
||||
actor_id=user.id if user and user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_requery_items_api():
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(requery_items_by_ids(
|
||||
item_ids=item_ids, deps=deps,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-manual-close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_manual_close_items_api():
|
||||
"""批量人工关闭异常项(原因必填,整批共用;单行隔离)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
return _ok(manual_close_items(
|
||||
item_ids=item_ids, reason=str(body.get("reason") or ""),
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def exceptions_excel_api(run_no: str):
|
||||
@@ -214,8 +597,8 @@ def receipt_files_api(run_no: str):
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
precheck = run.prechecks[0] if run.prechecks else None
|
||||
file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.file_snapshot_json, dict) else {}
|
||||
matching = run.matchings[0] if run.matchings else None
|
||||
file_snapshot = matching.file_snapshot_json if matching and isinstance(matching.file_snapshot_json, dict) else {}
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
@@ -257,10 +640,10 @@ def receipt_files_api(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
|
||||
"""下载本次匹配冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
@@ -270,19 +653,19 @@ def erp_inventory_api(run_no: str):
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"]
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
|
||||
lines.append(",".join([
|
||||
str(item.invoice_no), str(item.source_code), str(item.material_no),
|
||||
str(item.from_warehouse), str(item.to_warehouse),
|
||||
str(item.receipt_quantity), str(item.erp_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.erp_document_no or ""),
|
||||
str(item.receipt_quantity), str(item.external_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.external_document_no or ""),
|
||||
]))
|
||||
data = ("\n".join(lines) + "\n").encode("utf-8")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
|
||||
event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
@@ -297,7 +680,7 @@ def erp_inventory_api(run_no: str):
|
||||
io.BytesIO(data),
|
||||
mimetype="text/csv",
|
||||
as_attachment=True,
|
||||
download_name=f"erp-inventory-{run_no}.csv",
|
||||
download_name=f"external-inventory-{run_no}.csv",
|
||||
)
|
||||
|
||||
|
||||
@@ -315,8 +698,9 @@ def transfer_metrics_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
@@ -414,7 +798,7 @@ def backlog_summary_api():
|
||||
|
||||
|
||||
def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
"""待处理池项序列化。"""
|
||||
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
|
||||
return {
|
||||
'item_id': item.item_id,
|
||||
'source_code': item.source_code,
|
||||
@@ -425,4 +809,12 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
'age_days': item.age_days,
|
||||
'aging_level': item.aging_level,
|
||||
'last_attempt_at': item.last_attempt_at,
|
||||
'receipt_date': item.receipt_date,
|
||||
'material_name': item.material_name,
|
||||
'from_warehouse': item.from_warehouse,
|
||||
'to_warehouse': item.to_warehouse,
|
||||
'lot_no': item.lot_no,
|
||||
'receipt_quantity': item.receipt_quantity,
|
||||
'external_quantity': item.external_quantity,
|
||||
'result_code': item.result_code,
|
||||
}
|
||||
@@ -1,36 +1,80 @@
|
||||
"""api/integration_connector.py
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
|
||||
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto、
|
||||
models.integration_connector.CONNECTOR_TYPES / DB_KINDS(白名单同源)。
|
||||
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
||||
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
||||
客户端实例 connector_type ∈ rest/soap/database;database 时 db_kind 必填且 ∈
|
||||
mysql/oracle/sqlserver/postgresql,非 database 强制置 NULL。
|
||||
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
|
||||
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
|
||||
转移(绑定发布附加就绪门禁:每步接口须已发布且每步客户端启用);绑定以
|
||||
steps_json 有序数组表达一对多配方(每步 interface_code + param_mapping_json),
|
||||
客户端由各步接口归属自带;旧单步字段可合成单元素 steps(兼容窗)。
|
||||
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
||||
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
||||
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
||||
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
|
||||
/api/integration Dify 文件代理)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
IntegrationCall,
|
||||
IntegrationClientInstance,
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities
|
||||
from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS
|
||||
from app.services.integration_connector.capability import list_capabilities
|
||||
from app.services.integration_connector.credential_types import (
|
||||
build_secret_dict,
|
||||
get_credential_type,
|
||||
list_credential_types,
|
||||
visible_fields,
|
||||
)
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.security import (
|
||||
CREDENTIAL_KEY_CONFIG_NAME,
|
||||
_DB_SECRET_CODES,
|
||||
resolve_credential,
|
||||
)
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
||||
|
||||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||||
|
||||
VALID_CONNECTOR_TYPES = ('rest', 'soap')
|
||||
# 与模型 CONNECTOR_TYPES / DB_KINDS 同源,禁止本地另维护一份白名单。
|
||||
VALID_CONNECTOR_TYPES = CONNECTOR_TYPES
|
||||
VALID_DB_KINDS = DB_KINDS
|
||||
VALID_STATUSES = ('draft', 'published', 'retired')
|
||||
VALID_SECRET_PROVIDERS = ('db', 'env')
|
||||
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
|
||||
# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换,
|
||||
# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。
|
||||
VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired')
|
||||
|
||||
# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再
|
||||
# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回;
|
||||
# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。
|
||||
CONFIG_STATUS_TRANSITIONS = {
|
||||
'publish': ('draft', 'published'),
|
||||
'unpublish': ('published', 'draft'),
|
||||
'retire': ('published', 'retired'),
|
||||
'reopen': ('retired', 'draft'),
|
||||
}
|
||||
|
||||
|
||||
def _require(value, field: str) -> None:
|
||||
@@ -39,11 +83,187 @@ def _require(value, field: str) -> None:
|
||||
raise ValidationError(f'{field} is required', details={'field': field})
|
||||
|
||||
|
||||
def _resolve_db_kind(connector_type: str, raw_db_kind) -> str | None:
|
||||
"""按连接器类型解析 db_kind:database 必填且 ∈ VALID_DB_KINDS;其余强制 NULL。
|
||||
|
||||
Args:
|
||||
connector_type: 已校验的连接器类型。
|
||||
raw_db_kind: 请求体中的 db_kind(可为 None/空串)。
|
||||
|
||||
Returns:
|
||||
合法库种字符串,或非 database 时的 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: database 缺省或未知库种(fail-closed,含历史别名 mssql)。
|
||||
"""
|
||||
if connector_type != 'database':
|
||||
return None
|
||||
kind = str(raw_db_kind or '').strip()
|
||||
if not kind:
|
||||
raise ValidationError('db_kind is required for database connector', details={'field': 'db_kind'})
|
||||
if kind not in VALID_DB_KINDS:
|
||||
raise ValidationError(
|
||||
'invalid db_kind',
|
||||
details={'field': 'db_kind', 'allowed': list(VALID_DB_KINDS)},
|
||||
)
|
||||
return kind
|
||||
|
||||
|
||||
def _require_client(code: str) -> IntegrationClientInstance:
|
||||
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise ValidationError(
|
||||
'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND',
|
||||
details={'client_instance_code': code},
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
def _apply_status_transition(entity, action: str, *, kind: str) -> None:
|
||||
"""按转移表校验并落库状态;非法动作或源状态不符即 400。"""
|
||||
transition = CONFIG_STATUS_TRANSITIONS.get(action)
|
||||
if transition is None:
|
||||
raise ValidationError(
|
||||
'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)})
|
||||
src, dst = transition
|
||||
if entity.status != src:
|
||||
raise ValidationError(
|
||||
f'{kind} status is {entity.status}, cannot {action}',
|
||||
code='INTEGRATION.ILLEGAL_STATUS_TRANSITION',
|
||||
details={'action': action, 'from': entity.status, 'to': dst},
|
||||
)
|
||||
entity.status = dst
|
||||
|
||||
|
||||
def _require_interface(code: str) -> IntegrationInterfaceDefinition:
|
||||
"""按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise ValidationError(
|
||||
'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND',
|
||||
details={'interface_definition_code': code},
|
||||
)
|
||||
return iface
|
||||
|
||||
|
||||
def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]:
|
||||
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
||||
|
||||
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
||||
400(fail-fast),不留给调用期 fail-closed。多步绑定时仅用于可选的绑定级
|
||||
client_instance_code 与首步接口的一致性检查。
|
||||
"""
|
||||
client = _require_client(str(client_code).strip())
|
||||
iface = _require_interface(str(interface_code).strip())
|
||||
if iface.client_instance_code != client.code:
|
||||
raise ValidationError(
|
||||
'interface definition does not belong to the selected client instance',
|
||||
code='INTEGRATION.BINDING_PAIR_MISMATCH',
|
||||
details={
|
||||
'client_instance_code': client.code,
|
||||
'interface_definition_code': iface.code,
|
||||
'interface_client_instance_code': iface.client_instance_code,
|
||||
},
|
||||
)
|
||||
return client, iface
|
||||
|
||||
|
||||
def _normalize_binding_steps(body: dict) -> list[dict]:
|
||||
"""校验并归一化绑定 steps_json(非空数组;每步 interface 存在且客户端可用)。
|
||||
|
||||
核心逻辑:优先读 steps_json;缺省时用旧单步字段合成一元素数组(兼容窗)。
|
||||
每步 interface_code 必须存在,其归属客户端必须存在(绑定的客户端实例族);
|
||||
param_mapping_json 须为 dict。返回供落库的 [{interface_code, param_mapping_json}, ...]。
|
||||
|
||||
Args:
|
||||
body: 创建/更新请求体。
|
||||
|
||||
Returns:
|
||||
归一化后的步骤列表(至少一元素)。
|
||||
|
||||
Raises:
|
||||
ValidationError: 空数组、步形状非法、接口不存在、映射非 dict。
|
||||
"""
|
||||
raw = body.get('steps_json')
|
||||
if raw is None:
|
||||
# 兼容窗:旧单步 API 字段 → 单元素 steps
|
||||
iface_code = body.get('interface_definition_code')
|
||||
if not iface_code:
|
||||
raise ValidationError(
|
||||
'steps_json is required',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json'},
|
||||
)
|
||||
raw = [{
|
||||
'interface_code': iface_code,
|
||||
'param_mapping_json': body.get('param_mapping_json') or {},
|
||||
}]
|
||||
if not isinstance(raw, list) or len(raw) == 0:
|
||||
raise ValidationError(
|
||||
'steps_json must be a non-empty array',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json'},
|
||||
)
|
||||
|
||||
normalized: list[dict] = []
|
||||
for idx, step in enumerate(raw):
|
||||
if not isinstance(step, dict):
|
||||
raise ValidationError(
|
||||
'each step must be an object',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json', 'index': idx},
|
||||
)
|
||||
iface_code = step.get('interface_code') or step.get('interface_definition_code')
|
||||
_require(iface_code, f'steps_json[{idx}].interface_code')
|
||||
mapping = step.get('param_mapping_json', step.get('param_mapping', {}))
|
||||
if mapping is None:
|
||||
mapping = {}
|
||||
if not isinstance(mapping, dict):
|
||||
raise ValidationError(
|
||||
'step param_mapping_json must be an object',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json', 'index': idx, 'key': 'param_mapping_json'},
|
||||
)
|
||||
iface = _require_interface(str(iface_code).strip())
|
||||
# 客户端实例族:接口归属客户端必须存在(跨步可不同客户端,如 database+soap)。
|
||||
_require_client(iface.client_instance_code)
|
||||
normalized.append({
|
||||
'interface_code': iface.code,
|
||||
'param_mapping_json': mapping,
|
||||
})
|
||||
|
||||
# 若请求仍带绑定级 client_instance_code,与首步接口做成对校验(防错配镜像列)。
|
||||
binding_client = body.get('client_instance_code')
|
||||
if binding_client is not None and str(binding_client).strip():
|
||||
_validate_binding_pair(binding_client, normalized[0]['interface_code'])
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _mirror_legacy_binding_columns(steps: list[dict]) -> tuple[str, str, dict]:
|
||||
"""由归一化 steps 镜像旧 NOT NULL 列(首步);P2 删列前保持可写。
|
||||
|
||||
Returns:
|
||||
(client_instance_code, interface_definition_code, param_mapping_json)
|
||||
"""
|
||||
first = steps[0]
|
||||
iface = _require_interface(first['interface_code'])
|
||||
return iface.client_instance_code, iface.code, dict(first.get('param_mapping_json') or {})
|
||||
|
||||
|
||||
def _interface_transition(iface, action: str) -> None:
|
||||
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
|
||||
_apply_status_transition(iface, action, kind='interface')
|
||||
|
||||
|
||||
def _serialize_client(client) -> dict:
|
||||
"""客户端实例序列化(含 database 专列 db_kind;非 database 为 null)。"""
|
||||
return {
|
||||
'id': client.id, 'code': client.code, 'name': client.name,
|
||||
'connector_type': client.connector_type, 'environment': client.environment,
|
||||
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
||||
'enabled': client.enabled,
|
||||
}
|
||||
@@ -61,10 +281,12 @@ def _serialize_interface(iface) -> dict:
|
||||
|
||||
|
||||
def _serialize_binding(binding) -> dict:
|
||||
"""绑定序列化:含 steps_json;旧单步列仍回显(P2 删前列镜像)。"""
|
||||
return {
|
||||
'id': binding.id, 'capability': binding.capability,
|
||||
'context_selector_json': binding.context_selector_json or {},
|
||||
'context_source_code': binding.context_source_code,
|
||||
'steps_json': binding.steps_json or [],
|
||||
'param_mapping_json': binding.param_mapping_json or {},
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
'mapping_version': binding.mapping_version, 'priority': binding.priority,
|
||||
@@ -73,15 +295,59 @@ def _serialize_binding(binding) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _decrypted_secret(cred) -> dict:
|
||||
"""db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。"""
|
||||
if cred.secret_provider != 'db' or not cred.secret_ciphertext:
|
||||
return {}
|
||||
try:
|
||||
raw = decrypt_secret(
|
||||
cred.secret_ciphertext,
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
parsed = json.loads(raw)
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
except AppError:
|
||||
return {}
|
||||
|
||||
|
||||
def _serialize_credential(cred) -> dict:
|
||||
secret_dict = _decrypted_secret(cred)
|
||||
return {
|
||||
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
|
||||
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
|
||||
# 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。
|
||||
'secret_fields': visible_fields(cred.credential_type, secret_dict),
|
||||
'has_secret': bool(cred.secret_ciphertext),
|
||||
'version': cred.version, 'status': cred.status,
|
||||
'updated_at': cred.updated_at.isoformat() if cred.updated_at else None,
|
||||
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _apply_db_secret(cred, body) -> None:
|
||||
"""db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。
|
||||
|
||||
类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。
|
||||
"""
|
||||
ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip()
|
||||
if get_credential_type(ctype) is None:
|
||||
raise ValidationError('unknown credential_type', details={'credential_type': ctype})
|
||||
cred.credential_type = ctype
|
||||
current = _decrypted_secret(cred) if cred.secret_ciphertext else {}
|
||||
values: dict = dict(current)
|
||||
for key in (field['key'] for field in get_credential_type(ctype)['fields']):
|
||||
incoming = body.get(key)
|
||||
if incoming is not None and str(incoming) != '':
|
||||
values[key] = str(incoming)
|
||||
merged = build_secret_dict(ctype, values)
|
||||
cred.secret_ciphertext = encrypt_secret(
|
||||
json.dumps(merged, ensure_ascii=False),
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
|
||||
|
||||
def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
return {
|
||||
'status': result.status,
|
||||
@@ -98,7 +364,6 @@ def _result_to_dict(result: IntegrationCallResult) -> dict:
|
||||
@integration_connector_bp.route('/capabilities', methods=['GET'])
|
||||
@require_admin
|
||||
def list_capabilities_endpoint():
|
||||
ensure_capabilities_loaded()
|
||||
data = [{
|
||||
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
|
||||
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
|
||||
@@ -138,6 +403,7 @@ def list_client_instances():
|
||||
@integration_connector_bp.route('/client-instances', methods=['POST'])
|
||||
@require_admin
|
||||
def create_client_instance():
|
||||
"""创建客户端实例;database 类型强制校验 db_kind 四库枚举,非 database 置 NULL。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
connector_type = str(body.get('connector_type') or '').strip()
|
||||
_require(body.get('code'), 'code')
|
||||
@@ -146,11 +412,13 @@ def create_client_instance():
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
|
||||
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
|
||||
db_kind = _resolve_db_kind(connector_type, body.get('db_kind'))
|
||||
client = IntegrationClientInstance(
|
||||
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
||||
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
||||
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
||||
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
||||
db_kind=db_kind,
|
||||
config_json=body.get('config_json') or {},
|
||||
credential_ref_code=body.get('credential_ref_code'),
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
@@ -185,7 +453,10 @@ def delete_client_instance(code):
|
||||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_client_instance(code):
|
||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
|
||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停/db_kind)。
|
||||
|
||||
database 类型必填合法 db_kind;切离 database 时强制清空 db_kind。
|
||||
"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||||
@@ -210,6 +481,9 @@ def update_client_instance(code):
|
||||
client.credential_ref_code = body.get('credential_ref_code')
|
||||
if 'enabled' in body:
|
||||
client.enabled = bool(body.get('enabled', True))
|
||||
# 最终类型决定 db_kind:database 必填合法值;rest/soap 强制 NULL。
|
||||
raw_kind = body['db_kind'] if 'db_kind' in body else client.db_kind
|
||||
client.db_kind = _resolve_db_kind(connector_type, raw_kind)
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_client(client))
|
||||
@@ -231,15 +505,15 @@ def create_interface_definition():
|
||||
code = str(body.get('code') or '').strip()
|
||||
_require(code, 'code')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
connector_type = str(body.get('connector_type') or '')
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
# 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
|
||||
# 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。
|
||||
client = _require_client(str(body['client_instance_code']).strip())
|
||||
status = str(body.get('status') or 'draft')
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code=code, name=str(body.get('name') or code).strip(),
|
||||
client_instance_code=body['client_instance_code'], connector_type=connector_type,
|
||||
client_instance_code=client.code, connector_type=client.connector_type,
|
||||
http_method=(str(body.get('http_method') or '').strip().upper() or None),
|
||||
request_path=(str(body.get('request_path') or '').strip() or None),
|
||||
request_spec_json=body.get('request_spec_json') or {},
|
||||
@@ -247,7 +521,9 @@ def create_interface_definition():
|
||||
response_mapping_json=body.get('response_mapping_json') or {},
|
||||
output_schema_json=body.get('output_schema_json') or {},
|
||||
version=int(body.get('version') or 1), status=status,
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
# enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
|
||||
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
|
||||
enabled=True,
|
||||
)
|
||||
from app import db
|
||||
db.session.add(iface)
|
||||
@@ -258,7 +534,11 @@ def create_interface_definition():
|
||||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_interface_definition(code):
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。
|
||||
|
||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||||
连接器类型由所属客户端实例服务端推导,请求体传值被忽略。
|
||||
"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
@@ -268,12 +548,9 @@ def update_interface_definition(code):
|
||||
iface.name = str(body['name']).strip()
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
iface.client_instance_code = body['client_instance_code']
|
||||
if body.get('connector_type') is not None:
|
||||
connector_type = str(body['connector_type'])
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
iface.connector_type = connector_type
|
||||
client = _require_client(str(body['client_instance_code']).strip())
|
||||
iface.client_instance_code = client.code
|
||||
iface.connector_type = client.connector_type
|
||||
if 'http_method' in body:
|
||||
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
|
||||
if 'request_path' in body:
|
||||
@@ -283,18 +560,52 @@ def update_interface_definition(code):
|
||||
setattr(iface, json_field, body.get(json_field) or {})
|
||||
if body.get('version') is not None:
|
||||
iface.version = int(body.get('version') or 1)
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface.status = status
|
||||
if 'enabled' in body:
|
||||
iface.enabled = bool(body.get('enabled', True))
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ----
|
||||
|
||||
def _do_interface_lifecycle(code: str, action: str):
|
||||
"""动作端点共用体:取接口 → 按转移表转移 → 落库并回显。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
_interface_transition(iface, action)
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_interface_definition(code):
|
||||
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
|
||||
return _do_interface_lifecycle(code, 'publish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
|
||||
@require_admin
|
||||
def unpublish_interface_definition(code):
|
||||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||||
return _do_interface_lifecycle(code, 'unpublish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_interface_definition(code):
|
||||
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
|
||||
return _do_interface_lifecycle(code, 'retire')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>/reopen', methods=['POST'])
|
||||
@require_admin
|
||||
def reopen_interface_definition(code):
|
||||
"""恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。"""
|
||||
return _do_interface_lifecycle(code, 'reopen')
|
||||
|
||||
|
||||
# ---- Binding ----
|
||||
|
||||
@integration_connector_bp.route('/bindings', methods=['GET'])
|
||||
@@ -307,23 +618,26 @@ def list_bindings():
|
||||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_binding():
|
||||
"""创建绑定:校验 steps_json 后落库;新建固定落 draft,发布走 /publish 动作端点。
|
||||
|
||||
核心逻辑:归一化 steps → 镜像首步到旧列(NOT NULL)→ 落 draft。
|
||||
仍接受旧单步字段(无 steps_json 时合成一元素数组)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('capability'), 'capability')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
status = str(body.get('status') or 'draft')
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
steps = _normalize_binding_steps(body)
|
||||
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||
binding = IntegrationBinding(
|
||||
capability=body['capability'],
|
||||
context_selector_json=body.get('context_selector_json') or {},
|
||||
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
|
||||
client_instance_code=body['client_instance_code'],
|
||||
interface_definition_code=body['interface_definition_code'],
|
||||
steps_json=steps,
|
||||
param_mapping_json=param_mapping,
|
||||
client_instance_code=client_code,
|
||||
interface_definition_code=iface_code,
|
||||
mapping_version=int(body.get('mapping_version') or 1),
|
||||
priority=int(body.get('priority') or 0),
|
||||
environment=str(body.get('environment') or 'prod').strip(),
|
||||
status=status,
|
||||
status='draft',
|
||||
)
|
||||
from app import db
|
||||
db.session.add(binding)
|
||||
@@ -334,7 +648,15 @@ def create_binding():
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_binding(binding_id):
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
|
||||
"""更新绑定(可改 context / steps_json / 映射版本 / 优先级 / 环境 / 生效区间)。
|
||||
|
||||
状态不在此改写(须经动作端点按转移表流转)。规则(评审修正轮收紧后):
|
||||
[1] steps_json 与旧单步字段(interface_definition_code/param_mapping_json)同 PUT
|
||||
属矛盾载荷 → 400(旧键会被静默忽略、部分生效无提示);
|
||||
[2] 三把旧钥匙(interface_definition_code/param_mapping_json/client_instance_code)
|
||||
任一出现在多步绑定 PUT → 400(兼容窗会合成单元素 steps 回写、静默销毁第 2..n 步);
|
||||
[3] 单步绑定的旧字段 PUT 走兼容窗(换绑接口 / 仅更新首步映射);纯 steps_json PUT 不受限。
|
||||
"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
@@ -345,14 +667,83 @@ def update_binding(binding_id):
|
||||
binding.capability = body['capability']
|
||||
if 'context_selector_json' in body:
|
||||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||||
if 'context_source_code' in body:
|
||||
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
binding.client_instance_code = body['client_instance_code']
|
||||
if body.get('interface_definition_code') is not None:
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
binding.interface_definition_code = body['interface_definition_code']
|
||||
|
||||
if 'steps_json' in body:
|
||||
# 评审 P2-2:矛盾载荷 fail-fast——steps_json 分支本会静默忽略旧单步键(部分生效无提示)。
|
||||
# client_instance_code 不在矛盾集:它在 steps_json 分支仍被消费(首步成对校验)。
|
||||
conflicts = sorted(
|
||||
key for key in ('interface_definition_code', 'param_mapping_json') if key in body
|
||||
)
|
||||
if conflicts:
|
||||
raise ValidationError(
|
||||
'steps_json PUT cannot carry legacy single-step fields; they would be silently ignored',
|
||||
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
|
||||
details={
|
||||
'fields': conflicts,
|
||||
'conflicting_with': 'steps_json',
|
||||
'hint': 'submit the full ordered recipe via steps_json only',
|
||||
},
|
||||
)
|
||||
merge_body = {
|
||||
'steps_json': body['steps_json'],
|
||||
'client_instance_code': body.get('client_instance_code'),
|
||||
}
|
||||
steps = _normalize_binding_steps(merge_body)
|
||||
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||
binding.steps_json = steps
|
||||
binding.client_instance_code = client_code
|
||||
binding.interface_definition_code = iface_code
|
||||
binding.param_mapping_json = param_mapping
|
||||
elif 'interface_definition_code' in body or 'client_instance_code' in body or 'param_mapping_json' in body:
|
||||
# 评审 P1 守卫:三把旧钥匙(含 client_instance_code)任一出现在多步绑定 PUT,
|
||||
# 都会经兼容窗用旧单步列合成单元素 steps 回写、静默销毁第 2..n 步 → fail-fast 400。
|
||||
legacy_keys = sorted(
|
||||
key for key in ('interface_definition_code', 'param_mapping_json', 'client_instance_code')
|
||||
if key in body
|
||||
)
|
||||
if binding.steps_json and len(binding.steps_json) > 1:
|
||||
raise ValidationError(
|
||||
'legacy single-step fields cannot update a multi-step binding; use steps_json',
|
||||
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
|
||||
details={
|
||||
'fields': legacy_keys,
|
||||
'steps_count': len(binding.steps_json),
|
||||
'hint': 'submit the full ordered recipe via steps_json',
|
||||
},
|
||||
)
|
||||
# 兼容窗:旧单步字段 → 重写/局部更新 steps
|
||||
if (
|
||||
'param_mapping_json' in body
|
||||
and 'interface_definition_code' not in body
|
||||
and 'client_instance_code' not in body
|
||||
and binding.steps_json
|
||||
):
|
||||
steps = [dict(s) if isinstance(s, dict) else s for s in binding.steps_json]
|
||||
first = dict(steps[0])
|
||||
first['param_mapping_json'] = body.get('param_mapping_json') or {}
|
||||
steps[0] = first
|
||||
steps = _normalize_binding_steps({
|
||||
'steps_json': steps,
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
})
|
||||
else:
|
||||
steps = _normalize_binding_steps({
|
||||
'interface_definition_code': body.get(
|
||||
'interface_definition_code', binding.interface_definition_code,
|
||||
),
|
||||
'client_instance_code': body.get(
|
||||
'client_instance_code', binding.client_instance_code,
|
||||
),
|
||||
'param_mapping_json': body.get(
|
||||
'param_mapping_json', binding.param_mapping_json or {},
|
||||
),
|
||||
})
|
||||
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||
binding.steps_json = steps
|
||||
binding.client_instance_code = client_code
|
||||
binding.interface_definition_code = iface_code
|
||||
binding.param_mapping_json = param_mapping
|
||||
|
||||
if body.get('mapping_version') is not None:
|
||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||
if body.get('priority') is not None:
|
||||
@@ -363,16 +754,95 @@ def update_binding(binding_id):
|
||||
binding.effective_from = body['effective_from'] or None
|
||||
if body.get('effective_to') is not None:
|
||||
binding.effective_to = body['effective_to'] or None
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
binding.status = status
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
# ---- 绑定生命周期(状态只经动作端点按转移表流转) ----
|
||||
|
||||
def _do_binding_lifecycle(binding_id: int, action: str):
|
||||
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
||||
|
||||
发布(publish)附加就绪门禁:steps_json 每步接口须已发布、每步客户端须启用,
|
||||
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
||||
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
||||
"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||||
if action == 'publish':
|
||||
raw_steps = list(binding.steps_json or [])
|
||||
if not raw_steps and binding.interface_definition_code:
|
||||
raw_steps = [{
|
||||
'interface_code': binding.interface_definition_code,
|
||||
'param_mapping_json': binding.param_mapping_json or {},
|
||||
}]
|
||||
if not raw_steps:
|
||||
raise ValidationError(
|
||||
'binding target not ready: steps_json is empty',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={'steps_json': []},
|
||||
)
|
||||
for idx, step in enumerate(raw_steps):
|
||||
if not isinstance(step, dict):
|
||||
raise ValidationError(
|
||||
'binding target not ready: invalid step',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={'index': idx},
|
||||
)
|
||||
iface_code = str(step.get('interface_code') or '').strip()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
|
||||
client = (
|
||||
IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
|
||||
if iface is not None else None
|
||||
)
|
||||
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
||||
raise ValidationError(
|
||||
'binding target not ready: each step interface must be published '
|
||||
'and client instance enabled',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={
|
||||
'index': idx,
|
||||
'interface_code': iface_code,
|
||||
'client_instance_code': getattr(iface, 'client_instance_code', None),
|
||||
'iface_status': getattr(iface, 'status', None),
|
||||
'client_enabled': getattr(client, 'enabled', None),
|
||||
},
|
||||
)
|
||||
_apply_status_transition(binding, action, kind='binding')
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_binding(binding_id):
|
||||
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
|
||||
return _do_binding_lifecycle(binding_id, 'publish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
|
||||
@require_admin
|
||||
def unpublish_binding(binding_id):
|
||||
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
|
||||
return _do_binding_lifecycle(binding_id, 'unpublish')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_binding(binding_id):
|
||||
"""退役(published → retired):绑定退出自动调用。"""
|
||||
return _do_binding_lifecycle(binding_id, 'retire')
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>/reopen', methods=['POST'])
|
||||
@require_admin
|
||||
def reopen_binding(binding_id):
|
||||
"""恢复为草稿(retired → draft):重新走发布流程。"""
|
||||
return _do_binding_lifecycle(binding_id, 'reopen')
|
||||
|
||||
|
||||
# ---- 凭据引用 ----
|
||||
|
||||
@integration_connector_bp.route('/credential-references', methods=['GET'])
|
||||
@@ -385,41 +855,87 @@ def list_credential_references():
|
||||
@integration_connector_bp.route('/credential-references', methods=['POST'])
|
||||
@require_admin
|
||||
def create_credential_reference():
|
||||
"""创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('code'), 'code')
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
from app import db
|
||||
# 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。
|
||||
provider = str(body.get('secret_provider') or 'env').strip()
|
||||
if provider not in VALID_SECRET_PROVIDERS:
|
||||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||||
code = str(body['code']).strip()
|
||||
if IntegrationCredentialReference.query.filter_by(code=code).first():
|
||||
raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT')
|
||||
status = str(body.get('status') or 'active')
|
||||
if status not in ('active', 'rotating', 'retired'):
|
||||
raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']})
|
||||
cred = IntegrationCredentialReference(
|
||||
code=str(body['code']).strip(),
|
||||
secret_ref=str(body['secret_ref']).strip(),
|
||||
secret_provider=str(body.get('secret_provider') or 'env').strip(),
|
||||
code=code,
|
||||
secret_ref=str(body.get('secret_ref') or '').strip(),
|
||||
secret_provider=provider,
|
||||
credential_type=str(body.get('credential_type') or 'password').strip(),
|
||||
version=int(body.get('version') or 1),
|
||||
status=str(body.get('status') or 'active'),
|
||||
status=status,
|
||||
)
|
||||
if provider == 'db':
|
||||
_apply_db_secret(cred, body)
|
||||
cred.secret_ref = f'db:{code}'
|
||||
else:
|
||||
_require(cred.secret_ref, 'secret_ref')
|
||||
from app import db
|
||||
db.session.add(cred)
|
||||
db.session.commit()
|
||||
# 永不回显真实凭据值;只回元数据。
|
||||
# 永不回显真实凭据值;只回元数据与非密字段。
|
||||
return ok(_serialize_credential(cred), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/types', methods=['GET'])
|
||||
@require_admin
|
||||
def list_credential_type_specs():
|
||||
"""凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。"""
|
||||
return ok(list_credential_types())
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_credential_reference(code):
|
||||
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
|
||||
"""更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。"""
|
||||
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
|
||||
if cred is None:
|
||||
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if body.get('secret_provider') is not None:
|
||||
cred.secret_provider = str(body['secret_provider']).strip()
|
||||
if body.get('credential_type') is not None:
|
||||
cred.credential_type = str(body['credential_type']).strip()
|
||||
provider = str(body['secret_provider']).strip()
|
||||
if provider not in VALID_SECRET_PROVIDERS:
|
||||
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
|
||||
cred.secret_provider = provider
|
||||
if provider == 'env':
|
||||
# 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。
|
||||
cred.secret_ciphertext = None
|
||||
field_keys = tuple(
|
||||
field['key'] for field in (get_credential_type(
|
||||
str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []}
|
||||
)['fields']
|
||||
)
|
||||
has_secret_input = any(body.get(key) is not None for key in field_keys)
|
||||
if cred.secret_provider == 'db':
|
||||
if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext:
|
||||
_apply_db_secret(cred, body)
|
||||
cred.secret_ref = f'db:{cred.code}'
|
||||
else:
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if has_secret_input:
|
||||
raise ValidationError('credential fields only apply to db credentials')
|
||||
if body.get('status') is not None:
|
||||
cred.status = str(body['status']).strip()
|
||||
# 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道);
|
||||
# rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active),
|
||||
# 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。
|
||||
status = str(body['status']).strip()
|
||||
if status not in VALID_CREDENTIAL_UI_STATUSES:
|
||||
raise ValidationError(
|
||||
'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)})
|
||||
cred.status = status
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_credential(cred))
|
||||
@@ -430,6 +946,11 @@ def update_credential_reference(code):
|
||||
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_connection(code):
|
||||
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
||||
|
||||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds/db_kind
|
||||
独立列拼回 config_json 后再交给 transport,否则存独立列的地址/库种会被误判为未冻结。
|
||||
"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found')
|
||||
@@ -439,9 +960,103 @@ def test_connection(code):
|
||||
raise ValidationError(
|
||||
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
|
||||
)
|
||||
raw = transport.call(
|
||||
client={'config_json': client.config_json or {}, 'credential': {}},
|
||||
interface={'request_spec_json': {}},
|
||||
request={},
|
||||
)
|
||||
return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw})
|
||||
client_payload = {
|
||||
'config_json': merge_client_config({
|
||||
'config_json': client.config_json or {},
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
}),
|
||||
# 连接测试按设计须证明「网络与认证」可用(数据库直连无凭据无法建连):
|
||||
# 有凭据引用时解析真实凭据(db 解密 / env 注入,与 engine 调用链同源),
|
||||
# 无引用(匿名)为空 dict;解析失败 fail-closed 抛 CredentialUnresolvedError。
|
||||
'credential': resolve_credential(client.credential_ref_code) if client.credential_ref_code else {},
|
||||
}
|
||||
probe = getattr(transport, 'probe', None)
|
||||
if probe is not None:
|
||||
raw = probe(client=client_payload)
|
||||
ok_flag = bool(raw.get('ok'))
|
||||
else:
|
||||
# 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。
|
||||
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
||||
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
||||
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
||||
|
||||
|
||||
# ---- 集成调用日志查询 ----
|
||||
|
||||
@integration_connector_bp.route('/calls', methods=['GET'])
|
||||
@require_admin
|
||||
def list_integration_calls_api():
|
||||
"""集成调用日志分页查询(能力无关通用口径)。
|
||||
|
||||
筛选:capability/interface_code/client_code/connector_type/status/
|
||||
operation_id/trace_id/business_ref 精确;keyword 对请求摘要 JSON 文本模糊;
|
||||
date_from/date_to=YYYY-MM-DD(按 created_at 闭区间,date_to 补全天)。
|
||||
"""
|
||||
from sqlalchemy import cast, String
|
||||
|
||||
args = request.args
|
||||
query = IntegrationCall.query
|
||||
for field in ('capability', 'status', 'operation_id', 'trace_id', 'business_ref'):
|
||||
value = (args.get(field) or '').strip()
|
||||
if value:
|
||||
query = query.filter(getattr(IntegrationCall, field) == value)
|
||||
for json_field in ('interface_code', 'client_code', 'connector_type'):
|
||||
value = (args.get(json_field) or '').strip()
|
||||
if value:
|
||||
query = query.filter(
|
||||
IntegrationCall.binding_snapshot_json[json_field].as_string() == value)
|
||||
keyword = (args.get('keyword') or '').strip()
|
||||
if keyword:
|
||||
query = query.filter(
|
||||
cast(IntegrationCall.request_summary_json, String).ilike(f'%{keyword}%'))
|
||||
date_from = (args.get('date_from') or '').strip()
|
||||
if date_from:
|
||||
query = query.filter(IntegrationCall.created_at >= f'{date_from} 00:00:00')
|
||||
date_to = (args.get('date_to') or '').strip()
|
||||
if date_to:
|
||||
query = query.filter(IntegrationCall.created_at <= f'{date_to} 23:59:59.999999')
|
||||
|
||||
page = max(int(args.get('page') or 1), 1)
|
||||
page_size = min(max(int(args.get('page_size') or 20), 1), 100)
|
||||
total = query.count()
|
||||
rows = (query.order_by(IntegrationCall.id.desc())
|
||||
.offset((page - 1) * page_size).limit(page_size).all())
|
||||
|
||||
def _row(c: IntegrationCall) -> dict:
|
||||
snap = c.binding_snapshot_json or {}
|
||||
return {'id': c.id, 'created_at': c.created_at.isoformat() if c.created_at else None,
|
||||
'capability': c.capability, 'operation_id': c.operation_id,
|
||||
'trace_id': c.trace_id, 'status': c.status, 'elapsed_ms': c.elapsed_ms,
|
||||
'business_ref': c.business_ref,
|
||||
'client_code': snap.get('client_code'), 'interface_code': snap.get('interface_code'),
|
||||
'connector_type': snap.get('connector_type'),
|
||||
'step_index': snap.get('step_index'), 'step_count': snap.get('step_count')}
|
||||
|
||||
return ok({'total': total, 'page': page, 'page_size': page_size,
|
||||
'items': [_row(c) for c in rows]})
|
||||
|
||||
|
||||
@integration_connector_bp.route('/calls/<int:call_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_integration_call_api(call_id: int):
|
||||
"""单条全量(含 wire_json/request/response/绑定快照)+ 同 operation_id 步骤时间线。"""
|
||||
call = IntegrationCall.query.get(call_id)
|
||||
if call is None:
|
||||
raise NotFoundError('integration call not found', code='INTEGRATION.CALL_NOT_FOUND')
|
||||
full = {'id': call.id, 'created_at': call.created_at.isoformat() if call.created_at else None,
|
||||
'capability': call.capability, 'operation_id': call.operation_id,
|
||||
'trace_id': call.trace_id, 'status': call.status, 'elapsed_ms': call.elapsed_ms,
|
||||
'business_ref': call.business_ref,
|
||||
'binding_snapshot_json': call.binding_snapshot_json or {},
|
||||
'request_summary_json': call.request_summary_json or {},
|
||||
'response_summary_json': call.response_summary_json or {},
|
||||
'wire_json': call.wire_json}
|
||||
siblings = (IntegrationCall.query.filter_by(operation_id=call.operation_id)
|
||||
.order_by(IntegrationCall.id.asc()).all())
|
||||
timeline = [{'id': c.id, 'step_index': (c.binding_snapshot_json or {}).get('step_index'),
|
||||
'step_count': (c.binding_snapshot_json or {}).get('step_count'),
|
||||
'interface_code': (c.binding_snapshot_json or {}).get('interface_code'),
|
||||
'status': c.status, 'elapsed_ms': c.elapsed_ms} for c in siblings]
|
||||
return ok({'call': full, 'timeline': timeline})
|
||||
@@ -255,6 +255,8 @@ class Config:
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
# 集成连接器凭据密文的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
|
||||
INTEGRATION_CREDENTIAL_KEY = os.getenv('INTEGRATION_CREDENTIAL_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
@@ -282,27 +284,14 @@ class Config:
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
|
||||
# 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。
|
||||
# 在途仓自动调拨(独立业务模块)参数;外部系统端点/凭据由集成连接器客户端实例管理。
|
||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2'))
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2'))
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1'))
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
|
||||
# ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。
|
||||
IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip()
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
|
||||
@@ -498,7 +487,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_overseas_thailand_guidelines')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||
@@ -659,7 +648,9 @@ class Config:
|
||||
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
# 订单抽取发送后选择计划预算:首轮只挑最相关附件,后续批次按固定预算待扩展。
|
||||
# 订单抽取发送后选择计划预算:合格附件全量入选批次 1,有多少单解析多少单;
|
||||
# 唯一生效的选择预算是 MAX_TOTAL_BYTES(超限转 Review)。数量类字段仅作快照
|
||||
# 审计记录,不再截断;总量由 EML 层(每封 20)与单次上传 intake 数兜底。
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', '2')
|
||||
)
|
||||
@@ -670,7 +661,7 @@ class Config:
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', '2')
|
||||
)
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '6')
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '20')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv(
|
||||
@@ -768,6 +759,8 @@ class ProductionConfig(Config):
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
# 钉住测试 TTL 语义(陈旧行门禁用例按 600s 书写),不随开发者 .env.shared 漂移。
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = 600
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""app/core/credential_crypto.py
|
||||
|
||||
用途:通用 Fernet 凭据加解密(主密钥只来自 Flask config 的环境注入键,绝不落库明文)。
|
||||
依赖:cryptography.fernet、Flask current_app、app.core.errors。
|
||||
逻辑:调用方通过 CredentialCryptoErrorCodes 提供各自的业务错误码;主密钥缺失/无效时
|
||||
fail-closed 拒绝加密,避免产生不可恢复密文。shipping_notice(RPA Profile)与
|
||||
integration_connector(凭据引用)共用本模块,仅密钥键名与错误码不同。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CredentialCryptoErrorCodes:
|
||||
"""加解密失败的错误码集合(按调用方业务域自定义)。"""
|
||||
|
||||
key_missing: str
|
||||
key_invalid: str
|
||||
secret_empty: str
|
||||
secret_missing: str
|
||||
secret_invalid: str
|
||||
|
||||
|
||||
def _fernet(key_config_name: str, codes: CredentialCryptoErrorCodes) -> Fernet:
|
||||
"""从 Flask config 读取主密钥并构造加密器;缺失/无效即 fail-closed。"""
|
||||
key = str(current_app.config.get(key_config_name) or '').strip()
|
||||
if not key:
|
||||
raise ServiceUnavailableError(
|
||||
f'{key_config_name} is not configured',
|
||||
code=codes.key_missing,
|
||||
)
|
||||
try:
|
||||
return Fernet(key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
f'{key_config_name} is invalid',
|
||||
code=codes.key_invalid,
|
||||
) from exc
|
||||
|
||||
|
||||
def encrypt_secret(value: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
|
||||
"""加密单个凭据字段以便持久化;调用方不得记录明文。"""
|
||||
plaintext = str(value or '')
|
||||
if not plaintext:
|
||||
raise ValidationError('credential must not be empty', code=codes.secret_empty)
|
||||
return _fernet(key_config_name, codes).encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_secret(ciphertext: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
|
||||
"""在受控运行时解密密文;仅供当次调用内存使用,禁止落日志/响应。"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('credential ciphertext is missing', code=codes.secret_missing)
|
||||
try:
|
||||
return _fernet(key_config_name, codes).decrypt(value.encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeDecodeError) as exc:
|
||||
raise ValidationError('credential ciphertext is invalid', code=codes.secret_invalid) from exc
|
||||
@@ -9,7 +9,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
contract_payment,
|
||||
file_check_run,
|
||||
in_transit_transfer_item,
|
||||
in_transit_transfer_precheck,
|
||||
in_transit_transfer_match,
|
||||
in_transit_transfer_run,
|
||||
kb_clean,
|
||||
kb_dify_sync,
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
|
||||
用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。
|
||||
依赖:execution_service.execute_item、transfer deps、Job 注册表。
|
||||
逻辑:payload 携带 item_id;单项结果不影响其他项。
|
||||
逻辑:payload 携带 item_id;单项结果不影响其他项。业务收尾后 handler 自行
|
||||
finish_job(runner 仅兜底异常路径,正常完成不代收口)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.execution_service import execute_item
|
||||
|
||||
@@ -23,7 +27,16 @@ def run_in_transit_transfer_item(_ctx, payload: dict) -> None:
|
||||
item_id = payload.get("item_id")
|
||||
if item_id is None:
|
||||
raise RuntimeError("missing_transfer_item_id")
|
||||
execute_item(
|
||||
# 领取代次快照:finish_job 条件 UPDATE 需与领取时一致,防止超时重领后错收新代次。
|
||||
job_row = db.session.get(Job, int(payload["job_id"])) if payload.get("job_id") else None
|
||||
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||
status = execute_item(
|
||||
item_id=int(item_id),
|
||||
deps=transfer_deps.get_transfer_dependencies(),
|
||||
)
|
||||
if job_row is not None:
|
||||
finish_job(
|
||||
int(job_row.id),
|
||||
message=f"调拨单行执行完成:item_id={item_id} status={status}",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""backend/app/jobs/handlers/in_transit_transfer_match.py
|
||||
|
||||
用途:异步执行在途调拨匹配(文件准备 + 只读匹配),并更新匹配状态。
|
||||
依赖:Job 注册表、matching_service、transfer 模型、transfer deps。
|
||||
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
|
||||
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后
|
||||
handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, TransferMatching
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.matching_service import run_matching
|
||||
|
||||
|
||||
@register_handler(JobType.TRANSFER_MATCH)
|
||||
def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||
"""执行一次匹配 Job 并更新匹配状态。
|
||||
|
||||
【AI 触发时机】:仅由匹配创建异步路径入队;页面直连走 API 同步路径。
|
||||
"""
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
matching_no = str(payload.get("matching_id") or "").strip()
|
||||
if not matching_no:
|
||||
raise RuntimeError("missing_transfer_matching_id")
|
||||
matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise RuntimeError(f"missing_transfer_matching: {matching_no}")
|
||||
# 领取代次快照:finish_job 条件 UPDATE 需与领取时一致,防止超时重领后错收新代次。
|
||||
job_row = db.session.get(Job, int(payload["job_id"])) if payload.get("job_id") else None
|
||||
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
business_date=matching.business_date,
|
||||
deps=deps,
|
||||
run_no=matching.run.run_no if matching.run else "RUN-PENDING",
|
||||
# 类型范围随匹配落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
||||
)
|
||||
summary = result.summary
|
||||
matching.status = summary.status
|
||||
matching.counts_json = {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
}
|
||||
matching.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||
matching.estimated_external_write_count = summary.estimated_external_write_count
|
||||
matching.matching_hash = summary.matching_hash
|
||||
db.session.commit()
|
||||
if job_row is not None:
|
||||
finish_job(
|
||||
int(job_row.id),
|
||||
message=f"调拨匹配完成:matching={matching_no} status={summary.status}",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -1,55 +0,0 @@
|
||||
"""backend/app/jobs/handlers/in_transit_transfer_precheck.py
|
||||
|
||||
用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。
|
||||
依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。
|
||||
逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写
|
||||
状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import TransferPrecheck
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.precheck_service import run_precheck
|
||||
|
||||
|
||||
@register_handler(JobType.TRANSFER_PRECHECK)
|
||||
def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
||||
"""执行一次预检 Job 并更新预检状态。
|
||||
|
||||
【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。
|
||||
"""
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
precheck_no = str(payload.get("precheck_id") or "").strip()
|
||||
if not precheck_no:
|
||||
raise RuntimeError("missing_transfer_precheck_id")
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first()
|
||||
if precheck is None:
|
||||
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance(
|
||||
precheck.scope_json, dict
|
||||
) else []
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=precheck.business_date,
|
||||
deps=deps,
|
||||
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
|
||||
)
|
||||
summary = result.summary
|
||||
precheck.status = summary.status
|
||||
precheck.counts_json = {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"prechecked_count": summary.counts.prechecked_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
}
|
||||
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||
precheck.estimated_erp_write_count = summary.estimated_erp_write_count
|
||||
precheck.precheck_hash = summary.precheck_hash
|
||||
db.session.commit()
|
||||
@@ -1,29 +1,49 @@
|
||||
"""backend/app/jobs/handlers/in_transit_transfer_run.py
|
||||
|
||||
用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。
|
||||
依赖:execution_service、transfer deps、Job 注册表。
|
||||
逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。
|
||||
用途:Run 级执行 Job:领取 TRANSFER_RUN 任务并驱动执行服务 worker 段完成单据级写入。
|
||||
依赖:execution_service.execute_run、transfer deps、Job 注册表。
|
||||
逻辑:payload {run_id, item_ids} 为常规路径(worker 执行 Run 名下全部单);
|
||||
{run_id, doc_id} 为 retrigger 路径(D11:result_unknown 单唯一出口,仅执行
|
||||
该单且只触发末步);门禁/组复用守卫由 prepare_execution 前置完成,二次门禁
|
||||
由 execute_run 统一裁定(fail-closed)。业务收尾后 handler 须自行 finish_job
|
||||
(runner 仅兜底异常路径,正常完成不代收口)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.execution_service import execute_run
|
||||
|
||||
|
||||
@register_handler(JobType.TRANSFER_RUN)
|
||||
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
|
||||
"""执行一个 Run(异步路径)。
|
||||
"""执行 Run 名下全部单(或 retrigger 指定单)(异步路径)。
|
||||
|
||||
【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。
|
||||
【AI 触发时机】:仅由 prepare_execution(提交建单后)与 retrigger_document
|
||||
(人工重新触发)入队路径调用;页面直连走 API 同步段,不经过本 handler。
|
||||
"""
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
if not precheck_id:
|
||||
raise RuntimeError("missing_transfer_precheck_id")
|
||||
execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
run_id = str(payload.get("run_id") or "").strip()
|
||||
if not run_id:
|
||||
raise RuntimeError("missing_transfer_run_id")
|
||||
doc_id = str(payload.get("doc_id") or "").strip()
|
||||
# 领取代次快照:finish_job 条件 UPDATE 需与领取时一致,防止超时重领后错收新代次。
|
||||
job_row = db.session.get(Job, int(payload["job_id"])) if payload.get("job_id") else None
|
||||
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||
status = execute_run(
|
||||
run_id=int(run_id),
|
||||
deps=transfer_deps.get_transfer_dependencies(),
|
||||
doc_id=int(doc_id) if doc_id else None,
|
||||
skip_write_recheck=bool(payload.get("skip_write_recheck")),
|
||||
)
|
||||
if job_row is not None:
|
||||
finish_job(
|
||||
int(job_row.id),
|
||||
message=f"调拨单执行完成:run_id={run_id} status={status}",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -724,6 +724,33 @@ def _handoff_continue_order_extraction(
|
||||
return True
|
||||
|
||||
|
||||
def _is_transient_lock_error(exc: BaseException) -> bool:
|
||||
"""
|
||||
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
||||
|
||||
【AI 触发时机】:订单抽取 Job 异常收口时决定是否标记可重试。此类错误重试即可恢复,
|
||||
按终态失败收口会触发 run failed 并要求人工重新识别(2026-09-22 生产事故两次)。
|
||||
|
||||
需要穿透两层包装:①SQLAlchemy 将 DBAPI 错误挂在 exc.orig;②若失败后同一事务里
|
||||
还有后续语句,SQLAlchemy 会改抛 PendingRollbackError(无 .orig,原文内嵌在 message),
|
||||
或经 __cause__ 链包装。沿 orig/__cause__ 链遍历并对消息做特征匹配,确保包装后的
|
||||
死锁仍被判为瞬时(2026-09-24 test job 8840:同类死锁因分类漏判而一次判死)。
|
||||
"""
|
||||
pgcode_set = {'40P01', '55P03'}
|
||||
seen: set[int] = set()
|
||||
current: BaseException | None = exc
|
||||
while current is not None and id(current) not in seen and len(seen) < 6:
|
||||
seen.add(id(current))
|
||||
orig = getattr(current, 'orig', None)
|
||||
if getattr(orig, 'pgcode', None) in pgcode_set:
|
||||
return True
|
||||
text = str(current)
|
||||
if 'DeadlockDetected' in text or 'deadlock detected' in text or '40P01' in text or '55P03' in text:
|
||||
return True
|
||||
current = getattr(current, 'orig', None) or getattr(current, '__cause__', None)
|
||||
return False
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
@@ -917,15 +944,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
wave_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
|
||||
try:
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
)
|
||||
except Exception:
|
||||
from flask import current_app
|
||||
current_app.logger.exception(
|
||||
'retry unit progress failed run=%s unit=%s', run.run_no, unit.id,
|
||||
)
|
||||
# [收口不变量] 推送只物化 Candidate/Review Case,STP 统一由 run 收口
|
||||
# (submit_order_extraction_run_result)入队——STP Job 可见时抽取 Job
|
||||
# 必已提交完毕,结构性消除抽取∥STP 并发死锁(2026-09-22/24 事故族)。
|
||||
# 推送失败必须冒泡:此处是这些 Unit 候选与复核 Case 的唯一物化触发点,
|
||||
# 吞掉等于静默丢单。
|
||||
progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||
)
|
||||
continue
|
||||
if unit.status == 'review_required':
|
||||
continue
|
||||
@@ -1195,6 +1221,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
# [收口不变量] 同 replay 路径:推送只物化候选与复核 Case,STP 由 run 收口入队。
|
||||
try:
|
||||
unit_persist = progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=merged_unit_orders,
|
||||
@@ -1211,6 +1238,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
job_id=job.id,
|
||||
)
|
||||
except Exception as unit_exc:
|
||||
# [STEP] 先回滚再记录:推送失败时事务可能已中止(如死锁),直接写进度会抛
|
||||
# PendingRollbackError 顶掉原始异常(2026-09-24 test job 8840)。回滚后在新
|
||||
# 事务记录单元技术失败,再抛出原始异常交外层收口(瞬时锁错由其自动重排)。
|
||||
db.session.rollback()
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
@@ -1417,6 +1448,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
# [STEP] 瞬时锁错(PostgreSQL 死锁 40P01 / 锁超时 55P03)不收口 run/unit 失败:
|
||||
# 失败标记会写 run=failed,重试 Job 将被"run status is not executable"门弹掉。
|
||||
# 直接可重试入队,由队列在 attempts 耗尽前自动重排;冲突窗口为秒级,重试即过
|
||||
# (2026-09-22 SNER-20260922-6466EB53 / 879785D1 生产事故)。attempts 耗尽后
|
||||
# 走下方常规失败收口,fail-closed 语义不变。
|
||||
if _is_transient_lock_error(exc):
|
||||
fail_job(job.id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
return
|
||||
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = False
|
||||
if run is not None and run.status in {'queued', 'processing', 'failed'}:
|
||||
|
||||
@@ -8,6 +8,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
|
||||
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
|
||||
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
|
||||
waiting_external 先结束当前 Job 再延迟入队新 Job;
|
||||
external-wait 轮询异常时回滚并按 Gate 现状重排/安静结束,保证轮询链不因瞬时冲突断裂;
|
||||
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
|
||||
"""
|
||||
|
||||
@@ -88,7 +89,37 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
if external_wait_poll_gate_id and job is not None:
|
||||
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
|
||||
|
||||
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
|
||||
try:
|
||||
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
|
||||
except Exception as exc:
|
||||
# [STEP] 轮询与库存回调可能以相反顺序争抢 Gate 行与候选行(2026-09-23 test job 8818,
|
||||
# 事务被毒化后以 InFailedSqlTransaction 收口,轮询链断裂导致 Gate 永久等待)。
|
||||
# 回滚后按 Gate 现状分流:仍在等待外部 → 结束本 Job 并延迟重排,保持轮询链不断;
|
||||
# Gate 已被回调等其他路径收口 → 安静结束。错误文本留在 result_json 供排查。
|
||||
db.session.rollback()
|
||||
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
||||
gate_status = str(getattr(gate, 'status', '') or '') if gate is not None else None
|
||||
if gate_status == 'waiting_external':
|
||||
poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5)
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'status': 'waiting_external_requeued',
|
||||
'poll_error': sanitize_gate_error_text(exc, max_len=300),
|
||||
},
|
||||
owned_attempt=int(job.attempts or 0),
|
||||
)
|
||||
if gate is not None and gate.latest_attempt_id:
|
||||
schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id))
|
||||
db.session.commit()
|
||||
return
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'poll_superseded', 'gate_status': gate_status},
|
||||
owned_attempt=int(job.attempts or 0),
|
||||
)
|
||||
db.session.commit()
|
||||
return
|
||||
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
|
||||
if str(result.get('gate_status') or '') == 'waiting_external':
|
||||
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/jobs/store.py
|
||||
|
||||
用途:Job 认领与状态读写(KbJob 双轨 adapter + 通用 Job)。
|
||||
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
||||
逻辑:runner 通过 claim_next 获取 kb / shipping / contract / schedule 任务;返回归一化 dict 供 handler 分发。
|
||||
逻辑:runner 通过 claim_next 获取 kb / shipping / contract / schedule / transfer 任务;返回归一化 dict 供 handler 分发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -56,7 +56,7 @@ def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping / contract 队列;先 recover 卡死 running 任务。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping / contract / schedule / transfer 队列;先 recover 卡死 running 任务。
|
||||
Args:
|
||||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||||
Returns:
|
||||
@@ -156,6 +156,22 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
)
|
||||
if job:
|
||||
return _normalize_generic_job(job)
|
||||
elif name == 'transfer':
|
||||
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
|
||||
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
|
||||
# 会空轮询永远领不到任务,Run 卡在 queued。
|
||||
from app.jobs.queue import claim_next_job
|
||||
|
||||
job = claim_next_job(
|
||||
domain="in_transit_transfer",
|
||||
job_types=[
|
||||
JobType.TRANSFER_MATCH,
|
||||
JobType.TRANSFER_RUN,
|
||||
JobType.TRANSFER_ITEM,
|
||||
],
|
||||
)
|
||||
if job:
|
||||
return _normalize_generic_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@@ -39,8 +39,8 @@ class JobType(StrEnum):
|
||||
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
||||
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
||||
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
||||
# 在途仓自动调拨:文件准备 + 只读预检(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||
TRANSFER_PRECHECK = 'in_transit_transfer_precheck'
|
||||
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||
TRANSFER_MATCH = 'in_transit_transfer_match'
|
||||
TRANSFER_RUN = 'in_transit_transfer_run'
|
||||
TRANSFER_ITEM = 'in_transit_transfer_item'
|
||||
|
||||
@@ -83,7 +83,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
||||
'transfer': frozenset({
|
||||
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
@@ -204,8 +204,9 @@ from app.models.in_transit_transfer import (
|
||||
TransferArchive,
|
||||
TransferAttempt,
|
||||
TransferAuditEvent,
|
||||
TransferDocument,
|
||||
TransferInvoiceItem,
|
||||
TransferPrecheck,
|
||||
TransferMatching,
|
||||
TransferRun,
|
||||
TransferSourceJob,
|
||||
)
|
||||
@@ -425,7 +426,8 @@ __all__ = [
|
||||
'ContractPaymentSyncState',
|
||||
'TransferRun',
|
||||
'TransferSourceJob',
|
||||
'TransferPrecheck',
|
||||
'TransferMatching',
|
||||
'TransferDocument',
|
||||
'TransferInvoiceItem',
|
||||
'TransferAttempt',
|
||||
'TransferAuditEvent',
|
||||
|
||||
@@ -33,6 +33,8 @@ class ContractPaymentContract(Base):
|
||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
supplier_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
# OA 合同申请单「公司」。付款事实按该公司映射到 ERP 账套,空值按 HXJM 处理。
|
||||
company_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
applicant_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
total_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
|
||||
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""models/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、
|
||||
Attempt、AuditEvent 与 Archive。
|
||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
|
||||
逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单;
|
||||
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
|
||||
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
|
||||
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
|
||||
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
|
||||
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
|
||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
|
||||
"""
|
||||
|
||||
@@ -33,32 +35,52 @@ from app.models.base import Base
|
||||
|
||||
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
||||
TRANSFER_ITEM_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
|
||||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||
)
|
||||
TRANSFER_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
||||
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
|
||||
TRANSFER_RUN_TYPES = (
|
||||
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
|
||||
)
|
||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
TRANSFER_PRECHECK_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
TRANSFER_MATCH_STATUSES = (
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'failed', 'cancelled', 'expired',
|
||||
)
|
||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write')
|
||||
TRANSFER_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
|
||||
TRANSFER_ATTEMPT_STATUSES = (
|
||||
'queued', 'running', 'waiting_external', 'success', 'failed',
|
||||
'result_unknown', 'superseded',
|
||||
)
|
||||
# ERP 调拨单(TransferDocument)状态冻结枚举:服务层口径真相源;
|
||||
# ck_transfer_documents_status CHECK 由该元组生成(DB 兜底,非法态 fail-closed)。
|
||||
TRANSFER_DOCUMENT_STATUSES = (
|
||||
'pending', 'executing', 'success', 'duplicate_success',
|
||||
'business_failed', 'technical_failed', 'result_unknown', 'cancelled',
|
||||
)
|
||||
# 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时
|
||||
# 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(test_document_model.py 锁定)。
|
||||
UNRESOLVED_DOC_STATUSES = (
|
||||
'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed',
|
||||
)
|
||||
UNRESOLVED_DOC_STATUS_WHERE = "status IN ({})".format(
|
||||
', '.join(repr(s) for s in UNRESOLVED_DOC_STATUSES),
|
||||
)
|
||||
TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')
|
||||
|
||||
|
||||
class TransferRun(Base):
|
||||
"""一次调拨执行(或只读预检)的业务真相源。"""
|
||||
"""一次调拨执行(或只读匹配)的业务真相源。"""
|
||||
|
||||
__tablename__ = 'transfer_runs'
|
||||
__table_args__ = (
|
||||
@@ -75,6 +97,10 @@ class TransferRun(Base):
|
||||
"trigger_type IN ('manual', 'schedule')",
|
||||
name='ck_transfer_runs_trigger_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
|
||||
name='ck_transfer_runs_transfer_type',
|
||||
),
|
||||
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||
)
|
||||
@@ -82,6 +108,10 @@ class TransferRun(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
|
||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。
|
||||
transfer_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
@@ -103,14 +133,14 @@ class TransferRun(Base):
|
||||
source_jobs: Mapped[list['TransferSourceJob']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan',
|
||||
)
|
||||
prechecks: Mapped[list['TransferPrecheck']] = relationship(
|
||||
matchings: Mapped[list['TransferMatching']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan',
|
||||
)
|
||||
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run')
|
||||
|
||||
|
||||
class TransferSourceJob(Base):
|
||||
"""来源实例级的文件准备/预检执行单元;来源间互不阻断。"""
|
||||
"""来源实例级的文件准备/匹配执行单元;来源间互不阻断。"""
|
||||
|
||||
__tablename__ = 'transfer_source_jobs'
|
||||
__table_args__ = (
|
||||
@@ -142,33 +172,33 @@ class TransferSourceJob(Base):
|
||||
run: Mapped[TransferRun] = relationship(back_populates='source_jobs')
|
||||
|
||||
|
||||
class TransferPrecheck(Base):
|
||||
"""一次冻结快照的预检结果;确认/执行绑定其 Hash。"""
|
||||
class TransferMatching(Base):
|
||||
"""一次冻结快照的匹配结果;确认/执行绑定其 Hash。"""
|
||||
|
||||
__tablename__ = 'transfer_prechecks'
|
||||
__tablename__ = 'transfer_matchings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
|
||||
UniqueConstraint('matching_no', name='uq_transfer_matchings_matching_no'),
|
||||
CheckConstraint(
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})",
|
||||
name='ck_transfer_prechecks_status',
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_MATCH_STATUSES)})",
|
||||
name='ck_transfer_matchings_status',
|
||||
),
|
||||
Index('ix_transfer_prechecks_run_status', 'run_id', 'status'),
|
||||
Index('ix_transfer_prechecks_business_date', 'business_date'),
|
||||
Index('ix_transfer_matchings_run_status', 'run_id', 'status'),
|
||||
Index('ix_transfer_matchings_business_date', 'business_date'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
precheck_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
matching_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking')
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='matching', server_default='matching')
|
||||
scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
matching_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -177,32 +207,52 @@ class TransferPrecheck(Base):
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks')
|
||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='matchings')
|
||||
items: Mapped[list['TransferInvoiceItem']] = relationship(
|
||||
back_populates='precheck', cascade='all, delete-orphan',
|
||||
back_populates='matching', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class TransferInvoiceItem(Base):
|
||||
"""预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。"""
|
||||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
||||
|
||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_invoice_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
|
||||
UniqueConstraint(
|
||||
'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
|
||||
name='uq_transfer_invoice_items_matching_grain',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
|
||||
name='ck_transfer_invoice_items_status',
|
||||
),
|
||||
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
|
||||
Index('ix_transfer_invoice_items_run_id', 'run_id'),
|
||||
Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'),
|
||||
Index('ix_transfer_invoice_items_external_document_no', 'external_document_no'),
|
||||
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
|
||||
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。
|
||||
Index('ix_transfer_invoice_items_document_id', 'document_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True)
|
||||
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属
|
||||
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列,
|
||||
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按
|
||||
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。
|
||||
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
|
||||
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
|
||||
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
@@ -211,11 +261,11 @@ class TransferInvoiceItem(Base):
|
||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。
|
||||
raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
@@ -225,11 +275,87 @@ class TransferInvoiceItem(Base):
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
precheck: Mapped[TransferPrecheck] = relationship(back_populates='items')
|
||||
matching: Mapped[TransferMatching] = relationship(back_populates='items')
|
||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
|
||||
attempts: Mapped[list['TransferAttempt']] = relationship(
|
||||
back_populates='item', cascade='all, delete-orphan',
|
||||
)
|
||||
# 所属单(D14/D18):行随单执行推进;人工关闭调拨单(cancelled)时行脱离
|
||||
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||||
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items')
|
||||
|
||||
|
||||
class TransferDocument(Base):
|
||||
"""一张 ERP 调拨单(单):五元组一组一单;doc_no/submit_timestamp 终身复用(D3)。
|
||||
|
||||
防双单(D7/D15):同五元组至多一张未完结单,由部分唯一索引
|
||||
uq_transfer_documents_group_live 在 DB 层强制(并发提交竞态兜底;
|
||||
竞态方捕获 IntegrityError 后按同组复用重试);终态单(success/
|
||||
duplicate_success/cancelled)不占组锁。status 由
|
||||
ck_transfer_documents_status CHECK 兜底(非法态 fail-closed)。
|
||||
本表不存行集快照(D14:完整行集随写 Attempt 的 request_snapshot_json
|
||||
留档);closed_reason 为人工关闭原因(D18,审计之外的可视留档,
|
||||
仅失败单关闭时写入)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'),
|
||||
UniqueConstraint('submit_timestamp', name='uq_transfer_documents_submit_timestamp'),
|
||||
# 状态冻结枚举 DB 兜底(D15 纵深):组锁 WHERE 依赖状态字面量逐字匹配,
|
||||
# 非法态必须在 DB 层拒绝(fail-closed),生成口径同 TRANSFER_DOCUMENT_STATUSES。
|
||||
CheckConstraint(
|
||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_DOCUMENT_STATUSES)})",
|
||||
name='ck_transfer_documents_status',
|
||||
),
|
||||
# D15 防线:同组至多一张未完结单,由 DB 强制(并发提交竞态兜底;竞态方
|
||||
# 捕获 IntegrityError 按复用重试)。WHERE 子句由 UNRESOLVED_DOC_STATUSES
|
||||
# 生成;同时声明 postgresql_where/sqlite_where,保证 PG 与测试 SQLite
|
||||
# 建表同语义(部分唯一,非全组唯一)。
|
||||
Index(
|
||||
'uq_transfer_documents_group_live',
|
||||
'source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse',
|
||||
unique=True,
|
||||
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||||
sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||||
),
|
||||
Index('ix_transfer_documents_run_status', 'run_id', 'status'),
|
||||
Index('ix_transfer_documents_erp_no', 'erp_document_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
external_org: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
receipt_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
|
||||
# uq_transfer_documents_doc_no / uq_transfer_documents_submit_timestamp 强制。
|
||||
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
submit_timestamp: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='pending', server_default='pending',
|
||||
)
|
||||
# 写中间表成功时刻(D7② 末步跳过依据)。
|
||||
stage_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
# D18 人工关闭原因(仅失败单可关闭,状态 → cancelled 以释放组锁)。
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='document')
|
||||
attempts: Mapped[list['TransferAttempt']] = relationship(back_populates='document')
|
||||
# 只读投影关系(评审修正轮 ①):按 run_id 取现任 Run(Task 17 已执行单投影
|
||||
# serialize_executed_order / 关闭调拨单审计需要 run_no)。单向 relationship 不带
|
||||
# back_populates,避免与 TransferRun.items 环纠缠;纯 ORM 增量,无迁移。
|
||||
run: Mapped[Optional['TransferRun']] = relationship(foreign_keys=[run_id])
|
||||
|
||||
|
||||
class TransferAttempt(Base):
|
||||
@@ -251,6 +377,10 @@ class TransferAttempt(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False)
|
||||
# 单据级外键(D14:单:Attempt=1:N,外键在 Attempt 侧)。语义与 item_id 并存:
|
||||
# 写 Attempt(external_write)挂单(document_id=单 id),其 request_snapshot_json
|
||||
# 必须含单字段+完整行集;重查 Attempt(external_query)仍只挂 item,不挂单。
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
@@ -264,6 +394,7 @@ class TransferAttempt(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts')
|
||||
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='attempts')
|
||||
|
||||
|
||||
class TransferAuditEvent(Base):
|
||||
@@ -291,7 +422,7 @@ class TransferAuditEvent(Base):
|
||||
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matching_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""models/integration_connector.py
|
||||
|
||||
用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型:
|
||||
用途:Integration Connector(外部系统连接器框架)配置与运行时模型:
|
||||
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
|
||||
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
|
||||
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
|
||||
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
|
||||
连接器类型(rest/soap/database)与状态均用 CheckConstraint 兜底;database 客户端
|
||||
另有 db_kind 专列(mysql/oracle/sqlserver/postgresql),fail-closed 语义在服务层。
|
||||
Binding.steps_json 表达一对多有序接口配方(D10);旧单步列保留至 P2。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +24,7 @@ from sqlalchemy import (
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
@@ -30,8 +33,10 @@ from sqlalchemy.dialects.postgresql import JSONB
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
|
||||
CONNECTOR_TYPES = ('rest', 'soap')
|
||||
# 连接器类型白名单;模型 CHECK 由本常量动态生成,扩枚举须配套 Alembic 迁移重建 CHECK。
|
||||
CONNECTOR_TYPES = ('rest', 'soap', 'database')
|
||||
# database 专属库种(D16):专列 db_kind,非 config_json;API/transport 同源 fail-closed。
|
||||
DB_KINDS = ('mysql', 'oracle', 'sqlserver', 'postgresql')
|
||||
CONFIG_STATUSES = ('draft', 'published', 'retired')
|
||||
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
|
||||
|
||||
@@ -41,7 +46,7 @@ CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
|
||||
|
||||
|
||||
class IntegrationCredentialReference(Base):
|
||||
"""凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。"""
|
||||
"""凭据引用:真实凭据加密落库(db 模式)或引用环境注入键(env 模式),绝不落库明文。"""
|
||||
|
||||
__tablename__ = 'integration_credential_references'
|
||||
__table_args__ = (
|
||||
@@ -55,6 +60,9 @@ class IntegrationCredentialReference(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# db 模式:凭据 JSON(如 {"username","password"})的 Fernet 密文;主密钥由
|
||||
# INTEGRATION_CREDENTIAL_KEY 环境注入。env 模式为空。绝不回显、绝不写日志。
|
||||
secret_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
|
||||
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
||||
@@ -85,9 +93,12 @@ class IntegrationClientInstance(Base):
|
||||
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
|
||||
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
|
||||
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
|
||||
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点);
|
||||
# database 为 host:port[/database|service_name]。
|
||||
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
# database 专属库种(仅 connector_type='database' 有值;rest/soap 为 NULL)。
|
||||
db_kind: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
credential_ref_code: Mapped[Optional[str]] = mapped_column(
|
||||
ForeignKey('integration_credential_references.code'), nullable=True,
|
||||
@@ -140,7 +151,12 @@ class IntegrationInterfaceDefinition(Base):
|
||||
|
||||
|
||||
class IntegrationBinding(Base):
|
||||
"""绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
|
||||
"""绑定:(Capability, context_selector) → 有序接口步骤配方;版本化、可发布、可退役。
|
||||
|
||||
一对多有序(D10/D13):steps_json = [{interface_code, param_mapping_json}, ...];
|
||||
每步客户端由接口归属自带。旧列 interface_definition_code / param_mapping_json /
|
||||
client_instance_code 迁移后保留镜像首步,解析不再读取,P2 删除。
|
||||
"""
|
||||
|
||||
__tablename__ = 'integration_bindings'
|
||||
__table_args__ = (
|
||||
@@ -159,9 +175,15 @@ class IntegrationBinding(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
capability: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
|
||||
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
|
||||
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 有序步骤配方:每步 {interface_code, param_mapping_json};客户端由接口归属推导。
|
||||
steps_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
CONTEXT_SELECTOR_JSON, nullable=False, default=list,
|
||||
)
|
||||
# 域参数 → 接口参数的声明式映射(旧单步列,P2 删;迁移后镜像 steps_json[0])。
|
||||
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
|
||||
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||
client_instance_code: Mapped[str] = mapped_column(
|
||||
ForeignKey('integration_client_instances.code'), nullable=False,
|
||||
)
|
||||
@@ -181,13 +203,20 @@ class IntegrationBinding(Base):
|
||||
|
||||
|
||||
class IntegrationCall(Base):
|
||||
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
|
||||
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。
|
||||
|
||||
多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
|
||||
(一票一次执行 = N 条,按 operation_id 串联 + binding_snapshot_json.step_index
|
||||
定位),故 operation_id 无唯一约束;原唯一约束兼作的索引由普通索引
|
||||
ix_integration_calls_operation_id 补回(迁移 tt5b6c7d8e9f)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'integration_calls'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
|
||||
Index('ix_integration_calls_operation_id', 'operation_id'),
|
||||
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
|
||||
Index('ix_integration_calls_trace_id', 'trace_id'),
|
||||
Index('ix_integration_calls_business_ref', 'business_ref'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -199,4 +228,9 @@ class IntegrationCall(Base):
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
# 线级事实(database 最终 SQL/绑定/行数;soap endpoint+XML;rest HTTP 往返)。
|
||||
# 可空:历史行与未捕获场景为 NULL,前台如实展示。
|
||||
wire_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
# 通用业务锚点:调用方透传的业务单号/任务号(能力无关;不传为 NULL)。
|
||||
business_ref: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -37,7 +37,8 @@ class ShippingCustomer(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
|
||||
# 业务规则:客户简码允许重复(不同标准客户可共用同一简码,仅用作编号前缀),禁止再加唯一约束。
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_customers.id'),
|
||||
|
||||
@@ -160,9 +160,13 @@ class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
class ShippingInventoryParsingProfile(Base):
|
||||
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
|
||||
|
||||
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
|
||||
用途以 purpose 字段为准,勿按表名推断只服务库存。
|
||||
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
|
||||
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
|
||||
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
||||
@@ -358,7 +362,14 @@ class ShippingInventoryRoutingRuleVersion(Base):
|
||||
|
||||
|
||||
class ShippingInventoryExternalMapping(Base):
|
||||
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
|
||||
"""库存源到外部系统仓库的映射。
|
||||
|
||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||
「仓库」列(空值即「空库位」默认映射行,下方两个部分唯一索引保证同源最多
|
||||
一条启用的精确/默认映射);fixed 源仅一条启用映射直接取用。
|
||||
in_transit_warehouse_code(在途仓编码)是在途调拨拨出库位的来源
|
||||
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_external_mappings'
|
||||
__table_args__ = (
|
||||
@@ -387,6 +398,8 @@ class ShippingInventoryExternalMapping(Base):
|
||||
external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# 在途仓编码:在途调拨拨出库位来源(DefaultRouteResolver);保存端必填。
|
||||
in_transit_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='')
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
|
||||
@@ -52,7 +52,10 @@ class ShippingReceiptReportConfig(Base):
|
||||
|
||||
|
||||
class ShippingReceiptRpaUnitRun(Base):
|
||||
"""一次收料排程内的站点或站点-Warehouse 不可重复执行单元。"""
|
||||
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
|
||||
|
||||
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_receipt_rpa_unit_runs'
|
||||
__table_args__ = (
|
||||
@@ -66,7 +69,7 @@ class ShippingReceiptRpaUnitRun(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_run_id: Mapped[int] = mapped_column(ForeignKey('schedule_runs.id'), nullable=False, index=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
@@ -85,7 +88,7 @@ class ShippingReceiptRpaUnitRun(Base):
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
schedule_run: Mapped['ScheduleRun'] = relationship(foreign_keys=[schedule_run_id])
|
||||
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||
inventory_source: Mapped['ShippingInventorySource'] = relationship()
|
||||
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
|
||||
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
|
||||
|
||||
@@ -153,13 +153,7 @@ def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str)
|
||||
if status not in {'active', 'inactive'}:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
|
||||
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
|
||||
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
|
||||
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
|
||||
warnings.append({
|
||||
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
|
||||
'customer_id': code_owner.id,
|
||||
'short_code': short_code,
|
||||
})
|
||||
# 客户简码允许重复(业务规则),导入预检不再因简码撞码产生 warning。
|
||||
normalized_name = normalize_customer_name(name)
|
||||
similar = [
|
||||
item for item in db.session.query(ShippingCustomer).all()
|
||||
|
||||
@@ -320,23 +320,12 @@ def get_customer(customer_id: int) -> dict[str, Any]:
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
|
||||
"""校验客户简码全局唯一。"""
|
||||
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
|
||||
if exclude_customer_id is not None:
|
||||
query = query.filter(ShippingCustomer.id != exclude_customer_id)
|
||||
if query.first():
|
||||
raise ConflictError(
|
||||
'Customer short code already exists',
|
||||
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
|
||||
details={'short_code': short_code},
|
||||
)
|
||||
|
||||
|
||||
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
创建标准客户。
|
||||
|
||||
客户简码允许重复(业务规则),仅做格式归一化,不做唯一性校验。
|
||||
|
||||
Args:
|
||||
data: standard_name、short_code、status、remark。
|
||||
actor_id: 当前管理员 ID。
|
||||
@@ -351,7 +340,6 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
details={'field': 'standard_name'},
|
||||
)
|
||||
short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(short_code)
|
||||
status = clean_text(data.get('status') or 'active').lower()
|
||||
if status not in CUSTOMER_STATUSES - {'merged'}:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
@@ -442,7 +430,6 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
|
||||
next_name = name
|
||||
if 'short_code' in data:
|
||||
next_short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
|
||||
if 'status' in data:
|
||||
next_status = clean_text(data.get('status')).lower()
|
||||
if next_status not in CUSTOMER_STATUSES - {'merged'}:
|
||||
|
||||
@@ -255,15 +255,43 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
|
||||
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_movement_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。
|
||||
|
||||
Args:
|
||||
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
|
||||
Returns:
|
||||
规整后的规则 id 或 None。
|
||||
Raises:
|
||||
ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。
|
||||
"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
raise ValidationError(
|
||||
'Receipt movement parsing profile must be published with purpose movement',
|
||||
code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
@@ -328,6 +356,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
@@ -335,7 +364,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
@@ -1147,6 +1177,7 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
|
||||
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
|
||||
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
|
||||
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
|
||||
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
|
||||
@@ -1178,8 +1209,11 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
|
||||
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
|
||||
record.inventory_source_id = source_id
|
||||
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
|
||||
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
|
||||
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
|
||||
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
|
||||
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
|
||||
record.external_organization_code = _text(data, 'external_organization_code')
|
||||
record.external_site_code = _text(data, 'external_site_code')
|
||||
|
||||
@@ -166,7 +166,7 @@ agent_types:
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
- TransferRun
|
||||
- TransferPrecheck
|
||||
- TransferMatching
|
||||
- TransferInvoiceItem
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
@@ -186,7 +186,7 @@ agent_types:
|
||||
type: conversation_context
|
||||
keys:
|
||||
- run_no
|
||||
- precheck_id
|
||||
- matching_id
|
||||
requires_schedule_task: false
|
||||
presentation:
|
||||
layout: card
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
用途:在途仓自动调拨 Hybrid Handler。
|
||||
|
||||
依赖:agent_registry.handlers.base/registry。
|
||||
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute)
|
||||
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.match / transfer.execute)
|
||||
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
|
||||
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
|
||||
Dify Chatflow 生命周期。
|
||||
@@ -21,12 +21,12 @@ class InTransitTransferHandler(AgentHandler):
|
||||
"""
|
||||
在途仓自动调拨业务 Handler。
|
||||
|
||||
核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
|
||||
核心逻辑:匹配/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
|
||||
+ Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。
|
||||
"""
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。"""
|
||||
"""Dify 流开始前:校验领域上下文(预留 run_no/matching_id 锚点)。"""
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
|
||||
|
||||
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
||||
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;摘要接口与周五发送使用同一 pending 口径。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
|
||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||
"""
|
||||
|
||||
@@ -34,7 +34,12 @@ from app.services.integrations.wecom.notify import (
|
||||
send_wecom_file_message,
|
||||
upload_wecom_temp_media,
|
||||
)
|
||||
from app.services.contract_payment.erp_payment_service import fetch_paid_records, resolve_paid_node_dates
|
||||
from app.services.contract_payment.erp_payment_service import (
|
||||
erp_schema_for_company,
|
||||
fetch_paid_records,
|
||||
normalize_purchase_order_no,
|
||||
resolve_paid_node_dates,
|
||||
)
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
@@ -77,21 +82,22 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
.filter(ContractPaymentNode.status == "active", ContractPaymentContract.status == "active")
|
||||
.all()
|
||||
)
|
||||
paid_records = fetch_paid_records(
|
||||
contract.purchase_order_no
|
||||
for _node, contract in rows
|
||||
if _node.node_type in {"prepayment", "shipment"}
|
||||
)
|
||||
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)
|
||||
]
|
||||
paid_records = fetch_paid_records(payable_orders)
|
||||
paid_node_dates: dict[int, str | None] = {}
|
||||
nodes_by_purchase_order: dict[str, list[ContractPaymentNode]] = defaultdict(list)
|
||||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||||
for node, contract in rows:
|
||||
purchase_order_no = str(contract.purchase_order_no or "").strip()
|
||||
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||||
nodes_by_purchase_order[purchase_order_no].append(node)
|
||||
for purchase_order_no, payment_nodes in nodes_by_purchase_order.items():
|
||||
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(
|
||||
[(node.id, node.node_type, node.amount) for node in payment_nodes],
|
||||
paid_records.get(purchase_order_no, []),
|
||||
paid_records.get(ledger_key, []),
|
||||
))
|
||||
for node, contract in rows:
|
||||
anchor = _anchor_date(contract=contract, node=node)
|
||||
@@ -143,20 +149,170 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
return {"created": created, "pending": created, "sent": 0, "skipped": skipped, "resolved": resolved}
|
||||
|
||||
|
||||
def _resolve_pending_alerts(*, node_id: int) -> int:
|
||||
"""将某节点未发送的提醒标记为已按 ERP 付款关闭,保留历史发送记录。"""
|
||||
def _resolve_pending_alerts(*, node_id: int, reason: str = "erp_paid") -> int:
|
||||
"""将某节点未发送的提醒标记为已关闭,保留历史发送记录。"""
|
||||
rows = db.session.query(ContractPaymentAlert).filter_by(node_id=node_id, status="pending").all()
|
||||
for alert in rows:
|
||||
alert.status = "resolved"
|
||||
alert.message_json = {**(alert.message_json or {}), "resolved_reason": "erp_paid"}
|
||||
alert.message_json = {**(alert.message_json or {}), "resolved_reason": reason}
|
||||
return len(rows)
|
||||
|
||||
|
||||
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
||||
"""
|
||||
把一个未付的预付款或出货款手动标为已付。
|
||||
|
||||
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
验收款、质保款和已经付款的阶段不能标记。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
node_id: 付款节点主键,必须属于该合同。
|
||||
payload: paid_date 必填,remark 可选。
|
||||
operator_id: 操作人用户 ID,写入证据供审计。
|
||||
|
||||
Returns:
|
||||
更新后的合同。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同或节点不存在。
|
||||
ValidationError: 阶段类型、状态或付款日期不合法。
|
||||
"""
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
|
||||
contract = db.session.get(ContractPaymentContract, contract_id)
|
||||
if contract is None:
|
||||
raise NotFoundError("合同不存在")
|
||||
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.status == "paid":
|
||||
raise ValidationError("该阶段已是已付")
|
||||
if node.status != "active":
|
||||
raise ValidationError("该阶段当前不能标为已付")
|
||||
raw_date = str(payload.get("paid_date") or "").strip()[:10]
|
||||
try:
|
||||
paid_date = date.fromisoformat(raw_date)
|
||||
except ValueError:
|
||||
raise ValidationError("请填写付款日期") from None
|
||||
remark = str(payload.get("remark") or "").strip()
|
||||
if len(remark) > 500:
|
||||
raise ValidationError("说明不能超过 500 字")
|
||||
node.status = "paid"
|
||||
node.evidence_json = {
|
||||
**(node.evidence_json or {}),
|
||||
"paid_at": paid_date.isoformat(),
|
||||
"paid_source": "manual",
|
||||
"paid_remark": remark or None,
|
||||
"paid_by": operator_id,
|
||||
}
|
||||
_resolve_pending_alerts(node_id=node.id, reason="manual_paid")
|
||||
db.session.commit()
|
||||
return contract
|
||||
|
||||
|
||||
_FAILURE_REASON_LABELS: dict[str, str] = {
|
||||
"notify_disabled": "企业微信通知未启用",
|
||||
"event_disabled": "合同付款预警通知事件未启用",
|
||||
"user_unbound": "收件人未绑定企业微信账号",
|
||||
"textcard_failed": "企业微信卡片发送失败",
|
||||
"file_upload_failed": "企业微信附件上传失败",
|
||||
"file_failed": "企业微信附件发送失败",
|
||||
"unknown": "发送失败",
|
||||
}
|
||||
|
||||
|
||||
def _append_failure_reason(reasons: list[dict[str, str]], code: str, detail: str = "") -> None:
|
||||
"""向失败原因列表追加一条去重后的记录。
|
||||
|
||||
核心逻辑:压缩 detail 空白并截断到 500 字;code 与 detail 都相同则跳过。
|
||||
|
||||
Args:
|
||||
reasons: 正在组装的原因列表,就地修改。
|
||||
code: 前端可翻译的原因编码。
|
||||
detail: 企微或异常返回的补充说明,可为空。
|
||||
"""
|
||||
normalized = " ".join(str(detail or "").split())[:500]
|
||||
if any(item["code"] == code and item["detail"] == normalized for item in reasons):
|
||||
return
|
||||
reasons.append({"code": code, "detail": normalized})
|
||||
|
||||
|
||||
def describe_batch_failure(trace: dict | None, *, fallback: str | None = None) -> list[dict[str, str]]:
|
||||
"""把周汇总企微发送轨迹整理成可展示的失败原因。
|
||||
|
||||
核心逻辑:优先识别卡片失败、附件上传异常和附件发送失败;「未绑定企微」只保留一条。
|
||||
轨迹无法识别时回退到已保存的 error_message,避免历史失败批次没有原因可看。
|
||||
|
||||
Args:
|
||||
trace: 批次 wecom_trace_json。非字典时忽略。
|
||||
fallback: 轨迹无法识别时使用的已存错误文本。
|
||||
|
||||
Returns:
|
||||
原因列表。每项含 code 与 detail;没有可展示原因时返回空列表。
|
||||
"""
|
||||
reasons: list[dict[str, str]] = []
|
||||
# [STEP 1] 卡片发送失败优先按已知原因码归类,企微 errmsg 放在 detail。
|
||||
if isinstance(trace, dict):
|
||||
textcard = trace.get("textcard") if isinstance(trace.get("textcard"), dict) else {}
|
||||
if textcard and not textcard.get("ok"):
|
||||
reason = str(textcard.get("reason") or "").strip()
|
||||
raw = textcard.get("raw") if isinstance(textcard.get("raw"), dict) else {}
|
||||
errmsg = str(raw.get("errmsg") or "").strip()
|
||||
if reason in {"notify_disabled", "event_disabled", "user_unbound"}:
|
||||
_append_failure_reason(reasons, reason)
|
||||
else:
|
||||
_append_failure_reason(reasons, "textcard_failed", errmsg)
|
||||
|
||||
# [STEP 2] 附件失败与卡片失败分开记录;未绑定账号不重复展示。
|
||||
file_error = str(trace.get("file_error") or "").strip()
|
||||
if file_error:
|
||||
_append_failure_reason(reasons, "file_upload_failed", file_error)
|
||||
else:
|
||||
file_result = trace.get("file") if isinstance(trace.get("file"), dict) else {}
|
||||
errcode = file_result.get("errcode")
|
||||
if errcode not in (None, 0, "0"):
|
||||
errmsg = str(file_result.get("errmsg") or "").strip()
|
||||
if errmsg == "user_unbound":
|
||||
_append_failure_reason(reasons, "user_unbound")
|
||||
else:
|
||||
_append_failure_reason(reasons, "file_failed", errmsg or str(errcode))
|
||||
|
||||
if reasons:
|
||||
return reasons
|
||||
stored = " ".join(str(fallback or "").split())
|
||||
if stored:
|
||||
_append_failure_reason(reasons, "unknown", stored[:2000])
|
||||
return reasons
|
||||
|
||||
|
||||
def render_batch_failure_message(reasons: list[dict[str, str]]) -> str:
|
||||
"""把失败原因编码拼成写入批次审计字段的中文摘要。
|
||||
|
||||
核心逻辑:使用固定中文标签,detail 非空时接在标签后,多条以分号连接。
|
||||
|
||||
Args:
|
||||
reasons: describe_batch_failure 的返回值。
|
||||
|
||||
Returns:
|
||||
最长 2000 字的中文摘要;没有原因时返回空字符串。
|
||||
"""
|
||||
parts: list[str] = []
|
||||
for item in reasons:
|
||||
label = _FAILURE_REASON_LABELS.get(str(item.get("code") or ""), "发送失败")
|
||||
detail = str(item.get("detail") or "").strip()
|
||||
parts.append(f"{label}:{detail}" if detail else label)
|
||||
return ";".join(parts)[:2000]
|
||||
|
||||
|
||||
def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
|
||||
"""按收件人发送本周合同付款预警汇总及 Excel 明细。
|
||||
|
||||
AI 触发时机:每周五 18:00 的排程或管理员补发时调用。
|
||||
核心逻辑:每位收件人每周只产生一个批次;企微正文仅发送总笔数和阶段数量,逐笔信息写入附件。
|
||||
发送失败时把卡片和附件的原因写入 error_message,并把 sent_at 记为最近一次尝试时间,供周汇总页查看。
|
||||
Args:
|
||||
today: 用于确定 ISO 周标识,测试可显式传入。
|
||||
Returns:
|
||||
@@ -231,7 +387,9 @@ def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
|
||||
sent += 1
|
||||
else:
|
||||
batch.status = "failed"
|
||||
batch.error_message = str(trace)[:2000]
|
||||
# 失败也记录尝试时刻,周汇总「发送时间」不再空白;重试时覆盖为最近一次。
|
||||
batch.sent_at = datetime.utcnow()
|
||||
batch.error_message = render_batch_failure_message(describe_batch_failure(trace)) or str(trace)[:2000]
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return {"batches": batches, "sent": sent, "failed": failed, "alerts": detail_count}
|
||||
|
||||
@@ -3,12 +3,13 @@ backend/app/services/contract_payment/erp_payment_service.py
|
||||
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
|
||||
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
||||
逻辑:仅执行只读查询;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Iterable
|
||||
@@ -17,6 +18,73 @@ from flask import current_app
|
||||
|
||||
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
||||
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
||||
_SCHEMA_BY_COMPANY = {
|
||||
"无锡和宏智散热科技有限公司": "WZHHZ",
|
||||
"和泰科技(吴江)有限公司": "HTT",
|
||||
"苏州和信精密科技有限公司": "HXJM",
|
||||
}
|
||||
_DEFAULT_ERP_SCHEMA = "HXJM"
|
||||
_ALLOWED_ERP_SCHEMAS = frozenset({"HXJM", "WZHHZ", "HTT"})
|
||||
|
||||
|
||||
def normalize_company_name(company_name: str | None) -> str:
|
||||
"""压缩空白并把全角括号改成半角,便于和账套映射表精确比对。"""
|
||||
text = "".join(str(company_name or "").split())
|
||||
return text.replace("(", "(").replace(")", ")")
|
||||
|
||||
|
||||
# 采购单号首尾可能粘上 OA 单元格里的空格或供应商简称,ERP 的 apaud03 不含汉字。
|
||||
_PURCHASE_ORDER_EDGE_RE = re.compile(r"^[\s\u3000\u4e00-\u9fff]+|[\s\u3000\u4e00-\u9fff]+$")
|
||||
|
||||
|
||||
def normalize_purchase_order_no(value: str | None) -> str:
|
||||
"""
|
||||
去掉采购单号首尾的空格和汉字。
|
||||
|
||||
核心逻辑:真正的采购单号没有汉字。只剥两端,中间的数字和横杠保留。
|
||||
Args:
|
||||
value: OA 或台账上的采购单号原文,可为空。
|
||||
Returns:
|
||||
去掉首尾空格和汉字后的采购单号;空值返回空字符串。
|
||||
"""
|
||||
text = str(value or "")
|
||||
previous = None
|
||||
while text and text != previous:
|
||||
previous = text
|
||||
text = _PURCHASE_ORDER_EDGE_RE.sub("", text)
|
||||
return text
|
||||
|
||||
|
||||
def erp_schema_for_company(company_name: str | None) -> str:
|
||||
"""
|
||||
按 OA 合同申请单上的公司确定 ERP 账套。
|
||||
|
||||
核心逻辑:无锡和宏智散热科技有限公司用 WZHHZ,和泰科技(吴江)有限公司用 HTT,
|
||||
苏州和信精密科技有限公司以及其余公司用 HXJM。公司为空时也用 HXJM,保持存量合同行为。
|
||||
Args:
|
||||
company_name: OA「公司」字段原文。
|
||||
Returns:
|
||||
白名单内的账套代码。
|
||||
"""
|
||||
schema = _SCHEMA_BY_COMPANY.get(normalize_company_name(company_name), _DEFAULT_ERP_SCHEMA)
|
||||
return schema if schema in _ALLOWED_ERP_SCHEMAS else _DEFAULT_ERP_SCHEMA
|
||||
|
||||
|
||||
def _paid_records_sql(schema: str, placeholders: str) -> str:
|
||||
"""拼出指定账套的只读付款 SQL。schema 必须已在白名单内,禁止把公司名称拼进 SQL。"""
|
||||
if schema not in _ALLOWED_ERP_SCHEMAS:
|
||||
raise ValueError(f"unsupported erp schema: {schema}")
|
||||
return f"""
|
||||
SELECT TRIM(apaud03) AS purchase_order_no,
|
||||
NVL(apa34f, 0) AS paid_amount,
|
||||
TRUNC(apa02) AS paid_date
|
||||
FROM {schema}.apa_file
|
||||
WHERE TRIM(apaud03) IN ({placeholders})
|
||||
AND TRIM(TO_CHAR(apa00)) = '15'
|
||||
AND UPPER(TRIM(apa41)) = 'Y'
|
||||
AND TRIM(TO_CHAR(apa63)) = '1'
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -28,20 +96,27 @@ class ErpPaidRow:
|
||||
paid_date: str | None
|
||||
|
||||
|
||||
def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpPaidRow]]:
|
||||
def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[str, str], list[ErpPaidRow]]:
|
||||
"""
|
||||
查询采购单已完成付款记录(含付款日期)。
|
||||
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
||||
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
|
||||
核心逻辑:查询 `apa_file`,先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f`(金额)与 `apa02`(付款日期)。
|
||||
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
||||
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
||||
某一账套查询失败只影响该账套,其它账套继续。
|
||||
Args:
|
||||
purchase_order_nos: 待查询的采购单号集合;空集合不会连接 ERP。
|
||||
orders: `(采购单号, OA公司)`;公司为空时按 HXJM。空集合不会连接 ERP。
|
||||
Returns:
|
||||
采购单号到合格付款记录列表的映射。ERP 未配置、驱动不可用或查询失败时返回空映射,
|
||||
`(账套, 采购单号)` 到合格付款记录列表的映射。ERP 未配置或驱动不可用时返回空映射,
|
||||
由调用方按未付款处理,避免错误停止预警。
|
||||
"""
|
||||
normalized = sorted({str(value or "").strip() for value in purchase_order_nos if str(value or "").strip()})
|
||||
if not normalized:
|
||||
grouped: dict[str, set[str]] = {}
|
||||
for purchase_order_no, company_name in orders:
|
||||
po = normalize_purchase_order_no(purchase_order_no)
|
||||
if not po:
|
||||
continue
|
||||
grouped.setdefault(erp_schema_for_company(company_name), set()).add(po)
|
||||
if not grouped:
|
||||
return {}
|
||||
dsn = str(current_app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip()
|
||||
username = str(current_app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip()
|
||||
@@ -71,33 +146,33 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
|
||||
timeout = max(int(current_app.config.get("CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS") or 30), 5)
|
||||
connection.call_timeout = timeout * 1000
|
||||
cursor = connection.cursor()
|
||||
placeholders = ", ".join(f":po_{index}" for index in range(len(normalized)))
|
||||
# [STEP 1] 只取「厂商预付款作业」类型的付款记录:apa00='15' 为厂商预付款作业标志,
|
||||
# 过滤掉其它作业类型(如对账/其它付款),避免把非预付款的付款误匹配到预付款/出货款节点;
|
||||
# 后再叠加 apa41='Y'(有效)与 apa63=1(已完成付款)两层过滤,仅统计真正完成的预付款。
|
||||
# apaud03 varchar2 40 采购单号
|
||||
sql = f"""
|
||||
SELECT TRIM(apaud03) AS purchase_order_no,
|
||||
NVL(apa34f, 0) AS paid_amount,
|
||||
TRUNC(apa02) AS paid_date
|
||||
FROM apa_file
|
||||
WHERE TRIM(apaud03) IN ({placeholders})
|
||||
AND TRIM(TO_CHAR(apa00)) = '15'
|
||||
AND UPPER(TRIM(apa41)) = 'Y'
|
||||
AND TRIM(TO_CHAR(apa63)) = '1'
|
||||
"""
|
||||
cursor.execute(sql, {f"po_{index}": value for index, value in enumerate(normalized)})
|
||||
result: dict[str, list[ErpPaidRow]] = {}
|
||||
for raw_po, raw_amount, raw_paid_date in cursor:
|
||||
po = str(raw_po or "").strip()
|
||||
if not po:
|
||||
continue
|
||||
result: dict[tuple[str, str], list[ErpPaidRow]] = {}
|
||||
# [STEP 1] 同一连接按账套分别查 `{账套}.apa_file`。登录用户是 hxjm,未加前缀时只会读到 HXJM。
|
||||
# apa00='15' 限定厂商预付款作业,再叠加 apa41='Y' 与 apa63=1,避免把其它付款记到预付款/出货款。
|
||||
for schema, purchase_orders in grouped.items():
|
||||
normalized = sorted(purchase_orders)
|
||||
placeholders = ", ".join(f":po_{index}" for index in range(len(normalized)))
|
||||
try:
|
||||
amount = Decimal(str(raw_amount or "0"))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
continue
|
||||
paid_date = getattr(raw_paid_date, "isoformat", lambda: None)().split("T")[0] if raw_paid_date else None
|
||||
result.setdefault(po, []).append(ErpPaidRow(amount=amount, paid_date=paid_date))
|
||||
cursor.execute(
|
||||
_paid_records_sql(schema, placeholders),
|
||||
{f"po_{index}": value for index, value in enumerate(normalized)},
|
||||
)
|
||||
for raw_po, raw_amount, raw_paid_date in cursor:
|
||||
po = str(raw_po or "").strip()
|
||||
if not po:
|
||||
continue
|
||||
try:
|
||||
amount = Decimal(str(raw_amount or "0"))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
continue
|
||||
paid_date = getattr(raw_paid_date, "isoformat", lambda: None)().split("T")[0] if raw_paid_date else None
|
||||
result.setdefault((schema, po), []).append(ErpPaidRow(amount=amount, paid_date=paid_date))
|
||||
except Exception as exc:
|
||||
code = getattr(exc, "code", None) or getattr(exc, "full_code", None)
|
||||
current_app.logger.warning(
|
||||
"合同付款预警:账套 %s 付款查询失败,该账套按未付款处理,error_type=%s code=%s message=%s",
|
||||
schema, type(exc).__name__, code, str(exc) or getattr(exc, "message", ""),
|
||||
)
|
||||
return result
|
||||
except Exception as exc:
|
||||
# 记录具体 Oracle 错误码(如 ORA-01017/00942/12514)与消息,便于定位账号权限/服务名问题;不输出密码。
|
||||
@@ -117,10 +192,10 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
|
||||
pass
|
||||
|
||||
|
||||
def fetch_paid_amounts(purchase_order_nos: Iterable[str]) -> dict[str, list[Decimal]]:
|
||||
"""查询采购单已完成付款金额列表(兼容旧调用方)。"""
|
||||
records = fetch_paid_records(purchase_order_nos)
|
||||
return {po: [row.amount for row in rows] for po, rows in records.items()}
|
||||
def fetch_paid_amounts(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[str, str], list[Decimal]]:
|
||||
"""查询各账套采购单已完成付款金额列表。"""
|
||||
records = fetch_paid_records(orders)
|
||||
return {key: [row.amount for row in rows] for key, rows in records.items()}
|
||||
|
||||
|
||||
def _select_match(
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。未到期为付款日在 7 日以外且未逾期的未付合同;本月应付可与即将到期、逾期或未到期重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
services/contract_payment/oa_client.py
|
||||
|
||||
用途:读取 OA 中已归档的合同申请单,提取表单字段和合同附件供付款预警同步。
|
||||
依赖:requests、lxml、Flask 配置;由 sync_service 负责将本客户端的标准化结果落库。
|
||||
依赖:requests、lxml、Flask 配置、normalize_purchase_order_no;由 sync_service 负责将本客户端的标准化结果落库。
|
||||
逻辑:同一登录会话顺序扫描待办和已办归档列表并翻页;满页大小以 OA 实际返回行数为准(泛微默认 10 条/页),
|
||||
不得用配置页大小把首页短页误判为到底;首次全量翻到短页为止,增量触顶页上限时标记截断供同步层不推进断点。
|
||||
合同原文被临时文件清理删掉后,可按流程 ID 与附件 ID 重新打开详情并下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +23,8 @@ import requests
|
||||
from flask import current_app
|
||||
from lxml import html as lxml_html
|
||||
|
||||
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
|
||||
|
||||
|
||||
# OA 列表若始终返回满页,用硬上限防止死循环;首次全量也受此保护。
|
||||
_WORKLIST_HARD_MAX_PAGES = 1000
|
||||
@@ -340,6 +343,49 @@ class ContractOaClient:
|
||||
content_type = (response.headers.get("content-type") or "application/octet-stream").split(";", 1)[0].strip().lower()
|
||||
return data, content_type, _filename_from_disposition(response.headers.get("content-disposition"))
|
||||
|
||||
def download_attachment_by_id(self, *, process_id: str, attachment_id: str) -> tuple[bytes, str, str | None]:
|
||||
"""
|
||||
按 OA 流程和附件 ID 重新下载合同原文。
|
||||
|
||||
用途:合同附件曾按临时 FileAsset 落库,清理任务删除对象后,详情页下载和重解析用本方法找回字节。
|
||||
核心逻辑:打开 ViewRequest.jsp,在详情解析出的附件里匹配 attachment_id,再走 download_attachment。
|
||||
|
||||
Args:
|
||||
process_id: OA requestid,对应合同台账 oa_record_id。
|
||||
attachment_id: 详情页附件 ID,对应附件 source_key 去掉 `oa:` 前缀后的值。
|
||||
|
||||
Returns:
|
||||
文件字节、MIME 类型和响应头文件名。
|
||||
|
||||
Raises:
|
||||
ValueError: 流程 ID 或附件 ID 为空。
|
||||
RuntimeError: OA 未配置、详情打不开,或详情中没有该附件。
|
||||
requests.RequestException: 登录失效或 OA 下载失败。
|
||||
"""
|
||||
process_id = str(process_id or "").strip()
|
||||
attachment_id = str(attachment_id or "").strip()
|
||||
if not process_id or not attachment_id:
|
||||
raise ValueError("缺少 OA 流程或附件 ID")
|
||||
if not self.is_configured():
|
||||
raise RuntimeError("OA 未配置,无法重新下载合同附件")
|
||||
session = self._session()
|
||||
detail = self._fetch_detail(session, {
|
||||
"process_id": process_id,
|
||||
"detail_url": f"/workflow/request/ViewRequest.jsp?requestid={process_id}",
|
||||
})
|
||||
if not detail:
|
||||
raise RuntimeError("无法打开 OA 合同详情")
|
||||
match = next(
|
||||
(
|
||||
item for item in (detail.get("attachments") or [])
|
||||
if str(item.get("attachment_id") or "").strip() == attachment_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise RuntimeError("OA 详情中找不到原合同附件")
|
||||
return self.download_attachment(match)
|
||||
|
||||
def _session(self, *, refresh: bool = False) -> requests.Session:
|
||||
"""复用 20 分钟 OA 登录会话;登录字段通过环境变量覆盖以适配不同 OA 部署。"""
|
||||
with _SESSION_LOCK:
|
||||
@@ -632,7 +678,8 @@ class ContractOaClient:
|
||||
"""
|
||||
解析合同申请单表格与附件区域。
|
||||
|
||||
截图确认的字段名为“流程编号、采购单号、合同单位、合同金额、合同书币别、合同生效日期、约定到货日期”;
|
||||
截图确认的字段名为“流程编号、公司、采购单号、合同单位、合同金额、合同书币别、合同生效日期、约定到货日期”;
|
||||
「公司」决定 ERP 账套,「合同单位」是供应商,两者不能混用。
|
||||
解析保留原始 labels,便于首次联调快速发现同义字段变化。
|
||||
"""
|
||||
tree = _html_tree(page)
|
||||
@@ -663,7 +710,10 @@ class ContractOaClient:
|
||||
"status": _ARCHIVED_TEXT if _ARCHIVED_TEXT in full_text else "",
|
||||
"contract_no": contract_no,
|
||||
"workflow_no": workflow_no,
|
||||
"purchase_order_no": _field_value(labels, "采购单号") or _purchase_order_no_from_title(_field_value(labels, "标题")),
|
||||
"purchase_order_no": normalize_purchase_order_no(
|
||||
_field_value(labels, "采购单号") or _purchase_order_no_from_title(_field_value(labels, "标题"))
|
||||
),
|
||||
"company_name": _field_value(labels, "公司"),
|
||||
"supplier_name": _field_value(labels, "合同单位", "供应商"),
|
||||
"applicant_name": _field_value(labels, "申请人", "申请人员", "申请人姓名"),
|
||||
"total_amount": total_amount,
|
||||
@@ -763,6 +813,7 @@ class ContractOaClient:
|
||||
"contract_no": detail.get("contract_no") or None,
|
||||
"workflow_no": detail.get("workflow_no") or process_id,
|
||||
"purchase_order_no": detail.get("purchase_order_no"),
|
||||
"company_name": detail.get("company_name"),
|
||||
"supplier_name": detail.get("supplier_name"),
|
||||
"applicant_name": detail.get("applicant_name"),
|
||||
"total_amount": detail.get("total_amount"),
|
||||
@@ -863,12 +914,43 @@ def _pick(row: dict[str, Any], *keys: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _cell_text(cell: Any) -> str:
|
||||
"""
|
||||
读取表单单元格的展示值。
|
||||
|
||||
核心逻辑:下拉框的 HTML 会带上全部选项。只取 `option selected`;没有 selected 时,
|
||||
用同格隐藏 input 的 value 对上 option 的 value。普通文本格仍拼接可见文字。
|
||||
有下拉框但无法确定选中项时返回空,避免把候选项拼成公司名。
|
||||
"""
|
||||
selects = cell.xpath(".//select")
|
||||
if not selects:
|
||||
return _clean_text(" ".join(cell.xpath(".//text()")))
|
||||
select = selects[0]
|
||||
for option in select.xpath("./option[@selected]"):
|
||||
text = _clean_text("".join(option.xpath(".//text()")))
|
||||
if text:
|
||||
return text
|
||||
current = ""
|
||||
for node in cell.xpath(".//input[@value]"):
|
||||
current = str(node.get("value") or "").strip()
|
||||
if current:
|
||||
break
|
||||
if current:
|
||||
for option in select.xpath("./option"):
|
||||
if str(option.get("value") or "").strip() != current:
|
||||
continue
|
||||
text = _clean_text("".join(option.xpath(".//text()")))
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _table_fields(tree: Any) -> dict[str, str]:
|
||||
"""解析表格中“标签单元格 + 值单元格”对;同一行可包含多组字段。"""
|
||||
"""解析表格中“标签单元格 + 值单元格”对;同一行可包含多组字段。下拉框只取选中项。"""
|
||||
fields: dict[str, str] = {}
|
||||
for row in tree.xpath("//tr"):
|
||||
cells = row.xpath("./th|./td")
|
||||
texts = [_clean_text(" ".join(cell.xpath(".//text()"))) for cell in cells]
|
||||
texts = [_cell_text(cell) for cell in cells]
|
||||
for index in range(0, len(texts) - 1, 2):
|
||||
label, value = texts[index], texts[index + 1]
|
||||
if label and value and len(label) <= 32:
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/contract_payment/parse_service.py
|
||||
用途:从 DOC/DOCX/PDF/TXT 抽取采购合同关键字段,并生成四个付款阶段的节点草稿。
|
||||
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
|
||||
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
|
||||
同一付款阶段的相同比例重复抽取不报重复;详情接口展示前对 issues 去重。
|
||||
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -84,6 +84,26 @@ def _parse_decimal(value: str | None) -> Decimal | None:
|
||||
return None
|
||||
|
||||
|
||||
def positive_amount(value: object) -> Decimal | None:
|
||||
"""把金额归一为大于 0 的 Decimal。
|
||||
|
||||
核心逻辑:员工在 OA「合同金额」手填 0 时,0 与空值一样,都不能当成有效总额。
|
||||
正文抽出的正数才会用于阶段金额,并在台账总额为 0 或空时回写。
|
||||
|
||||
Args:
|
||||
value: OA 字段、正文抽取结果或库里的金额,可为 str、Decimal 或 None。
|
||||
|
||||
Returns:
|
||||
大于 0 的金额;空值、0、负数或非法格式返回 None。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
parsed = _parse_decimal(str(value))
|
||||
if parsed is None or parsed <= 0:
|
||||
return None
|
||||
return parsed
|
||||
|
||||
|
||||
def _to_days(value: int, unit: str) -> int:
|
||||
"""
|
||||
将质保期限统一为自然日。
|
||||
@@ -284,8 +304,9 @@ def parse_contract_text(text: str, *, total_amount: Decimal | None = None, deliv
|
||||
|
||||
AI 触发时机:合同附件保存后,需要自动获得付款节点时调用。
|
||||
参数约束:text 为已抽取正文;不允许用模型猜测缺失日期或比例,结果必须可序列化为 JSON。
|
||||
口径约定:合同正文是条款事实的权威来源;正文能抽取金额/交货期限时,即使与 OA 表单不同,
|
||||
也以正文为准,不生成“与OA字段不一致”的待确认问题;仅当正文无法抽取时才回退 OA 表单值。
|
||||
口径约定:合同正文抽出的正数金额优先于 OA。OA「合同金额」为 0 或空视为未录入,
|
||||
不生成“与OA字段不一致”的待确认问题;正文没有正数时才回退 OA 里大于 0 的金额。
|
||||
两边都没有有效金额时进入待确认,不把 0 当成总额。
|
||||
Returns:
|
||||
包含 fields、nodes、status、issues、evidence 的结构化结果。
|
||||
"""
|
||||
@@ -293,14 +314,11 @@ def parse_contract_text(text: str, *, total_amount: Decimal | None = None, deliv
|
||||
if body.startswith("[binary:"):
|
||||
body = ""
|
||||
issues: list[str] = []
|
||||
# 合同正文是条款事实的权威来源;OA 字段只在正文未写明时作为补充。
|
||||
# 正文能抽到金额/交货期限即以其为准,即使与 OA 表单不同也不再生成“不一致”待确认问题,
|
||||
# 避免 OA 申请人录入错误把本可自动预警的合同永久卡在待复核。
|
||||
# [STEP 1] 金额:正文正数优先。OA 手填 0 与空值都不是有效总额,不能拿来乘付款比例。
|
||||
# 正文没有正数时,才用 OA 里大于 0 的金额;两边都没有则金额留空并进入待确认。
|
||||
amount_match = _MONEY_RE.search(body)
|
||||
amount_from_contract = _parse_decimal(amount_match.group(1)) if amount_match else None
|
||||
# OA 字段 total_amount 可能是字符串(如 _parse_amount 返回的 "221000.00"),统一归一为 Decimal,
|
||||
# 否则下方 `amount * percentage` 会因字符串与 Decimal 相乘抛出 TypeError。
|
||||
total_decimal = _parse_decimal(total_amount)
|
||||
amount_from_contract = positive_amount(amount_match.group(1)) if amount_match else None
|
||||
total_decimal = positive_amount(total_amount)
|
||||
# 正文缺失时需回退 OA 交货期限;OA 字段可能以字符串到达(如 "2026-09-10"),
|
||||
# 归一为 date 避免交付节点在 due_date.isoformat() 处因字符串抛错。
|
||||
delivery_due_date = _parse_date(delivery_due_date)
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
"""
|
||||
services/contract_payment/review_service.py
|
||||
|
||||
用途:把待确认合同的人工复核结果写入台账,使其可以进入付款预警。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、ContractPaymentEvent、ValidationError。
|
||||
逻辑:由 api/contract_payment 的 manual-review 路由调用。校验通过后覆盖四阶段节点,
|
||||
合同改为 parsed / active;勾选无此阶段的节点状态为 not_applicable,扫描预警时会被跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time
|
||||
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ContractPaymentContract, ContractPaymentEvent, ContractPaymentNode
|
||||
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
|
||||
|
||||
_STAGE_TYPES = ("prepayment", "shipment", "acceptance", "warranty")
|
||||
_DATE_REQUIRED = {"prepayment", "shipment"}
|
||||
_PERCENT_SUM = Decimal("100")
|
||||
_SUM_TOLERANCE = Decimal("0.001")
|
||||
_AMOUNT_TOLERANCE = Decimal("0.02")
|
||||
_MANUAL_ACCEPTANCE_PREFIX = "manual-review:"
|
||||
|
||||
|
||||
def apply_manual_review(
|
||||
contract_id: int,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
operator_id: int | None = None,
|
||||
) -> ContractPaymentContract:
|
||||
"""
|
||||
用人工填写的金额、比例和日期依据确认一份合同,并放入合同台账。
|
||||
|
||||
核心逻辑:先完整校验再落库。启用阶段的比例不能留空,合计须为 100%,金额须等于合同金额乘比例。
|
||||
预付款、出货款必须有日期依据;验收款、质保款日期可空。无此阶段写成 0 且不参与预警。
|
||||
预付款日期写入节点,合同归档日写入 oa_archive_at,供首轮预警按归档日加 7 天计算。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
payload: 采购单号、合同金额、可选合同编号、归档日,以及四个阶段。
|
||||
operator_id: 当前操作人用户主键,写入复核审计;缺失时只记录复核事实。
|
||||
|
||||
Returns:
|
||||
已提交并刷新后的合同记录。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同不存在。
|
||||
ValidationError: 采购单号、金额、比例合计、金额核对或必填日期不满足进入台账的条件。
|
||||
"""
|
||||
contract = db.session.get(ContractPaymentContract, contract_id)
|
||||
if contract is None:
|
||||
raise NotFoundError("合同不存在")
|
||||
# [STEP 1] 先把请求整理成可比较的数字和日期,失败时不改台账。
|
||||
review = _normalize_review(contract, payload)
|
||||
# [STEP 2] 主表进入台账。人工确认的金额允许覆盖原来的 0 或错误正数,这是复核本身的目的。
|
||||
contract.purchase_order_no = review["purchase_order_no"]
|
||||
contract.contract_no = review["contract_no"]
|
||||
contract.total_amount = review["total_amount"]
|
||||
if review["archive_date"] is not None:
|
||||
contract.oa_archive_at = datetime.combine(review["archive_date"], time.min)
|
||||
elif review["prepayment_date"] is not None:
|
||||
contract.oa_archive_at = datetime.combine(review["prepayment_date"], time.min)
|
||||
previous = dict(contract.parse_result_json or {})
|
||||
contract.parse_result_json = {
|
||||
**previous,
|
||||
"status": "parsed",
|
||||
"issues": [],
|
||||
"manual_review": {
|
||||
"operator_id": operator_id,
|
||||
"reviewed_at": datetime.utcnow().replace(microsecond=0).isoformat() + "Z",
|
||||
"previous_issues": list(previous.get("issues") or []),
|
||||
},
|
||||
}
|
||||
contract.parse_status = "parsed"
|
||||
contract.plan_status = "active"
|
||||
kept_ids: set[int] = set()
|
||||
for stage in review["stages"]:
|
||||
node = _upsert_stage_node(contract, stage)
|
||||
kept_ids.add(node.id)
|
||||
if stage["node_type"] == "shipment" and not stage["skipped"] and stage["basis_date"] is not None:
|
||||
contract.delivery_due_date = stage["basis_date"]
|
||||
for stale in db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id).all():
|
||||
if stale.id in kept_ids:
|
||||
continue
|
||||
# 同类型重复节点或历史淘汰节点不再参与预警,避免复核后仍扫到旧阶段。
|
||||
stale.amount = None
|
||||
stale.percentage = None
|
||||
stale.anchor_date = None
|
||||
stale.due_date = None
|
||||
stale.status = "not_applicable"
|
||||
stale.evidence_json = {**(stale.evidence_json or {}), "manual_review": "未纳入本次复核"}
|
||||
_sync_manual_acceptance_event(contract, review["acceptance_date"], operator_id=operator_id)
|
||||
db.session.commit()
|
||||
db.session.refresh(contract)
|
||||
return contract
|
||||
|
||||
|
||||
def _normalize_review(contract: ContractPaymentContract, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
把复核请求整理成四个阶段的金额、比例和日期。
|
||||
|
||||
核心逻辑:启用阶段空比例不算 0;合计须为 100%;金额与合同金额乘比例的差额不超过 0.02。
|
||||
合同编号留空时不覆盖成空字符串,以免撞上唯一约束。
|
||||
|
||||
Args:
|
||||
contract: 当前合同,用于合同编号冲突检查。
|
||||
payload: 原始 JSON。
|
||||
|
||||
Returns:
|
||||
可直接落库的采购单号、金额、归档日和阶段列表。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任一进入台账的条件不满足。
|
||||
"""
|
||||
purchase_order_no = normalize_purchase_order_no(payload.get("purchase_order_no"))
|
||||
if not purchase_order_no:
|
||||
raise ValidationError("请填写采购单号")
|
||||
if len(purchase_order_no) > 128:
|
||||
raise ValidationError("采购单号过长")
|
||||
total_amount = _parse_decimal(payload.get("total_amount"), "合同金额")
|
||||
if total_amount is None or total_amount <= 0:
|
||||
raise ValidationError("请填写大于 0 的合同金额")
|
||||
total_amount = total_amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
contract_no = str(payload.get("contract_no") or "").strip() or None
|
||||
if contract_no and len(contract_no) > 128:
|
||||
raise ValidationError("合同编号过长")
|
||||
if contract_no and contract_no != contract.contract_no:
|
||||
conflict = db.session.query(ContractPaymentContract).filter(
|
||||
ContractPaymentContract.contract_no == contract_no,
|
||||
ContractPaymentContract.id != contract.id,
|
||||
).first()
|
||||
if conflict:
|
||||
raise ValidationError("合同编号与另一条合同台账冲突")
|
||||
|
||||
raw_stages = payload.get("stages")
|
||||
if not isinstance(raw_stages, list):
|
||||
raise ValidationError("请提交四个付款阶段")
|
||||
by_type: dict[str, dict[str, Any]] = {}
|
||||
for item in raw_stages:
|
||||
if not isinstance(item, dict):
|
||||
raise ValidationError("付款阶段格式不正确")
|
||||
node_type = str(item.get("node_type") or "").strip()
|
||||
if node_type not in _STAGE_TYPES or node_type in by_type:
|
||||
raise ValidationError("请提交预付款、出货款、验收款、质保款各一次")
|
||||
by_type[node_type] = item
|
||||
if set(by_type) != set(_STAGE_TYPES):
|
||||
raise ValidationError("请提交预付款、出货款、验收款、质保款各一次")
|
||||
|
||||
stages: list[dict[str, Any]] = []
|
||||
enabled_percent = Decimal("0")
|
||||
enabled_count = 0
|
||||
for node_type in _STAGE_TYPES:
|
||||
item = by_type[node_type]
|
||||
skipped = bool(item.get("skipped"))
|
||||
if skipped:
|
||||
stages.append({
|
||||
"node_type": node_type,
|
||||
"skipped": True,
|
||||
"percentage": Decimal("0"),
|
||||
"amount": Decimal("0.00"),
|
||||
"basis_date": None,
|
||||
})
|
||||
continue
|
||||
percentage = _parse_decimal(item.get("percentage"), f"{_stage_label(node_type)}比例")
|
||||
amount = _parse_decimal(item.get("amount"), f"{_stage_label(node_type)}金额")
|
||||
if percentage is None:
|
||||
raise ValidationError("启用阶段的付款比例不能为空")
|
||||
if percentage < 0 or percentage > _PERCENT_SUM:
|
||||
raise ValidationError("启用阶段的付款比例须在 0 到 100 之间")
|
||||
if amount is None:
|
||||
raise ValidationError("启用阶段的金额不能为空")
|
||||
percentage = percentage.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
||||
amount = amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
expected = (total_amount * percentage / _PERCENT_SUM).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
if abs(amount - expected) > _AMOUNT_TOLERANCE:
|
||||
raise ValidationError("阶段金额须等于合同金额乘以比例")
|
||||
basis_date = _parse_date(item.get("basis_date"), f"{_stage_label(node_type)}日期依据")
|
||||
if node_type in _DATE_REQUIRED and basis_date is None:
|
||||
raise ValidationError("预付款、出货款须填写日期依据")
|
||||
enabled_percent += percentage
|
||||
enabled_count += 1
|
||||
stages.append({
|
||||
"node_type": node_type,
|
||||
"skipped": False,
|
||||
"percentage": percentage,
|
||||
"amount": amount,
|
||||
"basis_date": basis_date,
|
||||
})
|
||||
if enabled_count == 0 or abs(enabled_percent - _PERCENT_SUM) > _SUM_TOLERANCE:
|
||||
raise ValidationError("启用阶段的付款比例合计须为 100%")
|
||||
|
||||
prepayment = next(stage for stage in stages if stage["node_type"] == "prepayment")
|
||||
acceptance = next(stage for stage in stages if stage["node_type"] == "acceptance")
|
||||
return {
|
||||
"purchase_order_no": purchase_order_no,
|
||||
"contract_no": contract_no,
|
||||
"total_amount": total_amount,
|
||||
"archive_date": _parse_date(payload.get("archive_date"), "合同归档日"),
|
||||
"prepayment_date": None if prepayment["skipped"] else prepayment["basis_date"],
|
||||
"acceptance_date": None if acceptance["skipped"] else acceptance["basis_date"],
|
||||
"stages": stages,
|
||||
}
|
||||
|
||||
|
||||
def _upsert_stage_node(contract: ContractPaymentContract, stage: dict[str, Any]) -> ContractPaymentNode:
|
||||
"""
|
||||
按阶段类型覆盖或新建付款节点。
|
||||
|
||||
核心逻辑:已有 ERP 已付事实且本次仍启用该阶段时保留 paid 和付款日。无此阶段改为 not_applicable。
|
||||
预付款的到期判断用复核填入的日期依据;出货款同时作为交货期限。
|
||||
|
||||
Args:
|
||||
contract: 当前合同。
|
||||
stage: 已规范化的单个阶段。
|
||||
|
||||
Returns:
|
||||
已挂到会话上的节点。节点主键在 flush 后可用于排除陈旧行。
|
||||
"""
|
||||
node = (
|
||||
db.session.query(ContractPaymentNode)
|
||||
.filter_by(contract_id=contract.id, node_type=stage["node_type"])
|
||||
.order_by(ContractPaymentNode.id.asc())
|
||||
.first()
|
||||
)
|
||||
if node is None:
|
||||
node = ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code=stage["node_type"],
|
||||
node_type=stage["node_type"],
|
||||
reminder_days=0,
|
||||
offset_days=0,
|
||||
)
|
||||
db.session.add(node)
|
||||
db.session.flush()
|
||||
was_paid = str(node.status or "").strip().lower() == "paid"
|
||||
evidence = dict(node.evidence_json or {})
|
||||
evidence["manual_review"] = True
|
||||
node.amount = stage["amount"]
|
||||
node.percentage = stage["percentage"]
|
||||
node.reminder_days = 0
|
||||
node.offset_days = 0
|
||||
if stage["skipped"]:
|
||||
node.anchor_type = None
|
||||
node.anchor_date = None
|
||||
node.due_date = None
|
||||
node.status = "not_applicable"
|
||||
else:
|
||||
node.anchor_type = "acceptance_archive" if stage["node_type"] == "acceptance" else (
|
||||
"warranty_expiry" if stage["node_type"] == "warranty" else "erp_payment"
|
||||
)
|
||||
node.anchor_date = stage["basis_date"]
|
||||
node.due_date = stage["basis_date"]
|
||||
node.status = "paid" if was_paid else "active"
|
||||
node.evidence_json = evidence
|
||||
return node
|
||||
|
||||
|
||||
def _sync_manual_acceptance_event(
|
||||
contract: ContractPaymentContract,
|
||||
basis_date: date | None,
|
||||
*,
|
||||
operator_id: int | None,
|
||||
) -> None:
|
||||
"""
|
||||
在还没有 OA 验收归档时,用复核填入的日期补一条验收事件。
|
||||
|
||||
核心逻辑:验收款预警读取最早的 acceptance_archive,不读节点上的日期。
|
||||
仅维护 source_event_id 为人工复核的那一条;已有 OA 事件时不另造,避免改写归档日。
|
||||
日期清空或阶段被跳过时删掉人工事件。
|
||||
|
||||
Args:
|
||||
contract: 当前合同。
|
||||
basis_date: 复核填入的验收单归档日;空表示不补事件。
|
||||
operator_id: 写入事件载荷的操作人。
|
||||
|
||||
Returns:
|
||||
None。
|
||||
"""
|
||||
source_event_id = f"{_MANUAL_ACCEPTANCE_PREFIX}{contract.id}"
|
||||
manual = db.session.query(ContractPaymentEvent).filter_by(
|
||||
contract_id=contract.id,
|
||||
event_type="acceptance_archive",
|
||||
source_event_id=source_event_id,
|
||||
).first()
|
||||
if basis_date is None:
|
||||
if manual is not None:
|
||||
db.session.delete(manual)
|
||||
return
|
||||
official = db.session.query(ContractPaymentEvent).filter(
|
||||
ContractPaymentEvent.contract_id == contract.id,
|
||||
ContractPaymentEvent.event_type == "acceptance_archive",
|
||||
ContractPaymentEvent.source_event_id != source_event_id,
|
||||
).first()
|
||||
if official is not None:
|
||||
return
|
||||
if manual is None:
|
||||
manual = ContractPaymentEvent(
|
||||
contract_id=contract.id,
|
||||
event_type="acceptance_archive",
|
||||
event_date=basis_date,
|
||||
source_event_id=source_event_id,
|
||||
)
|
||||
db.session.add(manual)
|
||||
manual.event_date = basis_date
|
||||
manual.payload_json = {"source": "manual_review", "operator_id": operator_id}
|
||||
|
||||
|
||||
def _parse_decimal(value: Any, label: str) -> Decimal | None:
|
||||
"""
|
||||
把请求中的金额或比例转成 Decimal。
|
||||
|
||||
Args:
|
||||
value: 原始字段,允许空。
|
||||
label: 出错时展示的字段名。
|
||||
|
||||
Returns:
|
||||
空值返回 None,否则返回 Decimal。
|
||||
|
||||
Raises:
|
||||
ValidationError: 字段不是数字。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
raw = str(value).strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return Decimal(raw)
|
||||
except InvalidOperation as exc:
|
||||
raise ValidationError(f"{label}不是有效数字") from exc
|
||||
|
||||
|
||||
def _parse_date(value: Any, label: str) -> date | None:
|
||||
"""
|
||||
把 YYYY-MM-DD 转成日期。
|
||||
|
||||
Args:
|
||||
value: 原始字段,允许空。
|
||||
label: 出错时展示的字段名。
|
||||
|
||||
Returns:
|
||||
空值返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 日期格式不正确。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
raw = str(value).strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(raw[:10])
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{label}格式应为 YYYY-MM-DD") from exc
|
||||
|
||||
|
||||
def _stage_label(node_type: str) -> str:
|
||||
"""返回校验文案里的阶段名称。"""
|
||||
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
|
||||
@@ -2,10 +2,12 @@
|
||||
backend/app/services/contract_payment/sync_service.py
|
||||
|
||||
用途:将 OA 合同、验收归档通知同步为合同付款预警事实,并由 ERP `apa_file` 提供付款完成事实。
|
||||
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service。
|
||||
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service、file_assets.service。
|
||||
逻辑:合同申请单走 HTTP 待办/已办;验收归档走 OA SQL(formtable_main_324.cgdh × workflow_requestbase.currentnodetype=3);
|
||||
通知按 source_event_id 幂等;合同编号与采购单号以 OA 为准;列表翻页截断时入库但不推进增量断点;
|
||||
付款状态不再读取 OA 请款作业;合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。
|
||||
付款状态不再读取 OA 请款作业;采购单号去掉首尾空格和汉字后再与 ERP 匹配。合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。
|
||||
OA 合同金额为 0 或空时不当有效总额;正文抽出的正数在解析时回写台账,强制覆盖也不能把正数总额改成 0。
|
||||
OA/DMS 合同原文落库后标为已引用;临时清理删掉对象后,下载和重解析按附件 ID 重新下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +20,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentContract,
|
||||
@@ -34,9 +37,15 @@ from app.services.contract_payment.acceptance_oa_service import (
|
||||
)
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.dms_client import ContractDmsClient
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||||
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text, positive_amount
|
||||
from app.services.contract_payment.alert_service import bind_contract_owner_from_applicant
|
||||
from app.services.file_assets.service import create_derived_file_asset_from_bytes, generate_asset_no
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
generate_asset_no,
|
||||
mark_asset_referenced,
|
||||
read_asset_bytes,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
@@ -158,7 +167,7 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
if contract is None and contract_no:
|
||||
contract = db.session.query(ContractPaymentContract).filter_by(contract_no=contract_no).first()
|
||||
if contract is None and event_type == "acceptance_archive":
|
||||
purchase_order_no = str(item.get("purchase_order_no") or "").strip()
|
||||
purchase_order_no = normalize_purchase_order_no(item.get("purchase_order_no"))
|
||||
if purchase_order_no:
|
||||
contract = (
|
||||
db.session.query(ContractPaymentContract)
|
||||
@@ -169,10 +178,11 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
if contract is None:
|
||||
contract = ContractPaymentContract(
|
||||
contract_no=contract_no,
|
||||
purchase_order_no=str(item.get("purchase_order_no") or "").strip() or None,
|
||||
purchase_order_no=normalize_purchase_order_no(item.get("purchase_order_no")) or None,
|
||||
company_name=str(item.get("company_name") or "").strip() or None,
|
||||
supplier_name=str(item.get("supplier_name") or "").strip() or None,
|
||||
applicant_name=str(item.get("applicant_name") or "").strip() or None,
|
||||
total_amount=item.get("total_amount"),
|
||||
total_amount=positive_amount(item.get("total_amount")),
|
||||
currency=str(item.get("currency") or "").strip() or None,
|
||||
effective_date=_as_date(item.get("effective_date")),
|
||||
delivery_due_date=_as_date(item.get("delivery_due_date")),
|
||||
@@ -189,12 +199,23 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
else:
|
||||
if force:
|
||||
overwritten += _overwrite_oa_fields(contract, item, operator_id=operator_id)
|
||||
contract.purchase_order_no = contract.purchase_order_no or str(item.get("purchase_order_no") or "").strip() or None
|
||||
stored_po = normalize_purchase_order_no(contract.purchase_order_no) or None
|
||||
if stored_po != (str(contract.purchase_order_no or "").strip() or None):
|
||||
contract.purchase_order_no = stored_po
|
||||
contract.purchase_order_no = contract.purchase_order_no or normalize_purchase_order_no(item.get("purchase_order_no")) or None
|
||||
incoming_company = str(item.get("company_name") or "").strip()
|
||||
stored_company = str(contract.company_name or "").strip()
|
||||
# 早期解析把下拉框全部选项拼进了公司。选中项是其中一段时,用选中项替换整段。
|
||||
if incoming_company and (not stored_company or (incoming_company != stored_company and incoming_company in stored_company)):
|
||||
contract.company_name = incoming_company
|
||||
contract.applicant_name = contract.applicant_name or str(item.get("applicant_name") or "").strip() or None
|
||||
# [STEP 0] 普通同步只回填“仍为空”的 OA 标量字段,不用本次值覆盖已有值。
|
||||
# 合同金额/供应商/币别/生效/交货期限仅在创建时写入;早前创建时缺失的历史合同可由此自愈。
|
||||
# 合同金额的 0 与空相同,不能挡住正文正数,也不能用 OA 的 0 覆盖已有正数。
|
||||
contract.supplier_name = contract.supplier_name or str(item.get("supplier_name") or "").strip() or None
|
||||
contract.total_amount = contract.total_amount or item.get("total_amount")
|
||||
if positive_amount(contract.total_amount) is None:
|
||||
incoming_amount = positive_amount(item.get("total_amount"))
|
||||
if incoming_amount is not None:
|
||||
contract.total_amount = incoming_amount
|
||||
contract.currency = contract.currency or (str(item.get("currency") or "").strip() or None)
|
||||
contract.effective_date = contract.effective_date or _as_date(item.get("effective_date"))
|
||||
contract.delivery_due_date = contract.delivery_due_date or _as_date(item.get("delivery_due_date"))
|
||||
@@ -389,7 +410,7 @@ def ingest_acceptance_archives(items: list[dict[str, Any]]) -> tuple[int, int]:
|
||||
created = skipped = 0
|
||||
touched_ids: set[int] = set()
|
||||
for item in items:
|
||||
purchase_order_no = str(item.get("purchase_order_no") or "").strip()
|
||||
purchase_order_no = normalize_purchase_order_no(item.get("purchase_order_no"))
|
||||
request_id = str(item.get("request_id") or "").strip()
|
||||
if not purchase_order_no or not request_id:
|
||||
skipped += 1
|
||||
@@ -453,8 +474,8 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
"""
|
||||
显式强制同步时,用 OA 本次返回的非空字段覆盖合同主表值。
|
||||
|
||||
核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空;同时把
|
||||
before/after 和操作人写入 source_payload_json,便于追溯“为什么金额发生变化”。
|
||||
核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空。
|
||||
合同金额为 0 视为未录入,不覆盖台账上已有的正数总额。变更写入 source_payload_json。
|
||||
Args:
|
||||
contract: 待更新的合同主记录。
|
||||
item: OA 合同归档事件。
|
||||
@@ -463,10 +484,11 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
实际发生覆盖的字段数量。
|
||||
"""
|
||||
field_parsers = {
|
||||
"purchase_order_no": lambda value: str(value).strip() or None,
|
||||
"purchase_order_no": lambda value: normalize_purchase_order_no(value) or None,
|
||||
"company_name": lambda value: str(value).strip() or None,
|
||||
"supplier_name": lambda value: str(value).strip() or None,
|
||||
"applicant_name": lambda value: str(value).strip() or None,
|
||||
"total_amount": lambda value: value,
|
||||
"total_amount": lambda value: positive_amount(value),
|
||||
"currency": lambda value: str(value).strip() or None,
|
||||
"effective_date": lambda value: _as_date(value),
|
||||
"delivery_due_date": lambda value: _as_date(value),
|
||||
@@ -568,7 +590,7 @@ def sync_vendor_prepayment_requests(*, client: ContractOaClient) -> tuple[int, i
|
||||
skipped += 1
|
||||
continue
|
||||
contract_no = str(item.get("contract_no") or "").strip()
|
||||
purchase_order_no = str(item.get("purchase_order_no") or "").strip()
|
||||
purchase_order_no = normalize_purchase_order_no(item.get("purchase_order_no"))
|
||||
if not contract_no and not purchase_order_no:
|
||||
skipped += 1
|
||||
continue
|
||||
@@ -608,6 +630,155 @@ def sync_vendor_prepayment_requests(*, client: ContractOaClient) -> tuple[int, i
|
||||
return created, skipped
|
||||
|
||||
|
||||
def _stored_asset_is_readable(asset: FileAsset | None) -> bool:
|
||||
"""
|
||||
判断合同附件指向的 FileAsset 是否还能读出字节。
|
||||
|
||||
核心逻辑:软删除、上传未完成,或仍为 temporary 且已过期,都视为不可读。
|
||||
这类行不能再被普通同步当成“已保存”跳过,否则下载和重解析会一直报文件资产不存在。
|
||||
"""
|
||||
if asset is None or asset.deleted_at is not None:
|
||||
return False
|
||||
if str(asset.upload_status or "") != "ready":
|
||||
return False
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and str(asset.lifecycle_status or "") == "temporary":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _retain_contract_file_asset(asset: FileAsset | None) -> None:
|
||||
"""
|
||||
把合同原文标成已引用,避免临时文件清理任务删掉 MinIO 对象。
|
||||
|
||||
核心逻辑:派生资产默认 lifecycle=temporary、reference_count=0,到期会被 cleanup 软删并删对象。
|
||||
已经是 referenced 且没有过期时间时不再 +1,避免每次下载都抬高引用计数。
|
||||
"""
|
||||
if asset is None or asset.id is None or asset.deleted_at is not None:
|
||||
return
|
||||
if (
|
||||
str(asset.lifecycle_status or "") == "referenced"
|
||||
and asset.expires_at is None
|
||||
and int(asset.reference_count or 0) > 0
|
||||
):
|
||||
return
|
||||
mark_asset_referenced(asset)
|
||||
|
||||
|
||||
def _attachment_external_id(attachment: ContractPaymentAttachment) -> str:
|
||||
"""从附件元数据或 source_key 取出 OA/DMS 侧的附件 ID。"""
|
||||
meta = attachment.metadata_json if isinstance(attachment.metadata_json, dict) else {}
|
||||
explicit = str(meta.get("attachment_id") or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
prefix = f"{attachment.source}:"
|
||||
key = str(attachment.source_key or "")
|
||||
if key.startswith(prefix):
|
||||
return key[len(prefix):].strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _restore_contract_attachment_bytes(
|
||||
contract: ContractPaymentContract,
|
||||
attachment: ContractPaymentAttachment,
|
||||
) -> bytes:
|
||||
"""
|
||||
从 OA 或 DMS 重新下载已被清理的合同原文,并写回新的已引用 FileAsset。
|
||||
|
||||
核心逻辑:按 source 与附件 ID 拉取字节,挂到原合同父资产下,再标记 referenced。
|
||||
下载或落库失败时抛出 ATTACHMENT_UNAVAILABLE,避免前端只看到笼统的“文件资产不存在”。
|
||||
|
||||
Args:
|
||||
contract: 附件所属合同。OA 恢复使用 oa_record_id。
|
||||
attachment: 已落库但 FileAsset 不可读的附件行。
|
||||
|
||||
Returns:
|
||||
恢复后的原文字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 无法从原系统重新下载。code=CONTRACT_PAYMENT.ATTACHMENT_UNAVAILABLE。
|
||||
"""
|
||||
source = str(attachment.source or "").strip()
|
||||
external_id = _attachment_external_id(attachment)
|
||||
owner_id = contract.owner_user_id or _default_owner_user_id()
|
||||
try:
|
||||
if source == "oa":
|
||||
process_id = str(contract.oa_record_id or "").strip()
|
||||
if not process_id or not external_id or not owner_id:
|
||||
raise RuntimeError("缺少 OA 流程、附件 ID 或文件所有者")
|
||||
data, mime_type, response_name = ContractOaClient().download_attachment_by_id(
|
||||
process_id=process_id,
|
||||
attachment_id=external_id,
|
||||
)
|
||||
parent = _ensure_oa_parent_asset(owner_id=owner_id, contract=contract)
|
||||
asset_role = "contract_oa_attachment"
|
||||
elif source == "dms":
|
||||
if not external_id or not owner_id or not ContractDmsClient.is_configured():
|
||||
raise RuntimeError("缺少 DMS 附件 ID、文件所有者,或 DMS 未配置")
|
||||
data, mime_type, response_name = ContractDmsClient.download_attachment(external_id)
|
||||
parent = _ensure_dms_parent_asset(owner_id=owner_id, contract=contract)
|
||||
asset_role = "contract_dms_attachment"
|
||||
else:
|
||||
raise RuntimeError(f"不支持的附件来源 {source}")
|
||||
filename = (response_name or attachment.file_name or "contract").strip()[:255] or "contract"
|
||||
asset, _created = create_derived_file_asset_from_bytes(
|
||||
user_id=owner_id,
|
||||
parent=parent,
|
||||
data=data,
|
||||
filename=filename,
|
||||
mime_type=mime_type or mimetypes.guess_type(filename)[0],
|
||||
source_attachment_key=attachment.source_key,
|
||||
asset_role=asset_role,
|
||||
)
|
||||
# [STEP 1] 新落下的合同原文立刻改为已引用,避免再次进入 72 小时临时清理。
|
||||
_retain_contract_file_asset(asset)
|
||||
attachment.file_name = filename
|
||||
if mime_type:
|
||||
attachment.mime_type = mime_type[:128]
|
||||
attachment.file_asset_id = asset.id
|
||||
attachment.status = "stored"
|
||||
db.session.flush()
|
||||
return read_asset_bytes(asset)
|
||||
except NotFoundError:
|
||||
raise
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
"合同付款预警:合同原文已清理且重新下载失败 contract_id=%s attachment_id=%s",
|
||||
contract.id,
|
||||
attachment.id,
|
||||
)
|
||||
raise NotFoundError(
|
||||
"合同原文已被清理,且无法从原系统重新下载",
|
||||
code="CONTRACT_PAYMENT.ATTACHMENT_UNAVAILABLE",
|
||||
)
|
||||
|
||||
|
||||
def read_contract_attachment_bytes(
|
||||
contract: ContractPaymentContract,
|
||||
attachment: ContractPaymentAttachment,
|
||||
) -> bytes:
|
||||
"""
|
||||
读取合同原文。临时资产还在时顺手改为已引用;已被清理时从 OA 或 DMS 重新下载。
|
||||
|
||||
核心逻辑:先读本地 FileAsset;deleted_at 或过期 temporary 视为丢失,再按附件来源恢复。
|
||||
详情下载、单合同重解析和批量重解析都走这里,避免三处各自判断清理状态。
|
||||
|
||||
Args:
|
||||
contract: 附件所属合同,重新下载 OA 时要用 oa_record_id。
|
||||
attachment: 已落库的合同附件行。
|
||||
|
||||
Returns:
|
||||
原文字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 资产不存在且无法从原系统恢复。
|
||||
"""
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id) if attachment.file_asset_id else None
|
||||
if _stored_asset_is_readable(asset):
|
||||
_retain_contract_file_asset(asset)
|
||||
return read_asset_bytes(asset)
|
||||
return _restore_contract_attachment_bytes(contract, attachment)
|
||||
|
||||
|
||||
def save_oa_attachments(
|
||||
contract: ContractPaymentContract,
|
||||
*,
|
||||
@@ -651,10 +822,15 @@ def save_oa_attachments(
|
||||
contract_id=contract.id, source="oa", source_key=source_key
|
||||
).first()
|
||||
if existing and existing.file_asset_id and existing.status == "stored":
|
||||
# 已保存的附件不得随普通 OA 增量同步重复解析:该同步可能与详情页单合同重解析
|
||||
# 并发,旧解析结果会覆盖人工刚确认的状态。规则升级时只能由显式批量重解析执行。
|
||||
contract.status = "active"
|
||||
return {"found": len(attachments), "saved": saved}
|
||||
stored_asset = db.session.get(FileAsset, existing.file_asset_id)
|
||||
if _stored_asset_is_readable(stored_asset):
|
||||
# 已保存且仍可读的附件不得随普通 OA 增量同步重复解析:该同步可能与详情页单合同重解析
|
||||
# 并发,旧解析结果会覆盖人工刚确认的状态。规则升级时只能由显式批量重解析执行。
|
||||
# 顺手把仍是 temporary 的历史附件标为已引用,避免清理任务之后删掉原文。
|
||||
_retain_contract_file_asset(stored_asset)
|
||||
contract.status = "active"
|
||||
return {"found": len(attachments), "saved": saved}
|
||||
# 资产已被临时文件清理删掉时不要跳过,继续按当前 OA 下载地址重新落库。
|
||||
try:
|
||||
current_app.logger.info("合同付款预警:开始下载 OA 附件 attachment_id=%s label=%s", attachment_id, attachment.get("label"))
|
||||
data, mime_type, response_name = client.download_attachment(attachment)
|
||||
@@ -669,6 +845,7 @@ def save_oa_attachments(
|
||||
source_attachment_key=source_key,
|
||||
asset_role="contract_oa_attachment",
|
||||
)
|
||||
_retain_contract_file_asset(asset)
|
||||
if existing is None:
|
||||
existing = ContractPaymentAttachment(
|
||||
contract_id=contract.id, source="oa", source_key=source_key, file_name=filename
|
||||
@@ -686,7 +863,6 @@ def save_oa_attachments(
|
||||
contract.status = "active"
|
||||
db.session.flush()
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
build_payment_plan_from_bytes(contract, filename=filename, data=read_asset_bytes(asset))
|
||||
except Exception:
|
||||
current_app.logger.exception("合同付款预警:OA 附件已保存但付款条款解析失败,合同编号=%s", contract.contract_no)
|
||||
@@ -737,8 +913,9 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
使用已归档附件批量刷新存量合同解析结果。
|
||||
|
||||
AI 触发时机:解析规则升级后,管理员需要清理数据库中遗留的旧待确认原因时调用。
|
||||
核心逻辑:不依赖 OA 增量通知,直接按“盖章完成合同上传”优先选择已保存附件并重跑解析;
|
||||
没有可用附件的合同跳过,解析失败的合同保留 needs_review。
|
||||
核心逻辑:不走 OA 增量通知列表,按“盖章完成合同上传”优先选择已保存附件并重跑解析。
|
||||
原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析,不改 OA 表单字段。
|
||||
没有可用附件的合同跳过;解析失败的合同保留 needs_review;仅重新下载失败时不改解析状态。
|
||||
Args:
|
||||
limit: 本次最多重解析合同数,防止单个 Job 长时间占用 Worker。
|
||||
Returns:
|
||||
@@ -746,7 +923,6 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
"""
|
||||
rows = db.session.query(ContractPaymentContract).order_by(ContractPaymentContract.id.asc()).limit(max(int(limit or 0), 0)).all()
|
||||
scanned = reparsed = failed = skipped = 0
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
for contract in rows:
|
||||
scanned += 1
|
||||
attachments = (
|
||||
@@ -759,13 +935,12 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
skipped += 1
|
||||
continue
|
||||
attachment = min(attachments, key=lambda row: (0 if str((row.metadata_json or {}).get("label") or "").strip() == "盖章完成合同上传" else 1, row.id))
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
build_payment_plan_from_bytes(contract, filename=attachment.file_name, data=read_asset_bytes(asset))
|
||||
data = read_contract_attachment_bytes(contract, attachment)
|
||||
build_payment_plan_from_bytes(contract, filename=attachment.file_name, data=data)
|
||||
reparsed += 1
|
||||
except NotFoundError:
|
||||
failed += 1
|
||||
except Exception:
|
||||
failed += 1
|
||||
contract.parse_status = "needs_review"
|
||||
@@ -814,8 +989,11 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
source_key = f"dms:{attachment_id}"
|
||||
existing = db.session.query(ContractPaymentAttachment).filter_by(contract_id=contract.id, source="dms", source_key=source_key).first()
|
||||
if existing and existing.file_asset_id:
|
||||
contract.status = "active"
|
||||
return {"found": 1, "saved": 0}
|
||||
stored_asset = db.session.get(FileAsset, existing.file_asset_id)
|
||||
if _stored_asset_is_readable(stored_asset):
|
||||
_retain_contract_file_asset(stored_asset)
|
||||
contract.status = "active"
|
||||
return {"found": 1, "saved": 0}
|
||||
try:
|
||||
data, mime_type, response_name = ContractDmsClient.download_attachment(attachment_id)
|
||||
filename = response_name or str(row.get("LeafName") or "contract").strip() or "contract"
|
||||
@@ -838,6 +1016,7 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
source_attachment_key=source_key,
|
||||
asset_role="contract_dms_attachment",
|
||||
)
|
||||
_retain_contract_file_asset(asset)
|
||||
if existing is None:
|
||||
existing = ContractPaymentAttachment(contract_id=contract.id, source="dms", source_key=source_key, file_name=filename[:255])
|
||||
db.session.add(existing)
|
||||
@@ -852,7 +1031,6 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
db.session.flush()
|
||||
# 解析服务读取私有 FileAsset;失败时保留已保存附件并进入待复核。
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
build_payment_plan_from_bytes(contract, filename=filename, data=read_asset_bytes(asset))
|
||||
except Exception:
|
||||
contract.parse_status = "needs_review"
|
||||
@@ -962,9 +1140,10 @@ def build_payment_plan(contract: ContractPaymentContract, *, text: str = "") ->
|
||||
|
||||
def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
持久化条款与节点,并只用附件正文回填真实合同编号。
|
||||
持久化条款与节点,并用正文正数金额回填台账总额。
|
||||
|
||||
核心逻辑:保持节点编码稳定以支持重解析覆盖;仅解析成功时启用提醒,防止不完整条款触发正式通知。
|
||||
台账总额为 0 或空、且本次解析得到正数金额时,用该正数覆盖 0。已有正数总额不被正文改写。
|
||||
若验收归档事件已先入库,节点生成后立即回放归档日到验收款/质保款。
|
||||
Args:
|
||||
contract: 当前合同台账记录。
|
||||
@@ -992,9 +1171,10 @@ def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str
|
||||
contract.parse_status = "needs_review"
|
||||
else:
|
||||
contract.contract_no = parsed_contract_no
|
||||
if not contract.total_amount and fields.get("total_amount"):
|
||||
from decimal import Decimal
|
||||
contract.total_amount = Decimal(str(fields["total_amount"]))
|
||||
# [STEP 2] OA 手填 0 不是有效总额。解析结果里的正数(正文优先,否则为 OA 正数)只填补 0 或空值。
|
||||
parsed_amount = positive_amount(fields.get("total_amount"))
|
||||
if parsed_amount is not None and positive_amount(contract.total_amount) is None:
|
||||
contract.total_amount = parsed_amount
|
||||
contract.parse_result_json = result
|
||||
contract.parse_status = str(result.get("status") or "needs_review")
|
||||
contract.warranty_period_days = fields.get("warranty_period_days") or contract.warranty_period_days
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:在途仓自动调拨 Agent 一期独立领域模块入口。
|
||||
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
|
||||
Phase 1 起扩展 file_preparation / precheck_service 等。
|
||||
Phase 1 起扩展 file_preparation / matching_service 等。
|
||||
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
|
||||
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
"""
|
||||
@@ -108,8 +108,8 @@ def archive_snapshot(
|
||||
"""归档一份对象并持久化索引 + 审计。
|
||||
|
||||
Args:
|
||||
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_id: 业务对象编号(precheck_no / run_no)。
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_id: 业务对象编号(matching_no / run_no)。
|
||||
data: 待归档字节。
|
||||
original_filename: 原始文件名。
|
||||
content_type: MIME。
|
||||
|
||||
@@ -94,7 +94,7 @@ def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]:
|
||||
"aggregate_type": event.aggregate_type,
|
||||
"aggregate_id": event.aggregate_id,
|
||||
"run_no": event.run_no,
|
||||
"precheck_no": event.precheck_no,
|
||||
"matching_no": event.matching_no,
|
||||
"invoice_no": event.invoice_no,
|
||||
"item_id": event.item_id,
|
||||
"attempt_no": event.attempt_no,
|
||||
@@ -124,7 +124,7 @@ def build_transfer_audit_event(
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
run_no: str | None = None,
|
||||
precheck_no: str | None = None,
|
||||
matching_no: str | None = None,
|
||||
invoice_no: str | None = None,
|
||||
item_id: str | None = None,
|
||||
attempt_no: str | None = None,
|
||||
@@ -144,7 +144,7 @@ def build_transfer_audit_event(
|
||||
|
||||
Args:
|
||||
event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。
|
||||
run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。
|
||||
run_no / matching_no / invoice_no / item_id / attempt_no: 业务关联。
|
||||
actor_*: 操作者(user/worker/schedule/admin/rpa)。
|
||||
request_id / operation_id: 关联上下文。
|
||||
before / after: 前后快照(自动脱敏并计算 Hash)。
|
||||
@@ -159,7 +159,7 @@ def build_transfer_audit_event(
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=aggregate_id,
|
||||
run_no=run_no,
|
||||
precheck_no=precheck_no,
|
||||
matching_no=matching_no,
|
||||
invoice_no=invoice_no,
|
||||
item_id=item_id,
|
||||
attempt_no=attempt_no,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨自动排程编排(09:00 自动调拨)。
|
||||
|
||||
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
|
||||
用途:组合"每日恢复 → 自动匹配 → 自动执行 → 企微汇总通知",
|
||||
供 in-transit-transfer platform job 调用。
|
||||
依赖:recovery_service、precheck_service、execution_service、notification。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
|
||||
依赖:recovery_service、matching_service、execution_service、notification。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,9 +12,9 @@ from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.execution_service import execute_matching_items
|
||||
from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps, create_matching
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
|
||||
|
||||
|
||||
@@ -52,12 +52,16 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
except Exception as exc: # noqa: BLE001
|
||||
outcome.errors.append(f"recovery_failed: {exc}")
|
||||
try:
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=source_codes or [],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
)
|
||||
executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
# 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
|
||||
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役);
|
||||
# 无可执行行时门禁抛错,
|
||||
# 与旧流程一致记入 errors 不阻断通知阶段。
|
||||
executed = execute_matching_items(matching_id=summary.matching_id, deps=deps)
|
||||
outcome.run_no = executed.run_no
|
||||
outcome.run_status = executed.status
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
||||
@@ -28,7 +28,7 @@ _BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BacklogItemDTO:
|
||||
"""待处理池单项。"""
|
||||
"""待处理池单项(明细字段与匹配窗口列一致,供异常表格直接渲染)。"""
|
||||
|
||||
item_id: int
|
||||
source_code: str
|
||||
@@ -39,6 +39,15 @@ class BacklogItemDTO:
|
||||
age_days: int
|
||||
aging_level: str
|
||||
last_attempt_at: Optional[str] = None
|
||||
receipt_date: Optional[str] = None
|
||||
material_name: Optional[str] = None
|
||||
from_warehouse: Optional[str] = None
|
||||
to_warehouse: Optional[str] = None
|
||||
lot_no: Optional[str] = None
|
||||
receipt_quantity: Optional[str] = None
|
||||
external_quantity: Optional[str] = None
|
||||
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
|
||||
result_code: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -81,6 +90,10 @@ def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int:
|
||||
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
|
||||
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
|
||||
|
||||
排序:收料日期 → Invoice → 创建时间(业务稳定键,与重查/恢复等操作无关)。
|
||||
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
||||
以此排序会让正在处理的行在列表中跳位。
|
||||
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
@@ -98,7 +111,12 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
if source_code:
|
||||
query = query.filter_by(source_code=source_code)
|
||||
output: list[BacklogItemDTO] = []
|
||||
for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all():
|
||||
for item in query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
).all():
|
||||
age = _item_age_days(item, current)
|
||||
latest = _latest_attempt(item)
|
||||
if item.status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
@@ -117,6 +135,14 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
age_days=age,
|
||||
aging_level=level,
|
||||
last_attempt_at=latest.created_at.isoformat() if latest is not None else None,
|
||||
receipt_date=item.receipt_date,
|
||||
material_name=item.material_name,
|
||||
from_warehouse=item.from_warehouse,
|
||||
to_warehouse=item.to_warehouse,
|
||||
lot_no=item.lot_no,
|
||||
receipt_quantity=str(item.receipt_quantity) if item.receipt_quantity is not None else None,
|
||||
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
|
||||
result_code=item.result_code,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
|
||||
|
||||
cancelled = 0
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no:
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = reason_value
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""services/in_transit_transfer/capabilities.py
|
||||
|
||||
用途:在途调拨域的能力声明——本域经集成连接器暴露的能力契约(入参/出参 Schema、
|
||||
幂等语义、读写标志),代码注册、禁止管理端动态定义。
|
||||
依赖:integration_connector.capability(机制层:CapabilitySpec/注册表)。
|
||||
逻辑:本模块属于领域包而非连接器框架——框架只提供注册/校验机制,域契约随域代码
|
||||
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
|
||||
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
|
||||
测试 reset 注册表后也能重建。
|
||||
D13 能力收缩:清单只登记真实业务语义,恰两个能力——
|
||||
query_inventory(读,按组织批量查库存)与 create_transfer(写,单据级原子建单/
|
||||
审核/过账,幂等键语义 batch);原 stage/submit 合成能力取消,其接口定义保留为
|
||||
create_transfer 绑定的两个步骤(管理端绑定配置,不属本代码);verify_duplicate
|
||||
注册占位已随 T9 客户端重建一并移除(D6 无回读:不存在 verify 能力,客户端
|
||||
verify_duplicate 方法同步删除,绑定缺失由网关承担)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
)
|
||||
|
||||
# 库存查询读契约(列锚点=TIPTOP img_file 库存资料明细档,2026-09-24 官方字典):
|
||||
# 按组织批量查库存,目标为 (料号, 仓库, 批号) 元组列表——键分别对应
|
||||
# img01 料件编号 / img02 仓库编号 / img04 批号;warehouse_code 用库存中性命名,
|
||||
# 调拨方向语义(拨出/拨入)属 movement 契约,翻译发生在仓库映射/绑定层。
|
||||
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
|
||||
# [口径] img03 库位刻意不进键:调拨按(仓库+批号)粒度汇总,同键多库位行由
|
||||
# StockQueryResult.lookup 累加;img11/img12 官方字典=No Use,永不取数。
|
||||
_INVENTORY_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["external_org", "targets"],
|
||||
"properties": {
|
||||
"external_org": {"type": "string"},
|
||||
"targets": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "warehouse_code", "lot_no"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"warehouse_code": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
# 出参五键:三键回显目标元组(join 用)+ stock_quantity=img10 库存数量(官方字典
|
||||
# 确认 img11=No Use,账面在库只认 img10)+ stock_unit=img09 库存单位——ERP 侧
|
||||
# 确认不为空(2026-09-24),故为必填(响应缺失即校验失败 fail-closed);
|
||||
# 仅作参考展示锚点,不参与匹配键(交易单位语义归 movement 契约)。
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["rows"],
|
||||
"properties": {
|
||||
"rows": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "warehouse_code", "lot_no", "stock_quantity", "stock_unit"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"warehouse_code": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"stock_quantity": {"type": "number"},
|
||||
"stock_unit": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
# 写出参六态语义(T9 交接项落地):status 为规范终态之一——成功族
|
||||
# success/duplicate_success/duplicate_unverified + 失败族 business_failed/
|
||||
# technical_failed + 触发超时 timeout/result_unknown;补 duplicate_success/
|
||||
# duplicate_unverified 两态使引擎 classify+映射后的成功族能过本 Schema 校验。
|
||||
# document_no/verified_posted 仅在可证明时携带(无法证明为 null)。
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"success", "duplicate_success", "duplicate_unverified",
|
||||
"business_failed", "technical_failed", "timeout", "result_unknown",
|
||||
],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
# 调拨单行级 Schema:一张单的 lines 元素,七字段必填——行号、料号、拨出/拨入库位、
|
||||
# 批号、数量与交易单位(Task 7:unit 为 movement 契约第 11 字段)。
|
||||
_TRANSFER_LINE_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["line_no", "material_no", "from_warehouse", "to_warehouse", "lot_no", "quantity", "unit"],
|
||||
"properties": {
|
||||
"line_no": {"type": "integer"},
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"to_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
"unit": {"type": "string"},
|
||||
},
|
||||
}
|
||||
# 建单写契约(单据级入参):五元组一组一单,doc_no/submit_timestamp 由域生成器
|
||||
# (Task 6 document_id)终身复用,作为 batch 幂等键语义的载体。
|
||||
_TICKET_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
# R9:maker_account=触发执行的操作人账号(执行服务从 run.created_by 解析),
|
||||
# 经绑定直通给中间表 :maker_account(gls_cm07/08 制单人)。
|
||||
"required": ["external_org", "doc_no", "submit_timestamp", "doc_date", "posting_date", "lines", "maker_account"],
|
||||
"properties": {
|
||||
"external_org": {"type": "string"},
|
||||
"doc_no": {"type": "string"},
|
||||
"submit_timestamp": {"type": "string"},
|
||||
"doc_date": {"type": "string"},
|
||||
"posting_date": {"type": "string"},
|
||||
"maker_account": {"type": "string"},
|
||||
"lines": {"type": "array", "items": _TRANSFER_LINE_SCHEMA},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域的两个能力(幂等:已注册的同名跳过)。
|
||||
|
||||
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
|
||||
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
|
||||
"""
|
||||
registered = {spec.name for spec in list_capabilities()}
|
||||
for spec in (
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_INVENTORY_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_TICKET_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="batch",
|
||||
write=True,
|
||||
),
|
||||
):
|
||||
if spec.name not in registered:
|
||||
register_capability(spec)
|
||||
|
||||
|
||||
register_transfer_capabilities()
|
||||
@@ -0,0 +1,353 @@
|
||||
"""services/in_transit_transfer/capability_client.py
|
||||
|
||||
用途:在途调拨域的外部访问统一客户端——查询与建单均经 CapabilityGateway 按能力
|
||||
调用(D13 恰两能力:query_inventory 读 / create_transfer 写);域单据级契约
|
||||
(TransferOrder)、写结果分类(TransferWriteResult)与六态映射集中于此。
|
||||
依赖:integration_connector.gateway / transports.base / errors、app.core.errors。
|
||||
逻辑:查询按 (料号, 仓库, 批号) 元组批量进行(列锚点=img_file img01/img02/img04,
|
||||
库存中性命名,拨出语义归 movement 契约),组织键 external_org 取自
|
||||
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
|
||||
网关失败→AppError。写路径为纯委派(D13/D6):create_transfer 把单据级
|
||||
TransferOrder 展平为六键 params → 网关顺序引擎按绑定多步快照执行
|
||||
(resume=final_only 纯透传,business_ref 业务锚点纯透传落调用日志,
|
||||
D7② 策略由执行服务按单状态决定,本层零判断)→
|
||||
_to_write_result 六态显式映射。D6 无回读:不实现任何 ERP 状态回读/verify,
|
||||
result_unknown 仅产生于触发超时(timeout)与 duplicate_unverified(保守收敛),
|
||||
两者均禁止自动重试;绑定缺失由网关 BindingNotFoundError 原样上抛承担
|
||||
(单据级异常隔离在执行服务),契约冻结门(ExternalNotFrozenError)已随
|
||||
WSDL 冻结移除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
CREATE_TRANSFER_CAPABILITY = "in_transit_transfer.create_transfer"
|
||||
|
||||
EXTERNAL_QUERY_TIMEOUT_CODE = "TRANSFER.EXTERNAL_QUERY_TIMEOUT"
|
||||
EXTERNAL_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
class ExternalQueryTimeoutError(AppError):
|
||||
"""外部系统查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "external query timeout"):
|
||||
super().__init__(code=EXTERNAL_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ExternalResultUnknownError(AppError):
|
||||
"""外部系统写结果无法确认(执行服务人工 retrigger 链路使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "external result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=EXTERNAL_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账结果分类(域侧六态枚举)。
|
||||
|
||||
经 _to_write_result 映射后 client 实际只产出五态:duplicate_unverified 保守
|
||||
收敛为 result_unknown(D6),枚举保留该态供执行服务/审计语义完整。
|
||||
"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferOrder:
|
||||
"""域单据级契约(外部系统无关):一张 ERP 调拨单的全部域事实。
|
||||
|
||||
五元组一组一单(D3):doc_no/submit_timestamp 由域生成器终身复用,作为 ERP
|
||||
batch 幂等键语义的载体;本结构不感知 ERP 字段名——单头六字段 → 接口参数的
|
||||
翻译由网关绑定的 param_mapping 承担(T15 配置)。lines 行 dict 结构由能力
|
||||
Schema 把关(capabilities._TRANSFER_LINE_SCHEMA):line_no / material_no /
|
||||
from_warehouse / to_warehouse / lot_no / quantity / unit 七字段必填;
|
||||
行级 from/to 允许与单头不同(行集由行聚合层产出,client 禁止改写)。
|
||||
"""
|
||||
|
||||
external_org: str
|
||||
doc_no: str
|
||||
submit_timestamp: str
|
||||
doc_date: str
|
||||
posting_date: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
lines: list[dict]
|
||||
# R9:制单人=触发本次执行的运维账号(run.created_by → users.username),
|
||||
# 由执行服务解析后随单下传;空串=系统触发无操作人(ERP 侧按其规则处理)。
|
||||
maker_account: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockTarget:
|
||||
"""库存查询目标元组:料号 + 仓库 + 批号(ERP img01/img02/img04)。
|
||||
|
||||
warehouse_code 为库存中性命名(img02 仓库编号);调拨方向语义(拨出库位)
|
||||
属 movement 契约,由调用方从路由解析值换键名传入。
|
||||
"""
|
||||
|
||||
material_no: str
|
||||
warehouse_code: str
|
||||
lot_no: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockRow:
|
||||
"""外部系统返回的一行账面库存。
|
||||
|
||||
stock_quantity=img10 库存数量(img11 官方字典 No Use,不取数);
|
||||
stock_unit=img09 库存单位(ERP 侧确认恒非空,能力出参必填)——
|
||||
调拨行交易单位(unit)的唯一数据来源(单据字段只取 ERP,禁用货代文件
|
||||
单位列),空值由域层落 blocked_missing_unit。
|
||||
"""
|
||||
|
||||
material_no: str
|
||||
warehouse_code: str
|
||||
lot_no: str
|
||||
quantity: Decimal
|
||||
stock_unit: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockQueryResult:
|
||||
"""一次批量库存查询的结果;按元组精确匹配取数。"""
|
||||
|
||||
rows: tuple[StockRow, ...]
|
||||
|
||||
def lookup(self, *, material_no: str, warehouse_code: str, lot_no: str) -> Decimal | None:
|
||||
"""按三元组取库存数量;同键多行累加;未命中返回 None。"""
|
||||
total: Decimal | None = None
|
||||
for row in self.rows:
|
||||
if (row.material_no, row.warehouse_code, row.lot_no) == (material_no, warehouse_code, lot_no):
|
||||
total = row.quantity if total is None else total + row.quantity
|
||||
return total
|
||||
|
||||
def lookup_row(self, *, material_no: str, warehouse_code: str, lot_no: str) -> StockRow | None:
|
||||
"""按三元组取首个命中库存行(数量+单位一并取用);未命中返回 None。
|
||||
|
||||
同键多行时数量口径见 lookup(累加),单位取首行(ERP 同料号+批号
|
||||
账面单位唯一,img09 恒非空)。
|
||||
"""
|
||||
for row in self.rows:
|
||||
if (row.material_no, row.warehouse_code, row.lot_no) == (material_no, warehouse_code, lot_no):
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
class CapabilityClient:
|
||||
"""域内外部访问统一客户端:查询与建单均经 CapabilityGateway 委派。
|
||||
|
||||
Args:
|
||||
gateway: 可注入替身(测试);缺省 get_capability_gateway()。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None) -> None:
|
||||
self._gateway_override = gateway
|
||||
|
||||
def _gateway(self) -> Any:
|
||||
if self._gateway_override is not None:
|
||||
return self._gateway_override
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_stock(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
external_org: str,
|
||||
targets: list[StockTarget],
|
||||
) -> StockQueryResult:
|
||||
"""按组织批量查询库存(一次调用覆盖全部目标元组)。
|
||||
|
||||
Raises:
|
||||
ExternalQueryTimeoutError: 查询超时(可重试)。
|
||||
AppError: 网关失败(绑定缺失/调用失败,fail-closed)。
|
||||
"""
|
||||
if not targets:
|
||||
return StockQueryResult(rows=())
|
||||
result = self._gateway().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"external_org": external_org,
|
||||
"targets": [
|
||||
{
|
||||
"material_no": target.material_no,
|
||||
"warehouse_code": target.warehouse_code,
|
||||
"lot_no": target.lot_no,
|
||||
}
|
||||
for target in targets
|
||||
],
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ExternalQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
rows = [
|
||||
StockRow(
|
||||
material_no=str(row.get("material_no") or ""),
|
||||
warehouse_code=str(row.get("warehouse_code") or ""),
|
||||
lot_no=str(row.get("lot_no") or ""),
|
||||
quantity=Decimal(str(row.get("stock_quantity") or "0")),
|
||||
stock_unit=str(row.get("stock_unit") or ""),
|
||||
)
|
||||
for row in ((result.data or {}).get("rows") or [])
|
||||
]
|
||||
return StockQueryResult(rows=tuple(rows))
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
order: TransferOrder,
|
||||
final_only: bool = False,
|
||||
on_nonfinal_success: Callable[[Any, int], None] | None = None,
|
||||
business_ref: str | None = None,
|
||||
) -> TransferWriteResult:
|
||||
"""域建单唯一入口:解析 create_transfer 绑定(多步快照)→ 委派顺序引擎。
|
||||
|
||||
【AI 触发时机】执行服务对一张未完结单发起 ERP 建单/审核/过账时调用;
|
||||
防双单策略(全量 or 只跑末步)完全由调用方按单状态决定,本方法零策略判断。
|
||||
|
||||
核心逻辑:[STEP 1] 单 → params 六键展平(external_org/doc_no/submit_timestamp/
|
||||
doc_date/posting_date/lines);[STEP 2] 网关 call(capability=
|
||||
in_transit_transfer.create_transfer,resume=final_only)——多步顺序(先落
|
||||
中间表后触发过账)、参数翻译、逐步审计(同 operation_id 串联)与末步分类
|
||||
全部在网关顺序引擎,本方法不感知步骤数;[STEP 3] _to_write_result 六态映射。
|
||||
|
||||
Args:
|
||||
operation_id: 审计串联键(一次建单 N 步共享,IntegrationCall 按 step_index 定位)。
|
||||
order: 域单(doc_no/submit_timestamp 终身复用;lines 原样下传,禁止改写行集)。
|
||||
final_only: 纯透传网关 resume(D7②,由执行服务按单状态决定)——
|
||||
True = result_unknown / 重领取的 executing 单续跑:可能已建成单,
|
||||
禁止重插,网关跳过全部非末步(不建连、不审计、不回调)只执行末步;
|
||||
False = pending 首跑 / business_failed / technical_failed 重提交:
|
||||
全量重跑(DELETE 清同时间戳旧行 + 插入当前可执行行集,可并入新行,
|
||||
使用最新绑定配置)。
|
||||
on_nonfinal_success: 纯透传网关通用步进回调(R7,引擎在「非末步成功放行
|
||||
且审计落库后、进入下一步前」同步回调一次 (该步 BindingStep, 步号))——
|
||||
语义:中间表(stage)写成功断点标记(如 stage_confirmed_at 先落库
|
||||
再触发,D7③),关闭「submit 途中被杀→恢复重插→双单」窗口;回调体
|
||||
必须短小(仅库内毫秒级操作),异常将由引擎按该步失败中止
|
||||
(STEP_CALLBACK_FAILED)。本方法不调用、不包装、不吞异常。
|
||||
business_ref: 通用业务锚点(可空):纯透传网关落 IntegrationCall.business_ref
|
||||
(每步审计行携带,通常传 order.doc_no),供调用日志按业务单号检索/关联
|
||||
(Task 5 API 直接读列);不传为 NULL,现有消费者零改动。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / business_failed /
|
||||
technical_failed / result_unknown(见 _to_write_result 六态映射)。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 无可用绑定(fail-closed,原样上抛;单据级异常隔离由执行服务承担)。
|
||||
AppError: 能力未注册 / 入参不合 Schema / 映射失败等引擎 fail-closed 异常。
|
||||
|
||||
单号键约定(T15 的 response_mapping 配置按此产出):映射结果优先取
|
||||
document_no 键,缺失时兜底取 doc_no 键。
|
||||
"""
|
||||
params = {
|
||||
"external_org": order.external_org,
|
||||
"doc_no": order.doc_no,
|
||||
"submit_timestamp": order.submit_timestamp,
|
||||
"doc_date": order.doc_date,
|
||||
"posting_date": order.posting_date,
|
||||
"lines": order.lines,
|
||||
"maker_account": order.maker_account,
|
||||
}
|
||||
result = self._gateway().call(
|
||||
capability=CREATE_TRANSFER_CAPABILITY,
|
||||
context={},
|
||||
params=params,
|
||||
operation_id=operation_id,
|
||||
resume=final_only,
|
||||
on_nonfinal_success=on_nonfinal_success,
|
||||
business_ref=business_ref,
|
||||
)
|
||||
return _to_write_result(result)
|
||||
|
||||
|
||||
def _to_write_result(result: IntegrationCallResult) -> TransferWriteResult:
|
||||
"""把网关顺序引擎的分类结果显式映射为域写结果(纯函数,D6 无回读)。
|
||||
|
||||
六态映射(逐态注释):
|
||||
- success → success+document_no:末步映射确认建成并过账。
|
||||
- duplicate_success → duplicate_success+document_no:ERP 重触发返回原单号路径
|
||||
(引擎 classify 的 duplicate_success 已隐含 verified_posted=True),幂等收敛。
|
||||
- business_failed → 透传(枚举保留兼容;R8 后 WS 路径不再产生该态),
|
||||
error_code/error_message 原样保留;业务明细留在 result.data(已落审计)。
|
||||
- technical_failed → technical_failed:传输层/引擎技术失败与 ERP 拒单
|
||||
(code≠0)统一归此态透传。
|
||||
- timeout → result_unknown:D6 触发超时是 result_unknown 的唯一自然来源——
|
||||
无法确认是否落单,禁自动重试,等人工 retrigger(D7② 只执行末步)。
|
||||
- duplicate_unverified → result_unknown:保守收敛——声称重复但无法证明已过账,
|
||||
同样禁自动重试/重插(防双单);document_no 留作人工核实 SOP 证据。
|
||||
- result_unknown → 恒等透传。
|
||||
- 其余未映射态 → fail-closed 归 technical_failed(不猜测语义、不重试)。
|
||||
|
||||
失败原因透传(R8 用户口径:失败=失败+原因):classify 对未知响应形态只给
|
||||
通用 error_code,ERP 的 description 落在 data.message——失败族在
|
||||
error_message 为空时回填,行级 result_message 由此向用户展示原文。
|
||||
|
||||
单号键约定:document_no 优先、doc_no 兜底(T15 response_mapping 按此产出);
|
||||
映射未携带时回落网关 classify 的顶层 document_no(传输层直通路径)。
|
||||
"""
|
||||
mapped = result.data if isinstance(result.data, dict) else {}
|
||||
status = str(result.status or "")
|
||||
document_no = mapped.get("document_no") or mapped.get("doc_no") or result.document_no
|
||||
# 失败原因透传:classify 对未知响应形态只给通用 error_code,ERP 的
|
||||
# description 落在 mapped.message——error_message 为空时回填(R8 用户口径)。
|
||||
failure_message = result.error_message or (
|
||||
str(mapped["message"]) if mapped.get("message") not in (None, "") else None
|
||||
)
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=result.error_code,
|
||||
error_message=failure_message,
|
||||
)
|
||||
if status == "technical_failed":
|
||||
return TransferWriteResult(
|
||||
status="technical_failed",
|
||||
error_code=result.error_code,
|
||||
error_message=failure_message,
|
||||
)
|
||||
if status == "timeout":
|
||||
# D6:触发超时 → result_unknown(终态),禁自动重试;不臆造单号。
|
||||
return TransferWriteResult(status="result_unknown", error_code=result.error_code or "EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
if status == "duplicate_unverified":
|
||||
return TransferWriteResult(
|
||||
status="result_unknown",
|
||||
document_no=document_no,
|
||||
error_code=result.error_code or "TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "result_unknown":
|
||||
return TransferWriteResult(status="result_unknown", document_no=document_no, error_code=result.error_code)
|
||||
# 其余未映射态 fail-closed:归技术失败(error_code 固定,便于运维检索)。
|
||||
return TransferWriteResult(
|
||||
status="technical_failed",
|
||||
error_code="EXTERNAL_UNKNOWN_RESPONSE",
|
||||
error_message=f"unmapped gateway status: {status}",
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨 Chat Action Handler。
|
||||
|
||||
用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件
|
||||
(message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。
|
||||
依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。
|
||||
逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。
|
||||
用途:通过 Chat Turn Action 触发匹配/执行,并输出结构化卡片事件
|
||||
(message_type=transfer-match / transfer-result),供前端 TransferMessageView 渲染。
|
||||
依赖:action_registry、action_schema.TurnEvent、matching_service、execution_service、deps、serializers。
|
||||
逻辑:Dify 只产生受限候选 Action;真实匹配/执行由本确定性 Handler 执行并流式输出卡片。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,11 +15,11 @@ from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from app.services.in_transit_transfer.serializers import serialize_precheck_detail
|
||||
from app.services.in_transit_transfer.execution_service import execute_matching_items, get_run
|
||||
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
|
||||
from app.services.in_transit_transfer.serializers import serialize_matching_detail
|
||||
|
||||
ACTION_TRANSFER_PRECHECK = "transfer.precheck"
|
||||
ACTION_TRANSFER_MATCH = "transfer.match"
|
||||
ACTION_TRANSFER_EXECUTE = "transfer.execute"
|
||||
|
||||
|
||||
@@ -33,31 +33,33 @@ def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEv
|
||||
|
||||
|
||||
@register_action_handler
|
||||
class TransferPrecheckAction:
|
||||
"""预检 Action:创建(或恢复)预检并输出预检卡。"""
|
||||
class TransferMatchAction:
|
||||
"""匹配 Action:创建(或恢复)匹配并输出匹配卡。"""
|
||||
|
||||
action_type = ACTION_TRANSFER_PRECHECK
|
||||
action_type = ACTION_TRANSFER_MATCH
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""执行只读预检并输出 transfer-precheck 卡片。
|
||||
"""执行只读匹配并输出 transfer-match 卡片。
|
||||
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
|
||||
只读,不写 ERP。
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 匹配"等意图后由候选 Action 触发;
|
||||
只读,不写 外部系统。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
|
||||
business_date = str(payload.get("business_date") or business_date_now())
|
||||
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
summary = create_matching(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
detail = restore_precheck(summary.precheck_id)
|
||||
detail = restore_matching(summary.matching_id, deps=deps)
|
||||
yield _message(
|
||||
content="调拨预检完成",
|
||||
message_type="transfer-precheck",
|
||||
payload={"kind": "precheck", **serialize_precheck_detail(detail)},
|
||||
content="调拨匹配完成",
|
||||
message_type="transfer-match",
|
||||
payload={"kind": "match", **serialize_matching_detail(detail)},
|
||||
)
|
||||
|
||||
|
||||
@@ -70,18 +72,20 @@ class TransferExecuteAction:
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""执行勾选范围并输出 transfer-result 卡片。
|
||||
|
||||
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
|
||||
后台确定性服务完成写前复查与 ERP 原子写入。
|
||||
【AI 触发时机】:用户在匹配卡点击"直接生成调拨单"后触发;
|
||||
后台按匹配 scope 圈定 ready 行(invoice_nos 过滤)后按行执行,
|
||||
两道门禁(可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)与
|
||||
写前复查、外部系统 原子写入由确定性服务完成。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
matching_id = str(payload.get("matching_id") or "").strip()
|
||||
invoice_nos = payload.get("invoice_nos")
|
||||
invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_precheck(
|
||||
precheck_id=precheck_id,
|
||||
outcome = execute_matching_items(
|
||||
matching_id=matching_id,
|
||||
deps=deps,
|
||||
selected_invoice_nos=invoice_nos,
|
||||
invoice_nos=invoice_nos,
|
||||
)
|
||||
run_view = get_run(outcome.run_no)
|
||||
yield _message(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨并发参数与单写者约束。
|
||||
|
||||
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
|
||||
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
|
||||
外部系统 写并发恒为 1,同匹配只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
依赖:无(纯常量)。
|
||||
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
|
||||
"""
|
||||
@@ -10,16 +10,16 @@ from __future__ import annotations
|
||||
|
||||
# 一期冻结并发参数(与规格 §10 一致)。
|
||||
SOURCE_CONCURRENCY = 3
|
||||
ERP_QUERY_CONCURRENCY = 3
|
||||
ERP_WRITE_CONCURRENCY = 3
|
||||
外部系统_QUERY_CONCURRENCY = 3
|
||||
外部系统_WRITE_CONCURRENCY = 3
|
||||
|
||||
|
||||
def assert_single_writer(run_count: int) -> None:
|
||||
"""同预检最多一个执行 Run。
|
||||
"""同匹配最多一个执行 Run。
|
||||
|
||||
Args:
|
||||
run_count: 已存在的执行 Run 数。
|
||||
Raises:
|
||||
AssertionError: run_count > 1(一期硬约束)。
|
||||
"""
|
||||
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
|
||||
assert run_count <= 1, "External write concurrency must stay 1 for the same matching"
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨 DTO 与稳定错误码契约。
|
||||
|
||||
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
|
||||
用途:冻结前后端契约(匹配摘要、明细项、外部系统 单据聚合结果)与一期错误码,
|
||||
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
|
||||
依赖:标准库 dataclasses / decimal。
|
||||
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
|
||||
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
|
||||
(决策 20:外部系统 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,8 +20,8 @@ TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
||||
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_MATCH_EXPIRED = "TRANSFER_MATCH_EXPIRED"
|
||||
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
|
||||
TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN"
|
||||
@@ -37,8 +37,8 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||
TRANSFER_FILE_SCHEMA_INVALID,
|
||||
TRANSFER_INVOICE_CONFLICT,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_MATCH_EXPIRED,
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED,
|
||||
TRANSFER_RESULT_UNKNOWN,
|
||||
@@ -61,16 +61,21 @@ def require_known_error_code(code: str) -> None:
|
||||
raise ValueError(f"unknown transfer error code: {code}")
|
||||
|
||||
|
||||
# ---- 预检 DTO -------------------------------------------------------------
|
||||
# ---- 匹配 DTO -------------------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckCountsDTO:
|
||||
"""预检计数。"""
|
||||
class MatchingCountsDTO:
|
||||
"""匹配计数。"""
|
||||
|
||||
file_invoice_count: int = 0
|
||||
not_matured_count: int = 0
|
||||
prechecked_count: int = 0
|
||||
matched_count: int = 0
|
||||
executable_count: int = 0
|
||||
blocked_count: int = 0
|
||||
# 文件已落地、尚未查 ERP 库存的待查行(status='matching' +
|
||||
# result_code='pending_stock_check',evidence_sync 落地态)。
|
||||
pending_stock_check_count: int = 0
|
||||
# blocked_file_removed 行数(文件新版本中消失,已出清,不进默认视图/明细)。
|
||||
invalid_count: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -83,8 +88,8 @@ class RawLineRefDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckInvoiceItemDTO:
|
||||
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
|
||||
class MatchingItemDTO:
|
||||
"""匹配明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
|
||||
|
||||
source_code: str
|
||||
material_no: str
|
||||
@@ -98,29 +103,42 @@ class PrecheckInvoiceItemDTO:
|
||||
result: str
|
||||
receipt_date: str | None = None
|
||||
reason: str = ""
|
||||
erp_document_no: str | None = None
|
||||
external_document_no: str | None = None
|
||||
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
|
||||
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
||||
unit: str = ""
|
||||
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
|
||||
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
|
||||
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
|
||||
item_id: int = 0
|
||||
checked_at: str | None = None
|
||||
stale: bool = False
|
||||
file_current: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckSummaryDTO:
|
||||
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
|
||||
class MatchingSummaryDTO:
|
||||
"""匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。"""
|
||||
|
||||
precheck_id: str
|
||||
matching_id: str
|
||||
status: str
|
||||
business_date: str
|
||||
eligible_receipt_date_to: str
|
||||
expires_at: str
|
||||
counts: PrecheckCountsDTO
|
||||
counts: MatchingCountsDTO
|
||||
estimated_transfer_quantity: str
|
||||
estimated_erp_write_count: int
|
||||
precheck_hash: str
|
||||
estimated_external_write_count: int
|
||||
matching_hash: str
|
||||
|
||||
|
||||
# ---- 结果页 DTO(决策 20)--------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class ErpDocumentLineDTO:
|
||||
"""ERP 单据内物料明细。"""
|
||||
class ExternalDocumentLineDTO:
|
||||
"""外部系统 单据内物料明细。"""
|
||||
|
||||
material_no: str
|
||||
material_name: str
|
||||
@@ -130,8 +148,8 @@ class ErpDocumentLineDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpDocumentDTO:
|
||||
"""按 ERP 单号聚合的结果项。"""
|
||||
class ExternalDocumentDTO:
|
||||
"""按 外部系统 单号聚合的结果项。"""
|
||||
|
||||
document_no: str
|
||||
from_warehouse: str
|
||||
@@ -139,12 +157,12 @@ class ErpDocumentDTO:
|
||||
material_count: int
|
||||
total_quantity: Decimal
|
||||
posting_status: str
|
||||
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
lines: tuple[ExternalDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferExceptionDTO:
|
||||
"""未生成 ERP 单据的异常项(单独展示)。"""
|
||||
"""未生成 外部系统 单据的异常项(单独展示)。"""
|
||||
|
||||
source_code: str
|
||||
invoice_no: str
|
||||
@@ -155,31 +173,31 @@ class TransferExceptionDTO:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RunResultDTO:
|
||||
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
|
||||
"""Run 最终结果投影:外部系统 单据聚合 + 未生成单据异常。"""
|
||||
|
||||
run_no: str
|
||||
status: str
|
||||
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
|
||||
external_documents: tuple[ExternalDocumentDTO, ...] = field(default_factory=tuple)
|
||||
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
|
||||
"""按 ERP 单号聚合成功项,产出结果页文档视图。
|
||||
def aggregate_external_documents(items: Iterable[MatchingItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
|
||||
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
|
||||
|
||||
Args:
|
||||
items: 预检明细项(含 erp_document_no 与 result)。
|
||||
items: 匹配明细项(含 external_document_no 与 result)。
|
||||
Returns:
|
||||
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
|
||||
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
|
||||
"""
|
||||
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
|
||||
grouped: dict[str, list[MatchingItemDTO]] = {}
|
||||
for item in items:
|
||||
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.erp_document_no, []).append(item)
|
||||
documents: list[ErpDocumentDTO] = []
|
||||
if item.external_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.external_document_no, []).append(item)
|
||||
documents: list[ExternalDocumentDTO] = []
|
||||
for document_no in sorted(grouped):
|
||||
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
|
||||
lines = tuple(
|
||||
ErpDocumentLineDTO(
|
||||
ExternalDocumentLineDTO(
|
||||
material_no=row.material_no,
|
||||
material_name=row.material_name,
|
||||
specification=row.specification,
|
||||
@@ -188,7 +206,7 @@ def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[Er
|
||||
)
|
||||
for row in rows
|
||||
)
|
||||
documents.append(ErpDocumentDTO(
|
||||
documents.append(ExternalDocumentDTO(
|
||||
document_no=document_no,
|
||||
from_warehouse=rows[0].from_warehouse,
|
||||
to_warehouse=rows[0].to_warehouse,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨业务日期与成熟度策略。
|
||||
|
||||
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
|
||||
昨天及更早可预检,未来日期阻断)。
|
||||
昨天及更早可匹配,未来日期阻断)。
|
||||
依赖:标准库 zoneinfo / datetime。
|
||||
逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用,
|
||||
逻辑:所有日期判定集中在本模块,供 matching_service / recovery_service 复用,
|
||||
避免各服务各自计算导致口径漂移。
|
||||
"""
|
||||
|
||||
@@ -20,19 +20,30 @@ MATURITY_NOT_MATURED = "not_matured"
|
||||
MATURITY_FUTURE = "future"
|
||||
|
||||
|
||||
def parse_date(value: date | str) -> date:
|
||||
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
|
||||
def parse_date(value: date | datetime | str) -> date:
|
||||
"""将 date/datetime 或日期字符串归一化为 date。
|
||||
|
||||
Args:
|
||||
value: date 对象或 ISO 日期字符串。
|
||||
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
|
||||
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
|
||||
Returns:
|
||||
归一化后的 date。
|
||||
Raises:
|
||||
ValueError: 字符串不是合法 ISO 日期。
|
||||
ValueError: 字符串不是可识别的日期/日期时间。
|
||||
"""
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
return date.fromisoformat(str(value).strip())
|
||||
text = str(value).strip()
|
||||
try:
|
||||
return date.fromisoformat(text)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return datetime.fromisoformat(text).date()
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid date value: {value!r}") from exc
|
||||
|
||||
|
||||
def business_date_now(moment: datetime | None = None) -> date:
|
||||
@@ -51,6 +62,29 @@ def business_date_now(moment: datetime | None = None) -> date:
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
用途:判定"文件是否当天抓取"等新鲜度场景。数据库统一存 naive UTC 时间,
|
||||
直接取 .date() 与业务日期比较会漂移 8 小时,必须先换算窗口再比较。
|
||||
Args:
|
||||
now: 可选时刻;naive 按 UTC 兼容处理(与 business_date_now 口径一致)。
|
||||
Returns:
|
||||
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(SHANGHAI_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=ZoneInfo("UTC"))
|
||||
sh_now = now.astimezone(SHANGHAI_TZ)
|
||||
start_utc = (
|
||||
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=SHANGHAI_TZ)
|
||||
.astimezone(ZoneInfo("UTC"))
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
"""按 D+1 规则判定收料日期成熟度。
|
||||
|
||||
@@ -71,7 +105,7 @@ def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
|
||||
|
||||
def eligible_receipt_date_to(business_date: date | str) -> date:
|
||||
"""返回可进入预检的收料截止日期(业务日期 T - 1 天)。
|
||||
"""返回可进入匹配的收料截止日期(业务日期 T - 1 天)。
|
||||
|
||||
Args:
|
||||
business_date: 当前业务日期。
|
||||
|
||||
@@ -1,58 +1,101 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
|
||||
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
|
||||
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
|
||||
CONFIRM_TTL_SECONDS 的真实生效点(2026-09-24 接线,此前环境变量为死配置:
|
||||
TransferDeps 不传 strategy 时落数据类硬编码 600s)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
RouteNotResolvedError,
|
||||
RouteResolver,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
DEFAULT_CONFIRM_TTL_SECONDS,
|
||||
default_strategy,
|
||||
)
|
||||
|
||||
|
||||
class DefaultRouteResolver:
|
||||
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
|
||||
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
|
||||
|
||||
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
|
||||
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
|
||||
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
|
||||
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
|
||||
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须启用)。
|
||||
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
|
||||
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
Returns:
|
||||
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
|
||||
Raises:
|
||||
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
mapping = ShippingInventoryExternalMapping.query.filter_by(
|
||||
mappings = ShippingInventoryExternalMapping.query.filter_by(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
).first()
|
||||
if mapping is None or not mapping.external_organization_code:
|
||||
).all()
|
||||
selected = None
|
||||
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
|
||||
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
|
||||
key = str(warehouse_code or '').strip().upper()
|
||||
if key:
|
||||
selected = next(
|
||||
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
|
||||
)
|
||||
if selected is None:
|
||||
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
|
||||
else:
|
||||
selected = mappings[0] if mappings else None
|
||||
if selected is None or not selected.external_organization_code:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
|
||||
if not from_warehouse:
|
||||
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return RouteMapping(
|
||||
erp_org=mapping.external_organization_code,
|
||||
from_warehouse=source.fixed_warehouse_id or "",
|
||||
to_warehouse=mapping.external_warehouse_code,
|
||||
external_org=selected.external_organization_code,
|
||||
from_warehouse=from_warehouse,
|
||||
to_warehouse=selected.external_warehouse_code,
|
||||
)
|
||||
|
||||
|
||||
def _build_erp_adapter() -> CapabilityErpAdapter:
|
||||
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
|
||||
def _build_capability_client() -> CapabilityClient:
|
||||
"""装配调拨外部访问客户端:查询/建单统一走 CapabilityGateway(绑定缺失 fail-closed)。
|
||||
|
||||
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
|
||||
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
|
||||
承担;create_transfer 为单据级委派(T9)——顺序编排/分类在网关引擎,域侧只做
|
||||
TransferOrder → 六键 params 展平与六态结果映射;原「WSDL 冻结前 fail-closed」
|
||||
门(ExternalNotFrozenError)已移除,绑定缺失由网关 BindingNotFoundError 承担。
|
||||
"""
|
||||
return CapabilityErpAdapter()
|
||||
return CapabilityClient()
|
||||
|
||||
|
||||
_override: TransferDeps | None = None
|
||||
@@ -64,15 +107,39 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
_override = deps
|
||||
|
||||
|
||||
def _strategy_from_config():
|
||||
"""从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。
|
||||
|
||||
Why: IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS 只进 Flask config(settings.Config),
|
||||
而 TransferDeps.strategy 缺省落数据类硬编码 600s——环境变量曾是死配置,调大无效。
|
||||
无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。
|
||||
|
||||
Returns:
|
||||
TransferStrategyPolicy(confirm_ttl_seconds=max(1, 配置值),禁令项沿用默认)。
|
||||
"""
|
||||
try:
|
||||
raw = current_app.config.get(
|
||||
"IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS,
|
||||
)
|
||||
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
|
||||
raw = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
try:
|
||||
ttl = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
ttl = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
return replace(default_strategy(), confirm_ttl_seconds=max(1, ttl))
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return TransferDeps(
|
||||
file_repository=ShippingReceiptFileRepository(),
|
||||
rpa_trigger=_DefaultRpaTrigger(),
|
||||
route_resolver=DefaultRouteResolver(),
|
||||
erp=_build_erp_adapter(),
|
||||
capabilities=_build_capability_client(),
|
||||
strategy=_strategy_from_config(),
|
||||
)
|
||||
|
||||
|
||||
@@ -81,11 +148,25 @@ class _DefaultRpaTrigger:
|
||||
|
||||
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
|
||||
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
|
||||
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
|
||||
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
|
||||
"""
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
|
||||
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
|
||||
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is not None:
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is not None:
|
||||
profile = config.parsing_profile
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
|
||||
|
||||
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": bool(outcome.get("ok")),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""在途调拨单号与提交时间戳生成器(D2/D3 幂等锚)。
|
||||
|
||||
用途:生成调拨单的两个终身幂等锚——来源单号 doc_no(D2:
|
||||
{external_org}-OR-{yyMMdd}{全局PG序列:05d},超 99999 自然扩位、
|
||||
不按日重置)与提交时间戳 submit_timestamp(D3:32 位 uuid4 hex +
|
||||
yyyyMMddHHmmssSSS,总长 49)。
|
||||
依赖:标准库 uuid/datetime/typing;app.db(SQLAlchemy 实例,仅默认 PG
|
||||
序列读取使用);app.core.errors.ValidationError(external_org
|
||||
非空 fail-closed)。
|
||||
逻辑:execution_service 组建新单时各调用一次并终身复用(禁止重试换新:
|
||||
我方清理 / ERP 处理 / ERP 回带单号三方全锚定此值)。两函数均为纯
|
||||
函数,时刻与序列经参数注入;默认序列读取仅支持 PostgreSQL(迁移
|
||||
tt8b9c0d1e2f 创建 transfer_doc_no_seq),SQLite 等无序列后端不做
|
||||
兼容,测试一律注入 sequence_loader 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Callable
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 来源单号中间固定连接段(D2:{org}-OR-{yyMMdd}{seq})。
|
||||
_DOC_NO_MIDDLE = "-OR-"
|
||||
# 序列段最小位数(%05d;超 99999 自然扩位,禁止截断)。
|
||||
_SEQUENCE_MIN_DIGITS = 5
|
||||
# external_org 为空的错误码(与 frontend/src/locales/*/errors.json 四语言同步)。
|
||||
_ORG_REQUIRED_CODE = "TRANSFER.ORG_REQUIRED"
|
||||
# 默认 PG 全局序列(迁移 tt8b9c0d1e2f 创建;标识符为模块常量,非用户输入)。
|
||||
_PG_NEXTVAL_SQL = "SELECT nextval('transfer_doc_no_seq')"
|
||||
|
||||
|
||||
def new_submit_timestamp(now: datetime | None = None) -> str:
|
||||
"""生成 49 位提交时间戳(D3 幂等锚,一单生成一次终身复用)。
|
||||
|
||||
唯一性语义:前 32 位 uuid4 hex 承担唯一性(同一 now 两次调用必不同),
|
||||
后 17 位 yyyyMMddHHmmssSSS 仅承担可读时序;禁止依赖时间戳段做去重,
|
||||
禁止对同一单重复生成(重试/清理/ERP 回带均复用首次值)。
|
||||
|
||||
Args:
|
||||
now: 可选时刻(缺省 utcnow),仅用于生成可读时间戳段。
|
||||
|
||||
Returns:
|
||||
32 位小写 hex + 17 位 yyyyMMddHHmmssSSS 字符串,总长恒 49。
|
||||
"""
|
||||
moment = now if now is not None else datetime.utcnow()
|
||||
# [STEP 1] 可读段:秒级格式化 + 毫秒(取微秒前三位,恒 3 位)。
|
||||
readable = f"{moment.strftime('%Y%m%d%H%M%S')}{moment.microsecond // 1000:03d}"
|
||||
# [STEP 2] 唯一段:uuid4 hex(32 位小写,承担唯一性)。
|
||||
return f"{uuid.uuid4().hex}{readable}"
|
||||
|
||||
|
||||
def _pg_sequence_loader() -> int:
|
||||
"""从 PG 全局序列取下一单号序号(默认 sequence_loader 实现)。
|
||||
|
||||
注意:仅支持 PostgreSQL(transfer_doc_no_seq 由迁移 tt8b9c0d1e2f
|
||||
创建);SQLite 等无序列后端不做兼容——测试一律注入替身。
|
||||
|
||||
Returns:
|
||||
序列下一个值(int,全局单调递增,不按日重置)。
|
||||
"""
|
||||
result = db.session.execute(text(_PG_NEXTVAL_SQL))
|
||||
return int(result.scalar_one())
|
||||
|
||||
|
||||
def next_document_no(
|
||||
external_org: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
sequence_loader: Callable[[], int] | None = None,
|
||||
) -> str:
|
||||
"""生成来源单号(D2):{external_org}-OR-{yyMMdd}{seq:05d}。
|
||||
|
||||
业务约束:seq 来自全局 PG 序列(不按日重置,跨日不回绕);%05d 为
|
||||
最小五位数,超 99999 自然扩位(100000 → 6 位),禁止截断;yyMMdd
|
||||
日期段取自 now,仅用于可读性,唯一性由全局序列保证。
|
||||
|
||||
Args:
|
||||
external_org: 外部组织代码,禁止为空/全空白(fail-closed)。
|
||||
now: 可选时刻(缺省 utcnow),仅用于 yyMMdd 可读日期段。
|
||||
sequence_loader: 可选序列取值函数(缺省读 PG nextval;
|
||||
测试/非 PG 后端注入替身,禁止传入会重置序号的实现)。
|
||||
|
||||
Returns:
|
||||
形如 'DEMO-OR-26092400001' 的来源单号字符串。
|
||||
|
||||
Raises:
|
||||
ValidationError: external_org 为 None、空串或全空白
|
||||
(code=TRANSFER.ORG_REQUIRED)。
|
||||
"""
|
||||
# [STEP 1] fail-closed:组织代码缺失时拒绝生成(缺组织无法回带 ERP 对账)。
|
||||
if not isinstance(external_org, str) or not external_org.strip():
|
||||
raise ValidationError("external_org is required", code=_ORG_REQUIRED_CODE)
|
||||
|
||||
# [STEP 2] 取全局序列下一个值(缺省走 PG nextval)。
|
||||
loader = sequence_loader if sequence_loader is not None else _pg_sequence_loader
|
||||
seq = loader()
|
||||
|
||||
# [STEP 3] 拼装:日期段 yyMMdd(可读时序)+ 序列段 %05d(最小五位、自然扩位)。
|
||||
moment = now if now is not None else datetime.utcnow()
|
||||
return (
|
||||
f"{external_org}{_DOC_NO_MIDDLE}{moment.strftime('%y%m%d')}"
|
||||
f"{seq:0{_SEQUENCE_MIN_DIGITS}d}"
|
||||
)
|
||||
@@ -1,295 +0,0 @@
|
||||
"""在途调拨 ERP 访问统一边界(Adapter)。
|
||||
|
||||
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
|
||||
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
|
||||
verify_duplicate / 结果分类。
|
||||
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
|
||||
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
|
||||
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
|
||||
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
|
||||
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
|
||||
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryQuery:
|
||||
"""ERP 账面库存查询结果。"""
|
||||
|
||||
found: bool
|
||||
quantity: Decimal | None = None
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class ErpNotFrozenError(AppError):
|
||||
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP contract not frozen"):
|
||||
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ErpQueryTimeoutError(AppError):
|
||||
"""ERP 查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP query timeout"):
|
||||
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ErpResultUnknownError(AppError):
|
||||
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ErpWriteTimeoutError(TimeoutError):
|
||||
"""ERP 写超时;committed 表达是否可证明已落单。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
committed: bool | None,
|
||||
document_no: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.committed = committed
|
||||
self.document_no = document_no
|
||||
self.operation_id = operation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class ErpTransport(Protocol):
|
||||
"""ERP 传输层协议(SOAP 或测试替身)。"""
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""按 Invoice 查询账面库存。"""
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""原子建单/审核/过账(Phase 2)。"""
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""核实重复 Invoice 原单是否已审核过账。"""
|
||||
|
||||
|
||||
class SoapErpTransport:
|
||||
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
|
||||
|
||||
Args:
|
||||
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict[str, Any] | None = None) -> None:
|
||||
self._config = config or {}
|
||||
|
||||
def _require_frozen(self, operation: str) -> None:
|
||||
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
|
||||
if not str(self._config.get("endpoint") or "").strip():
|
||||
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("query_inventory")
|
||||
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("create_transfer")
|
||||
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("verify_duplicate")
|
||||
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
|
||||
|
||||
|
||||
class ErpAdapter:
|
||||
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
|
||||
|
||||
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
|
||||
self._transport = transport
|
||||
self._default_org = default_org
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询 ERP 账面库存并分类结果。
|
||||
|
||||
Args:
|
||||
operation_id / run_no / attempt_no / invoice_no / erp_org /
|
||||
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
|
||||
Returns:
|
||||
InventoryQuery。
|
||||
Raises:
|
||||
ErpQueryTimeoutError: 查询超时(可重试)。
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
try:
|
||||
response = self._transport.query_inventory(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
raise ErpQueryTimeoutError() from exc
|
||||
response = response if isinstance(response, dict) else {}
|
||||
if response.get("found"):
|
||||
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
|
||||
return InventoryQuery(found=False)
|
||||
|
||||
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
|
||||
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
|
||||
"""组装携带全部强制追踪字段的 ERP 请求。"""
|
||||
return {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
Raises:
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.create_transfer(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except ErpWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.verify_duplicate(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except (TimeoutError, ErpWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
response = response if isinstance(response, dict) else {}
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if status == "duplicate_success" and posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按 ERP 写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=False,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
|
||||
@@ -0,0 +1,339 @@
|
||||
"""services/in_transit_transfer/evidence_sync.py
|
||||
|
||||
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
|
||||
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
|
||||
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
|
||||
matching_service(_item_evaluated_sha 复用)/ models / audit。
|
||||
逻辑:一次解析三分类写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
|
||||
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
|
||||
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
|
||||
查的,作废);消失标记行复现 → 无论证据变化与否无条件恢复待查(防复现行卡死
|
||||
隐藏);文件里消失 → blocked_file_removed 且换戳到最新 sha(保证对齐入口
|
||||
row_shas 收敛直通)。全程零外部调用(不查 ERP、不触发 RPA);终态行绝不触碰,
|
||||
终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
|
||||
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.file_parser import parse_movement_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_FILE_REMOVED,
|
||||
RouteNotResolvedError,
|
||||
_item_evaluated_sha,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
filter_invoices_for_type,
|
||||
)
|
||||
|
||||
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
|
||||
# 表示「收料文件已落地、库存侧尚未核对」;禁用新状态值。
|
||||
SYNC_RESULT_PENDING = "pending_stock_check"
|
||||
|
||||
# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。
|
||||
_TERMINAL_ITEM_STATUSES = frozenset({
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncOutcome:
|
||||
"""一次来源同步的结果计数(审计与兜底日志的数据源)。"""
|
||||
|
||||
source_code: str
|
||||
file_sha256: str
|
||||
inserted: int = 0 # 文件有、本地无 → 插入待查行
|
||||
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
|
||||
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
|
||||
removed: int = 0 # 文件里消失 → blocked_file_removed
|
||||
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
|
||||
|
||||
|
||||
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
deps: TransferDeps(只用 file_repository 与 route_resolver)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
|
||||
Returns:
|
||||
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None。
|
||||
"""
|
||||
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
|
||||
if ready is None:
|
||||
return None
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready.rows)
|
||||
invoices = filter_invoices_for_type(
|
||||
aggregate_invoices(parsed, file_version=ready.file_version),
|
||||
TransferType.IN_TRANSIT_TO_HUB,
|
||||
)
|
||||
|
||||
# [STEP 1] 圈定本来源全部非终态既有行,按四元组建索引(matching_id 已放开
|
||||
# 非空,落地行不受 uq_transfer_invoice_items_matching_grain 保护,幂等去重
|
||||
# 由本应用层四元组负责)。
|
||||
existing = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing}
|
||||
|
||||
# [终态去重圈] 终态行同样纳入四元组去重范围(只查四列,轻量):若只在非终态
|
||||
# 行内去重,来源全终态后同文件重落地(同日 RPA 重试再触发落地桥 / align 兜底
|
||||
# 重解析)时 quad 缺席索引会被当全新行重插 pending——已执行的调拨单「复活」
|
||||
# 回待办池,存在以新 doc_no 二次真实执行的风险。终态不复活是冻结约束:
|
||||
# 重落地对终态行既不重插也不触碰。
|
||||
terminal_keys = {
|
||||
tuple(r)
|
||||
for r in TransferInvoiceItem.query.with_entities(
|
||||
TransferInvoiceItem.source_code,
|
||||
TransferInvoiceItem.invoice_no,
|
||||
TransferInvoiceItem.material_no,
|
||||
TransferInvoiceItem.receipt_date,
|
||||
).filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.in_(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
}
|
||||
|
||||
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "removed": 0, "skipped": 0}
|
||||
incoming_keys: set[tuple] = set()
|
||||
|
||||
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
|
||||
for invoice in invoices:
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso)
|
||||
incoming_keys.add(key)
|
||||
row = by_key.get(key)
|
||||
# [终态不复活] 该四元组已有终态行(已执行/已关闭等):同文件重落地跳过
|
||||
# 整行——不重插新 pending 行,也不触碰终态行本身(计数归 skipped 口径)。
|
||||
# 必须在插入判定之前拦截,否则全终态来源重落地会重开已执行的调拨单。
|
||||
if row is None and key in terminal_keys:
|
||||
counters["skipped"] += 1
|
||||
continue
|
||||
# [证据变化判定] 只比对收料事实(数量/批号/仓库);material_name 等展示
|
||||
# 字段不触发重置(重置会作废旧库存查询,代价是重查)。
|
||||
evidence_changed = row is None or (
|
||||
str(row.receipt_quantity) != str(invoice.receipt_quantity)
|
||||
or (row.lot_no or "") != (invoice.lot_no or "")
|
||||
or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "")
|
||||
)
|
||||
if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum:
|
||||
counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入(不续新鲜度)
|
||||
continue
|
||||
if row is None:
|
||||
from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice)
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, # 落地行尚无匹配归属(列已放开非空)
|
||||
source_code=source_code,
|
||||
invoice_no=invoice.invoice_no,
|
||||
material_no=invoice.material_no,
|
||||
material_name=invoice.material_name,
|
||||
specification=invoice.specification,
|
||||
receipt_date=receipt_date_iso,
|
||||
status=status_machine.TransferStatus.MATCHING.value,
|
||||
result_code=SYNC_RESULT_PENDING,
|
||||
result_message=None,
|
||||
from_warehouse=from_wh,
|
||||
to_warehouse=to_wh,
|
||||
receipt_quantity=str(invoice.receipt_quantity),
|
||||
external_quantity=None,
|
||||
lot_no=invoice.lot_no or "",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
unit="", # 单位只取 ERP stock_unit,匹配查询时落列
|
||||
raw_lines_json=[
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
],
|
||||
updated_at=now,
|
||||
))
|
||||
counters["inserted"] += 1
|
||||
continue
|
||||
# [Important② 复现行] 消失标记行(blocked_file_removed)重新出现在最新
|
||||
# 文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)已
|
||||
# 失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
|
||||
# 非终态行恢复不违反终态冻结。
|
||||
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
|
||||
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
|
||||
# 据此收敛直通)。
|
||||
row.raw_lines_json = [
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
]
|
||||
# [Important① 展示字段] 名称/规格属展示字段:进入非跳过分支即刷新
|
||||
# (放在证据分支判断之外)——是否重置待查只由三证据字段决定,避免纯
|
||||
# 名称变更落入 refreshed 后展示值随新戳固化(align 直通后永不更新)。
|
||||
row.material_name = invoice.material_name
|
||||
row.specification = invoice.specification
|
||||
if evidence_changed:
|
||||
# [STEP 3] 收料事实变化:刷新证据值(数量/批号/仓库)。
|
||||
row.receipt_quantity = str(invoice.receipt_quantity)
|
||||
row.lot_no = invoice.lot_no or ""
|
||||
row.receipt_warehouse_code = invoice.warehouse_code or ""
|
||||
if evidence_changed or restored_from_removed:
|
||||
# [重置/恢复] 值变 → 重置回待查(旧库存是对旧数量查的,作废);
|
||||
# 复现行 → 恢复待查(重新进入待办池,计数同归 reset_pending 口径)。
|
||||
row.status = status_machine.TransferStatus.MATCHING.value
|
||||
row.result_code = SYNC_RESULT_PENDING
|
||||
row.result_message = None
|
||||
row.external_quantity = None # 旧库存对旧数量,作废待重查
|
||||
counters["reset_pending"] += 1
|
||||
else:
|
||||
counters["refreshed"] += 1
|
||||
row.updated_at = now
|
||||
|
||||
# [STEP 4] 文件里消失的非终态行 → blocked_file_removed(终态行不在 by_key,绝不触碰)。
|
||||
for key, row in by_key.items():
|
||||
if key in incoming_keys:
|
||||
continue
|
||||
# [版本戳] 消失标记行同样换戳到最新文件 sha(保留原 sheet/row_no 行定位,
|
||||
# 只更新版本号与 sha):否则行版本戳停在旧文件,align 判据 row_shas 永不
|
||||
# 收敛为 {latest_sha},每次兜底都会空转重解析。
|
||||
row.raw_lines_json = [
|
||||
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
|
||||
for line in (row.raw_lines_json or [])
|
||||
]
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_FILE_REMOVED
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
row.updated_at = now
|
||||
counters["removed"] += 1
|
||||
|
||||
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
|
||||
db.session.flush()
|
||||
outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "", **counters)
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EVIDENCE_SYNCED",
|
||||
aggregate_type="transfer_source",
|
||||
aggregate_id=source_code,
|
||||
actor_type="system",
|
||||
result="success",
|
||||
after={
|
||||
"file_sha256": outcome.file_sha256,
|
||||
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
|
||||
"reset_pending": outcome.reset_pending, "removed": outcome.removed,
|
||||
"skipped": outcome.skipped,
|
||||
},
|
||||
))
|
||||
return outcome
|
||||
|
||||
|
||||
def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict:
|
||||
"""兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。
|
||||
|
||||
【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用;
|
||||
落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表。
|
||||
deps: TransferDeps(透传 sync_source_rows)。
|
||||
business_date: 业务日期(文件新鲜度口径)。
|
||||
now: 新鲜度基准。
|
||||
Returns:
|
||||
{source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。
|
||||
"""
|
||||
outcomes: dict = {}
|
||||
for code in source_codes:
|
||||
latest = resolve_source_file_status(source_code=code) or {}
|
||||
latest_sha = latest.get("file_sha256")
|
||||
if not latest_sha:
|
||||
outcomes[code] = None
|
||||
continue
|
||||
rows = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
row_shas = {_item_evaluated_sha(r) for r in rows}
|
||||
if row_shas == {latest_sha}:
|
||||
outcomes[code] = None # 已对齐:直通
|
||||
continue
|
||||
outcomes[code] = sync_source_rows(source_code=code, deps=deps,
|
||||
business_date=business_date, now=now)
|
||||
return outcomes
|
||||
|
||||
|
||||
def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]:
|
||||
"""同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。
|
||||
|
||||
Args:
|
||||
deps: TransferDeps(只用 route_resolver)。
|
||||
source_code: 来源实例编码。
|
||||
invoice: AggregatedInvoice(取 invoice_no / warehouse_code)。
|
||||
Returns:
|
||||
(from_warehouse, to_warehouse);未配置路由返回 ("", "")。
|
||||
"""
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
return route.from_warehouse, route.to_warehouse
|
||||
except RouteNotResolvedError:
|
||||
return "", ""
|
||||
|
||||
|
||||
def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool:
|
||||
"""收料回调桥专用入口:同步 + 自行 commit + 异常全吞(仅 warning 日志)。
|
||||
|
||||
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
|
||||
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
|
||||
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(收料单元行上的 source_code)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at)。
|
||||
Returns:
|
||||
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志)。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
outcome = sync_source_rows(source_code=source_code, deps=_default_deps(),
|
||||
business_date=business_date, now=now)
|
||||
# [桥隔离] sync_source_rows 只 flush 不 commit;桥由回调主链路在归档
|
||||
# commit 之后独立调用,提交时机不归调用方管(B3 持久性教训),必须
|
||||
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的待办行。
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s removed=%s skipped=%s",
|
||||
source_code, outcome.inserted, outcome.refreshed,
|
||||
outcome.reset_pending, outcome.removed, outcome.skipped)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
|
||||
# 绝不允许波及收料归档终态;丢失的同步由对齐入口 align_scope_rows 兜底。
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
|
||||
db.session.rollback()
|
||||
return False
|
||||
|
||||
|
||||
def _default_deps():
|
||||
"""装配默认 TransferDeps(桥入口专用:收料链路无 deps 可透传)。
|
||||
|
||||
Returns:
|
||||
TransferDeps(测试经 deps._override 注入 Fake 时返回注入值)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.deps import get_transfer_dependencies
|
||||
|
||||
return get_transfer_dependencies()
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨七 Sheet 异常 Excel 导出。
|
||||
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
|
||||
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/外部系统无库存/
|
||||
外部系统技术失败/外部系统结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
依赖:openpyxl、models、execution_service。
|
||||
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
|
||||
Secret 明文永不写入单元格(仅输出业务字段)。
|
||||
@@ -21,9 +21,9 @@ from app.core.errors import NotFoundError
|
||||
EXCEL_SHEET_NAMES = [
|
||||
"执行汇总",
|
||||
"数量不一致",
|
||||
"ERP无库存",
|
||||
"ERP技术失败",
|
||||
"ERP结果未知",
|
||||
"外部系统无库存",
|
||||
"外部系统技术失败",
|
||||
"外部系统结果未知",
|
||||
"通知失败",
|
||||
"原始文件追溯",
|
||||
]
|
||||
@@ -52,9 +52,9 @@ def build_exceptions_workbook(run_no: str) -> bytes:
|
||||
workbook.remove(workbook.active)
|
||||
|
||||
_sheet_summary(workbook, run, items)
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
|
||||
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "matching_expired"})
|
||||
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_unknown(workbook, items)
|
||||
_sheet_notification(workbook, run)
|
||||
_sheet_raw_trace(workbook, items)
|
||||
@@ -71,30 +71,30 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
|
||||
sheet.append(["Run 状态", run.status])
|
||||
sheet.append(["通知状态", run.notification_status])
|
||||
sheet.append([])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
|
||||
sheet.append(["Invoice", "来源", "料号", "匹配结果", "外部系统 单号"])
|
||||
for item in items:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.result_code or item.status, item.erp_document_no or "",
|
||||
item.result_code or item.status, item.external_document_no or "",
|
||||
])
|
||||
|
||||
|
||||
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
|
||||
"""按阻断原因归类 Sheet。"""
|
||||
sheet = workbook.create_sheet(sheet_name)
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
|
||||
for item in items:
|
||||
if (item.result_code or "") in codes or item.status in codes:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.receipt_quantity, item.erp_quantity or "",
|
||||
item.receipt_quantity, item.external_quantity or "",
|
||||
item.result_message or item.result_code or item.status,
|
||||
])
|
||||
|
||||
|
||||
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
|
||||
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("ERP结果未知")
|
||||
"""外部系统 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("外部系统结果未知")
|
||||
sheet.append(["Invoice", "来源", "料号", "说明"])
|
||||
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
|
||||
for item in items:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,7 +9,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
@@ -34,6 +34,12 @@ class ParsedReceiptRow:
|
||||
specification: str
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
# 交易单位列原值(movement 契约第 11 字段 unit,计划 D4):仅 trim 空白、
|
||||
# 不做单位换算/清洗;空值不产生解析失败,由匹配阶段行级 blocked_missing_unit 阻断。
|
||||
unit: str = ""
|
||||
|
||||
|
||||
class ReceiptFileSchemaError(AppError):
|
||||
@@ -53,6 +59,18 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
|
||||
rows.append({"row_no": row_no, "reason": reason})
|
||||
|
||||
|
||||
def _is_unreceived_row(date_value: Any) -> bool:
|
||||
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
|
||||
|
||||
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
|
||||
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
|
||||
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配;
|
||||
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
|
||||
"""
|
||||
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
|
||||
|
||||
|
||||
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
||||
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
|
||||
|
||||
@@ -60,8 +78,11 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
doc_no → invoice_no(幂等/汇总键)
|
||||
quantity → receipt_quantity(严格数量匹配)
|
||||
movement_date → receipt_date(成熟过滤)
|
||||
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
|
||||
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
|
||||
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
unit 原值透传至 ParsedReceiptRow.unit(movement 契约第 11 字段,仅 trim,
|
||||
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
|
||||
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(行内来源身份一致性校验)。
|
||||
@@ -120,7 +141,7 @@ def _parse_rows(
|
||||
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
|
||||
到原始行字段名的映射(如 {invoice_no: doc_no})。
|
||||
Returns:
|
||||
已校验的 ParsedReceiptRow 列表。
|
||||
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
|
||||
Raises:
|
||||
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
"""
|
||||
@@ -137,7 +158,7 @@ def _parse_rows(
|
||||
invoice_no = str(row.get(invoice_key) or "").strip()
|
||||
material_no = str(row.get(material_key) or "").strip()
|
||||
sheet = str(row.get("sheet") or "").strip()
|
||||
receipt_date_raw = str(row.get(date_key) or "").strip()
|
||||
receipt_date_value = row.get(date_key)
|
||||
quantity_raw = row.get(quantity_key)
|
||||
|
||||
if not sheet or not row_no:
|
||||
@@ -153,10 +174,12 @@ def _parse_rows(
|
||||
if row_source and row_source.upper() != str(source_code).upper():
|
||||
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
||||
continue
|
||||
if _is_unreceived_row(receipt_date_value):
|
||||
continue
|
||||
try:
|
||||
receipt_date = parse_date(receipt_date_raw)
|
||||
receipt_date = parse_date(receipt_date_value)
|
||||
except ValueError:
|
||||
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
|
||||
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
|
||||
continue
|
||||
try:
|
||||
quantity = validate_receipt_quantity(quantity_raw)
|
||||
@@ -173,6 +196,10 @@ def _parse_rows(
|
||||
specification=str(row.get("specification") or "").strip(),
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=quantity,
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
# unit 原值透传(movement 契约第 11 字段):仅 trim,空值解析放行。
|
||||
unit=str(row.get("unit") or "").strip(),
|
||||
))
|
||||
if errors:
|
||||
raise ReceiptFileSchemaError(rows=errors)
|
||||
|
||||
@@ -84,7 +84,7 @@ def ensure_receipt_file_ready(
|
||||
outcome = rpa_trigger.trigger(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
reason="precheck_missing_ready_file",
|
||||
reason="matching_missing_ready_file",
|
||||
)
|
||||
outcome = outcome if isinstance(outcome, dict) else {}
|
||||
if outcome.get("ok"):
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
"""services/in_transit_transfer/gateway_adapter.py
|
||||
|
||||
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
|
||||
(query_inventory 是首个配置绑定消费者)。
|
||||
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
|
||||
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
|
||||
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
|
||||
class CapabilityErpAdapter:
|
||||
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
|
||||
|
||||
Args:
|
||||
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None) -> None:
|
||||
self._gateway = gateway
|
||||
|
||||
def _gateway_or_default(self):
|
||||
if self._gateway is not None:
|
||||
return self._gateway
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询外部系统库存(经连接器框架)。
|
||||
|
||||
Args/Raises:
|
||||
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
|
||||
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
|
||||
来源专属绑定待 P2/P3。
|
||||
"""
|
||||
result = self._gateway_or_default().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"invoice_no": invoice_no,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ErpQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
data = result.data or {}
|
||||
found = bool(data.get("found"))
|
||||
qty = data.get("quantity")
|
||||
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨 Invoice 多行汇总与冲突阻断。
|
||||
"""在途调拨 Invoice 多行汇总。
|
||||
|
||||
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
|
||||
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
|
||||
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
|
||||
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
|
||||
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
|
||||
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
|
||||
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,6 +30,12 @@ class AggregatedInvoice:
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
raw_lines: tuple[RawLineRefDTO, ...]
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
# 组内首行交易单位原值(movement 契约第 11 字段 unit,计划 D4):与 lot_no 同为
|
||||
# 「组内首行」口径;空值在匹配阶段行级 blocked_missing_unit 阻断,不在此换算/清洗。
|
||||
unit: str = ""
|
||||
|
||||
|
||||
class InvoiceConflictError(AppError):
|
||||
@@ -45,34 +51,25 @@ class InvoiceConflictError(AppError):
|
||||
|
||||
|
||||
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
|
||||
"""按 Invoice 汇总收料数量并保留原始行证据。
|
||||
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
|
||||
|
||||
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
|
||||
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
|
||||
自然拆分为多张发票(部分交付场景),不做整单阻断。
|
||||
Args:
|
||||
rows: 已校验的解析行。
|
||||
file_version: 当前文件版本(写入原始行追溯)。
|
||||
Returns:
|
||||
汇总后的 Invoice 列表(按 Invoice 排序)。
|
||||
Raises:
|
||||
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
|
||||
汇总后的 Invoice 列表(按汇总键排序)。
|
||||
"""
|
||||
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
|
||||
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
|
||||
for row in rows:
|
||||
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
|
||||
grouped.setdefault(
|
||||
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
|
||||
).append(row)
|
||||
|
||||
invoices: list[AggregatedInvoice] = []
|
||||
for (source_code, invoice_no), group in sorted(grouped.items()):
|
||||
material_nos = {row.material_no for row in group}
|
||||
dates = {row.receipt_date for row in group}
|
||||
if len(material_nos) > 1:
|
||||
raise InvoiceConflictError(
|
||||
invoice_no=invoice_no,
|
||||
conflict=f"multiple_material_no: {sorted(material_nos)}",
|
||||
)
|
||||
if len(dates) > 1:
|
||||
raise InvoiceConflictError(
|
||||
invoice_no=invoice_no,
|
||||
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
|
||||
)
|
||||
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
|
||||
first = group[0]
|
||||
raw_lines = tuple(
|
||||
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
|
||||
@@ -81,11 +78,14 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
invoices.append(AggregatedInvoice(
|
||||
source_code=source_code,
|
||||
invoice_no=invoice_no,
|
||||
material_no=first.material_no,
|
||||
material_no=material_no,
|
||||
material_name=first.material_name,
|
||||
specification=first.specification,
|
||||
receipt_date=first.receipt_date,
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
|
||||
raw_lines=raw_lines,
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
unit=first.unit,
|
||||
))
|
||||
return invoices
|
||||
@@ -64,3 +64,38 @@ def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None,
|
||||
))
|
||||
db.session.commit()
|
||||
return {"item_id": item.id, "status": item.status}
|
||||
|
||||
|
||||
def manual_close_items(
|
||||
*, item_ids: list[int], reason: str,
|
||||
actor_id: str | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""批量人工关闭异常项(待处理池批量「标记无需处理」入口)。
|
||||
|
||||
Args:
|
||||
item_ids: TransferInvoiceItem.id 列表(非空)。
|
||||
reason: 关闭原因(必填,整批共用)。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"total", "results": [{item_id, ok, status|error}]};单行失败不阻断其余行。
|
||||
Raises:
|
||||
ValidationError: 原因缺失或 item_ids 为空。
|
||||
"""
|
||||
reason_value = str(reason or "").strip()
|
||||
if not reason_value:
|
||||
raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)
|
||||
ids = [int(x) for x in (item_ids or []) if x is not None]
|
||||
if not ids:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
results: list[dict] = []
|
||||
for item_id in ids:
|
||||
try:
|
||||
outcome = manual_close_item(item_id=item_id, reason=reason_value,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
results.append({"item_id": item_id, "ok": True, "status": outcome["status"]})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"item_id": item_id, "ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批
|
||||
results.append({"item_id": item_id, "ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"total": len(ids), "results": results}
|
||||
@@ -0,0 +1,977 @@
|
||||
"""在途调拨匹配服务。
|
||||
|
||||
用途:编排「证据兜底对齐 → 圈行 → D+1 成熟过滤 → 路由分组批量查 外部系统 库存 →
|
||||
严格数量比对落位 → 匹配快照与 Hash」,并支持匹配进度恢复(restore)。
|
||||
依赖:evidence_sync(STEP 0 兜底对齐)/ file_preparation(缺文件 RPA 分支)/
|
||||
source_file_status / capability_client / date_policy / quantity / contracts /
|
||||
audit / models。
|
||||
逻辑:【语义变更 2026-09-25】文件解析已上移 evidence_sync——行由文件落地同步
|
||||
(收料回调桥,主链路)或 run_matching STEP 0 兜底对齐(备)写入 DB;
|
||||
匹配只读 DB 行并写库存侧字段(status/result_code/result_message/
|
||||
external_quantity/from_warehouse/to_warehouse/unit/updated_at),
|
||||
raw_lines 版本戳归 evidence_sync 所有,匹配不碰。来源实例独立处理,
|
||||
任一来源失败不阻断其他来源;当天收料不查询 外部系统;匹配 Hash 由冻结
|
||||
快照复算;create_matching 只落 Run + SourceJob + Matching 留痕(行落位
|
||||
已由 run_matching 完成,行归属 matching_id 保持首次创建值不迁移);
|
||||
restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行;
|
||||
restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度
|
||||
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合,
|
||||
blocked_file_removed 行不进明细与常规 counts(只进 invalid_count);
|
||||
行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的
|
||||
stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列):
|
||||
命中库存但 ERP 未给单位 → 行级 blocked_missing_unit(拨出/拨入仓库
|
||||
已解析落列,行可解释可重查);unit 不参与匹配 Hash 快照,口径冻结。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import func, false, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import canonical_hash
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
MatchingCountsDTO,
|
||||
MatchingItemDTO,
|
||||
MatchingSummaryDTO,
|
||||
RawLineRefDTO,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
eligible_receipt_date_to,
|
||||
MATURITY_FUTURE,
|
||||
MATURITY_NOT_MATURED,
|
||||
maturity_status,
|
||||
parse_date,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
|
||||
from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError
|
||||
from app.services.in_transit_transfer.file_preparation import (
|
||||
ReceiptFileRepository,
|
||||
RpaTrigger,
|
||||
ensure_receipt_file_ready,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES,
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
|
||||
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
|
||||
|
||||
# 明细结果值(对应 Invoice 项状态)
|
||||
RESULT_EXECUTABLE = "executable"
|
||||
RESULT_NOT_MATURED = "not_matured"
|
||||
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
|
||||
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
# 文件新版本缺失该行(上一版本可执行、最新文件中消失)。
|
||||
RESULT_FILE_REMOVED = "blocked_file_removed"
|
||||
# 交易单位缺失:ERP 库存行未返回单位(stock_unit 空,img09 契约恒非空——出现即
|
||||
# ERP 侧数据异常):行级数据质量阻断。行在此前已完成路由解析,拨出/拨入仓库
|
||||
# 已落列(可解释、可重查);blocked_ 前缀计入 blocked_count(既有 blocked_* 契约)。
|
||||
RESULT_MISSING_UNIT = "blocked_missing_unit"
|
||||
# 路由不可解析(2026-09-25 行级化):行落 blocked 可解释、可重查(路由配置修复后
|
||||
# 重跑匹配/重查即恢复);同时来源级 stage 仍标 failed(fail-closed 语义保留)。
|
||||
RESULT_ROUTE_NOT_RESOLVED = "blocked_route_not_resolved"
|
||||
|
||||
# 匹配不触碰的行终态集合(与 evidence_sync._TERMINAL_ITEM_STATUSES 同口径):
|
||||
# 已执行/人工关闭等既定事实不复活;RESULT_UNKNOWN 行处于执行结果裁决中,同样不可
|
||||
# 被匹配改写(否则执行链路的结果回写会与匹配落位互相踩踏)。
|
||||
_SYNC_TERMINAL_STATUSES = frozenset({
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RouteMapping:
|
||||
"""来源路由:外部组织(external_org,取自仓库映射)/ 拨出仓(外部在途仓)/ 拨入仓(映射仓)。"""
|
||||
|
||||
external_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
|
||||
|
||||
class RouteNotResolvedError(AppError):
|
||||
"""来源实例缺少路由归属映射(fail-closed)。"""
|
||||
|
||||
def __init__(self, *, source_code: str):
|
||||
super().__init__(
|
||||
code=ROUTE_NOT_RESOLVED_CODE,
|
||||
message=f"route not resolved for source {source_code}",
|
||||
http_status=422,
|
||||
details={"source_code": source_code},
|
||||
)
|
||||
|
||||
|
||||
class RouteResolver(Protocol):
|
||||
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceProgressDTO:
|
||||
"""来源实例级进度(决策 18:来源隔离展示)。"""
|
||||
|
||||
source_code: str
|
||||
stage: str
|
||||
file_no: str | None = None
|
||||
file_version: str | None = None
|
||||
checksum: str | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchingRunResult:
|
||||
"""一次匹配运行的完整结果。"""
|
||||
|
||||
summary: MatchingSummaryDTO
|
||||
items: tuple[MatchingItemDTO, ...]
|
||||
sources: tuple[SourceProgressDTO, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferDeps:
|
||||
"""匹配/执行依赖集合(测试注入 Fake 替身)。"""
|
||||
|
||||
file_repository: ReceiptFileRepository
|
||||
rpa_trigger: RpaTrigger
|
||||
route_resolver: RouteResolver
|
||||
capabilities: Any
|
||||
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
|
||||
|
||||
|
||||
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCountsDTO) -> str:
|
||||
"""匹配状态:存在未完成来源 → file_pending;否则按可执行数定。"""
|
||||
if any(source.stage not in {"file_ready"} for source in sources):
|
||||
return "file_pending"
|
||||
if counts.executable_count > 0:
|
||||
return "ready_to_execute"
|
||||
return "success"
|
||||
|
||||
|
||||
def run_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
deps: TransferDeps,
|
||||
active_source_job_key: str | None = None,
|
||||
run_no: str = "RUN-PENDING",
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> MatchingRunResult:
|
||||
"""执行一次匹配(对齐→圈行→查库存→落位;文件解析已上移 evidence_sync)。
|
||||
|
||||
【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(收料回调桥,
|
||||
主链路)或 STEP 0 兜底对齐(备)写入 DB;本函数只做「成熟过滤 → 路由分组
|
||||
批量查库存 → 数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取
|
||||
并按准备结果标来源阶段。落库写入不在此 commit(随调用方事务:create_matching
|
||||
末尾统一提交 / 异步 Job handler 回写后提交)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
|
||||
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
|
||||
run_no: Run 编号(契约兼容保留;当前管道不消费,仅调用方留痕)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
|
||||
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
|
||||
Returns:
|
||||
MatchingRunResult(摘要 + 明细 + 来源进度)。
|
||||
Raises:
|
||||
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
|
||||
"""
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
|
||||
range_from = parse_date(receipt_date_from) if receipt_date_from else None
|
||||
range_to = parse_date(receipt_date_to) if receipt_date_to else None
|
||||
if range_from and range_to and range_from > range_to:
|
||||
raise ValidationError(
|
||||
"receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
)
|
||||
if range_to and range_to > eligible_receipt_date_to(business_date):
|
||||
raise ValidationError(
|
||||
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
|
||||
# [STEP 0] 证据兜底对齐:sha 不一致的来源先重解析(落地同步失败的静默兜底)。
|
||||
# 逐来源调用以保留来源级隔离:单个来源解析失败(如文件格式坏)只标该来源
|
||||
# failed,不炸整批(2026-09-25 前该隔离在「解析→匹配」内实现,现前移至此)。
|
||||
align_errors: dict[str, tuple[str, str]] = {}
|
||||
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
|
||||
|
||||
for source_code in source_codes:
|
||||
try:
|
||||
align_scope_rows(source_codes=[source_code], deps=deps,
|
||||
business_date=business_date, now=now)
|
||||
except ReceiptFileSchemaError as exc:
|
||||
align_errors[source_code] = (exc.code, exc.message)
|
||||
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
|
||||
align_errors[source_code] = ("TRANSFER.SOURCE_MATCH_ERROR", str(exc))
|
||||
|
||||
# [文件状态快照] 逐来源判定可用文件:resolve 命中(含 sha)→ file_ready 留痕;
|
||||
# 未命中 → ensure_receipt_file_ready(缺文件触发 RPA,既有 UX 保留)。仓库
|
||||
# 复用直接给出 ready 文件(状态投影延迟或测试替身场景)时同样按 file_ready
|
||||
# 处理并留痕文件信息——只有拿到文件 checksum 的来源才进入本次圈行管道。
|
||||
sources: list[SourceProgressDTO] = []
|
||||
file_snapshot: dict[str, Any] = {}
|
||||
pipeline_codes: list[str] = []
|
||||
for source_code in source_codes:
|
||||
if source_code in align_errors:
|
||||
error_code, error_message = align_errors[source_code]
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=error_code, error_message=error_message,
|
||||
))
|
||||
continue
|
||||
file_status = resolve_source_file_status(source_code=source_code) or {}
|
||||
checksum = file_status.get("file_sha256")
|
||||
if not checksum:
|
||||
prepared = ensure_receipt_file_ready(
|
||||
source_code=source_code, business_date=business_date,
|
||||
repository=deps.file_repository, rpa_trigger=deps.rpa_trigger,
|
||||
active_source_job_key=active_source_job_key,
|
||||
)
|
||||
if prepared.stage == "file_ready" and prepared.file is not None:
|
||||
ready_file = prepared.file
|
||||
checksum = ready_file.checksum
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": ready_file.file_no,
|
||||
"file_version": ready_file.file_version,
|
||||
"checksum": ready_file.checksum,
|
||||
}
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=ready_file.file_no,
|
||||
file_version=ready_file.file_version,
|
||||
checksum=ready_file.checksum,
|
||||
))
|
||||
else:
|
||||
# 等待 RPA 回调 / 触发失败:该来源本轮不圈行(行保持既有状态)。
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage=prepared.stage,
|
||||
error_code=prepared.error_code,
|
||||
error_message=prepared.error_message,
|
||||
))
|
||||
continue
|
||||
else:
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": file_status.get("file_no"),
|
||||
"file_version": f"sha256:{checksum}"[:64],
|
||||
"checksum": checksum,
|
||||
}
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=file_status.get("file_no"),
|
||||
file_version=f"sha256:{checksum}"[:64],
|
||||
checksum=checksum,
|
||||
))
|
||||
pipeline_codes.append(source_code)
|
||||
|
||||
items, pending_stock_check_count, route_failed_sources = _matching_rows(
|
||||
source_codes=pipeline_codes, business_date=business_date, deps=deps,
|
||||
receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to,
|
||||
file_snapshot=file_snapshot, now=now,
|
||||
)
|
||||
# [来源级 fail-closed] 路由不可解析的来源整源标 failed(行级已落
|
||||
# blocked_route_not_resolved,二者同源不同层:行可解释可重查,来源状态
|
||||
# 提示配置缺漏需人工处理)。
|
||||
for failed_code in route_failed_sources:
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
source_code=stage.source_code, stage="failed",
|
||||
file_no=stage.file_no, file_version=stage.file_version,
|
||||
checksum=stage.checksum,
|
||||
error_code=ROUTE_NOT_RESOLVED_CODE,
|
||||
error_message=f"route not resolved for source {stage.source_code}",
|
||||
) if stage.source_code == failed_code else stage
|
||||
for stage in sources
|
||||
]
|
||||
|
||||
# [失效行计数] 同口径独立计数:blocked_file_removed 行不进明细与常规 counts,
|
||||
# 只以 invalid_count 透出(范围过滤与 _matching_rows 一致)。
|
||||
invalid_count = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code.in_(list(source_codes)),
|
||||
TransferInvoiceItem.result_code == RESULT_FILE_REMOVED,
|
||||
*([] if not (receipt_date_from or receipt_date_to) else [
|
||||
*([TransferInvoiceItem.receipt_date >= str(receipt_date_from)] if receipt_date_from else []),
|
||||
*([TransferInvoiceItem.receipt_date <= str(receipt_date_to)] if receipt_date_to else []),
|
||||
]),
|
||||
).count()
|
||||
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=sum(1 for item in items),
|
||||
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
|
||||
matched_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
|
||||
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
|
||||
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
|
||||
pending_stock_check_count=pending_stock_check_count,
|
||||
invalid_count=invalid_count,
|
||||
)
|
||||
estimated_quantity = sum(
|
||||
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
|
||||
)
|
||||
snapshot = {
|
||||
"scope": sorted(set(source_codes)),
|
||||
"business_date": business_date,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"file_snapshot": file_snapshot,
|
||||
"counts": {
|
||||
# [Hash 口径] 快照 counts 保持既有 5 键结构不变:pending/invalid 两桶
|
||||
# 是「落位前的瞬态口径」,纳入会使重复匹配的 Hash 漂移,破坏
|
||||
# 「相同输入可审计复算」性质(DTO/counts_json 留痕仍携带全桶)。
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
"not_matured_count": counts.not_matured_count,
|
||||
"matched_count": counts.matched_count,
|
||||
"executable_count": counts.executable_count,
|
||||
"blocked_count": counts.blocked_count,
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
# [Hash 口径冻结] items 快照仅含匹配身份与结果字段;unit 不参与哈希
|
||||
# (口径冻结,历史预检哈希不因本次字段追加而变化——计划 D4,2026-09-24)。
|
||||
# 【2026-09-25】快照行集 = _matching_rows 落位后的 DB 行投影(键形状不变;
|
||||
# Hash 形状变化安全:hash 已是纯留痕不拦执行)。
|
||||
"source_code": item.source_code,
|
||||
"invoice_no": item.invoice_no,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"result": item.result,
|
||||
}
|
||||
for item in items
|
||||
],
|
||||
}
|
||||
matching_hash = f"sha256:{canonical_hash(snapshot)}"
|
||||
sources_tuple = tuple(sources)
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id="", # 落库时回填
|
||||
status=_summary_status(sources_tuple, counts),
|
||||
business_date=business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
(date.fromisoformat(business_date) - timedelta(days=1))
|
||||
),
|
||||
expires_at="",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_external_write_count=counts.executable_count,
|
||||
matching_hash=matching_hash,
|
||||
)
|
||||
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
|
||||
|
||||
def _matching_rows(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
deps: TransferDeps,
|
||||
receipt_date_from: str | None,
|
||||
receipt_date_to: str | None,
|
||||
file_snapshot: dict[str, Any],
|
||||
now: datetime,
|
||||
) -> tuple[list[MatchingItemDTO], int, set[str]]:
|
||||
"""对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。
|
||||
|
||||
【2026-09-25】替代旧 _matching_invoices(按文件 Invoice 内存匹配):行已在
|
||||
DB(evidence_sync 落地),本函数只写库存侧字段(status/result_code/
|
||||
result_message/external_quantity/from_warehouse/to_warehouse/unit/
|
||||
updated_at);raw_lines 版本戳归 evidence_sync 所有,匹配不碰。
|
||||
|
||||
Args:
|
||||
source_codes: 本轮有可用文件的来源(无文件来源不圈行,行保持既有状态)。
|
||||
business_date: 业务日期 T(成熟过滤基准)。
|
||||
deps: 注入依赖(路由解析 / 外部系统库存查询)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期范围(ISO 字符串列比较)。
|
||||
file_snapshot: {source_code: 文件留痕}(行 DTO 文件对账装饰输入)。
|
||||
now: 落位时间(updated_at 新鲜度基准)。
|
||||
Returns:
|
||||
(items DTO 列表, pending_count, route_failed_sources)——pending_count=
|
||||
落位前的待查行数(counts 桶);route_failed_sources=路由不可解析的来源
|
||||
集合(run_matching 据此整源标 failed)。
|
||||
"""
|
||||
# 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code.in_(source_codes),
|
||||
TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES),
|
||||
# 失效行(文件新版本消失)不参与匹配,也不进明细(invalid_count 单独计数)。
|
||||
or_(TransferInvoiceItem.result_code.is_(None),
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
)
|
||||
if receipt_date_from:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= str(receipt_date_from))
|
||||
if receipt_date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= str(receipt_date_to))
|
||||
scope_rows_all = query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc(), TransferInvoiceItem.id.asc(),
|
||||
).all()
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行
|
||||
# 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。
|
||||
pending_count = 0
|
||||
route_failed_sources: set[str] = set()
|
||||
matured: list[tuple[TransferInvoiceItem, RouteMapping]] = []
|
||||
output: list[MatchingItemDTO] = []
|
||||
for row in scope_rows_all:
|
||||
# [口径] 待查行计数先于落位统计(落位会改写 result_code)。
|
||||
if (row.status == status_machine.TransferStatus.MATCHING.value
|
||||
and row.result_code == SYNC_RESULT_PENDING):
|
||||
pending_count += 1
|
||||
maturity = maturity_status(row.receipt_date, business_date)
|
||||
if maturity == MATURITY_NOT_MATURED:
|
||||
row.status = status_machine.TransferStatus.NOT_MATURED.value
|
||||
row.result_code = RESULT_NOT_MATURED
|
||||
row.result_message = "receipt not matured until next business day"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
if maturity == MATURITY_FUTURE:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_FUTURE_DATE
|
||||
row.result_message = "future receipt date"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=row.source_code, invoice_no=row.invoice_no,
|
||||
warehouse_code=row.receipt_warehouse_code or "",
|
||||
)
|
||||
except RouteNotResolvedError:
|
||||
# [2026-09-25 行级化] 路由不可解析:行落 blocked(可解释、可重查),
|
||||
# 来源级 stage 由调用方标 failed;不炸整批(原「来源级中断」语义)。
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_ROUTE_NOT_RESOLVED
|
||||
row.result_message = f"route not resolved for source {row.source_code}"
|
||||
row.updated_at = now
|
||||
route_failed_sources.add(row.source_code)
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse
|
||||
matured.append((row, route))
|
||||
|
||||
# [STEP 2] 按(来源, 外部组织)分组——来源实例为执行边界(故障域隔离:
|
||||
# 一个来源的网关绑定缺失不得波及同组织其他来源的查询结果)。
|
||||
groups: dict[tuple[str, str], list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
|
||||
for row, route in matured:
|
||||
groups.setdefault((row.source_code, route.external_org), []).append((row, route))
|
||||
|
||||
for (_group_source, external_org), entries in groups.items():
|
||||
# [外部形态] 批号经 WTP→HOW 派生后查询与回查(movement_contract.external_lot_no):
|
||||
# 行上落库为 WMS 文件原形态,ERP 账面批号是 HOW 形态——原形态直查必查空(假阴性)。
|
||||
targets = [
|
||||
StockTarget(material_no=row.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(row.lot_no))
|
||||
for row, route in entries
|
||||
]
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
try:
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org, targets=targets,
|
||||
)
|
||||
except ExternalQueryTimeoutError:
|
||||
for row, _route in entries:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_EXTERNAL_QUERY_TIMEOUT
|
||||
row.result_message = "external query timeout"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
# 组内逐行给 blocked_external_query_failed + 原因,行保持可见可解释。
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
for row, _route in entries:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
row.result_message = f"external query failed: {detail}"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
for row, route in entries:
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=row.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(row.lot_no),
|
||||
)
|
||||
if stock_row is None:
|
||||
# 查无库存记录也是外部系统的真实答复:库存数按 0 落库展示(而非"-"),
|
||||
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_INVENTORY_NOT_FOUND
|
||||
row.result_message = "external inventory not found"
|
||||
row.external_quantity = "0"
|
||||
row.unit = ""
|
||||
else:
|
||||
stock_unit = (stock_row.stock_unit or "").strip()
|
||||
# [STEP 3] 交易单位只取 ERP(stock_unit=img09,ERP 侧确认恒非空):
|
||||
# 命中库存但单位缺失=ERP 侧数据异常 → 本行 blocked_missing_unit;
|
||||
# 行已完成路由解析,拨出/拨入仓库照常落列(可解释、可重查)。
|
||||
if not stock_unit:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_MISSING_UNIT
|
||||
row.result_message = "external inventory unit is missing"
|
||||
row.external_quantity = str(stock_row.quantity)
|
||||
row.unit = ""
|
||||
else:
|
||||
match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity)
|
||||
row.external_quantity = str(stock_row.quantity)
|
||||
row.unit = stock_unit
|
||||
if match == RESULT_EXECUTABLE:
|
||||
row.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
row.result_code = None
|
||||
row.result_message = None
|
||||
else:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = match
|
||||
row.result_message = "strict quantity mismatch"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
return output, pending_count, route_failed_sources
|
||||
|
||||
|
||||
def _generate_no(prefix: str, business_date: str) -> str:
|
||||
"""生成稳定业务编号(MTG-YYYYMMDD-XXXX / RUN-...)。"""
|
||||
compact = str(business_date).replace("-", "")
|
||||
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
|
||||
|
||||
|
||||
def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
"""读取行的文件版本戳(评估该行时所用的收料文件 checksum)。
|
||||
|
||||
用途:消失行标记(create_matching)与文件对账(restore 展示 / execute_items
|
||||
执行门禁②)据此判断"行的评估版本是否仍是最新文件版本"。
|
||||
两个消费方对 None(未知版本)口径不同:
|
||||
- restore 展示:None → file_current=False(仅展示不可执行原因,不阻断);
|
||||
- execute_items 门禁②:None 按"评估版本缺失"fail-closed 拒绝执行
|
||||
(TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。
|
||||
|
||||
Args:
|
||||
item: InvoiceItem 行(raw_lines_json 首条携带 file_sha256 版本戳)。
|
||||
Returns:
|
||||
版本戳字符串;行无 raw_lines 或存量数据缺 file_sha256 键时返回 None
|
||||
(None 表示评估版本未知,调用方按各自口径处理,见上)。
|
||||
"""
|
||||
lines = item.raw_lines_json or []
|
||||
if not lines:
|
||||
return None
|
||||
return lines[0].get("file_sha256")
|
||||
|
||||
|
||||
def create_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
deps: TransferDeps,
|
||||
active_source_job_key: str | None = None,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> MatchingSummaryDTO:
|
||||
"""运行匹配并落库 TransferRun + SourceJob + TransferMatching(留痕;不写行)。
|
||||
|
||||
【语义变更 2026-09-25】行落位已全部由 run_matching 完成(证据同步落地 +
|
||||
库存比对落位),本函数只负责留痕:Run / 来源级 SourceJob / Matching 记录
|
||||
(scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」
|
||||
——消失行标记(blocked_file_removed)归 evidence_sync;行归属 matching_id
|
||||
保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
receipt_date_from / receipt_date_to / transfer_type: 同 run_matching。
|
||||
Returns:
|
||||
匹配摘要(matching_id 已回填)。
|
||||
"""
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
run_no = _generate_no("RUN", business_date)
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
active_source_job_key=active_source_job_key,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
transfer_type=resolved_transfer_type,
|
||||
run_no=run_no,
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
run = TransferRun(
|
||||
run_no=run_no,
|
||||
trigger_type="manual",
|
||||
business_date=business_date,
|
||||
status="matching",
|
||||
source_codes_json=list(source_codes),
|
||||
counts_json=asdict(result.summary.counts),
|
||||
transfer_type=resolved_transfer_type.value,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
|
||||
# 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。
|
||||
# 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。
|
||||
from app.services.in_transit_transfer.source_job_service import create_source_job
|
||||
|
||||
_valid_job_statuses = {
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
}
|
||||
for job_source in result.sources:
|
||||
create_source_job(
|
||||
run_id=run.id,
|
||||
source_code=job_source.source_code,
|
||||
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
|
||||
error_code=job_source.error_code,
|
||||
error_message=job_source.error_message,
|
||||
)
|
||||
|
||||
matching_no = _generate_no("MTG", business_date)
|
||||
matching = TransferMatching(
|
||||
matching_no=matching_no,
|
||||
run_id=run.id,
|
||||
business_date=business_date,
|
||||
status=result.summary.status,
|
||||
scope_json={
|
||||
"source_codes": list(source_codes),
|
||||
"receipt_date_from": receipt_date_from,
|
||||
"receipt_date_to": receipt_date_to,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"transfer_type_scope": transfer_type_scope_note(resolved_transfer_type),
|
||||
},
|
||||
file_snapshot_json={
|
||||
stage.source_code: {
|
||||
"file_no": stage.file_no,
|
||||
"file_version": stage.file_version,
|
||||
"checksum": stage.checksum,
|
||||
}
|
||||
for stage in result.sources
|
||||
if stage.file_no
|
||||
},
|
||||
mapping_version="v0",
|
||||
strategy_version="v0",
|
||||
counts_json=asdict(result.summary.counts),
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
matching_hash=result.summary.matching_hash,
|
||||
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
|
||||
)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
# 留痕提交:行落位随本事务一并持久化(run_matching 只写不提交)。
|
||||
db.session.commit()
|
||||
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id=matching_no,
|
||||
status=matching.status,
|
||||
business_date=matching.business_date,
|
||||
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
|
||||
expires_at=matching.expires_at.isoformat() if matching.expires_at else "",
|
||||
counts=result.summary.counts,
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
matching_hash=result.summary.matching_hash,
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def restore_matching(
|
||||
matching_id: str,
|
||||
*,
|
||||
deps: TransferDeps | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""按 matching_no 恢复匹配进度与明细(页面刷新/会话恢复)。
|
||||
|
||||
匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与
|
||||
匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行
|
||||
实时聚合;blocked_file_removed 行不进明细与常规 counts(只计入
|
||||
counts.invalid_count,2026-09-25);estimated_* 与 expires_at /
|
||||
matching_hash 沿用匹配记录留痕展示。
|
||||
|
||||
Args:
|
||||
matching_id: 匹配编号(MTG-...)。
|
||||
deps: 注入依赖(缺省内部取 deps.get_transfer_dependencies();restore
|
||||
只读 strategy.confirm_ttl_seconds,不产生外部调用)。
|
||||
now: 新鲜度判定基准时间(缺省 datetime.utcnow(),测试注入冻结时钟)。
|
||||
Returns:
|
||||
{"summary": {...}, "items": [...], "sources": [...]};items 每行额外装饰
|
||||
item_id / checked_at / stale / file_current 四字段。
|
||||
Raises:
|
||||
NotFoundError: 匹配不存在。
|
||||
"""
|
||||
# [依赖缺省] API/Chat 未显式传 deps 时取默认装配(局部导入避免装配模块反向依赖)。
|
||||
if deps is None:
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
moment = now or datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
|
||||
matching = db.session.query(TransferMatching).filter_by(
|
||||
matching_no=str(matching_id).strip()
|
||||
).first()
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
|
||||
# [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属
|
||||
# (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。
|
||||
rows_all = (
|
||||
scope_item_query(matching)
|
||||
.order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
# [失效行分层]【2026-09-25】blocked_file_removed 行已出清:不进明细与常规
|
||||
# counts(与 _matching_rows 圈行口径一致),只计入 invalid_count。
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
|
||||
invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED]
|
||||
rows = [row for row in rows_all if row.result_code != RESULT_FILE_REMOVED]
|
||||
|
||||
# [STEP 2] 文件对账映射:scope 内去重来源逐个投影当前可用文件版本,
|
||||
# 行评估版本戳与之比对得 file_current(来源无可用文件 → False)。
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({row.source_code for row in rows})
|
||||
}
|
||||
|
||||
# [STEP 3] counts 按 scope 行实时聚合(行归属不参与)。
|
||||
# matched_count 为"未成熟以外"的可用总数(与 run_matching 语义一致);
|
||||
# pending/invalid 两桶为 2026-09-25 counts 契约扩展(同口径内存计算)。
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
not_matured_status = status_machine.TransferStatus.NOT_MATURED.value
|
||||
not_matured_count = sum(1 for row in rows if row.status == not_matured_status)
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=len(rows),
|
||||
not_matured_count=not_matured_count,
|
||||
matched_count=len(rows) - not_matured_count,
|
||||
executable_count=sum(1 for row in rows if row.status == ready_status),
|
||||
blocked_count=sum(1 for row in rows if row.status == blocked_status),
|
||||
pending_stock_check_count=sum(
|
||||
1 for row in rows
|
||||
if row.status == status_machine.TransferStatus.MATCHING.value
|
||||
and row.result_code == SYNC_RESULT_PENDING
|
||||
),
|
||||
invalid_count=len(invalid_rows),
|
||||
)
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id=matching.matching_no,
|
||||
status=matching.status,
|
||||
business_date=matching.business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
date.fromisoformat(matching.business_date) - timedelta(days=1)
|
||||
),
|
||||
expires_at=matching.expires_at.isoformat() if matching.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=matching.estimated_transfer_quantity or "0",
|
||||
estimated_external_write_count=int(matching.estimated_external_write_count or 0),
|
||||
matching_hash=matching.matching_hash,
|
||||
)
|
||||
|
||||
items = []
|
||||
for item in rows:
|
||||
items.append(
|
||||
_item_dto(item, latest_files.get(item.source_code) or {}, moment, ttl_seconds)
|
||||
)
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
source_code=job.source_code,
|
||||
stage=job.status,
|
||||
file_no=job.file_no,
|
||||
file_version=None,
|
||||
checksum=job.file_sha256,
|
||||
error_code=job.error_code,
|
||||
error_message=job.error_message,
|
||||
)
|
||||
for job in (matching.run.source_jobs if matching.run else [])
|
||||
] or [
|
||||
SourceProgressDTO(source_code=code, stage="file_ready")
|
||||
for code in (matching.scope_json.get("source_codes") or [])
|
||||
]
|
||||
return {
|
||||
"summary": summary,
|
||||
"items": items,
|
||||
"sources": sources,
|
||||
}
|
||||
|
||||
|
||||
def scope_item_query(matching: TransferMatching):
|
||||
"""按匹配 scope_json 实时圈定其行集(不依赖行的 matching_id 归属)。
|
||||
|
||||
用途:行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"只能由
|
||||
scope(来源 + 收料日期区间 + 调拨类型范围)重新计算;
|
||||
restore 实时视图与可调拨明细队列共用本查询。
|
||||
|
||||
Args:
|
||||
matching: 匹配记录(读取 scope_json 的 source_codes / receipt_date_from /
|
||||
receipt_date_to / transfer_type)。
|
||||
Returns:
|
||||
TransferInvoiceItem 的 BaseQuery;类型 Invoice 前缀过滤与
|
||||
invoice_in_scope 同一常量口径,占位类型恒空(无任何行)。
|
||||
"""
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
sources = [str(code) for code in (scope.get("source_codes") or [])]
|
||||
query = db.session.query(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.source_code.in_(sources),
|
||||
)
|
||||
# 收料日期为 ISO 字符串列,直接用字符串区间比较(与 run_matching 的内存过滤同语义)。
|
||||
date_from = scope.get("receipt_date_from")
|
||||
date_to = scope.get("receipt_date_to")
|
||||
if date_from:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= str(date_from))
|
||||
if date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= str(date_to))
|
||||
resolved_type = normalize_transfer_type(scope.get("transfer_type"))
|
||||
if resolved_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
query = query.filter(or_(
|
||||
*(func.upper(TransferInvoiceItem.invoice_no).like(f"{prefix}%") for prefix in prefixes),
|
||||
))
|
||||
else:
|
||||
# 占位类型范围外无任何单(与 invoice_in_scope 恒 False 同口径)。
|
||||
query = query.filter(false())
|
||||
return query
|
||||
|
||||
|
||||
def _item_dto(
|
||||
item: TransferInvoiceItem,
|
||||
latest: dict,
|
||||
moment: datetime,
|
||||
ttl_seconds: int,
|
||||
) -> MatchingItemDTO:
|
||||
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
|
||||
|
||||
Args:
|
||||
item: 明细行。
|
||||
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
|
||||
moment: 新鲜度判定基准时间。
|
||||
ttl_seconds: 行级 stale 展示阈值(strategy.confirm_ttl_seconds;仅驱动
|
||||
stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||
Returns:
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
|
||||
"""
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
updated_at = item.updated_at
|
||||
return MatchingItemDTO(
|
||||
source_code=item.source_code,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
# 交易单位原值(movement 契约第 11 字段):restore/明细队列视图与
|
||||
# 序列化(serializers)均已透传(T11 接线完成)。
|
||||
unit=item.unit or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
# 失败原因落库于 result_message(匹配/重查降级均写);restore 不回读则
|
||||
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
|
||||
reason=item.result_message or "",
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
row_no=int(line.get("row_no", 0)),
|
||||
file_version=line.get("file_version", ""),
|
||||
)
|
||||
for line in (item.raw_lines_json or [])
|
||||
),
|
||||
# [行装饰] 行级新鲜度与文件对账(均纯展示,不阻断执行):
|
||||
# [2026-09-25 TTL 退役] stale 仅是「库存数据已过期,请重查」展示徽标
|
||||
# (原 TTL 执行门禁已删除,防错由文件版本对账 + worker 写前库存复查
|
||||
# 承担):stale=距上次评估超过展示阈值(confirm_ttl_seconds);
|
||||
# file_current=行评估版本戳仍是该来源当前可用文件 sha
|
||||
# (无版本戳或无可用文件均视为不一致 → False)。
|
||||
item_id=item.id,
|
||||
checked_at=updated_at.isoformat() if updated_at else None,
|
||||
stale=bool(updated_at) and (moment - updated_at).total_seconds() > ttl_seconds,
|
||||
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
||||
)
|
||||
|
||||
|
||||
def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""全局可执行明细队列(「可调拨明细」入口数据源)。
|
||||
|
||||
用途:行归属与匹配解耦后,可执行行不再依附任何匹配卡——本查询给出全部
|
||||
ready_to_execute 行(跨匹配范围,业务稳定排序),供前端勾选后按行
|
||||
执行生成调拨单;行装饰(item_id / checked_at / stale / file_current)
|
||||
与 restore 实时视图同一口径。
|
||||
|
||||
Args:
|
||||
deps: 注入依赖(缺省内部取 get_transfer_dependencies;只读 TTL 配置)。
|
||||
now: 新鲜度判定基准时间(缺省 datetime.utcnow())。
|
||||
Returns:
|
||||
{"items": [MatchingItemDTO...], "counts": {"executable_count": N}}。
|
||||
"""
|
||||
if deps is None:
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
moment = now or datetime.utcnow()
|
||||
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
|
||||
|
||||
# [稳定排序] 收料日期(空值最后)→ Invoice → 创建时间:与重查/恢复等操作
|
||||
# 无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位。
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
)
|
||||
.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({row.source_code for row in rows})
|
||||
}
|
||||
items = [
|
||||
_item_dto(row, latest_files.get(row.source_code) or {}, moment, ttl_seconds)
|
||||
for row in rows
|
||||
]
|
||||
return {"items": items, "counts": {"executable_count": len(rows)}}
|
||||
@@ -40,7 +40,14 @@ class MovementField:
|
||||
required: bool = False
|
||||
|
||||
|
||||
# 定死的 10 个通用异动字段(领域契约,不配置化)。
|
||||
# 定死的 11 个通用异动字段(领域契约,不配置化)。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
|
||||
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生收敛为 external_lot_no() 唯一实现——
|
||||
# 库存查询 / 建单下传 / 单行聚合 / 展示统一按外部形态;落库保持文件原形态(证据原则)。
|
||||
# [PROMPT_UPDATE] 2026-09-24:追加第 11 字段 unit(交易单位,计划 D4)——ERP 写入
|
||||
# 行必填(gls_cm19),但解析层放行空值(不产生解析失败),空值由匹配阶段行级
|
||||
# blocked_missing_unit 阻断;unit 不参与幂等/匹配,也不进匹配 Hash 快照(口径冻结)。
|
||||
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
|
||||
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
|
||||
@@ -52,6 +59,7 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("lot_no", "批号", MovementFieldValueType.TEXT),
|
||||
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
|
||||
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
|
||||
MovementField("unit", "单位", MovementFieldValueType.TEXT),
|
||||
)
|
||||
|
||||
|
||||
@@ -73,3 +81,25 @@ def movement_identity_fields() -> set[str]:
|
||||
def movement_field_codes() -> set[str]:
|
||||
"""全部定死字段名集合。"""
|
||||
return {field.code for field in MOVEMENT_FIELDS}
|
||||
|
||||
|
||||
def external_lot_no(lot_no: str | None) -> str:
|
||||
"""批号外部形态派生:WMS 批号 WTP 前缀 → 外部系统真实批号 HOW 前缀。
|
||||
|
||||
【AI 触发时机】任何把行上 lot_no 发往外部系统的场景——库存查询 targets、
|
||||
写前库存复查、建单单行——组装参数前必须经本函数转换;单行聚合键与展示列
|
||||
「拨出/拨入批号」同规则(前端 features/chat/components/messages/transferBatch.ts
|
||||
deriveBatchNo 为本函数的展示侧镜像,改动须双侧同步)。行上落库值保持文件
|
||||
原形态(证据原则:raw_lines 对账/审计复算以文件为准),转换只发生在外部
|
||||
系统边界。
|
||||
|
||||
Args:
|
||||
lot_no: 行上批号原值(文件证据形态;None/空白按空串处理)。
|
||||
Returns:
|
||||
外部系统批号形态:WTP 前缀识别大小写不敏感,余串逐字保留;
|
||||
非 WTP 前缀原样返回;空输入返回空串。
|
||||
"""
|
||||
value = str(lot_no or "").strip()
|
||||
if value.upper().startswith("WTP"):
|
||||
return f"HOW{value[3:]}"
|
||||
return value
|
||||
@@ -4,11 +4,11 @@
|
||||
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
|
||||
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
|
||||
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
|
||||
movement_contract、openpyxl。
|
||||
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
|
||||
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
|
||||
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
|
||||
file_parser 完成。
|
||||
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
|
||||
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
|
||||
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
|
||||
校验由下游 file_parser 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +18,7 @@ from typing import Any, Mapping
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
@@ -27,13 +28,14 @@ class ShippingReceiptFileRepository:
|
||||
self._storage = file_asset_storage
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
|
||||
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
|
||||
Returns:
|
||||
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
|
||||
|
||||
@@ -52,7 +54,8 @@ class ShippingReceiptFileRepository:
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -114,7 +117,11 @@ def _extract_movement_rows(
|
||||
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
|
||||
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
|
||||
|
||||
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
|
||||
header_to_code: dict[str, list[str]] = {}
|
||||
for code, alias in field_mapping.items():
|
||||
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
|
||||
# 反查必须是 一别名→多字段,不得互相覆盖。
|
||||
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
|
||||
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
|
||||
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
|
||||
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
|
||||
@@ -126,11 +133,16 @@ def _extract_movement_rows(
|
||||
]
|
||||
|
||||
|
||||
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
|
||||
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
|
||||
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
|
||||
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
|
||||
|
||||
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
|
||||
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
|
||||
"""
|
||||
output: dict[str, Any] = {}
|
||||
for index, header in enumerate(headers):
|
||||
code = header_to_code.get(header)
|
||||
if code and index < len(row):
|
||||
output[code] = row[index]
|
||||
codes = header_to_code.get(header)
|
||||
if codes and index < len(row):
|
||||
for code in codes:
|
||||
output[code] = row[index]
|
||||
return output
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨企业微信汇总通知。
|
||||
|
||||
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
|
||||
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
|
||||
notification_failed 且不改变 外部系统 业务结果(run.status 保持)。
|
||||
依赖:models、audit、typing.Protocol。
|
||||
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
|
||||
逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,7 +65,7 @@ def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str
|
||||
if failed:
|
||||
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
|
||||
run.notification_error_message = str(outcome.get("error_message") or "")
|
||||
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
|
||||
# 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_NOTIFICATION",
|
||||
aggregate_type="transfer_run",
|
||||
|
||||
@@ -1,70 +1,75 @@
|
||||
"""在途调拨执行编排(Run 生命周期辅助)。
|
||||
|
||||
用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、
|
||||
用途:按选中明细行创建执行 Run(初始态 queued、记录业务日/来源范围/行计数)、
|
||||
按明细终态收尾 Run(success / partial_failed)。
|
||||
依赖:models、status、precheck_service.TransferDeps。
|
||||
逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。
|
||||
依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。
|
||||
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);D8 异步拆分后
|
||||
Run 初始态为 queued(prepare 段只建 Run+关联行+建单,worker 段置 executing);
|
||||
行归属由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
|
||||
本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps
|
||||
|
||||
EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED"
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps, _generate_no
|
||||
|
||||
|
||||
def create_execution_run(
|
||||
precheck: TransferPrecheck,
|
||||
def create_execution_run_for_items(
|
||||
items: list[TransferInvoiceItem],
|
||||
*,
|
||||
deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展
|
||||
actor_id: int | None = None,
|
||||
selected_invoice_nos: set[str] | None = None,
|
||||
selected_item_ids: set[int] | None = None,
|
||||
) -> TransferRun:
|
||||
"""为已就绪预检创建执行 Run 并关联选中的可执行明细。
|
||||
"""为选中可执行明细行创建执行 Run 并关联(行级执行,不绑定匹配)。
|
||||
|
||||
D8 异步拆分:Run 初始态为 queued——API 同步段(prepare_execution)只建 Run、
|
||||
关联行并组建单,worker 段(execute_run)领取后置 executing。
|
||||
|
||||
Args:
|
||||
precheck: 已预检(ready_to_execute)对象。
|
||||
items: 候选明细行(调用方已完成可执行校验,见 execution_service.execute_items)。
|
||||
deps: 依赖集合(预留)。
|
||||
actor_id: 确认操作者。
|
||||
selected_invoice_nos: 选择范围(缺省关联全部可执行项)。
|
||||
actor_id: 触发执行的用户(写入 run.created_by 留痕)。
|
||||
selected_item_ids: 关联范围(行 id 集;缺省关联 items 中全部可执行未关联行)。
|
||||
Returns:
|
||||
状态为 executing 的 TransferRun。
|
||||
Raises:
|
||||
ConflictError: 预检已确认(重复执行)。
|
||||
状态为 queued 的 TransferRun(run_no/business_date 取当前业务日)。
|
||||
"""
|
||||
if precheck.confirmed_at is not None:
|
||||
raise ConflictError(
|
||||
"precheck already executed", code=EXECUTION_CONFLICT_CODE,
|
||||
)
|
||||
run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}"
|
||||
selected = selected_item_ids if selected_item_ids is not None else None
|
||||
business_date = str(business_date_now())
|
||||
# 行计数快照:按本次关联(选中)行聚合,供通知/运营展示(与匹配 counts 同形状)。
|
||||
candidates = [
|
||||
item for item in items
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
and item.run_id is None
|
||||
and (selected is None or item.id in selected)
|
||||
]
|
||||
run = TransferRun(
|
||||
run_no=run_no,
|
||||
run_no=_generate_no("RUN", business_date),
|
||||
trigger_type="manual",
|
||||
business_date=precheck.business_date,
|
||||
status=status_machine.TransferRunStatus.EXECUTING.value,
|
||||
source_codes_json=list(precheck.scope_json.get("source_codes") or []),
|
||||
counts_json=dict(precheck.counts_json or {}),
|
||||
business_date=business_date,
|
||||
# D8 异步拆分:初始态 queued(API 同步段毫秒级返回,worker 领取后置 executing)。
|
||||
status=status_machine.TransferRunStatus.QUEUED.value,
|
||||
source_codes_json=sorted({item.source_code for item in candidates}),
|
||||
counts_json={
|
||||
"file_invoice_count": len(candidates),
|
||||
"not_matured_count": 0,
|
||||
"matched_count": len(candidates),
|
||||
"executable_count": len(candidates),
|
||||
"blocked_count": 0,
|
||||
},
|
||||
created_by=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
|
||||
precheck.run_id = run.id
|
||||
precheck.status = status_machine.TransferRunStatus.EXECUTING.value
|
||||
precheck.confirmed_at = datetime.utcnow()
|
||||
precheck.confirmed_by = actor_id
|
||||
|
||||
for item in precheck.items:
|
||||
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None:
|
||||
continue
|
||||
if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos:
|
||||
continue
|
||||
# 关联选中行:置 executing 并递增 Attempt 序号(每次执行创建新 Attempt)。
|
||||
for item in candidates:
|
||||
item.run_id = run.id
|
||||
item.status = status_machine.TransferStatus.EXECUTING.value
|
||||
item.attempt_no += 1
|
||||
|
||||
@@ -1,581 +0,0 @@
|
||||
"""在途调拨预检服务。
|
||||
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
|
||||
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
|
||||
date_policy / quantity / contracts / audit / models。
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
|
||||
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import canonical_hash
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
PrecheckCountsDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
PrecheckSummaryDTO,
|
||||
RawLineRefDTO,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
MATURITY_ELIGIBLE,
|
||||
MATURITY_FUTURE,
|
||||
MATURITY_NOT_MATURED,
|
||||
maturity_status,
|
||||
)
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_movement_rows,
|
||||
parse_receipt_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_preparation import (
|
||||
ReadyReceiptFile,
|
||||
ReceiptFileRepository,
|
||||
RpaTrigger,
|
||||
ensure_receipt_file_ready,
|
||||
)
|
||||
from app.services.in_transit_transfer.invoice_aggregator import (
|
||||
InvoiceConflictError,
|
||||
aggregate_invoices,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
)
|
||||
|
||||
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
|
||||
|
||||
# 明细结果值(对应 Invoice 项状态)
|
||||
RESULT_EXECUTABLE = "executable"
|
||||
RESULT_NOT_MATURED = "not_matured"
|
||||
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
|
||||
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RouteMapping:
|
||||
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
|
||||
|
||||
erp_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
|
||||
|
||||
class RouteNotResolvedError(AppError):
|
||||
"""来源实例缺少路由归属映射(fail-closed)。"""
|
||||
|
||||
def __init__(self, *, source_code: str):
|
||||
super().__init__(
|
||||
code=ROUTE_NOT_RESOLVED_CODE,
|
||||
message=f"route not resolved for source {source_code}",
|
||||
http_status=422,
|
||||
details={"source_code": source_code},
|
||||
)
|
||||
|
||||
|
||||
class RouteResolver(Protocol):
|
||||
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceProgressDTO:
|
||||
"""来源实例级进度(决策 18:来源隔离展示)。"""
|
||||
|
||||
source_code: str
|
||||
stage: str
|
||||
file_no: str | None = None
|
||||
file_version: str | None = None
|
||||
checksum: str | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckRunResult:
|
||||
"""一次预检运行的完整结果。"""
|
||||
|
||||
summary: PrecheckSummaryDTO
|
||||
items: tuple[PrecheckInvoiceItemDTO, ...]
|
||||
sources: tuple[SourceProgressDTO, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferDeps:
|
||||
"""预检/执行依赖集合(测试注入 Fake 替身)。"""
|
||||
|
||||
file_repository: ReceiptFileRepository
|
||||
rpa_trigger: RpaTrigger
|
||||
route_resolver: RouteResolver
|
||||
erp: Any
|
||||
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
|
||||
|
||||
|
||||
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str:
|
||||
"""预检状态:存在未完成来源 → file_pending;否则按可执行数定。"""
|
||||
if any(source.stage not in {"file_ready"} for source in sources):
|
||||
return "file_pending"
|
||||
if counts.executable_count > 0:
|
||||
return "ready_to_execute"
|
||||
return "success"
|
||||
|
||||
|
||||
def run_precheck(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
deps: TransferDeps,
|
||||
active_source_job_key: str | None = None,
|
||||
run_no: str = "RUN-PENDING",
|
||||
) -> PrecheckRunResult:
|
||||
"""执行一次只读预检(不写 ERP)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
|
||||
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
|
||||
run_no: Run 编号(创建 Run 前可为占位)。
|
||||
Returns:
|
||||
PrecheckRunResult(摘要 + 明细 + 来源进度)。
|
||||
Raises:
|
||||
ValidationError: source_codes 为空。
|
||||
"""
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
validate_strategy = deps.strategy
|
||||
|
||||
sources: list[SourceProgressDTO] = []
|
||||
items: list[PrecheckInvoiceItemDTO] = []
|
||||
file_snapshot: dict[str, Any] = {}
|
||||
for source_code in source_codes:
|
||||
source_stage: SourceProgressDTO
|
||||
try:
|
||||
prepared = ensure_receipt_file_ready(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
repository=deps.file_repository,
|
||||
rpa_trigger=deps.rpa_trigger,
|
||||
active_source_job_key=active_source_job_key,
|
||||
)
|
||||
if prepared.stage != "file_ready" or prepared.file is None:
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code,
|
||||
stage=prepared.stage,
|
||||
error_code=prepared.error_code,
|
||||
error_message=prepared.error_message,
|
||||
))
|
||||
continue
|
||||
ready_file = prepared.file
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": ready_file.file_no,
|
||||
"file_version": ready_file.file_version,
|
||||
"checksum": ready_file.checksum,
|
||||
}
|
||||
# 真实仓库(movement_file_repository)产出 movement 领域字段行
|
||||
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
|
||||
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
|
||||
source_items = _precheck_invoices(
|
||||
invoices=invoices,
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
ready_file=ready_file,
|
||||
deps=deps,
|
||||
run_no=run_no,
|
||||
)
|
||||
items.extend(source_items)
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code,
|
||||
stage="file_ready",
|
||||
file_no=ready_file.file_no,
|
||||
file_version=ready_file.file_version,
|
||||
checksum=ready_file.checksum,
|
||||
))
|
||||
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=exc.code, error_message=exc.message,
|
||||
))
|
||||
except RouteNotResolvedError as exc:
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=exc.code, error_message=exc.message,
|
||||
))
|
||||
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code="TRANSFER.SOURCE_PRECheck_ERROR",
|
||||
error_message=str(exc),
|
||||
))
|
||||
|
||||
counts = PrecheckCountsDTO(
|
||||
file_invoice_count=sum(
|
||||
1 for item in items
|
||||
),
|
||||
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
|
||||
prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
|
||||
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
|
||||
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
|
||||
)
|
||||
estimated_quantity = sum(
|
||||
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
|
||||
)
|
||||
snapshot = {
|
||||
"scope": sorted(set(source_codes)),
|
||||
"business_date": business_date,
|
||||
"file_snapshot": file_snapshot,
|
||||
"counts": {
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
"not_matured_count": counts.not_matured_count,
|
||||
"prechecked_count": counts.prechecked_count,
|
||||
"executable_count": counts.executable_count,
|
||||
"blocked_count": counts.blocked_count,
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"source_code": item.source_code,
|
||||
"invoice_no": item.invoice_no,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"result": item.result,
|
||||
}
|
||||
for item in items
|
||||
],
|
||||
}
|
||||
precheck_hash = f"sha256:{canonical_hash(snapshot)}"
|
||||
sources_tuple = tuple(sources)
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id="", # 落库时回填
|
||||
status=_summary_status(sources_tuple, counts),
|
||||
business_date=business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
(date.fromisoformat(business_date) - timedelta(days=1))
|
||||
),
|
||||
expires_at="",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_erp_write_count=counts.executable_count,
|
||||
precheck_hash=precheck_hash,
|
||||
)
|
||||
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
|
||||
|
||||
def _precheck_invoices(
|
||||
*,
|
||||
invoices: list,
|
||||
source_code: str,
|
||||
business_date: str,
|
||||
ready_file: ReadyReceiptFile,
|
||||
deps: TransferDeps,
|
||||
run_no: str,
|
||||
) -> list[PrecheckInvoiceItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
|
||||
output: list[PrecheckInvoiceItemDTO] = []
|
||||
for invoice in invoices:
|
||||
maturity = maturity_status(invoice.receipt_date, business_date)
|
||||
raw = tuple(
|
||||
RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version)
|
||||
for line in invoice.raw_lines
|
||||
)
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
if maturity == MATURITY_NOT_MATURED:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
if maturity == MATURITY_FUTURE:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_FUTURE_DATE, reason="future receipt date",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=run_no,
|
||||
attempt_no=1,
|
||||
invoice_no=invoice.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=invoice.receipt_quantity,
|
||||
)
|
||||
except ErpQueryTimeoutError:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
if not query.found:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
raw_lines=raw,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
def _item_status(result: str) -> str:
|
||||
"""明细结果 → Invoice 项状态。"""
|
||||
mapping = {
|
||||
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
|
||||
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}
|
||||
return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value)
|
||||
|
||||
|
||||
def _generate_no(prefix: str, business_date: str) -> str:
|
||||
"""生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。"""
|
||||
compact = str(business_date).replace("-", "")
|
||||
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
|
||||
|
||||
|
||||
def create_precheck(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
deps: TransferDeps,
|
||||
active_source_job_key: str | None = None,
|
||||
) -> PrecheckSummaryDTO:
|
||||
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_precheck。
|
||||
Returns:
|
||||
预检摘要(precheck_id 已回填)。
|
||||
"""
|
||||
run_no = _generate_no("RUN", business_date)
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
active_source_job_key=active_source_job_key,
|
||||
run_no=run_no,
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
run = TransferRun(
|
||||
run_no=run_no,
|
||||
trigger_type="manual",
|
||||
business_date=business_date,
|
||||
status="prechecking",
|
||||
source_codes_json=list(source_codes),
|
||||
counts_json=asdict(result.summary.counts),
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
|
||||
# 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。
|
||||
# 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。
|
||||
from app.services.in_transit_transfer.source_job_service import create_source_job
|
||||
|
||||
_valid_job_statuses = {
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
}
|
||||
for job_source in result.sources:
|
||||
create_source_job(
|
||||
run_id=run.id,
|
||||
source_code=job_source.source_code,
|
||||
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
|
||||
)
|
||||
|
||||
precheck_no = _generate_no("TPC", business_date)
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no=precheck_no,
|
||||
run_id=run.id,
|
||||
business_date=business_date,
|
||||
status=result.summary.status,
|
||||
scope_json={"source_codes": list(source_codes)},
|
||||
file_snapshot_json={
|
||||
stage.source_code: {
|
||||
"file_no": stage.file_no,
|
||||
"file_version": stage.file_version,
|
||||
"checksum": stage.checksum,
|
||||
}
|
||||
for stage in result.sources
|
||||
if stage.file_no
|
||||
},
|
||||
mapping_version="v0",
|
||||
strategy_version="v0",
|
||||
counts_json=asdict(result.summary.counts),
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
|
||||
)
|
||||
db.session.add(precheck)
|
||||
db.session.flush()
|
||||
|
||||
for item in result.items:
|
||||
db.session.add(TransferInvoiceItem(
|
||||
precheck_id=precheck.id,
|
||||
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
receipt_date=item.receipt_date,
|
||||
from_warehouse=item.from_warehouse or "",
|
||||
to_warehouse=item.to_warehouse or "",
|
||||
receipt_quantity=str(item.to_quantity),
|
||||
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
status=_item_status(item.result),
|
||||
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
|
||||
result_message=item.reason or None,
|
||||
raw_lines_json=[
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id=precheck_no,
|
||||
status=precheck.status,
|
||||
business_date=precheck.business_date,
|
||||
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=result.summary.counts,
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
"""按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。
|
||||
|
||||
Args:
|
||||
precheck_id: 预检编号(TPC-...)。
|
||||
Returns:
|
||||
{"summary": {...}, "items": [...], "sources": [...]}。
|
||||
Raises:
|
||||
NotFoundError: 预检不存在。
|
||||
"""
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(
|
||||
precheck_no=str(precheck_id).strip()
|
||||
).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
counts = PrecheckCountsDTO(**{
|
||||
key: int(precheck.counts_json.get(key, 0))
|
||||
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
|
||||
"executable_count", "blocked_count")
|
||||
})
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id=precheck.precheck_no,
|
||||
status=precheck.status,
|
||||
business_date=precheck.business_date,
|
||||
eligible_receipt_date_to=str(
|
||||
date.fromisoformat(precheck.business_date) - timedelta(days=1)
|
||||
),
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
|
||||
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
|
||||
precheck_hash=precheck.precheck_hash,
|
||||
)
|
||||
items = []
|
||||
for item in sorted(precheck.items, key=lambda row: row.invoice_no):
|
||||
items.append(PrecheckInvoiceItemDTO(
|
||||
source_code=item.source_code,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
row_no=int(line.get("row_no", 0)),
|
||||
file_version=line.get("file_version", ""),
|
||||
)
|
||||
for line in (item.raw_lines_json or [])
|
||||
),
|
||||
))
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
source_code=job.source_code,
|
||||
stage=job.status,
|
||||
file_no=job.file_no,
|
||||
file_version=None,
|
||||
checksum=job.file_sha256,
|
||||
)
|
||||
for job in (precheck.run.source_jobs if precheck.run else [])
|
||||
] or [
|
||||
SourceProgressDTO(source_code=code, stage="file_ready")
|
||||
for code in (precheck.scope_json.get("source_codes") or [])
|
||||
]
|
||||
return {
|
||||
"summary": summary,
|
||||
"items": items,
|
||||
"sources": sources,
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁。
|
||||
|
||||
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
|
||||
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
|
||||
禁止部分调拨、数量容差与隐式截断。
|
||||
依赖:标准库 decimal。
|
||||
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
|
||||
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
|
||||
return Decimal(str(left)) == Decimal(str(right))
|
||||
|
||||
|
||||
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
|
||||
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
|
||||
"""按严格相等规则分类数量匹配结果。
|
||||
|
||||
Args:
|
||||
receipt_quantity: 收料数量。
|
||||
erp_quantity: ERP 账面库存;None 表示无库存。
|
||||
external_quantity: 外部系统 账面库存;None 表示无库存。
|
||||
Returns:
|
||||
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
|
||||
"""
|
||||
if erp_quantity is None:
|
||||
if external_quantity is None:
|
||||
return MATCH_INVENTORY_NOT_FOUND
|
||||
if strict_quantities_equal(receipt_quantity, erp_quantity):
|
||||
if strict_quantities_equal(receipt_quantity, external_quantity):
|
||||
return MATCH_EXECUTABLE
|
||||
return MATCH_QUANTITY_MISMATCH
|
||||
@@ -0,0 +1,69 @@
|
||||
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
|
||||
|
||||
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
|
||||
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
|
||||
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
|
||||
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
|
||||
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
|
||||
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
|
||||
两函数同核推导,规则文本只存在一处。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
ShippingReceiptReportFile.created_at >= window_start,
|
||||
ShippingReceiptReportFile.created_at < window_end,
|
||||
or_(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_(None),
|
||||
ShippingReceiptReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的收料归档文件」SQL 条件。
|
||||
|
||||
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
|
||||
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
|
||||
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
@@ -96,7 +96,7 @@ def trigger_receipt_rpa(
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 0 占位约定
|
||||
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
|
||||
inventory_source_id=unit_payload['inventory_source_id'],
|
||||
source_code=unit_payload['source_code'],
|
||||
connector_type=unit_payload['connector_type'],
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.execution_service import _write_item
|
||||
from app.services.in_transit_transfer.orchestrator import finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps
|
||||
|
||||
STALE_EXECUTION_THRESHOLD_SECONDS = 3600
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨每日历史恢复(自动复核待处理池)。
|
||||
|
||||
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新匹配并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:models、retry_service._recheck_item、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +13,7 @@ from dataclasses import dataclass
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.precheck_service import TransferDeps
|
||||
from app.services.in_transit_transfer.matching_service import TransferDeps
|
||||
from app.services.in_transit_transfer.retry_service import _recheck_item
|
||||
|
||||
|
||||
|
||||
@@ -1,73 +1,170 @@
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
|
||||
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
|
||||
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
|
||||
单行入口由 retry_item 的 result_code 兜底拒绝(拒绝逻辑单点闭环,消失证据
|
||||
不可用旧库存翻回可执行);
|
||||
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
RESULT_FILE_REMOVED,
|
||||
RESULT_MISSING_UNIT,
|
||||
TransferDeps,
|
||||
scope_item_query,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
|
||||
|
||||
RETRY_KIND_ERP_RECHECK = "erp_recheck"
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
|
||||
# 可重查状态:可恢复阻断 + 可执行(已可执行的行也允许重查核对最新库存,
|
||||
# 避免匹配后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
|
||||
_RETRYABLE_STATUSES = {
|
||||
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
}
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
|
||||
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
|
||||
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
|
||||
|
||||
Returns:
|
||||
重检后的 item 状态。
|
||||
"""
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
# [口径] 重查按当前路由配置发查询,行上仓库字段同步刷新为本次解析值——
|
||||
# 查询与后续执行写路径必须用同一仓库值:行上旧值可能来自更早配置(路由
|
||||
# 已漂移),也可能为空(如 blocked_missing_unit 行在路由解析前被阻断)。
|
||||
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
|
||||
item.from_warehouse = route.from_warehouse
|
||||
item.to_warehouse = route.to_warehouse
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=item.run.run_no if item.run else "RUN-PENDING",
|
||||
attempt_no=item.attempt_no + 1,
|
||||
invoice_no=item.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
)
|
||||
item.attempt_no += 1
|
||||
before_status = item.status
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
# [降级] 与 matching 逐单语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)],
|
||||
)
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)
|
||||
stock_qty = stock_row.quantity if stock_row is not None else None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
|
||||
logger.warning(
|
||||
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
|
||||
item.invoice_no, item.id, item.attempt_no, detail,
|
||||
)
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
|
||||
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
|
||||
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_RECHECKED",
|
||||
aggregate_type="transfer_item",
|
||||
aggregate_id=str(item.id),
|
||||
run_no=item.run.run_no if item.run else None,
|
||||
invoice_no=item.invoice_no,
|
||||
item_id=str(item.id),
|
||||
attempt_no=item.attempt_no,
|
||||
actor_type="worker",
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
result="failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
|
||||
))
|
||||
db.session.flush()
|
||||
return item.status
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
|
||||
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
|
||||
# 查无记录与数量不足都是外部系统的真实答复:库存数必须落库展示(查无记录按 0),
|
||||
# 不得显示"-"让用户误以为查询失败。
|
||||
item.external_quantity = str(stock_qty) if stock_qty is not None else "0"
|
||||
attempt.status = "failed"
|
||||
elif not (stock_row.stock_unit or "").strip():
|
||||
# [单位只取 ERP] 数量一致但 ERP 未返回单位(img09 契约恒非空,出现即 ERP
|
||||
# 侧数据异常)→ blocked_missing_unit,禁止落 ready、禁止以文件单位顶替;
|
||||
# 行仓库已刷新为本次路由解析值(可解释、可再重查)。
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_MISSING_UNIT
|
||||
item.result_message = "external inventory unit is missing"
|
||||
item.external_quantity = str(stock_qty)
|
||||
item.unit = ""
|
||||
attempt.status = "failed"
|
||||
else:
|
||||
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
item.erp_quantity = str(query.quantity)
|
||||
item.external_quantity = str(stock_qty)
|
||||
item.unit = (stock_row.stock_unit or "").strip()
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 重查即续新鲜度:状态落定后显式刷新 updated_at(执行门禁
|
||||
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
|
||||
item.updated_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_RECHECKED",
|
||||
aggregate_type="transfer_item",
|
||||
@@ -87,34 +184,275 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
return item.status
|
||||
|
||||
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""人工重试异常项。
|
||||
|
||||
Args:
|
||||
item_id: TransferInvoiceItem.id。
|
||||
deps: 注入依赖。
|
||||
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
kind: external_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"item_id": ..., "status": ..., "attempt_no": ...}。
|
||||
Raises:
|
||||
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。
|
||||
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读 /
|
||||
file_removed 行不可重查(消失证据不可恢复:证据行的源单已从最新
|
||||
收料文件中消失,重查只会用外部系统旧库存把行翻回可执行,唯一出口
|
||||
= 人工关闭 / 等重新同步恢复)。
|
||||
NotFoundError: item 不存在。
|
||||
"""
|
||||
kind_value = str(kind or "").strip()
|
||||
if kind_value == RETRY_KIND_RPA_REFETCH:
|
||||
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
|
||||
if kind_value != RETRY_KIND_ERP_RECHECK:
|
||||
if kind_value != RETRY_KIND_EXTERNAL_RECHECK:
|
||||
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
if item is None:
|
||||
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
|
||||
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
|
||||
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
|
||||
if item.status not in _RETRYABLE_STATUSES:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
# [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope
|
||||
# 谓词排除失效行,但按 id 直取(requery_items_by_ids 循环)与单行入口都绕过
|
||||
# 该谓词——拒绝逻辑只落在此单点,三条入口同时闭环。为什么拒绝:消失证据
|
||||
# 不可恢复,重查会用外部系统旧库存把行翻回可执行(虚假放行),唯一出口
|
||||
# = 人工关闭 / 等重新同步恢复该行。
|
||||
if item.result_code == RESULT_FILE_REMOVED:
|
||||
raise ValidationError(
|
||||
"removed rows cannot be requeried; close manually or wait for re-sync",
|
||||
code="TRANSFER.RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
status = _recheck_item(item, deps=deps, request_id=request_id)
|
||||
db.session.commit()
|
||||
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
|
||||
|
||||
|
||||
def requery_items_by_ids(
|
||||
*, item_ids: list[int], deps: TransferDeps,
|
||||
actor_id: str | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""按明细 id 批量重查外部系统库存(待处理池批量「重查」入口)。
|
||||
|
||||
与 requery_items(匹配号定位)的差异:待处理池的行可能分散在多份历史
|
||||
匹配,只能按 id 直取。单行失败(状态不允许/不存在/异常)不影响其余行,
|
||||
隔离语义与 requery_items 一致。
|
||||
|
||||
Args:
|
||||
item_ids: TransferInvoiceItem.id 列表(非空)。
|
||||
deps / actor_id / request_id: 同 retry_item。
|
||||
Returns:
|
||||
{"total", "results": [{item_id, invoice_no, ok, status|error}]}。
|
||||
Raises:
|
||||
ValidationError: item_ids 为空。
|
||||
"""
|
||||
ids = [int(x) for x in (item_ids or []) if x is not None]
|
||||
if not ids:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
# [口径] 受影响来源=按 id 查回行的 source_code 去重(先查行→对齐→再重查)。
|
||||
source_rows = (
|
||||
db.session.query(TransferInvoiceItem.source_code)
|
||||
.filter(TransferInvoiceItem.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
affected_sources = sorted({(code or "").strip() for (code,) in source_rows})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于任何
|
||||
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
results: list[dict] = []
|
||||
for item_id in ids:
|
||||
try:
|
||||
retry_item(item_id=item_id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
results.append({"item_id": item_id, "invoice_no": item.invoice_no if item else "",
|
||||
"ok": True, "status": item.status if item else ""})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"item_id": item_id, "invoice_no": "", "ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批
|
||||
logger.warning(
|
||||
"transfer batch requery row crashed (skipped): item=%s error=%s",
|
||||
item_id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"item_id": item_id, "invoice_no": "", "ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"total": len(ids), "results": results}
|
||||
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行逐单重查并刷新。
|
||||
|
||||
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
|
||||
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
|
||||
(matching_id 指向旧匹配)必须同样可被本次匹配的重查触达,否则出现「卡片提示
|
||||
重查、重查却查不到行」的死锁(2026-09-24 修复)。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(经 scope_json 圈定行集)。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该 scope 全部可重查行。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
|
||||
"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
# [口径一致] 受影响来源=scope_json 的 source_codes(与 scope_item_query 圈行同源,
|
||||
# 提取口径同 matching_service.scope_item_query:非 dict 视为空 scope)。
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
affected_sources = sorted({str(code) for code in (scope.get("source_codes") or [])})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于 scope
|
||||
# 圈行执行,否则重查会圈到过期行、基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
# [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)——
|
||||
# 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。
|
||||
# file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。
|
||||
query = (
|
||||
scope_item_query(matching)
|
||||
.filter(
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
or_(
|
||||
TransferInvoiceItem.result_code.is_(None),
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED,
|
||||
),
|
||||
)
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
|
||||
items = query.order_by(TransferInvoiceItem.id).all()
|
||||
|
||||
results: list[dict] = []
|
||||
for item in items:
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": True, "status": item.status})
|
||||
except (ValidationError, NotFoundError) as exc:
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
|
||||
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
|
||||
logger.warning(
|
||||
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
|
||||
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"matching_no": matching_no, "total": len(items), "results": results}
|
||||
|
||||
|
||||
def retry_document(
|
||||
*, doc_no: str, deps: TransferDeps,
|
||||
actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""调拨单级重试(失败单一键恢复,主路径):圈单内行 → 逐行重查 → 全 ready 自动重跑。
|
||||
|
||||
【AI 触发时机】:用户在失败调拨单上点「重试」——替代旧的单据级重查(其按
|
||||
可执行池关联行,对 blocked 行必报"未能关联");本函数按单圈行(单是行权威
|
||||
归属),不依赖前端跨池拼 item_id。
|
||||
|
||||
核心逻辑:[STEP 1] 状态门禁——仅 failed 族(business/technical_failed)可重试;
|
||||
result_unknown 唯一出口=重新触发(D11),pending/executing 在飞拒绝,终态拒绝。
|
||||
[STEP 2] 单内 blocked 行逐行重查(复用 retry_item:单行隔离、file_removed 拒绝、
|
||||
每行落 Attempt);ready 行原样保留。 [STEP 3] 全部行 ready → 自动建新 Run 重跑
|
||||
(prepare_execution:门禁②文件对账 + D7①分支②复用原单号,写前复查兜底);
|
||||
任一行仍阻断 → 不重跑(单是原子单位,缺行不跑),阻断明细原样返回由池子兜底。
|
||||
|
||||
Args:
|
||||
doc_no: TransferDocument.doc_no。
|
||||
deps / actor_id / request_id: 同 retry_item。
|
||||
Returns:
|
||||
{"doc_no", "rerun": bool, "run_no": str|None,
|
||||
"ready": int, "blocked": [{invoice_no, item_id, reason}], "total": int}。
|
||||
Raises:
|
||||
NotFoundError: 单不存在。
|
||||
ValidationError: 状态不允许重试。
|
||||
"""
|
||||
from app.models import TransferDocument
|
||||
|
||||
doc = TransferDocument.query.filter_by(doc_no=str(doc_no).strip()).first()
|
||||
if doc is None:
|
||||
raise NotFoundError("transfer document not found", code="TRANSFER.DOCUMENT_NOT_FOUND")
|
||||
if doc.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
raise ValidationError(
|
||||
"result_unknown is read-only; use retrigger (D11)",
|
||||
code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
if doc.status not in DOCUMENT_STATUS_GROUPS["failed"]:
|
||||
raise ValidationError(
|
||||
f"document status {doc.status} is not retryable",
|
||||
code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
items = list(doc.items)
|
||||
if not items:
|
||||
raise ValidationError(
|
||||
"document has no attached items", code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
# [STEP 2] 单内 blocked 行逐行重查(行级隔离,单行失败不炸整单)。
|
||||
for item in items:
|
||||
if item.status != status_machine.TransferStatus.BLOCKED_RECOVERABLE.value:
|
||||
continue
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
except (ValidationError, NotFoundError):
|
||||
# file_removed 等拒绝语义:行保持阻断,原因随结果返回。
|
||||
continue
|
||||
|
||||
for item in items:
|
||||
db.session.expire(item)
|
||||
ready_ids = [item.id for item in items
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
|
||||
blocked = [
|
||||
{"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"reason": item.result_message or item.result_code or ""}
|
||||
for item in items
|
||||
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
]
|
||||
|
||||
# [STEP 3] 全 ready → 自动重跑;缺行不跑(单是原子单位)。
|
||||
rerun = bool(ready_ids) and not blocked
|
||||
run_no = None
|
||||
if rerun:
|
||||
from app.services.in_transit_transfer.execution_service import prepare_execution
|
||||
|
||||
outcome = prepare_execution(
|
||||
item_ids=ready_ids, deps=deps, actor_id=actor_id, request_id=request_id,
|
||||
# 链内新鲜事实豁免:重查(恢复判定)刚完成,重跑豁免写前复查。
|
||||
skip_write_recheck=True,
|
||||
)
|
||||
run_no = outcome.run_no
|
||||
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_DOCUMENT_RETRIED",
|
||||
aggregate_type="transfer_document",
|
||||
aggregate_id=doc.doc_no,
|
||||
run_no=run_no,
|
||||
actor_type="user",
|
||||
actor_id=str(actor_id) if actor_id else None,
|
||||
request_id=request_id,
|
||||
result="success" if rerun else "failure",
|
||||
before={"status": doc.status},
|
||||
after={"ready": len(ready_ids), "blocked": len(blocked), "rerun": rerun},
|
||||
))
|
||||
db.session.commit()
|
||||
return {
|
||||
"doc_no": doc.doc_no, "rerun": rerun, "run_no": run_no,
|
||||
"ready": len(ready_ids), "blocked": blocked, "total": len(items),
|
||||
}
|
||||
@@ -1,21 +1,44 @@
|
||||
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
|
||||
|
||||
用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。
|
||||
依赖:contracts、execution_service。
|
||||
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
|
||||
用途:将领域 DTO 转为前端稳定 JSON(匹配摘要/明细/来源进度/执行结果/单投影)。
|
||||
依赖:contracts、execution_service(serialize_order 内按需延迟引用其行聚合,
|
||||
避免模块级循环导入:execution_service 顶层引用本模块的 serialize_order)。
|
||||
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移;
|
||||
单(TransferDocument)投影经 serialize_order 统一(Task 11 融合卡调拨单清单
|
||||
与 Task 17 已执行单查询共用同一契约源)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.execution_service import serialize_run_result
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
# ---------------------------------------------------------------------------
|
||||
# success=累计产出(含重复提交成功);failed/executing/result_unknown=未完结即待办;
|
||||
# cancelled 不展示(无产生路径,且不在任何分组计数中)。
|
||||
DOCUMENT_STATUS_GROUPS: dict[str, tuple[str, ...]] = {
|
||||
"success": ("success", "duplicate_success"),
|
||||
"failed": ("business_failed", "technical_failed"),
|
||||
"executing": ("pending", "executing"),
|
||||
"result_unknown": ("result_unknown",),
|
||||
}
|
||||
|
||||
|
||||
def order_status_group(status: str) -> str | None:
|
||||
"""单状态 → 展示分组键;组外状态(cancelled)返回 None(不展示)。"""
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items():
|
||||
if status in statuses:
|
||||
return group
|
||||
return None
|
||||
|
||||
|
||||
def serialize_summary(summary) -> dict[str, Any]:
|
||||
"""预检摘要序列化。"""
|
||||
"""匹配摘要序列化。"""
|
||||
return {
|
||||
"precheck_id": summary.precheck_id,
|
||||
"matching_id": summary.matching_id,
|
||||
"status": summary.status,
|
||||
"business_date": summary.business_date,
|
||||
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
|
||||
@@ -23,35 +46,51 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"counts": {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"prechecked_count": summary.counts.prechecked_count,
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
# 待查行(文件已落地未查库存)与失效行(blocked_file_removed)透传
|
||||
# (2026-09-25 counts 契约扩展,键名与 DTO 字段同名)。
|
||||
"pending_stock_check_count": summary.counts.pending_stock_check_count,
|
||||
"invalid_count": summary.counts.invalid_count,
|
||||
},
|
||||
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
|
||||
"estimated_erp_write_count": summary.estimated_erp_write_count,
|
||||
"precheck_hash": summary.precheck_hash,
|
||||
"estimated_external_write_count": summary.estimated_external_write_count,
|
||||
"matching_hash": summary.matching_hash,
|
||||
}
|
||||
|
||||
|
||||
def serialize_item(item) -> dict[str, Any]:
|
||||
"""明细项序列化(决策 6 十列字段)。"""
|
||||
"""明细项序列化(决策 6 十列字段 + 行装饰字段)。
|
||||
|
||||
行装饰字段(item_id/checked_at/stale/file_current)由 restore 按 scope
|
||||
实时视图路径在 DTO 上填齐;匹配快照路径(run_matching)为缺省值
|
||||
(0/None/False/False),前端按存在性展示。
|
||||
"""
|
||||
return {
|
||||
"source_code": item.source_code,
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
"specification": item.specification,
|
||||
"invoice_no": item.invoice_no,
|
||||
"lot_no": item.lot_no,
|
||||
"receipt_date": item.receipt_date,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"to_quantity": str(item.to_quantity),
|
||||
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
|
||||
"unit": item.unit,
|
||||
"result": item.result,
|
||||
"reason": item.reason,
|
||||
"raw_lines": [
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
"item_id": item.item_id,
|
||||
"checked_at": item.checked_at,
|
||||
"stale": item.stale,
|
||||
"file_current": item.file_current,
|
||||
}
|
||||
|
||||
|
||||
@@ -68,10 +107,120 @@ def serialize_source(source) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"""预检恢复详情(summary + items + sources)。"""
|
||||
def serialize_matching_detail(detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"""匹配恢复详情(summary + items + sources)。"""
|
||||
return {
|
||||
"summary": serialize_summary(detail["summary"]),
|
||||
"items": [serialize_item(item) for item in detail["items"]],
|
||||
"sources": [serialize_source(source) for source in detail["sources"]],
|
||||
}
|
||||
|
||||
|
||||
def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
"""单投影公共序列化(Task 11 融合卡调拨单清单与 Task 17 已执行单查询共用契约源)。
|
||||
|
||||
【AI 触发时机】:任何需要把一张 TransferDocument(单)转成前端 JSON 的场景
|
||||
(GET /runs/{run_no} 的 orders 数组、GET /documents 的单行),禁止再各自拼装。
|
||||
|
||||
核心逻辑:[STEP 1] 行集按 ERP 行粒度(物料+批号+拨出/拨入库位)聚合,数量
|
||||
Decimal 相加取 6 位小数字符串(D14 快照口径),unit/material_name 取组内首个
|
||||
非空原值;[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内
|
||||
首个非空行级 result_message,成功行/无原因为 None(前端按
|
||||
「reason ?? 单 error_message」展示)。
|
||||
|
||||
Args:
|
||||
doc: TransferDocument ORM 实例。
|
||||
items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。
|
||||
|
||||
Returns:
|
||||
单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse,
|
||||
status, erp_document_no, error_message, lines}。
|
||||
"""
|
||||
# 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入;
|
||||
# 运行期 sys.modules 已就绪)。聚合键/序与 ERP 写入行一致。
|
||||
from app.services.in_transit_transfer.execution_service import _build_order_lines
|
||||
|
||||
ordered = sorted(items, key=lambda row: row.id)
|
||||
aggregated = _build_order_lines(ordered)
|
||||
name_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
reason_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
for item in ordered:
|
||||
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号 WTP→HOW 派生),
|
||||
# 否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
|
||||
key = (
|
||||
str(item.material_no or "").strip(),
|
||||
external_lot_no(item.lot_no),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
name = str(item.material_name or "").strip()
|
||||
if name and key not in name_by_key:
|
||||
name_by_key[key] = name
|
||||
# [T13-3] 行级失败/未知原因(result_message)随行组投影;成功行为 None。
|
||||
message = str(item.result_message or "").strip()
|
||||
if message and key not in reason_by_key:
|
||||
reason_by_key[key] = message
|
||||
return {
|
||||
"doc_no": doc.doc_no,
|
||||
"receipt_date": doc.receipt_date,
|
||||
"from_warehouse": doc.from_warehouse,
|
||||
"to_warehouse": doc.to_warehouse,
|
||||
"status": doc.status,
|
||||
"erp_document_no": doc.erp_document_no,
|
||||
"error_message": doc.error_message,
|
||||
"lines": [
|
||||
{
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
line["from_warehouse"], line["to_warehouse"]),
|
||||
"",
|
||||
),
|
||||
"lot_no": line["lot_no"],
|
||||
"quantity": line["quantity_text"],
|
||||
"unit": line["unit"],
|
||||
# [T13-3 契约] reason=行级 result_message(失败/未知行),成功行 None。
|
||||
"reason": reason_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
line["from_warehouse"], line["to_warehouse"]),
|
||||
),
|
||||
}
|
||||
for line in aggregated
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"""已执行单查询投影(Task 17 GET /documents orders 逐键,首页区块数据源)。
|
||||
|
||||
在公共单投影(serialize_order)之上补齐查询视图字段:submit_timestamp/
|
||||
status_group/created_at/run_no/items(invoice 粒度行集——与融合卡的聚合
|
||||
lines 不同,本视图逐 Invoice 行展示,供展开明细与影响面核对)。
|
||||
run_no 为 Task 17 契约的必要补充键(契约未列但 result_unknown 行
|
||||
[重新触发] 必须持 run_no 调 POST /runs/{run_no}/documents/{doc_no}/retrigger)。
|
||||
"""
|
||||
base = serialize_order(doc, items)
|
||||
return {
|
||||
"doc_no": base["doc_no"],
|
||||
"submit_timestamp": doc.submit_timestamp,
|
||||
"status": base["status"],
|
||||
"status_group": order_status_group(doc.status),
|
||||
"receipt_date": base["receipt_date"],
|
||||
"from_warehouse": base["from_warehouse"],
|
||||
"to_warehouse": base["to_warehouse"],
|
||||
"erp_document_no": base["erp_document_no"],
|
||||
"error_message": base["error_message"],
|
||||
"created_at": doc.created_at.isoformat() if doc.created_at else None,
|
||||
"run_no": doc.run.run_no if doc.run_id and doc.run else None,
|
||||
"items": [
|
||||
{
|
||||
"invoice_no": item.invoice_no,
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
"lot_no": item.lot_no or "",
|
||||
"quantity": item.receipt_quantity,
|
||||
"unit": item.unit or "",
|
||||
}
|
||||
for item in sorted(items, key=lambda row: row.id)
|
||||
],
|
||||
}
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
|
||||
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
|
||||
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;否则 → none。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
|
||||
receipt_file_gate(可用/失效判定单一事实来源)。
|
||||
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
|
||||
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
expired_receipt_file_condition,
|
||||
usable_receipt_file_condition,
|
||||
)
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
@@ -19,16 +25,19 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的收料文件状态投影。
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
|
||||
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。
|
||||
"""
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -60,4 +69,17 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
|
||||
expired_report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
expired_receipt_file_condition(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if expired_report is not None:
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨来源级状态服务(唯一推进入口)。
|
||||
|
||||
用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源),
|
||||
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
让 create_matching / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
依赖:models(TransferSourceJob)、status_machine。
|
||||
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,17 +17,26 @@ from app.models import TransferSourceJob
|
||||
|
||||
SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
|
||||
|
||||
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
|
||||
def create_source_job(
|
||||
*,
|
||||
run_id: int,
|
||||
source_code: str,
|
||||
status: str = 'pending',
|
||||
error_code: str | None = None,
|
||||
error_message: str | None = None,
|
||||
) -> TransferSourceJob:
|
||||
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
|
||||
|
||||
Args:
|
||||
run_id: 所属 TransferRun.id。
|
||||
source_code: 来源实例编码。
|
||||
status: 初始状态。
|
||||
error_code / error_message: 来源级失败事实(如解析失败 error_code),
|
||||
随创建落库,保证刷新/恢复后失败原因仍可见(不静默丢成全 0)。
|
||||
Returns:
|
||||
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
|
||||
"""
|
||||
@@ -36,7 +45,13 @@ def create_source_job(*, run_id: int, source_code: str, status: str = 'pending')
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
|
||||
job = TransferSourceJob(
|
||||
run_id=run_id,
|
||||
source_code=source_code,
|
||||
status=status,
|
||||
error_code=error_code,
|
||||
error_message=error_message,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.flush()
|
||||
return job
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
|
||||
result_unknown / manually_closed / success / duplicate_success /
|
||||
not_matured / cancelled 为无出边终态;
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
|
||||
not_matured / cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
|
||||
DOCUMENT_RETRIGGER_TRANSITIONS 允许 result_unknown 单经人工 retrigger
|
||||
→ executing,D11 唯一出口;QUEUED Run 经 worker 领取 → executing);
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,7 +27,7 @@ class TransferStatus(StrEnum):
|
||||
|
||||
FILE_PENDING = "file_pending"
|
||||
FILE_READY = "file_ready"
|
||||
PRECHECKING = "prechecking"
|
||||
MATCHING = "matching"
|
||||
READY_TO_EXECUTE = "ready_to_execute"
|
||||
EXECUTING = "executing"
|
||||
SUCCESS = "success"
|
||||
@@ -39,11 +41,11 @@ class TransferStatus(StrEnum):
|
||||
|
||||
|
||||
class TransferRunStatus(StrEnum):
|
||||
"""Run 级生命周期;ERP 结果与通知结果分离。"""
|
||||
"""Run 级生命周期;外部系统 结果与通知结果分离。"""
|
||||
|
||||
QUEUED = "queued"
|
||||
PREPARING_FILES = "preparing_files"
|
||||
PRECHECKING = "prechecking"
|
||||
MATCHING = "matching"
|
||||
READY_TO_EXECUTE = "ready_to_execute"
|
||||
EXECUTING = "executing"
|
||||
SUCCESS = "success"
|
||||
@@ -61,6 +63,9 @@ class TransferNotificationStatus(StrEnum):
|
||||
|
||||
|
||||
# 无出边终态:这些状态不得再触发任何自动或手工迁移。
|
||||
# [T10/R7 例外,均已显式声明于 ITEM_TRANSITIONS]:result_unknown 行唯一人工出边 =
|
||||
# retrigger 驱动 → executing(D11 唯一出口,随单重跑);success/duplicate_success
|
||||
# 仍为严格终态(单成功行不可再执行)。
|
||||
TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
|
||||
TransferStatus.SUCCESS.value,
|
||||
TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
@@ -78,17 +83,17 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}),
|
||||
TransferStatus.FILE_READY.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value,
|
||||
TransferStatus.MATCHING.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}),
|
||||
TransferStatus.PRECHECKING.value: frozenset({
|
||||
TransferStatus.MATCHING.value: frozenset({
|
||||
TransferStatus.READY_TO_EXECUTE.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.NOT_MATURED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.READY_TO_EXECUTE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检
|
||||
TransferStatus.MATCHING.value, # 确认失效/库存变化 → 新 Attempt 重新匹配
|
||||
TransferStatus.EXECUTING.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
@@ -99,16 +104,24 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.RESULT_UNKNOWN.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
# [T10 执行链路出边] worker 重领取/同单复用重跑:executing 行随单再次进入执行。
|
||||
TransferStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.MATCHING.value, # 仅 外部系统 重查/重新匹配,创建新 Attempt
|
||||
# [T10 执行链路出边] D7①② 复用重跑:blocked 行随失败单重新勾选,随单再执行。
|
||||
TransferStatus.EXECUTING.value,
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.NOT_MATURED.value: frozenset(),
|
||||
TransferStatus.SUCCESS.value: frozenset(),
|
||||
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
|
||||
TransferStatus.RESULT_UNKNOWN.value: frozenset(),
|
||||
# [T10/R7 出边] result_unknown 行唯一出边 = 人工 retrigger 驱动 → executing
|
||||
# (D11 唯一出口;行随 result_unknown 单重跑,仅 retrigger_document 链路可达)。
|
||||
TransferStatus.RESULT_UNKNOWN.value: frozenset({
|
||||
TransferStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferStatus.MANUALLY_CLOSED.value: frozenset(),
|
||||
TransferStatus.CANCELLED.value: frozenset(),
|
||||
TransferStatus.NOTIFICATION_FAILED.value: frozenset(),
|
||||
@@ -116,16 +129,18 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
|
||||
# Run 级转换白名单。
|
||||
RUN_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
# QUEUED → EXECUTING:D8 异步拆分(prepare 建 queued Run,worker 领取后置 executing)。
|
||||
TransferRunStatus.QUEUED.value: frozenset({
|
||||
TransferRunStatus.PREPARING_FILES.value,
|
||||
TransferRunStatus.EXECUTING.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferRunStatus.PREPARING_FILES.value: frozenset({
|
||||
TransferRunStatus.PRECHECKING.value,
|
||||
TransferRunStatus.MATCHING.value,
|
||||
TransferRunStatus.FAILED.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferRunStatus.PRECHECKING.value: frozenset({
|
||||
TransferRunStatus.MATCHING.value: frozenset({
|
||||
TransferRunStatus.READY_TO_EXECUTE.value,
|
||||
TransferRunStatus.FAILED.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
@@ -140,9 +155,16 @@ RUN_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferRunStatus.FAILED.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
# [T10/R7 复用边] 终态/部分失败 Run 承载 retrigger 重触发执行(execute_run
|
||||
# doc_id 路径回置 executing,逐单完成后由 finalize_run 重新收尾)。
|
||||
# success/cancelled 仍为严格终态(cancelled=人工停止;success=全单已成,无出边)。
|
||||
TransferRunStatus.SUCCESS.value: frozenset(),
|
||||
TransferRunStatus.PARTIAL_FAILED.value: frozenset(),
|
||||
TransferRunStatus.FAILED.value: frozenset(),
|
||||
TransferRunStatus.PARTIAL_FAILED.value: frozenset({
|
||||
TransferRunStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferRunStatus.FAILED.value: frozenset({
|
||||
TransferRunStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferRunStatus.CANCELLED.value: frozenset(),
|
||||
}
|
||||
|
||||
@@ -198,20 +220,52 @@ def assert_transition_allowed(
|
||||
)
|
||||
|
||||
|
||||
def apply_notification_failure(run_status: str) -> str:
|
||||
"""通知失败不改变 ERP 结果。
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单(TransferDocument)级人工转移白名单(D11 红线,仅 retrigger 驱动)
|
||||
# ---------------------------------------------------------------------------
|
||||
# result_unknown 单禁止关闭后重建(唯一双单路径),唯一合法出边 =
|
||||
# 人工重新触发(retrigger)→ executing(复用单号/时间戳只触发末步,幂等)。
|
||||
DOCUMENT_RETRIGGER_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.RESULT_UNKNOWN.value: frozenset({TransferStatus.EXECUTING.value}),
|
||||
}
|
||||
|
||||
|
||||
def assert_document_retrigger_allowed(current: str) -> None:
|
||||
"""单据级人工转移门禁:仅 result_unknown → executing(D11,retrigger 唯一出口)。
|
||||
|
||||
用途:retrigger_document 在改写单状态前调用本门禁,保证「人工转移」只能由
|
||||
retrigger 链路驱动;其余任何路径对 result_unknown 单的状态改写均视为
|
||||
违反 SOP 红线。
|
||||
|
||||
Args:
|
||||
run_status: Run 的 ERP 业务终态。
|
||||
current: 单当前状态。
|
||||
Raises:
|
||||
TransferStateError: 当前状态不是 result_unknown(或目标非 executing)。
|
||||
"""
|
||||
current_value = str(current or "").strip()
|
||||
allowed = DOCUMENT_RETRIGGER_TRANSITIONS.get(current_value)
|
||||
if allowed is None or TransferStatus.EXECUTING.value not in allowed:
|
||||
raise TransferStateError(
|
||||
"document retrigger only allowed from result_unknown",
|
||||
current=current_value,
|
||||
target=TransferStatus.EXECUTING.value,
|
||||
)
|
||||
|
||||
|
||||
def apply_notification_failure(run_status: str) -> str:
|
||||
"""通知失败不改变 外部系统 结果。
|
||||
|
||||
Args:
|
||||
run_status: Run 的 外部系统 业务终态。
|
||||
Returns:
|
||||
原 run_status(保持不变)。
|
||||
Raises:
|
||||
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
|
||||
TransferStateError: Run 尚未进入 外部系统 终态时不允许记录通知失败。
|
||||
"""
|
||||
status = str(run_status or "").strip()
|
||||
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
|
||||
raise TransferStateError(
|
||||
"notification failure only allowed after ERP terminal status",
|
||||
"notification failure only allowed after 外部系统 terminal status",
|
||||
current=status,
|
||||
)
|
||||
return status
|
||||
@@ -1,7 +1,8 @@
|
||||
"""在途调拨策略硬门禁。
|
||||
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
强制默认 10 分钟确认有效期。
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试;
|
||||
confirm_ttl_seconds 为纯展示阈值(默认 10 分钟 stale 徽标判定窗口,
|
||||
不再作为执行门禁——2026-09-25 退役)。
|
||||
依赖:app.core.errors.AppError、standard decimal。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
|
||||
阻止发布/执行(fail-closed)。
|
||||
@@ -24,7 +25,10 @@ class TransferStrategyPolicy:
|
||||
|
||||
allow_partial: bool = False
|
||||
quantity_tolerance: Decimal = Decimal("0")
|
||||
allow_erp_auto_retry: bool = False
|
||||
allow_external_auto_retry: bool = False
|
||||
# 纯展示阈值:行 stale 徽标(「库存数据已过期,请重查」提示)的判定窗口;
|
||||
# 不再作为执行门禁(2026-09-25 退役)——防错由文件版本对账 + worker 写前
|
||||
# 库存复查承担(见 execution_service)。
|
||||
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
|
||||
|
||||
@@ -46,16 +50,16 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
|
||||
Args:
|
||||
strategy: 待校验策略。
|
||||
Raises:
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 外部系统 自动重试。
|
||||
"""
|
||||
if strategy.allow_partial:
|
||||
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
|
||||
if strategy.quantity_tolerance != Decimal("0"):
|
||||
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
|
||||
if strategy.allow_erp_auto_retry:
|
||||
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
|
||||
if strategy.allow_external_auto_retry:
|
||||
raise StrategyViolationError("External auto retry is forbidden in phase 1", reason="allow_external_auto_retry")
|
||||
|
||||
|
||||
def default_strategy() -> TransferStrategyPolicy:
|
||||
"""返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。"""
|
||||
"""返回一期默认策略(全部禁令关闭,stale 展示阈值 600 秒)。"""
|
||||
return TransferStrategyPolicy()
|
||||
@@ -0,0 +1,127 @@
|
||||
"""在途调拨类型契约。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定匹配纳入哪些收料单——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的单(大小写不敏感,范围外单与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
|
||||
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Iterable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
|
||||
# 类型不支持(占位类型被调用)时的稳定错误码。
|
||||
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
|
||||
|
||||
class TransferType(StrEnum):
|
||||
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
|
||||
|
||||
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
|
||||
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
|
||||
|
||||
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
|
||||
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
|
||||
|
||||
|
||||
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
|
||||
|
||||
Args:
|
||||
value: 前端/API 传入的调拨类型值。
|
||||
Returns:
|
||||
TransferType 枚举。
|
||||
Raises:
|
||||
ValidationError: 非法类型值(不在枚举内)。
|
||||
"""
|
||||
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
|
||||
if not raw:
|
||||
return TransferType.IN_TRANSIT_TO_HUB
|
||||
try:
|
||||
return TransferType(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f"unknown transfer type: {raw}",
|
||||
code="TRANSFER.TRANSFER_TYPE_INVALID",
|
||||
details={"transfer_type": raw},
|
||||
) from exc
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
Raises:
|
||||
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
|
||||
"""
|
||||
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
|
||||
raise ValidationError(
|
||||
f"transfer type not supported yet: {transfer_type.value}",
|
||||
code=TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
details={"transfer_type": transfer_type.value},
|
||||
)
|
||||
|
||||
|
||||
def invoice_in_scope(invoice_no: str, transfer_type: TransferType | str | None) -> bool:
|
||||
"""判断 Invoice 单号是否落在调拨类型的收料数据范围内(单一判断口径)。
|
||||
|
||||
用途:匹配过滤(filter_invoices_for_type)与 scope 行圈定(matching_service
|
||||
的 scope_item_query)共用本谓词,避免"单过滤"与"行圈定"口径漂移。
|
||||
|
||||
Args:
|
||||
invoice_no: 收料单单号(大小写不敏感,前后空白忽略;空值恒 False)。
|
||||
transfer_type: 调拨类型(未规范化值允许,缺省/空回落类型 1)。
|
||||
Returns:
|
||||
True 表示该单在类型范围内(应纳入匹配/scope 查询);
|
||||
占位类型(规则未启用)恒 False。
|
||||
"""
|
||||
resolved = normalize_transfer_type(transfer_type)
|
||||
if resolved == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return str(invoice_no or "").strip().upper().startswith(prefixes)
|
||||
# 类型 2/3 的范围规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return False
|
||||
|
||||
|
||||
def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总单(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料单。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的单列表(判断口径统一走 invoice_in_scope)。
|
||||
"""
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if invoice_in_scope(invoice.invoice_no, transfer_type)
|
||||
]
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferMatching.scope_json 供审计追溯)。"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
|
||||
if transfer_type == TransferType.HUB_REPAIR_OUT:
|
||||
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
|
||||
return "pending_rule"
|
||||
@@ -1,37 +1,58 @@
|
||||
"""services/integration_connector/binding.py
|
||||
|
||||
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
|
||||
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
|
||||
有序 BindingStep 快照(一对多配方),并冻结调用期配置。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、
|
||||
errors.py、transports.base.merge_client_config。
|
||||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||||
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
|
||||
每步接口须 published、每步客户端须 enabled(fail-closed);同 context 下 priority
|
||||
高者优先;无命中或任一步门禁失败抛 BindingNotFoundError。
|
||||
存量空 steps_json 时由旧列合成单步(迁移兜底);读能力=单步,形状与多步统一。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.errors import BindingNotFoundError
|
||||
from app.services.integration_connector.transports.base import merge_client_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindingStep:
|
||||
"""绑定中的单步冻结快照:接口 + 归属客户端配置 + 该步参数映射。"""
|
||||
|
||||
interface_code: str
|
||||
connector_type: str
|
||||
client_code: str
|
||||
config: dict
|
||||
request_spec: dict
|
||||
response_mapping: dict
|
||||
input_schema: dict
|
||||
param_mapping: dict
|
||||
output_schema: dict
|
||||
interface_version: int
|
||||
credential_ref_code: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindingSnapshot:
|
||||
"""一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。"""
|
||||
"""一次调用冻结的绑定快照:有序步骤 + 映射版本(非活表引用)。
|
||||
|
||||
读能力为单元素 steps;写能力可为多步。credential_ref_code 兼容字段取自首步
|
||||
(真实凭据在逐步 client 上,顺序引擎按步解析)。
|
||||
"""
|
||||
|
||||
capability: str
|
||||
context_selector: dict
|
||||
client_code: str
|
||||
interface_code: str
|
||||
connector_type: str
|
||||
interface_version: int
|
||||
steps: tuple[BindingStep, ...]
|
||||
mapping_version: int
|
||||
credential_ref_code: str | None
|
||||
config: dict
|
||||
request_spec: dict
|
||||
response_mapping: dict
|
||||
output_schema: dict
|
||||
|
||||
|
||||
def _to_naive(dt: datetime | None) -> datetime | None:
|
||||
@@ -57,18 +78,140 @@ def _is_subset(selector: dict, context: dict) -> bool:
|
||||
return all(context.get(k) == v for k, v in selector.items())
|
||||
|
||||
|
||||
def _raw_steps_from_binding(row: IntegrationBinding) -> list[dict]:
|
||||
"""取出绑定步骤原料:优先 steps_json;空则由旧单步列合成(存量迁移兜底)。"""
|
||||
raw = list(row.steps_json or [])
|
||||
if raw:
|
||||
return raw
|
||||
# 兼容窗:迁移前/未回填行 → 单元素数组
|
||||
if row.interface_definition_code:
|
||||
return [{
|
||||
'interface_code': row.interface_definition_code,
|
||||
'param_mapping_json': row.param_mapping_json or {},
|
||||
}]
|
||||
return []
|
||||
|
||||
|
||||
def _freeze_step(
|
||||
*,
|
||||
capability: str,
|
||||
binding_id: int,
|
||||
step_index: int,
|
||||
step_raw: dict,
|
||||
) -> BindingStep:
|
||||
"""将一步配置冻结为 BindingStep;门禁失败抛 BindingNotFoundError。
|
||||
|
||||
Args:
|
||||
capability: 能力名(日志/异常)。
|
||||
binding_id: 绑定主键。
|
||||
step_index: 步骤下标(0-based,日志区分哪一步)。
|
||||
step_raw: {interface_code, param_mapping_json|param_mapping}。
|
||||
|
||||
Returns:
|
||||
BindingStep。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 接口/客户端缺失、未发布或停用。
|
||||
"""
|
||||
if not isinstance(step_raw, dict):
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=not_dict",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
iface_code = str(
|
||||
step_raw.get('interface_code') or step_raw.get('interface_definition_code') or ''
|
||||
).strip()
|
||||
if not iface_code:
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=missing_interface_code",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
mapping = step_raw.get('param_mapping_json', step_raw.get('param_mapping', {}))
|
||||
if mapping is None:
|
||||
mapping = {}
|
||||
if not isinstance(mapping, dict):
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=param_mapping_not_dict",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
|
||||
if iface is None:
|
||||
logger.warning(
|
||||
"connector binding step target missing: capability=%s binding_id=%s step=%s iface=%s",
|
||||
capability, binding_id, step_index, iface_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
client = IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
|
||||
if client is None:
|
||||
logger.warning(
|
||||
"connector binding step client missing: capability=%s binding_id=%s step=%s client=%s iface=%s",
|
||||
capability, binding_id, step_index, iface.client_instance_code, iface_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# fail-closed:该步接口未发布或客户端停用 → 视同无可用绑定(日志标明步号与原因)。
|
||||
if iface.status != 'published':
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s step=%s iface=%s reason=iface_status=%s",
|
||||
capability, binding_id, step_index, iface_code, iface.status,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
if not client.enabled:
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s step=%s client=%s reason=client_disabled",
|
||||
capability, binding_id, step_index, client.code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
config = merge_client_config({
|
||||
'config_json': client.config_json,
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
})
|
||||
request_spec = dict(iface.request_spec_json or {})
|
||||
if iface.http_method is not None:
|
||||
request_spec['method'] = iface.http_method
|
||||
if iface.request_path is not None:
|
||||
request_spec['path'] = iface.request_path
|
||||
|
||||
return BindingStep(
|
||||
interface_code=iface.code,
|
||||
connector_type=client.connector_type,
|
||||
client_code=client.code,
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
input_schema=iface.input_schema_json or {},
|
||||
param_mapping=dict(mapping),
|
||||
output_schema=iface.output_schema_json or {},
|
||||
interface_version=int(iface.version or 1),
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
)
|
||||
|
||||
|
||||
def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot:
|
||||
"""解析最佳绑定并冻结调用期快照。
|
||||
"""解析最佳绑定并冻结有序步骤快照。
|
||||
|
||||
Args:
|
||||
capability: 能力名(如 in_transit_transfer.query_inventory)。
|
||||
context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。
|
||||
environment: 环境(prod/test/dev)。
|
||||
now: 可选时钟(测试注入);缺省用 utcnow。
|
||||
|
||||
Returns:
|
||||
BindingSnapshot。
|
||||
BindingSnapshot(steps 至少一元素;读能力通常单步)。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 无可用绑定(fail-closed)。
|
||||
BindingNotFoundError: 无可用绑定,或任一步接口未发布/客户端停用/目标缺失
|
||||
(与列表「发布/退役」「启停」语义闭环;不向调用方泄露配置细节)。
|
||||
"""
|
||||
base_now = now or datetime.utcnow()
|
||||
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
|
||||
@@ -81,44 +224,37 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
continue
|
||||
candidates.append((row, selector))
|
||||
if not candidates:
|
||||
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」。
|
||||
logger.warning(
|
||||
"connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s",
|
||||
capability, environment, len(rows), sorted((context or {}).keys()),
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
|
||||
row, selector = candidates[0]
|
||||
|
||||
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
|
||||
if client is None or iface is None:
|
||||
raw_steps = _raw_steps_from_binding(row)
|
||||
if not raw_steps:
|
||||
logger.warning(
|
||||
"connector binding empty steps: capability=%s binding_id=%s",
|
||||
capability, row.id,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
|
||||
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
|
||||
config = dict(client.config_json or {})
|
||||
if client.endpoint is not None:
|
||||
config['endpoint'] = client.endpoint
|
||||
if client.timeout_seconds is not None:
|
||||
config['timeout_seconds'] = client.timeout_seconds
|
||||
|
||||
request_spec = dict(iface.request_spec_json or {})
|
||||
if iface.http_method is not None:
|
||||
request_spec['method'] = iface.http_method
|
||||
if iface.request_path is not None:
|
||||
request_spec['path'] = iface.request_path
|
||||
|
||||
selector = dict(row.context_selector_json or {})
|
||||
if row.context_source_code is not None and 'source_code' not in selector:
|
||||
selector['source_code'] = row.context_source_code
|
||||
steps: list[BindingStep] = []
|
||||
for idx, step_raw in enumerate(raw_steps):
|
||||
steps.append(_freeze_step(
|
||||
capability=capability,
|
||||
binding_id=row.id,
|
||||
step_index=idx,
|
||||
step_raw=step_raw,
|
||||
))
|
||||
|
||||
return BindingSnapshot(
|
||||
capability=row.capability,
|
||||
context_selector=selector,
|
||||
client_code=client.code,
|
||||
interface_code=iface.code,
|
||||
connector_type=client.connector_type,
|
||||
interface_version=iface.version,
|
||||
context_selector=dict(row.context_selector_json or {}),
|
||||
steps=tuple(steps),
|
||||
mapping_version=row.mapping_version,
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
output_schema=iface.output_schema_json or {},
|
||||
credential_ref_code=steps[0].credential_ref_code,
|
||||
)
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
|
||||
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
|
||||
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。
|
||||
逻辑:能力必须由代码注册,不能由管理端动态定义;各域契约声明在各域包的
|
||||
capabilities 模块(如 in_transit_transfer/capabilities.py),由应用组合根
|
||||
import 完成注册;领域只调用已注册能力,未注册 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,37 +14,6 @@ from dataclasses import dataclass
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.integration_connector.errors import CapabilityNotFoundError
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
|
||||
"properties": {
|
||||
"invoice_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"to_warehouse": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
},
|
||||
}
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"found": {"type": "boolean"},
|
||||
"quantity": {"type": ["number", "null"]},
|
||||
},
|
||||
}
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilitySpec:
|
||||
@@ -56,7 +27,6 @@ class CapabilitySpec:
|
||||
|
||||
|
||||
_CAPABILITIES: dict[str, CapabilitySpec] = {}
|
||||
_LOADED = False
|
||||
|
||||
|
||||
def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
|
||||
@@ -84,42 +54,6 @@ def list_capabilities() -> list[CapabilitySpec]:
|
||||
return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
|
||||
|
||||
|
||||
def ensure_capabilities_loaded() -> None:
|
||||
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
|
||||
global _LOADED # noqa: PLW0603
|
||||
if _LOADED:
|
||||
return
|
||||
_LOADED = True
|
||||
_register_transfer_capabilities()
|
||||
|
||||
|
||||
def _register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
))
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=True,
|
||||
))
|
||||
register_capability(CapabilitySpec(
|
||||
name="in_transit_transfer.verify_duplicate",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=False,
|
||||
))
|
||||
|
||||
|
||||
def reset_capability_registry_for_tests() -> None:
|
||||
"""单测隔离:清空注册表并重置加载标记。"""
|
||||
global _LOADED # noqa: PLW0603
|
||||
"""单测隔离:清空注册表(领域 capabilities 模块可重调其注册函数重建)。"""
|
||||
_CAPABILITIES.clear()
|
||||
_LOADED = False
|
||||
@@ -0,0 +1,79 @@
|
||||
"""services/integration_connector/credential_types.py
|
||||
|
||||
用途:凭据形态注册表——每种凭据类型定义自己的字段清单(键名/是否密文/是否必填),
|
||||
是 UI 动态渲染与 API 组装/校验的唯一事实来源。
|
||||
依赖:app.core.errors;纯代码注册表,无 DB/IO。
|
||||
逻辑:类型由代码注册(与能力注册同哲学),管理端不可动态定义;字段键名即模板
|
||||
占位符 credential_<key> 的 <key>;新增形态 = 加一个注册条目 + 前端标签,零迁移。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 凭据形态注册表:key 为稳定类型编码(credential_type 列值),fields 为字段清单。
|
||||
# secret=True 的字段加密落库且永不回显;required 在「合并旧值后」仍缺失即拒绝。
|
||||
CREDENTIAL_TYPE_SPECS: dict[str, dict[str, Any]] = {
|
||||
"password": {
|
||||
"fields": [
|
||||
{"key": "username", "secret": False, "required": True},
|
||||
{"key": "password", "secret": True, "required": True},
|
||||
],
|
||||
},
|
||||
"token": {
|
||||
"fields": [
|
||||
{"key": "token", "secret": True, "required": True},
|
||||
],
|
||||
},
|
||||
"api_key": {
|
||||
"fields": [
|
||||
{"key": "api_key", "secret": True, "required": True},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_credential_type(credential_type: str) -> dict[str, Any] | None:
|
||||
"""按类型编码查字段定义;未知类型返回 None(调用方 fail-closed)。"""
|
||||
return CREDENTIAL_TYPE_SPECS.get(str(credential_type or "").strip())
|
||||
|
||||
|
||||
def list_credential_types() -> list[dict[str, Any]]:
|
||||
"""返回全部已注册类型及其字段定义(供 GET /credential-references/types)。"""
|
||||
return [
|
||||
{"type": type_code, "fields": [dict(field) for field in spec["fields"]]}
|
||||
for type_code, spec in sorted(CREDENTIAL_TYPE_SPECS.items())
|
||||
]
|
||||
|
||||
|
||||
def build_secret_dict(credential_type: str, values: dict) -> dict[str, str]:
|
||||
"""按类型定义从「合并旧值后的提交值」组装凭据字典。
|
||||
|
||||
只保留类型定义内的键(未知键丢弃);必填字段缺失抛 ValidationError(fail-closed)。
|
||||
"""
|
||||
spec = get_credential_type(credential_type)
|
||||
if spec is None:
|
||||
raise ValidationError("unknown credential_type", details={"credential_type": credential_type})
|
||||
result: dict[str, str] = {}
|
||||
for field in spec["fields"]:
|
||||
value = values.get(field["key"])
|
||||
if value is not None and str(value) != "":
|
||||
result[field["key"]] = str(value)
|
||||
missing = [field["key"] for field in spec["fields"] if field["required"] and not result.get(field["key"])]
|
||||
if missing:
|
||||
raise ValidationError("required credential fields missing", details={"fields": missing})
|
||||
return result
|
||||
|
||||
|
||||
def visible_fields(credential_type: str, secret_dict: dict) -> dict[str, str]:
|
||||
"""按类型定义回显非密字段(secret=True 的字段永不回显)。"""
|
||||
spec = get_credential_type(credential_type)
|
||||
if spec is None:
|
||||
return {}
|
||||
return {
|
||||
field["key"]: str(secret_dict[field["key"]])
|
||||
for field in spec["fields"]
|
||||
if not field["secret"] and secret_dict.get(field["key"])
|
||||
}
|
||||
@@ -1,26 +1,88 @@
|
||||
"""services/integration_connector/engine.py
|
||||
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→按步 map-params→call→classify→audit。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout;
|
||||
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
|
||||
逻辑:域入参先经能力 Schema 校验,再按绑定步骤 param_mapping 翻译为接口参数(对照该步
|
||||
接口入参 Schema 校验);凭据按引用逐步解析后以 credential_* 注入传输层。
|
||||
读能力(write=False)保持单步语义:首步执行 + 成功态做输出映射(行为与历史一致)。
|
||||
写能力(write=True)按 BindingSnapshot.steps 顺序执行四条统一规则(唯一编排语义,
|
||||
禁止扩展成 DSL):①resume=True 跳过全部非末步(不建连、不审计);
|
||||
②非末步失败/超时 → 中止=技术失败(后续步零调用):普通失败原样返回该步分类结果;
|
||||
超时的审计行保留 status='timeout' 技术真相,引擎对外返回 technical_failed
|
||||
(error_code=EXTERNAL_TIMEOUT_ABORTED,与末步超时区分)——stage 超时=WS 未触发、
|
||||
ERP 不可能建单,恢复路径是全量重跑(stage SQL 自带 DELETE 同时间戳幂等),
|
||||
不得落入 result_unknown 红线态;
|
||||
③末步响应经该步 response_mapping 映射 → 六态分类,result.data 恒带映射结果
|
||||
(含失败态);④末步超时 → status=timeout(上层落 result_unknown)。
|
||||
非末步成功放行后支持可选同步回调 on_nonfinal_success(通用步进机制,非业务 DSL):
|
||||
供域调用方在「中间表写成功」与「触发末步」之间落库断点标记(如 stage_confirmed_at
|
||||
先落库再触发);回调异常按该步失败处理(中止=technical_failed,追加异常审计行);
|
||||
读能力单步路径不回调。
|
||||
每步落一条 IntegrationCall:同 operation_id(一票一次执行 = N 条,按 operation_id 串联,
|
||||
步骤定位靠 binding_snapshot_json 的 step_index;模型已解除该列唯一约束并补普通索引,
|
||||
迁移 tt5b6c7d8e9f);传输层返回的保留键 `_wire`(线级事实,database/soap/rest)在落库前
|
||||
剥离为 wire_json 独立成列(经 _clamp_wire 统一尺寸收口,防超大响应撑爆审计行),
|
||||
禁止混入 response_summary_json;调用方可透传 business_ref(业务单号锚点)落库供检索;
|
||||
禁止跨步传参;入参非法/无绑定/映射失败/无 transport
|
||||
均 fail-closed;result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import replace
|
||||
from typing import Callable
|
||||
|
||||
from app import db
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability
|
||||
from app.services.integration_connector.binding import BindingSnapshot, BindingStep, resolve_binding
|
||||
from app.services.integration_connector.capability import CapabilitySpec, get_capability
|
||||
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
|
||||
from app.services.integration_connector.mapping import map_response, schema_errors
|
||||
from app.services.integration_connector.security import sanitize
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.services.integration_connector.security import resolve_credential, sanitize
|
||||
from app.services.integration_connector.transports.base import (
|
||||
RESULT_FAILURE_STATUSES,
|
||||
IntegrationCallResult,
|
||||
Transport,
|
||||
classify_transport_response,
|
||||
)
|
||||
from app.models import IntegrationCall
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 非末步"允许继续"的终态:仅成功族。其余(失败态/timeout/result_unknown)一律中止——
|
||||
# 非末步未确认成功时继续执行后续步会破坏"先落表后触发"的顺序不变量。
|
||||
_NON_FINAL_PROCEED_STATUSES = ('success', 'duplicate_success', 'duplicate_unverified')
|
||||
|
||||
# wire_json 内单字符串尺寸收口上限(控制器裁定:引擎侧统一截断,不在三传输层散补)。
|
||||
_WIRE_MAX_STRING_LEN = 20000
|
||||
# 超长截断尾缀:排障时可辨识"此处曾被收口",非原文。
|
||||
_WIRE_TRUNCATED_SUFFIX = '...[truncated]'
|
||||
|
||||
|
||||
def _clamp_wire(wire):
|
||||
"""递归收口 wire_json 内所有字符串字段到 _WIRE_MAX_STRING_LEN(纯函数,不改入参)。
|
||||
|
||||
用途:传输层 `_wire` 可能携带超大线级事实(SQL 全文/statements[].sql、请求体/
|
||||
响应体等),落 IntegrationCall.wire_json 前统一截断,防审计行与 JSON 列被撑爆。
|
||||
|
||||
Args:
|
||||
wire: `_wire` 原始结构(dict/嵌套 dict/list/标量任意组合)。
|
||||
Returns:
|
||||
收口后的新结构:超长字符串截为前 _WIRE_MAX_STRING_LEN 字符并追加
|
||||
_WIRE_TRUNCATED_SUFFIX 尾缀;未超长字符串与其余类型原样保留。
|
||||
"""
|
||||
if isinstance(wire, str):
|
||||
if len(wire) > _WIRE_MAX_STRING_LEN:
|
||||
return wire[:_WIRE_MAX_STRING_LEN] + _WIRE_TRUNCATED_SUFFIX
|
||||
return wire
|
||||
if isinstance(wire, dict):
|
||||
return {key: _clamp_wire(value) for key, value in wire.items()}
|
||||
if isinstance(wire, (list, tuple)):
|
||||
return [_clamp_wire(item) for item in wire]
|
||||
return wire
|
||||
|
||||
|
||||
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
|
||||
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
|
||||
@@ -84,67 +146,347 @@ class CapabilityGateway:
|
||||
idempotency_key: str | None = None,
|
||||
environment: str | None = None,
|
||||
transports: dict[str, Transport] | None = None,
|
||||
resume: bool = False,
|
||||
on_nonfinal_success: Callable[[BindingStep, int], None] | None = None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
ensure_capabilities_loaded()
|
||||
"""执行一次能力调用:读能力单步(既有行为);写能力按绑定步骤顺序执行。
|
||||
|
||||
Args:
|
||||
capability: 已注册能力名。
|
||||
context: 绑定路由上下文(来源/组织等键值对)。
|
||||
params: 域入参(先经能力 input_schema 校验,再逐步经 param_mapping 翻译)。
|
||||
operation_id: 审计串联键(一次调用 N 步共享,按 step_index 定位)。
|
||||
idempotency_key: 预留幂等键(引擎当前不消费)。
|
||||
environment: 显式环境;缺省从 Flask 配置推导。
|
||||
transports: 临时覆盖的 {connector_type: Transport}。
|
||||
resume: True 时跳过全部非末步(断点续跑:该票可能已建成单,禁止重插,
|
||||
只重新触发末步);被跳过的步骤不建连、不落审计、不回调。
|
||||
on_nonfinal_success: 通用步进回调(仅写能力多步路径):每个非末步成功放行
|
||||
(该步审计落库后、进入下一步前)同步调用一次,入参 (该步 BindingStep, 步号)。
|
||||
用途:域调用方在「中间表写成功」与「触发末步」之间落库断点标记
|
||||
(如 stage_confirmed_at 先落库再触发,D7③)。约束:回调同步执行并阻塞
|
||||
后续步,须保持短小——长事务/外部 IO 的副作用与耗时由调用方自律;
|
||||
回调异常按该步失败处理(中止=technical_failed,追加异常审计行,
|
||||
原成功审计行保留不篡改)。读能力单步路径不回调。
|
||||
business_ref: 通用业务锚点(可空):调用方透传的业务单号/任务号,落
|
||||
IntegrationCall.business_ref 供调用日志按业务单号检索/关联(能力无关,
|
||||
不传为 NULL,现有消费者零改动)。
|
||||
|
||||
Returns:
|
||||
IntegrationCallResult(六态之一;写能力末步 data 恒带映射结果)。
|
||||
|
||||
Raises:
|
||||
CapabilityNotFoundError: 能力未注册。
|
||||
InputInvalidError: 域入参不合能力输入 Schema。
|
||||
BindingNotFoundError: 无可用绑定或任一步接口/客户端门禁失败。
|
||||
CallFailedError: 某步无可用 transport。
|
||||
MappingInvalidError: 参数翻译或末步输出映射不合 Schema。
|
||||
"""
|
||||
spec = get_capability(capability)
|
||||
input_errors = schema_errors(params, spec.input_schema)
|
||||
if input_errors:
|
||||
# InputInvalidError 只带 message 不带明细,降级进 result_message 后只剩
|
||||
# "input invalid";不落日志则字段级原因(required missing/类型不符)永久丢失。
|
||||
logger.warning(
|
||||
"connector input invalid: capability=%s errors=%s",
|
||||
capability, input_errors,
|
||||
)
|
||||
raise InputInvalidError(details={'errors': input_errors})
|
||||
|
||||
env = environment or _environment()
|
||||
snapshot = resolve_binding(capability, context, env)
|
||||
transport = (transports or self.transports).get(snapshot.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
|
||||
if not spec.write:
|
||||
return self._call_read(spec, snapshot, params, operation_id, transports, business_ref)
|
||||
return self._call_write(
|
||||
spec, snapshot, params, operation_id, transports, resume, on_nonfinal_success,
|
||||
business_ref,
|
||||
)
|
||||
|
||||
request = build_request(snapshot.request_spec, snapshot.config, params)
|
||||
# ------------------------------------------------------------------
|
||||
# 读能力:单步(既有行为,勿改语义)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _call_read(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""读能力单步执行:首步翻译参数 → 调用 → 失败态直通分类 / 成功态输出映射。"""
|
||||
step = snapshot.steps[0]
|
||||
# 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行,
|
||||
# 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。
|
||||
params = map_response(step.param_mapping, params, step.input_schema) \
|
||||
if step.param_mapping else params
|
||||
transport = (transports or self.transports).get(step.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={step.connector_type}'})
|
||||
|
||||
# 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。
|
||||
credential = resolve_credential(step.credential_ref_code) if step.credential_ref_code else {}
|
||||
request = build_request(step.request_spec, step.config, params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}'
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': snapshot.config, 'credential': {}},
|
||||
interface={'request_spec_json': snapshot.request_spec},
|
||||
client={'config_json': step.config, 'credential': credential},
|
||||
interface={'request_spec_json': step.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, 0, params, None, result, start_ms, trace_id, business_ref)
|
||||
return result
|
||||
|
||||
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success')
|
||||
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
|
||||
if isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||||
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。
|
||||
result = classify_transport_response(raw)
|
||||
else:
|
||||
result = IntegrationCallResult(status='success')
|
||||
if result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
data = map_response(step.response_mapping, raw, step.output_schema or spec.output_schema)
|
||||
result = replace(result, data=data)
|
||||
result = replace(result, trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, 0, params, raw, result, start_ms, trace_id, business_ref)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 写能力:多步顺序执行(四条统一规则)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _call_write(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
resume: bool,
|
||||
on_nonfinal_success: Callable[[BindingStep, int], None] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""写能力按绑定步骤顺序执行;规则②非末步失败/超时中止、规则④末步超时返回 timeout。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(write=True)。
|
||||
snapshot: 冻结的有序步骤快照(≥1 步)。
|
||||
params: 域入参(已过能力 Schema 校验)。
|
||||
operation_id: 审计串联键。
|
||||
transports: 临时覆盖的传输层字典。
|
||||
resume: 规则①——True 跳过全部非末步(不建连、不审计、不回调)。
|
||||
on_nonfinal_success: 非末步成功放行后的同步回调((该步 BindingStep, 步号));
|
||||
None 表示不回调。
|
||||
business_ref: 业务锚点(可空):透传各步审计行 business_ref 列落库。
|
||||
|
||||
Returns:
|
||||
末步分类结果;或中止步(非末步)结果——普通失败原样返回该步分类结果,
|
||||
超时中止对外返回 technical_failed(EXTERNAL_TIMEOUT_ABORTED,与末步超时区分),
|
||||
回调异常中止返回 technical_failed(STEP_CALLBACK_FAILED)。
|
||||
"""
|
||||
steps = snapshot.steps
|
||||
last_index = len(steps) - 1
|
||||
result: IntegrationCallResult | None = None
|
||||
for index, step in enumerate(steps):
|
||||
is_final = index == last_index
|
||||
if resume and not is_final:
|
||||
# 规则①:续跑只执行末步——非末步可能已落表,禁止重插;不建连、不审计、不回调。
|
||||
continue
|
||||
result, step_params, trace_id, start_ms = self._execute_step(
|
||||
spec, snapshot, index, step, params, operation_id, transports, business_ref,
|
||||
)
|
||||
if not is_final and result.status not in _NON_FINAL_PROCEED_STATUSES:
|
||||
if result.status == 'timeout':
|
||||
# 规则②:非末步超时 → 中止=技术失败。审计行已按 'timeout' 落库(技术
|
||||
# 真相),对外改判 technical_failed:stage 超时=WS 未触发、ERP 不可能
|
||||
# 建单,正确恢复路径是全量重跑(stage SQL 自带 DELETE 同时间戳幂等),
|
||||
# 不得落入 result_unknown 红线态(组锁+人工 retrigger)。
|
||||
result = replace(result, status='technical_failed', error_code='EXTERNAL_TIMEOUT_ABORTED')
|
||||
return result
|
||||
if not is_final and on_nonfinal_success is not None:
|
||||
# 通用步进机制(非业务 DSL):非末步成功放行且审计已落库后、进入下一步前
|
||||
# 同步回调一次——域调用方借此在「中间表写成功」与「触发末步」之间落库
|
||||
# 断点标记(如 stage_confirmed_at 先落库再触发,D7③)。
|
||||
callback_started_ms = int(time.time() * 1000)
|
||||
try:
|
||||
on_nonfinal_success(step, index)
|
||||
except Exception as exc:
|
||||
# 回调异常按该步失败处理:中止=technical_failed,并追加一条异常审计行
|
||||
# (原成功审计行保留不篡改,append-only,同 operation_id 同 step_index)。
|
||||
logger.warning(
|
||||
"connector nonfinal callback failed: capability=%s operation_id=%s step=%s",
|
||||
spec.name, operation_id, index, exc_info=True,
|
||||
)
|
||||
cb_result = IntegrationCallResult(
|
||||
status='technical_failed',
|
||||
error_code='STEP_CALLBACK_FAILED',
|
||||
error_message=str(exc)[:500],
|
||||
trace_id=trace_id,
|
||||
)
|
||||
_record_call(
|
||||
operation_id, spec.name, snapshot, index, step_params,
|
||||
None, cb_result, callback_started_ms, trace_id, business_ref,
|
||||
)
|
||||
return cb_result
|
||||
assert result is not None # steps ≥ 1(resolve_binding 保证),末步必产出结果
|
||||
return result
|
||||
|
||||
def _execute_step(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
index: int,
|
||||
step: BindingStep,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> tuple[IntegrationCallResult, dict, str, int]:
|
||||
"""执行单步:参数翻译 → transport → 分类;末步追加映射 + 六态分类(规则③)。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(write=True)。
|
||||
snapshot: 冻结的有序步骤快照。
|
||||
index: 当前步下标(0-based)。
|
||||
step: 当前步快照。
|
||||
params: 域入参(已过能力 Schema 校验)。
|
||||
operation_id: 审计串联键(所有步骤共用同一裸值)。
|
||||
transports: 临时覆盖的传输层字典。
|
||||
business_ref: 业务锚点(可空):本步审计行 business_ref 列落库值。
|
||||
|
||||
Returns:
|
||||
(该步结果, 该步翻译后的接口参数, trace_id, 起始毫秒)——后三项供调用方在
|
||||
回调异常等场景补落审计行时复用。
|
||||
"""
|
||||
# 域参数 → 该步接口参数翻译(沿用既有 map_response 路径,结果对照该步入参 Schema)。
|
||||
step_params = map_response(step.param_mapping, params, step.input_schema) \
|
||||
if step.param_mapping else params
|
||||
transport = (transports or self.transports).get(step.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={step.connector_type}'})
|
||||
credential = resolve_credential(step.credential_ref_code) if step.credential_ref_code else {}
|
||||
request = build_request(step.request_spec, step.config, step_params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}' # 每步独立链路 ID(与单步时代一致;串联由 operation_id 承担)
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': step.config, 'credential': credential},
|
||||
interface={'request_spec_json': step.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, index, step_params, None, result, start_ms, trace_id, business_ref)
|
||||
return result, step_params, trace_id, start_ms
|
||||
|
||||
if index == len(snapshot.steps) - 1:
|
||||
result = _finalize_step(spec, step, raw, trace_id)
|
||||
else:
|
||||
# 非末步不产出末步判定:仅按传输层分类,供"是否继续"判定。
|
||||
classified = classify_transport_response(raw if isinstance(raw, dict) else {})
|
||||
result = replace(classified, trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, index, step_params, raw, result, start_ms, trace_id, business_ref)
|
||||
return result, step_params, trace_id, start_ms
|
||||
|
||||
|
||||
def _finalize_step(
|
||||
spec: CapabilitySpec,
|
||||
step: BindingStep,
|
||||
raw: dict | None,
|
||||
trace_id: str,
|
||||
) -> IntegrationCallResult:
|
||||
"""末步判定链(规则③):response_mapping 映射 → 六态分类。
|
||||
|
||||
分类输入 = 原始响应 ∪ 映射结果(映射优先):映射未覆盖 status 时保留传输层
|
||||
规范六态(存量单步写绑定兼容),覆盖后以映射为准(如 TIPTOP code→status)。
|
||||
result.data 恒带 mapped(含失败态),供上层消费业务字段;ERP 业务拒单
|
||||
(code≠0)即 classify 归 technical_failed、code/message 透传(用户口径:
|
||||
失败+原因,恢复动作与关票口径对失败态本就一致)。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(output_schema 兜底来源)。
|
||||
step: 末步快照(response_mapping/output_schema)。
|
||||
raw: 末步原始响应。
|
||||
trace_id: 链路追踪 ID。
|
||||
|
||||
Returns:
|
||||
分类后的 IntegrationCallResult。
|
||||
|
||||
Raises:
|
||||
MappingInvalidError: 映射结果不合该步/能力输出 Schema(fail-closed)。
|
||||
"""
|
||||
mapped = map_response(step.response_mapping, raw, step.output_schema or spec.output_schema)
|
||||
base = dict(raw) if isinstance(raw, dict) else {}
|
||||
result = classify_transport_response({**base, **mapped})
|
||||
return replace(result, data=mapped, trace_id=trace_id)
|
||||
|
||||
|
||||
def _record_call(
|
||||
operation_id: str,
|
||||
capability: str,
|
||||
snapshot: BindingSnapshot,
|
||||
step_index: int,
|
||||
params: dict,
|
||||
raw: dict | None,
|
||||
result: IntegrationCallResult,
|
||||
start_ms: int,
|
||||
trace_id: str,
|
||||
business_ref: str | None = None,
|
||||
) -> None:
|
||||
"""落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。"""
|
||||
"""落 IntegrationCall(每步一条;同 operation_id 串联 + step_index 定位 + 脱敏请求/响应摘要)。
|
||||
|
||||
多步顺序引擎一次调用落 N 条、共享同一裸 operation_id(模型唯一约束已由迁移
|
||||
tt5b6c7d8e9f 解除并补普通索引);步骤定位靠 binding_snapshot_json.step_index/step_count。
|
||||
传输层保留键 `_wire`(线级事实)在本函数剥离:经 _clamp_wire 尺寸收口后落
|
||||
wire_json 独立成列,不混入 response_summary_json。
|
||||
|
||||
Args:
|
||||
operation_id: 审计串联键(所有步骤共用同一裸值)。
|
||||
capability: 能力名。
|
||||
snapshot: 冻结的有序步骤快照。
|
||||
step_index: 当前步下标(0-based)。
|
||||
params: 该步翻译后的接口参数(sanitize 脱敏后入审计)。
|
||||
raw: 该步原始响应(超时为 None;可含保留键 `_wire`)。
|
||||
result: 该步结果。
|
||||
start_ms: 该步起始毫秒时间戳。
|
||||
trace_id: 该步链路 ID(每步独立生成)。
|
||||
business_ref: 业务锚点(可空):调用方透传的业务单号/任务号,不传为 NULL。
|
||||
"""
|
||||
elapsed_ms = int(time.time() * 1000) - start_ms
|
||||
step = snapshot.steps[step_index]
|
||||
# 剥离保留键 `_wire`:副本上 pop(不污染传输层原返回对象);非 dict(可缺/异形)
|
||||
# 视为无 wire;dict 则尺寸收口后落 wire_json 独立列。余下内容才是响应摘要。
|
||||
raw_dict = dict(raw) if isinstance(raw, dict) else {}
|
||||
wire = raw_dict.pop('_wire', None)
|
||||
call = IntegrationCall(
|
||||
operation_id=operation_id,
|
||||
capability=capability,
|
||||
binding_snapshot_json={
|
||||
'client_code': snapshot.client_code,
|
||||
'interface_code': snapshot.interface_code,
|
||||
'connector_type': snapshot.connector_type,
|
||||
'interface_version': snapshot.interface_version,
|
||||
'client_code': step.client_code,
|
||||
'interface_code': step.interface_code,
|
||||
'connector_type': step.connector_type,
|
||||
'interface_version': step.interface_version,
|
||||
'mapping_version': snapshot.mapping_version,
|
||||
'credential_ref_code': snapshot.credential_ref_code,
|
||||
'credential_ref_code': step.credential_ref_code,
|
||||
# 步骤定位:本条审计对应的步号与总步数(一票一次执行 = N 条同 operation_id)。
|
||||
'step_index': step_index,
|
||||
'step_count': len(snapshot.steps),
|
||||
'steps': [
|
||||
{
|
||||
'interface_code': s.interface_code,
|
||||
'client_code': s.client_code,
|
||||
'connector_type': s.connector_type,
|
||||
}
|
||||
for s in snapshot.steps
|
||||
],
|
||||
},
|
||||
request_summary_json=sanitize(params),
|
||||
response_summary_json=sanitize(raw or {}),
|
||||
response_summary_json=sanitize(raw_dict or {}),
|
||||
wire_json=_clamp_wire(wire) if isinstance(wire, dict) else None,
|
||||
business_ref=business_ref,
|
||||
status=result.status,
|
||||
elapsed_ms=elapsed_ms,
|
||||
trace_id=trace_id,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"""services/integration_connector/gateway.py
|
||||
|
||||
用途:模块级 CapabilityGateway 装配与测试注入点。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap。
|
||||
逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap/database。
|
||||
逻辑:生产用 REST/SOAP/Database 传输;测试通过 set_capability_gateway 注入替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
@@ -21,7 +22,11 @@ def set_capability_gateway(gateway: CapabilityGateway | None) -> None:
|
||||
|
||||
|
||||
def get_capability_gateway() -> CapabilityGateway:
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。"""
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP/Database)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()})
|
||||
return CapabilityGateway(transports={
|
||||
'rest': RestTransport(),
|
||||
'soap': SoapTransport(),
|
||||
'database': DatabaseTransport(),
|
||||
})
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
|
||||
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
|
||||
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
逻辑:只允许点路径/数组下标提取与白名单转换函数(含 pick 键值取值、template 参数模板、
|
||||
each 列表逐元素子映射),禁止任意 Python/JS/SQL;缺字段且不可满足→MappingInvalidError;
|
||||
输出不合 Schema→MappingInvalidError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import string
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
@@ -50,25 +52,57 @@ def _tokenize(path: str) -> list[str]:
|
||||
|
||||
|
||||
def extract_path(obj: Any, path: str) -> Any:
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
|
||||
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。
|
||||
|
||||
路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中:
|
||||
全部未命中视为 MISSING,部分命中收集为列表——同一配置在单/多记录
|
||||
(如多条件查询返回多个 RecordSet)之间不再随机失效。
|
||||
"""
|
||||
path = str(path or "")
|
||||
if len(path) > MAX_PATH_LENGTH:
|
||||
raise MappingInvalidError(details={"reason": "path_too_long"})
|
||||
tokens = _tokenize(path)
|
||||
if len(tokens) > MAX_DEPTH:
|
||||
raise MappingInvalidError(details={"reason": "path_too_deep"})
|
||||
cur = obj
|
||||
for tok in tokens:
|
||||
if isinstance(cur, list) and tok.isdigit():
|
||||
idx = int(tok)
|
||||
if idx >= len(cur):
|
||||
return MISSING
|
||||
cur = cur[idx]
|
||||
elif isinstance(cur, dict) and tok in cur:
|
||||
cur = cur[tok]
|
||||
else:
|
||||
return _walk(obj, tokens)
|
||||
|
||||
|
||||
def _walk(cur: Any, tokens: list[str]) -> Any:
|
||||
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。
|
||||
|
||||
[缺陷修复 2026-09-23] 扇出收集的命中值本身可能是列表(更深层重复节点,如
|
||||
多 RecordSet 的 Master 列表、单 Master 多 Record 的 Field 列表)。若不拍平,
|
||||
嵌套 list 会让 each/pick 等消费方取不到任何字段 → 行被静默丢弃——后果是
|
||||
批量库存查询整批误判为查无库存(机制推演;该嵌套形态尚未在生产观测到)。
|
||||
收集结果统一拍平一层:语义仍是"路径在重复结构中的全部命中"。
|
||||
"""
|
||||
if not tokens:
|
||||
return cur
|
||||
tok, rest = tokens[0], tokens[1:]
|
||||
if isinstance(cur, list) and tok.isdigit():
|
||||
idx = int(tok)
|
||||
if idx >= len(cur):
|
||||
return MISSING
|
||||
return cur
|
||||
return _walk(cur[idx], rest)
|
||||
if isinstance(cur, dict) and tok in cur:
|
||||
return _walk(cur[tok], rest)
|
||||
if isinstance(cur, list):
|
||||
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
|
||||
if not collected:
|
||||
return MISSING
|
||||
return _flatten(collected)
|
||||
return MISSING
|
||||
|
||||
|
||||
def _flatten(items: list[Any]) -> list[Any]:
|
||||
"""把扇出收集结果拍平一层:列表命中拼接、标量/字典命中保留,顺序不变。"""
|
||||
flat: list[Any] = []
|
||||
for item in items:
|
||||
if isinstance(item, list):
|
||||
flat.extend(item)
|
||||
else:
|
||||
flat.append(item)
|
||||
return flat
|
||||
|
||||
|
||||
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
|
||||
@@ -119,6 +153,125 @@ def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
|
||||
return then if condition == "truthy" and bool(value) else else_
|
||||
|
||||
|
||||
def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
|
||||
value_field: str | None = None, exists: bool = False, cast: str | None = None) -> Any:
|
||||
"""从「键值对记录列表」按 key_field==key_value 取值(行转列通用需求)。
|
||||
|
||||
Args:
|
||||
value: 目标列表(每项为 dict,如 XML 归一化后的 Field 列表)。
|
||||
key_field / key_value: 匹配键字段名与期望值(按字符串比较)。
|
||||
value_field: 命中后取的字段名;缺省返回整条记录。
|
||||
exists: True 时返回布尔(是否命中),不取值。
|
||||
cast: 可选 "decimal" 或 _cast 支持的标量类型。
|
||||
"""
|
||||
if value is MISSING:
|
||||
return MISSING
|
||||
if key_field is None or key_value is None:
|
||||
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
|
||||
# [形态归一] XML 归一化后重复子节点"单条=dict、多条=list"二态并存(如单条
|
||||
# Field);单 dict 等价单元素列表,直接按列表语义 pick(回归:ERP 返回单条
|
||||
# doc_no Field 时 pick_target_not_list → 单号丢失,单被误判 technical_failed)。
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
|
||||
for item in value:
|
||||
if isinstance(item, dict) and str(item.get(key_field)) == str(key_value):
|
||||
if exists:
|
||||
return True
|
||||
found = item.get(value_field) if value_field is not None else item
|
||||
if cast == "decimal":
|
||||
return _decimal(found)
|
||||
return _cast(found, cast) if cast else found
|
||||
if exists:
|
||||
return False
|
||||
return MISSING
|
||||
|
||||
|
||||
def _expand_repeated_child(item: Any, fields: dict) -> list[Any]:
|
||||
"""把"容器记录"沿 fields 表达式引用的重复子节点展开成逐子记录单元。
|
||||
|
||||
[缺陷修复 2026-09-23] 假说防御:若 ERP 返回"单 Master 容器挂多条库存 Record"
|
||||
的形态,fields 的 expr 都以同一首段(如 Record)开头时,扁平映射会让 pick 只
|
||||
取到首条记录,其余行(不同批号/料号的库存)被静默丢弃——批量查询整批误判为
|
||||
查无库存。本修复对该形态按首段逐元素拆开,保证"一条 Record 一行"。
|
||||
真实留档响应(IntegrationCall 审计)均为扁平形态(每 Master 单 Record),
|
||||
该嵌套形态尚未在生产观测到;此处按通用归一化语义防御。
|
||||
|
||||
Args:
|
||||
item: each 的单个元素(dict 容器记录;非 dict 原样返回)。
|
||||
fields: each 的子映射(expr 首段即候选重复子节点名)。
|
||||
Returns:
|
||||
展开后的单元列表(无可展开的重复子节点时为 [item])。
|
||||
仅当全部 expr 首段一致且该子节点是"非空 dict 列表"时才展开,
|
||||
其余形态维持原行为(fail-safe,不做有歧义的拆分)。
|
||||
"""
|
||||
if not isinstance(item, dict):
|
||||
return [item]
|
||||
roots = {
|
||||
str(spec.get("expr") or "").split(".", 1)[0].split("[", 1)[0]
|
||||
for spec in fields.values() if isinstance(spec, dict)
|
||||
}
|
||||
if "" in roots or len(roots) != 1:
|
||||
return [item]
|
||||
root = next(iter(roots))
|
||||
children = item.get(root)
|
||||
if not isinstance(children, list) or not children or not all(isinstance(c, dict) for c in children):
|
||||
return [item]
|
||||
return [{**item, root: child} for child in children]
|
||||
|
||||
|
||||
def _each(value: Any, fields: dict | None = None) -> Any:
|
||||
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
|
||||
|
||||
Args:
|
||||
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
|
||||
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
|
||||
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
|
||||
Note:
|
||||
元素是"容器记录"(同一 Master 下挂多条 Record,见 _expand_repeated_child)
|
||||
时按子记录逐条展开成行——批量查询多条库存不得丢行(2026-09-23 缺陷修复)。
|
||||
"""
|
||||
if value is MISSING:
|
||||
# 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表:
|
||||
# 空结果是合法答案(如库存查无此批号),交领域层归类为"未找到",
|
||||
# 不得因输出 Schema 校验 fail-closed 成映射错误。
|
||||
return []
|
||||
# XML 重复节点归一化后单条记录是 dict、多条是 list:单记录归一为单元素列表,
|
||||
# 否则同一配置在单/多记录间会随机 fail-closed。
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "each_target_not_list"})
|
||||
out: list[Any] = []
|
||||
for item in value:
|
||||
# [缺陷修复 2026-09-23] 容器记录内挂多条子记录(重复节点)时逐条展开,
|
||||
# 保证"一条外部记录一行";单条 dict 子节点行为不变。
|
||||
for unit in _expand_repeated_child(item, fields or {}):
|
||||
row: dict[str, Any] = {}
|
||||
for field, spec in (fields or {}).items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
v: Any = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
v = extract_path(unit, expr) if expr is not None else MISSING
|
||||
transform = spec.get("transform")
|
||||
if transform:
|
||||
fn = TRANSFORMS.get(transform)
|
||||
if fn is None:
|
||||
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
|
||||
v = fn(v, **(spec.get("args") or {}))
|
||||
if v is not MISSING:
|
||||
row[field] = v
|
||||
if row:
|
||||
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
|
||||
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
TRANSFORMS: dict[str, Any] = {
|
||||
"default": _default,
|
||||
"fallback": _fallback,
|
||||
@@ -127,9 +280,64 @@ TRANSFORMS: dict[str, Any] = {
|
||||
"enum-map": _enum_map,
|
||||
"list-map": _list_map,
|
||||
"if-else": _if_else,
|
||||
"pick": _pick,
|
||||
"each": _each,
|
||||
}
|
||||
|
||||
|
||||
# ---- 参数模板填充(spec 级 "template",对整个参数表渲染,多用于域参数→接口参数翻译)----
|
||||
|
||||
def _render_template_value(value: Any, args: dict) -> str:
|
||||
"""渲染单个占位符值:列表按 list_item_template 逐项渲染后用 separator 连接。
|
||||
|
||||
列表项为 dict 时,item_template 的占位符对 item 的键校验(缺失即
|
||||
template_item_field_missing,fail-closed)并按字段转义渲染,
|
||||
如 list_item_template = "(img01 = '{material_no}' AND img04 = '{lot_no}')"。
|
||||
"""
|
||||
item_template = str(args.get("list_item_template") or "{item}")
|
||||
separator = str(args.get("separator") if args.get("separator") is not None else ",")
|
||||
escape = args.get("escape")
|
||||
|
||||
def _escape(text: Any) -> str:
|
||||
text = str(text)
|
||||
if escape == "quote":
|
||||
text = text.replace("'", "''")
|
||||
return text
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
rendered: list[str] = []
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
placeholders = {f for _, f, _, _ in string.Formatter().parse(item_template) if f}
|
||||
missing = sorted(p for p in placeholders if p not in item)
|
||||
if missing:
|
||||
raise MappingInvalidError(details={"reason": "template_item_field_missing", "field": missing[0]})
|
||||
rendered.append(item_template.format(**{k: _escape(v) for k, v in item.items()}))
|
||||
else:
|
||||
rendered.append(item_template.format(item=_escape(item)))
|
||||
return separator.join(rendered)
|
||||
return _escape(value)
|
||||
|
||||
|
||||
def fill_param_template(template: str, params: dict, args: dict | None = None) -> str:
|
||||
"""按 {param} 占位符对参数表渲染模板(str.format 语义,{{}} 转义字面大括号)。
|
||||
|
||||
缺占位符即抛 MappingInvalidError(fail-closed),绝不静默输出空串。
|
||||
"""
|
||||
template = str(template or "")
|
||||
args = args or {}
|
||||
placeholders = {fname for _, fname, _, _ in string.Formatter().parse(template) if fname}
|
||||
rendered: dict[str, str] = {}
|
||||
for name in placeholders:
|
||||
if name not in (params or {}):
|
||||
raise MappingInvalidError(details={"reason": "template_param_missing", "param": name})
|
||||
rendered[name] = _render_template_value(params[name], args)
|
||||
try:
|
||||
return template.format(**rendered)
|
||||
except (KeyError, IndexError, ValueError) as exc:
|
||||
raise MappingInvalidError(details={"reason": "template_invalid"}) from exc
|
||||
|
||||
|
||||
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
|
||||
|
||||
def _matches_type(value: Any, type_spec: Any) -> bool:
|
||||
@@ -190,7 +398,10 @@ def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
|
||||
for field, spec in mapping.items():
|
||||
if not isinstance(spec, dict):
|
||||
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
|
||||
if "default" in spec:
|
||||
if "template" in spec:
|
||||
# 参数模板:对整个 raw(参数表)渲染,与单字段 expr 提取互补。
|
||||
value = fill_param_template(spec["template"], raw, spec.get("args") or {})
|
||||
elif "default" in spec:
|
||||
value = spec["default"]
|
||||
else:
|
||||
expr = spec.get("expr")
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
"""services/integration_connector/security.py
|
||||
|
||||
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
|
||||
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
|
||||
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
|
||||
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
|
||||
依赖:IntegrationCredentialReference 模型、core.credential_crypto、current_app.config、errors.py。
|
||||
逻辑:db 模式解密 secret_ciphertext(主密钥 INTEGRATION_CREDENTIAL_KEY 环境注入);
|
||||
env 模式按 secret_ref 读当前环境配置,缺失即抛 CredentialUnresolvedError;
|
||||
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文/密文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationCredentialReference
|
||||
from app.services.integration_connector.errors import CredentialUnresolvedError
|
||||
|
||||
# 连接器凭据密文的 Fernet 主密钥配置键与错误码。
|
||||
CREDENTIAL_KEY_CONFIG_NAME = 'INTEGRATION_CREDENTIAL_KEY'
|
||||
_DB_SECRET_CODES = CredentialCryptoErrorCodes(
|
||||
key_missing='INTEGRATION.CREDENTIAL_KEY_MISSING',
|
||||
key_invalid='INTEGRATION.CREDENTIAL_KEY_INVALID',
|
||||
secret_empty='INTEGRATION.CREDENTIAL_SECRET_EMPTY',
|
||||
secret_missing='INTEGRATION.CREDENTIAL_SECRET_MISSING',
|
||||
secret_invalid='INTEGRATION.CREDENTIAL_SECRET_INVALID',
|
||||
)
|
||||
|
||||
DEFAULT_SENSITIVE_KEYS = frozenset({
|
||||
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
|
||||
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
|
||||
@@ -20,10 +34,10 @@ DEFAULT_SENSITIVE_KEYS = frozenset({
|
||||
|
||||
|
||||
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
|
||||
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
|
||||
"""按凭据引用解析真实凭据(db 解密 / env 配置键),fail-closed。
|
||||
|
||||
Raises:
|
||||
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
|
||||
CredentialUnresolvedError: 引用不存在、密文缺失、主密钥缺失/无效或 env 键缺失。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
@@ -32,13 +46,29 @@ def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
|
||||
).first()
|
||||
if cred is None:
|
||||
raise CredentialUnresolvedError(ref=credential_ref_code)
|
||||
if cred.secret_provider == 'db':
|
||||
if not cred.secret_ciphertext:
|
||||
raise CredentialUnresolvedError(ref=credential_ref_code)
|
||||
try:
|
||||
value = decrypt_secret(
|
||||
cred.secret_ciphertext,
|
||||
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
|
||||
codes=_DB_SECRET_CODES,
|
||||
)
|
||||
except AppError as exc:
|
||||
raise CredentialUnresolvedError(message=str(exc.message)) from exc
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
except (ValueError, TypeError):
|
||||
parsed = None
|
||||
return dict(parsed) if isinstance(parsed, dict) else {'value': value}
|
||||
secret_ref = cred.secret_ref
|
||||
value = current_app.config.get(secret_ref) if has_app_ctx() else None
|
||||
if value is None or value == '':
|
||||
config_value = current_app.config.get(secret_ref) if has_app_ctx() else None
|
||||
if config_value is None or config_value == '':
|
||||
raise CredentialUnresolvedError(ref=secret_ref)
|
||||
if isinstance(value, dict):
|
||||
return dict(value)
|
||||
return {'value': value}
|
||||
if isinstance(config_value, dict):
|
||||
return dict(config_value)
|
||||
return {'value': config_value}
|
||||
|
||||
|
||||
def has_app_ctx() -> bool:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""services/integration_connector/transports/__init__.py
|
||||
|
||||
集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。
|
||||
集成连接器传输层:base(契约+分类)、rest、soap、database。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
@@ -15,4 +16,5 @@ __all__ = [
|
||||
'classify_transport_response',
|
||||
'RestTransport',
|
||||
'SoapTransport',
|
||||
'DatabaseTransport',
|
||||
]
|
||||
@@ -4,6 +4,8 @@
|
||||
依赖:typing.Protocol、dataclass;无 Flask/DB。
|
||||
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
|
||||
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
|
||||
probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。
|
||||
merge_client_config 将 endpoint/timeout_seconds/db_kind 专列拼回 config_json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +20,9 @@ RESULT_STATUSES = (
|
||||
'technical_failed', 'timeout', 'result_unknown',
|
||||
)
|
||||
|
||||
# 传输层直接判失败的子集(读能力返回带这些 status 的原始 dict 时不再做输出映射)。
|
||||
RESULT_FAILURE_STATUSES = ('business_failed', 'technical_failed')
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IntegrationCallResult:
|
||||
@@ -32,13 +37,47 @@ class IntegrationCallResult:
|
||||
|
||||
|
||||
class Transport(Protocol):
|
||||
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。"""
|
||||
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。
|
||||
|
||||
probe 为可选实现的连接测试探针:只证明网络/服务可达,不要求接口契约;
|
||||
Admin API 测试端点优先调 probe,未实现时回退 call(空 interface 规格)。
|
||||
"""
|
||||
|
||||
connector_type: str
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
...
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
...
|
||||
|
||||
|
||||
def merge_client_config(client: dict) -> dict:
|
||||
"""把客户端实例独立列(endpoint/timeout_seconds/db_kind)拼回 config_json 的兼容层。
|
||||
|
||||
与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等
|
||||
不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。
|
||||
database 类型的 db_kind 专列在此拼入,供 DatabaseTransport 查驱动注册表。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
if client.get('endpoint') is not None:
|
||||
config['endpoint'] = client['endpoint']
|
||||
if client.get('timeout_seconds') is not None:
|
||||
config['timeout_seconds'] = client['timeout_seconds']
|
||||
if client.get('db_kind') is not None:
|
||||
config['db_kind'] = client['db_kind']
|
||||
return config
|
||||
|
||||
|
||||
def mask_secrets(text: str, credential: dict | None) -> str:
|
||||
"""把凭据值从自由文本(错误回显/响应摘要)中替换为 ***,防外泄进审计与日志。"""
|
||||
result = str(text or '')
|
||||
for value in (credential or {}).values():
|
||||
secret = str(value or '')
|
||||
if secret:
|
||||
result = result.replace(secret, '***')
|
||||
return result
|
||||
|
||||
|
||||
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
|
||||
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。
|
||||
@@ -67,7 +106,7 @@ def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
|
||||
error_message=str(raw.get('message') or ''),
|
||||
)
|
||||
if status == 'timeout':
|
||||
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN')
|
||||
return IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN')
|
||||
if status == 'result_unknown':
|
||||
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no)
|
||||
return IntegrationCallResult(status='result_unknown', error_code='EXTERNAL_RESULT_UNKNOWN', document_no=document_no)
|
||||
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
|
||||
@@ -0,0 +1,570 @@
|
||||
"""services/integration_connector/transports/database.py
|
||||
|
||||
用途:Database SQL 传输层——按 db_kind 四库驱动注册表连接并执行/查询 SQL。
|
||||
依赖:oracledb / pymysql / psycopg2 / pymssql;errors、transports.base.mask_secrets。
|
||||
逻辑:gateway 按 connector_type=database 分发至此;request_spec.sql 支持 execute
|
||||
(pre→bulk→post 单事务 commit)与 query(返回 rows 不 commit);D17 标识符
|
||||
白名单 `{key}` 替换(替换后残留任何 `{...}` 形状即 fail-closed,封堵畸形
|
||||
占位符静默直通缺口);四库 connect 工厂消费 config.timeout_seconds 接入驱动
|
||||
超时参数(缺失/非法用驱动默认);异常 rollback + 凭据脱敏;probe 按库种 probe_sql。
|
||||
标识符替换后须从 bind dict 剔除白名单键(oracledb 不容多余键);pre/bulk/post/query
|
||||
再按各语句实际引用的 :bind(跳过字符串字面量与注释)逐语句过滤(oracledb 对
|
||||
语句未引用的键同样报 ORA-01036)。
|
||||
本模块禁止出现具体业务表/单据字面量(D12)。
|
||||
调用日志:execute/query 成功返回 dict 附带保留键 `_wire`(语句、最终 SQL、
|
||||
实际绑定、行数/行快照等线级事实),由引擎(Task 4)剥离落库 wire_json,
|
||||
禁止上游业务消费该键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.integration_connector.errors import InputInvalidError, TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
# D17:标识符(schema/表名)安全正则——字母开头,允许字母数字与 _ $ #
|
||||
_IDENTIFIER_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_$#]{0,127}$')
|
||||
# 语句中出现的 {placeholder}
|
||||
_PLACEHOLDER_RE = re.compile(r'\{([A-Za-z_][A-Za-z0-9_]*)\}')
|
||||
# 语句中出现的 :bind(配合字面量/注释扫描使用)
|
||||
_PLACEHOLDER_BIND_RE = re.compile(r':([A-Za-z_][A-Za-z0-9_]*)')
|
||||
# 任意 `{...}` 残留形状(含畸形占位符如 {schema.} / {1abc} / {})——替换后不容残留
|
||||
_RESIDUAL_PLACEHOLDER_RE = re.compile(r'\{[^}]*\}')
|
||||
# endpoint 统一 host:port[/database](oracle 段为 service_name)
|
||||
_ENDPOINT_RE = re.compile(r'^([^:]+):(\d+)(?:/(.+))?$')
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
ConnectFn = Callable[..., Any]
|
||||
|
||||
|
||||
def _timeout_seconds(config: dict) -> int | None:
|
||||
"""从 config.timeout_seconds 解析整数秒;缺失/非法/非正数 → None(用驱动默认,不报错)。
|
||||
|
||||
Args:
|
||||
config: 客户端 config(merge_client_config 已拼入 timeout_seconds 专列值)。
|
||||
|
||||
Returns:
|
||||
正整数秒;不可解析或 ≤0 返回 None(调用方据此省略驱动超时参数)。
|
||||
"""
|
||||
raw = config.get('timeout_seconds')
|
||||
if raw is None or isinstance(raw, bool):
|
||||
return None
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DriverSpec:
|
||||
"""单库驱动规格:connect 工厂 + probe SQL。"""
|
||||
|
||||
connect: ConnectFn
|
||||
probe_sql: str
|
||||
|
||||
|
||||
def _parse_endpoint(endpoint: str) -> tuple[str, int, str | None]:
|
||||
"""解析统一 endpoint 为 (host, port, database_or_service)。
|
||||
|
||||
Args:
|
||||
endpoint: `host:port` 或 `host:port/database`(oracle 为 service_name)。
|
||||
|
||||
Returns:
|
||||
(host, port, database_or_service);无路径段时第三项为 None。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 格式不合法。
|
||||
"""
|
||||
text = str(endpoint or '').strip()
|
||||
match = _ENDPOINT_RE.match(text)
|
||||
if not match:
|
||||
raise TransportNotFrozenError(f'invalid database endpoint: {endpoint!r}')
|
||||
host, port_s, db = match.group(1), match.group(2), match.group(3)
|
||||
return host, int(port_s), db or None
|
||||
|
||||
|
||||
def _connect_oracle(*, config: dict, credential: dict) -> Any:
|
||||
"""Oracle:oracledb EZConnect dsn=host:port/service;可选 thick(11g 等老服务端必须)。
|
||||
|
||||
thick 目录取值优先级:按客户端 config_json.oracle_lib_dir → 全局环境变量
|
||||
ORACLE_CLIENT_LIB_DIR(.env.* 由 settings 载入 os.environ;容器/系统环境同样生效,
|
||||
与 text2sql 同源)。初始化失败(路径无效/版本过老/已初始化)静默回退 thin——
|
||||
真实连接失败在 connect 处暴露(thick-only 的老版本服务端会报 DPY-3010)。
|
||||
超时:tcp_connect_timeout(秒,建连超时)为安装版本(oracledb 4.0.2)connect()
|
||||
实际支持的参数;call_timeout(毫秒,单次 round-trip 超时)不是 connect 参数,
|
||||
建连后按连接属性设置(thin/thick 均支持,异常安装版本静默跳过用驱动默认)。
|
||||
"""
|
||||
import oracledb
|
||||
|
||||
# [STEP 1] 可选 thick 模式(config_json.oracle_lib_dir → 全局环境兜底)
|
||||
lib_dir = str(config.get('oracle_lib_dir') or '').strip() or (os.getenv('ORACLE_CLIENT_LIB_DIR') or '').strip()
|
||||
if lib_dir:
|
||||
try:
|
||||
oracledb.init_oracle_client(lib_dir=lib_dir)
|
||||
except Exception:
|
||||
# 已初始化或 thin 可用时忽略;真实连接失败再暴露
|
||||
pass
|
||||
|
||||
host, port, service = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
if not service:
|
||||
raise TransportNotFrozenError('oracle endpoint requires service_name: host:port/service')
|
||||
dsn = f'{host}:{port}/{service}'
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs['tcp_connect_timeout'] = timeout
|
||||
conn = oracledb.connect(
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
dsn=dsn,
|
||||
**kwargs,
|
||||
)
|
||||
if timeout is not None:
|
||||
try:
|
||||
conn.call_timeout = timeout * 1000 # 毫秒
|
||||
except Exception:
|
||||
# 个别安装模式不支持 call_timeout 属性时跳过(建连超时已生效),不阻断调用
|
||||
pass
|
||||
return conn
|
||||
|
||||
|
||||
def _connect_mysql(*, config: dict, credential: dict) -> Any:
|
||||
"""MySQL:pymysql,charset=utf8mb4;超时=connect/read/write_timeout(秒)。"""
|
||||
import pymysql
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs.update(connect_timeout=timeout, read_timeout=timeout, write_timeout=timeout)
|
||||
return pymysql.connect(
|
||||
host=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
database=database or '',
|
||||
charset='utf8mb4',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _connect_postgresql(*, config: dict, credential: dict) -> Any:
|
||||
"""PostgreSQL:psycopg2,dbname 对应 endpoint 路径段;超时=connect_timeout(秒)。"""
|
||||
import psycopg2
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs['connect_timeout'] = timeout
|
||||
return psycopg2.connect(
|
||||
host=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
dbname=database or '',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _connect_sqlserver(*, config: dict, credential: dict) -> Any:
|
||||
"""SQL Server:pymssql(注册表键为 sqlserver,非 mssql);超时=login/timeout(秒)。"""
|
||||
import pymssql
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs.update(login_timeout=timeout, timeout=timeout)
|
||||
return pymssql.connect(
|
||||
server=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
database=database or '',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
# D16 四库驱动注册表;键必须与 models.DB_KINDS 一致(sqlserver 非 mssql)。
|
||||
_DRIVERS: dict[str, DriverSpec] = {
|
||||
'oracle': DriverSpec(connect=_connect_oracle, probe_sql='SELECT 1 FROM DUAL'),
|
||||
'mysql': DriverSpec(connect=_connect_mysql, probe_sql='SELECT 1'),
|
||||
'postgresql': DriverSpec(connect=_connect_postgresql, probe_sql='SELECT 1'),
|
||||
'sqlserver': DriverSpec(connect=_connect_sqlserver, probe_sql='SELECT 1'),
|
||||
}
|
||||
|
||||
|
||||
def _apply_identifiers(sql: str, *, identifiers: list[str], params: dict) -> str:
|
||||
"""对单条 SQL 做 D17 标识符 `{key}` 白名单替换。
|
||||
|
||||
标识符值字面量写入 SQL,不走 :bind。调用方在 execute/executemany 前须用
|
||||
`_strip_identifier_keys` 剔除白名单键,否则 oracledb 等对多余 bind 键报错。
|
||||
|
||||
Args:
|
||||
sql: 原始语句。
|
||||
identifiers: 允许替换的键名白名单。
|
||||
params: 绑定参数(标识符值取自此,不走 :bind)。
|
||||
|
||||
Returns:
|
||||
替换后的 SQL(保证无任何 `{...}` 残留形状)。
|
||||
|
||||
Raises:
|
||||
InputInvalidError: 未声明占位符、缺值、值未过安全正则,或替换后仍残留
|
||||
`{...}` 形状(畸形占位符如 `{schema.}`/`{1abc}` 不匹配替换正则,
|
||||
若不拦截会原样进入 SQL——fail-closed 封堵该静默直通缺口)。
|
||||
"""
|
||||
allowed = set(identifiers or [])
|
||||
|
||||
def _repl(match: re.Match[str]) -> str:
|
||||
key = match.group(1)
|
||||
if key not in allowed:
|
||||
raise InputInvalidError(
|
||||
f'undeclared SQL identifier placeholder: {{{key}}}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
if key not in params:
|
||||
raise InputInvalidError(
|
||||
f'missing identifier value: {key}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
value = str(params[key])
|
||||
if not _IDENTIFIER_RE.match(value):
|
||||
raise InputInvalidError(
|
||||
f'illegal SQL identifier value for {key}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
return value
|
||||
|
||||
result = _PLACEHOLDER_RE.sub(_repl, sql)
|
||||
# 替换完成后断言无残留:任何 `{...}` 形状(含畸形占位符)都视为未消化的模板,
|
||||
# 静默下传会让数据库收到字面 `{...}` 或被利用的畸形标识符。
|
||||
residual = _RESIDUAL_PLACEHOLDER_RE.search(result)
|
||||
if residual:
|
||||
raise InputInvalidError(
|
||||
f'unresolved SQL placeholder after substitution: {residual.group(0)}',
|
||||
details={'placeholder': residual.group(0)},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _strip_identifier_keys(params: dict, identifiers: list[str]) -> dict:
|
||||
"""从 bind 参数字典中剔除 identifiers 白名单键。
|
||||
|
||||
用途:`{schema}` 等已做字面量替换后,不得再作为 :bind 传入驱动。
|
||||
核心逻辑:按白名单集合过滤,返回新 dict(不修改入参)。
|
||||
|
||||
Args:
|
||||
params: 待传给 execute/executemany 的绑定参数。
|
||||
identifiers: `sql.identifiers` 白名单键列表。
|
||||
|
||||
Returns:
|
||||
已剔除标识符键的新字典。
|
||||
"""
|
||||
if not identifiers:
|
||||
return dict(params)
|
||||
drop = set(identifiers)
|
||||
return {k: v for k, v in params.items() if k not in drop}
|
||||
|
||||
|
||||
def _referenced_bind_names(sql: str) -> set[str]:
|
||||
"""提取语句实际引用的 :bind 名(跳过字符串字面量与注释)。
|
||||
|
||||
【为什么】oracledb 不容许多余 bind 键(ORA-01036 unrecognized bind variable);
|
||||
pre/bulk/post/query 共享同一份参数字典,而各语句通常只引用其中一部分——
|
||||
必须按语句真实引用过滤,映射方可只写自己需要的绑定。
|
||||
|
||||
Args:
|
||||
sql: 标识符替换后的最终 SQL 文本。
|
||||
|
||||
Returns:
|
||||
语句中出现的 :name 集合(不含字符串字面量与 `--` / `/* */` 注释内的冒号)。
|
||||
"""
|
||||
names: set[str] = set()
|
||||
in_string = False
|
||||
i = 0
|
||||
n = len(sql)
|
||||
while i < n:
|
||||
ch = sql[i]
|
||||
if in_string:
|
||||
if ch == "'":
|
||||
in_string = False
|
||||
i += 1
|
||||
continue
|
||||
if ch == "'":
|
||||
in_string = True
|
||||
i += 1
|
||||
continue
|
||||
if ch == '-' and sql[i:i + 2] == '--':
|
||||
i = sql.find('\n', i)
|
||||
i = n if i == -1 else i + 1
|
||||
continue
|
||||
if ch == '/' and sql[i:i + 2] == '/*':
|
||||
end = sql.find('*/', i + 2)
|
||||
i = n if end == -1 else end + 2
|
||||
continue
|
||||
if ch == ':':
|
||||
match = _PLACEHOLDER_BIND_RE.match(sql, i)
|
||||
if match:
|
||||
names.add(match.group(1))
|
||||
i = match.end()
|
||||
continue
|
||||
i += 1
|
||||
return names
|
||||
|
||||
|
||||
def _filter_statement_binds(params: dict, sql: str) -> dict:
|
||||
"""按语句引用的 :bind 过滤参数字典(保持原键序,不改入参)。
|
||||
|
||||
Args:
|
||||
params: 待传给 execute/executemany 的绑定参数。
|
||||
sql: 该语句替换标识符后的最终文本。
|
||||
|
||||
Returns:
|
||||
仅含语句实际引用键的新字典。
|
||||
"""
|
||||
allowed = _referenced_bind_names(sql)
|
||||
return {k: v for k, v in params.items() if k in allowed}
|
||||
|
||||
|
||||
def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]:
|
||||
"""将游标结果按 description 列名(别名)转为 dict 列表。"""
|
||||
description = getattr(cursor, 'description', None) or ()
|
||||
columns = [col[0] for col in description]
|
||||
return [dict(zip(columns, row)) for row in (cursor.fetchall() or [])]
|
||||
|
||||
|
||||
class DatabaseTransport:
|
||||
"""数据库 SQL 传输;按 config.db_kind 查 `_DRIVERS`,未知值 fail-closed。"""
|
||||
|
||||
connector_type = 'database'
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""执行 request_spec.sql(execute 单事务 / query 返回 rows)。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(须已拼入 endpoint/db_kind)与 credential。
|
||||
interface: 含 request_spec_json.sql 节点。
|
||||
request: 引擎构造的请求,参数取自 request['params']。
|
||||
|
||||
Returns:
|
||||
成功 dict(execute: status=success;query: 另含 rows),均附带保留键
|
||||
`_wire`(线级事实,由引擎剥离落库,业务侧不得消费);
|
||||
驱动异常时 technical_failed(message 已脱敏,无 `_wire`)。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint/db_kind 或未知库种。
|
||||
InputInvalidError: 标识符白名单/安全正则失败或 sql 规格非法。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
credential = dict(client.get('credential') or {})
|
||||
params = dict(request.get('params') or {})
|
||||
sql_spec = (interface.get('request_spec_json') or {}).get('sql') or {}
|
||||
if not isinstance(sql_spec, dict) or not sql_spec:
|
||||
raise InputInvalidError('request_spec.sql is required for database transport')
|
||||
|
||||
driver = self._resolve_driver(config)
|
||||
identifiers = list(sql_spec.get('identifiers') or [])
|
||||
mode = str(sql_spec.get('mode') or '').strip().lower()
|
||||
|
||||
conn = None
|
||||
try:
|
||||
# [STEP 1] 建连
|
||||
conn = driver.connect(config=config, credential=credential)
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
if mode == 'execute':
|
||||
return self._run_execute(conn, cursor, sql_spec, params, identifiers)
|
||||
if mode == 'query':
|
||||
return self._run_query(cursor, sql_spec, params, identifiers)
|
||||
raise InputInvalidError(
|
||||
f'unsupported sql.mode: {mode!r}',
|
||||
details={'mode': mode},
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
except (TransportNotFrozenError, InputInvalidError):
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except Exception as exc:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'DB_ERROR',
|
||||
'message': mask_secrets(str(exc)[:2000], credential)[:500],
|
||||
}
|
||||
finally:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试:执行各库 probe_sql,成功即 ok(不做业务调用)。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/db_kind)与 credential。
|
||||
|
||||
Returns:
|
||||
{'ok': True/False, 'code': ..., 'message': ...};异常 message 已脱敏。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint/db_kind 或未知库种。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
credential = dict(client.get('credential') or {})
|
||||
driver = self._resolve_driver(config)
|
||||
conn = None
|
||||
try:
|
||||
conn = driver.connect(config=config, credential=credential)
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(driver.probe_sql)
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
return {'ok': True, 'code': 'DB_PROBE_OK', 'message': 'ok'}
|
||||
except TransportNotFrozenError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
return {
|
||||
'ok': False,
|
||||
'code': 'CONNECTION_FAILED',
|
||||
'message': mask_secrets(str(exc)[:500], credential),
|
||||
}
|
||||
finally:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _resolve_driver(self, config: dict) -> DriverSpec:
|
||||
"""校验 endpoint/db_kind 并返回驱动规格;未知库种 fail-closed。"""
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('database endpoint not frozen (missing endpoint)')
|
||||
db_kind = str(config.get('db_kind') or '').strip().lower()
|
||||
if not db_kind:
|
||||
raise TransportNotFrozenError('database db_kind not frozen (missing db_kind)')
|
||||
driver = _DRIVERS.get(db_kind)
|
||||
if driver is None:
|
||||
raise TransportNotFrozenError(f'unknown database db_kind: {db_kind!r}')
|
||||
return driver
|
||||
|
||||
def _run_execute(
|
||||
self,
|
||||
conn: Any,
|
||||
cursor: Any,
|
||||
sql_spec: dict,
|
||||
params: dict,
|
||||
identifiers: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""execute:pre → bulk(executemany) → post,单事务 commit。
|
||||
|
||||
标识符 `{key}` 替换后,bind 参数(含 bulk 行合并)须剔除 identifiers 键。
|
||||
返回 dict 附带保留键 `_wire`:逐语句记录 phase/最终 SQL/实际绑定/行数
|
||||
(bulk 另记 row_count),顶层 rowcount 为各语句之和,供调用日志落库。
|
||||
"""
|
||||
bulk = sql_spec.get('bulk') or {}
|
||||
rows_param = str(bulk.get('rows_param') or '').strip() if bulk else ''
|
||||
# 基础参数不含行列表,避免 pre/post 绑定把整表塞进驱动参数。
|
||||
base_raw = (
|
||||
{k: v for k, v in params.items() if k != rows_param}
|
||||
if rows_param
|
||||
else dict(params)
|
||||
)
|
||||
# [STEP 1.5] 剔除已字面量替换的标识符键,避免 oracledb 多余 bind 键报错
|
||||
base = _strip_identifier_keys(base_raw, identifiers)
|
||||
|
||||
statements: list[dict] = []
|
||||
# [STEP 2] pre 语句(按语句引用过滤后的基础参数)
|
||||
for stmt in list(sql_spec.get('pre') or []):
|
||||
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
|
||||
cursor.execute(sql, _filter_statement_binds(base, sql))
|
||||
statements.append({'phase': 'pre', 'sql': sql,
|
||||
'binds': _filter_statement_binds(base, sql),
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
|
||||
|
||||
# [STEP 3] bulk:行与基础参数合并,行内键覆盖;合并后再剔标识符键
|
||||
if bulk:
|
||||
bulk_sql = _apply_identifiers(
|
||||
str(bulk.get('sql') or ''), identifiers=identifiers, params=params,
|
||||
)
|
||||
raw_rows = params.get(rows_param) if rows_param else None
|
||||
if not isinstance(raw_rows, list):
|
||||
raise InputInvalidError(
|
||||
f'bulk.rows_param must resolve to a list: {rows_param!r}',
|
||||
details={'rows_param': rows_param},
|
||||
)
|
||||
merged_rows = [
|
||||
_strip_identifier_keys({**base_raw, **dict(row or {})}, identifiers)
|
||||
for row in raw_rows
|
||||
]
|
||||
cursor.executemany(
|
||||
bulk_sql,
|
||||
[_filter_statement_binds(row, bulk_sql) for row in merged_rows],
|
||||
)
|
||||
statements.append({'phase': 'bulk', 'sql': bulk_sql,
|
||||
'binds': merged_rows[0] if merged_rows else {},
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0),
|
||||
'row_count': len(merged_rows)})
|
||||
|
||||
# [STEP 4] post 语句
|
||||
for stmt in list(sql_spec.get('post') or []):
|
||||
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
|
||||
cursor.execute(sql, _filter_statement_binds(base, sql))
|
||||
statements.append({'phase': 'post', 'sql': sql,
|
||||
'binds': _filter_statement_binds(base, sql),
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
|
||||
|
||||
conn.commit()
|
||||
return {'status': 'success',
|
||||
'_wire': {'kind': 'database', 'statements': statements,
|
||||
'rowcount': sum(s.get('rowcount', 0) for s in statements)}}
|
||||
|
||||
def _run_query(
|
||||
self,
|
||||
cursor: Any,
|
||||
sql_spec: dict,
|
||||
params: dict,
|
||||
identifiers: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""query:执行 SELECT,按列别名返回 rows,不 commit。
|
||||
|
||||
标识符替换后 bind 参数剔除 identifiers 键。
|
||||
返回 dict 附带保留键 `_wire`:单语句记录 phase=query 与最终 SQL/实际绑定,
|
||||
rows 截断至 _WIRE_TEXT_LIMIT 行作快照,供调用日志落库。
|
||||
"""
|
||||
raw_sql = str(sql_spec.get('sql') or '').strip()
|
||||
if not raw_sql:
|
||||
raise InputInvalidError('query mode requires sql.sql')
|
||||
sql = _apply_identifiers(raw_sql, identifiers=identifiers, params=params)
|
||||
binds = _filter_statement_binds(
|
||||
_strip_identifier_keys(params, identifiers), sql)
|
||||
cursor.execute(sql, binds)
|
||||
rows = _rows_as_dicts(cursor)
|
||||
return {'status': 'success', 'rows': rows,
|
||||
'_wire': {'kind': 'database',
|
||||
'statements': [{'phase': 'query', 'sql': sql, 'binds': binds}],
|
||||
'rows': rows[:_WIRE_TEXT_LIMIT]}}
|
||||
@@ -4,18 +4,27 @@
|
||||
依赖:requests(默认注入),可注入 http_request 供测试替身。
|
||||
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
|
||||
business_failed dict;非 JSON 响应映射为 technical_failed。
|
||||
调用日志:call 各返回分支(JSON 成功/HTTP≥400/NON_JSON)附带保留键 `_wire`
|
||||
(method/url/脱敏请求头/请求体/状态码/脱敏响应体等线级事实),由引擎
|
||||
(Task 4)剥离落库 wire_json,禁止上游业务消费该键。
|
||||
probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Callable
|
||||
|
||||
import requests
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
|
||||
class RestTransport:
|
||||
"""REST 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
|
||||
@@ -26,6 +35,24 @@ class RestTransport:
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""构造 HTTP 请求并返回原始响应 dict;各返回分支附带保留键 `_wire`。
|
||||
|
||||
用途与触发时机:引擎按 connector_type=rest 分发至此完成一次真实调用;
|
||||
`_wire` 记录线级事实(method/url/脱敏请求头/请求体/状态码/脱敏响应体),
|
||||
仅由调用日志引擎剥离落库,业务侧禁止消费。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/timeout_seconds/headers)与 credential。
|
||||
interface: 含 request_spec_json(method/path)。
|
||||
request: 引擎构造的请求(params/body/headers)。
|
||||
|
||||
Returns:
|
||||
JSON 成功 dict / business_failed(HTTP≥400)/ technical_failed(NON_JSON),
|
||||
各分支均附 `_wire`(JSON 解析结果非 dict 时无法附加键,按原样返回)。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint(fail-closed)。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
@@ -46,17 +73,55 @@ class RestTransport:
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
http_status = int(getattr(response, 'status_code', 0))
|
||||
response_text = str(getattr(response, 'text', '') or '')
|
||||
request_body = json.dumps(request.get('body'), ensure_ascii=False, default=str) \
|
||||
if request.get('body') is not None else ''
|
||||
wire = {'kind': 'rest', 'method': method, 'url': url,
|
||||
'headers': mask_secrets(json.dumps(headers, ensure_ascii=False, default=str),
|
||||
client.get('credential')),
|
||||
'request_body': request_body,
|
||||
'http_status': http_status,
|
||||
'response_body': mask_secrets(response_text, client.get('credential'))[:_WIRE_TEXT_LIMIT]}
|
||||
if http_status >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
'message': str(getattr(response, 'text', ''))[:500],
|
||||
'code': f"HTTP_{http_status}",
|
||||
# 错误回显可能包含请求内容(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
try:
|
||||
return response.json()
|
||||
parsed = response.json()
|
||||
except Exception:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_JSON',
|
||||
'message': str(getattr(response, 'text', ''))[:500],
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
# JSON 解析结果为 dict 时附 `_wire`;list/标量无法携带键,按原样返回。
|
||||
if isinstance(parsed, dict):
|
||||
parsed['_wire'] = wire
|
||||
return parsed
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。
|
||||
|
||||
与 call 的区别:不要求接口契约(method/path),不做业务语义解析;
|
||||
连接建立失败(DNS/超时/拒绝)才算不通。异常回显先脱敏再截断。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
|
||||
timeout = int(config.get('timeout_seconds') or 60)
|
||||
try:
|
||||
response = self._http_request('GET', endpoint, timeout=timeout)
|
||||
except Exception as exc:
|
||||
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
|
||||
return {
|
||||
'ok': True,
|
||||
'code': f"HTTP_{int(getattr(response, 'status_code', 0))}",
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:200], client.get('credential'))[:200],
|
||||
}
|
||||
@@ -1,29 +1,246 @@
|
||||
"""services/integration_connector/transports/soap.py
|
||||
|
||||
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。
|
||||
依赖:zeep(延时导入);errors.py。
|
||||
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。
|
||||
用途:SOAP Transport——按接口消息配置(soap.body_template)生成报文并解析 XML 响应。
|
||||
依赖:requests(默认注入)、xml.etree.ElementTree、errors.py。
|
||||
逻辑:endpoint 或 body_template 缺失 → fail-closed(TransportNotFrozenError);
|
||||
模板占位符从请求参数 + 凭据(credential_* 保留前缀)填充,缺参即失败;
|
||||
响应按 localname 解析(不绑命名空间前缀),Body 首子节点为业务根,
|
||||
叶节点文本本身是合法 XML 时递归展开(内嵌转义报文的通用规则);
|
||||
标准 SOAP 1.1 Fault(faultcode/faultstring)→ business_failed(SOAP 1.2 的
|
||||
Code/Reason 结构暂只归 business_failed 不提取消息);HTTP ≥400 → business_failed;
|
||||
非 XML → technical_failed。
|
||||
probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通);
|
||||
裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。
|
||||
调用日志:call 各返回分支(成功/HTTP≥400/NON_XML)附带保留键 `_wire`
|
||||
(method/url/soap_action/脱敏请求体/状态码/脱敏响应体等线级事实),
|
||||
由引擎(Task 4)剥离落库 wire_json,禁止上游业务消费该键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import string
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
import requests
|
||||
|
||||
from app.services.integration_connector.errors import (
|
||||
InputInvalidError,
|
||||
TransportNotFrozenError,
|
||||
)
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。
|
||||
MAX_EMBED_DEPTH = 3
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
|
||||
def _localname(tag: Any) -> str:
|
||||
"""去掉命名空间 URI,只取元素/属性的本地名(厂商前缀差异不影响映射路径)。"""
|
||||
return tag.rsplit('}', 1)[-1] if isinstance(tag, str) else ''
|
||||
|
||||
|
||||
def fill_soap_template(template: str, params: dict, credential: dict) -> str:
|
||||
"""填充 SOAP 报文模板:{param} 来自请求参数,{credential_*} 来自凭据注入。
|
||||
|
||||
Args:
|
||||
template: 接口配置里的完整报文模板(str.format 语义,{{}} 为字面大括号)。
|
||||
params: 引擎映射后的接口参数。
|
||||
credential: resolve_credential 解析出的凭据字典,按 credential_ 前缀注入。
|
||||
Raises:
|
||||
InputInvalidError: 占位符无对应值(fail-closed,绝不静默出空串)。
|
||||
"""
|
||||
merged: dict[str, Any] = dict(params or {})
|
||||
# 凭据后注入并覆盖同名占位符:请求参数不得冒充/覆盖 credential_* 值。
|
||||
for key, value in (credential or {}).items():
|
||||
merged[f'credential_{key}'] = value
|
||||
missing = sorted({
|
||||
field for _, field, _, _ in string.Formatter().parse(template)
|
||||
if field and field not in merged
|
||||
})
|
||||
if missing:
|
||||
raise InputInvalidError(details={'reason': 'soap_template_param_missing', 'params': missing})
|
||||
for key, value in merged.items():
|
||||
# CDATA 内出现 ]]> 会截断报文;模板骨架自身的 CDATA 结束符不受影响,仅查替换值。
|
||||
if ']]>' in str(value):
|
||||
raise InputInvalidError(details={'reason': 'soap_cdata_terminator_in_params', 'param': key})
|
||||
try:
|
||||
return template.format(**merged)
|
||||
except (KeyError, IndexError, ValueError) as exc:
|
||||
# 覆盖裸 {} / 格式规格非法等 str.format 原生异常,统一 fail-closed 语义。
|
||||
raise InputInvalidError(details={'reason': 'soap_template_invalid'}) from exc
|
||||
|
||||
|
||||
def _element_to_value(elem: ET.Element, embed_depth: int) -> Any:
|
||||
"""把元素转为通用 dict:属性 → @key;重复同名子元素 → list;叶子文本为值。
|
||||
|
||||
叶子文本本身是合法 XML(网关型系统常见的转义内嵌报文)时递归解析并保留内层根标签。
|
||||
"""
|
||||
attrs = {f'@{_localname(key)}': value for key, value in elem.attrib.items()}
|
||||
children = list(elem)
|
||||
text = (elem.text or '').strip()
|
||||
if children:
|
||||
node: dict[str, Any] = dict(attrs)
|
||||
grouped: dict[str, list[Any]] = {}
|
||||
for child in children:
|
||||
name = _localname(child.tag)
|
||||
grouped.setdefault(name, []).append(_element_to_value(child, embed_depth))
|
||||
for name, items in grouped.items():
|
||||
node[name] = items[0] if len(items) == 1 else items
|
||||
if text:
|
||||
node['#text'] = text
|
||||
return node
|
||||
if text.startswith('<') and embed_depth > 0:
|
||||
try:
|
||||
inner = ET.fromstring(text)
|
||||
except ET.ParseError:
|
||||
inner = None
|
||||
if inner is not None:
|
||||
return {_localname(inner.tag): _element_to_value(inner, embed_depth - 1)}
|
||||
if not attrs:
|
||||
return text or None
|
||||
if text:
|
||||
return {**attrs, '#text': text}
|
||||
return attrs
|
||||
|
||||
|
||||
def _parse_soap_payload(text: str) -> dict[str, Any]:
|
||||
"""解析 SOAP 信封:取 Body 首子元素为业务根并转 dict;检测标准 Fault。"""
|
||||
root = ET.fromstring(text)
|
||||
body = None
|
||||
for node in root.iter():
|
||||
if _localname(node.tag) == 'Body':
|
||||
body = node
|
||||
break
|
||||
payload = list(body)[0] if body is not None and len(body) else root
|
||||
for node in payload.iter():
|
||||
if _localname(node.tag) == 'Fault':
|
||||
code = message = ''
|
||||
for child in node.iter():
|
||||
name = _localname(child.tag)
|
||||
if name == 'faultcode' and not code:
|
||||
code = (child.text or '').strip()
|
||||
if name == 'faultstring' and not message:
|
||||
message = (child.text or '').strip()
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': code or 'SOAP_FAULT',
|
||||
'message': message,
|
||||
}
|
||||
return {_localname(payload.tag): _element_to_value(payload, MAX_EMBED_DEPTH)}
|
||||
|
||||
|
||||
class SoapTransport:
|
||||
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。"""
|
||||
"""SOAP 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
|
||||
|
||||
connector_type = 'soap'
|
||||
|
||||
def __init__(self, http_request: HttpRequest | None = None):
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""按契约生成 SOAP 报文并解析响应;各返回分支附带保留键 `_wire`。
|
||||
|
||||
用途与触发时机:引擎按 connector_type=soap 分发至此完成一次真实调用;
|
||||
`_wire` 记录线级事实(method/url/soap_action/脱敏请求体/状态码/脱敏响应体),
|
||||
仅由调用日志引擎剥离落库,业务侧禁止消费。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/timeout_seconds)与 credential。
|
||||
interface: 含 request_spec_json(method + soap.action/body_template)。
|
||||
request: 引擎构造的请求,参数取自 request['params']。
|
||||
|
||||
Returns:
|
||||
解析后的业务 dict / business_failed(HTTP≥400、SOAP Fault)/
|
||||
technical_failed(NON_XML),各分支均附 `_wire`。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint 或 soap.body_template(fail-closed)。
|
||||
InputInvalidError: 模板占位符缺值/非法(fail-closed)。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
|
||||
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
|
||||
wsdl = str(config.get('endpoint') or '').strip()
|
||||
if not wsdl:
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
|
||||
|
||||
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
|
||||
raise NotImplementedError('SOAP implementation pending frozen WSDL')
|
||||
spec = interface.get('request_spec_json') or {}
|
||||
soap_spec = spec.get('soap') or {}
|
||||
template = str(soap_spec.get('body_template') or '').strip()
|
||||
if not template:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing soap.body_template)')
|
||||
|
||||
body = fill_soap_template(template, request.get('params') or {}, client.get('credential') or {})
|
||||
headers = {'Content-Type': 'text/xml; charset=utf-8'}
|
||||
action = str(soap_spec.get('action') or '').strip()
|
||||
# SOAPAction 头必须存在且按规范带引号(空契约即 '""'):不带引号或缺失
|
||||
# 会被鼎捷网关以 415 拒绝(2026-09-22 实测)。
|
||||
headers['SOAPAction'] = f'"{action}"'
|
||||
method = str(spec.get('method') or 'POST').upper()
|
||||
path = str(spec.get('path') or '').strip()
|
||||
url = endpoint.rstrip('/') + '/' + path.lstrip('/') if path else endpoint
|
||||
|
||||
response = self._http_request(
|
||||
method,
|
||||
url,
|
||||
data=body.encode('utf-8'),
|
||||
headers=headers,
|
||||
timeout=int(config.get('timeout_seconds') or 60),
|
||||
)
|
||||
http_status = int(getattr(response, 'status_code', 0))
|
||||
# 响应文本与请求体在进入任何分支前先脱敏:错误回显/成功报文都可能含凭据。
|
||||
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
|
||||
wire = {'kind': 'soap', 'method': method, 'url': url,
|
||||
'soap_action': headers['SOAPAction'],
|
||||
'request_body': mask_secrets(body, client.get('credential')),
|
||||
'http_status': http_status,
|
||||
'response_body': response_text[:_WIRE_TEXT_LIMIT]}
|
||||
if http_status >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{http_status}",
|
||||
# 错误回显可能包含请求体(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
try:
|
||||
parsed = _parse_soap_payload(response_text)
|
||||
except ET.ParseError:
|
||||
return {'status': 'technical_failed', 'code': 'NON_XML',
|
||||
'message': response_text[:500], '_wire': wire}
|
||||
parsed['_wire'] = wire
|
||||
return parsed
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。
|
||||
|
||||
与 call 的区别:不要求 soap.body_template 契约;根元素为 definitions
|
||||
(WSDL 地址约定)或 Envelope(直连服务端点约定)任一即算通过。
|
||||
裸服务端点对 GET 常返回 404/405/501(SOAP 只实现 POST),故未带 query
|
||||
时自动补 ?wsdl 取服务描述;已带 query(如 ?wsdl)则按原地址探测。
|
||||
连接失败 / HTTP ≥400 / 非 XML / 根元素不符 → ok=False;错误回显先脱敏。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
|
||||
timeout = int(config.get('timeout_seconds') or 60)
|
||||
probe_url = endpoint if '?' in endpoint else f'{endpoint}?wsdl'
|
||||
try:
|
||||
response = self._http_request('GET', probe_url, timeout=timeout)
|
||||
except Exception as exc:
|
||||
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
|
||||
status = int(getattr(response, 'status_code', 0))
|
||||
text = mask_secrets(str(getattr(response, 'text', '') or '')[:500], client.get('credential'))
|
||||
if status >= 400:
|
||||
return {'ok': False, 'code': f'HTTP_{status}', 'message': text}
|
||||
try:
|
||||
root = ET.fromstring(str(getattr(response, 'text', '') or ''))
|
||||
except ET.ParseError:
|
||||
return {'ok': False, 'code': 'NON_XML', 'message': text}
|
||||
root_name = _localname(root.tag)
|
||||
if root_name not in ('definitions', 'Envelope'):
|
||||
return {'ok': False, 'code': 'NOT_WSDL', 'message': f'unexpected root <{root_name}>'}
|
||||
return {'ok': True, 'code': f'HTTP_{status}', 'message': f'wsdl root <{root_name}>'}
|
||||
@@ -28,6 +28,7 @@ from app.services.lean_training_service import (
|
||||
_already_pushed_resource_ids,
|
||||
_config_video_resource_ids,
|
||||
_current_week_bounds,
|
||||
format_beijing_iso,
|
||||
target_user_ids_for_task,
|
||||
)
|
||||
from app.services.schedule.timezone_util import utc_now_naive
|
||||
@@ -132,7 +133,8 @@ def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
|
||||
"status": log.status,
|
||||
"error_message": log.error_message,
|
||||
"created_by_id": log.created_by_id,
|
||||
"created_at": log.created_at.isoformat() if log.created_at else None,
|
||||
# 展示层转北京时间:管理端"推送记录"直接渲染该字段,UTC 直出会比实际早 8 小时
|
||||
"created_at": format_beijing_iso(log.created_at),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -69,6 +69,55 @@ def _format_dashboard_datetime(value: str | None) -> str:
|
||||
return text[:16].replace("T", " ") if text else ""
|
||||
|
||||
|
||||
def format_beijing_iso(value: datetime | str | None) -> str | None:
|
||||
"""
|
||||
将存储的 UTC 时间转换为北京时间 ISO 字符串,供页面/Excel 展示。
|
||||
|
||||
用途:培训模块数据库统一存 UTC naive(观看/完成/截止时间),而业务要求所有对外展示为北京时间;
|
||||
此前序列化直接输出 UTC 导致页面显示比实际早 8 小时(如 18:47 显示 10:47)。
|
||||
Args:
|
||||
value: UTC naive datetime 或 ISO 字符串;naive 按 UTC 处理,带时区则先归一到绝对时间;
|
||||
字符串无法解析时原样返回,避免历史脏数据导致展示层报错。
|
||||
Returns:
|
||||
带 +08:00 偏移的 ISO 字符串(如 2026-09-22T18:47:00+08:00,前端 slice(0,16) 即得北京时间);入参为空返回 None。
|
||||
业务约束:仅用于序列化输出层,禁止将转换结果写回数据库——存储与服务端比较(超期判定等)仍一律 UTC。
|
||||
"""
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.strip())
|
||||
except ValueError:
|
||||
return value.strip()
|
||||
else:
|
||||
parsed = value
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
return parsed.astimezone(resolve_schedule_tzinfo("Asia/Shanghai")).isoformat()
|
||||
|
||||
|
||||
def parse_client_iso_to_utc_text(text: str) -> str:
|
||||
"""
|
||||
将客户端回显的观看时间 ISO 字符串归一为 UTC naive ISO 文本,供存储。
|
||||
|
||||
用途:save_completion 会合并客户端提交的 watched_at 兜底值(服务端记录缺失时入库);
|
||||
客户端时间格式随版本演进(UTC 带 Z / 北京时间带 +08:00),必须归一为 UTC,
|
||||
否则 watched_at_json 混入非 UTC 值会破坏"存储一律 UTC"的约定,后续服务端比较将出错。
|
||||
Args:
|
||||
text: 客户端提交的 ISO 时间字符串。
|
||||
Returns:
|
||||
UTC naive ISO 文本;无法解析时原样返回(与历史行为一致,不因脏数据阻塞提交)。
|
||||
"""
|
||||
try:
|
||||
parsed = datetime.fromisoformat(str(text))
|
||||
except ValueError:
|
||||
return str(text)
|
||||
if parsed.tzinfo is None:
|
||||
# naive 视为北京时间墙钟(新版客户端口径),入库前转 UTC
|
||||
parsed = parsed.replace(tzinfo=resolve_schedule_tzinfo("Asia/Shanghai"))
|
||||
return to_utc_naive(parsed).isoformat()
|
||||
|
||||
|
||||
def _dashboard_status_label(status: str | None) -> str:
|
||||
"""将看板状态转换为页面一致的中文文案。"""
|
||||
return {
|
||||
@@ -244,7 +293,8 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
|
||||
"week_key": task.week_key,
|
||||
"week_end": (week_start + timedelta(days=6)).isoformat() if week_start else None,
|
||||
"week_index": week_index_for_task(task),
|
||||
"due_at": task.due_at.isoformat(),
|
||||
# 展示层转北京时间:管理端编辑器/看板头与学员端均直接渲染该字段,UTC 直出会比实际早 8 小时
|
||||
"due_at": format_beijing_iso(task.due_at),
|
||||
"video_resource_ids": visible_ids,
|
||||
"target_roles": list(task.target_roles or []),
|
||||
"target_user_ids": list(task.target_user_ids or []),
|
||||
@@ -414,8 +464,9 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
||||
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
|
||||
item["completion"] = {
|
||||
"summary_text": completion.summary_text,
|
||||
"watched_at": dict(completion.watched_at_json or {}),
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
# 展示层转北京时间:学员端"已观看"直接渲染该字典值,存储仍为 UTC
|
||||
"watched_at": {key: format_beijing_iso(value) for key, value in (completion.watched_at_json or {}).items()},
|
||||
"completed_at": format_beijing_iso(completion.completed_at),
|
||||
} if completion else None
|
||||
items.append(item)
|
||||
return items
|
||||
@@ -451,7 +502,8 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
# 观看草稿:保持 completed_at 为空,任务仍为进行中/已延期,直至感悟提交完成
|
||||
db.session.add(completion)
|
||||
db.session.commit()
|
||||
return {"watched_at": watched}
|
||||
# 返回值供学员端即时回显"已观看时间",展示层转北京时间;数据库中保持 UTC
|
||||
return {"watched_at": {key: format_beijing_iso(value) for key, value in watched.items()}}
|
||||
|
||||
|
||||
def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -465,7 +517,8 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
||||
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
|
||||
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
|
||||
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
||||
watched = {str(key): str(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
|
||||
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||
completion = db.session.execute(
|
||||
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
||||
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
|
||||
@@ -501,7 +554,7 @@ def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompl
|
||||
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
|
||||
visible_ids = task.video_resource_ids[: task.pushed_video_count]
|
||||
return [
|
||||
{"name": titles.get(resource_id, ""), "watched_at": watched.get(str(resource_id))}
|
||||
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
|
||||
for resource_id in visible_ids
|
||||
]
|
||||
|
||||
@@ -522,7 +575,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
|
||||
"videos": _task_video_rows(task, completion),
|
||||
"summary_text": completion.summary_text,
|
||||
"status": status,
|
||||
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
||||
"completed_at": format_beijing_iso(completion.completed_at),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -71,8 +71,16 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary
|
||||
deliver_schedule_receipt_summary(run.id)
|
||||
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。
|
||||
try:
|
||||
task = run.task
|
||||
if task is not None and task.notify_enabled:
|
||||
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
|
||||
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
db.session.commit()
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc)
|
||||
return {'finalized': True, 'status': run.status}
|
||||
|
||||
|
||||
|
||||
@@ -32,7 +32,10 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportConfig, warehouse_id: str | None) -> ShippingReceiptRpaUnitRun:
|
||||
def _build_unit(
|
||||
source: ShippingInventorySource, config: ShippingReceiptReportConfig,
|
||||
warehouse_id: str | None, schedule_run_id: int,
|
||||
) -> ShippingReceiptRpaUnitRun:
|
||||
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
snapshot = {
|
||||
@@ -41,7 +44,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, inventory_source_id=source.id, source_code=source.source_code,
|
||||
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
|
||||
status='awaiting_rpa', config_snapshot_json=snapshot,
|
||||
)
|
||||
@@ -81,9 +84,7 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
|
||||
unit.schedule_run_id = run.id
|
||||
units.append(unit)
|
||||
units.append(_build_unit(source, config, str(warehouse_id) if warehouse_id else None, run.id))
|
||||
if not units:
|
||||
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
|
||||
db.session.add_all(units)
|
||||
|
||||
@@ -18,11 +18,12 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header
|
||||
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
|
||||
from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
is_awaiting_rpa_schedule_run,
|
||||
@@ -118,6 +119,36 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
|
||||
return params
|
||||
|
||||
|
||||
def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]:
|
||||
"""
|
||||
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
|
||||
|
||||
核心逻辑:库存与收料 RPA 共用同一企微通知出口(_notify_schedule_run_wecom),
|
||||
本函数是收料侧的唯一分叉点——按 platform_api_path 识别收料排程,返回该 run
|
||||
全部单元已归档且未被清理(archive_deleted_at 为空)的报表文件。
|
||||
"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
task = run.task
|
||||
if (
|
||||
task is None
|
||||
or task.schedule_type != 'platform_job'
|
||||
or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY
|
||||
):
|
||||
return []
|
||||
return (
|
||||
ShippingReceiptReportFile.query.join(
|
||||
ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
"""
|
||||
组装排程完成企微 textcard 正文。
|
||||
@@ -140,6 +171,9 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
|
||||
if inventory_raw_zip_available_from_summary(summary):
|
||||
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
|
||||
receipt_files = _receipt_report_files_for_run(run)
|
||||
if receipt_files:
|
||||
description += f'\n收料报表文件 {len(receipt_files)} 份:已随本通知发送'
|
||||
return description
|
||||
|
||||
|
||||
@@ -148,6 +182,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
排程完成后的通用企微通知。
|
||||
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
|
||||
则跳过以免与领域缺件/失败告警重复。
|
||||
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
|
||||
收料附加该 run 全部单元的收料报表文件(见 _receipt_report_files_for_run)。
|
||||
"""
|
||||
from app.services.integrations.wecom.notify import (
|
||||
upload_wecom_temp_media,
|
||||
@@ -208,6 +244,21 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
receipt_media: list[tuple[str, str]] = []
|
||||
for receipt_file in _receipt_report_files_for_run(run):
|
||||
try:
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
receipt_media_id = upload_wecom_temp_media(
|
||||
file_asset_storage.get_bytes(receipt_file.storage_key), receipt_file.original_filename,
|
||||
)
|
||||
receipt_media.append((receipt_media_id, receipt_file.original_filename))
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
'[wecom-schedule] receipt file media upload failed for run %s file %s: %s',
|
||||
run.run_no, receipt_file.id, exc,
|
||||
)
|
||||
|
||||
textcard_ok_count = 0
|
||||
errors = []
|
||||
|
||||
@@ -263,6 +314,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
|
||||
|
||||
for receipt_media_id, receipt_filename in receipt_media:
|
||||
try:
|
||||
receipt_audit = _create_audit(
|
||||
f'{_WECOM_EVENT_TYPE}_receipt_file', u,
|
||||
title, f'[收料报表] {receipt_filename}', uuid.uuid4().hex,
|
||||
)
|
||||
receipt_data = send_wecom_file_message(u.wecom_userid, receipt_media_id)
|
||||
if receipt_data.get('errcode') == 0:
|
||||
receipt_audit.status = 'sent'
|
||||
else:
|
||||
receipt_audit.error_code = str(receipt_data.get('errcode'))
|
||||
receipt_audit.error_message = str(receipt_data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: receipt file errcode={receipt_data.get("errcode")}')
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: receipt file exception={exc}')
|
||||
|
||||
if textcard_ok_count > 0:
|
||||
run.wecom_notified = True
|
||||
run.wecom_notified_at = datetime.utcnow()
|
||||
|
||||
@@ -4,7 +4,8 @@ services/shipping_notice/attachment_selection.py
|
||||
用途:基于 Intake 快览事实生成可审计的附件选择计划。
|
||||
依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
|
||||
所有预算内附件先物化为同一 Run 的 Unit,Worker 再按并发预算执行,避免把排队误建模为扩批。
|
||||
合格业务附件全量入选批次 1(有多少单解析多少单),仅字节预算超限转 Review;
|
||||
数量类预算字段仅作快照记录,不再截断,扩批链路不再产出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -150,10 +151,11 @@ def build_attachment_selection_snapshot(
|
||||
|
||||
Args:
|
||||
intakes: 当前发送批次的 Intake;必须已经通过上传快览。
|
||||
max_initial_attachments: 兼容旧快照的首轮附件字段;新计划不以它限制 Unit 创建。
|
||||
max_initial_attachments: 历史兼容字段,仅写入快照作审计记录,不参与选择。
|
||||
max_initial_concurrency: Worker 最大并发,仅限制执行,不限制 Unit 创建。
|
||||
expansion_batch_size: 后续每轮扩展的附件上限。
|
||||
max_total_attachments: 单次邮件深度解析总附件预算上限。
|
||||
expansion_batch_size: 历史兼容字段,仅写入快照作审计记录,不参与选择。
|
||||
max_total_attachments: 历史兼容字段,仅写入快照作审计记录,不再按数量截断。
|
||||
max_total_bytes: 唯一生效的选择预算;累计超限的附件以 budget_total_bytes 转 Review。
|
||||
|
||||
Returns:
|
||||
可写入 Run 快照的脱敏计划摘要,包含每个附件的 selected / skipped 结论与原因码。
|
||||
@@ -227,19 +229,16 @@ def build_attachment_selection_snapshot(
|
||||
eligible_ordered = sorted(eligible, key=lambda item: (-int(item['score']), str(item['filename'])))
|
||||
byte_budget = max(0, int(max_total_bytes or 0))
|
||||
planned_bytes = 0
|
||||
for index, row in enumerate(eligible_ordered):
|
||||
for row in eligible_ordered:
|
||||
size = int(row.get('size') or 0)
|
||||
if byte_budget and planned_bytes + size > byte_budget:
|
||||
row['skip_reason_codes'] = ['budget_total_bytes']
|
||||
continue
|
||||
# [STEP 1] 同一发送批次内的预算内附件必须全部创建 Unit。执行并发由
|
||||
# max_initial_concurrency 在物化/Worker 层控制,不能借“首轮选择”延迟附件身份。
|
||||
if index < max_total_attachments:
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = 1
|
||||
planned_bytes += size
|
||||
continue
|
||||
row['skip_reason_codes'] = ['budget_total_limit']
|
||||
# [STEP 1] 合格业务附件全量入选,不设数量截断:有多少单解析多少单。
|
||||
# 执行节奏由 max_initial_concurrency 与 Worker 运行时预算控制,扩批链路不再产出。
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = 1
|
||||
planned_bytes += size
|
||||
|
||||
group_counts: dict[str, int] = defaultdict(int)
|
||||
for row in rows:
|
||||
|
||||
Loaded 100 of 336 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user