Merge branch 'hugo-shipping-notice' into test

This commit is contained in:
hugo committed 2026-09-24 17:06:33 +08:00
commit 387b3157fe
113 files changed
+6036 -1759

No files matched your search

+114 -49
View File
@@ -1,9 +1,9 @@
"""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})。
Phase 1 提供匹配创建(POST /matchings)与进度恢复(GET /matchings/{id})。
"""
from __future__ import annotations
@@ -22,13 +22,21 @@ 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,
execute_items,
get_run,
serialize_run_result,
)
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 requery_items as retry_service_requery_items, retry_item
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.serializers import (
serialize_item,
serialize_source,
@@ -69,15 +77,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():
"""创建或复用一次调拨预检(只读,不写 外部系统)。
def create_matching_api():
"""创建或复用一次调拨匹配(只读,不写 外部系统)。
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
"receipt_date_from"/"receipt_date_to"(可选),
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。
"""
body = request.get_json(silent=True) or {}
if not isinstance(body, dict):
@@ -87,7 +95,7 @@ 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,
@@ -98,11 +106,18 @@ def create_precheck_api():
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"]],
@@ -110,41 +125,16 @@ 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 状态 / 外部系统 单号聚合结果。
"""
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")
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_precheck(
precheck_id=precheck_id,
deps=deps,
selected_invoice_nos=invoice_nos,
)
return _ok({
"run_no": outcome.run_no,
"status": outcome.status,
"result": serialize_run_result(outcome.result),
}, status=201)
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
@require_transfer_permission
def requery_items_api(precheck_no: str):
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.get("invoice_nos"), list) else None
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_service_requery_items(
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
matching_no=matching_no, deps=deps, invoice_nos=invoice_nos,
actor_id=str(user.id) if user.id else None,
))
@@ -180,7 +170,7 @@ def download_source_receipt_files_api():
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径,
# 单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
)
@@ -255,6 +245,73 @@ 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():
"""按行执行调拨(三层门禁:①存在且可执行 ②行级新鲜度 ③文件版本对账)。
请求体:{"item_ids": [int]}(匹配卡/待执行池勾选的真实明细行 id)。
响应:200 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果;
门禁失败 400,error.details 携带对应 id 列表
(invalid_item_ids / stale_item_ids / changed_item_ids)。
"""
user = _require_user()
body = request.get_json(silent=True) or {}
item_ids = _require_item_ids(body)
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_items(
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,
"result": serialize_run_result(outcome.result),
})
@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):
@@ -301,8 +358,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:
@@ -347,7 +404,7 @@ def receipt_files_api(run_no: str):
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
@require_transfer_permission
def erp_inventory_api(run_no: str):
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
"""下载本次匹配冻结的 外部系统 库存表(csv);记录访问审计。"""
import io
from app import db
@@ -403,7 +460,7 @@ def transfer_sources_api():
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
"""
from app.models import ShippingInventorySource
@@ -502,7 +559,7 @@ def backlog_summary_api():
def _serialize_backlog_item(item) -> dict[str, Any]:
"""待处理池项序列化。"""
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
return {
'item_id': item.item_id,
'source_code': item.source_code,
@@ -513,4 +570,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 -1
View File
@@ -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,
@@ -0,0 +1,56 @@
"""backend/app/jobs/handlers/in_transit_transfer_match.py
用途:异步执行在途调拨匹配(文件准备 + 只读匹配),并更新匹配状态。
依赖:Job 注册表、matching_service、transfer 模型、transfer deps。
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
状态/计数/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 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}")
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()
@@ -1,56 +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()
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
source_codes = list(scope.get("source_codes") or [])
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",
# 类型范围随预检落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
)
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_external_write_count = summary.estimated_external_write_count
precheck.precheck_hash = summary.precheck_hash
db.session.commit()
@@ -1,8 +1,9 @@
"""backend/app/jobs/handlers/in_transit_transfer_run.py
用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。
用途:Run 级执行 Job:按匹配 scope 圈定 ready 行并驱动按行执行服务完成写入。
依赖:execution_service、transfer deps、Job 注册表。
逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。
逻辑:payload 携带 matching_id(仅用于 scope 圈行);三层门禁由 execute_items
统一裁定,门禁失败即入队路径失败(fail-closed)。
"""
from __future__ import annotations
@@ -10,20 +11,20 @@ from __future__ import annotations
from app.jobs.registry import register_handler
from app.jobs.types import JobType
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_matching_items
@register_handler(JobType.TRANSFER_RUN)
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
"""执行一个 Run(异步路径)。
"""执行匹配 scope 内全部可执行行(异步路径)。
【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。
"""
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,
matching_id = str(payload.get("matching_id") or "").strip()
if not matching_id:
raise RuntimeError("missing_transfer_matching_id")
execute_matching_items(
matching_id=matching_id,
deps=transfer_deps.get_transfer_dependencies(),
)
@@ -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 -3
View File
@@ -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',
}),
}
+2 -2
View File
@@ -205,7 +205,7 @@ from app.models.in_transit_transfer import (
TransferAttempt,
TransferAuditEvent,
TransferInvoiceItem,
TransferPrecheck,
TransferMatching,
TransferRun,
TransferSourceJob,
)
@@ -425,7 +425,7 @@ __all__ = [
'ContractPaymentSyncState',
'TransferRun',
'TransferSourceJob',
'TransferPrecheck',
'TransferMatching',
'TransferInvoiceItem',
'TransferAttempt',
'TransferAuditEvent',
+31 -31
View File
@@ -1,9 +1,9 @@
"""models/in_transit_transfer.py
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
Attempt、AuditEvent 与 Archive。
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单;
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
"""
@@ -33,12 +33,12 @@ 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 保持一致的冻结枚举
@@ -48,13 +48,13 @@ TRANSFER_RUN_TYPES = (
)
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', 'external_query', 'external_write')
TRANSFER_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
TRANSFER_ATTEMPT_STATUSES = (
'queued', 'running', 'waiting_external', 'success', 'failed',
'result_unknown', 'superseded',
@@ -63,7 +63,7 @@ TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'sched
class TransferRun(Base):
"""一次调拨执行(或只读预检)的业务真相源。"""
"""一次调拨执行(或只读匹配)的业务真相源。"""
__tablename__ = 'transfer_runs'
__table_args__ = (
@@ -91,7 +91,7 @@ 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仓间调拨);决定预检收料数据范围。
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。
transfer_type: Mapped[str] = mapped_column(
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
)
@@ -116,14 +116,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__ = (
@@ -155,25 +155,25 @@ 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)
@@ -181,7 +181,7 @@ class TransferPrecheck(Base):
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_external_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)
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)
@@ -190,14 +190,14 @@ 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 业务口径):同一批号跨料号/跨日期拆分为多行。
"""
@@ -205,8 +205,8 @@ class TransferInvoiceItem(Base):
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint(
'precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
name='uq_transfer_invoice_items_precheck_grain',
'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)})",
@@ -218,7 +218,7 @@ class TransferInvoiceItem(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True)
matching_id: Mapped[int] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=False, 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)
@@ -248,7 +248,7 @@ 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',
@@ -314,7 +314,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)
@@ -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:
@@ -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/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
"""
@@ -109,7 +109,7 @@ def archive_snapshot(
Args:
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
object_id: 业务对象编号(precheck_no / run_no)。
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,8 +1,8 @@
"""在途调拨自动排程编排(09:00 自动调拨)。
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
用途:组合"每日恢复 → 自动匹配 → 自动执行 → 企微汇总通知",
供 in-transit-transfer platform job 调用。
依赖:recovery_service、precheck_service、execution_service、notification。
依赖:recovery_service、matching_service、execution_service、notification。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
"""
@@ -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,15 @@ 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
# (三层门禁:可执行/行级新鲜度/文件版本对账);无可执行行时门禁抛错,
# 与旧流程一致记入 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
@@ -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,15 +33,15 @@ 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 触发;
【AI 触发时机】:用户表达"查询今天可调拨 / 匹配"等意图后由候选 Action 触发;
只读,不写 外部系统。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
@@ -49,17 +49,17 @@ class TransferPrecheckAction:
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)},
)
@@ -72,18 +72,20 @@ class TransferExecuteAction:
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行勾选范围并输出 transfer-result 卡片。
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
后台确定性服务完成写前复查与 外部系统 原子写入。
【AI 触发时机】:用户在匹配卡点击"直接生成调拨单"后触发;
后台按匹配 scope 圈定 ready 行(invoice_nos 过滤)后按行执行,
三层门禁(可执行/行级新鲜度/文件版本对账)与写前复查、
外部系统 原子写入由确定性服务完成。
"""
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)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
外部系统 写并发恒为 1,同匹配只允许一个执行 Run(由 orchestrator 门禁兜底)。
依赖:无(纯常量)。
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
"""
@@ -15,11 +15,11 @@ SOURCE_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, "External write concurrency must stay 1 for the same precheck"
assert run_count <= 1, "External write concurrency must stay 1 for the same matching"
@@ -1,6 +1,6 @@
"""在途调拨 DTO 与稳定错误码契约。
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
用途:冻结前后端契约(匹配摘要、明细项、外部系统 单据聚合结果)与一期错误码,
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
依赖:标准库 dataclasses / decimal。
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
@@ -21,7 +21,7 @@ TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
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"
@@ -38,7 +38,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_INVOICE_CONFLICT,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_MATCH_EXPIRED,
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_DUPLICATE_NOT_VERIFIED,
TRANSFER_RESULT_UNKNOWN,
@@ -61,14 +61,14 @@ 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
@@ -83,8 +83,8 @@ class RawLineRefDTO:
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
class MatchingItemDTO:
"""匹配明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
source_code: str
material_no: str
@@ -103,21 +103,28 @@ class PrecheckInvoiceItemDTO:
lot_no: str = ""
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
receipt_warehouse_code: 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:
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 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_external_write_count: int
precheck_hash: str
matching_hash: str
# ---- 结果页 DTO(决策 20)--------------------------------------------------
@@ -166,15 +173,15 @@ class RunResultDTO:
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
def aggregate_external_documents(items: Iterable[MatchingItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
Args:
items: 预检明细项(含 external_document_no 与 result)。
items: 匹配明细项(含 external_document_no 与 result)。
Returns:
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
"""
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
grouped: dict[str, list[MatchingItemDTO]] = {}
for item in items:
if item.external_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.external_document_no, []).append(item)
@@ -1,9 +1,9 @@
"""在途调拨业务日期与成熟度策略。
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
昨天及更早可预检,未来日期阻断)。
昨天及更早可匹配,未来日期阻断)。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用,
逻辑:所有日期判定集中在本模块,供 matching_service / recovery_service 复用,
避免各服务各自计算导致口径漂移。
"""
@@ -105,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,10 +1,10 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:movement_file_repository / capability_client / precheck_service / models。
依赖:movement_file_repository / capability_client / matching_service / models。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
"""
@@ -15,7 +15,7 @@ from typing import Any
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
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,
@@ -120,7 +120,7 @@ class _DefaultRpaTrigger:
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,预检会反复重抓。fail-closed 返回明确错误码。
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
@@ -52,7 +52,7 @@ 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, "数量不一致", {"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)
@@ -71,7 +71,7 @@ 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", "来源", "料号", "预检结果", "外部系统 单号"])
sheet.append(["Invoice", "来源", "料号", "匹配结果", "外部系统 单号"])
for item in items:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
@@ -1,9 +1,11 @@
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
"""在途调拨执行服务(按行执行三层门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
用途:按行执行调拨:三层门禁(①存在且可执行 ②行级新鲜度 ③文件版本对账,
fail-closed 任一不过则 外部系统 写入为 0)→ 创建执行 Run →
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
依赖:orchestrator、capability_client、quantity、contracts、audit、status、
source_file_status、matching_service(scope 圈行/_item_evaluated_sha)、models。
逻辑:执行与匹配确认解耦(hash/expires 门禁退役,新鲜度由行 updated_at 承担);
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
"""
@@ -17,29 +19,31 @@ from decimal import Decimal
from typing import Any
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem, TransferMatching, TransferRun
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_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
ExternalDocumentDTO,
PrecheckInvoiceItemDTO,
MatchingItemDTO,
RunResultDTO,
TransferExceptionDTO,
aggregate_external_documents,
)
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
from app.services.in_transit_transfer.precheck_service import (
from app.services.in_transit_transfer.orchestrator import (
create_execution_run_for_items,
finalize_run,
)
from app.services.in_transit_transfer.matching_service import (
RESULT_EXECUTABLE,
RouteNotResolvedError,
TransferDeps,
_item_evaluated_sha,
scope_item_query,
)
from app.services.in_transit_transfer.capability_client import StockTarget
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
PRECHECK_EXPIRED_RESULT = "precheck_expired"
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
@@ -53,7 +57,7 @@ class ExecuteOutcome:
def _item_result_of(item: TransferInvoiceItem) -> str:
"""从持久化状态还原明细结果值(与预检快照口径一致)。"""
"""从持久化状态还原明细结果值(与匹配快照口径一致)。"""
if item.result_code:
return item.result_code
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
@@ -61,121 +65,97 @@ def _item_result_of(item: TransferInvoiceItem) -> str:
return item.status
def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
"""由存储明细复算预检 Hash(写前快照校验口径)。"""
from app.services.in_transit_transfer.audit import canonical_hash
counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {}
items = [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": item.receipt_quantity,
"external_quantity": item.external_quantity,
"result": _item_result_of(item),
}
for item in sorted(precheck.items, key=lambda row: row.id)
]
snapshot = {
"scope": sorted(precheck.scope_json.get("source_codes") or []),
"business_date": precheck.business_date,
"file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {},
"counts": {
key: int(counts.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
},
"items": items,
}
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
if scope_transfer_type:
snapshot["transfer_type"] = scope_transfer_type
return f"sha256:{canonical_hash(snapshot)}"
def _expire(precheck: TransferPrecheck) -> None:
"""将预检置为过期(fail-closed 落位)。"""
precheck.status = "expired"
db.session.flush()
def execute_precheck(
def execute_items(
*,
precheck_id: str,
item_ids: list[int],
deps: TransferDeps,
selected_invoice_nos: list[str] | None = None,
actor_id: int | None = None,
request_id: str | None = None,
) -> ExecuteOutcome:
"""执行一次已确认的预检(手工或自动触发共用)。
"""按行执行调拨(三层门禁,手工执行与自动触发共用)。
【AI 触发时机】:用户/自动排程圈定待执行明细行(item_ids)后触发;
任一门禁不过则 外部系统 写入为 0(fail-closed)。
三层门禁(顺序校验,命中即抛、后续不执行):
① 存在且可执行:id 存在且 status == ready_to_execute,否则
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID", details.invalid_item_ids)。
② 行级新鲜度:updated_at 距 now 超过 deps.strategy.confirm_ttl_seconds →
ValidationError(code="TRANSFER.ITEMS_STALE", details.stale_item_ids)。
③ 文件版本对账:按去重来源调 resolve_source_file_status,行评估版本戳
(_item_evaluated_sha)缺失或 ≠ 来源最新可用文件 sha(含来源无可用文件)→
ValidationError(code="TRANSFER.FILE_CHANGED", details.changed_item_ids)。
Args:
precheck_id: 预检编号。
item_ids: 待执行明细行 id 列表(重复 id 自动去重,保持首现顺序)。
deps: 注入依赖。
selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。
actor_id / request_id: 审计上下文。
actor_id / request_id: 审计上下文(写入 run.created_by / 写入审计事件)。
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
ConflictError: 重复执行。
ValidationError: 三层门禁任一不过(details 携带对应 id 列表)。
"""
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")
if precheck.confirmed_at is not None:
from app.core.errors import ConflictError
# [STEP 1] 门禁①:加载并校验 id(存在 + ready_to_execute)。
seen: set[int] = set()
ordered_ids = [i for i in (int(x) for x in item_ids) if not (i in seen or seen.add(i))]
if not ordered_ids:
raise ValidationError(
"item_ids is required", code="TRANSFER.EXECUTE_ITEMS_INVALID",
details={"invalid_item_ids": []},
)
rows = db.session.query(TransferInvoiceItem).filter(
TransferInvoiceItem.id.in_(ordered_ids),
).all()
by_id = {row.id: row for row in rows}
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
invalid = [
i for i in ordered_ids
if by_id.get(i) is None or by_id[i].status != ready_status
]
if invalid:
raise ValidationError(
"items not executable", code="TRANSFER.EXECUTE_ITEMS_INVALID",
details={"invalid_item_ids": invalid},
)
items = [by_id[i] for i in ordered_ids]
raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED")
if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value:
raise AppError(
code=TRANSFER_CONFIRMATION_REQUIRED,
message="precheck is not confirmed for execution",
http_status=400,
)
if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow():
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired",
http_status=409,
)
if recompute_precheck_hash(precheck) != precheck.precheck_hash:
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED,
message="precheck snapshot changed since confirmation",
http_status=409,
# [STEP 2] 门禁②:行级新鲜度(updated_at 距 now ≤ 确认 TTL)。
now = datetime.utcnow()
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
stale = [
item.id for item in items
if item.updated_at is None
or (now - item.updated_at).total_seconds() > ttl_seconds
]
if stale:
raise ValidationError(
"items stale since last evaluation", code="TRANSFER.ITEMS_STALE",
details={"stale_item_ids": stale},
)
executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
if selected_invoice_nos is not None:
selected_set = {str(item).strip() for item in selected_invoice_nos}
available = {item.invoice_no for item in executable}
invalid = selected_set - available
if invalid:
raise ValidationError(
f"invoices not executable: {sorted(invalid)}",
code="TRANSFER.SELECTION_INVALID",
)
selected = [item for item in executable if item.invoice_no in selected_set]
else:
selected = list(executable)
if not selected:
raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED)
# [STEP 3] 门禁③:文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致;
# 来源无可用文件或行无版本戳均视为不一致 → FILE_CHANGED)。
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({item.source_code for item in items})
}
changed = []
for item in items:
evaluated_sha = _item_evaluated_sha(item)
latest = latest_files.get(item.source_code) or {}
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
changed.append(item.id)
if changed:
raise ValidationError(
"source receipt file changed since evaluation", code="TRANSFER.FILE_CHANGED",
details={"changed_item_ids": changed},
)
run = create_execution_run(
precheck, deps=deps, actor_id=actor_id,
selected_invoice_nos={item.invoice_no for item in selected},
# [STEP 4] 建执行 Run(不绑定匹配)+ 逐行写前复查与原子写入(单项失败不阻断)。
run = create_execution_run_for_items(
items, deps=deps, actor_id=actor_id, selected_item_ids=set(ordered_ids),
)
for item in selected:
for item in items:
try:
_write_item(item, deps=deps, run_no=run.run_no, request_id=request_id)
except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项
@@ -190,6 +170,61 @@ def execute_precheck(
return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run))
def execute_matching_items(
*,
matching_id: str,
deps: TransferDeps,
invoice_nos: list[str] | None = None,
actor_id: int | None = None,
request_id: str | None = None,
) -> ExecuteOutcome:
"""按匹配 scope 圈定 ready 行并按行执行(chat action / 自动排程 / Run Job 共用入口)。
行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"由 scope 重新圈定
(scope_item_query:来源 + 收料日期区间 + 调拨类型前缀);本入口按 scope 取
ready_to_execute 行(可选 invoice_nos 过滤)后委托 execute_items 执行,
三层门禁由 execute_items 统一裁定。
Args:
matching_id: 匹配编号(MTG-...),仅用于圈定 scope。
deps: 注入依赖。
invoice_nos: 选择范围(可选);含 scope 内不可执行票时整单拒绝(fail-closed)。
actor_id / request_id: 审计上下文。
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError: 匹配不存在。
ValidationError: 选择含不可执行票(TRANSFER.SELECTION_INVALID)或
execute_items 三层门禁失败。
"""
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")
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
ready_rows = (
scope_item_query(matching)
.filter(TransferInvoiceItem.status == ready_status)
.order_by(TransferInvoiceItem.id.asc())
.all()
)
if invoice_nos is not None:
selected_set = {str(invoice_no).strip() for invoice_no in invoice_nos}
available = {row.invoice_no for row in ready_rows}
invalid = selected_set - available
if invalid:
raise ValidationError(
f"invoices not executable: {sorted(invalid)}",
code="TRANSFER.SELECTION_INVALID",
)
ready_rows = [row for row in ready_rows if row.invoice_no in selected_set]
return execute_items(
item_ids=[row.id for row in ready_rows],
deps=deps, actor_id=actor_id, request_id=request_id,
)
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(
@@ -197,7 +232,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
warehouse_code=item.receipt_warehouse_code or "",
)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
_mark_recheck_blocked(item, "matching_expired", "route mapping changed since matching")
return
receipt_qty = Decimal(item.receipt_quantity)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
@@ -215,7 +250,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
except RouteNotResolvedError:
raise
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
_mark_recheck_blocked(item, "matching_expired", "external inventory changed since matching")
return
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
@@ -337,11 +372,11 @@ def get_run(run_no: str) -> dict[str, Any]:
def _build_run_result(run: TransferRun) -> RunResultDTO:
"""由 Run 明细构建结果投影。"""
item_dtos: list[PrecheckInvoiceItemDTO] = []
item_dtos: list[MatchingItemDTO] = []
exceptions: list[TransferExceptionDTO] = []
for item in sorted(run.items, key=lambda row: row.invoice_no):
result = _item_result_of(item)
item_dtos.append(PrecheckInvoiceItemDTO(
item_dtos.append(MatchingItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
@@ -62,7 +62,7 @@ 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())
@@ -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"):
@@ -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}
@@ -1,11 +1,16 @@
"""在途调拨预检服务。
"""在途调拨匹配服务。
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
严格数量匹配 → 匹配快照与 Hash",并支持匹配进度恢复(restore)。
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
date_policy / quantity / contracts / audit / models。
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
匹配 Hash 由冻结快照复算;create_matching 落库 Run + Matching + Items,
重复匹配对既有行"原地刷新"(不迁移 matching_id),行携带文件版本戳
file_sha256,文件新版本消失的可执行行标记 blocked_file_removed;
restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行;
restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合。
"""
from __future__ import annotations
@@ -16,15 +21,17 @@ from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Protocol
from sqlalchemy import case, func, false, or_
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
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 (
PrecheckCountsDTO,
PrecheckInvoiceItemDTO,
PrecheckSummaryDTO,
MatchingCountsDTO,
MatchingItemDTO,
MatchingSummaryDTO,
RawLineRefDTO,
)
from app.services.in_transit_transfer.date_policy import (
@@ -52,14 +59,17 @@ from app.services.in_transit_transfer.invoice_aggregator import (
aggregate_invoices,
)
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,
filter_invoices_for_type,
invoice_in_scope,
normalize_transfer_type,
transfer_type_scope_note,
)
@@ -74,6 +84,8 @@ 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"
@dataclass(frozen=True)
@@ -118,17 +130,17 @@ class SourceProgressDTO:
@dataclass(frozen=True)
class PrecheckRunResult:
"""一次预检运行的完整结果。"""
class MatchingRunResult:
"""一次匹配运行的完整结果。"""
summary: PrecheckSummaryDTO
items: tuple[PrecheckInvoiceItemDTO, ...]
summary: MatchingSummaryDTO
items: tuple[MatchingItemDTO, ...]
sources: tuple[SourceProgressDTO, ...]
@dataclass(frozen=True)
class TransferDeps:
"""预检/执行依赖集合(测试注入 Fake 替身)。"""
"""匹配/执行依赖集合(测试注入 Fake 替身)。"""
file_repository: ReceiptFileRepository
rpa_trigger: RpaTrigger
@@ -137,8 +149,8 @@ class TransferDeps:
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str:
"""预检状态:存在未完成来源 → file_pending;否则按可执行数定。"""
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:
@@ -146,7 +158,7 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCoun
return "success"
def run_precheck(
def run_matching(
*,
source_codes: list[str],
business_date: str,
@@ -156,8 +168,8 @@ def run_precheck(
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
transfer_type: TransferType | str | None = None,
) -> PrecheckRunResult:
"""执行一次只读预检(不写 外部系统)。
) -> MatchingRunResult:
"""执行一次只读匹配(不写 外部系统)。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
@@ -168,7 +180,7 @@ def run_precheck(
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
Returns:
PrecheckRunResult(摘要 + 明细 + 来源进度)。
MatchingRunResult(摘要 + 明细 + 来源进度)。
Raises:
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
"""
@@ -190,7 +202,7 @@ def run_precheck(
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
items: list[PrecheckInvoiceItemDTO] = []
items: list[MatchingItemDTO] = []
file_snapshot: dict[str, Any] = {}
for source_code in source_codes:
source_stage: SourceProgressDTO
@@ -227,7 +239,7 @@ def run_precheck(
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
source_items = _precheck_invoices(
source_items = _matching_invoices(
invoices=invoices,
source_code=source_code,
business_date=business_date,
@@ -256,16 +268,16 @@ def run_precheck(
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER.SOURCE_PRECheck_ERROR",
error_code="TRANSFER.SOURCE_MATCH_ERROR",
error_message=str(exc),
))
counts = PrecheckCountsDTO(
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),
prechecked_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_")),
)
@@ -280,7 +292,7 @@ def run_precheck(
"counts": {
"file_invoice_count": counts.file_invoice_count,
"not_matured_count": counts.not_matured_count,
"prechecked_count": counts.prechecked_count,
"matched_count": counts.matched_count,
"executable_count": counts.executable_count,
"blocked_count": counts.blocked_count,
},
@@ -297,10 +309,10 @@ def run_precheck(
for item in items
],
}
precheck_hash = f"sha256:{canonical_hash(snapshot)}"
matching_hash = f"sha256:{canonical_hash(snapshot)}"
sources_tuple = tuple(sources)
summary = PrecheckSummaryDTO(
precheck_id="", # 落库时回填
summary = MatchingSummaryDTO(
matching_id="", # 落库时回填
status=_summary_status(sources_tuple, counts),
business_date=business_date,
eligible_receipt_date_to=str(
@@ -310,12 +322,12 @@ def run_precheck(
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_external_write_count=counts.executable_count,
precheck_hash=precheck_hash,
matching_hash=matching_hash,
)
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
def _precheck_invoices(
def _matching_invoices(
*,
invoices: list,
source_code: str,
@@ -323,9 +335,9 @@ def _precheck_invoices(
ready_file: ReadyReceiptFile,
deps: TransferDeps,
run_no: str,
) -> list[PrecheckInvoiceItemDTO]:
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
output: list[PrecheckInvoiceItemDTO] = []
) -> list[MatchingItemDTO]:
"""对单个来源的汇总 Invoice 匹配(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
output: list[MatchingItemDTO] = []
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
@@ -338,7 +350,7 @@ def _precheck_invoices(
)
receipt_date_iso = invoice.receipt_date.isoformat()
if maturity == MATURITY_NOT_MATURED:
output.append(PrecheckInvoiceItemDTO(
output.append(MatchingItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
@@ -350,7 +362,7 @@ def _precheck_invoices(
))
continue
if maturity == MATURITY_FUTURE:
output.append(PrecheckInvoiceItemDTO(
output.append(MatchingItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
@@ -385,7 +397,7 @@ def _precheck_invoices(
)
except ExternalQueryTimeoutError:
for invoice, route, raw, receipt_date_iso in entries:
output.append(PrecheckInvoiceItemDTO(
output.append(MatchingItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
@@ -399,10 +411,10 @@ def _precheck_invoices(
continue
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
# 组内逐票给 blocked_external_query_failed + 原因,预检列表保持可见可解释。
# 组内逐票给 blocked_external_query_failed + 原因,匹配列表保持可见可解释。
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
for invoice, route, raw, receipt_date_iso in entries:
output.append(PrecheckInvoiceItemDTO(
output.append(MatchingItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
@@ -419,7 +431,7 @@ def _precheck_invoices(
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
)
if stock_qty is None:
output.append(PrecheckInvoiceItemDTO(
output.append(MatchingItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
@@ -434,7 +446,7 @@ def _precheck_invoices(
))
continue
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
output.append(PrecheckInvoiceItemDTO(
output.append(MatchingItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
@@ -462,12 +474,34 @@ def _item_status(result: str) -> str:
def _generate_no(prefix: str, business_date: str) -> str:
"""生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。"""
"""生成稳定业务编号(MTG-YYYYMMDD-XXXX / RUN-...)。"""
compact = str(business_date).replace("-", "")
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
def create_precheck(
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,
@@ -476,19 +510,23 @@ def create_precheck(
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
transfer_type: TransferType | str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
) -> MatchingSummaryDTO:
"""运行匹配并落库 TransferRun + TransferMatching + InvoiceItems。
落库为行原地刷新语义:相同粒度的既有行只刷新业务值(不迁移 matching_id)、
行携带本次评估所用文件的 file_sha256 版本戳;上一版本可执行而最新文件
消失的 ready 行被标记 blocked_file_removed。
Args:
source_codes / business_date / deps: 同 run_precheck。
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
source_codes / business_date / deps: 同 run_matching。
receipt_date_from / receipt_date_to / transfer_type: 同 run_matching。
Returns:
预检摘要(precheck_id 已回填)。
匹配摘要(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_precheck(
result = run_matching(
source_codes=source_codes,
business_date=business_date,
deps=deps,
@@ -503,7 +541,7 @@ def create_precheck(
run_no=run_no,
trigger_type="manual",
business_date=business_date,
status="prechecking",
status="matching",
source_codes_json=list(source_codes),
counts_json=asdict(result.summary.counts),
transfer_type=resolved_transfer_type.value,
@@ -517,7 +555,7 @@ def create_precheck(
_valid_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',
}
for job_source in result.sources:
create_source_job(
@@ -528,9 +566,9 @@ def create_precheck(
error_message=job_source.error_message,
)
precheck_no = _generate_no("TPC", business_date)
precheck = TransferPrecheck(
precheck_no=precheck_no,
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,
@@ -555,14 +593,16 @@ def create_precheck(
counts_json=asdict(result.summary.counts),
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_external_write_count=result.summary.estimated_external_write_count,
precheck_hash=result.summary.precheck_hash,
matching_hash=result.summary.matching_hash,
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
)
db.session.add(precheck)
db.session.add(matching)
db.session.flush()
# [幂等] 相同 (来源,单号,料号,收料日期) 的重复预检不得累加异常行:
# 非终态行原地刷新并挂到最新预检;终态行(已执行/人工关闭等)保持既定事实不复活。
# [幂等·原地刷新] 相同 (来源,单号,料号,收料日期) 的重复匹配不得累加异常行:
# 非终态行在原地刷新业务值(不迁移 matching_id 归属),并显式续 updated_at
# 新鲜度(同值写入不触发 onupdate);终态行(已执行/人工关闭等)保持既定事实
# 不复活。行是否仍有效由文件版本戳 + 消失行标记判定(见循环后标记段)。
_terminal_item_statuses = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
@@ -570,9 +610,14 @@ def create_precheck(
status_machine.TransferStatus.CANCELLED.value,
status_machine.TransferStatus.EXECUTING.value,
}
# 文件版本戳与 file_snapshot 同源:本次评估各行所用的收料文件 checksum。
source_checksums = {
stage.source_code: stage.checksum
for stage in result.sources
if stage.checksum
}
for item in result.items:
fields = {
"precheck_id": precheck.id,
"status": _item_status(item.result),
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
"result_message": item.reason or None,
@@ -583,7 +628,13 @@ def create_precheck(
"lot_no": item.lot_no or "",
"receipt_warehouse_code": item.receipt_warehouse_code or "",
"raw_lines_json": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
{
"sheet": line.sheet,
"row_no": line.row_no,
"file_version": line.file_version,
# 文件版本戳:Task 2/3 文件对账与消失行标记的判定依据。
"file_sha256": source_checksums.get(item.source_code),
}
for line in item.raw_lines
],
}
@@ -603,9 +654,13 @@ def create_precheck(
if existing.status not in _terminal_item_statuses:
for attr, value in fields.items():
setattr(existing, attr, value)
# 行不迁移归属(matching_id 保持首次创建值);显式续新鲜度,
# 否则"同值刷新"不触发 onupdate、行看似陈旧。
existing.updated_at = now
continue
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
# 匹配阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
db.session.add(TransferInvoiceItem(
matching_id=matching.id,
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
@@ -614,85 +669,134 @@ def create_precheck(
receipt_date=item.receipt_date,
**fields,
))
# [消失行标记] 对每个有文件的 source:上一版本评估为可执行、本次文件版本
# 已变化且行消失(或内容变化导致版本不同)的 ready 行,停用为
# blocked_file_removed——防止按过期文件数据执行。只标 ready 行(blocked 行
# 已有终局解释,覆盖会丢失真实原因);无版本戳的存量行跳过(fail-safe)。
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
for stage in result.sources:
checksum = source_checksums.get(stage.source_code)
if not checksum:
continue
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code == stage.source_code,
TransferInvoiceItem.status == ready_status,
)
# 仅标记本次匹配收料日期范围内的行(范围外行不属于本次评估口径)。
if receipt_date_from:
query = query.filter(TransferInvoiceItem.receipt_date >= receipt_date_from)
if receipt_date_to:
query = query.filter(TransferInvoiceItem.receipt_date <= receipt_date_to)
with db.session.no_autoflush:
candidates = query.all()
for row in candidates:
evaluated_sha = _item_evaluated_sha(row)
if evaluated_sha is None or evaluated_sha == checksum:
continue
row.status = blocked_status
row.result_code = RESULT_FILE_REMOVED
row.result_message = "receipt row removed from latest file"
db.session.commit()
summary = PrecheckSummaryDTO(
precheck_id=precheck_no,
status=precheck.status,
business_date=precheck.business_date,
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=precheck.expires_at.isoformat() if precheck.expires_at else "",
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,
precheck_hash=result.summary.precheck_hash,
matching_hash=result.summary.matching_hash,
)
return summary
def restore_precheck(precheck_id: str) -> dict[str, Any]:
"""按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。
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 行
实时聚合;estimated_* 与 expires_at / matching_hash 沿用匹配记录留痕展示。
Args:
precheck_id: 预检编号(TPC-...)。
matching_id: 匹配编号(MTG-...)。
deps: 注入依赖(缺省内部取 deps.get_transfer_dependencies();restore
只读 strategy.confirm_ttl_seconds,不产生外部调用)。
now: 新鲜度判定基准时间(缺省 datetime.utcnow(),测试注入冻结时钟)。
Returns:
{"summary": {...}, "items": [...], "sources": [...]}。
{"summary": {...}, "items": [...], "sources": [...]};items 每行额外装饰
item_id / checked_at / stale / file_current 四字段。
Raises:
NotFoundError: 预检不存在。
NotFoundError: 匹配不存在。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip()
# [依赖缺省] 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 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_external_write_count=int(precheck.estimated_external_write_count or 0),
precheck_hash=precheck.precheck_hash,
if matching is None:
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
# [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属
# (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。
rows = (
scope_item_query(matching)
.order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc())
.all()
)
# [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 语义一致)。
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),
)
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 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,
receipt_date=item.receipt_date,
lot_no=item.lot_no or "",
receipt_warehouse_code=item.receipt_warehouse_code 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 [])
),
))
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,
@@ -703,13 +807,151 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
error_code=job.error_code,
error_message=job.error_message,
)
for job in (precheck.run.source_jobs if precheck.run else [])
for job in (matching.run.source_jobs if matching.run else [])
] or [
SourceProgressDTO(source_code=code, stage="file_ready")
for code in (precheck.scope_json.get("source_codes") or [])
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: 行级新鲜度 TTL(strategy.confirm_ttl_seconds)。
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 "",
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 [])
),
# [行装饰] 行级新鲜度与文件对账(实时视图判定依据):
# stale=距上次评估超过确认 TTL;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)}}
@@ -42,7 +42,7 @@ class MovementField:
# 定死的 10 个通用异动字段(领域契约,不配置化)。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
# 批号(lot_no)为展示维度——预检列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
@@ -1,70 +1,70 @@
"""在途调拨执行编排(Run 生命周期辅助)。
用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、
用途:按选中明细行创建执行 Run(置 executing、记录业务日/来源范围/行计数)、
按明细终态收尾 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);行归属
由调用方按 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 并关联(行级执行,不绑定匹配)。
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: 预检已确认(重复执行)。
状态为 executing 的 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,
business_date=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 {}),
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,7 +1,7 @@
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
供来源状态投影(source_file_status)、预检取文件(movement_file_repository)、
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
@@ -36,7 +36,7 @@ def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnEleme
"""返回「当前可用的收料归档文件」SQL 条件。
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期(archive_expires_at 为空视为长期有效)。预检复用与下载
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
Args:
@@ -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,6 +1,6 @@
"""在途调拨每日历史恢复(自动复核待处理池)。
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新预检并创建新 Attempt;
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新匹配并创建新 Attempt;
result_unknown / manually_closed / success 不自动写入。
依赖:models、retry_service._recheck_item、TransferDeps。
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
@@ -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
@@ -2,8 +2,9 @@
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、capability_client、quantity、status、audit、precheck_service.TransferDeps。
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制)。
"""
from __future__ import annotations
@@ -19,7 +20,7 @@ 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.capability_client import StockTarget
from app.services.in_transit_transfer.precheck_service import (
from app.services.in_transit_transfer.matching_service import (
RESULT_EXTERNAL_QUERY_FAILED,
RESULT_EXECUTABLE,
TransferDeps,
@@ -30,7 +31,7 @@ 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,
@@ -64,7 +65,7 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
)
db.session.add(attempt)
db.session.flush()
# [降级] 与 precheck 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
# [降级] 与 matching 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
try:
@@ -89,6 +90,9 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
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",
@@ -121,6 +125,9 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
item.external_quantity = str(stock_qty)
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",
@@ -173,26 +180,67 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
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:
precheck_no: 预检编号(定位明细集合)。
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")
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:
"""批量重查 外部系统 库存:对同一匹配下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
Args:
matching_no: 匹配编号(定位明细集合)。
deps: 注入依赖(capabilities = 外部系统网关客户端)。
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可重查行。
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行。
actor_id / request_id: 审计上下文。
Returns:
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
"""
from app.models import TransferPrecheck
from app.models import TransferMatching
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
if matching is None:
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.precheck_id == precheck.id,
TransferInvoiceItem.matching_id == matching.id,
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
)
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
@@ -219,4 +267,4 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False,
"error": str(exc).strip() or exc.__class__.__name__})
return {"precheck_no": precheck_no, "total": len(items), "results": results}
return {"matching_no": matching_no, "total": len(items), "results": results}
@@ -1,6 +1,6 @@
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。
用途:将领域 DTO 转为前端稳定 JSON(匹配摘要/明细/来源进度/执行结果)。
依赖:contracts、execution_service。
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
"""
@@ -13,9 +13,9 @@ from app.services.in_transit_transfer.execution_service import serialize_run_res
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,18 +23,23 @@ 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,
},
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
"estimated_external_write_count": summary.estimated_external_write_count,
"precheck_hash": summary.precheck_hash,
"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,
@@ -53,6 +58,10 @@ def serialize_item(item) -> dict[str, Any]:
{"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,
}
@@ -69,8 +78,8 @@ 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"]],
@@ -25,7 +25,7 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
失效判定(不依赖保留期清理任务落位,与预检取文件/下载同口径,见
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
Returns:
@@ -1,7 +1,7 @@
"""在途调拨来源级状态服务(唯一推进入口)。
用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源),
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
让 create_matching / restore / 未来回调等调用方都经由本服务,不各自散落改表。
依赖:models(TransferSourceJob)、status_machine。
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
@@ -17,7 +17,7 @@ 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',
)
@@ -25,7 +25,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"
@@ -43,7 +43,7 @@ class TransferRunStatus(StrEnum):
QUEUED = "queued"
PREPARING_FILES = "preparing_files"
PRECHECKING = "prechecking"
MATCHING = "matching"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
@@ -78,17 +78,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,
@@ -101,7 +101,7 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.CANCELLED.value,
}),
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
TransferStatus.PRECHECKING.value, # 仅 外部系统 重查/重新预检,创建新 Attempt
TransferStatus.MATCHING.value, # 仅 外部系统 重查/重新匹配,创建新 Attempt
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
@@ -121,11 +121,11 @@ RUN_TRANSITIONS: dict[str, frozenset[str]] = {
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,
@@ -1,12 +1,13 @@
"""在途调拨类型契约。
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝预检,规则先冻结)。
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
逻辑:类型决定预检纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
逻辑:类型决定匹配纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
类型 3 规则待业务定义。调用方必须先 ensure_transfer_type_supported 再过滤。
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
"""
from __future__ import annotations
@@ -29,7 +30,7 @@ class TransferType(StrEnum):
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
# 一期已实现预检/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
@@ -63,7 +64,7 @@ def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入预检。
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。
Args:
transfer_type: 已规范化的调拨类型。
@@ -78,6 +79,27 @@ def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
)
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,
@@ -88,20 +110,16 @@ def filter_invoices_for_type(
invoices: 已汇总的收料票。
transfer_type: 已规范化且已确认支持的调拨类型。
Returns:
类型范围内的票列表。
类型范围内的票列表(判断口径统一走 invoice_in_scope)。
"""
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
return [
invoice for invoice in invoices
if str(invoice.invoice_no or "").strip().upper().startswith(prefixes)
]
# 类型 2/3 的过滤规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
return list(invoices)
return [
invoice for invoice in invoices
if invoice_in_scope(invoice.invoice_no, transfer_type)
]
def transfer_type_scope_note(transfer_type: TransferType) -> str:
"""类型的范围规则说明(写入 TransferPrecheck.scope_json 供审计追溯)。"""
"""类型的范围规则说明(写入 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:
@@ -68,7 +68,14 @@ def extract_path(obj: Any, path: str) -> Any:
def _walk(cur: Any, tokens: list[str]) -> Any:
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。"""
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。
[缺陷修复 2026-09-23] 扇出收集的命中值本身可能是列表(更深层重复节点,如
多 RecordSet 的 Master 列表、单 Master 多 Record 的 Field 列表)。若不拍平,
嵌套 list 会让 each/pick 等消费方取不到任何字段 → 行被静默丢弃——后果是
批量库存查询整批误判为查无库存(机制推演;该嵌套形态尚未在生产观测到)。
收集结果统一拍平一层:语义仍是"路径在重复结构中的全部命中"。
"""
if not tokens:
return cur
tok, rest = tokens[0], tokens[1:]
@@ -81,10 +88,23 @@ def _walk(cur: Any, tokens: list[str]) -> Any:
return _walk(cur[tok], rest)
if isinstance(cur, list):
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
return collected if collected else 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) ----
def _default(value: Any, default: Any) -> Any:
@@ -163,6 +183,39 @@ def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
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 列表(多条外部记录→多行结果的通用需求)。
@@ -170,6 +223,9 @@ def _each(value: Any, fields: dict | None = None) -> Any:
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)→ 归一为空列表:
@@ -184,27 +240,30 @@ def _each(value: Any, fields: dict | None = None) -> Any:
raise MappingInvalidError(details={"reason": "each_target_not_list"})
out: list[Any] = []
for item in value:
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(item, 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)
# [缺陷修复 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
@@ -792,6 +792,24 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
return None
def _lock_process_gates_for_task(task: ShippingNotice) -> None:
"""
[锁序约定] 回调写库存候选数据前,先锁该任务活跃 Execution 的全部 Gate 行。
外部等待轮询(run_inventory_external_wait_poll)的顺序是先锁 Gate 再读候选行;
本侧若先写候选、后经 Gate 同步更新 Gate 行,会以相反顺序与轮询形成死锁环,
事务被毒化后以 InFailedSqlTransaction 收口且轮询链断裂
(2026-09-23 test job 8818:库存 RPA 回调 × external-wait 轮询竞跑)。
统一为两侧都先取 Gate 锁:后到方短暂阻塞后串行执行,不再产生错误。
"""
from app.models import ShippingProcessGate
execution_id = int(getattr(task, 'active_process_execution_id', 0) or 0)
if not execution_id:
return
ShippingProcessGate.query.filter_by(execution_id=execution_id).with_for_update().all()
def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None:
"""
复核 RPA 触发后可能漂移的订单与路由门禁(skipped/failed/success 共用)。
@@ -1813,6 +1831,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if gate_resp is not None:
return gate_resp
# [锁序约定] 写入前先锁 Gate 行,与 external-wait 轮询串行(见 _lock_process_gates_for_task)。
_lock_process_gates_for_task(task)
runtime = _save_last_inventory_rpa_runtime(task, payload)
callback_status = _normalize_rpa_inventory_result_status(payload)
@@ -2486,6 +2506,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
"error": gate_resp.get("message") or "inventory_source_gate_blocked",
})
continue
# [锁序约定] 写入前先锁 Gate 行,与 external-wait 轮询串行(见 _lock_process_gates_for_task)。
_lock_process_gates_for_task(task)
round_resp = _validate_rpa_callback_round(task, merged_item)
if round_resp is not None:
round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {}