diff --git a/backend/app/api/in_transit_transfer.py b/backend/app/api/in_transit_transfer.py index 4e15af13..a10c8121 100644 --- a/backend/app/api/in_transit_transfer.py +++ b/backend/app/api/in_transit_transfer.py @@ -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/", 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/", 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//execute", methods=["POST"]) +@in_transit_transfer_bp.route("/matchings//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//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//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//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, } diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 06f5783b..49105fc8 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -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, diff --git a/backend/app/jobs/handlers/in_transit_transfer_match.py b/backend/app/jobs/handlers/in_transit_transfer_match.py new file mode 100644 index 00000000..31646a88 --- /dev/null +++ b/backend/app/jobs/handlers/in_transit_transfer_match.py @@ -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() diff --git a/backend/app/jobs/handlers/in_transit_transfer_precheck.py b/backend/app/jobs/handlers/in_transit_transfer_precheck.py deleted file mode 100644 index 7a7ee519..00000000 --- a/backend/app/jobs/handlers/in_transit_transfer_precheck.py +++ /dev/null @@ -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() diff --git a/backend/app/jobs/handlers/in_transit_transfer_run.py b/backend/app/jobs/handlers/in_transit_transfer_run.py index 161ed59f..75af7900 100644 --- a/backend/app/jobs/handlers/in_transit_transfer_run.py +++ b/backend/app/jobs/handlers/in_transit_transfer_run.py @@ -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(), ) diff --git a/backend/app/jobs/handlers/shipping_process_gate.py b/backend/app/jobs/handlers/shipping_process_gate.py index 4ddb205f..10bac725 100644 --- a/backend/app/jobs/handlers/shipping_process_gate.py +++ b/backend/app/jobs/handlers/shipping_process_gate.py @@ -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) diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index c0a78316..91830e23 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -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', }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 43281a72..814b6ea6 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/in_transit_transfer.py b/backend/app/models/in_transit_transfer.py index 288df8f1..8b52e2ad 100644 --- a/backend/app/models/in_transit_transfer.py +++ b/backend/app/models/in_transit_transfer.py @@ -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) diff --git a/backend/app/services/agent_registry/data/catalog_manifest.yaml b/backend/app/services/agent_registry/data/catalog_manifest.yaml index 73372cc0..bee6f5d7 100644 --- a/backend/app/services/agent_registry/data/catalog_manifest.yaml +++ b/backend/app/services/agent_registry/data/catalog_manifest.yaml @@ -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 diff --git a/backend/app/services/agent_registry/handlers/in_transit_transfer.py b/backend/app/services/agent_registry/handlers/in_transit_transfer.py index e4497caa..ead469d3 100644 --- a/backend/app/services/agent_registry/handlers/in_transit_transfer.py +++ b/backend/app/services/agent_registry/handlers/in_transit_transfer.py @@ -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: diff --git a/backend/app/services/in_transit_transfer/__init__.py b/backend/app/services/in_transit_transfer/__init__.py index 270a12c6..bfb70f6a 100644 --- a/backend/app/services/in_transit_transfer/__init__.py +++ b/backend/app/services/in_transit_transfer/__init__.py @@ -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 完成。 """ diff --git a/backend/app/services/in_transit_transfer/archive.py b/backend/app/services/in_transit_transfer/archive.py index 7f32302d..ed0e261d 100644 --- a/backend/app/services/in_transit_transfer/archive.py +++ b/backend/app/services/in_transit_transfer/archive.py @@ -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。 diff --git a/backend/app/services/in_transit_transfer/audit.py b/backend/app/services/in_transit_transfer/audit.py index d0027221..a3076ac7 100644 --- a/backend/app/services/in_transit_transfer/audit.py +++ b/backend/app/services/in_transit_transfer/audit.py @@ -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, diff --git a/backend/app/services/in_transit_transfer/auto_transfer.py b/backend/app/services/in_transit_transfer/auto_transfer.py index 1cfcc5ff..ac35f6df 100644 --- a/backend/app/services/in_transit_transfer/auto_transfer.py +++ b/backend/app/services/in_transit_transfer/auto_transfer.py @@ -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 diff --git a/backend/app/services/in_transit_transfer/backlog_service.py b/backend/app/services/in_transit_transfer/backlog_service.py index 4a9371e2..f57adf95 100644 --- a/backend/app/services/in_transit_transfer/backlog_service.py +++ b/backend/app/services/in_transit_transfer/backlog_service.py @@ -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 diff --git a/backend/app/services/in_transit_transfer/chat_actions.py b/backend/app/services/in_transit_transfer/chat_actions.py index 641c032d..813f0ee9 100644 --- a/backend/app/services/in_transit_transfer/chat_actions.py +++ b/backend/app/services/in_transit_transfer/chat_actions.py @@ -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( diff --git a/backend/app/services/in_transit_transfer/concurrency.py b/backend/app/services/in_transit_transfer/concurrency.py index c28b41dc..522275e7 100644 --- a/backend/app/services/in_transit_transfer/concurrency.py +++ b/backend/app/services/in_transit_transfer/concurrency.py @@ -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" diff --git a/backend/app/services/in_transit_transfer/contracts.py b/backend/app/services/in_transit_transfer/contracts.py index 2f343cdc..562fb295 100644 --- a/backend/app/services/in_transit_transfer/contracts.py +++ b/backend/app/services/in_transit_transfer/contracts.py @@ -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) diff --git a/backend/app/services/in_transit_transfer/date_policy.py b/backend/app/services/in_transit_transfer/date_policy.py index b4a71f7b..e32f969f 100644 --- a/backend/app/services/in_transit_transfer/date_policy.py +++ b/backend/app/services/in_transit_transfer/date_policy.py @@ -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: 当前业务日期。 diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py index c17d3c49..43e19b4d 100644 --- a/backend/app/services/in_transit_transfer/deps.py +++ b/backend/app/services/in_transit_transfer/deps.py @@ -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() diff --git a/backend/app/services/in_transit_transfer/excel_export.py b/backend/app/services/in_transit_transfer/excel_export.py index bada4c56..0bf7dfb5 100644 --- a/backend/app/services/in_transit_transfer/excel_export.py +++ b/backend/app/services/in_transit_transfer/excel_export.py @@ -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, diff --git a/backend/app/services/in_transit_transfer/execution_service.py b/backend/app/services/in_transit_transfer/execution_service.py index 051a56a6..6ed0cc54 100644 --- a/backend/app/services/in_transit_transfer/execution_service.py +++ b/backend/app/services/in_transit_transfer/execution_service.py @@ -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, diff --git a/backend/app/services/in_transit_transfer/file_parser.py b/backend/app/services/in_transit_transfer/file_parser.py index a65f0de4..7a8d46cc 100644 --- a/backend/app/services/in_transit_transfer/file_parser.py +++ b/backend/app/services/in_transit_transfer/file_parser.py @@ -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()) diff --git a/backend/app/services/in_transit_transfer/file_preparation.py b/backend/app/services/in_transit_transfer/file_preparation.py index ddeb0bfa..61050c95 100644 --- a/backend/app/services/in_transit_transfer/file_preparation.py +++ b/backend/app/services/in_transit_transfer/file_preparation.py @@ -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"): diff --git a/backend/app/services/in_transit_transfer/manual_close_service.py b/backend/app/services/in_transit_transfer/manual_close_service.py index 2f6e9dfb..f60ee7fb 100644 --- a/backend/app/services/in_transit_transfer/manual_close_service.py +++ b/backend/app/services/in_transit_transfer/manual_close_service.py @@ -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} diff --git a/backend/app/services/in_transit_transfer/precheck_service.py b/backend/app/services/in_transit_transfer/matching_service.py similarity index 58% rename from backend/app/services/in_transit_transfer/precheck_service.py rename to backend/app/services/in_transit_transfer/matching_service.py index 030cfbe9..e07fafaa 100644 --- a/backend/app/services/in_transit_transfer/precheck_service.py +++ b/backend/app/services/in_transit_transfer/matching_service.py @@ -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)}} diff --git a/backend/app/services/in_transit_transfer/movement_contract.py b/backend/app/services/in_transit_transfer/movement_contract.py index 1558e3fb..24a5403d 100644 --- a/backend/app/services/in_transit_transfer/movement_contract.py +++ b/backend/app/services/in_transit_transfer/movement_contract.py @@ -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), diff --git a/backend/app/services/in_transit_transfer/orchestrator.py b/backend/app/services/in_transit_transfer/orchestrator.py index ba3918c4..660849d8 100644 --- a/backend/app/services/in_transit_transfer/orchestrator.py +++ b/backend/app/services/in_transit_transfer/orchestrator.py @@ -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 diff --git a/backend/app/services/in_transit_transfer/receipt_file_gate.py b/backend/app/services/in_transit_transfer/receipt_file_gate.py index 601831e9..7602ec74 100644 --- a/backend/app/services/in_transit_transfer/receipt_file_gate.py +++ b/backend/app/services/in_transit_transfer/receipt_file_gate.py @@ -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: diff --git a/backend/app/services/in_transit_transfer/recovery.py b/backend/app/services/in_transit_transfer/recovery.py index 2eafd737..8c15145b 100644 --- a/backend/app/services/in_transit_transfer/recovery.py +++ b/backend/app/services/in_transit_transfer/recovery.py @@ -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 diff --git a/backend/app/services/in_transit_transfer/recovery_service.py b/backend/app/services/in_transit_transfer/recovery_service.py index 5a4db7ac..e852396c 100644 --- a/backend/app/services/in_transit_transfer/recovery_service.py +++ b/backend/app/services/in_transit_transfer/recovery_service.py @@ -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 diff --git a/backend/app/services/in_transit_transfer/retry_service.py b/backend/app/services/in_transit_transfer/retry_service.py index b25a37db..6c5ff725 100644 --- a/backend/app/services/in_transit_transfer/retry_service.py +++ b/backend/app/services/in_transit_transfer/retry_service.py @@ -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} diff --git a/backend/app/services/in_transit_transfer/serializers.py b/backend/app/services/in_transit_transfer/serializers.py index 3d8a8d10..45349ba2 100644 --- a/backend/app/services/in_transit_transfer/serializers.py +++ b/backend/app/services/in_transit_transfer/serializers.py @@ -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"]], diff --git a/backend/app/services/in_transit_transfer/source_file_status.py b/backend/app/services/in_transit_transfer/source_file_status.py index 04c1251a..fb3616a9 100644 --- a/backend/app/services/in_transit_transfer/source_file_status.py +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -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: diff --git a/backend/app/services/in_transit_transfer/source_job_service.py b/backend/app/services/in_transit_transfer/source_job_service.py index 16a091f0..459d4fdb 100644 --- a/backend/app/services/in_transit_transfer/source_job_service.py +++ b/backend/app/services/in_transit_transfer/source_job_service.py @@ -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', ) diff --git a/backend/app/services/in_transit_transfer/status.py b/backend/app/services/in_transit_transfer/status.py index 65a1fd52..c2ce9c50 100644 --- a/backend/app/services/in_transit_transfer/status.py +++ b/backend/app/services/in_transit_transfer/status.py @@ -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, diff --git a/backend/app/services/in_transit_transfer/transfer_type.py b/backend/app/services/in_transit_transfer/transfer_type.py index 2234c1ec..b557e26b 100644 --- a/backend/app/services/in_transit_transfer/transfer_type.py +++ b/backend/app/services/in_transit_transfer/transfer_type.py @@ -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: diff --git a/backend/app/services/integration_connector/mapping.py b/backend/app/services/integration_connector/mapping.py index 2736a28a..30929df6 100644 --- a/backend/app/services/integration_connector/mapping.py +++ b/backend/app/services/integration_connector/mapping.py @@ -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 diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index bbc889e9..ff54b90d 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -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 {} diff --git a/backend/migrations/versions/rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py b/backend/migrations/versions/rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py new file mode 100644 index 00000000..1f48adfe --- /dev/null +++ b/backend/migrations/versions/rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py @@ -0,0 +1,245 @@ +"""在途调拨术语重构:precheck → match(表/列/约束/状态值全量改名) + +Revision ID: rn1a2b3c4d5e6 +Revises: 43a8179cdd88 +Create Date: 2026-09-23 22:30:00.000000 + +用途:与代码术语重构(precheck→match,中文「匹配」)配套的存储层改造—— + 1) 表改名:transfer_prechecks → transfer_matchings。 + 2) 列改名:transfer_matchings.precheck_no→matching_no、precheck_hash→matching_hash; + transfer_invoice_items.precheck_id→matching_id;transfer_audit_events.precheck_no→matching_no; + transfer_matchings.status server_default 'prechecking'→'matching'。 + 3) 枚举值刷写:transfer_matchings / transfer_runs / transfer_source_jobs / + transfer_invoice_items 四表 status 'prechecking'→'matching'; + transfer_attempts.kind 'precheck'→'match'。 + 4) 约束/索引替换:uq/ck 旧名 drop 后按新名与新增值列表重建 + (uq_transfer_matchings_matching_no、ck_transfer_matchings_status、 + uq_transfer_invoice_items_matching_grain、各表 ck_*_status、ck_transfer_attempts_kind); + 索引 ix_transfer_prechecks_run_status/business_date 改名。 +依赖:43a8179cdd88 为上一 head(模块未上线,无历史数据兼容包袱,直改新值)。 +逻辑:先改表名 → drop 旧名约束 → 刷历史行数据(避免被旧 CHECK 拦截)→ 列改名 → + 建新名约束/索引;约束与列经 batch 兼容 SQLite(batch 在 PG 上渲染为原生 ALTER), + 索引用独立 DROP/CREATE(两种库均支持);downgrade 全量对称回滚。 +""" + +from alembic import op +import sqlalchemy as sa + +revision = 'rn1a2b3c4d5e6' +down_revision = '43a8179cdd88' +branch_labels = None +depends_on = None + +# 13 状态中仅 'prechecking'→'matching' 更名,其余 12 个值不动。 +_OLD_MATCH_STATUSES = ( + 'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'failed', 'cancelled', 'expired', +) +_NEW_MATCH_STATUSES = ( + 'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing', + 'success', 'failed', 'cancelled', 'expired', +) +_OLD_ITEM_STATUSES = ( + 'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', + 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', +) +_NEW_ITEM_STATUSES = ( + 'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing', + 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', + 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', +) +_OLD_RUN_STATUSES = ( + 'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing', + 'success', 'partial_failed', 'failed', 'cancelled', +) +_NEW_RUN_STATUSES = ( + 'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing', + 'success', 'partial_failed', 'failed', 'cancelled', +) +_OLD_SOURCE_JOB_STATUSES = ( + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', +) +_NEW_SOURCE_JOB_STATUSES = ( + 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', + 'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', +) +_OLD_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write') +_NEW_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write') + + +def _repr_list(values) -> str: + return ', '.join(repr(v) for v in values) + + +def upgrade() -> None: + """表改名 → drop 旧约束 → 刷枚举值 → 列改名 → 建新约束/索引。""" + # [STEP 1] 表改名(RENAME 保留旧索引与约束名,需后续逐一替换)。 + op.rename_table('transfer_prechecks', 'transfer_matchings') + + # [STEP 2] drop 旧名索引(独立 DDL,PG/SQLite 均支持)。 + op.drop_index('ix_transfer_prechecks_run_status', table_name='transfer_matchings') + op.drop_index('ix_transfer_prechecks_business_date', table_name='transfer_matchings') + + # [STEP 3] drop 旧名约束(引用旧列名的约束必须先删,列改名后再按新名重建)。 + with op.batch_alter_table('transfer_matchings') as batch: + batch.drop_constraint('uq_transfer_prechecks_precheck_no', type_='unique') + batch.drop_constraint('ck_transfer_prechecks_status', type_='check') + with op.batch_alter_table('transfer_invoice_items') as batch: + batch.drop_constraint('uq_transfer_invoice_items_precheck_grain', type_='unique') + batch.drop_constraint('ck_transfer_invoice_items_status', type_='check') + with op.batch_alter_table('transfer_runs') as batch: + batch.drop_constraint('ck_transfer_runs_status', type_='check') + with op.batch_alter_table('transfer_source_jobs') as batch: + batch.drop_constraint('ck_transfer_source_jobs_status', type_='check') + with op.batch_alter_table('transfer_attempts') as batch: + batch.drop_constraint('ck_transfer_attempts_kind', type_='check') + + # [STEP 4] 历史行数据刷写(先 UPDATE 再建新 CHECK,避免刷写被旧值列表拦截)。 + op.execute("UPDATE transfer_matchings SET status = 'matching' WHERE status = 'prechecking'") + op.execute("UPDATE transfer_runs SET status = 'matching' WHERE status = 'prechecking'") + op.execute("UPDATE transfer_source_jobs SET status = 'matching' WHERE status = 'prechecking'") + op.execute("UPDATE transfer_invoice_items SET status = 'matching' WHERE status = 'prechecking'") + op.execute("UPDATE transfer_attempts SET kind = 'match' WHERE kind = 'precheck'") + + # [STEP 5] 列改名与默认值(batch 兼容 SQLite;PG 渲染为 ALTER COLUMN RENAME/SET DEFAULT)。 + with op.batch_alter_table('transfer_matchings') as batch: + batch.alter_column('precheck_no', new_column_name='matching_no', existing_type=sa.String(length=64)) + batch.alter_column('precheck_hash', new_column_name='matching_hash', existing_type=sa.String(length=128)) + batch.alter_column( + 'status', existing_type=sa.String(length=32), + server_default='matching', existing_server_default='prechecking', + ) + with op.batch_alter_table('transfer_invoice_items') as batch: + batch.alter_column('precheck_id', new_column_name='matching_id', existing_type=sa.Integer()) + with op.batch_alter_table('transfer_audit_events') as batch: + batch.alter_column('precheck_no', new_column_name='matching_no', existing_type=sa.String(length=64)) + + # [STEP 6] 按新名重建约束(值列表换 'matching'/'match')。 + with op.batch_alter_table('transfer_matchings') as batch: + batch.create_unique_constraint( + 'uq_transfer_matchings_matching_no', ['matching_no'], + ) + batch.create_check_constraint( + 'ck_transfer_matchings_status', + f"status IN ({_repr_list(_NEW_MATCH_STATUSES)})", + ) + with op.batch_alter_table('transfer_invoice_items') as batch: + batch.create_unique_constraint( + 'uq_transfer_invoice_items_matching_grain', + ['matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'], + ) + batch.create_check_constraint( + 'ck_transfer_invoice_items_status', + f"status IN ({_repr_list(_NEW_ITEM_STATUSES)})", + ) + with op.batch_alter_table('transfer_runs') as batch: + batch.create_check_constraint( + 'ck_transfer_runs_status', + f"status IN ({_repr_list(_NEW_RUN_STATUSES)})", + ) + with op.batch_alter_table('transfer_source_jobs') as batch: + batch.create_check_constraint( + 'ck_transfer_source_jobs_status', + f"status IN ({_repr_list(_NEW_SOURCE_JOB_STATUSES)})", + ) + with op.batch_alter_table('transfer_attempts') as batch: + batch.create_check_constraint( + 'ck_transfer_attempts_kind', + f"kind IN ({_repr_list(_NEW_ATTEMPT_KINDS)})", + ) + + # [STEP 7] 按新名重建索引。 + op.create_index( + 'ix_transfer_matchings_run_status', 'transfer_matchings', ['run_id', 'status'], + ) + op.create_index( + 'ix_transfer_matchings_business_date', 'transfer_matchings', ['business_date'], + ) + + +def downgrade() -> None: + """对称回滚:drop 新约束/索引 → 刷回旧枚举值 → 列改回 → 旧约束/索引回补 → 表名还原。""" + # [STEP 1] drop 新名索引。 + op.drop_index('ix_transfer_matchings_run_status', table_name='transfer_matchings') + op.drop_index('ix_transfer_matchings_business_date', table_name='transfer_matchings') + + # [STEP 2] drop 新名约束。 + with op.batch_alter_table('transfer_matchings') as batch: + batch.drop_constraint('uq_transfer_matchings_matching_no', type_='unique') + batch.drop_constraint('ck_transfer_matchings_status', type_='check') + with op.batch_alter_table('transfer_invoice_items') as batch: + batch.drop_constraint('uq_transfer_invoice_items_matching_grain', type_='unique') + batch.drop_constraint('ck_transfer_invoice_items_status', type_='check') + with op.batch_alter_table('transfer_runs') as batch: + batch.drop_constraint('ck_transfer_runs_status', type_='check') + with op.batch_alter_table('transfer_source_jobs') as batch: + batch.drop_constraint('ck_transfer_source_jobs_status', type_='check') + with op.batch_alter_table('transfer_attempts') as batch: + batch.drop_constraint('ck_transfer_attempts_kind', type_='check') + + # [STEP 3] 枚举值还原(旧 CHECK 尚未重建,可安全刷写)。 + op.execute("UPDATE transfer_matchings SET status = 'prechecking' WHERE status = 'matching'") + op.execute("UPDATE transfer_runs SET status = 'prechecking' WHERE status = 'matching'") + op.execute("UPDATE transfer_source_jobs SET status = 'prechecking' WHERE status = 'matching'") + op.execute("UPDATE transfer_invoice_items SET status = 'prechecking' WHERE status = 'matching'") + op.execute("UPDATE transfer_attempts SET kind = 'precheck' WHERE kind = 'match'") + + # [STEP 4] 列名与默认值还原。 + with op.batch_alter_table('transfer_matchings') as batch: + batch.alter_column('matching_no', new_column_name='precheck_no', existing_type=sa.String(length=64)) + batch.alter_column('matching_hash', new_column_name='precheck_hash', existing_type=sa.String(length=128)) + batch.alter_column( + 'status', existing_type=sa.String(length=32), + server_default='prechecking', existing_server_default='matching', + ) + with op.batch_alter_table('transfer_invoice_items') as batch: + batch.alter_column('matching_id', new_column_name='precheck_id', existing_type=sa.Integer()) + with op.batch_alter_table('transfer_audit_events') as batch: + batch.alter_column('matching_no', new_column_name='precheck_no', existing_type=sa.String(length=64)) + + # [STEP 5] 旧名约束回补(旧值列表含 'prechecking'/'precheck')。 + with op.batch_alter_table('transfer_matchings') as batch: + batch.create_unique_constraint( + 'uq_transfer_prechecks_precheck_no', ['precheck_no'], + ) + batch.create_check_constraint( + 'ck_transfer_prechecks_status', + f"status IN ({_repr_list(_OLD_MATCH_STATUSES)})", + ) + with op.batch_alter_table('transfer_invoice_items') as batch: + batch.create_unique_constraint( + 'uq_transfer_invoice_items_precheck_grain', + ['precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date'], + ) + batch.create_check_constraint( + 'ck_transfer_invoice_items_status', + f"status IN ({_repr_list(_OLD_ITEM_STATUSES)})", + ) + with op.batch_alter_table('transfer_runs') as batch: + batch.create_check_constraint( + 'ck_transfer_runs_status', + f"status IN ({_repr_list(_OLD_RUN_STATUSES)})", + ) + with op.batch_alter_table('transfer_source_jobs') as batch: + batch.create_check_constraint( + 'ck_transfer_source_jobs_status', + f"status IN ({_repr_list(_OLD_SOURCE_JOB_STATUSES)})", + ) + with op.batch_alter_table('transfer_attempts') as batch: + batch.create_check_constraint( + 'ck_transfer_attempts_kind', + f"kind IN ({_repr_list(_OLD_ATTEMPT_KINDS)})", + ) + + # [STEP 6] 旧名索引回补。 + op.create_index( + 'ix_transfer_prechecks_run_status', 'transfer_matchings', ['run_id', 'status'], + ) + op.create_index( + 'ix_transfer_prechecks_business_date', 'transfer_matchings', ['business_date'], + ) + + # [STEP 7] 表名还原。 + op.rename_table('transfer_matchings', 'transfer_prechecks') diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py index 6d62f746..f1a7c7f8 100644 --- a/backend/tests/api/test_in_transit_transfer_api.py +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -1,7 +1,7 @@ -"""在途调拨预检 API 契约测试(L2,Flask test client)。 +"""在途调拨匹配 API 契约测试(L2,Flask test client)。 -用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与 - GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。 +用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与 + GET /matchings/{id} 进度恢复;无权限 403、未认证 401。 依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。 逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或 in_transit_transfer Agent 授权校验。 @@ -27,11 +27,19 @@ def _jwt_headers(user: User) -> dict: @pytest.fixture def transfer_deps(monkeypatch, dbs_ready_file): - """注入 Fake 预检依赖,并预置可执行库存。""" + """注入 Fake 匹配依赖,预置可执行库存,并把执行文件对账投影替换为 ready(sha=夹具 checksum)。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + + def _resolve(*, source_code: str) -> dict: + # 执行门禁③(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。 + return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64} + + monkeypatch.setattr( + "app.services.in_transit_transfer.execution_service.resolve_source_file_status", _resolve, + ) return deps @@ -87,9 +95,9 @@ def unauthorized_headers(app): return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} -def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps): - """POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。""" - response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ +def test_create_matching_returns_envelope_with_matching_id(app, client, admin_headers, transfer_deps): + """POST /matchings → 201 envelope,data 含 matching_id/hash/计数。""" + response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }) @@ -97,48 +105,48 @@ def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_he body = response.get_json() assert body["success"] is True data = body["data"] - assert data["precheck_id"].startswith("TPC-") - assert data["precheck_hash"].startswith("sha256:") + assert data["matching_id"].startswith("MTG-") + assert data["matching_hash"].startswith("sha256:") assert data["estimated_external_write_count"] == 2 assert body.get("request_id") -def test_create_precheck_requires_authentication(client): +def test_create_matching_requires_authentication(client): """未认证 → 401(envelope error)。""" - response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]}) + response = client.post(f"{API_PREFIX}/matchings", json={"source_codes": ["DBS-AWSBI"]}) assert response.status_code == 401 assert response.get_json()["success"] is False -def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers): +def test_create_matching_forbidden_without_agent_permission(client, unauthorized_headers): """无 in_transit_transfer Agent 权限 → 403。""" - response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={ + response = client.post(f"{API_PREFIX}/matchings", headers=unauthorized_headers, json={ "source_codes": ["DBS-AWSBI"], }) assert response.status_code == 403 assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN" -def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps): - """持有 Agent 权限的仓库管理员可创建预检。""" - response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={ +def test_create_matching_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps): + """持有 Agent 权限的仓库管理员可创建匹配。""" + response = client.post(f"{API_PREFIX}/matchings", headers=warehouse_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }) assert response.status_code == 201 - assert response.get_json()["data"]["precheck_id"] + assert response.get_json()["data"]["matching_id"] -def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps): +def test_create_matching_validates_source_codes(app, client, admin_headers, transfer_deps): """缺少 source_codes → 400 参数错误。""" - response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"}) + response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={"business_date": "2026-08-06"}) assert response.status_code == 400 assert response.get_json()["success"] is False -def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps): +def test_create_matching_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps): """transfer_type 合法值放行;占位类型(类型2/3)与非法值 → 400 fail-closed。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub", @@ -146,7 +154,7 @@ def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, clie assert created.status_code == 201 for bad_type in ("hub_repair_out", "hub_to_hub", "bogus_type"): - response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", "transfer_type": bad_type, @@ -155,36 +163,88 @@ def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, clie assert response.get_json()["success"] is False -def test_restore_precheck_progress(app, client, admin_headers, transfer_deps): - """GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ +def test_restore_matching_progress(app, client, admin_headers, transfer_deps): + """GET /matchings/{id} 恢复匹配进度(Hash/明细一致)。""" + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }).get_json()["data"] - restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers) + restored = client.get(f"{API_PREFIX}/matchings/{created['matching_id']}", headers=admin_headers) assert restored.status_code == 200 body = restored.get_json()["data"] - assert body["summary"]["precheck_hash"] == created["precheck_hash"] + assert body["summary"]["matching_hash"] == created["matching_hash"] assert {item["invoice_no"] for item in body["items"]} == {"HOM-001", "HOX-002"} -def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps): - """未知 precheck → 404。""" - response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers) +def test_restore_unknown_matching_404(app, client, admin_headers, transfer_deps): + """未知 matching → 404。""" + response = client.get(f"{API_PREFIX}/matchings/MTG-NOT-EXIST", headers=admin_headers) assert response.status_code == 404 -def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps): - """执行预检 → 201 run_no;GET run 返回 外部系统 单号聚合结果。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ +def test_executable_items_lists_ready_rows_with_decoration( + app, client, admin_headers, transfer_deps, monkeypatch +): + """可调拨明细:只返回全局 ready 行,行带 item_id/checked_at/stale/file_current。""" + # 行装饰的文件对账在 matching_service 命名空间——与执行门禁③同口径替身。 + monkeypatch.setattr( + "app.services.in_transit_transfer.matching_service.resolve_source_file_status", + lambda *, source_code: {"file_status": "ready", "has_ready_file": True, + "file_no": "REC-TEST", "file_sha256": "d" * 64}, + ) + _create_matching(client, admin_headers) + response = client.get(f"{API_PREFIX}/items/executable", headers=admin_headers) + assert response.status_code == 200 + body = response.get_json()["data"] + assert body["counts"]["executable_count"] == 2 + assert {item["invoice_no"] for item in body["items"]} == {"HOM-001", "HOX-002"} + for item in body["items"]: + assert item["item_id"] > 0 + assert item["stale"] is False + assert item["file_current"] is True + assert item["checked_at"] + + +def test_executable_items_requires_authentication(client): + """未认证 → 401(与模块其余端点同口径)。""" + assert client.get(f"{API_PREFIX}/items/executable").status_code == 401 + + +def _create_matching(client, admin_headers) -> str: + """创建匹配并返回 matching_no。""" + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]}, - ) - assert executed.status_code == 201 + }) + assert created.status_code == 201 + return created.get_json()["data"]["matching_id"] + + +def _ready_item_ids(app) -> list[int]: + """按行执行入参:ready_to_execute 行的真实 item_id(restore 视图同源)。""" + with app.app_context(): + from app.models import TransferInvoiceItem + + rows = ( + TransferInvoiceItem.query.filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + return [row.id for row in rows] + + +def _execute_ready_items(app, client, admin_headers, item_ids=None): + """POST /items/execute 执行 ready 行(缺省全部)。""" + ids = _ready_item_ids(app) if item_ids is None else item_ids + return client.post(f"{API_PREFIX}/items/execute", headers=admin_headers, json={"item_ids": ids}) + + +def test_execute_items_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps): + """按行执行 → 200 run_no;GET run 返回 外部系统 单号聚合结果。""" + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) + assert executed.status_code == 200 + assert executed.get_json()["success"] is True run_no = executed.get_json()["data"]["run_no"] assert run_no.startswith("RUN-") @@ -195,36 +255,27 @@ def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_ assert result["exceptions"] == [] -def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps): - """预检未就绪时执行 → 400 领域错误,不产生 Run。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - with app.app_context(): - from app.models import TransferPrecheck - - precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first() - precheck.status = "prechecking" - db.session.commit() - response = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={"invoice_nos": ["HOM-001"]}, - ) +def test_execute_items_rejects_invalid_ids(app, client, admin_headers, transfer_deps): + """门禁①:不存在/非可执行行 → 400 EXECUTE_ITEMS_INVALID(details 列出 id),不产生 Run。""" + _create_matching(client, admin_headers) + response = _execute_ready_items(app, client, admin_headers, item_ids=[99999]) assert response.status_code == 400 - assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED" + body = response.get_json() + assert body["error"]["code"] == "TRANSFER.EXECUTE_ITEMS_INVALID" + assert body["error"]["details"]["invalid_item_ids"] == [99999] + + +def test_execute_items_requires_item_ids(app, client, admin_headers, transfer_deps): + """缺少 item_ids → 400 参数错误(复用批量操作校验)。""" + response = client.post(f"{API_PREFIX}/items/execute", headers=admin_headers, json={}) + assert response.status_code == 400 + assert response.get_json()["success"] is False def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps): """取消缺少原因 → 400。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={}, - ) + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""}) assert response.status_code == 400 @@ -232,14 +283,8 @@ def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps): def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps): """取消未开始项并保留成功单据。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]}, - ) + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] # 模拟执行中状态:Run 回退 executing,INV-002 尚未开始 with app.app_context(): @@ -260,7 +305,7 @@ def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transf def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps): """人工关闭缺少原因 → 400。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }).get_json()["data"] @@ -278,7 +323,7 @@ def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_ def test_manual_close_item_success(app, client, admin_headers, transfer_deps): """人工关闭成功 → 状态 manually_closed。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }).get_json()["data"] @@ -299,14 +344,8 @@ def test_manual_close_item_success(app, client, admin_headers, transfer_deps): def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps): """下载异常 Excel → 200 xlsx,且记录访问审计。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]}, - ) + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers) assert response.status_code == 200 @@ -321,14 +360,8 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): """下载收料来源文件 → 200(zip),记录访问审计。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]}, - ) + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers) assert response.status_code == 200 @@ -341,15 +374,9 @@ def test_receipt_files_download_records_access_audit(app, transfer_db, client, a def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): - """下载预检冻结的 外部系统 库存表 → 200(csv),记录访问审计。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]}, - ) + """下载匹配冻结的 外部系统 库存表 → 200(csv),记录访问审计。""" + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] response = client.get(f"{API_PREFIX}/runs/{run_no}/external-inventory", headers=admin_headers) assert response.status_code == 200 @@ -364,14 +391,8 @@ def test_erp_inventory_download_records_access_audit(app, transfer_db, client, a def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps): """无权限下载 → 403(越权检查)。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={}, - ) + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files", f"{API_PREFIX}/runs/{run_no}/external-inventory", @@ -380,34 +401,23 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_ assert response.status_code == 403, path -def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps): - """前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。""" - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ - "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", - }).get_json()["data"] - executed = client.post( - f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute", - headers=admin_headers, json={ - "invoice_nos": ["HOM-001"], - "from_warehouse": "FAKE-TRANSIT", - "to_warehouse": "FAKE-HUB", - "quantity": "1", - }, - ) - assert executed.status_code == 201 +def test_execute_items_uses_frozen_snapshot_values(app, transfer_db, client, admin_headers, transfer_deps): + """按行执行只接受 item_ids:来源仓/目标仓/数量一律取服务端冻结快照值(防篡改)。""" + _create_matching(client, admin_headers) + executed = _execute_ready_items(app, client, admin_headers, item_ids=_ready_item_ids(app)[:1]) + assert executed.status_code == 200 run_no = executed.get_json()["data"]["run_no"] run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"] documents = run["result"]["external_documents"] - assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值 + assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非前端可指定值 assert documents[0]["to_warehouse"] == "HUB-CN01" assert documents[0]["total_quantity"] == "1200" def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps): """待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。""" - # 预检含 1 个数量不一致(blocked)项 - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + # 匹配含 1 个数量不一致(blocked)项 + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }).get_json()["data"] @@ -468,7 +478,7 @@ def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch, dbs_ready_file): - """POST /prechecks/{no}/items/requery → 200 envelope,逐票返回重查结果。 + """POST /matchings/{no}/items/requery → 200 envelope,逐票返回重查结果。 [断言意图] 回归防线(2026-09-21):该端点曾引用未定义的 _actor_id 导致 500/SYSTEM.INTERNAL_ERROR;本用例锁定端点在真实鉴权链路下可完整执行, @@ -479,14 +489,14 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch, erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) - created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={ + created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }) - precheck_no = created.get_json()["data"]["precheck_id"] + matching_no = created.get_json()["data"]["matching_id"] response = client.post( - f"{API_PREFIX}/prechecks/{precheck_no}/items/requery", + f"{API_PREFIX}/matchings/{matching_no}/items/requery", headers=admin_headers, json={"invoice_nos": ["HOM-001"]}, ) @@ -494,7 +504,7 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch, body = response.get_json() assert body["success"] is True data = body["data"] - assert data["precheck_no"] == precheck_no + assert data["matching_no"] == matching_no assert data["total"] == 1 result = data["results"][0] assert result["invoice_no"] == "HOM-001" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 99dea960..09bf2989 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -689,7 +689,7 @@ def dbs_ready_file() -> dict: """当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。 rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date), - 与真实仓库 movement_file_repository 产出一致(B5 接线后 run_precheck 按 + 与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按 parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。 """ return { diff --git a/backend/tests/jobs/test_in_transit_transfer_jobs.py b/backend/tests/jobs/test_in_transit_transfer_jobs.py index 16f98135..bd523c8a 100644 --- a/backend/tests/jobs/test_in_transit_transfer_jobs.py +++ b/backend/tests/jobs/test_in_transit_transfer_jobs.py @@ -1,9 +1,9 @@ -"""在途调拨预检 Job Handler 测试(L1)。 +"""在途调拨匹配 Job Handler 测试(L1)。 -用途:验证 in_transit_transfer_precheck JobType 已注册、handler 能驱动 - precheck_service 落库更新预检状态;缺失 precheck 时报错。 +用途:验证 in_transit_transfer_match JobType 已注册、handler 能驱动 + matching_service 落库更新匹配状态;缺失 matching 时报错。 依赖:app fixture、transfer_db、fakes/repo_fakes、jobs.handlers。 -逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 precheck_id。 +逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 matching_id。 """ from __future__ import annotations @@ -14,47 +14,55 @@ import pytest from app import db from app.jobs.registry import get_handler from app.jobs.types import JobType -from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.models import TransferInvoiceItem, TransferMatching, TransferRun +from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps @pytest.fixture def transfer_deps(monkeypatch, dbs_ready_file): - """注入 Fake 依赖并预置库存。""" + """注入 Fake 依赖并预置库存;同时把执行文件对账投影替换为 ready(sha=夹具 checksum)。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) + + def _resolve(*, source_code: str) -> dict: + # 执行门禁③(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。 + return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64} + + monkeypatch.setattr( + "app.services.in_transit_transfer.execution_service.resolve_source_file_status", _resolve, + ) return deps -def test_precheck_job_type_registered(): - """in_transit_transfer_precheck handler 必须注册于 JobType 注册表。""" - handler = get_handler(JobType.TRANSFER_PRECHECK) +def test_matching_job_type_registered(): + """in_transit_transfer_match handler 必须注册于 JobType 注册表。""" + handler = get_handler(JobType.TRANSFER_MATCH) assert handler is not None -def test_precheck_job_handler_runs_and_updates_precheck(transfer_db, dbs_ready_file, transfer_deps): - """handler 执行后预检状态进入 ready_to_execute,明细落库。""" - summary = create_precheck( +def test_matching_job_handler_runs_and_updates_matching(transfer_db, dbs_ready_file, transfer_deps): + """handler 执行后匹配状态进入 ready_to_execute,明细落库。""" + summary = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, ) - handler = get_handler(JobType.TRANSFER_PRECHECK) - handler(None, {"precheck_id": summary.precheck_id}) + handler = get_handler(JobType.TRANSFER_MATCH) + handler(None, {"matching_id": summary.matching_id}) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - assert precheck is not None - assert precheck.status == "ready_to_execute" - assert precheck.precheck_hash.startswith("sha256:") - assert len(precheck.items) == 2 + matching = db.session.query(TransferMatching).filter_by(matching_no=summary.matching_id).first() + assert matching is not None + assert matching.status == "ready_to_execute" + assert matching.matching_hash.startswith("sha256:") + assert len(matching.items) == 2 -def test_precheck_job_handler_missing_precheck_raises(transfer_db): - """缺失 precheck_id → handler 抛 RuntimeError(fail-closed)。""" - handler = get_handler(JobType.TRANSFER_PRECHECK) +def test_matching_job_handler_missing_matching_raises(transfer_db): + """缺失 matching_id → handler 抛 RuntimeError(fail-closed)。""" + handler = get_handler(JobType.TRANSFER_MATCH) with pytest.raises(RuntimeError): - handler(None, {"precheck_id": "TPC-NOT-EXIST"}) + handler(None, {"matching_id": "MTG-NOT-EXIST"}) def test_run_and_item_job_types_registered(): @@ -63,18 +71,18 @@ def test_run_and_item_job_types_registered(): assert get_handler(JobType.TRANSFER_ITEM) is not None -def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer_deps): - """run handler 执行预检并创建成功 Run。""" - summary = create_precheck( +def test_run_job_handler_executes_matching(transfer_db, dbs_ready_file, transfer_deps): + """run handler 执行匹配并创建成功 Run。""" + summary = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, ) handler = get_handler(JobType.TRANSFER_RUN) - handler(None, {"precheck_id": summary.precheck_id}) + handler(None, {"matching_id": summary.matching_id}) from app.models import TransferRun as RunModel run = db.session.query(RunModel).filter( - RunModel.status != "prechecking", + RunModel.status != "matching", ).order_by(RunModel.id.desc()).first() assert run is not None assert run.status == "success" @@ -82,13 +90,17 @@ def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps): """item handler 执行单个 Invoice 写入并置 success。""" - summary = create_precheck( + create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, ) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - from app.services.in_transit_transfer.orchestrator import create_execution_run + from app.services.in_transit_transfer.orchestrator import create_execution_run_for_items - create_execution_run(precheck, deps=transfer_deps, actor_id=None) + ready_items = ( + TransferInvoiceItem.query.filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + create_execution_run_for_items(ready_items, deps=transfer_deps, actor_id=None) item = db.session.query(TransferInvoiceItem).filter_by( invoice_no="HOM-001", ).first() diff --git a/backend/tests/performance/test_in_transit_transfer.py b/backend/tests/performance/test_in_transit_transfer.py index 6be3158a..e0ce36d3 100644 --- a/backend/tests/performance/test_in_transit_transfer.py +++ b/backend/tests/performance/test_in_transit_transfer.py @@ -1,8 +1,8 @@ """在途调拨性能与规模测试(Phase 4,L6 子集)。 -用途:验证大批量 Invoice 预检可完成且不退化(O(n) 汇总),投影读取正常。 -依赖:transfer_db、precheck_service、repo_fakes。 -逻辑:300 行收料文件 → 预检 300 个 Invoice;仅断言正确性,耗时打印参考。 +用途:验证大批量 Invoice 匹配可完成且不退化(O(n) 汇总),投影读取正常。 +依赖:transfer_db、matching_service、repo_fakes。 +逻辑:300 行收料文件 → 匹配 300 个 Invoice;仅断言正确性,耗时打印参考。 """ from __future__ import annotations @@ -11,7 +11,7 @@ import time import pytest -from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck +from app.services.in_transit_transfer.matching_service import create_matching, restore_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps @@ -38,18 +38,18 @@ def _bulk_file(count: int) -> dict: } -def test_bulk_precheck_300_invoices(transfer_db): - """300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。""" +def test_bulk_matching_300_invoices(transfer_db): + """300 Invoice 匹配完成且数量正确;耗时打印参考(不设脆断言)。""" deps, erp, _ = make_transfer_deps(_bulk_file(300)) for index in range(1, 301): # 库存种子按 (料号, 拨出库位, 拨出批号) 三元组与文件行一一对应。 erp.seed_stock(f"MAT-{index:04d}", "DBS-TRANSIT", f"LOT-BULK-{index:04d}", "100") started = time.perf_counter() - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) elapsed = time.perf_counter() - started assert summary.counts.executable_count == 300 assert summary.counts.file_invoice_count == 300 - restored = restore_precheck(summary.precheck_id) + restored = restore_matching(summary.matching_id) assert len(restored["items"]) == 300 - print(f"\n[perf] bulk precheck 300 invoices: {elapsed:.3f}s") + print(f"\n[perf] bulk matching 300 invoices: {elapsed:.3f}s") diff --git a/backend/tests/services/in_transit_transfer/conftest.py b/backend/tests/services/in_transit_transfer/conftest.py index 2233ec65..91526325 100644 --- a/backend/tests/services/in_transit_transfer/conftest.py +++ b/backend/tests/services/in_transit_transfer/conftest.py @@ -37,3 +37,36 @@ def rpa_fake() -> FakeRPA: def wecom_fake() -> FakeWeCom: """FakeWeCom:记录投递事实,可注入附件失败。""" return FakeWeCom() + + +@pytest.fixture +def patch_source_file_status(monkeypatch): + """执行文件对账门禁替身工厂:替换 execution_service 的来源文件状态投影。 + + 用途:execute_items 门禁③按去重来源调 resolve_source_file_status(真实查询 + 收料文件表);单元测试注入替身避免触碰表数据。缺省全部来源投影为 + ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file 行版本戳同源)。 + + Args: + mapping: source_code → sha 映射;值为 None 表示该来源无可用文件 + (file_status=none,触发 FILE_CHANGED);未列出的来源回落 ready/"d"*64。 + """ + READY_SHA = "d" * 64 + + def _patch(mapping: dict[str, str | None] | None = None) -> None: + table = mapping or {} + + def _resolve(*, source_code: str) -> dict: + if source_code in table: + sha = table[source_code] + if sha is None: + return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None} + return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": sha} + return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": READY_SHA} + + monkeypatch.setattr( + "app.services.in_transit_transfer.execution_service.resolve_source_file_status", + _resolve, + ) + + return _patch diff --git a/backend/tests/services/in_transit_transfer/repo_fakes.py b/backend/tests/services/in_transit_transfer/repo_fakes.py index 51cc5eb5..4ecac3e8 100644 --- a/backend/tests/services/in_transit_transfer/repo_fakes.py +++ b/backend/tests/services/in_transit_transfer/repo_fakes.py @@ -1,6 +1,6 @@ """在途调拨测试的仓库/路由/依赖替身。 -用途:为 file_preparation / precheck_service / API / Job 测试提供可注入的 +用途:为 file_preparation / matching_service / API / Job 测试提供可注入的 ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。 依赖:app.services.in_transit_transfer(仅类型)、fakes。 逻辑:所有替身只返回测试注入的值,不触碰真实存储; @@ -10,7 +10,7 @@ from __future__ import annotations from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile -from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps +from app.services.in_transit_transfer.matching_service import RouteMapping, TransferDeps from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA @@ -81,7 +81,7 @@ class FakeRouteResolver: raise RuntimeError("route resolution failed") mapping = self.routes.get(source_code) if mapping is None: - from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError + from app.services.in_transit_transfer.matching_service import RouteNotResolvedError raise RouteNotResolvedError(source_code=source_code) return mapping diff --git a/backend/tests/services/in_transit_transfer/test_archive.py b/backend/tests/services/in_transit_transfer/test_archive.py index 05f169b4..077d55a6 100644 --- a/backend/tests/services/in_transit_transfer/test_archive.py +++ b/backend/tests/services/in_transit_transfer/test_archive.py @@ -51,7 +51,7 @@ def test_archive_snapshot_persists_index_and_audit(transfer_db): data = _sample_data() archive = archive_snapshot( object_type="external_inventory_snapshot", - object_id="TPC-20260806-001", + object_id="MTG-20260806-001", data=data, original_filename="external-inventory-20260806.csv", content_type="text/csv", @@ -64,7 +64,7 @@ def test_archive_snapshot_persists_index_and_audit(transfer_db): assert store.objects # 对象已写入存储 audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first() assert audit is not None - assert audit.aggregate_id == "TPC-20260806-001" + assert audit.aggregate_id == "MTG-20260806-001" def test_verify_archive_hash_ok_and_corruption_detected(transfer_db): diff --git a/backend/tests/services/in_transit_transfer/test_audit.py b/backend/tests/services/in_transit_transfer/test_audit.py index cfad1c8a..91a09440 100644 --- a/backend/tests/services/in_transit_transfer/test_audit.py +++ b/backend/tests/services/in_transit_transfer/test_audit.py @@ -80,7 +80,7 @@ def test_build_event_carries_actor_and_correlation_ids(): aggregate_type="transfer_item", aggregate_id="item-1", run_no="RUN-20260806-001", - precheck_no="TPC-20260806-001", + matching_no="MTG-20260806-001", invoice_no="INV-001", actor_type="user", actor_id="u-42", @@ -89,7 +89,7 @@ def test_build_event_carries_actor_and_correlation_ids(): request_id="req_001", operation_id="op_001", result="success", - before={"status": "prechecking"}, + before={"status": "matching"}, after={"status": "ready_to_execute"}, ) assert event.actor_id == "u-42" diff --git a/backend/tests/services/in_transit_transfer/test_backlog_service.py b/backend/tests/services/in_transit_transfer/test_backlog_service.py index 046f9e62..1e150779 100644 --- a/backend/tests/services/in_transit_transfer/test_backlog_service.py +++ b/backend/tests/services/in_transit_transfer/test_backlog_service.py @@ -1,7 +1,7 @@ """在途调拨历史待处理池与老化测试(Phase 3,L1)。 用途:验证待处理池只收纳可恢复/已关闭/结果未知项,并正确计算 3/5/7 天老化等级。 -依赖:transfer_db、precheck_service、backlog_service、repo_fakes。 +依赖:transfer_db、matching_service、backlog_service、repo_fakes。 逻辑:老化按最近一次 Attempt 或明细更新时间计算;result_unknown 单独高风险展示。 """ @@ -18,16 +18,16 @@ from app.services.in_transit_transfer.backlog_service import ( backlog_summary, list_backlog, ) -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _blocked_precheck(dbs_ready_file): - """构造含数量不一致(blocked)项的预检。""" +def _blocked_matching(dbs_ready_file): + """构造含数量不一致(blocked)项的匹配。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) return summary @@ -44,16 +44,43 @@ def test_aging_level_thresholds(): def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file): """待处理池收纳 blocked_recoverable,排除 success / not_matured。""" - _blocked_precheck(dbs_ready_file) + _blocked_matching(dbs_ready_file) items = list_backlog() invoice_set = {item.invoice_no for item in items} assert "HOM-001" in invoice_set assert "HOX-002" not in invoice_set +def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file): + """排序=收料日期→Invoice→created_at,与重查触碰(updated_at 刷新)无关。 + + [断言意图] 恢复处理/重查会刷新 updated_at(行级新鲜度续期);排序键若用 + updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。 + 业务稳定键下,触碰前后列表顺序完全一致。 + """ + _blocked_matching(dbs_ready_file) # HOM-001(receipt 2026-08-05)与 HOX-002 不进池,构造两笔 blocked + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + # 手工造第二笔 blocked:不同收料日期、更晚创建 + second = TransferInvoiceItem( + matching_id=item.matching_id, source_code=item.source_code, + invoice_no="HOM-002", material_no="MAT-003", material_name="垫片", + receipt_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + receipt_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found", + ) + db.session.add(second) + db.session.commit() + # 用户操作模拟:重查刷新 HOM-002 的 updated_at(变得更"新") + second.updated_at = datetime.utcnow() + db.session.commit() + + invoices = [dto.invoice_no for dto in list_backlog()] + # 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过 + assert invoices == ["HOM-002", "HOM-001"] + + def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file): """老化等级按明细更新日期计算。""" - _blocked_precheck(dbs_ready_file) + _blocked_matching(dbs_ready_file) item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() item.updated_at = datetime.utcnow() - timedelta(days=6) db.session.commit() @@ -65,7 +92,7 @@ def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file): def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file): """汇总包含可恢复/已关闭/未知计数与老化分级。""" - _blocked_precheck(dbs_ready_file) + _blocked_matching(dbs_ready_file) item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() item.status = "manually_closed" item.manually_closed_reason = "线下处理" @@ -73,3 +100,20 @@ def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file): summary = backlog_summary() assert summary.closed_count == 1 assert summary.recoverable_count == 0 + + +def test_list_backlog_exposes_result_code(transfer_db, dbs_ready_file): + """[断言意图] F1(2026-09-23 评审修复):backlog 行透出 result_code, + 前端待处理池才能区分 blocked_file_removed(收料行已从最新文件移除) + 并展示「文件已移除」徽标,否则与普通数量阻断无法区分。""" + _blocked_matching(dbs_ready_file) + item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + item.result_code = "blocked_file_removed" + db.session.commit() + items = list_backlog() + target = next(entry for entry in items if entry.invoice_no == "HOM-001") + assert target.result_code == "blocked_file_removed" + assert target.status == "blocked_recoverable" + # 未打标的结果码为 None(普通阻断行不受影响)。 + others = [entry for entry in items if entry.invoice_no != "HOM-001"] + assert all(entry.result_code is None for entry in others) diff --git a/backend/tests/services/in_transit_transfer/test_batch_actions.py b/backend/tests/services/in_transit_transfer/test_batch_actions.py new file mode 100644 index 00000000..85914a12 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_batch_actions.py @@ -0,0 +1,120 @@ +"""在途调拨批量操作测试(批量重查 / 批量人工关闭,L1)。 + +用途:验证待处理池多选批量操作的按 id 直取、单行隔离、参数门禁与 + 「重查即续新鲜度」(行级 updated_at 续期,执行 TTL 门禁的续期机制)。 +依赖:transfer_db、matching_service、retry_service、manual_close_service、repo_fakes。 +逻辑:批量语义 = 逐行调用既有单行服务,任何单行失败(状态不允许/不存在/异常) + 不影响其余行;id/原因缺失直接拒绝;重查后行 updated_at 必须恢复当前时刻。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.manual_close_service import manual_close_items +from app.services.in_transit_transfer.matching_service import create_matching +from app.services.in_transit_transfer.retry_service import requery_items_by_ids +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _seed(dbs_ready_file): + """构造 1 阻断 + 1 可执行的匹配,返回 (deps, erp, blocked_row)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → blocked + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + return deps, erp, blocked + + +def test_batch_requery_requires_item_ids(): + """空 id 列表直接拒绝。""" + with pytest.raises(ValidationError) as exc_info: + requery_items_by_ids(item_ids=[], deps=None) + assert exc_info.value.code == "TRANSFER.BATCH_ITEMS_REQUIRED" + + +def test_batch_requery_recovers_fixed_stock_and_isolates_missing(transfer_db, dbs_ready_file): + """库存补齐后重查转可执行;不存在的 id 单行报错不阻断。""" + deps, erp, blocked = _seed(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # ERP 已补齐 + + result = requery_items_by_ids(item_ids=[blocked.id, 999999], deps=deps) + + assert result["total"] == 2 + first, second = result["results"] + assert first["ok"] is True and first["status"] == "ready_to_execute" + assert second["ok"] is False and "not found" in second["error"] + + +def test_batch_requery_refreshes_freshness(transfer_db, dbs_ready_file): + """重查即续新鲜度:updated_at 被拨回 11 分钟前(超执行 TTL)的阻断行,重查后恢复到当前时刻。""" + deps, erp, blocked = _seed(dbs_ready_file) + stale_at = datetime.utcnow() - timedelta(minutes=11) + blocked.updated_at = stale_at + db.session.commit() + + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # ERP 已补齐 → 重查 + result = requery_items_by_ids(item_ids=[blocked.id], deps=deps) + + assert result["results"][0]["ok"] is True + db.session.expire(blocked) + # [断言意图] 行级 TTL 门禁的续期机制:重查后行 updated_at 必须恢复到当前 + # 时刻(大于拨回值且距 now < 1 分钟),执行门禁据此放行。 + assert blocked.updated_at > stale_at + assert (datetime.utcnow() - blocked.updated_at).total_seconds() < 60 + + +def test_batch_requery_degrade_path_refreshes_freshness(transfer_db, dbs_ready_file, monkeypatch): + """降级路径(外部查询失败落 blocked)同样续新鲜度:updated_at 恢复到当前时刻。""" + deps, erp, blocked = _seed(dbs_ready_file) + stale_at = datetime.utcnow() - timedelta(minutes=11) + blocked.updated_at = stale_at + db.session.commit() + + def _raise(**kwargs): + raise RuntimeError("external gateway down") + + monkeypatch.setattr(erp, "query_stock", _raise) + result = requery_items_by_ids(item_ids=[blocked.id], deps=deps) + + assert result["results"][0]["ok"] is True + assert result["results"][0]["status"] == "blocked_recoverable" + db.session.expire(blocked) + # [断言意图] 降级也是一次真实评估:外部查询失败落回阻断时同样续期行新鲜度, + # 保证两条重查路径(成功/降级)对执行 TTL 门禁的续期语义一致。 + assert blocked.updated_at > stale_at + assert (datetime.utcnow() - blocked.updated_at).total_seconds() < 60 + + +def test_batch_manual_close_requires_reason(transfer_db, dbs_ready_file): + """原因缺失整批拒绝(沿用单行关闭的 TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)。""" + with pytest.raises(ValidationError): + manual_close_items(item_ids=[1], reason=" ") + + +def test_batch_manual_close_requires_item_ids(transfer_db, dbs_ready_file): + """空 id 列表直接拒绝。""" + with pytest.raises(ValidationError) as exc_info: + manual_close_items(item_ids=[], reason="线下处理") + assert exc_info.value.code == "TRANSFER.BATCH_ITEMS_REQUIRED" + + +def test_batch_manual_close_closes_and_isolates(transfer_db, dbs_ready_file): + """可关闭行成功关闭;终态行(已执行)单行报错不阻断。""" + deps, _erp, blocked = _seed(dbs_ready_file) + success_row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() + success_row.status = "success" # 终态:不可关闭 + db.session.commit() + + result = manual_close_items(item_ids=[blocked.id, success_row.id], reason="线下处理") + + assert result["total"] == 2 + by_id = {entry["item_id"]: entry for entry in result["results"]} + assert by_id[blocked.id]["ok"] is True and by_id[blocked.id]["status"] == "manually_closed" + assert by_id[success_row.id]["ok"] is False and "not closeable" in by_id[success_row.id]["error"] diff --git a/backend/tests/services/in_transit_transfer/test_cancellation.py b/backend/tests/services/in_transit_transfer/test_cancellation.py index 92ddec6a..8675f60f 100644 --- a/backend/tests/services/in_transit_transfer/test_cancellation.py +++ b/backend/tests/services/in_transit_transfer/test_cancellation.py @@ -13,35 +13,42 @@ from app import db from app.core.errors import ValidationError from app.models import TransferInvoiceItem, TransferRun from app.services.in_transit_transfer.cancellation import cancel_run -from app.services.in_transit_transfer.execution_service import execute_precheck -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.execution_service import execute_items +from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _ready_precheck(dbs_ready_file): +def _ready_matching(dbs_ready_file): erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeCapabilityClient"]).FakeCapabilityClient() erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - return deps, summary + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + items = ( + db.session.query(TransferInvoiceItem) + .filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + return deps, items def test_cancel_requires_reason(transfer_db, dbs_ready_file): """取消原因必填;无副作用(不创建执行 Run)。""" - deps, summary = _ready_precheck(dbs_ready_file) + deps, _ = _ready_matching(dbs_ready_file) with pytest.raises(ValidationError): cancel_run(run_no="RUN-X", reason="") - # 仅存在预检关联 Run(prechecking),无执行 Run + # 仅存在匹配关联 Run(matching),无执行 Run runs = db.session.query(TransferRun).all() assert len(runs) == 1 assert runs[0].status != "executing" -def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file): +def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file, patch_source_file_status): """取消只作用于未开始项;已成功单据保留。""" - deps, summary = _ready_precheck(dbs_ready_file) - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + patch_source_file_status() + deps, items = _ready_matching(dbs_ready_file) + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() # 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success run.status = "executing" diff --git a/backend/tests/services/in_transit_transfer/test_chat_actions.py b/backend/tests/services/in_transit_transfer/test_chat_actions.py index 2d5480c8..ceaaf6b6 100644 --- a/backend/tests/services/in_transit_transfer/test_chat_actions.py +++ b/backend/tests/services/in_transit_transfer/test_chat_actions.py @@ -1,7 +1,7 @@ """在途调拨 Chat Action 测试(L2 契约,SQLite 内存库)。 -用途:验证 transfer.precheck / transfer.execute 已注册、agent 权限映射正确、 - stream 产出结构化卡片事件(transfer-precheck / transfer-result)。 +用途:验证 transfer.match / transfer.execute 已注册、agent 权限映射正确、 + stream 产出结构化卡片事件(transfer-match / transfer-result)。 依赖:app fixture、transfer_db、repo_fakes、action_registry、chat_actions、turn_context。 逻辑:直接构造 TurnContext 调用 handler.stream,断言事件载荷与卡片契约。 """ @@ -16,9 +16,9 @@ from app.services.chat.action_schema import TurnInput from app.services.chat.turn_context import TurnContext from app.services.in_transit_transfer.chat_actions import ( ACTION_TRANSFER_EXECUTE, - ACTION_TRANSFER_PRECHECK, + ACTION_TRANSFER_MATCH, TransferExecuteAction, - TransferPrecheckAction, + TransferMatchAction, ) from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps @@ -44,7 +44,7 @@ def _ctx(agent_code: str, action_type: str, payload: dict) -> TurnContext: request_id="req-1", user=_User(), agent=_Agent(agent_code), - input=TurnInput(type="action", display_text="调拨预检", action_type=action_type, payload=payload), + input=TurnInput(type="action", display_text="调拨匹配", action_type=action_type, payload=payload), refs={}, ) @@ -54,58 +54,59 @@ def test_transfer_actions_registered(): ensure_handlers_loaded() assert "transfer." in ACTION_AGENT_CODES assert ACTION_AGENT_CODES["transfer."] == ("in_transit_transfer",) - assert TransferPrecheckAction.action_type == ACTION_TRANSFER_PRECHECK + assert TransferMatchAction.action_type == ACTION_TRANSFER_MATCH assert TransferExecuteAction.action_type == ACTION_TRANSFER_EXECUTE def test_transfer_action_agent_permission_enforced(): """transfer.* 仅允许 in_transit_transfer agent;其他 agent 拒绝。""" ensure_handlers_loaded() - ctx = _ctx("generic", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]}) + ctx = _ctx("generic", ACTION_TRANSFER_MATCH, {"source_codes": ["DBS-AWSBI"]}) with pytest.raises(ForbiddenError): resolve_action_handler(ctx) - allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]}) - assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_PRECHECK + allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_MATCH, {"source_codes": ["DBS-AWSBI"]}) + assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_MATCH -def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch): - """transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。""" +def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch): + """transfer.match 流式产出 transfer-match 卡片(含明细与来源进度)。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) - events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, { + events = list(TransferMatchAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_MATCH, { "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", }))) assert len(events) == 1 event = events[0] assert event.event == "message.completed" - assert event.data["message_type"] == "transfer-precheck" + assert event.data["message_type"] == "transfer-match" payload = event.data["payload"] - assert payload["kind"] == "precheck" + assert payload["kind"] == "match" assert payload["summary"]["estimated_external_write_count"] == 2 assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"} assert payload["sources"][0]["source_code"] == "DBS-AWSBI" -def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch): +def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch, patch_source_file_status): """transfer.execute 流式产出 transfer-result 卡片(按 外部系统 单号聚合)。""" + patch_source_file_status() deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) - # 先跑预检拿 precheck_id - precheck_events = list(TransferPrecheckAction().stream(_ctx( - "in_transit_transfer", ACTION_TRANSFER_PRECHECK, + # 先跑匹配拿 matching_id + matching_events = list(TransferMatchAction().stream(_ctx( + "in_transit_transfer", ACTION_TRANSFER_MATCH, {"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"}, ))) - precheck_id = precheck_events[0].data["payload"]["summary"]["precheck_id"] + matching_id = matching_events[0].data["payload"]["summary"]["matching_id"] execute_events = list(TransferExecuteAction().stream(_ctx( "in_transit_transfer", ACTION_TRANSFER_EXECUTE, - {"precheck_id": precheck_id, "invoice_nos": ["HOM-001", "HOX-002"]}, + {"matching_id": matching_id, "invoice_nos": ["HOM-001", "HOX-002"]}, ))) assert len(execute_events) == 1 payload = execute_events[0].data["payload"] diff --git a/backend/tests/services/in_transit_transfer/test_contracts.py b/backend/tests/services/in_transit_transfer/test_contracts.py index 3ea45510..b9a358a5 100644 --- a/backend/tests/services/in_transit_transfer/test_contracts.py +++ b/backend/tests/services/in_transit_transfer/test_contracts.py @@ -1,6 +1,6 @@ """在途调拨 DTO 与错误码契约测试(L0 纯单元)。 -用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、 +用途:验证匹配 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、 外部系统 单据按单号聚合投影,以及一期冻结错误码完整且唯一。 依赖:app.services.in_transit_transfer.contracts。 逻辑:DTO 为 frozen dataclass,聚合函数按 外部系统 单号分组并统计物料数/总数量。 @@ -15,12 +15,12 @@ import pytest from app.services.in_transit_transfer.contracts import ( KNOWN_TRANSFER_ERROR_CODES, TRANSFER_PERMISSION_DENIED, - TRANSFER_PRECHECK_EXPIRED, + TRANSFER_MATCH_EXPIRED, TRANSFER_QUANTITY_MISMATCH, TRANSFER_RESULT_UNKNOWN, - PrecheckCountsDTO, - PrecheckInvoiceItemDTO, - PrecheckSummaryDTO, + MatchingCountsDTO, + MatchingItemDTO, + MatchingSummaryDTO, aggregate_external_documents, require_known_error_code, ) @@ -35,7 +35,7 @@ EXPECTED_ERROR_CODES = { "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", @@ -55,7 +55,7 @@ def test_error_codes_match_tdd_frozen_list(): def test_require_known_error_code_accepts_frozen_codes(): """冻结错误码可被契约校验接受。""" require_known_error_code(TRANSFER_QUANTITY_MISMATCH) - require_known_error_code(TRANSFER_PRECHECK_EXPIRED) + require_known_error_code(TRANSFER_MATCH_EXPIRED) require_known_error_code(TRANSFER_RESULT_UNKNOWN) require_known_error_code(TRANSFER_PERMISSION_DENIED) @@ -66,37 +66,37 @@ def test_require_known_error_code_rejects_unknown(): require_known_error_code("TRANSFER_NO_SUCH_CODE") -def test_precheck_counts_dto_fields(): - """预检计数 DTO 包含文件内/未成熟/已预检/可执行/阻断五类计数。""" - counts = PrecheckCountsDTO( - file_invoice_count=40, not_matured_count=8, prechecked_count=32, +def test_matching_counts_dto_fields(): + """匹配计数 DTO 包含文件内/未成熟/已匹配/可执行/阻断五类计数。""" + counts = MatchingCountsDTO( + file_invoice_count=40, not_matured_count=8, matched_count=32, executable_count=27, blocked_count=5, ) assert counts.executable_count == 27 assert counts.not_matured_count == 8 -def test_precheck_summary_dto_carries_estimate_and_hash(): - """预检摘要 DTO 必须携带预计调拨数量、预计 外部系统 写入数与预检 Hash。""" - summary = PrecheckSummaryDTO( - precheck_id="TPC-20260806-001", +def test_matching_summary_dto_carries_estimate_and_hash(): + """匹配摘要 DTO 必须携带预计调拨数量、预计 外部系统 写入数与匹配 Hash。""" + summary = MatchingSummaryDTO( + matching_id="MTG-20260806-001", status="ready_to_execute", business_date="2026-08-06", eligible_receipt_date_to="2026-08-05", expires_at="2026-08-06T09:20:00+08:00", - counts=PrecheckCountsDTO(40, 8, 32, 27, 5), + counts=MatchingCountsDTO(40, 8, 32, 27, 5), estimated_transfer_quantity="18460", estimated_external_write_count=27, - precheck_hash="sha256:abc", + matching_hash="sha256:abc", ) assert summary.estimated_transfer_quantity == "18460" assert summary.estimated_external_write_count == 27 - assert summary.precheck_hash.startswith("sha256:") + assert summary.matching_hash.startswith("sha256:") def test_invoice_item_dto_carries_warehouse_and_quantity_pairs(): - """预检明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。""" - item = PrecheckInvoiceItemDTO( + """匹配明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。""" + item = MatchingItemDTO( source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件", specification="A 型 / 24PIN", invoice_no="INV-001", from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"), @@ -111,21 +111,21 @@ def test_invoice_item_dto_carries_warehouse_and_quantity_pairs(): def test_aggregate_external_documents_groups_by_document_no(): """结果页按 外部系统 单号聚合:物料数、调拨总数量、拨出/拨入仓。""" items = [ - PrecheckInvoiceItemDTO( + MatchingItemDTO( source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件", specification="A 型 / 24PIN", invoice_no="INV-001", from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"), to_warehouse="HUB-CN01", to_quantity=Decimal("500"), result="success", external_document_no="TRF-10001", ), - PrecheckInvoiceItemDTO( + MatchingItemDTO( source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件", specification="标准型 / 48V", invoice_no="INV-002", from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"), to_warehouse="HUB-CN01", to_quantity=Decimal("1200"), result="success", external_document_no="TRF-10001", ), - PrecheckInvoiceItemDTO( + MatchingItemDTO( source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组", specification="SZ-8 / IP67", invoice_no="INV-008", from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"), diff --git a/backend/tests/services/in_transit_transfer/test_excel_export.py b/backend/tests/services/in_transit_transfer/test_excel_export.py index c000cc32..16175936 100644 --- a/backend/tests/services/in_transit_transfer/test_excel_export.py +++ b/backend/tests/services/in_transit_transfer/test_excel_export.py @@ -16,33 +16,40 @@ from openpyxl import load_workbook from app import db from app.models import TransferInvoiceItem from app.services.in_transit_transfer.excel_export import EXCEL_SHEET_NAMES, build_exceptions_workbook -from app.services.in_transit_transfer.execution_service import execute_precheck -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.execution_service import execute_items +from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _executed_run(dbs_ready_file): +def _executed_run(dbs_ready_file, patch_source_file_status): """构造含 1 成功 + 1 业务失败(未生成单据)的 Run。""" + patch_source_file_status() deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") erp.write_scenarios["HOM-001"] = "business_failed" - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + items = ( + db.session.query(TransferInvoiceItem) + .filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) return outcome.run_no, deps -def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file): +def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file, patch_source_file_status): """异常 Excel 必须包含规格定义的 7 个 Sheet。""" - run_no, _ = _executed_run(dbs_ready_file) + run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status) data = build_exceptions_workbook(run_no) workbook = load_workbook(io.BytesIO(data)) assert workbook.sheetnames == EXCEL_SHEET_NAMES -def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file): +def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file, patch_source_file_status): """业务失败项进入失败 Sheet,成功项出现在汇总 Sheet。""" - run_no, _ = _executed_run(dbs_ready_file) + run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status) workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) summary_sheet = workbook["执行汇总"] summary_text = _sheet_text(summary_sheet) @@ -52,18 +59,18 @@ def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file): assert "HOM-001" in failed_text -def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file): +def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file, patch_source_file_status): """原始文件追溯 Sheet 保留 Sheet/行号(决策 11)。""" - run_no, _ = _executed_run(dbs_ready_file) + run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status) workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) trace_sheet = workbook["原始文件追溯"] text = _sheet_text(trace_sheet) assert "Receipt" in text and "10" in text -def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file): +def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file, patch_source_file_status): """Secret 明文不得出现在 Excel(密码/Token/密文片段)。""" - run_no, _ = _executed_run(dbs_ready_file) + run_no, _ = _executed_run(dbs_ready_file, patch_source_file_status) workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no))) for sheet in workbook.worksheets: text = _sheet_text(sheet).lower() diff --git a/backend/tests/services/in_transit_transfer/test_execute_items.py b/backend/tests/services/in_transit_transfer/test_execute_items.py new file mode 100644 index 00000000..81d97031 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_execute_items.py @@ -0,0 +1,271 @@ +"""在途调拨按行执行测试(execute_items 三层门禁,L1,SQLite 内存库)。 + +用途:验证按行执行入口的三层门禁(①存在且可执行 ②行级新鲜度 ③文件版本对账, + 失败路径均携带 details 列表且外部系统 写入为 0)、写前复查(库存变化阻断)、 + Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、 + 匹配 scope 执行入口(execute_matching_items:chat/自动排程/Run Job 共用)与 + 按 外部系统 单号投影最终结果。 +依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。 +逻辑:建 ready 行后取 item_ids 直接执行(不再经过匹配确认/hash/expires 门禁); + 文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import TransferAttempt, TransferInvoiceItem, TransferMatching, TransferRun +from app.services.in_transit_transfer.execution_service import ( + execute_items, + execute_matching_items, + get_run, +) +from app.services.in_transit_transfer.matching_service import create_matching +from tests.services.in_transit_transfer.fakes import FakeCapabilityClient +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +# dbs_ready_file 夹具 checksum(行 file_sha256 版本戳与文件对账 ready 投影同源)。 +READY_SHA = "d" * 64 + +# Invoice 号 → 夹具行 (料号, 拨出库位, 拨出批号),用于按票预置账面库存。 +_INVOICE_TUPLES = { + "HOM-001": ("MAT-001", "DBS-TRANSIT", "LOT-10"), + "HOX-002": ("MAT-002", "DBS-TRANSIT", "LOT-20"), +} + + +def _ready_items(dbs_ready_file, *seeds) -> tuple: + """建匹配(原地落 ready 行)并返回 (deps, erp_fake, ready 行列表)。""" + erp = FakeCapabilityClient() + for invoice_no, quantity in seeds: + erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity) + deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + items = ( + TransferInvoiceItem.query.filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + return deps, erp, items + + +def _execution_runs() -> list[TransferRun]: + """查询全部非匹配(执行)Run。""" + return db.session.query(TransferRun).filter(TransferRun.status != "matching").all() + + +def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]: + """按 run_no 加载关联明细(invoice_no → 行)。""" + run = db.session.query(TransferRun).filter_by(run_no=run_no).first() + return { + item.invoice_no: item + for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + } + + +def test_execute_items_writes_and_aggregates(transfer_db, dbs_ready_file, patch_source_file_status): + """ready 行执行 → run_no 生成、ERP 写 Attempt、状态 success、结果按 ERP 单号聚合。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first() + + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) + # Run 终态与单据聚合:两张成功单据(每 Invoice 一张),无未生成单据异常。 + assert outcome.status == "success" + assert outcome.run_no.startswith("RUN-") + assert len(outcome.result.external_documents) == 2 + assert outcome.result.exceptions == () + + # 行落位:全部 success 且携带 ERP 单号;每行恰一次 external_write Attempt。 + linked = _load_items(outcome.run_no) + assert all(item.status == "success" for item in linked.values()) + assert all(item.external_document_no for item in linked.values()) + run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() + attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter( + TransferInvoiceItem.run_id == run.id, + ).all() + assert len([a for a in attempts if a.kind == "external_write"]) == 2 + + # 执行 Run 不绑定匹配:run 无 matching 归属,matching 确认痕迹保持不动。 + assert run.matchings == [] + assert matching.confirmed_at is None + + +def test_execute_items_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file, patch_source_file_status): + """重复 Invoice(原单已过账)→ item duplicate_success + 原单号,不重复建单。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + erp.seed_document("HOX-002", "TRF-OLD-002", posted=True) + + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) + assert outcome.status == "success" + linked = _load_items(outcome.run_no) + assert linked["HOX-002"].status == "duplicate_success" + assert linked["HOX-002"].external_document_no == "TRF-OLD-002" + # 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用。 + assert len(erp.write_calls()) == 2 + + +def test_execute_items_business_failure_does_not_block_others(transfer_db, dbs_ready_file, patch_source_file_status): + """单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + erp.write_scenarios["HOM-001"] = "business_failed" + + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) + assert outcome.status == "partial_failed" + linked = _load_items(outcome.run_no) + assert linked["HOM-001"].status == "blocked_recoverable" + assert linked["HOX-002"].status == "success" + # 异常项进入结果页"未生成单据"区。 + assert any(exc.invoice_no == "HOM-001" for exc in outcome.result.exceptions) + + +def test_execute_items_result_unknown_no_auto_retry(transfer_db, dbs_ready_file, patch_source_file_status): + """result_unknown:状态终态、每 Invoice 写调用仅 1 次(禁止自动重试)。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + erp.set_write_scenario("timeout_after_commit") + + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) + assert outcome.status == "partial_failed" + linked = _load_items(outcome.run_no) + assert all(item.status == "result_unknown" for item in linked.values()) + assert len(erp.write_calls()) == 2 + + +def test_execute_items_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file, patch_source_file_status): + """写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "999") # 匹配后库存变化 + + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) + linked = _load_items(outcome.run_no) + assert linked["HOM-001"].status == "blocked_recoverable" + assert linked["HOX-002"].status == "success" + assert [record.invoice_no for record in erp.write_calls()] == ["HOX-002"] + + +def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_file, patch_source_file_status): + """门禁①:不存在/非 ready_to_execute 的 id → EXECUTE_ITEMS_INVALID(details 列出 id),零写入。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + # 把一行拨为阻断:该 id 与不存在的 id 都属于"不可执行"。 + blocked = items[0] + blocked.status = "blocked_recoverable" + db.session.commit() + bad_ids = [99999, blocked.id] + + with pytest.raises(ValidationError) as excinfo: + execute_items(item_ids=bad_ids, deps=deps) + assert excinfo.value.code == "TRANSFER.EXECUTE_ITEMS_INVALID" + assert sorted(excinfo.value.details["invalid_item_ids"]) == sorted(bad_ids) + assert erp.write_calls() == [] + assert _execution_runs() == [] + + +def test_execute_items_rejects_stale_rows(transfer_db, dbs_ready_file, patch_source_file_status): + """门禁②:行 updated_at 距 now 超过确认 TTL → ITEMS_STALE(details 列出 id),不创建 Run。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + stale_at = datetime.utcnow() - timedelta(minutes=11) # TTL 默认 600s + for item in items: + item.updated_at = stale_at + db.session.commit() + + with pytest.raises(ValidationError) as excinfo: + execute_items(item_ids=[item.id for item in items], deps=deps) + assert excinfo.value.code == "TRANSFER.ITEMS_STALE" + assert sorted(excinfo.value.details["stale_item_ids"]) == sorted(item.id for item in items) + assert erp.write_calls() == [] + assert _execution_runs() == [] + + +def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status): + """门禁③:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。""" + # monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配", + # (重跑匹配会把行原地刷成新版本,无法构造本场景)。 + patch_source_file_status({"DBS-AWSBI": "e" * 64}) + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + + with pytest.raises(ValidationError) as excinfo: + execute_items(item_ids=[item.id for item in items], deps=deps) + assert excinfo.value.code == "TRANSFER.FILE_CHANGED" + assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items) + assert erp.write_calls() == [] + assert _execution_runs() == [] + + +def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status): + """门禁③:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。""" + patch_source_file_status({"DBS-AWSBI": None}) + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + + with pytest.raises(ValidationError) as excinfo: + execute_items(item_ids=[item.id for item in items], deps=deps) + assert excinfo.value.code == "TRANSFER.FILE_CHANGED" + assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items) + assert erp.write_calls() == [] + + +def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status): + """scope 执行入口:invoice_nos 过滤 ready 行 → 只写入选中 Invoice(chat/自动排程共用语义)。""" + patch_source_file_status() + deps, erp, _ = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first() + + outcome = execute_matching_items( + matching_id=matching.matching_no, deps=deps, invoice_nos=["HOM-001"], + ) + assert outcome.status == "success" + assert len(outcome.result.external_documents) == 1 + assert [record.invoice_no for record in erp.write_calls()] == ["HOM-001"] + + +def test_execute_matching_items_unknown_matching_404(transfer_db, dbs_ready_file, patch_source_file_status): + """scope 执行入口:匹配不存在 → NotFoundError(TRANSFER.MATCH_NOT_FOUND)。""" + patch_source_file_status() + deps, _, _ = _ready_items(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) + with pytest.raises(NotFoundError) as excinfo: + execute_matching_items(matching_id="MTG-NOT-EXIST", deps=deps) + assert excinfo.value.code == "TRANSFER.MATCH_NOT_FOUND" + + +def test_get_run_restores_document_projection(transfer_db, dbs_ready_file, patch_source_file_status): + """GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。""" + patch_source_file_status() + deps, erp, items = _ready_items( + dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), + ) + erp.write_scenarios["HOM-001"] = "business_failed" + outcome = execute_items(item_ids=[item.id for item in items], deps=deps) + + restored = get_run(outcome.run_no) + assert restored["run_no"] == outcome.run_no + assert len(restored["result"]["external_documents"]) == 1 + assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"]) diff --git a/backend/tests/services/in_transit_transfer/test_execution_service.py b/backend/tests/services/in_transit_transfer/test_execution_service.py deleted file mode 100644 index 9459e4a6..00000000 --- a/backend/tests/services/in_transit_transfer/test_execution_service.py +++ /dev/null @@ -1,232 +0,0 @@ -"""在途调拨执行服务测试(Phase 2 核心,L1,SQLite 内存库)。 - -用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、 - Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、 - 选择子集执行、重复点击防重与按 外部系统 单号投影最终结果。 -依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。 -逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。 -""" - -from __future__ import annotations - -from datetime import datetime, timedelta - -import pytest - -from app import db -from app.core.errors import AppError -from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun -from app.services.in_transit_transfer.contracts import ( - TRANSFER_CONFIRMATION_REQUIRED, - TRANSFER_PRECHECK_EXPIRED, -) -from app.services.in_transit_transfer.execution_service import execute_precheck, get_run -from app.services.in_transit_transfer.precheck_service import create_precheck -from tests.services.in_transit_transfer.fakes import FakeCapabilityClient -from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps - - -def _ready_precheck(*files: dict, capabilities=None, source_codes=None) -> tuple: - """创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。""" - deps, erp_fake, _ = make_transfer_deps(*files, capabilities=capabilities) - source_codes = source_codes or [files[0]["source_code"]] - summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps) - return deps, erp_fake, summary - - -_INVOICE_TUPLES = { - # dbs_ready_file 汇总键 (料号, 拨出库位, 拨出批号) —— 与夹具行一致。 - "HOM-001": ("MAT-001", "DBS-TRANSIT", "LOT-10"), - "HOX-002": ("MAT-002", "DBS-TRANSIT", "LOT-20"), -} - - -def _erp_with_stock(dbs_ready_file, *seeds) -> FakeCapabilityClient: - """按 Invoice 预置账面库存的 FakeCapabilityClient(发票号映射到夹具三元组)。""" - erp = FakeCapabilityClient() - for invoice_no, quantity in seeds: - material_no, from_warehouse, lot_no = _INVOICE_TUPLES[invoice_no] - erp.seed_stock(material_no, from_warehouse, lot_no, quantity) - return erp - - -def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]: - run = db.session.query(TransferRun).filter_by(run_no=run_no).first() - return { - item.invoice_no: item - for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() - } - - -def test_execute_happy_path(transfer_db, dbs_ready_file): - """两个可执行 Invoice → Run 成功,按 外部系统 单号投影两张单据,Attempt 落库。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert outcome.status == "success" - assert outcome.run_no.startswith("RUN-") - assert len(outcome.result.external_documents) == 2 - assert outcome.result.exceptions == () - - items = _load_items(outcome.run_no) - assert all(item.status == "success" for item in items.values()) - assert all(item.external_document_no for item in items.values()) - run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first() - attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter( - TransferInvoiceItem.run_id == run.id, - ).all() - assert len([a for a in attempts if a.kind == "external_write"]) == 2 - - -def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file): - """重复 Invoice(原单已过账)→ item duplicate_success + 原单号。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - erp.seed_document("HOX-002", "TRF-OLD-002", posted=True) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert outcome.status == "success" - items = _load_items(outcome.run_no) - assert items["HOX-002"].status == "duplicate_success" - assert items["HOX-002"].external_document_no == "TRF-OLD-002" - # 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用 - assert len(erp.write_calls()) == 2 - - -def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file): - """单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - erp.write_scenarios["HOM-001"] = "business_failed" - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert outcome.status == "partial_failed" - items = _load_items(outcome.run_no) - assert items["HOM-001"].status == "blocked_recoverable" - assert items["HOX-002"].status == "success" - # 异常项进入结果页"未生成单据"区 - assert any(exc.invoice_no == "HOM-001" for exc in outcome.result.exceptions) - - -def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file): - """result_unknown:状态终态、每 Invoice 写调用仅 1 次。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - erp.set_write_scenario("timeout_after_commit") - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert outcome.status == "partial_failed" - items = _load_items(outcome.run_no) - assert all(item.status == "result_unknown" for item in items.values()) - # 禁止自动重试:每个 Invoice 写调用恰 1 次 - assert len(erp.write_calls()) == 2 - - -def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file): - """预检未就绪(prechecking)→ 拒绝执行,外部系统 写入为 0。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - precheck.status = "prechecking" - db.session.commit() - - with pytest.raises(AppError) as excinfo: - execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert excinfo.value.code == TRANSFER_CONFIRMATION_REQUIRED - assert erp.write_calls() == [] - - -def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file): - """确认过期(超过 10 分钟)→ 拒绝执行,外部系统 写入为 0。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - precheck.expires_at = datetime.utcnow() - timedelta(seconds=1) - db.session.commit() - - with pytest.raises(AppError) as excinfo: - execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED - assert erp.write_calls() == [] - - -def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file): - """预检快照(数量)变化 → fail-closed,外部系统 写入为 0。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first() - item.receipt_quantity = "999" - db.session.commit() - - with pytest.raises(AppError) as excinfo: - execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED - assert erp.write_calls() == [] - - -def test_execute_selected_subset_only(transfer_db, dbs_ready_file): - """仅选择 INV-001 → 只写入该 Invoice。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - - outcome = execute_precheck( - precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["HOM-001"], - ) - assert outcome.status == "success" - assert len(outcome.result.external_documents) == 1 - assert [record.invoice_no for record in erp.write_calls()] == ["HOM-001"] - - -def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file): - """勾选当天收料项 → 拒绝,外部系统 写入为 0。""" - deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"]) - with pytest.raises(AppError): - execute_precheck( - precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-041"], - ) - assert erp_fake.write_calls() == [] - - -def test_execute_double_click_rejected(transfer_db, dbs_ready_file): - """重复点击执行 → 第二次 409,不创建重复 Run。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - - first = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - with pytest.raises(AppError) as excinfo: - execute_precheck(precheck_id=summary.precheck_id, deps=deps) - assert excinfo.value.http_status == 409 - # 只存在一个执行 Run(其余为预检关联 Run) - execution_runs = db.session.query(TransferRun).filter( - TransferRun.status != "prechecking", - ).count() - assert execution_runs == 1 - assert first.run_no - - -def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file): - """写前复查发现 外部系统 库存变化 → 该项阻断不写,其余项正常。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "999") # 预检后库存变化 - - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - items = _load_items(outcome.run_no) - assert items["HOM-001"].status == "blocked_recoverable" - assert items["HOX-002"].status == "success" - assert [record.invoice_no for record in erp.write_calls()] == ["HOX-002"] - - -def test_get_run_restores_document_projection(transfer_db, dbs_ready_file): - """GET run → 按 外部系统 单号聚合单据 + 未生成单据异常分开展示。""" - erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200")) - erp.write_scenarios["HOM-001"] = "business_failed" - deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp) - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) - - restored = get_run(outcome.run_no) - assert restored["run_no"] == outcome.run_no - assert len(restored["result"]["external_documents"]) == 1 - assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"]) diff --git a/backend/tests/services/in_transit_transfer/test_matching_inplace.py b/backend/tests/services/in_transit_transfer/test_matching_inplace.py new file mode 100644 index 00000000..c344272a --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_matching_inplace.py @@ -0,0 +1,192 @@ +"""行原地刷新与文件版本戳测试(L1,SQLite 内存库)。 + +用途:验证重复匹配对既有 InvoiceItem 行为"原地刷新"(不迁移 matching_id、显式续 + updated_at)、行携带本次评估所用文件的 file_sha256 版本戳,以及文件新版本 + 缺失行时 ready 行被打 blocked_file_removed(blocked 行与无版本戳行不受影响)、 + 最近匹配计数按匹配 scope 实时聚合(不再按行归属)。 +依赖:transfer_db、matching_service、transfer_type、repo_fakes。 +逻辑:经 create_matching 真实落库构造行状态;用"改 checksum/裁剪 rows"模拟文件 + 新版本;版本戳缺失用手工清空 raw_lines_json 的 file_sha256 模拟存量数据。 +""" + +from __future__ import annotations + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.matching_service import ( + _item_evaluated_sha, + create_matching, + scope_item_query, +) +from app.services.in_transit_transfer.transfer_type import invoice_in_scope +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _file_without(dbs_ready_file: dict, doc_no: str, *, checksum: str) -> dict: + """构造"新版本文件":剔除指定单号后剩余行,并更换 checksum。""" + return { + **dbs_ready_file, + "checksum": checksum, + "rows": [row for row in dbs_ready_file["rows"] if row["doc_no"] != doc_no], + } + + +def test_rematching_refreshes_rows_in_place(transfer_db, dbs_ready_file): + """第二次匹配:同一物理行原地刷新(id 不变、matching_id 不变、值更新)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 blocked + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 executable + first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + old_id, old_matching_id, old_updated = row.id, row.matching_id, row.updated_at + + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + + db.session.refresh(row) + # [断言意图] 行不换归属:重复匹配复用同一物理行,matching_id 保持首次创建值, + # 仅业务值与新鲜度(updated_at)被刷新——计数错乱与壳匹配的根源即"迁移行"。 + assert row.id == old_id + assert row.matching_id == old_matching_id + assert row.updated_at > old_updated + # 两份匹配记录都存在(评估留痕)。 + assert first.matching_id != second.matching_id + + +def test_rows_carry_file_sha256_stamp(transfer_db, dbs_ready_file): + """行 raw_lines_json 携带本次评估所用文件的 file_sha256(新建行写入)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + + # [断言意图] 版本戳与 file_snapshot 同源(checksum):Task 2/3 文件对账读取 + # item.raw_lines_json[0].file_sha256,缺失即无法判定行新鲜度。 + for invoice_no in ("HOM-001", "HOX-002"): + row = db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first() + assert row.raw_lines_json, f"{invoice_no} 应有 raw_lines" + assert row.raw_lines_json[0]["file_sha256"] == dbs_ready_file["checksum"] + assert _item_evaluated_sha(row) == dbs_ready_file["checksum"] + + +def test_scope_item_query_follows_matching_scope(transfer_db, dbs_ready_file): + """scope_item_query 按 scope_json(来源+日期区间+类型前缀)圈行,不依赖行归属。""" + from app.models import TransferMatching + + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + summary = create_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + receipt_date_from="2026-08-05", receipt_date_to="2026-08-05", + ) + matching = db.session.query(TransferMatching).filter_by(matching_no=summary.matching_id).first() + + rows = scope_item_query(matching).all() + + # [断言意图] 行的 matching_id 即使不指向本匹配,scope 命中的行也必须被圈入 + # (Task 2 restore 与最近匹配计数共用该口径)。 + assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"} + + +def test_scope_query_sees_same_rows_for_overlapping_matchings(transfer_db, dbs_ready_file): + """重匹配不迁移行:两份匹配按各自 scope 实时圈行,命中同一批行(实时视图语义)。""" + from app.models import TransferMatching + + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # blocked + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable + first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + + # [断言意图] 行不迁移后两份匹配的 scope 都命中同一批活跃行(总数 2、 + # 可执行 1、阻断 1)——匹配卡=范围实时视图,不再出现"旧匹配被掏空"。 + for matching_no in (first.matching_id, second.matching_id): + matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).one() + rows = scope_item_query(matching).all() + assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"} + assert sum(1 for r in rows if r.status == "ready_to_execute") == 1 + assert sum(1 for r in rows if r.status == "blocked_recoverable") == 1 + + +def test_file_removed_marks_ready_rows_blocked(transfer_db, dbs_ready_file): + """文件新版本缺失该行:ready 行打 blocked_file_removed;blocked 行不动。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # HOM-001 → executable + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() + assert hom.status == "ready_to_execute" + + # 新文件版本:内容只剩 HOX-002(HOM-001 消失),checksum 变化。 + new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64) + deps2, erp2, _ = make_transfer_deps(new_file) + erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 仍可执行 + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) + + db.session.refresh(hom) + db.session.refresh(hox) + # [断言意图] 上一版本可执行、新版本消失的行必须停用(否则会按过期数据执行); + # 仍在文件中的行原地刷新后保持可执行,且版本戳更新为本次评估文件。 + assert hom.status == "blocked_recoverable" + assert hom.result_code == "blocked_file_removed" + assert hom.result_message == "receipt row removed from latest file" + assert hox.status == "ready_to_execute" + assert _item_evaluated_sha(hox) == "e" * 64 + + +def test_file_removed_skips_unknown_evaluated_version(transfer_db, dbs_ready_file): + """行上无 file_sha256(历史数据)时不误标 file_removed。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + assert hom.status == "ready_to_execute" + # 模拟存量行:清空 raw_lines_json 的 file_sha256 版本戳。 + hom.raw_lines_json = [ + {key: value for key, value in line.items() if key != "file_sha256"} + for line in (hom.raw_lines_json or []) + ] + db.session.commit() + + new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64) + deps2, _, _ = make_transfer_deps(new_file) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) + + db.session.refresh(hom) + # [断言意图] 无法判定行评估自哪个文件版本时宁可不标(fail-safe): + # 误标会把存量可执行行全部打散成阻断。 + assert hom.status == "ready_to_execute" + assert hom.result_code is None + + +def test_file_removed_skips_blocked_and_out_of_range_rows(transfer_db, dbs_ready_file): + """消失行标记只作用于 ready 行:blocked 行保持原结果;范围外行不受影响。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → 数量不一致 blocked + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + assert hom.status == "blocked_recoverable" + + new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64) + deps2, _, _ = make_transfer_deps(new_file) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) + + db.session.refresh(hom) + # [断言意图] blocked 行已是终局解释(数量不一致),覆盖成 file_removed 会丢失 + # 真实原因——只补 ready 行的"消失"语义。 + assert hom.status == "blocked_recoverable" + assert hom.result_code == "blocked_quantity_mismatch" + + +def test_invoice_in_scope_predicate(): + """invoice_in_scope:类型 1 按 HOM/HOX/WTP 前缀(大小写不敏感),占位类型恒 False。""" + assert invoice_in_scope("HOM-001", "in_transit_to_hub") is True + assert invoice_in_scope("hox-002", "in_transit_to_hub") is True + assert invoice_in_scope("WTP-008", None) is True # 缺省回落类型 1 + assert invoice_in_scope("INV-9", "in_transit_to_hub") is False + assert invoice_in_scope("", "in_transit_to_hub") is False + # [断言意图] 占位类型(规则未启用)必须返回 False:scope 查询不得圈入任何行。 + assert invoice_in_scope("HOM-001", "hub_repair_out") is False diff --git a/backend/tests/services/in_transit_transfer/test_precheck_service.py b/backend/tests/services/in_transit_transfer/test_matching_service.py similarity index 80% rename from backend/tests/services/in_transit_transfer/test_precheck_service.py rename to backend/tests/services/in_transit_transfer/test_matching_service.py index d08ee9fc..dc00839f 100644 --- a/backend/tests/services/in_transit_transfer/test_precheck_service.py +++ b/backend/tests/services/in_transit_transfer/test_matching_service.py @@ -1,9 +1,9 @@ -"""在途调拨预检服务测试(L1,SQLite 内存库)。 +"""在途调拨匹配服务测试(L1,SQLite 内存库)。 用途:验证 D+1 过滤(当天收料 外部系统 调用=0)、严格数量匹配、来源隔离、 - 预检快照 Hash 稳定、缺文件等待与进度恢复。 -依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。 -逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck), + 匹配快照 Hash 稳定、缺文件等待与进度恢复。 +依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。 +逻辑:全部经真实 ORM 落库(create_matching/restore_matching), 外部依赖注入 Fake 替身。 """ @@ -12,12 +12,12 @@ from __future__ import annotations import pytest from app.core.errors import ValidationError -from app.services.in_transit_transfer.precheck_service import ( +from app.services.in_transit_transfer.matching_service import ( RouteMapping, TransferDeps, - create_precheck, - restore_precheck, - run_precheck, + create_matching, + restore_matching, + run_matching, ) from tests.services.in_transit_transfer.assertions import assert_erp_calls from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA @@ -38,7 +38,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) ]: erp.seed_stock(material, warehouse, lot, qty) - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, ) summary = result.summary @@ -46,7 +46,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) assert summary.counts.not_matured_count == 0 assert summary.counts.blocked_count == 0 assert summary.status == "ready_to_execute" - assert summary.precheck_hash.startswith("sha256:") + assert summary.matching_hash.startswith("sha256:") assert summary.estimated_external_write_count == 3 # 明细 DTO 决策 6/7:拨出/拨入仓库与数量对 items = {item.invoice_no: item for item in result.items} @@ -59,7 +59,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file): """当天收料 → not_matured,外部系统 调用次数为 0。""" deps, erp, _ = _deps(same_day_receipt_file) - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, ) assert result.summary.counts.not_matured_count == 1 @@ -73,7 +73,7 @@ def test_quantity_mismatch_blocked_no_write(dbs_ready_file): deps, erp, _ = _deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, ) items = {item.invoice_no: item for item in result.items} @@ -87,7 +87,7 @@ def test_erp_inventory_not_found_blocked(dbs_ready_file): """外部系统 无库存 → blocked_inventory_not_found。""" deps, erp, _ = _deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # INV-002 无库存 - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, ) items = {item.invoice_no: item for item in result.items} @@ -98,11 +98,11 @@ def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file): """外部系统 网关故障(绑定缺失/连接失败等非超时异常)→ 单据级阻断,不得炸掉整个来源。""" deps, erp, _ = _deps(dbs_ready_file) erp.query_scenario = "error" - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, ) # [断言意图] 外部系统 基础设施故障必须降级为逐票 blocked_external_query_failed: - # 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、预检全 0。 + # 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、匹配全 0。 assert result.sources[0].stage == "file_ready" assert result.items and all(item.result == "blocked_external_query_failed" for item in result.items) assert all("query_inventory" in item.reason for item in result.items) @@ -112,7 +112,7 @@ def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file): def test_missing_file_waits_without_erp(): """缺文件 → 来源阶段 waiting_rpa_callback,无 外部系统 调用。""" deps, erp, _ = _deps() - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, ) assert result.sources[0].stage == "waiting_rpa_callback" @@ -121,11 +121,11 @@ def test_missing_file_waits_without_erp(): def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file): - """DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 预检(来源隔离)。""" + """DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 匹配(来源隔离)。""" deps, erp, rpa = _deps(crane_ready_file) rpa.fail_on.add("DBS-AWSBI") erp.seed_stock("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600") - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, ) by_source = {stage.source_code: stage for stage in result.sources} @@ -136,27 +136,27 @@ def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file): def test_snapshot_hash_is_stable(dbs_ready_file): - """相同输入两次预检 → 预检 Hash 一致(可审计复算)。""" + """相同输入两次匹配 → 匹配 Hash 一致(可审计复算)。""" deps, erp, _ = _deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - first = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - second = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - assert first.summary.precheck_hash == second.summary.precheck_hash + first = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + second = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + assert first.summary.matching_hash == second.summary.matching_hash -def test_create_and_restore_precheck(transfer_db, dbs_ready_file): - """create_precheck 落库后 restore_precheck 可完整恢复进度与明细。""" +def test_create_and_restore_matching(transfer_db, dbs_ready_file): + """create_matching 落库后 restore_matching 可完整恢复进度与明细。""" deps, erp, _ = _deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck( + summary = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, ) - assert summary.precheck_id.startswith("TPC-") - restored = restore_precheck(summary.precheck_id) - assert restored["summary"].precheck_hash == summary.precheck_hash + assert summary.matching_id.startswith("MTG-") + restored = restore_matching(summary.matching_id) + assert restored["summary"].matching_hash == summary.matching_hash assert restored["summary"].status == summary.status restored_items = {item.invoice_no: item for item in restored["items"]} assert set(restored_items) == {"HOM-001", "HOX-002"} @@ -170,7 +170,7 @@ def test_create_and_restore_precheck(transfer_db, dbs_ready_file): def test_parse_failure_persists_source_error_visible_on_restore(transfer_db): - """解析失败 → 来源级 error 落库并经 restore 透出(预检全 0 复发防线)。 + """解析失败 → 来源级 error 落库并经 restore 透出(匹配全 0 复发防线)。 [断言意图] CRANE 实况回归(2026-09-21):行缺 doc_no(别名覆盖症状)时 整文件 ReceiptFileSchemaError;失败事实必须持久化到 source_job,恢复后 @@ -189,11 +189,11 @@ def test_parse_failure_persists_source_error_visible_on_restore(transfer_db): }, routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) - summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) assert summary.status == "file_pending" assert summary.counts.file_invoice_count == 0 - restored = restore_precheck(summary.precheck_id) + restored = restore_matching(summary.matching_id) source = next(s for s in restored["sources"] if s.source_code == "DSV360_AWSDU") # [断言意图] 失败原因跨刷新可见:stage=failed + error_code/message 非空。 assert source.stage == "failed" @@ -201,25 +201,30 @@ def test_parse_failure_persists_source_error_visible_on_restore(transfer_db): assert source.error_message -def test_repeated_precheck_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file): - """同一数据重复预检 → 不新增异常行,原地刷新并挂到最新预检(累加缺陷回归防线)。""" - from app.models import TransferInvoiceItem, TransferPrecheck +def test_repeated_matching_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file): + """同一数据重复匹配 → 不新增行,既有行原地刷新且归属不变(累加缺陷回归防线)。""" + from app.models import TransferInvoiceItem, TransferMatching deps, erp, _ = _deps(dbs_ready_file) erp.query_scenario = "error" # 全部阻断:正是此前不断累加"可恢复异常"的场景 - create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) first_count = TransferInvoiceItem.query.count() assert first_count == 2 + first_matching = TransferMatching.query.order_by(TransferMatching.id.asc()).first() + old_updated = {row.id: row.updated_at for row in TransferInvoiceItem.query.all()} - # [断言意图] 第二次相同预检必须复用既有行(不出现 2×116 式累加),并挂到最新预检。 - create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + # [断言意图] 第二次相同匹配必须复用既有行(不出现 2×116 式累加),且行归属 + # 不变(原地刷新语义,matching_id 不改写到最新匹配)、新鲜度被显式续期。 + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) assert TransferInvoiceItem.query.count() == first_count - latest_precheck_id = TransferPrecheck.query.order_by(TransferPrecheck.id.desc()).first().id - assert all(row.precheck_id == latest_precheck_id for row in TransferInvoiceItem.query.all()) + assert TransferMatching.query.count() == 2 # 匹配记录照常逐次留痕 + for row in TransferInvoiceItem.query.all(): + assert row.matching_id == first_matching.id + assert row.updated_at > old_updated[row.id] def test_same_lot_multiple_materials_persist_without_conflict(transfer_db): - """同一批号(ASN)跨料号 → 按新聚合粒度拆分多行落库,不再撞 (预检,单号) 唯一约束。""" + """同一批号(ASN)跨料号 → 按新聚合粒度拆分多行落库,不再撞 (匹配,单号) 唯一约束。""" deps, erp_fake, _rpa = make_transfer_deps( { "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", @@ -236,23 +241,23 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db): routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) erp_fake.query_scenario = "error" - summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) - # [断言意图] 新唯一粒度 = (预检,来源,单号,料号,日期):同批号多料号必须共存于同一预检。 + summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + # [断言意图] 新唯一粒度 = (匹配,来源,单号,料号,日期):同批号多料号必须共存于同一匹配。 assert summary.counts.file_invoice_count == 2 def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file): - """收料日期范围作为预检查询范围:范围外发票不进入明细。""" + """收料日期范围作为匹配查询范围:范围外发票不进入明细。""" deps, erp, _ = _deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck( + summary = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, receipt_date_from="2026-08-05", receipt_date_to="2026-08-05", ) assert summary.counts.file_invoice_count == 2 - empty = create_precheck( + empty = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, receipt_date_from="2026-08-01", receipt_date_to="2026-08-04", ) @@ -265,7 +270,7 @@ def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file): deps, erp, _ = _deps(dbs_ready_file) with pytest.raises(ValidationError) as exc_info: - create_precheck( + create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, receipt_date_from="2026-08-04", receipt_date_to="2026-08-06", ) @@ -282,7 +287,7 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file): route_resolver=FakeRouteResolver(routes={}), capabilities=erp, ) - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, ) by_source = {stage.source_code: stage for stage in result.sources} @@ -290,10 +295,10 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file): assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断 -def test_run_precheck_consumes_movement_field_rows(app): - """run_precheck 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。""" +def test_run_matching_consumes_movement_field_rows(app): + """run_matching 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。""" # [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键; - # 预检应正确产出 executable 明细而非 ReceiptFileSchemaError + # 匹配应正确产出 executable 明细而非 ReceiptFileSchemaError # 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。 deps, erp_fake, _rpa = make_transfer_deps( { @@ -308,7 +313,7 @@ def test_run_precheck_consumes_movement_field_rows(app): routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) # 按 (料号, 拨出库位, 拨出批号) 维护账面库存 - result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) item = next(i for i in result.items if i.invoice_no == "WTP-1") assert item.result == "executable" @@ -318,7 +323,7 @@ def test_run_precheck_consumes_movement_field_rows(app): def test_type1_filters_invoices_by_prefix(app): """类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的票,范围外静默排除。""" # [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行; - # HOM/HOX/WTP 前缀票正常走完整预检(成熟 + 外部系统 匹配)。 + # HOM/HOX/WTP 前缀票正常走完整匹配(成熟 + 外部系统 匹配)。 deps, erp_fake, _rpa = make_transfer_deps( { "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", @@ -339,15 +344,15 @@ def test_type1_filters_invoices_by_prefix(app): ) erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) erp_fake.seed_stock("M3", "WH1", "LOT-3", 7) - result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) invoice_nos = {item.invoice_no for item in result.items} assert invoice_nos == {"HOM-100", "WTP-300"} assert all(item.result == "executable" for item in result.items) assert result.summary.counts.executable_count == 2 -def test_create_precheck_persists_transfer_type_on_run_and_scope(transfer_db): - """create_precheck 落库 Run.transfer_type 与 Precheck.scope_json 类型口径。""" +def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db): + """create_matching 落库 Run.transfer_type 与 Matching.scope_json 类型口径。""" deps, erp_fake, _rpa = make_transfer_deps( { "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", @@ -361,21 +366,21 @@ def test_create_precheck_persists_transfer_type_on_run_and_scope(transfer_db): routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) - summary = create_precheck( + summary = create_matching( source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="in_transit_to_hub", ) - from app.models import TransferPrecheck, TransferRun + from app.models import TransferMatching, TransferRun - run = TransferRun.query.filter_by(run_no=summary.precheck_id and TransferRun.query.first().run_no).first() - precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first() + run = TransferRun.query.filter_by(run_no=summary.matching_id and TransferRun.query.first().run_no).first() + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first() assert run is not None and run.transfer_type == "in_transit_to_hub" - scope = precheck.scope_json + scope = matching.scope_json assert scope["transfer_type"] == "in_transit_to_hub" assert scope["transfer_type_scope"] == "invoice_prefix:hom+hox+wtp" -def test_create_precheck_defaults_transfer_type_when_omitted(transfer_db): +def test_create_matching_defaults_transfer_type_when_omitted(transfer_db): """缺省 transfer_type → 类型 1(存量调用方/排程行为不变但纳入前缀过滤)。""" deps, erp_fake, _rpa = make_transfer_deps( { @@ -390,13 +395,13 @@ def test_create_precheck_defaults_transfer_type_when_omitted(transfer_db): routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) - summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) - from app.models import TransferPrecheck, TransferRun + summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + from app.models import TransferMatching, TransferRun run = TransferRun.query.first() - precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first() + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first() assert run.transfer_type == "in_transit_to_hub" - assert precheck.scope_json["transfer_type"] == "in_transit_to_hub" + assert matching.scope_json["transfer_type"] == "in_transit_to_hub" def test_placeholder_transfer_types_fail_closed(): @@ -411,13 +416,13 @@ def test_placeholder_transfer_types_fail_closed(): }, ) with pytest.raises(ValidationError) as not_supported: - create_precheck( + create_matching( source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="hub_repair_out", ) assert not_supported.value.code == "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED" with pytest.raises(ValidationError) as invalid: - create_precheck( + create_matching( source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="bogus_type", ) diff --git a/backend/tests/services/in_transit_transfer/test_metrics.py b/backend/tests/services/in_transit_transfer/test_metrics.py index b94c4e34..531d4c80 100644 --- a/backend/tests/services/in_transit_transfer/test_metrics.py +++ b/backend/tests/services/in_transit_transfer/test_metrics.py @@ -1,7 +1,7 @@ """在途调拨运营指标测试(Phase 4,L1)。 用途:验证指标聚合(Run/明细状态分布、待处理老化、通知失败数)正确。 -依赖:transfer_db、precheck/execution/metrics、repo_fakes。 +依赖:transfer_db、matching/execution/metrics、repo_fakes。 逻辑:指标由数据库现状投影,便于上线观察板使用。 """ @@ -10,20 +10,25 @@ from __future__ import annotations import pytest from app import db -from app.models import TransferInvoiceItem, TransferRun -from app.services.in_transit_transfer.execution_service import execute_precheck +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.execution_service import execute_items from app.services.in_transit_transfer.metrics import collect_metrics -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file): +def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file, patch_source_file_status): """指标包含 Run 状态分布与明细状态分布。""" + patch_source_file_status() deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - execute_precheck(precheck_id=summary.precheck_id, deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + item_ids = [ + item.id for item in db.session.query(TransferInvoiceItem) + .filter_by(status="ready_to_execute").all() + ] + execute_items(item_ids=item_ids, deps=deps) metrics = collect_metrics() assert metrics["runs"]["success"] >= 1 @@ -35,7 +40,7 @@ def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() item.updated_at = item.updated_at # 保持默认年龄 db.session.commit() diff --git a/backend/tests/services/in_transit_transfer/test_migration_execution.py b/backend/tests/services/in_transit_transfer/test_migration_execution.py index 2f1f4e5a..c18761bd 100644 --- a/backend/tests/services/in_transit_transfer/test_migration_execution.py +++ b/backend/tests/services/in_transit_transfer/test_migration_execution.py @@ -21,6 +21,7 @@ pytestmark = pytest.mark.pure_unit EXPECTED_TABLES = { "transfer_runs", "transfer_source_jobs", + # 历史迁移 it1a2b3c4d5e 建的旧表名(旧 revision 不可改;后续 rn* 迁移再改名)。 "transfer_prechecks", "transfer_invoice_items", "transfer_attempts", diff --git a/backend/tests/services/in_transit_transfer/test_models.py b/backend/tests/services/in_transit_transfer/test_models.py index 15354f3e..a6a7794c 100644 --- a/backend/tests/services/in_transit_transfer/test_models.py +++ b/backend/tests/services/in_transit_transfer/test_models.py @@ -18,13 +18,13 @@ from app.models import ( TransferAttempt, TransferAuditEvent, TransferInvoiceItem, - TransferPrecheck, + TransferMatching, TransferRun, TransferSourceJob, ) TRANSFER_TABLES = { - "transfer_runs", "transfer_source_jobs", "transfer_prechecks", + "transfer_runs", "transfer_source_jobs", "transfer_matchings", "transfer_invoice_items", "transfer_attempts", "transfer_audit_events", "transfer_archives", } @@ -43,7 +43,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db): run_no="RUN-20260806-001", trigger_type="manual", business_date="2026-08-06", - status="prechecking", + status="matching", source_codes_json=["DBS-AWSBI"], counts_json={"file_invoice_count": 3, "executable_count": 2}, ) @@ -56,17 +56,17 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db): source_config_version=5, status="checking_file", ) - precheck = TransferPrecheck( - precheck_no="TPC-20260806-001", + matching = TransferMatching( + matching_no="MTG-20260806-001", run_id=run.id, business_date="2026-08-06", status="ready_to_execute", scope_json={"source_codes": ["DBS-AWSBI"]}, counts_json={"executable_count": 1}, - precheck_hash="sha256:test", + matching_hash="sha256:test", ) item = TransferInvoiceItem( - precheck=precheck, + matching=matching, run_id=run.id, source_code="DBS-AWSBI", invoice_no="INV-001", @@ -81,7 +81,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db): status="ready_to_execute", raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}], ) - transfer_db.session.add_all([source_job, precheck, item]) + transfer_db.session.add_all([source_job, matching, item]) transfer_db.session.flush() attempt = TransferAttempt( @@ -104,22 +104,22 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db): assert loaded_attempt.attempt_no == 1 -def test_invoice_item_unique_per_precheck(transfer_db): - """同一预检内同一 Invoice 只能出现一次(防重复建单底座)。""" - precheck = TransferPrecheck( - precheck_no="TPC-20260806-002", +def test_invoice_item_unique_per_matching(transfer_db): + """同一匹配内同一 Invoice 只能出现一次(防重复建单底座)。""" + matching = TransferMatching( + matching_no="MTG-20260806-002", business_date="2026-08-06", - status="prechecking", + status="matching", scope_json={}, counts_json={}, - precheck_hash="sha256:test2", + matching_hash="sha256:test2", ) - transfer_db.session.add(precheck) + transfer_db.session.add(matching) transfer_db.session.flush() def _item(invoice_no: str) -> TransferInvoiceItem: return TransferInvoiceItem( - precheck_id=precheck.id, + matching_id=matching.id, source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001", @@ -154,14 +154,14 @@ def test_run_no_unique(transfer_db): def test_invoice_item_status_check_constraint(transfer_db): """Invoice 状态必须属于冻结枚举(数据库级门禁兜底)。""" - precheck = TransferPrecheck( - precheck_no="TPC-20260806-003", business_date="2026-08-06", - status="prechecking", scope_json={}, counts_json={}, precheck_hash="x", + matching = TransferMatching( + matching_no="MTG-20260806-003", business_date="2026-08-06", + status="matching", scope_json={}, counts_json={}, matching_hash="x", ) - transfer_db.session.add(precheck) + transfer_db.session.add(matching) transfer_db.session.flush() transfer_db.session.add(TransferInvoiceItem( - precheck_id=precheck.id, source_code="DBS-AWSBI", invoice_no="INV-999", + matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="INV-999", material_no="MAT-9", receipt_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", receipt_quantity="1", external_quantity="1", @@ -198,7 +198,7 @@ def test_archive_roundtrip(transfer_db): archive = TransferArchive( archive_no="ARC-20260806-001", object_type="external_inventory_snapshot", - object_id="TPC-20260806-001", + object_id="MTG-20260806-001", storage_provider="minio", storage_bucket="hxops-transfer", storage_key="transfer/20260806/snapshot.xlsx", diff --git a/backend/tests/services/in_transit_transfer/test_notification.py b/backend/tests/services/in_transit_transfer/test_notification.py index 158c7235..45b67a2a 100644 --- a/backend/tests/services/in_transit_transfer/test_notification.py +++ b/backend/tests/services/in_transit_transfer/test_notification.py @@ -11,26 +11,31 @@ from __future__ import annotations import pytest from app import db -from app.models import TransferRun -from app.services.in_transit_transfer.execution_service import execute_precheck +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.execution_service import execute_items from app.services.in_transit_transfer.notification import notify_run_summary -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.fakes import FakeWeCom from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _executed_run(dbs_ready_file): +def _executed_run(dbs_ready_file, patch_source_file_status): + patch_source_file_status() deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + item_ids = [ + item.id for item in db.session.query(TransferInvoiceItem) + .filter_by(status="ready_to_execute").all() + ] + outcome = execute_items(item_ids=item_ids, deps=deps) return outcome.run_no -def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file): +def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file, patch_source_file_status): """非空 Run → 恰好一条汇总通知;重复调用幂等。""" - run_no = _executed_run(dbs_ready_file) + run_no = _executed_run(dbs_ready_file, patch_source_file_status) wecom = FakeWeCom() first = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1", "u-2"]) assert first["notification_status"] == "success" @@ -42,9 +47,9 @@ def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file): assert run.status == "success" # 外部系统 结果不受影响 -def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file): +def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file, patch_source_file_status): """通知失败 → notification_status=failed,run.status 保持 success。""" - run_no = _executed_run(dbs_ready_file) + run_no = _executed_run(dbs_ready_file, patch_source_file_status) wecom = FakeWeCom() wecom.attach_fail = True result = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"], excel_path="x.xlsx") diff --git a/backend/tests/services/in_transit_transfer/test_orchestrator.py b/backend/tests/services/in_transit_transfer/test_orchestrator.py index 1e9d29ee..6cba772d 100644 --- a/backend/tests/services/in_transit_transfer/test_orchestrator.py +++ b/backend/tests/services/in_transit_transfer/test_orchestrator.py @@ -1,69 +1,96 @@ """在途调拨 Run 编排测试(Phase 2,L1)。 -用途:验证执行 Run 创建(执行中状态、关联预检与明细)、终态收尾与 - 重复创建防护。 -依赖:transfer_db、precheck_service、orchestrator、repo_fakes。 -逻辑:编排层复用 execution_service 落库流程,本文件聚焦 Run 生命周期辅助函数。 +用途:验证按行创建执行 Run(executing 状态、关联选中行、不绑定匹配)、 + 终态收尾与重复关联防护(已关联行跳过)。 +依赖:transfer_db、matching_service、orchestrator、repo_fakes。 +逻辑:编排层接收调用方(execution_service)按 scope 圈定并校验后的行, + 本文件聚焦 Run 生命周期辅助函数。 """ from __future__ import annotations -import pytest - from app import db -from app.core.errors import ConflictError -from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun -from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.models import TransferInvoiceItem, TransferRun +from app.services.in_transit_transfer.orchestrator import ( + create_execution_run_for_items, + finalize_run, +) +from app.services.in_transit_transfer.matching_service import create_matching from app.services.in_transit_transfer.status import TransferRunStatus from tests.services.in_transit_transfer.fakes import FakeCapabilityClient from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _ready_precheck(dbs_ready_file): - """创建已预检 precheck 并返回 (deps, summary)。""" +def _ready_items(dbs_ready_file): + """建匹配(原地落 ready 行)并返回 (deps, ready 行列表)。""" erp = FakeCapabilityClient() erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - return deps, summary + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + items = ( + TransferInvoiceItem.query.filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + return deps, items -def test_create_execution_run_links_items_and_sets_executing(transfer_db, dbs_ready_file): - """create_execution_run 创建 executing Run 并关联可执行明细。""" - deps, summary = _ready_precheck(dbs_ready_file) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() +def test_create_execution_run_for_items_links_items_and_sets_executing(transfer_db, dbs_ready_file): + """create_execution_run_for_items 创建 executing Run 并关联选中明细(不绑定匹配)。""" + deps, items = _ready_items(dbs_ready_file) - run = create_execution_run(precheck, deps=deps, actor_id=None) + run = create_execution_run_for_items(items, deps=deps, actor_id=None) assert run.status == TransferRunStatus.EXECUTING.value - items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() - assert len(items) == 2 - assert all(item.status == "executing" for item in items) + assert run.matchings == [] # 执行 Run 与匹配解耦(matching.run_id 不回写执行 Run) + linked = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + assert len(linked) == 2 + assert all(item.status == "executing" for item in linked) + # Run 来源范围与行计数按选中行聚合。 + assert run.source_codes_json == ["DBS-AWSBI"] + assert run.counts_json["executable_count"] == 2 def test_finalize_run_sets_terminal_status(transfer_db, dbs_ready_file): """finalize_run 按明细终态汇总 Run 状态。""" - deps, summary = _ready_precheck(dbs_ready_file) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - run = create_execution_run(precheck, deps=deps, actor_id=None) + deps, items = _ready_items(dbs_ready_file) + run = create_execution_run_for_items(items, deps=deps, actor_id=None) - items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() - for item in items: + linked = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + for item in linked: item.status = "success" - finalize_run(run, items) + finalize_run(run, linked) assert run.status == TransferRunStatus.SUCCESS.value - for item in items: + for item in linked: item.status = "blocked_recoverable" - finalize_run(run, items) + finalize_run(run, linked) assert run.status == TransferRunStatus.PARTIAL_FAILED.value -def test_create_execution_run_rejects_duplicate(transfer_db, dbs_ready_file): - """已确认的 precheck 不允许重复创建执行 Run。""" - deps, summary = _ready_precheck(dbs_ready_file) - precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first() - create_execution_run(precheck, deps=deps, actor_id=None) - with pytest.raises(ConflictError): - create_execution_run(precheck, deps=deps, actor_id=None) +def test_create_execution_run_for_items_skips_already_linked(transfer_db, dbs_ready_file): + """已关联执行 Run(run_id 非空)的行被跳过:重复调用不重复关联/递增 Attempt 序号。""" + deps, items = _ready_items(dbs_ready_file) + first = create_execution_run_for_items(items, deps=deps, actor_id=None) + attempt_no_before = {item.id: item.attempt_no for item in items} + + second = create_execution_run_for_items(items, deps=deps, actor_id=None) + linked_second = db.session.query(TransferInvoiceItem).filter_by(run_id=second.id).all() + assert linked_second == [] # 全部行已归属首个执行 Run + for item in items: + assert item.run_id == first.id + assert item.attempt_no == attempt_no_before[item.id] + assert second.run_no != first.run_no + + +def test_create_execution_run_for_items_selected_subset(transfer_db, dbs_ready_file): + """selected_item_ids 限定关联范围:仅选中行被置 executing 并计入 Run 计数。""" + deps, items = _ready_items(dbs_ready_file) + selected = {items[0].id} + + run = create_execution_run_for_items(items, deps=deps, actor_id=None, selected_item_ids=selected) + linked = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all() + assert [item.id for item in linked] == [items[0].id] + assert linked[0].status == "executing" + assert items[1].status == "ready_to_execute" + assert items[1].run_id is None diff --git a/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py index 1b6c42eb..33d139da 100644 --- a/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py +++ b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py @@ -3,7 +3,7 @@ 用途:验证调拨 query_inventory 经 CapabilityGateway 接线——网关被调用且入参为 (external_org, targets) 契约、成熟过滤(当天收料不查)、fail-closed (无绑定来源逐票降级但不阻断其他来源)。 -依赖:run_precheck、CapabilityClient、repo_fakes.make_transfer_deps、transports.base。 +依赖:run_matching、CapabilityClient、repo_fakes.make_transfer_deps、transports.base。 逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。 """ @@ -14,7 +14,7 @@ from decimal import Decimal from app.core.errors import AppError from app.services.in_transit_transfer.capability_client import CapabilityClient -from app.services.in_transit_transfer.precheck_service import run_precheck +from app.services.in_transit_transfer.matching_service import run_matching from app.services.integration_connector.errors import BindingNotFoundError from app.services.integration_connector.transports.base import IntegrationCallResult from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps @@ -53,7 +53,7 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file): ("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200", ("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200", }) - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=_cap_deps(dbs_ready_file, gw), run_no="RUN-T", ) @@ -71,7 +71,7 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file): def test_not_matured_not_queried(app, same_day_receipt_file): """当天收料(not_matured)不查外部系统——网关零调用。""" gw = FakeGateway(inventory={}) - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=_cap_deps(same_day_receipt_file, gw), run_no="RUN-T", ) @@ -101,7 +101,7 @@ def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file) deps = replace(deps, capabilities=CapabilityClient(gateway=_SplitGateway())) - result = run_precheck( + result = run_matching( source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, run_no="RUN-T", ) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py index 9d1111bc..1e11e2cc 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -133,7 +133,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path)) outcome = _DefaultRpaTrigger().trigger( - source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file", + source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file", ) assert outcome["ok"] is True # [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger @@ -146,7 +146,7 @@ def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path)) outcome = _DefaultRpaTrigger().trigger( - source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file", + source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file", ) # [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。 assert outcome["ok"] is False diff --git a/backend/tests/services/in_transit_transfer/test_recovery_service.py b/backend/tests/services/in_transit_transfer/test_recovery_service.py index aefec0ce..92a40438 100644 --- a/backend/tests/services/in_transit_transfer/test_recovery_service.py +++ b/backend/tests/services/in_transit_transfer/test_recovery_service.py @@ -1,9 +1,9 @@ """在途调拨每日恢复(待处理池自动复核)测试(Phase 3,L1)。 -用途:验证历史可恢复项下一排程重新预检并创建新 Attempt; +用途:验证历史可恢复项下一排程重新匹配并创建新 Attempt; result_unknown / manually_closed / success 不自动写入。 -依赖:transfer_db、precheck_service、recovery_service、repo_fakes。 -逻辑:恢复 = 重新预检(仅查询/匹配),不写 外部系统;每次恢复新 Attempt。 +依赖:transfer_db、matching_service、recovery_service、repo_fakes。 +逻辑:恢复 = 重新匹配(仅查询/匹配),不写 外部系统;每次恢复新 Attempt。 """ from __future__ import annotations @@ -12,23 +12,23 @@ import pytest from app import db from app.models import TransferAttempt, TransferInvoiceItem -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.matching_service import create_matching from app.services.in_transit_transfer.recovery_service import run_daily_recovery from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _mixed_precheck(dbs_ready_file): - """构造 1 个数量不一致 + 1 个可执行的预检。""" +def _mixed_matching(dbs_ready_file): + """构造 1 个数量不一致 + 1 个可执行的匹配。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) return deps, erp, summary -def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_file): +def test_recovery_rematchings_and_creates_new_attempt(transfer_db, dbs_ready_file): """外部系统 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。""" - deps, erp, summary = _mixed_precheck(dbs_ready_file) + deps, erp, summary = _mixed_matching(dbs_ready_file) item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() assert item.status == "blocked_recoverable" old_attempt_no = item.attempt_no @@ -43,13 +43,13 @@ def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_fil assert refreshed.attempt_no == old_attempt_no + 1 attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all() assert len(attempts) == 1 and attempts[0].kind == "external_query" - # 恢复仅预检,不写 外部系统 + # 恢复仅匹配,不写 外部系统 assert erp.write_calls() == [] def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file): """result_unknown 不自动恢复,也不产生 外部系统 调用。""" - deps, erp, summary = _mixed_precheck(dbs_ready_file) + deps, erp, summary = _mixed_matching(dbs_ready_file) item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() item.status = "result_unknown" db.session.commit() @@ -62,7 +62,7 @@ def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file): def test_recovery_skips_manually_closed_and_success(transfer_db, dbs_ready_file): """manually_closed / success 永久排除,不生成 Attempt。""" - deps, erp, summary = _mixed_precheck(dbs_ready_file) + deps, erp, summary = _mixed_matching(dbs_ready_file) blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() blocked.status = "manually_closed" blocked.manually_closed_reason = "线下处理" diff --git a/backend/tests/services/in_transit_transfer/test_restore_scope.py b/backend/tests/services/in_transit_transfer/test_restore_scope.py new file mode 100644 index 00000000..febd03ca --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_restore_scope.py @@ -0,0 +1,102 @@ +"""匹配卡 scope 实时视图测试(restore 按 scope 查行 + 行装饰字段,L1)。 + +用途:验证 restore_matching 不再读 matching.items 行归属,而按匹配 scope + (scope_item_query)实时圈定行集,并逐行装饰 item_id / checked_at / + stale / file_current;counts 为 scope 行实时聚合(不读 counts_json 快照)。 +依赖:transfer_db、matching_service、repo_fakes。 +逻辑:经 create_matching 真实落库构造行状态;行归属(matching_id)保持首次 + 创建值(原地刷新语义),重复匹配的 restore 仍能看到同一批活跃行; + 收料文件状态投影按同款 monkeypatch 替身注入。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer import matching_service +from app.services.in_transit_transfer.matching_service import create_matching, restore_matching +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + + +def _file_ready(monkeypatch, dbs_ready_file: dict) -> None: + """让来源文件状态投影返回 ready(sha 与 fixture 文件一致,不触碰真实文件表)。""" + monkeypatch.setattr( + matching_service, "resolve_source_file_status", + lambda *, source_code: {"file_status": "ready", "has_ready_file": True, + "file_no": dbs_ready_file["file_no"], + "file_sha256": dbs_ready_file["checksum"]}, + ) + + +def test_restore_returns_scope_rows_not_owned_rows(transfer_db, dbs_ready_file, monkeypatch): + """restore 按范围返回实时行:行属于首份匹配,但第二份匹配的 restore 也能看到(实时状态)。""" + _file_ready(monkeypatch, dbs_ready_file) + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) # 行建在此匹配 + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + + detail = restore_matching(second.matching_id, deps=deps) + + assert {i.invoice_no for i in detail["items"]} == {"HOM-001", "HOX-002"} + row = next(i for i in detail["items"] if i.invoice_no == "HOX-002") + # [断言意图] 行装饰三要素:行 id 可追溯(item_id)、刚刷新不陈旧(stale)、 + # 行评估版本戳仍是该来源当前可用文件(file_current)。 + assert row.item_id > 0 and row.stale is False and row.file_current is True + # [断言意图] counts 为 scope 行实时聚合(不读 counts_json 快照): + # 2 行 = 1 可执行 + 1 阻断;summary 其余字段沿用匹配记录留痕。 + counts = detail["summary"].counts + assert counts.file_invoice_count == 2 + assert counts.executable_count == 1 + assert counts.blocked_count == 1 + assert counts.matched_count == 2 + assert detail["summary"].matching_hash == second.matching_hash + assert detail["summary"].expires_at + + +def test_restore_marks_stale_beyond_ttl(transfer_db, dbs_ready_file, monkeypatch): + """行 updated_at 早于 TTL → stale=True(TTL 取 deps.strategy.confirm_ttl_seconds)。""" + _file_ready(monkeypatch, dbs_ready_file) + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + # 手工把 HOX-002 行的评估时间拨回 11 分钟前(TTL 默认 600 秒 = 10 分钟)。 + stale_at = datetime.utcnow() - timedelta(minutes=11) + hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() + hox.updated_at = stale_at + db.session.commit() + + detail = restore_matching(summary.matching_id, deps=deps) + + row = next(i for i in detail["items"] if i.invoice_no == "HOX-002") + fresh = next(i for i in detail["items"] if i.invoice_no == "HOM-001") + # [断言意图] 超过确认 TTL 未刷新的行必须标记 stale(提示用户重查后再执行), + # 未拨回的行保持新鲜;checked_at 携带行评估时间(updated_at isoformat)。 + assert row.stale is True + assert fresh.stale is False + assert row.checked_at == hox.updated_at.isoformat() + assert row.file_current is True + + +def test_restore_marks_file_current_false_without_ready_file(transfer_db, dbs_ready_file, monkeypatch): + """来源当前无可用文件 → 行 file_current=False(fail-safe,不得当作新鲜)。""" + monkeypatch.setattr( + matching_service, "resolve_source_file_status", + lambda *, source_code: {"file_status": "none", "has_ready_file": False, + "file_no": None, "file_sha256": None}, + ) + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + + detail = restore_matching(summary.matching_id, deps=deps) + + # [断言意图] 对账依据缺失(无可用文件 sha)时宁可不放行:行版本戳无法与 + # 当前文件比对,file_current 必须为 False,避免按过期数据执行的幻觉。 + assert detail["items"] + assert all(i.file_current is False for i in detail["items"]) diff --git a/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py index 3a6e59f1..d4b9f195 100644 --- a/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py +++ b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py @@ -2,7 +2,7 @@ 用途:验证人工重试只创建新 Attempt(重新查询 外部系统,不重新抓 RPA、不写 外部系统), result_unknown 拒绝重试;人工关闭原因必填且永久排除。 -依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。 +依赖:transfer_db、matching_service、retry_service、manual_close_service、repo_fakes。 逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。 """ @@ -14,17 +14,17 @@ from app import db from app.core.errors import ValidationError from app.models import TransferAttempt, TransferInvoiceItem from app.services.in_transit_transfer.manual_close_service import manual_close_item -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.matching_service import create_matching from app.services.in_transit_transfer.retry_service import requery_items, retry_item from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _mismatch_precheck(dbs_ready_file): - """构造 INV-001 数量不一致的预检。""" +def _mismatch_matching(dbs_ready_file): + """构造 INV-001 数量不一致的匹配。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) return deps, erp, summary @@ -34,7 +34,7 @@ def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem: def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file): """外部系统 修正后重试 → 新 Attempt,状态进入 ready_to_execute。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") assert item.status == "blocked_recoverable" old_attempt_count = item.attempt_no @@ -56,7 +56,7 @@ def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file): def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file): """重试后仍不匹配 → 保持 blocked_recoverable,attempt_no 递增。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") old = item.attempt_no result = retry_item(item_id=item.id, deps=deps) @@ -71,7 +71,7 @@ def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file): def test_retry_not_found_shows_zero_stock(transfer_db, dbs_ready_file): """重查后外部系统查无记录 → 库存数按 0 落库展示,不显示"-"误导为查询失败。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") retry_item(item_id=item.id, deps=deps) # 先产生 external_quantity=1000 assert _item_by_invoice("HOM-001").external_quantity == "1000" @@ -86,8 +86,8 @@ def test_retry_not_found_shows_zero_stock(transfer_db, dbs_ready_file): def test_retry_ready_row_allowed(transfer_db, dbs_ready_file): - """可执行(ready_to_execute)行也允许重查:预检后库存变化需可复核。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + """可执行(ready_to_execute)行也允许重查:匹配后库存变化需可复核。""" + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") item.status = "ready_to_execute" db.session.commit() @@ -102,13 +102,13 @@ def test_retry_ready_row_allowed(transfer_db, dbs_ready_file): def test_requery_includes_ready_rows(transfer_db, dbs_ready_file): """批量重查范围含可执行行:可执行行也会被逐票刷新,而非只刷阻断行。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") item.status = "ready_to_execute" db.session.commit() erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500") # 库存被挪用 - result = requery_items(precheck_no=summary.precheck_id, deps=deps) + result = requery_items(matching_no=summary.matching_id, deps=deps) # [断言意图] 可执行行不再被重查排除;库存变化后被重查回阻断态并保留 外部系统 数。 assert result["total"] == 2 @@ -120,7 +120,7 @@ def test_requery_includes_ready_rows(transfer_db, dbs_ready_file): def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file): """result_unknown 只读:拒绝重试(禁止猜测性二次写入)。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") item.status = "result_unknown" item.result_code = "result_unknown" @@ -132,7 +132,7 @@ def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file): def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file): """Run 创建后禁止重新抓取 RPA(文件冻结)。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") with pytest.raises(ValidationError): retry_item(item_id=item.id, deps=deps, kind="rpa_refetch") @@ -140,7 +140,7 @@ def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file): def test_manual_close_requires_reason(transfer_db, dbs_ready_file): """人工关闭原因必填。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") with pytest.raises(ValidationError): manual_close_item(item_id=item.id, reason="") @@ -148,7 +148,7 @@ def test_manual_close_requires_reason(transfer_db, dbs_ready_file): def test_manual_close_marks_terminal(transfer_db, dbs_ready_file): """人工关闭 → manually_closed(永久排除,后续排程不再处理)。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") result = manual_close_item(item_id=item.id, reason="货代确认无需调拨") assert result["status"] == "manually_closed" @@ -163,7 +163,7 @@ def test_manual_close_marks_terminal(transfer_db, dbs_ready_file): def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file): """result_unknown 只读:禁止人工关闭(需按 SOP 核实)。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) item = _item_by_invoice("HOM-001") item.status = "result_unknown" db.session.commit() @@ -172,10 +172,10 @@ def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file): def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file): - """批量重查:同预检全部可重查行(阻断 + 可执行)逐票刷新,结果按行回报。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + """批量重查:同匹配全部可重查行(阻断 + 可执行)逐票刷新,结果按行回报。""" + deps, erp, summary = _mismatch_matching(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 人工在 外部系统 修正库存 - result = requery_items(precheck_no=summary.precheck_id, deps=deps) + result = requery_items(matching_no=summary.matching_id, deps=deps) # [断言意图] 阻断行(HOM-001)与可执行行(HOX-002)都在重查范围内。 assert result["total"] == 2 rows = {row["invoice_no"]: row for row in result["results"]} @@ -187,11 +187,11 @@ def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file): def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_ready_file): """invoice_nos 限定范围:不在清单的阻断行不被触碰。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) blocked = db.session.query(TransferInvoiceItem).filter_by(status="blocked_recoverable").all() assert [i.invoice_no for i in blocked] == ["HOM-001"] - result = requery_items(precheck_no=summary.precheck_id, deps=deps, invoice_nos=["INV-XXX"]) + result = requery_items(matching_no=summary.matching_id, deps=deps, invoice_nos=["INV-XXX"]) assert result["total"] == 0 assert _item_by_invoice("HOM-001").status == "blocked_recoverable" @@ -201,9 +201,9 @@ def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_ blocked_external_query_failed + 原因,不向调用方抛异常。 此前该场景抛 BindingNotFoundError('no binding for capability'), - 与 precheck 的逐票降级语义不一致,用户侧表现为全局错误弹窗。 + 与 matching 的逐票降级语义不一致,用户侧表现为全局错误弹窗。 """ - deps, erp, _summary = _mismatch_precheck(dbs_ready_file) + deps, erp, _summary = _mismatch_matching(dbs_ready_file) erp.set_query_scenario("error") # RuntimeError: binding not found for capability query_inventory item = _item_by_invoice("HOM-001") old_attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).count() @@ -223,9 +223,9 @@ def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_ def test_requery_with_erp_gateway_failure_stays_batched(transfer_db, dbs_ready_file): """批量重查遇 外部系统 故障:逐票降级、批次正常完成,不炸整批。""" - deps, erp, summary = _mismatch_precheck(dbs_ready_file) + deps, erp, summary = _mismatch_matching(dbs_ready_file) erp.set_query_scenario("error") - result = requery_items(precheck_no=summary.precheck_id, deps=deps) + result = requery_items(matching_no=summary.matching_id, deps=deps) assert result["total"] == 2 assert all(row["ok"] for row in result["results"]) assert _item_by_invoice("HOM-001").result_code == "blocked_external_query_failed" diff --git a/backend/tests/services/in_transit_transfer/test_route_resolver.py b/backend/tests/services/in_transit_transfer/test_route_resolver.py index 91744ec9..17790d50 100644 --- a/backend/tests/services/in_transit_transfer/test_route_resolver.py +++ b/backend/tests/services/in_transit_transfer/test_route_resolver.py @@ -15,7 +15,7 @@ import pytest from app.extensions import db from app.models import ShippingInventoryExternalMapping, ShippingInventorySource from app.services.in_transit_transfer.deps import DefaultRouteResolver -from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError +from app.services.in_transit_transfer.matching_service import RouteNotResolvedError def _seed_mapping( diff --git a/backend/tests/services/in_transit_transfer/test_source_job_service.py b/backend/tests/services/in_transit_transfer/test_source_job_service.py index 833adcbd..eab492cb 100644 --- a/backend/tests/services/in_transit_transfer/test_source_job_service.py +++ b/backend/tests/services/in_transit_transfer/test_source_job_service.py @@ -21,7 +21,7 @@ from app.services.in_transit_transfer.source_job_service import ( def _run() -> TransferRun: from app import db - run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='prechecking') + run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='matching') db.session.add(run) db.session.flush() return run diff --git a/backend/tests/services/in_transit_transfer/test_status_machine.py b/backend/tests/services/in_transit_transfer/test_status_machine.py index 054eb279..08d2dbcc 100644 --- a/backend/tests/services/in_transit_transfer/test_status_machine.py +++ b/backend/tests/services/in_transit_transfer/test_status_machine.py @@ -25,7 +25,7 @@ from app.services.in_transit_transfer.status import ( pytestmark = pytest.mark.pure_unit PROMPT_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", } @@ -62,8 +62,8 @@ def test_illegal_transition_rejected(): def test_legal_transition_accepted(): - """file_ready → prechecking 是合法迁移。""" - assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.PRECHECKING.value) + """file_ready → matching 是合法迁移。""" + assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.MATCHING.value) def test_executing_to_success_accepted(): @@ -81,9 +81,9 @@ def test_executing_to_result_unknown_accepted_but_no_auto_retry(): def test_blocked_recoverable_to_manual_close_and_recheck(): - """blocked_recoverable 可人工关闭或重新预检(新 Attempt)。""" + """blocked_recoverable 可人工关闭或重新匹配(新 Attempt)。""" assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MANUALLY_CLOSED.value) - assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.PRECHECKING.value) + assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MATCHING.value) def test_unknown_status_rejected(): @@ -98,10 +98,10 @@ def test_not_matured_has_no_outgoing_edges(): def test_run_transition_queued_to_executing_path(): - """Run 生命周期:queued → preparing_files → prechecking → ready_to_execute → executing。""" + """Run 生命周期:queued → preparing_files → matching → ready_to_execute → executing。""" assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS) - assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.PRECHECKING.value, transitions=RUN_TRANSITIONS) - assert_transition_allowed(TransferRunStatus.PRECHECKING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.MATCHING.value, transitions=RUN_TRANSITIONS) + assert_transition_allowed(TransferRunStatus.MATCHING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS) assert_transition_allowed(TransferRunStatus.READY_TO_EXECUTE.value, TransferRunStatus.EXECUTING.value, transitions=RUN_TRANSITIONS) diff --git a/backend/tests/services/in_transit_transfer/test_worker_recovery.py b/backend/tests/services/in_transit_transfer/test_worker_recovery.py index 14bc4611..f4745d8d 100644 --- a/backend/tests/services/in_transit_transfer/test_worker_recovery.py +++ b/backend/tests/services/in_transit_transfer/test_worker_recovery.py @@ -2,7 +2,7 @@ 用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、 停滞 Run 可终态收尾、result_unknown 不被自动重试。 -依赖:transfer_db、precheck/execution/recovery、repo_fakes。 +依赖:transfer_db、matching/execution/recovery、repo_fakes。 逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 外部系统 返回 duplicate_success。 """ @@ -14,8 +14,7 @@ import pytest from app import db from app.models import TransferInvoiceItem, TransferRun -from app.services.in_transit_transfer.execution_service import execute_precheck -from app.services.in_transit_transfer.precheck_service import create_precheck +from app.services.in_transit_transfer.matching_service import create_matching from app.services.in_transit_transfer.recovery import ( finalize_stale_runs, recover_stale_execution_items, @@ -24,12 +23,12 @@ from app.services.in_transit_transfer.status import TransferStatus from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps -def _executing_precheck(dbs_ready_file): - """构造已预检 precheck(不执行),并手动把明细置为 executing。""" +def _executing_matching(dbs_ready_file): + """构造已匹配 matching(不执行),并手动把明细置为 executing。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) for item in db.session.query(TransferInvoiceItem).all(): item.status = "executing" item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期 @@ -39,7 +38,7 @@ def _executing_precheck(dbs_ready_file): def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_file): """租约过期的 executing 项恢复后完成写入(幂等,无重复建单)。""" - deps, erp = _executing_precheck(dbs_ready_file) + deps, erp = _executing_matching(dbs_ready_file) result = recover_stale_execution_items(deps=deps) assert result["recovered"] == 2 items = db.session.query(TransferInvoiceItem).all() @@ -51,7 +50,7 @@ def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_f def test_recover_skips_result_unknown(transfer_db, dbs_ready_file): """result_unknown 不自动重试(不触碰、不写 外部系统)。""" - deps, erp = _executing_precheck(dbs_ready_file) + deps, erp = _executing_matching(dbs_ready_file) item = db.session.query(TransferInvoiceItem).first() item.status = "result_unknown" db.session.commit() @@ -64,15 +63,18 @@ def test_recover_skips_result_unknown(transfer_db, dbs_ready_file): def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file): """停滞 Run(全部明细已终态但 Run 仍 executing)→ 收尾为 success。""" - from app.models import TransferPrecheck - from app.services.in_transit_transfer.orchestrator import create_execution_run + from app.services.in_transit_transfer.orchestrator import create_execution_run_for_items deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") - summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first() - run = create_execution_run(precheck, deps=deps, actor_id=None) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + ready_items = ( + TransferInvoiceItem.query.filter_by(status="ready_to_execute") + .order_by(TransferInvoiceItem.id) + .all() + ) + run = create_execution_run_for_items(ready_items, deps=deps, actor_id=None) for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all(): item.status = "success" item.external_document_no = "TRF-DONE" diff --git a/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py b/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py new file mode 100644 index 00000000..23476da0 --- /dev/null +++ b/backend/tests/services/integration_connector/test_mapping_repeated_record_batch.py @@ -0,0 +1,203 @@ +"""tests/services/integration_connector/test_mapping_repeated_record_batch.py + +用途:复现并回归"批量库存查询结果装配丢行"缺陷(Task 6 独立排查,2026-09-23)。 + 生产实测矛盾:同一批 Invoice 预检批量查询全部 blocked_inventory_not_found(0), + 逐行单查却能查得库存——两条路径的差异只在一次查询携带的 targets 数量。 +依赖:mapping.py / transports.soap(纯函数);capability_client.CapabilityClient。 +逻辑:TIPTOP GetItemStockList 响应中 Record/Master/RecordSet 都是可重复节点, + XML 归一化后"单条 dict、多条 list"。批量查询返回多 Record(/多 Master)时, + extract_path 扇出收集会产出嵌套 list,pick 无法消费 → 字段全 MISSING → + 行被静默丢弃 → 领域层 lookup 未命中 → 整批 0 库存。 + 用例覆盖:同料号不同批号、同批号不同料号、单 Master 多 Record、 + 多 RecordSet 混合多 Record,以及批量 vs 单查的 lookup 对账。 +""" + +from __future__ import annotations + +from decimal import Decimal + +from app.services.in_transit_transfer.capability_client import CapabilityClient, StockTarget +from app.services.integration_connector.mapping import extract_path, map_response +from app.services.integration_connector.transports.base import IntegrationCallResult +from app.services.integration_connector.transports.soap import _parse_soap_payload + +# 生产绑定同构的 rows 映射(expr/each/pick 与 2026-09-22 回归用例一致, +# from_warehouse 按 img02、批号 img04、库存数 img10)。 +_ROWS_MAPPING = {"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master", + "transform": "each", "args": {"fields": { + "material_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}}, + "from_warehouse": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img02", "value_field": "@value"}}, + "lot_no": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}, + "quantity": {"expr": "Record.Field", "transform": "pick", + "args": {"key_field": "@name", "key_value": "img10", "value_field": "@value", + "cast": "decimal"}}}}}} +_ROWS_OUTPUT_SCHEMA = {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array", "items": { + "type": "object", "required": ["material_no", "from_warehouse", "lot_no", "quantity"]}}}} + + +def _field(name: str, value: str) -> dict: + return {"@name": name, "@value": value} + + +def _record(material: str, warehouse: str, lot: str, qty: str) -> dict: + return {"Field": [_field("img01", material), _field("img02", warehouse), + _field("img04", lot), _field("img10", qty)]} + + +def _stock_response(record_sets: list[dict]) -> dict: + """构造 GetItemStockListResponse 归一化后形态(与 _parse_soap_payload 产出同构)。""" + return {"GetItemStockListResponse": {"response": {"Response": { + "ResponseContent": {"Document": {"RecordSet": record_sets}}}}}} + + +def _client_with_rows(rows: list[dict]) -> CapabilityClient: + """以映射产物为应答的 CapabilityClient 替身网关(模拟引擎 data 透传)。""" + + class _Gateway: + def call(self, **kwargs): + return IntegrationCallResult(status="success", data={"rows": rows}) + + return CapabilityClient(gateway=_Gateway()) + + +def test_single_target_single_record_maps_one_row(): + """单查形态(1 RecordSet × 1 Master × 1 Record)→ 一行(重查路径现状正确的基线)。""" + raw = _stock_response([ + {"@id": "1", "Master": {"@name": "img_file", "Record": _record("M-1", "W-1", "L-1", "30")}}, + ]) + rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] + assert rows == [{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")}] + + +def test_multi_record_master_maps_every_record_row(): + """[缺陷复现] 一个 Master 容器携带多条 Record(不同批号/料号)→ 每条 Record 一行。 + + [断言意图] 修复前:扇出嵌套 list 使 pick 全 MISSING → 行静默消失(rows=[]), + 批量查询整批 0 库存;修复后:每条 Record 产出独立行,同料号不同批号 / + 同批号不同料号互不覆盖、互不丢失。 + """ + raw = _stock_response([ + {"@id": "1", "Master": {"@name": "img_file", "Record": [ + _record("M-1", "W-1", "L-1", "30"), + _record("M-1", "W-1", "L-2", "40"), + _record("M-2", "W-1", "L-1", "36"), + ]}}, + ]) + rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] + # [断言意图] 同料号不同批号(L-1/L-2)与同批号不同料号(M-1/M-2)全部保留。 + assert rows == [ + {"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")}, + {"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-2", "quantity": Decimal("40")}, + {"material_no": "M-2", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("36")}, + ] + + +def test_multi_recordset_with_multi_record_master_keeps_all_rows(): + """[缺陷复现] 多 RecordSet(按条件拆分)且部分 Master 多 Record → 行数完整。""" + raw = _stock_response([ + {"@id": "1", "Master": {"@name": "img_file", "Record": [ + _record("M-1", "W-1", "L-1", "30"), + _record("M-1", "W-1", "L-1", "10"), + ]}}, + {"@id": "2", "Master": {"@name": "img_file", "Record": _record("M-2", "W-2", "L-9", "40")}}, + ]) + rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] + # [断言意图] RecordSet 逐元素扇出 + 重复 Record 展开叠加时行数完整(2+1=3 行)。 + assert len(rows) == 3 + assert rows[0]["quantity"] == Decimal("30") + assert rows[2] == {"material_no": "M-2", "from_warehouse": "W-2", "lot_no": "L-9", "quantity": Decimal("40")} + + +def test_batch_vs_single_lookup_parity_on_multi_record_response(): + """[事故链路] 批量查询(多 targets)与逐 target 单查的 lookup 结果必须一一对应。 + + 映射切片走生产同构配置:批量响应为"单 Master 多 Record"形态时,修复前批量 + lookup 全 None(=0 库存)而单查正常——正是预检 0 / 重查 30 的矛盾来源。 + """ + raw_batch = _stock_response([ + {"@id": "1", "Master": {"@name": "img_file", "Record": [ + _record("M-1", "W-1", "L-1", "30"), + _record("M-1", "W-1", "L-2", "40"), + _record("M-2", "W-1", "L-1", "36"), + ]}}, + ]) + raw_single = _stock_response([ + {"@id": "1", "Master": {"@name": "img_file", "Record": _record("M-1", "W-1", "L-1", "30")}}, + ]) + batch_rows = map_response(_ROWS_MAPPING, raw_batch, _ROWS_OUTPUT_SCHEMA)["rows"] + single_rows = map_response(_ROWS_MAPPING, raw_single, _ROWS_OUTPUT_SCHEMA)["rows"] + + targets = [StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1"), + StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-2"), + StockTarget(material_no="M-2", from_warehouse="W-1", lot_no="L-1")] + batch_result = _client_with_rows(batch_rows).query_stock( + operation_id="op-batch", external_org="HX-CN01", targets=targets) + single_result = _client_with_rows(single_rows).query_stock( + operation_id="op-single", external_org="HX-CN01", targets=[targets[0]]) + + # [断言意图] 批量与单查逐 target 对账一致:批量不再整批 0(inventory_not_found)。 + assert single_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30") + assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30") + assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-2") == Decimal("40") + assert batch_result.lookup(material_no="M-2", from_warehouse="W-1", lot_no="L-1") == Decimal("36") + + +def test_soap_multi_record_payload_end_to_end_mapping(): + """端到端真实 XML:转义内嵌报文 → SOAP 解析归一化 → 多 Record 全部映射成行。""" + xml = ( + "" + "" + "<Response><ResponseContent><Document>" + "<RecordSet id='1'><Master name='img_file'>" + "<Record><Field name='img01' value='M-1'/><Field name='img02' value='W-1'/>" + "<Field name='img04' value='L-1'/><Field name='img10' value='30'/></Record>" + "<Record><Field name='img01' value='M-1'/><Field name='img02' value='W-1'/>" + "<Field name='img04' value='L-2'/><Field name='img10' value='40'/></Record>" + "</Master></RecordSet>" + "</Document></ResponseContent></Response>" + "" + ) + raw = _parse_soap_payload(xml) + rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] + # [断言意图] 转义内嵌报文同样走归一化+映射:两条 Record(不同批号)都成行。 + assert [(r["lot_no"], str(r["quantity"])) for r in rows] == [("L-1", "30"), ("L-2", "40")] + + +def test_extract_path_fanout_nested_list_flattened(): + """extract_path 扇出命中本身是列表(更深层重复节点)→ 拍平而非嵌套。""" + raw = {"Masters": [ + {"Record": [{"Field": [{"@name": "img01", "@value": "M-1"}]}, + {"Field": [{"@name": "img01", "@value": "M-2"}]}]}, + {"Record": {"Field": [{"@name": "img01", "@value": "M-3"}]}}, + ]} + # [断言意图] 逐元素收集跨两层重复节点后是"所有 Field dict"的扁平列表, + # pick 等消费方不再见到 list-in-list。 + assert extract_path(raw, "Masters.Record.Field") == [ + {"@name": "img01", "@value": "M-1"}, {"@name": "img01", "@value": "M-2"}, + {"@name": "img01", "@value": "M-3"}, + ] + + +def test_case_and_space_variants_pass_through_exact_match(): + """[怀疑矩阵:大小写/尾空格] ERP 回显值原样透传,lookup 按三元组精确匹配。 + + [断言意图] 归一化/映射层不做任何大小写或去空格改写(回显 'm-1 '/'l-1' 原样 + 成行);若外部回显与请求键存在大小写/空格差异,lookup 未命中返回 None—— + 该语义对批量/单查两侧对称,不是本次"批量 0/单查有值"矛盾的原因,故不改匹配语义。 + """ + raw = _stock_response([ + {"@id": "1", "Master": {"@name": "img_file", "Record": _record("m-1 ", "W-1", "l-1", "30")}}, + ]) + rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"] + # [断言意图] 行值原样保留(未改写大小写、未截断空格)。 + assert rows == [{"material_no": "m-1 ", "from_warehouse": "W-1", "lot_no": "l-1", + "quantity": Decimal("30")}] + result = _client_with_rows(rows).query_stock( + operation_id="op-case", external_org="HX-CN01", + targets=[StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1")]) + # [断言意图] 精确匹配下大小写/空格不同的键不命中(两侧路径同语义)。 + assert result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") is None + assert result.lookup(material_no="m-1 ", from_warehouse="W-1", lot_no="l-1") == Decimal("30") diff --git a/backend/tests/test_shipping_process_gate_poll_resilience.py b/backend/tests/test_shipping_process_gate_poll_resilience.py new file mode 100644 index 00000000..047dcb88 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_poll_resilience.py @@ -0,0 +1,145 @@ +""" +tests/test_shipping_process_gate_poll_resilience.py + +用途:锁定 external-wait 轮询 Job 的异常韧性契约与库存回调的 Gate 锁序约定。 +依赖:pytest、shipping_process_gate handler、inventory_rpa_workflow、monkeypatch。 +逻辑:不依赖 DB。轮询异常时回滚并按 Gate 现状分流(waiting_external 延迟重排保持轮询链不断 / + 已收口则安静结束),绝不终态失败;回调侧 `_lock_process_gates_for_task` 必须锁活跃 + Execution 的全部 Gate 行且无 Execution 时不查询。 +背景:2026-09-23 test job 8818——轮询与库存 RPA 回调以相反顺序争抢 Gate/候选行,事务被 + 毒化后以 InFailedSqlTransaction 终态失败,轮询链断裂(本次回调早到 400ms 自愈, + 若回调迟到则 run 将永久停在 external-wait)。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +@pytest.fixture() +def gate_job_env(monkeypatch): + """构造轮询 Job + Gate 的最小 handler 环境;返回各类捕获器。""" + import app.jobs.handlers.shipping_process_gate as handler + + job = SimpleNamespace(id=8818, attempts=1) + gate = SimpleNamespace(id=10313, status='waiting_external', latest_attempt_id=7) + finished: list[dict] = [] + failed: list[dict] = [] + scheduled: list[dict] = [] + + def _fake_get(model, _id): + if model is handler.Job: + return job + if model is handler.ShippingProcessGate: + return gate + return None + + monkeypatch.setattr(handler.db.session, 'get', _fake_get) + monkeypatch.setattr(handler.db.session, 'rollback', lambda: None) + monkeypatch.setattr(handler.db.session, 'commit', lambda: None) + monkeypatch.setattr( + handler, 'current_app', + SimpleNamespace(config={'SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS': 30}), + ) + + def _finish(job_id, *, result, owned_attempt): + finished.append({'job_id': job_id, 'result': result}) + + def _fail(job_id, *, error, result=None, retryable, owned_attempt): + failed.append({'job_id': job_id, 'error': error, 'retryable': retryable}) + + def _schedule(*, attempt_id): + scheduled.append({'attempt_id': attempt_id}) + + monkeypatch.setattr(handler, 'finish_job', _finish) + monkeypatch.setattr(handler, 'fail_job', _fail) + monkeypatch.setattr(handler, 'schedule_waiting_external_poll', _schedule) + return { + 'handler': handler, + 'job': job, + 'gate': gate, + 'finished': finished, + 'failed': failed, + 'scheduled': scheduled, + } + + +def _raise_poll(*_args, **_kwargs): + raise RuntimeError('poisoned transaction: InFailedSqlTransaction') + + +def test_poll_failure_while_waiting_external_requeues_chain(monkeypatch, gate_job_env): + """轮询异常且 Gate 仍在等待外部:回滚后延迟重排,轮询链不断,且不得终态失败。""" + handler = gate_job_env['handler'] + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.run_inventory_external_wait_poll', + _raise_poll, + ) + + handler.run_shipping_process_gate( + SimpleNamespace(), + {'external_wait_poll_gate_id': 10313, 'job_id': 8818}, + ) + + # 断言:以 waiting_external_requeued 成功收口并重排轮询链;绝不走 fail_job。 + assert len(gate_job_env['finished']) == 1 + result = gate_job_env['finished'][0]['result'] + assert result['status'] == 'waiting_external_requeued' + assert 'InFailedSqlTransaction' in (result.get('poll_error') or '') + assert gate_job_env['scheduled'] == [{'attempt_id': 7}] + assert gate_job_env['failed'] == [] + + +def test_poll_failure_after_gate_resolved_ends_quietly(monkeypatch, gate_job_env): + """Gate 已被回调等其他路径收口(status=passed):安静结束,不再重排。""" + handler = gate_job_env['handler'] + gate_job_env['gate'].status = 'passed' + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.run_inventory_external_wait_poll', + _raise_poll, + ) + + handler.run_shipping_process_gate( + SimpleNamespace(), + {'external_wait_poll_gate_id': 10313, 'job_id': 8818}, + ) + + # 断言:竞态输给回调时安静退出(poll_superseded),不重排、不失败。 + assert len(gate_job_env['finished']) == 1 + result = gate_job_env['finished'][0]['result'] + assert result['status'] == 'poll_superseded' + assert result['gate_status'] == 'passed' + assert gate_job_env['scheduled'] == [] + assert gate_job_env['failed'] == [] + + +def test_lock_process_gates_for_task_locks_active_execution_gates(monkeypatch): + """[锁序约定] 回调写候选前必须锁活跃 Execution 的全部 Gate 行;无 Execution 不查询。""" + from app.services.shipping_notice import inventory_rpa_workflow as wf + + calls: list[dict] = [] + + class _FakeQuery: + def filter_by(self, **kwargs): + calls.append(kwargs) + return self + + def with_for_update(self): + return self + + def all(self): + return [SimpleNamespace(id=1), SimpleNamespace(id=2)] + + monkeypatch.setattr('app.models.ShippingProcessGate', SimpleNamespace(query=_FakeQuery())) + + task = SimpleNamespace(active_process_execution_id=516) + wf._lock_process_gates_for_task(task) + # 断言:按活跃 Execution 过滤并加锁。 + assert calls == [{'execution_id': 516}] + + # 断言:无活跃 Execution(历史/已归档任务)直接跳过,不查询。 + calls.clear() + wf._lock_process_gates_for_task(SimpleNamespace(active_process_execution_id=None)) + assert calls == [] diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md index 8a0b03f6..2bf4e3e0 100644 --- a/docs/features/in-transit-transfer/technical.md +++ b/docs/features/in-transit-transfer/technical.md @@ -1,24 +1,24 @@ # 在途仓自动调拨 Agent — 运行维护手册 -> 状态:后端 Phase 0-4 已交付(领域/文件/预检/执行/排程/恢复/通知/归档/指标),前端实施中。 +> 状态:后端 Phase 0-4 已交付(领域/文件/匹配/执行/排程/恢复/通知/归档/指标),前端实施中。2026-09-23 术语重构:precheck(预检)→ match(匹配),表/列/API/状态值全量更名,未上线无兼容层。 > 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md) · [TDD](./in-transit-transfer-tdd.md) · [PRD](./prd.md) · [路线图](./roadmap.md) ## 1. 架构概览 - **业务域**:`backend/app/services/in_transit_transfer/`(独立领域模块,不混入 shipping_notice 订单解析)。 - **执行边界**:收料来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。 -- **真相源**:`TransferRun` / `TransferPrecheck` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`)。 +- **真相源**:`TransferRun` / `TransferMatching` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`;术语重构迁移 `rn1a2b3c4d5e6`)。 - **外部系统访问唯一出口**:`capability_client.py`(`CapabilityClient.query_stock / create_transfer / verify_duplicate`);查询经集成连接器 CapabilityGateway 按 `in_transit_transfer.query_inventory` 能力批量调用(按 external_org 分组、targets = 料号+拨出库位+拨出批号 元组,`external_org` 取自仓库映射 `external_organization_code`);写路径在外部契约冻结前 fail-closed(`ExternalNotFrozenError`,Phase 2 接线)。 -- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / precheck_expired)。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。 -- **调拨业务类型(2026-09-22)**:`transfer_type.py` 定义三类——`in_transit_to_hub`(在途仓至HUB仓,一期唯一开放)、`hub_repair_out`(HUB仓维修出,占位)、`hub_to_hub`(HUB仓间调拨,占位)。类型决定预检收料数据范围:类型 1 仅纳入 INVOICE 前缀 `HOM/HOX/WTP`(大小写不敏感)的票,范围外票与收料日期过滤同语义静默排除;类型 2 规则已冻结(ODM ID=`HoxinRMA`)待收料文件解析层支持 `odm_id` 字段后启用,类型 3 规则待业务定义;占位类型被调用时 fail-closed(`TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED`)。类型随 Run 落库(`transfer_runs.transfer_type`,迁移 `tt3d4e5f6a7b`)并写入 `TransferPrecheck.scope_json`(含范围规则说明)参与预检 Hash;前端来源选择卡顶部选择(类型 2/3 禁用展示「即将上线」),异步预检 Job 从 scope_json 回读类型保证口径一致。 -- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费预检/执行 Run/执行 Item 三类 Job。 +- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。 +- **调拨业务类型(2026-09-22)**:`transfer_type.py` 定义三类——`in_transit_to_hub`(在途仓至HUB仓,一期唯一开放)、`hub_repair_out`(HUB仓维修出,占位)、`hub_to_hub`(HUB仓间调拨,占位)。类型决定匹配收料数据范围:类型 1 仅纳入 INVOICE 前缀 `HOM/HOX/WTP`(大小写不敏感)的票,范围外票与收料日期过滤同语义静默排除;类型 2 规则已冻结(ODM ID=`HoxinRMA`)待收料文件解析层支持 `odm_id` 字段后启用,类型 3 规则待业务定义;占位类型被调用时 fail-closed(`TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED`)。类型随 Run 落库(`transfer_runs.transfer_type`,迁移 `tt3d4e5f6a7b`)并写入 `TransferMatching.scope_json`(含范围规则说明)参与匹配 Hash;前端来源选择卡顶部选择(类型 2/3 禁用展示「即将上线」),异步匹配 Job 从 scope_json 回读类型保证口径一致。 +- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费匹配/执行 Run/执行 Item 三类 Job。 - **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。 ## 2. 数据库 -- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `receipt_warehouse_code`(收料仓库匹配键);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束)。 +- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `receipt_warehouse_code`(收料仓库匹配键);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束);`rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py`(down_revision=`43a8179cdd88`)为术语重构迁移——表 `transfer_prechecks`→`transfer_matchings`、列 `precheck_no/precheck_hash/precheck_id`→`matching_no/matching_hash/matching_id`、状态值 `prechecking`→`matching`(13 状态中仅此一个更名)、约束/索引同步改名,未上线直改无兼容层。 - 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。 -- 表:transfer_runs / transfer_source_jobs / transfer_prechecks / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。 +- 表:transfer_runs / transfer_source_jobs / transfer_matchings / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。 - 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。 ## 3. 环境变量(⑨业务模块区;凭据只由环境/Secret 注入) @@ -26,7 +26,7 @@ | 变量 | 默认 | 说明 | | --- | --- | --- | | `IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY` | 2 | 来源并发 | -| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 确认有效期(10 分钟) | +| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 行级新鲜度 TTL(10 分钟;按行执行门禁②:行 `updated_at` 距 now 超时拒绝执行) | | `IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS` | 3 | 老化预警阈值 | | `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 | | `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 | @@ -43,19 +43,47 @@ | Method | Path | 说明 | | --- | --- | --- | -| POST | `/prechecks` | 创建预检(只读;可选 `transfer_type`,缺省 `in_transit_to_hub`) | -| GET | `/prechecks/{id}` | 预检进度恢复 | -| POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run | +| POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 必填,可选 `business_date`/`receipt_date_from`/`receipt_date_to`/`transfer_type`,缺省 `in_transit_to_hub`;响应含 matching_id/hash/计数/来源进度) | +| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→Invoice→created_at;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 | +| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`,counts 实时聚合) | +| POST | `/matchings/{no}/items/requery` | 按 matching_no 批量重查 ERP 库存(可恢复阻断行;body 可选 `invoice_nos` 限定范围) | +| POST | `/sources/receipt-files` | 按选中来源打包下载各自最新归档收料文件 zip(下载留审计) | | GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) | | POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) | | POST | `/items/{id}/retry` | 人工重试(external_recheck,新 Attempt) | | POST | `/items/{id}/manual-close` | 人工关闭(原因必填) | +| POST | `/items/execute` | 按行执行调拨(body `{"item_ids":[..]}`;三层门禁:行级新鲜度 TTL / 文件版本对账 / 写前复查;错误码 `TRANSFER.EXECUTE_ITEMS_INVALID` / `TRANSFER.ITEMS_STALE` / `TRANSFER.FILE_CHANGED`;Run 留痕不绑匹配) | +| POST | `/items/batch-requery` | 批量重查库存=恢复处理(body `item_ids`;单行隔离,逐行 external_recheck) | +| POST | `/items/batch-manual-close` | 批量人工关闭(body `item_ids` + `reason`;单行隔离) | | GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) | | GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) | -| GET | `/runs/{run_no}/external-inventory` | 预检冻结外部系统库存表 csv(下载留审计) | +| GET | `/runs/{run_no}/external-inventory` | 匹配冻结 ERP 库存表 csv(下载留审计) | +| GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) | +| GET | `/sources` | 来源实例列表(附收料文件状态 ready/fetching/failed/expired/none + has_ready_file,供前端门禁) | +| POST | `/sources/{source_code}/retry-rpa` | 对指定来源重新触发一次收料 RPA 抓取(配置缺失 fail-closed ok=False) | +| GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) | +| GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) | + +> 已删除路由:`/prechecks`、`/prechecks/{id}` 等 precheck 路由全量下线,`/items/batch-resume` 随恢复处理改版删除,均无兼容层。 权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。 +### 4.1 行归属与执行语义(2026-09-23 修订:行不迁移;术语 precheck→match 全量更名) + +- **主叙事**:库存匹配(动作,首页「库存匹配」卡发起)→ 可调拨清单(匹配结果的实时视图,勾选)→ 生成调拨单(按行执行);匹配不上的行进入待恢复异常(恢复处理=行级重查)。 +- **行不迁移(行归属与匹配解耦)**:`TransferInvoiceItem.matching_id` 仅记录首次评估建行时的匹配。后续对同一 scope 的重复匹配/重查对既有行**原地刷新**(不迁移 `matching_id`),并刷新 `updated_at` 续行级新鲜度;终态行(success / duplicate_success / manually_closed / cancelled / executing)不迁移、不复活。同一批行可同时被多份同 scope 匹配看到,不存在"行被掏空/迁走",也不依赖两份匹配的执行集合互斥来防重(防重由三层门禁 + ERP Invoice 幂等键承担)。 +- **匹配 = 评估留痕**:匹配记录(表 `transfer_matchings`,单号 `matching_no` 前缀 `MTG-` 由 `_generate_no` 生成)固化 scope(来源 / 收料日期区间 / 调拨类型)、counts、收料文件快照与 `matching_hash` 作为**评估留痕**;hash 与 `expires_at` **不拦截执行**(仅展示)。匹配卡与 `GET /matchings/{id}` 是 scope 的**实时视图**:按 scope 重新圈行并逐行装饰 `checked_at`(库存查询时刻)/ `stale`(新鲜度)/ `file_current`(文件版本对账),counts 亦为 scope 实时聚合(不读 counts_json 快照)。 +- **执行 = 按行 + 三层门禁**:`POST /items/execute` 按 `item_ids` 执行,Run 留痕不绑匹配;手工执行与自动排程共用同一入口。三层门禁任一不过 fail-closed(ERP 写入为 0): + + | 门禁 | 防什么 | 机制 | 失败表现 | + | --- | --- | --- | --- | + | ① 行级新鲜度 TTL | 时间漂移 | 行 `updated_at` 距 now 超过 `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` 拒绝 | `TRANSFER.ITEMS_STALE`(`details.stale_item_ids`) | + | ② 文件版本对账 | 文件漂移 | 行评估版本戳(file_sha256)≠ 来源最新可用文件 sha(含来源无可用文件 / 行无版本戳)即拒绝;评估后被更新版本文件取代而**消失的 ready 行**在匹配/重查时标 `blocked_file_removed` 入异常池(fail-closed,宁可误拒也不按过期文件写 ERP) | `TRANSFER.FILE_CHANGED`(`details.changed_item_ids`) | + | ③ 写前复查 | ERP 漂移 | 逐行重查库存 + 按收料仓库列重解析路由;库存变化/路由失败标记该行 `matching_expired` 阻断(单项失败不阻断其他行) | 行级 `matching_expired`(不整批失败) | + + 门禁前置校验:id 不存在或非 `ready_to_execute` → `TRANSFER.EXECUTE_ITEMS_INVALID`(`details.invalid_item_ids`)。 +- **恢复处理 = 行级重查**:待处理池「恢复处理」= 对选中行逐行 external_recheck(`POST /items/batch-requery`)**原地刷新 + 续新鲜度**,不创建匹配、不迁移行,单行隔离;ERP 事实修正后重查通过即回到可执行。按组重建范围匹配的 `POST /items/batch-resume` 与 `resume_service` 已删除,无兼容层。 + ## 5. 部署 ```bash @@ -65,7 +93,7 @@ cd backend && flask db upgrade # command: python workers/worker_in_transit_transfer.py,环境同后端) ``` -上线灰度顺序(路线图 §8.6):ERP 测试组织 UAT → 生产只读观察(预检、写=0)→ 小范围对话写入试点 → 正式对话写入 → 单来源自动排程 → 全部来源自动排程;每步留启用人/时间/配置版本/门禁结果/回退条件审计。 +上线灰度顺序(路线图 §8.6):ERP 测试组织 UAT → 生产只读观察(匹配、写=0)→ 小范围对话写入试点 → 正式对话写入 → 单来源自动排程 → 全部来源自动排程;每步留启用人/时间/配置版本/门禁结果/回退条件审计。 ## 6. 告警与运维关注点 @@ -75,6 +103,17 @@ cd backend && flask db upgrade - 外部系统查询超时率与 `ExternalNotFrozenError` 出现(说明契约/配置未冻结或 endpoint 缺失)。 - 归档 Hash 复核(`verify_archive_hash`)与 MinIO 容量。 +### 6.1 批量库存查询对账结论(2026-09-23) + +- **现象**:对话侧库存答复为 0,与 ERP 账套内真实库存(30/40/36)不一致,触发批量查询对账排查。 +- **根因**:收料仓库映射行曾指向**错误的 ERP 组织账套 TGHX**;2026-09-23 00:52 修正为 TGHX1 后重查得到真实库存 30/40/36。关键证据来自 `integration_calls` 落库:call_id 12/13(TGHX 账套)仅返回 2 条 Record 且 `img10=0`;call_id 163(TGHX1 账套)返回 30/40/36——查询链路本身无丢数/改数,差异完全由账套路由错误造成。 +- **WTP26060612**:在 TGHX1 亦真实查无,属真实业务答复,非缺陷。 +- **顺带修复**:`integration_connector/mapping.py` 记录扇出(fan-out)在嵌套形态下丢行的潜在缺陷已修复(该嵌套形态尚未在生产数据中观测到,属防御性修复)。 +- **待确认清单(移交 ERP/业务)**: + - `img10` vs `img11` 字段语义(在库 vs 可用):当前取 `img10`;若业务口径应为 `img11`(可用量),仅需管理端调整映射配置,无需改代码。 + - 批量 targets 跨 Invoice 未去重的双计风险:同一料号+库位+批号被多张 Invoice 共用时 targets 重复,建议在 `matching_service` 侧去重。 + - 组织账套白名单与变更审计:仓库映射的 `external_organization_code` 建议增加账套白名单校验与变更审计,避免再次静默指向错误账套。 + ## 7. 归档与数据保留 - 大型快照/Excel/报文经 `archive.py` 归档 MinIO,`transfer_archives` 索引+Hash 留库;归档必须重算 Hash 并写审计。 @@ -82,7 +121,7 @@ cd backend && flask db upgrade ## 8. 回退策略 -- 停用 `in-transit-transfer` 自动排程(不删除历史 Run);保留对话只读预检与手工执行。 +- 停用 `in-transit-transfer` 自动排程(不删除历史 Run);保留对话只读匹配与手工执行。 - `result_unknown` 继续进入人工核实池;已成功 ERP 单据不自动撤销。 - 回退配置走新发布版本 + Diff 审计,不直接改数据库。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 1b0e271e..6fb5ac08 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -76,6 +76,7 @@ - “保存订单并校验”是唯一确认入口。后端先保存 Draft,再在同一业务链路重新计算必填、证据、冲突、重复、客户确认和自动建单策略门禁;只有 `auto_create_enabled=true` 且全部自动建单门禁通过时,才返回 `can_auto_create=true` 并进入建单,否则返回稳定阻断原因及可执行的 Review 动作。 - **显式校验幂等短路 + STP Job 串行化(2026-09-22)**:STP 自动建单持有草稿(等待入队/排队/执行)且内容相对最近一次校验未变(`validation_result_json.content_checksum` 比对)时,重复“保存并校验”幂等短路——不递增 `draft_version`、不写 `draft_validated` 事件、不重复入队。背景:连点保存曾产生版本/Job 风暴,同文档两个 STP Job 并发在建单 advisory 锁上死锁且 `max_attempts=1` 一次判死(case 永久停在 ready)。配套修复:`ensure_stp_auto_create_for_case` 入队前作废同文档旧版本 queued Job(running 由执行期“新版替代”检查收口);STP Job `max_attempts` 1→3,死锁类瞬时失败在 attempts 耗尽前自动重排,业务阻断仍 `retryable=false` 收口为“等待用户选择下一步动作”。自动化持有期间前端复核表单只读,与后端 `_locked_case` 的 `SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION` 同义。 - **抽取交接不变量:STP 只由最后一个抽取 Job 入队(2026-09-22 第二轮)**:多附件 EML 版面分批就绪时,交接 Job 与续抽 Job 同 commit 入队并被双 worker 并发执行,抽取链(持 run 锁→锁 intake)与 STP 确认链(持 intake→进度写锁 run)以相反顺序形成**结构性死锁**(`SNER-20260922-6466EB53` 整 run 卡死、附件滞留识别;同日 `879785D1` 的 STP 死锁同族)。修复:①`submit_order_extraction_unit_result` 增加 `defer_stp_enqueue`——Worker 开工快照仍有待排版附件(`pending_layout_ids` 非空、必交接)时跳过本 Unit 的 STP 入队,Candidate/Review Case 仍即时物化,STP 统一由最后一个抽取 Job 的 run 收口(`submit_order_extraction_run_result`)与 run 状态同事务入队,时序上消除抽取∥STP 并发;②收口前重放推送失败必须冒泡(原 try/except 吞错不回滚,会把真实死锁伪装成 `InFailedSqlTransaction` 并静默丢单),删除吞错让异常走外层收口;③外层收口对瞬时锁错(SQLSTATE 40P01 死锁 / 55P03 锁超时)标记 `retryable=true`,队列在 attempts 耗尽前自动重排(requeue 状态为 queued,`sync_order_extraction_run_after_job_failure` 的终态守卫保证不会误收口 run),attempts 耗尽仍终态失败等人工。残余概率性锁对(版面收尾×抽取、复核编辑×后台确认)由③兜底为秒级自愈。 +- **库存回调×external-wait 轮询锁序约定(2026-09-23,test job 8818)**:库存 RPA 回调与 external-wait 轮询曾以相反顺序争抢 Gate 行与库存候选行(回调=先写候选后更 Gate;轮询=先锁 Gate 后读候选),轮询事务被毒化后以 `InFailedSqlTransaction` 终态失败、轮询链断裂(本次回调早 400ms 自愈,否则 run 永久停在 external-wait)。根治:回调侧写候选前先锁活跃 Execution 的全部 Gate 行(`_lock_process_gates_for_task`,批量与单任务两个入口统一),两侧在 Gate 锁上串行、环消失;防御:`shipping_process_gate` 轮询分支增加异常韧性——异常回滚后按 Gate 现状分流(仍 `waiting_external` 则以 `waiting_external_requeued` 收口并延迟重排保持轮询链不断;已被收口则 `poll_superseded` 安静结束),错误文本留在 `result_json.poll_error` 供排查,轮询 Job 永不终态失败。 - Review Gate 或字段冲突发生变化时,即使生命周期 `stage/status` 不变,也必须递增 `progress_version` 并写入对应审计事件。Review 工作台、聊天投影和任务详情均按该版本刷新,禁止以前端旧 Projection 推导按钮。 - 上传成功(人工确认或 RPA 回调)必须统一清除历史上传阻断原因并收口正式 Execution 的履约 Gate;Notice 面成功词唯一为 `uploaded`(经 `project_notice_upload_status`;Attempt 库内仍写 `succeeded`)。业务完成用 `has_verified_upload_success`;`facts.upload_state` 成功词为 `succeeded`(`project_facts_upload_state`)。禁止调用方再读 Attempt 原词或扩同义词集合。 - `resolve_field_conflicts` 仅在当前 Case 仍存在开放字段冲突时展示;Case 已无开放冲突时,旧 Projection 中残留的该动作必须被前端隐藏,同时以后端 `ui_state.actions` 为最终动作契约。 diff --git a/docs/funclist.md b/docs/funclist.md index d0429deb..a9dd2335 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -757,13 +757,17 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | -| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | ackend/app/models/in_transit_transfer.py(Run/SourceJob/Precheck/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e;13 状态服务端门禁(services/in_transit_transfer/status.py) | -| 收料文件准备与只读预检 | 后端已实现 | ready 复用/缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/ERP 库存查询/严格数量匹配/预检快照 Hash/进度恢复 | -| 确认与 ERP 原子调拨 | 后端已实现 | 直接生成执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按 ERP 单号聚合结果(ERP SOAP 实现在 WSDL 冻结前 fail-closed) | +| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) | +| 收料文件准备与只读匹配(原"预检") | 后端已实现 | ready 复用/缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/ERP 库存查询/严格数量匹配/匹配快照 Hash/进度恢复 | +| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行生成执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按 ERP 单号聚合结果(ERP SOAP 实现在 WSDL 冻结前 fail-closed) | | 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | -| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入预检 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) | +| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) | | 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | -| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/预检/结果/待处理)与 admin 模块按计划实施 | +| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) | +| 待处理池批量操作与恢复处理 | 已实现 | 批量重查(恢复处理=行级重查原地刷新+续新鲜度)/批量关闭;blocked_file_removed 消失行 fail-closed 入异常池;匹配=评估留痕,行不迁移 | +| 按行执行与三层执行门禁 | 已实现 | execute(item_ids):行级新鲜度 TTL + 文件版本对账 + 写前复查;Run 留痕不绑匹配;确认 TTL/hash 拦截退役(hash 留痕) | +| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 D+1 规则日期(上海业务日 T-1);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 | +| 前端 Chat 卡片/结果页与四语言 | 实施中 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块按计划实施 | --- diff --git a/docs/superpowers/plans/2026-09-23-transfer-erp-write-path.md b/docs/superpowers/plans/2026-09-23-transfer-erp-write-path.md new file mode 100644 index 00000000..37d914c6 --- /dev/null +++ b/docs/superpowers/plans/2026-09-23-transfer-erp-write-path.md @@ -0,0 +1,1003 @@ +# 在途调拨 ERP 写路径打通(中间表 + TIPTOP WS)实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 打通在途调拨写路径:按(组织×来源×路由)分组建单,经集成连接器新增 `database` 类型直写 ERP Oracle 中间表 `htt.gls_cm_file`,SOAP 触发 TIPTOP WS 同步建单,按六态分类落位。 + +**Architecture:** 外部建单的域契约永久固定(`CapabilityClient.create_transfer(票级参数) → TransferWriteResult 六态`),编排差异收敛到 `write_strategies.py` 策略注册表——一期唯一策略 `tiptop_stage_submit`(写中间表 → SOAP 触发建单,WS 同步返回即终态裁决,无回读);未来直连类系统=新增一个策略类,域上层零改动。两步各经 CapabilityGateway 独立绑定/审计;幂等靠「同一 gls_cm27 批次号 + stage 前 DELETE 同批次未处理行 + 票级在飞守卫」;执行粒度从按行升级为按票(`TransferDocument` 新表)。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;`oracledb`(thin,先例 `voucher_check/erp_repository`);既有集成连接器框架(engine/binding/mapping/transports)。 + +**Spec:** 契约与决策记录见 `.engramory-memory/in-transit-transfer.md` §写路径 ERP 契约样例(2026-09-23)与本文档 §全局约束;ERP 报文样例以用户提供为准(本文 Task 12 固化为配置)。 + +## 全局约束(每个任务隐含遵守) + +- fail-closed:任何契约/绑定/凭据缺失一律拒绝,禁止猜测默认值(`BindingNotFoundError` / `TransportNotFrozenError` 语义不变)。 +- SQL 一律绑定变量(`:name`),禁止字符串拼值进 SQL 文本;表名/常量来自接口定义配置(管理端受控),不来自调用参数。 +- **中间表 SQL 全文属于接口定义配置(管理端维护、发布门禁管控),后端代码零 SQL**:`OracleSqlTransport` 仅是通用 SQL 执行器,不得出现任何 `gls_cm`/调拨业务词汇(Task 2 有回归锁);改列/改常量/换组织 = 管理端改接口定义或绑定,零代码发布。 +- **通用性锚点**:`create_transfer(票) → 六态` 是域永久契约,execution/retry/结果投影不感知外部系统差异;每个外部系统的建单步骤序列 = 一个编排策略类(代码注册,含裁决语义,**禁配置 DSL 编排**);未来多系统并存=新策略类 + 绑定 context_selector 路由(框架既有能力),策略选择配置键等第二系统接入时再加(YAGNI)。 +- 改表结构必须配套 Alembic 迁移;迁移链 `down_revision` 一律先 `cd backend && flask db heads` 取当前 head 再写。 +- 新增 error.code 同步四语言 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`;新增界面文案同步四语言。 +- 后端注释遵循 AGENTS.md §5(模块 docstring 三要素 + 函数 docstring Args/Returns + `[STEP n]`);测试含断言意图注释。 +- **禁止自动 commit**:每个任务以 `git add <具体文件>` 结束,提交由用户批准。 +- 六态写分类语义不变:success / duplicate_success / business_failed / technical_failed / timeout / result_unknown;`result_unknown` 仍为终态禁自动重试。 +- 幂等纪律(本次冻结):**同一票(文档)生命周期内 `doc_no` 与 `batch_id`(gls_cm27)一经生成永不更换**;重写幂等 = stage 前 `DELETE 同批次且状态='10'` + 票级在飞守卫,**不配置状态回读**(`result_unknown` 走人工核实 SOP:在 ERP 按来源单号查单)。 +- 域内禁止 `erp_*` 命名外部系统字段(沿用 `external_org` 等既有口径)。 + +## 命名对照表(执行者必读) + +| 名字 | 出现层 | 含义 | +| --- | --- | --- | +| `stage_transfer_order` | 能力(代码注册) | 「调拨单暂存」——把票写入 ERP 中间表待处理(stage = staging table,中间表的行业叫法;2026-09-23 用户确认不改名) | +| `submit_transfer_order` | 能力(代码注册) | 「提交建单」——SOAP 调 TIPTOP WS,同步生成 ERP 调拨单 | +| `create_transfer` | 能力(代码注册) | 域编排门面声明 = 暂存 + 提交 两步的组合(CapabilityClient 方法同名) | +| `tiptop_stage_submit` | 编排策略(代码注册) | TIPTOP 专属建单序列:先 stage 写中间表、再 submit 触发 WS;未来其他外部系统 = 新策略类(如单接口直连 `direct_api`),域契约不变 | +| `htt_gls_cm_stage` / `htt_tiptop_submit` | 接口定义(管理端配置) | **编码仅为本文示例,管理员自定**:接口定义整行(编码、SQL/报文全文、含 schema 前缀的表名)都由管理员在界面自行创建,后端代码零引用接口编码;能力↔接口的配对走绑定(同样是管理端配置) | +| `doc_no` / `batch_id` | 域参数 | 来源单号(HTT-OR-…,gls_cm04)/ 批次幂等锚(gls_cm27);一票一生成终身复用 | + +## 文件结构总览 + +```text +backend/ + app/models/integration_connector.py # 改:CONNECTOR_TYPES + 'database' + app/models/in_transit_transfer.py # 改:TransferDocument 新表 + Item.document_id/unit + Attempt.document_id + app/api/integration_connector.py # 改:VALID_CONNECTOR_TYPES + app/services/integration_connector/ + transports/oracle_sql.py # 新:Oracle SQL 传输(execute/query + probe) + gateway.py # 改:注册 database 传输 + engine.py # 改:write 能力先响应映射再分类,data 恒带映射结果 + app/services/in_transit_transfer/ + capabilities.py # 改:能力契约重造(3 能力 + 能力名常量) + capability_client.py # 改:create_transfer 委派编排策略(六态裁决移入策略) + write_strategies.py # 新:建单编排策略注册表(每外部系统一个策略类) + document_id.py # 新:HTT-OR 单号 + gls_cm27 批次号生成 + execution_service.py # 改:分组建单 + 票级执行 + 结果落位 + movement_contract.py / file_parser.py / precheck_service.py # 改:unit 第 11 字段 + migrations/versions/ # 新迁移 ×4(连接器类型 CHECK、单号序列、调拨表、unit 列) + tests/services/in_transit_transfer/... # 改/新 +frontend/src/features/admin/modules/integration-connector/ # 改:database 类型表单 + 四语言 +docs/features/in-transit-transfer/technical.md · docs/funclist.md # 改 +``` + +--- + +### Task 1: `database` 连接器类型注册(模型 + 迁移 + API) + +**Files:** +- Modify: `backend/app/models/integration_connector.py:35`(CONNECTOR_TYPES) +- Modify: `backend/app/api/integration_connector.py:48`(VALID_CONNECTOR_TYPES) +- Create: `backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py` +- Test: `backend/tests/services/integration_connector/test_database_connector_type.py` + +**Interfaces:** +- Produces: `CONNECTOR_TYPES = ('rest', 'soap', 'database')`;API 校验放行 `database`;迁移把 `integration_client_instances` / `integration_interface_definitions` 两表 CHECK 约束同步为三值。 + +- [ ] **Step 1: 写失败测试** + +```python +"""database 连接器类型:模型常量 / API 校验 / CHECK 约束三处一致(回归锁)。""" +from app.models.integration_connector import CONNECTOR_TYPES + + +def test_database_is_registered_connector_type(): + # 断言:'database' 进入合法类型集,且模型与 API 白名单同源不漂移 + assert 'database' in CONNECTOR_TYPES + from app.api.integration_connector import VALID_CONNECTOR_TYPES + assert set(VALID_CONNECTOR_TYPES) == set(CONNECTOR_TYPES) +``` + +- [ ] **Step 2: 运行确认失败** —— `cd backend && pytest -q tests/services/integration_connector/test_database_connector_type.py`,预期 FAIL(`'database' not in`)。 + +- [ ] **Step 3: 最小实现** —— 两处常量加 `'database'`;建迁移(先 `flask db heads` 取 head 作为 down_revision): + +```python +"""add database connector type + +Revision ID: tt7a8b9c0d1e +""" +from alembic import op + +old = "('rest', 'soap')" +new = "('rest', 'soap', 'database')" + + +def upgrade() -> None: + # 两个约束同名分属两表,逐一重建(先删后建,SQLite 批量模式不适用——生产为 PG) + op.drop_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances', type_='check') + op.create_check_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances', + f"connector_type IN {new}") + op.drop_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions', type_='check') + op.create_check_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions', + f"connector_type IN {new}") + + +def downgrade() -> None: + # 回滚前置:database 实例/接口必须先人工清空,否则 CHECK 违约 + op.drop_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances', type_='check') + op.create_check_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances', + f"connector_type IN {old}") + op.drop_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions', type_='check') + op.create_check_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions', + f"connector_type IN {old}") +``` + +注意:模型文件内 CheckConstraint 是 `f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})"` 动态生成,常量改后自动跟随,勿手改表达式。 + +- [ ] **Step 4: 运行测试通过** + `pytest -q tests/services/integration_connector tests/api/test_integration_connector_api.py`(存量全绿)。 + +- [ ] **Step 5: 落盘** —— `git add backend/app/models/integration_connector.py backend/app/api/integration_connector.py backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py backend/tests/services/integration_connector/test_database_connector_type.py` + +--- + +### Task 2: Oracle SQL 传输层 `transports/oracle_sql.py` + +**Files:** +- Create: `backend/app/services/integration_connector/transports/oracle_sql.py` +- Modify: `backend/app/services/integration_connector/gateway.py`(注册) +- Test: `backend/tests/services/integration_connector/test_oracle_sql_transport.py` + +**Interfaces:** +- Produces: `OracleSqlTransport(connector_type='database')`,实现 `call(client, interface, request) -> dict` 与 `probe(client) -> dict`。 +- request_spec_json 契约(`sql` 节点): + - 执行型:`{"sql": {"mode": "execute", "pre": ["DELETE ..."], "bulk": {"sql": "INSERT ...", "rows_param": "lines"}, "post": []}}`;bulk 行先与 `request['params']` 合并(行内同名键覆盖基础参数),`executemany` 一次提交。 + - 查询型:`{"sql": {"mode": "query", "sql": "SELECT ..."}}`;列别名即输出键,返回 `{"status": "success", "rows": [{...}]}`。 +- 客户端 config:`endpoint` 列 = Oracle 连接串(`host:port/service_name`),`timeout_seconds`,可选 `oracle_lib_dir`(thick 模式);凭据复用 `password` 类型(`credential_username`/`credential_password` → 组装为 `username`/`password`)。 + +- [ ] **Step 1: 写失败测试**(连接工厂注入替身,不连真库) + +```python +"""Oracle SQL 传输:绑定变量执行 / bulk 合并 / query 返回行 / 失败脱敏(全部用假连接)。""" +from app.services.integration_connector.transports.oracle_sql import OracleSqlTransport + + +class FakeCursor: + def __init__(self, rows=None): + self.rows = rows or [] + self.executed = [] + + def execute(self, sql, params=None): + self.executed.append(("execute", sql, params)) + + def executemany(self, sql, rows): + self.executed.append(("executemany", sql, rows)) + + @property + def rowcount(self): + return len(self.executed) + + def __iter__(self): + return iter(self.rows) + + +class FakeConnection: + def __init__(self, rows=None): + self.cursor_obj = FakeCursor(rows) + self.committed = False + self.rolled_back = False + + def cursor(self): + return self.cursor_obj + + def commit(self): + self.committed = True + + def rollback(self): + self.rolled_back = True + + def close(self): + pass + + +def _client(credential=None): + return {"config_json": {"endpoint": "dbhost:1521/HTTPDB", "timeout_seconds": 30}, + "credential": credential or {"username": "u", "password": "p"}} + + +def test_execute_runs_pre_bulk_post_and_commits(): + conn = FakeConnection() + transport = OracleSqlTransport(connection_factory=lambda config, cred: conn) + raw = transport.call( + client=_client(), + interface={"request_spec_json": {"sql": { + "mode": "execute", + "pre": ["DELETE FROM htt.gls_cm_file WHERE gls_cm27 = :batch_id AND gls_cm29 = '10'"], + "bulk": {"sql": "INSERT INTO htt.gls_cm_file (gls_cm04) VALUES (:doc_no)", "rows_param": "lines"}, + "post": [], + }}}, + request={"params": {"batch_id": "B1", "doc_no": "D1", "lines": [{"doc_no": "D1", "material_no": "M1"}]}}, + ) + # 断言:bulk 行与基础参数合并(行内含 doc_no),DELETE→INSERT→commit 顺序执行 + assert raw["status"] == "success" + kinds = [item[0] for item in conn.cursor_obj.executed] + assert kinds == ["execute", "executemany"] + assert conn.committed and conn.rolled_back is False + bulk_rows = conn.cursor_obj.executed[1][2] + assert bulk_rows[0]["batch_id"] == "B1" and bulk_rows[0]["material_no"] == "M1" + + +def test_query_returns_rows_as_dicts(): + conn = FakeConnection(rows=[{"status_code": "30", "document_no": "1401-1"}]) + transport = OracleSqlTransport(connection_factory=lambda config, cred: conn) + raw = transport.call( + client=_client(), + interface={"request_spec_json": {"sql": {"mode": "query", "sql": "SELECT gls_cm29 AS status_code FROM htt.gls_cm_file WHERE gls_cm04 = :doc_no"}}}, + request={"params": {"doc_no": "D1"}}, + ) + # 断言:query 模式返回 rows 列表且不 commit(只读) + assert raw["status"] == "success" + assert raw["rows"][0]["document_no"] == "1401-1" + assert conn.committed is False + + +def test_db_error_is_masked_technical_failure(): + class Boom(FakeConnection): + def cursor(self): + raise RuntimeError("ORA-01017 invalid username/password: u/p@dbhost") + + transport = OracleSqlTransport(connection_factory=lambda config, cred: Boom()) + raw = transport.call(client=_client(), interface={"request_spec_json": {"sql": {"mode": "execute", "pre": [], "post": []}}}, request={"params": {}}) + # 断言:异常归 technical_failed,且凭据值被 *** 脱敏 + assert raw["status"] == "technical_failed" + assert "u/p@dbhost" not in raw["message"] and "***" in raw["message"] or "u" != raw["message"] + + +def test_probe_selects_dual(): + conn = FakeConnection(rows=[{"one": 1}]) + transport = OracleSqlTransport(connection_factory=lambda config, cred: conn) + result = transport.probe(client=_client()) + # 断言:probe 只证明可达(SELECT 1 FROM DUAL),不要求业务契约 + assert result["ok"] is True + + +def test_missing_endpoint_fails_closed(): + transport = OracleSqlTransport(connection_factory=lambda config, cred: FakeConnection()) + client = {"config_json": {}, "credential": {}} + # 断言:无 endpoint 直接抛 TransportNotFrozenError(fail-closed) + import pytest + from app.services.integration_connector.errors import TransportNotFrozenError + with pytest.raises(TransportNotFrozenError): + transport.call(client=client, interface={"request_spec_json": {"sql": {"mode": "query", "sql": "SELECT 1 FROM DUAL"}}}, request={"params": {}}) + + +def test_transport_is_business_agnostic(): + import inspect + from app.services.integration_connector.transports import oracle_sql + + source = inspect.getsource(oracle_sql) + # 断言:传输层零业务知识——不出现中间表列名/调拨词汇;SQL 全文属于接口定义配置, + # 这是"插入逻辑不写死、能力可配置"的代码级回归锁。 + assert "gls_cm" not in source + assert "调拨" not in source and "C0089" not in source +``` + +- [ ] **Step 2: 运行确认失败** —— `pytest -q tests/services/integration_connector/test_oracle_sql_transport.py`,预期 FAIL(模块不存在)。 + +- [ ] **Step 3: 实现**(完整模块) + +```python +"""services/integration_connector/transports/oracle_sql.py + +用途:database(Oracle 直连)传输——按接口 SQL 规格执行绑定变量语句,覆盖 + 中间表写入(execute)与状态回读(query)两类接口。 +依赖:oracledb(惰性 import)、errors.py、transports.base.mask_secrets。 +逻辑:endpoint(DSN)或 SQL 规格缺失 → fail-closed;所有值经 :named 绑定变量, + 禁止拼接;execute 按 pre→bulk→post 单事务提交,异常回滚并脱敏归 + technical_failed;query 返回列别名为键的 rows,不 commit; + probe = SELECT 1 FROM DUAL(只证明可达)。连接工厂可注入供测试。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +from app.services.integration_connector.errors import TransportNotFrozenError +from app.services.integration_connector.transports.base import mask_secrets + +ConnectionFactory = Callable[[dict, dict], Any] + + +def _default_connect(config: dict, credential: dict) -> Any: + """按客户端配置建 Oracle 连接;凭据键取 credential_types password 形态组装值。""" + import oracledb + + dsn = str(config.get('endpoint') or '').strip() + if not dsn: + raise TransportNotFrozenError('database contract not frozen (missing endpoint/DSN)') + lib_dir = str(config.get('oracle_lib_dir') or '').strip() + if lib_dir: + oracledb.init_oracle_client(lib_dir=lib_dir) + return oracledb.connect( + user=str(credential.get('username') or ''), + password=str(credential.get('password') or ''), + dsn=dsn, + ) + + +class OracleSqlTransport: + """Oracle SQL 传输;connection_factory 可注入以便单元测试(默认真连)。""" + + connector_type = 'database' + + def __init__(self, connection_factory: ConnectionFactory | None = None): + self._connection_factory = connection_factory or _default_connect + + def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: + config = client.get('config_json') or {} + if not str(config.get('endpoint') or '').strip(): + raise TransportNotFrozenError('database contract not frozen (missing endpoint/DSN)') + spec = (interface.get('request_spec_json') or {}).get('sql') or {} + if not spec: + raise TransportNotFrozenError('database contract not frozen (missing sql spec)') + params = dict(request.get('params') or {}) + credential = client.get('credential') or {} + try: + connection = self._connection_factory(config, credential) + except TransportNotFrozenError: + raise + except Exception as exc: # noqa: BLE001 —— 连接失败(含驱动缺失)统一脱敏归技术失败 + return self._failure('DB_CONNECT_FAILED', exc, credential) + try: + mode = str(spec.get('mode') or 'execute') + cursor = connection.cursor() + if mode == 'query': + cursor.execute(str(spec['sql']), params) + columns = [str(desc[0]).lower() for desc in cursor.description] + rows = [dict(zip(columns, row)) for row in cursor.fetchall()] + return {'status': 'success', 'rows': rows} + # [STEP 1] pre:清理同批次未处理行(幂等 DELETE) + for statement in spec.get('pre') or []: + cursor.execute(str(statement), params) + # [STEP 2] bulk:行参数与基础参数合并(行内同名键覆盖)后 executemany + bulk = spec.get('bulk') + if bulk: + base = {k: v for k, v in params.items() if not isinstance(v, (list, dict))} + rows = [dict(base, **row) for row in (params.get(str(bulk.get('rows_param')) or 'lines') or [])] + cursor.executemany(str(bulk['sql']), rows) + # [STEP 3] post + 单事务提交 + for statement in spec.get('post') or []: + cursor.execute(str(statement), params) + connection.commit() + return {'status': 'success', 'rows_affected': int(getattr(cursor, 'rowcount', 0) or 0)} + except Exception as exc: # noqa: BLE001 —— 执行失败回滚 + 脱敏(错误文本可能回显绑定值) + try: + connection.rollback() + except Exception: # noqa: BLE001 + pass + return self._failure('DB_EXECUTE_FAILED', exc, credential) + finally: + try: + connection.close() + except Exception: # noqa: BLE001 + pass + + def probe(self, *, client: dict) -> dict[str, Any]: + """连接测试探针:SELECT 1 FROM DUAL,只证明网络/账号/服务可达。""" + config = client.get('config_json') or {} + credential = client.get('credential') or {} + try: + connection = self._connection_factory(config, credential) + except Exception as exc: # noqa: BLE001 + return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], credential)} + try: + cursor = connection.cursor() + cursor.execute('SELECT 1 FROM DUAL') + cursor.fetchall() + return {'ok': True, 'code': 'DB_OK', 'message': 'select dual ok'} + except Exception as exc: # noqa: BLE001 + return {'ok': False, 'code': 'DB_ERROR', 'message': mask_secrets(str(exc)[:500], credential)} + finally: + try: + connection.close() + except Exception: # noqa: BLE001 + pass + + @staticmethod + def _failure(code: str, exc: Exception, credential: dict) -> dict[str, Any]: + return { + 'status': 'technical_failed', + 'code': code, + 'message': mask_secrets(str(exc)[:500], credential), + } +``` + +gateway.py 注册(`get_capability_gateway`): + +```python +from app.services.integration_connector.transports.oracle_sql import OracleSqlTransport +# ... + return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport(), 'database': OracleSqlTransport()}) +``` + +- [ ] **Step 4: 运行通过** + 存量 connector 测试全绿。 +- [ ] **Step 5: 落盘** —— `git add` 上述三个文件。 + +--- + +### Task 3: 引擎写能力「先响应映射再分类」 + +**Files:** +- Modify: `backend/app/services/integration_connector/engine.py:135-141`(call 内写分支) +- Test: `backend/tests/services/integration_connector/test_engine_write_mapping.py` + +**Interfaces:** +- Produces: 写能力调用行为——①传输层已判失败(`RESULT_FAILURE_STATUSES`)短路不变;②否则先过 `response_mapping` 归一为 `{status, document_no, ...}` 再 `classify_transport_response`;③`result.data` **恒携带**映射后 dict(原实现仅成功态带 data,业务侧需要从 data 读 `code`/`message` 二次解释)。 +- 兼容性:读能力路径零改动;未配置 response_mapping 的写接口(如 SQL 写入返回自带 status)行为不变。 + +- [ ] **Step 1: 写失败测试** + +```python +"""引擎写能力:Tiptop 无 status 键的原始响应经映射归一后再分类;data 恒携带映射结果。""" +from app.services.integration_connector.capability import CapabilitySpec, register_capability, reset_capabilities +from app.services.integration_connector.engine import CapabilityGateway + + +class _FakeTransport: + connector_type = 'soap' + + def call(self, *, client, interface, request): + # 模拟 TIPTOP Response 归一化形状:无 status 键,ERP 单号藏在 @name/@value 列表 + return {"Response": {"Execution": {"Status": {"@code": "0", "@description": ""}}, + "ResponseContent": {"Parameter": {"Record": {"Field": [ + {"@name": "doc_no", "@value": "1401-2609230003"}]}}}}} + + def probe(self, *, client): + return {"ok": True} + + +def test_write_capability_maps_response_before_classify(reset_capability_registry, app_ctx): + reset_capabilities() + register_capability(CapabilitySpec(name="t.write", input_schema={}, output_schema={}, idempotency="none", write=True)) + gateway = CapabilityGateway(transports={"soap": _FakeTransport()}) + result = gateway.call( + capability="t.write", context={}, params={}, + operation_id="op-test", environment="prod", transports={"soap": _FakeTransport()}, + # 绑定解析依赖 DB(app_ctx 夹具内 seed client/interface/binding,response_mapping 如下) + # response_mapping = { + # "status": {"expr": "Response.Execution.Status.@code", "transform": "enum-map", "args": {"mapping": {"0": "success"}}}, + # "document_no": {"expr": "Response.ResponseContent.Parameter.Record.Field", "transform": "pick", + # "args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}}, + # } + ) + # 断言:code=0 经 enum-map 归一 success;document_no 经 pick 取出;data 恒带映射 dict + assert result.status == "success" + assert result.document_no == "1401-2609230003" + assert result.data["document_no"] == "1401-2609230003" +``` + +(夹具按既有 `test_binding` / connector API 测试的 seed 方式落 ClientInstance+InterfaceDefinition+Binding 三行,response_mapping 用注释中 JSON。) + +- [ ] **Step 2: 运行确认失败** —— 现实现 raw 无 status → `technical_failed`。 +- [ ] **Step 3: 实现** —— `engine.call` 中: + +```python + if isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES: + # 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML、DB 异常)→ 原样分类,不做输出映射。 + result = classify_transport_response(raw) + elif spec.write: + # [写能力] 先按响应映射归一为 {status, document_no, code, message}(如 Tiptop + # 状态码→六态),再走通用分类;data 恒携带映射结果供域层二次解释(如非 0 码→业务失败)。 + mapped = raw + if snapshot.response_mapping: + mapped = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema) + result = classify_transport_response(mapped if isinstance(mapped, dict) else {}) + result = replace(result, data=mapped if isinstance(mapped, dict) else raw) + elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES: + result = classify_transport_response(raw) + else: + result = IntegrationCallResult(status='success') +``` + +(原有 `if spec.write:` 直接 classify 的分支删除;成功态末尾的 data 映射对写能力跳过——`result.status in (...)` 分支对写能力保持原样即可,重复映射无害但浪费,加 `and not spec.write` 守卫。) + +- [ ] **Step 4: 全绿** —— `pytest -q tests/services/integration_connector`。 +- [ ] **Step 5: 落盘。** + +--- + +### Task 4: 能力契约重造(`capabilities.py`) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/capabilities.py` +- Test: `backend/tests/services/in_transit_transfer/test_capabilities_contract.py`(新) + +**Interfaces:** +- Produces 三个能力(`register_transfer_capabilities` 幂等注册,组合根零改动): + - `in_transit_transfer.stage_transfer_order`(write, idempotency=batch):入参 = 票级 Schema(下),出参 = `_WRITE_OUTPUT_SCHEMA`。 + - `in_transit_transfer.submit_transfer_order`(write, idempotency=batch):入参 `{external_org, doc_no, batch_id}`,出参 = `_WRITE_OUTPUT_SCHEMA`。 + - `in_transit_transfer.create_transfer`(write, idempotency=batch):入参 = 票级 Schema(域编排门面声明,不经网关直调,仅作能力清单展示与契约文档)。 +- 删除:`verify_duplicate` 能力声明与 `_QUERY_INPUT_SCHEMA` 占位(`create_transfer` 旧 Schema);重复票裁决依赖 WS 同步响应,不设回读能力(2026-09-23 用户拍板)。 + +- [ ] **Step 1: 写失败测试** + +```python +"""能力契约:票级 Schema 必填字段与三能力注册(幂等重注册不报错)。""" +from app.services.in_transit_transfer.capabilities import register_transfer_capabilities +from app.services.integration_connector.capability import get_capability + + +def test_stage_capability_requires_doc_and_lines(): + register_transfer_capabilities() + spec = get_capability("in_transit_transfer.stage_transfer_order") + # 断言:票级入参必备 单号/批次/组织/行数组;行必备 料号/仓/批号/数量/单位/行号 + for field in ("external_org", "doc_no", "batch_id", "lines"): + assert field in spec.input_schema["required"] + line_required = spec.input_schema["properties"]["lines"]["items"]["required"] + assert set(line_required) >= {"line_no", "material_no", "from_warehouse", "to_warehouse", "lot_no", "quantity", "unit"} + + +def test_submit_capability_is_doc_ref_input(): + register_transfer_capabilities() + spec = get_capability("in_transit_transfer.submit_transfer_order") + # 断言:WS 触发只带 单据引用三元组,且是写能力 + assert set(spec.input_schema["required"]) == {"external_org", "doc_no", "batch_id"} + assert spec.write is True +``` + +票级 Schema(实现内容): + +```python +_TRANSFER_LINE_SCHEMA: dict = { + "type": "object", + "required": ["line_no", "material_no", "from_warehouse", "to_warehouse", "lot_no", "quantity", "unit"], + "properties": { + "line_no": {"type": "string"}, + "material_no": {"type": "string"}, + "from_warehouse": {"type": "string"}, + "to_warehouse": {"type": "string"}, + "lot_no": {"type": "string"}, + "quantity": {"type": "string"}, + "unit": {"type": "string"}, + }, +} +_TICKET_INPUT_SCHEMA: dict = { + "type": "object", + "required": ["external_org", "doc_no", "batch_id", "doc_date", "posting_date", "lines"], + "properties": { + "external_org": {"type": "string"}, + "doc_no": {"type": "string"}, + "batch_id": {"type": "string"}, + "doc_date": {"type": "string"}, # YYYY-MM-DD 制单日期 + "posting_date": {"type": "string"}, # YYYY-MM-DD 过账日期 + "lines": {"type": "array", "items": _TRANSFER_LINE_SCHEMA}, + }, +} +_DOC_REF_INPUT_SCHEMA: dict = { + "type": "object", + "required": ["external_org", "doc_no", "batch_id"], + "properties": {"external_org": {"type": "string"}, "doc_no": {"type": "string"}, "batch_id": {"type": "string"}}, +} +``` + +- [ ] **Step 2: 失败 → Step 3: 实现**(按上表替换 `register_transfer_capabilities` 的四能力与 Schema 常量;`_QUERY_INPUT_SCHEMA` 保留给 query_inventory)。 +- [ ] **Step 4: 全绿**(in_transit_transfer 存量 + 新测试)。 +- [ ] **Step 5: 落盘。** + +--- + +### Task 5: 单号与批次号生成器 `document_id.py` + +**Files:** +- Create: `backend/app/services/in_transit_transfer/document_id.py` +- Create: `backend/migrations/versions/tt8b9c0d1e2f_add_transfer_doc_no_seq.py` +- Test: `backend/tests/services/in_transit_transfer/test_document_id.py` + +**Interfaces:** +- Produces: + - `new_batch_id(now: datetime | None = None) -> str` —— 32 位 uuid4 hex + `yyyyMMddHHmmssSSS`(与 ERP 样例 `gls_cm27` 同构)。 + - `next_document_no(external_org: str, *, now=None, sequence_loader: Callable[[], int] | None = None) -> str` —— `{org}-OR-{yyMMdd}{seq:05d}`(全局 PG 序列,超 99999 自然扩位)。 + +- [ ] **Step 1: 失败测试** + +```python +"""单号/批次生成:格式契约 + 序列注入;批次号是票生命周期幂等锚(长度/字符集锁定)。""" +from app.services.in_transit_transfer.document_id import new_batch_id, next_document_no + + +def test_batch_id_format_matches_erp_sample(): + from datetime import datetime + value = new_batch_id(datetime(2026, 9, 23, 9, 52, 8, 25000)) + # 断言:32hex + 17 位时间戳(样例 ecd459a6...20260923095208025 同构) + assert len(value) == 49 and value[32:] == "20260923095208025" + assert all(c in "0123456789abcdef" for c in value[:32]) + + +def test_document_no_format(): + value = next_document_no("HTT", now=__import__("datetime").datetime(2026, 9, 23), sequence_loader=lambda: 5) + # 断言:组织-OR-年月日+5位流水(样例 HTT-OR-260923000005 同构) + assert value == "HTT-OR-260923000005" + + +def test_document_no_sequence_over_99999_expands(): + value = next_document_no("HTT", sequence_loader=lambda: 100000) + # 断言:超五位自然扩位不截断(唯一性优先于格式定长) + assert value == "HTT-OR-260923100000" +``` + +- [ ] **Step 2: 失败 → Step 3: 实现** + +```python +"""services/in_transit_transfer/document_id.py + +用途:ERP 建单的两个幂等锚生成——来源单号(gls_cm04,{org}-OR-yyMMdd+全局序列) + 与批次号(gls_cm27,uuid+毫秒时间戳)。 +依赖:app.db(PG 序列 nextval,可注入替身)。 +逻辑:批次号与单号在票(TransferDocument)创建时生成一次、终身复用;重试/重执行 + 禁止重新生成(否则中间表残留未处理行会被 ERP 侧捡走造成双单)。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime +from typing import Callable + +DOC_NO_SEQUENCE = 'transfer_doc_no_seq' + + +def new_batch_id(now: datetime | None = None) -> str: + """批次幂等锚:uuid4 hex(32) + yyyyMMddHHmmssSSS(与样例 gls_cm27 同构)。""" + moment = now or datetime.utcnow() + return f"{uuid.uuid4().hex}{moment.strftime('%Y%m%d%H%M%S%f')[:17]}" + + +def next_document_no(external_org: str, *, now: datetime | None = None, + sequence_loader: Callable[[], int] | None = None) -> str: + """来源单号:{org}-OR-{yyMMdd}{seq:05d};序列全局递增免按日重置的并发计数表。""" + loader = sequence_loader or _next_sequence_value + date_part = (now or datetime.utcnow()).strftime('%y%m%d') + return f"{external_org}-OR-{date_part}{int(loader()):05d}" + + +def _next_sequence_value() -> int: + from sqlalchemy import text + from app import db + + return int(db.session.execute(text(f'SELECT nextval(:seq)'), {'seq': DOC_NO_SEQUENCE}).scalar_one()) +``` + +迁移(head 先查): + +```python +"""add transfer_doc_no_seq + +Revision ID: tt8b9c0d1e2f +""" +from alembic import op + +SEQ = op.create_table # noqa: F841 —— 占位勿用;实际用原生 SQL(PG 方言) + + +def upgrade() -> None: + op.execute("CREATE SEQUENCE IF NOT EXISTS transfer_doc_no_seq START WITH 1 INCREMENT BY 1") + + +def downgrade() -> None: + op.execute("DROP SEQUENCE IF EXISTS transfer_doc_no_seq") +``` + +(删掉 `SEQ = ...` 占位行——写文件时不要它;`nextval` 用 `text('SELECT nextval(\'transfer_doc_no_seq\')')` 直拼常量即可,序列名是代码常量非用户输入。) + +- [ ] **Step 4: 全绿 → Step 5: 落盘。** + +--- + +### Task 6: 交易单位(movement 契约第 11 字段) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/movement_contract.py`(MOVEMENT_FIELDS) +- Modify: `backend/app/services/in_transit_transfer/file_parser.py`(parse_movement_rows 透传 unit) +- Modify: `backend/app/services/in_transit_transfer/precheck_service.py`(建 Item 时落 unit;缺失 → 行级 blocked) +- Modify: `backend/app/models/in_transit_transfer.py`(TransferInvoiceItem 加 `unit` 列) +- Create: `backend/migrations/versions/tt9c0d1e2f3a_add_transfer_invoice_items_unit.py` +- Test: `backend/tests/services/in_transit_transfer/test_unit_field.py`(新)+ 存量 movement 测试 + +**Interfaces:** +- Produces: `MOVEMENT_FIELDS` 含 `unit`;`TransferInvoiceItem.unit: Mapped[str]`(String(16),NOT NULL,server_default '')。 +- 语义:解析规则(movement profile)的 `field_mapping` 必须映射 unit 列;文件缺列/行值为空 → 该行预检落 `missing_unit` 行级 blocked(**不做**文件级 ReceiptFileSchemaError——单位缺失不该废掉整份收料文件,与 doc_no 缺失的文件级语义不同,此差异写入 movement_contract 注释)。 + +- [ ] **Step 1: 失败测试**(三断言:契约含 unit;解析行带 unit 原值;空 unit 行 → 预检 blocked 且 reason=missing_unit,同文件其余行不受影响) +- [ ] **Step 2: 失败 → Step 3: 实现**(按 Interfaces;迁移加列;`recompute_precheck_hash` 的 items 快照**不加** unit——Hash 口径不变,避免存量预检 409)。 +- [ ] **Step 4: 全绿(含存量 test_movement_file_repository / test_precheck_service)→ Step 5: 落盘。** + +--- + +### Task 7: `TransferDocument` 票模型 + 迁移 + +**Files:** +- Modify: `backend/app/models/in_transit_transfer.py`(新模型 + 常量 + Item/Attempt 外键) +- Create: `backend/migrations/versions/tt0d1e2f3a4b_add_transfer_documents.py` +- Test: `backend/tests/services/in_transit_transfer/test_document_model.py`(新,含迁移链测试更新 `test_migration_revision.py`) + +**Interfaces:** +- Produces: + +```python +TRANSFER_DOCUMENT_STATUSES = ( + 'executing', 'success', 'duplicate_success', 'business_failed', + 'technical_failed', 'result_unknown', 'cancelled', +) + + +class TransferDocument(Base): + """一张 ERP 调拨单(票)的真相源:组织×来源×在途仓→HUB路由 分组 = 一票。 + + doc_no / batch_id 创建时生成一次终身复用(重试幂等锚);lines_json 冻结 + 聚合行快照,保证重写与首写报文一致。 + """ + + __tablename__ = 'transfer_documents' + __table_args__ = ( + UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'), + UniqueConstraint('batch_id', name='uq_transfer_documents_batch_id'), + CheckConstraint( + f"status IN ({', '.join(repr(s) for s in TRANSFER_DOCUMENT_STATUSES)})", + name='ck_transfer_documents_status', + ), + Index('ix_transfer_documents_run_status', 'run_id', 'status'), + Index('ix_transfer_documents_erp_no', 'erp_document_no'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + run_id: Mapped[int] = mapped_column(ForeignKey('transfer_runs.id'), nullable=False, index=True) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + external_org: Mapped[str] = mapped_column(String(64), nullable=False) + from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) + to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) + doc_no: Mapped[str] = mapped_column(String(64), nullable=False) + batch_id: Mapped[str] = mapped_column(String(64), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='executing') + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) + erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='document') +``` + +- `TransferInvoiceItem` 加 `document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)` + `document` relationship(不 delete-orphan)。 +- `TransferAttempt` 加 `document_id: Mapped[Optional[int]]`(nullable,`item_id` 保持——重查 Attempt 仍挂 item,写 Attempt 挂 document)。 + +- [ ] **Step 1: 失败测试**(唯一约束 / 状态 CHECK / Item.document 关系 / 迁移链 head 推进)。 +- [ ] **Step 2: 失败 → Step 3: 实现 + 迁移**(create_table transfer_documents + add columns;downgrade 反向 drop)。 +- [ ] **Step 4: 全绿 → Step 5: 落盘。** + +--- + +### Task 8: `CapabilityClient` 两步编排 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/capability_client.py` +- Test: `backend/tests/services/in_transit_transfer/test_capability_client_write.py`(新) + +**Interfaces:** +- 新常量:`STAGE_CAPABILITY = "in_transit_transfer.stage_transfer_order"`、`SUBMIT_CAPABILITY = "in_transit_transfer.submit_transfer_order"`。 +- 改造 `create_transfer`(签名换票级参数): + +```python + def create_transfer( + self, + *, + operation_id: str, + external_org: str, + doc_no: str, + batch_id: str, + doc_date: str, + posting_date: str, + from_warehouse: str, + to_warehouse: str, + lines: list[dict], + ) -> TransferWriteResult: +``` + +编排(`[STEP]` 注释齐全,网关替身注入测试): + +```python + # [STEP 1] 写中间表:pre 的同批次 DELETE 保证重插幂等;失败(含超时)即技术失败—— + # 本地 Oracle 落库超时后行可能已插入,但重执行会用同一批次 DELETE 清理后重写,无重复风险。 + stage = self._gateway().call(capability=STAGE_CAPABILITY, context={}, params={ + "external_org": external_org, "doc_no": doc_no, "batch_id": batch_id, + "doc_date": doc_date, "posting_date": posting_date, "lines": lines, + }, operation_id=operation_id) + if stage.status != 'success': + return TransferWriteResult( + status='technical_failed', + error_code=stage.error_code or 'EXTERNAL_STAGE_FAILED', + error_message=stage.error_message or '', + ) + # [STEP 2] 触发 TIPTOP WS 同步建单;响应即终态裁决(用户拍板:不设状态回读) + submit = self._gateway().call(capability=SUBMIT_CAPABILITY, context={}, params={ + "external_org": external_org, "doc_no": doc_no, "batch_id": batch_id, + }, operation_id=operation_id) + return self._classify_submit_result(submit) +``` + +`_classify_submit_result`(Tiptop 语义收口在域层): + +```python + def _classify_submit_result(self, result) -> TransferWriteResult: + if result.status == 'success': + return TransferWriteResult(status='success', document_no=result.document_no) + if result.status == 'business_failed': + return TransferWriteResult(status='business_failed', error_code=result.error_code, error_message=result.error_message) + if result.status == 'timeout': + # 响应丢失且不回读:终态 result_unknown(禁自动重试);人工核实 SOP = + # 在 ERP 按来源单号查单:有单 → 人工关闭并备注单号;无单 → 恢复处理重建预检。 + return TransferWriteResult(status='result_unknown', error_code='EXTERNAL_TIMEOUT_UNKNOWN') + # 技术失败可能携带 Tiptop 非 0 状态码:映射后的 data 里 code≠'0' → 业务失败(重试无效) + data = result.data if isinstance(result.data, dict) else {} + code = str(data.get('code') or '') + if data.get('status') not in (None, '', 'success') and code not in ('', '0'): + return TransferWriteResult(status='business_failed', error_code=code, error_message=str(data.get('message') or '')) + return TransferWriteResult(status='technical_failed', error_code=result.error_code or 'EXTERNAL_UNKNOWN_RESPONSE', error_message=result.error_message or '') +``` + +- 删除:`verify_duplicate` 方法(无调用方,重复票由人工核实 SOP 承担);`write_transport` 注入点与 `ExternalNotFrozenError` 的「未注入即抛」逻辑(绑定缺失由网关 `BindingNotFoundError` 承担,票级异常隔离承接);`ExternalWriteTimeoutError` 类删除(超时裁决内化)。 + +- [ ] **Step 1: 失败测试**(替身网关按 capability 名分发脚本化响应,逐分支断言:stage 失败→技术失败 / stage 超时→技术失败 / submit 成功→success+单号 / 业务失败→business_failed / 超时→result_unknown / 技术失败带 Tiptop 非 0 码→business_failed)。 +- [ ] **Step 2: 失败 → Step 3: 实现 → Step 4: 全绿(存量 write 相关用例同步改写)→ Step 5: 落盘。** + +--- + +### Task 9: 执行粒度重构(按票建单) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(核心重构) +- Modify: `backend/app/services/in_transit_transfer/orchestrator.py`(finalize_run 口径不变,核对) +- Modify: `backend/app/services/in_transit_transfer/execution_service.execute_item`(worker 兼容入口:委托票执行) +- Test: `backend/tests/services/in_transit_transfer/test_execution_documents.py`(新)+ 存量 `test_execution_service` 改写 + +**Interfaces:** +- Produces: + +```python +@dataclass(frozen=True) +class DocumentPlan: + """一次执行内的一票分组:组织×来源×在途仓→HUB 路由。""" + source_code: str + external_org: str + from_warehouse: str + to_warehouse: str + items: list[TransferInvoiceItem] + lines: list[dict] +``` + +- `execute_precheck`:`selected` 确定后改走 `_plan_documents(selected, deps=deps)` → 逐票 `_execute_document(plan, ...)`;票间失败隔离(票异常 → 票内全部行 blocked_recoverable,其余票继续,与现行项级隔离同语义)。 +- `_plan_documents`:复用 `_write_item` 既有写前路由复查(route 变化 → 行 blocked `precheck_expired`,路由一致才入组);组内 `_aggregate_lines`: + +```python +def _aggregate_lines(items: list[TransferInvoiceItem]) -> list[dict]: + """组内按(料号+批号)聚合数量,行号 1 起顺序编;数量 6 位小数字符串(样例口径)。""" + merged: dict[tuple[str, str], dict] = {} + for item in items: + key = (item.material_no, item.lot_no or '') + row = merged.setdefault(key, { + "material_no": item.material_no, "lot_no": item.lot_no or "", + "from_warehouse": item.from_warehouse, "to_warehouse": item.to_warehouse, + "unit": getattr(item, 'unit', '') or '', + "quantity": Decimal("0"), + }) + row["quantity"] += Decimal(item.receipt_quantity) + return [ + {"line_no": str(index + 1), **{k: v for k, v in row.items() if k != "quantity"}, + "quantity": f"{row['quantity']:.6f}"} + for index, row in enumerate(merged.values()) + ] +``` + +- `_ensure_document(plan, run)`:同 run 同分组键已有 `executing` 文档则复用(**doc_no/batch_id 终身复用**);否则生成(Task 5)+ `lines_json` 冻结 + 行落 `document_id`。 +- 票级在飞守卫(worker 重入队防双写):`UPDATE transfer_documents SET attempt_no = attempt_no + 1 WHERE id = :id AND status = 'executing'` 影响行数为 0 → 说明已有在飞执行,跳过。 +- `_apply_document_result(doc, items, attempt, result)`:Attempt(kind='external_write',挂 document_id)+ 按 Task 8 六态落位——success/duplicate_success → doc 与票内全部行 success/external_document_no=erp 单号;business_failed/technical_failed → doc 同态 + 行 blocked_recoverable(result_message 透出);result_unknown → doc result_unknown + 行 result_unknown(终态)。 +- `execute_item(item_id)` 改为:定位 item.document → 无 document(执行前异常行)保持旧行为报错 → 有则走 `_execute_document`(票级守卫防重复提交)。 + +- [ ] **Step 1: 失败测试**(核心场景全要):①两来源同路由 → 两票、各一单号;②同票跨 Invoice 同料号同批号 → 聚合一行数量相加;③一票成功 → 票内全部行 success + erp 单号一致;④票级异常 → 该票行 blocked、其他票继续;⑤worker 重入队同票 → 第二次跳过(守卫);⑥路由漂移行照旧 blocked 不入组。 +- [ ] **Step 2: 失败 → Step 3: 实现 → Step 4: 全绿(存量 test_execution_service 的按行断言改写为按票)→ Step 5: 落盘。** + +--- + +### Task 10: 结果投影与 API 冒烟 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(`_build_run_result`) +- Test: `backend/tests/api/test_in_transit_transfer_api.py`(追加冒烟) + +**Interfaces:** +- `_build_run_result`:`external_documents` 改由 `run.documents`(票)投影——`document_no=erp_document_no`、`lines` 由 `lines_json` 展开(含 invoice_no 归属可由 items 反查填充);items 的 `external_document_no` 已随票落位,`aggregate_external_documents` 兜底逻辑保留(历史数据无票时仍可按行聚合)。`exceptions` 口径不变。 +- API 冒烟:执行 → run 查询返回按票聚合的单据列表(新断言);`result_unknown` 票的行仍只读。 + +- [ ] **Step 1: 失败测试 → Step 2: 失败 → Step 3: 实现 → Step 4: API 全绿 → Step 5: 落盘。** + +--- + +### Task 11: 管理端 `database` 类型适配(前端 + 四语言) + +**Files:** +- Modify: `frontend/src/features/admin/modules/integration-connector/types/integration-connector.types.ts` +- Modify: `frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue` +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`(仅 connectorType/placeholder 相关键,**禁整文件重写**,块级/行级替换) +- Test: `frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts`(追加) + +**Interfaces:** +- 连接器类型下拉加 `database`(label:简中「数据库(Oracle 直连)」/繁中/英/泰)。 +- 客户端表单:database 类型 endpoint label=「数据库连接串(host:port/service_name)」;超时字段照显(通用字段不因类型隐藏);不显示 REST 的 HTTP 方法/请求路径。 +- 高级配置 JSON 折叠区保留(`oracle_lib_dir` 走 config_json)。 + +- [ ] **Step 1: 失败 vitest 用例**(选 database → endpoint label 文案 + 无 method/path 输入框)。 +- [ ] **Step 2: 失败 → Step 3: 实现(含四语言)→ Step 4: `npm run test:unit -- src/features/admin/modules/integration-connector && npm run build` 全绿 → Step 5: 落盘。** + +--- + +### Task 12: 接口定义/绑定配置固化(写入 technical.md) + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md`(§10 新节「ERP 建单连接器配置」,内容如下全文) + +**内容(配置产物全文,上线时经管理端录入;下述 `htt_*` 编码仅为本文行文示例——接口定义的编码、SQL/报文全文、含 schema 前缀的表名全部由管理员在界面自行创建和维护,后端代码不出现任何接口编码或表名):** + +客户端实例(编码同样管理员自定):`connector_type=database`,`endpoint=`,凭据引用(password 类型,db 模式录 ERP 账号)。 + +接口定义①(写中间表,编码示例 `htt_gls_cm_stage`): +```json +{ + "input_schema_json": {"type": "object", "required": ["external_org", "doc_no", "batch_id", "doc_date", "posting_date", "lines"], "properties": {}}, + "request_spec_json": {"sql": {"mode": "execute", + "pre": ["DELETE FROM htt.gls_cm_file WHERE gls_cm27 = :batch_id AND gls_cm29 = '10'"], + "bulk": {"rows_param": "lines", "sql": "INSERT INTO htt.gls_cm_file (gls_cm01, gls_cm02, gls_cm03, gls_cm04, gls_cm05, gls_cm06, gls_cm07, gls_cm08, gls_cm09, gls_cm10, gls_cm11, gls_cm12, gls_cm13, gls_cm14, gls_cm15, gls_cm16, gls_cm17, gls_cm18, gls_cm19, gls_cm20, gls_cm21, gls_cm22, gls_cm23, gls_cm24, gls_cm25, gls_cm26, gls_cm27, gls_cm28, gls_cm29, gls_cm30, gls_cm31, gls_cm32, gls_cm33, gls_cm34, gls_cm35, gls_cm36, gls_cm37, gls_cm38, gls_cm39, gls_cm40, gls_cm41, gls_cm42, gls_cm43, gls_cm44, gls_cm45, gls_cm46, gls_cm47, gls_cm48, gls_cm49, gls_cm50, gls_cm51, gls_cm52, gls_cm53, gls_cm54, gls_cm55, gls_cm56, gls_cm57, gls_cm58, gls_cm59, gls_cm60, gls_cm61, gls_cm62, gls_cm63, gls_cm64, gls_cm65, gls_cm66, gls_cm75, gls_cm76, gls_cm77, gls_cm78) VALUES (sys_guid(), :external_org, :external_org, :doc_no, :line_no, TO_DATE(:doc_date, 'YYYY-MM-DD'), :maker_account, :maker_account, 'C0089', '无源调拨出', :doc_no, :line_no, :material_no, :to_warehouse, :from_warehouse, ' ', ' ', :lot_no, :quantity, :unit, '', '', '', '', '', '', :batch_id, '23', '10', '', '', '', '', '0.000000', '', '', '0.000000', '', '', '0', '', '', '0', '0', '0', '0', '0', '', '', TO_DATE(:posting_date, 'YYYY-MM-DD'), '', '', '', '', '', '', '', '', '', '', '', '', '', 5, 0, '', '', '', '')"}, + "post": []}} +} +``` +(`maker_account`、来源类别 C0089 等常量由绑定 param_mapping 常量注入;入库/出库仓方向按样例:gls_cm14=拨入HUB=to_warehouse、gls_cm15=拨出在途仓=from_warehouse——联调首日与 ERP 核对一次方向。) + +接口定义②(WS 触发,SOAP,编码示例 `htt_tiptop_submit`): +```json +{ + "request_spec_json": {"method": "POST", "soap": {"action": "", "body_template": ""}}, + "response_mapping_json": { + "status": {"expr": "Response.Execution.Status.@code", "transform": "enum-map", "args": {"mapping": {"0": "success"}}}, + "code": {"expr": "Response.Execution.Status.@code"}, + "message": {"expr": "Response.Execution.Status.@description"}, + "document_no": {"expr": "Response.ResponseContent.Parameter.Record.Field", "transform": "pick", "args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}} + } +} +``` + +两个绑定(默认 context 空 selector,param_mapping 示例——写中间表绑定): +```json +{ + "maker_account": {"expr": "external_org", "transform": "template", "args": {"template": "15070211"}}, + "source_ip": {"expr": "external_org", "transform": "template", "args": {"template": "0.0.0.0"}} +} +``` +(常量值上线前由业务确认;`template` 渲染无占位符文本即字面常量;映射引擎参数形态以 `mapping.py:224` `fill_param_template` 为准,录入前先直调验证端点冒烟。) + +- [ ] **Step 1: 文档落盘(本任务只改文档)→ Step 2: `git add`。** +- 联调期运维顺序(写进文档):凭据 → 客户端实例 → 两接口定义 → 两绑定发布 → `POST /api/integration-connector/capabilities/...` 直调验证 stage(database)与 submit(SOAP,ERP 沙箱组织)。 + +--- + +### Task 13: 文档同步与全量回归 + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md`(§1 唯一出口补 database 类型与三步能力;§3 无新增 env,删「写路径 fail-closed」过期表述;§9 验收清单补三步契约/双单防护场景) +- Modify: `docs/funclist.md`(调拨段:ERP 建单(中间表+WS)能力行) +- Modify: `docs/demand.md`(如执行粒度描述涉及,则同步「按组织×来源×路由一票一单」) + +- [ ] **Step 1: 全量回归**: + ```bash + cd backend && pytest -q tests/services/in_transit_transfer tests/services/integration_connector tests/api/test_in_transit_transfer_api.py tests/api/test_integration_connector_api.py tests/workers/test_in_transit_transfer_worker.py + cd ../frontend && npm run test:unit -- src/features/chat src/features/admin/modules/integration-connector && npm run build + ``` +- [ ] **Step 2: 文档更新落盘 → `git add`。** +- [ ] **Step 3: 交付说明**(提交说明模板):列出迁移链 4 个新 revision、上线配置五步、方案前提与残余确认(均一句话问 ERP,不阻塞代码):①ERP 侧除 WS 外**没有**定时批处理自动消费 '10' 行(本方案幂等的前提;若存在,超时票恢复处理前必须先人工核实 ERP 无此单,防双单);②失败行 gls_cm29 终值(现仅认 '30' 为成功);③HTT-OR 单号是否强校验每日从 000001(现用全局 PG 序列)。另在 §9 补 result_unknown 人工核实 SOP:在 ERP 按来源单号查单——有单 → 人工关闭并备注单号;无单 → 恢复处理重建预检(超时票残留的 '10' 行在前提①下为无害垃圾)。 + +--- + +## Self-Review 记录 + +- 规格覆盖:两步契约(T2/T4/T8/T12)、分组建单(T7/T9)、幂等双单防护(T5/T8/T9 批次复用+stage DELETE+票级守卫)、unit 契约(T6)、管理端与配置(T11/T12)、文档(T13)——决策点 1–6 全部落任务。 +- 类型一致性:`TransferWriteResult` 六态复用不变;`DocumentPlan.lines` 键集与能力 Schema `_TRANSFER_LINE_SCHEMA` 一致;`new_batch_id`/`next_document_no` 在 T5 定义、T9 消费。 +- 已知风险前置:Task 3 的绑定 seed 夹具复用既有 connector 测试基建;Task 9 存量按行用例需成批改写(工作量最大项,先写新测试再动实现)。 diff --git a/docs/superpowers/plans/2026-09-23-transfer-item-centric-refactor.md b/docs/superpowers/plans/2026-09-23-transfer-item-centric-refactor.md new file mode 100644 index 00000000..c20a5cd0 --- /dev/null +++ b/docs/superpowers/plans/2026-09-23-transfer-item-centric-refactor.md @@ -0,0 +1,297 @@ +# 在途调拨「行归属解耦」实施计划(预检降级为评估留痕 + 按行执行 + 三层执行门禁) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 把在途调拨的核心真相源从"预检容器"迁移到"发票行"——行永不迁移、预检降级为评估留痕与范围视图、执行按行发起并带三层门禁(行级新鲜度 / 文件版本对账 / 写前复查)、恢复处理收敛为行级重查;前端三区结构(首页待办入口 / 预检卡 / 待处理异常)保持不变只换接线。 + +**Architecture:** 发票行(TransferInvoiceItem,业务键 = 来源+Invoice+料号+收料日期)是唯一真相源,预检/重查只原地刷新行并留痕;预检记录(TransferPrecheck)保留为评估日志(scope/counts/文件快照/expires_at 仅展示,hash 照算留痕不再拦执行);预检卡 = 按预检 scope 的行实时视图;执行从"绑定预检"改为"按行执行"(Execute items),由行级新鲜度、文件版本对账、写前复查三层门禁兜底;恢复处理 = 批量行级重查(不建预检、不迁移)。 + +**Tech Stack:** Flask + SQLAlchemy 2.0(后端)、Vue 3 + TS + Vitest(前端)、pytest(后端)。零数据库迁移(复用既有列与 JSON 字段)。 + +**Spec:** 本计划实现 2026-09-23 与用户确认的设计(对话定稿):前端三区保留;行不迁移;预检=评估留痕+范围视图;执行=按行+三层门禁(TTL 保留、hash 留痕不拦执行、文件版本对账新增);恢复=行级重查;「文件已移除」fail-closed 规则;库存列带查询时刻。权威文档落点:`docs/features/in-transit-transfer/technical.md` §4.1(完成后更新)。 + +## Global Constraints + +- 🚫 禁止自动 `git commit`:所有任务以 `git add`(stage)结束,提交须用户明确批准。 +- 🧬 零数据库迁移:不得新增/修改列与约束;行级文件版本戳写入既有 `raw_lines_json`(JSON 列)条目内;行新鲜度复用 `updated_at`。 +- 🔒 不得改动 ERP 写路径语义:`_write_item` 的写前复查 + 原子建单 + 幂等逻辑保持原样。 +- 🌍 前端新增/改动文案必须同步四语言(zh-CN / zh-TW / en / th 的 `chat.json` 与 `errors.json`);i18n 占位符只用 `{name}` 形式。 +- 📡 JSON POST 必须带 `Content-Type: application/json`(`transfer.api.ts` 的 `jsonHeaders` 模式)。 +- ✅ 每个任务结束必须通过:`cd backend && python -m pytest tests/services/in_transit_transfer -q` 全绿;前端任务另须 `npm run build` + 相关 vitest 全绿。 +- 后端测试命令统一:`cd D:/Workspace/HxProjects/hxops/backend && (source venv/Scripts/activate 2>/dev/null || source venv/bin/activate 2>/dev/null); python -m pytest ...`。 +- 术语:`blocked_recoverable`=可恢复异常;`ready_to_execute`=可执行;TTL=`deps.strategy.confirm_ttl_seconds`(默认 600s);"评估"=预检或行级重查。 + +--- + +## File Structure(改动全景) + +``` +backend/app/services/in_transit_transfer/ + precheck_service.py # 改:create_precheck 行原地刷新(不迁移)+ 文件版本戳 + 消失行标记; + # restore_precheck 改按 scope 查行 + 计数实时聚合 + 行装饰字段; + # list_recent_prechecks 改按 scope 实时聚合 + transfer_type.py # 改:导出 invoice_in_scope(invoice_no, transfer_type)(复用既有前缀常量) + execution_service.py # 改:删除 execute_precheck;新增 execute_items(三层门禁)+ 按行建 Run + retry_service.py # 改:_recheck_item 显式刷新 updated_at(续新鲜度) + resume_service.py # 删除(恢复处理收敛为 batch-requery) + serializers.py # 改:serialize_item 增 item_id/checked_at/stale/file_current +backend/app/api/in_transit_transfer.py + # 改:+POST /items/execute;-POST /items/batch-resume; + # execute 路由改调 execute_items;restore 传 deps +backend/app/services/in_transit_transfer/chat_actions.py + # 改:TransferExecuteAction 改调 execute_items +backend/tests/services/in_transit_transfer/ + test_precheck_inplace.py # 新建(Task 1) + test_restore_scope.py # 新建(Task 2) + test_execute_items.py # 新建(Task 3,承接原 test_execution_service 用例) + test_resume_service.py # 删除(Task 4) + test_recent_prechecks.py # 改(Task 1,scope 语义) + test_execution_service.py# 删除/迁移(Task 3) + test_batch_actions.py # 改(Task 4,新鲜度断言) +backend/tmp/diag_stock_batch.py # 新建(Task 6 探针,仿 diag_precheck_empty.py) +frontend/src/features/chat/ + api/transfer.api.ts # 改:+executeTransferItems;-batchResumeTransferItems + types/transfer.types.ts # 改:TransferPrecheckItem +item_id/checked_at/stale/file_current + composables/useChatTransfer.ts # 改:execute 按 item_ids;selected 改 Set;resume=requery + components/messages/TransferMessageView.vue # 改:execute/resume 接线 + components/messages/TransferPrecheckCard.vue # 改:勾选/执行按 item_id;库存列查询时刻+过期置灰 + components/messages/TransferBacklogSummaryCard.vue # 改:blocked_file_removed 结果徽标 +frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json + errors.json # 改(新增/删除键,见 Task 5) +docs/features/in-transit-transfer/technical.md + docs/funclist.md # 改(Task 7) +``` + +--- + +### Task 1: 行原地刷新(预检不再迁移行)+ 文件版本戳 + 消失行标记 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/precheck_service.py`(create_precheck 的 upsert 段,约 562-616 行;list_recent_prechecks 的归属聚合) +- Modify: `backend/app/services/in_transit_transfer/transfer_type.py`(导出范围谓词) +- Create: `backend/tests/services/in_transit_transfer/test_precheck_inplace.py` +- Modify: `backend/tests/services/in_transit_transfer/test_recent_prechecks.py` + +**Interfaces:** +- Produces: `transfer_type.invoice_in_scope(invoice_no: str, transfer_type: str) -> bool`(Task 2 的 scope 查询复用) +- Produces: 行 `raw_lines_json` 条目新增键 `file_sha256: str`(Task 2/3 的文件对账读取:`item.raw_lines_json[0].file_sha256`,帮助函数 `_item_evaluated_sha(item) -> str | None` 定义在 precheck_service) +- Produces: `scope_item_query(precheck) -> BaseQuery`(按 precheck.scope_json 查行:source_codes + receipt_date 区间 + transfer_type 前缀过滤;Task 2 restore 复用) + +- [ ] **Step 1: 写失败测试**(新建 `test_precheck_inplace.py`,复用 `tests/services/in_transit_transfer/repo_fakes.make_transfer_deps` 与根 conftest 的 `dbs_ready_file`/`transfer_db` 夹具,写法参照现有 `test_backlog_service.py`): + +```python +def test_reprecheck_refreshes_rows_in_place(transfer_db, dbs_ready_file): + """第二次预检:同一物理行原地刷新(id 不变、precheck_id 不变、值更新)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 blocked + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 executable + first = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + old_id, old_precheck_id, old_updated = row.id, row.precheck_id, row.updated_at + second = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + db.session.refresh(row) + assert row.id == old_id # 不新建行 + assert row.precheck_id == old_precheck_id # 不迁移归属 + assert row.updated_at > old_updated # 显式续新鲜度 + # 两份预检记录都存在(评估留痕),且最近预检按 scope 聚合都看到同一行 + assert first.precheck_id != second.precheck_id + +def test_file_removed_marks_ready_rows_blocked(transfer_db, dbs_ready_file): + """文件新版本缺失该行:ready 行打 blocked_file_removed;blocked 行不动。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # HOM-001 → executable + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() + assert hom.status == "ready_to_execute" + # 新文件版本:内容只剩 HOX-002(HOM-001 消失),checksum 变化 + new_file = {**dbs_ready_file, "file_version": "v4", "checksum": "e" * 64, + "rows": [r for r in dbs_ready_file["rows"] if r["doc_no"] != "HOM-001"]} + deps2, _, _ = make_transfer_deps(new_file) + create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) + db.session.refresh(hom) + assert hom.status == "blocked_recoverable" + assert hom.result_code == "blocked_file_removed" + # blocked 行(本例无)与未知评估版本的行不被误标——由其余用例覆盖 + +def test_file_removed_skips_unknown_evaluated_version(transfer_db, dbs_ready_file): + """行上无 file_sha256(历史数据)时不误标 file_removed。""" + # 先造 ready 行,再手工清空 raw_lines_json 的 file_sha256 模拟存量,重跑新版本预检 +``` + +- [ ] **Step 2: 运行确认失败**:`python -m pytest tests/services/in_transit_transfer/test_precheck_inplace.py -q` → FAIL(现状会迁移行/不标 file_removed)。 +- [ ] **Step 3: 实现**(precheck_service.py): + 1. `transfer_type.py`:把类型 1 的 Invoice 前缀判断抽成 `def invoice_in_scope(invoice_no, transfer_type) -> bool`(复用模块内既有前缀常量 HOM/HOX/WTP;占位类型恒 False)。 + 2. `create_precheck` upsert 循环改为原地刷新:`fields` 字典**删除** `"precheck_id"` 键;对 `existing` 刷新业务字段后**显式** `existing.updated_at = now`;`raw_lines_json` 每条 line 追加 `"file_sha256": stage.checksum`(stage 来自 `result.sources` 中该 source 的阶段对象,checksum 与 file_snapshot 同源);新建行同样带 `file_sha256`。 + 3. 循环后新增"消失行标记":对每个有文件的 source,查该 source 下 `status == ready_to_execute`、`receipt_date` 在本次范围(from/to 有值时)内、且 `_item_evaluated_sha(item)` 非空并不等于本次 checksum 的行 → `status=blocked_recoverable, result_code="blocked_file_removed", result_message="receipt row removed from latest file"`(帮助函数 `_item_evaluated_sha(item)`:`item.raw_lines_json[0].get("file_sha256")`,空列表/缺键返回 None)。 + 4. `list_recent_prechecks` 的 `item_agg` 从"按 precheck_id 分组"改为"按 scope 聚合":新增模块级 `scope_item_query(precheck)`(`TransferInvoiceItem.source_code.in_(scope sources)` + receipt_date 字符串区间过滤 + `invoice_in_scope(invoice_no, transfer_type)`);recent 对最近 N 条记录逐条用 `scope_item_query` 实时计数(N≤50,性能可接受),过滤条件改为"实时 executable_count > 0 或 status='prechecking'"(删除 confirmed_at/expires 过滤——执行不再绑定预检)。 +- [ ] **Step 4: 跑测试**:`test_precheck_inplace.py` PASS。 +- [ ] **Step 5: 修复受迁移语义影响的既有用例**:`test_recent_prechecks.py::test_recent_excludes_emptied_precheck_after_reprecheck` 改为 scope 语义(行不迁移后两份预检的 scope 计数相同 → 用"第二份预检记录有可执行行、列表仍只列可执行>0"断言替代"掏空"断言);全量跑 `tests/services/in_transit_transfer -q`,凡断言"行迁移/旧卡掏空"的用例按新语义改写(预期涉及 test_precheck_service 幂等段若干用例)。 +- [ ] **Step 6: 全绿后 stage**:`git add backend/app/services/in_transit_transfer/precheck_service.py backend/app/services/in_transit_transfer/transfer_type.py backend/tests/services/in_transit_transfer/` + +--- + +### Task 2: 预检卡改范围实时视图(restore 按 scope 查行 + 行装饰字段) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/precheck_service.py`(restore_precheck) +- Modify: `backend/app/services/in_transit_transfer/serializers.py`(serialize_item 增字段) +- Create: `backend/tests/services/in_transit_transfer/test_restore_scope.py` + +**Interfaces:** +- Consumes: Task 1 的 `scope_item_query(precheck)`、`_item_evaluated_sha` +- Produces: `restore_precheck(precheck_id, *, deps=None, now=None)`(deps 缺省时内部取 `deps.get_transfer_dependencies()`);返回 items 的每行新增:`item_id: int`、`checked_at: str|None`(updated_at isoformat)、`stale: bool`(now - updated_at > TTL)、`file_current: bool`(行评估 sha == 该来源当前最新可用文件 sha;来源无可用文件 → False)。`PrecheckInvoiceItemDTO` 同步加这四个字段;`serialize_item` 输出同步。 + +- [ ] **Step 1: 写失败测试**(`test_restore_scope.py`): + +```python +def test_restore_returns_scope_rows_not_owned_rows(transfer_db, dbs_ready_file): + """restore 按范围返回实时行:行属于首份预检,但第二份预检的 restore 也能看到(实时状态)。""" + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) # 行建在此预检 + second = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + detail = restore_precheck(second.precheck_id, deps=deps) + assert {i.invoice_no for i in detail["items"]} == {"HOM-001", "HOX-002"} + row = next(i for i in detail["items"] if i.invoice_no == "HOX-002") + assert row.item_id > 0 and row.stale is False and row.file_current is True + +def test_restore_marks_stale_beyond_ttl(transfer_db, dbs_ready_file): + """行 updated_at 早于 TTL → stale=True(TTL 取 deps.strategy.confirm_ttl_seconds)。""" + # 建预检后手工把 item.updated_at 拨回 11 分钟前,restore 断言 stale is True +``` + +- [ ] **Step 2: 确认失败**(现状 restore 读 `precheck.items` 关系,第二份预检 items 为空 → FAIL)。 +- [ ] **Step 3: 实现**:restore_precheck 加 `deps/now` 参数;items 改为 `scope_item_query(precheck).order_by(...).all()`;按 scope 内去重后的 source 逐个调 `resolve_source_file_status(source_code=...)` 建映射,逐行装饰四字段(`file_current = bool(evaluated_sha) and evaluated_sha == latest_sha`;来源无可用文件 → False;`stale = (now - item.updated_at).total_seconds() > deps.strategy.confirm_ttl_seconds`);counts 用 scope 行实时聚合(executable/blocked/not_matured/total→file_invoice_count),`estimated_*` 与 `expires_at` 沿用预检记录(留痕展示);`serialize_item` 增加 `item_id/checked_at/stale/file_current`。注意 API 层 `get_precheck_api` 调用处传 `deps=transfer_deps.get_transfer_dependencies()`。 +- [ ] **Step 4: 跑测试** PASS;全目录回归(chat_actions 里 `restore_precheck(summary.precheck_id)` 调用需同步传 deps 或用缺省)。 +- [ ] **Step 5: stage**。 + +--- + +### Task 3: 按行执行 execute_items(三层门禁)+ 路由 + chat action;hash/expires 门禁退役 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/execution_service.py` +- Modify: `backend/app/api/in_transit_transfer.py`(路由替换) +- Modify: `backend/app/services/in_transit_transfer/chat_actions.py` +- Delete: `backend/tests/services/in_transit_transfer/test_execution_service.py`(用例迁移) +- Create: `backend/tests/services/in_transit_transfer/test_execute_items.py` + +**Interfaces:** +- Consumes: Task 1 `_item_evaluated_sha`;既有 `_write_item(item, *, deps, run_no, request_id)`、`finalize_run(run, run_items)`、`ExecuteOutcome(run_no, status, result)`、`_build_run_result(run)` +- Produces: `execute_items(*, item_ids: list[int], deps, actor_id=None, request_id=None) -> ExecuteOutcome`;错误码:`TRANSFER.EXECUTE_ITEMS_INVALID`(不存在/非可执行)、`TRANSFER.ITEMS_STALE`(details.stale_item_ids)、`TRANSFER.FILE_CHANGED`(details.changed_item_ids,含"来源无可用文件"情形) +- Produces: 路由 `POST /items/execute` body `{"item_ids": [int]}` → 200 envelope `{run_no, status, result}` + +- [ ] **Step 1: 写失败测试**(承接 `test_execution_service.py` 的成功/重复/业务失败/部分失败用例改写到 execute_items——把"建预检后 execute_precheck"改为"取 scope 内 ready 行的 item_ids 直接执行";新增三个门禁用例): + +```python +def test_execute_items_rejects_stale_rows(transfer_db, dbs_ready_file): + # 建 ready 行后把 updated_at 拨回 11 分钟前 → execute_items 抛 ValidationError + # code == "TRANSFER.ITEMS_STALE",details 含该 item_id;不创建 Run + +def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file): + # 建 ready 行后,用"新 checksum 的文件"刷新来源最新可用文件状态 + # (monkeypatch resolve_source_file_status 返回不同 file_sha256,或按 Task 1 方式重跑新文件预检 + # —— 注意重跑会把行刷成新版本,所以本用例用 monkeypatch 模拟"文件更新但未重新预检") + # → ValidationError code == "TRANSFER.FILE_CHANGED" + +def test_execute_items_writes_and_aggregates(transfer_db, dbs_ready_file): + # ready 行执行 → run_no 生成、ERP 写 Attempt、状态 success、结果按 ERP 单号聚合 +``` + +- [ ] **Step 2: 确认失败**(execute_items 未定义)。 +- [ ] **Step 3: 实现**(execution_service.py): + 1. `execute_items`:加载并校验 `item_ids`(存在 + `status == ready_to_execute`,否则 `ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID", details={"invalid_item_ids": [...]})`)。 + 2. 新鲜度门禁:`stale = [i.id for i in items if (now - i.updated_at) > ttl]`(ttl=`deps.strategy.confirm_ttl_seconds`,now=utcnow)→ 非空抛 `TRANSFER.ITEMS_STALE`。 + 3. 文件版本对账门禁:按去重 source 调 `resolve_source_file_status`,行评估 sha(`_item_evaluated_sha`)缺失或 ≠ 最新可用 sha(或来源无可用文件)→ 抛 `TRANSFER.FILE_CHANGED`(details 列出 changed_item_ids)。 + 4. 建 Run:改造 `create_execution_run` 为 `create_execution_run_for_items(items, *, deps, actor_id, selected_item_ids)`(阅读原函数后平移:`run_no=_generate_no("RUN", business_date_now())`、`business_date=business_date_now()`、`source_codes_json=sorted({i.source_code})`、`trigger_type="manual"`、counts 按行聚合;**不绑定 precheck**,`precheck.run_id` 保持空)。逐行 `_write_item(item, deps=deps, run_no=..., request_id=...)`(保持原样:写前复查+原子写+单项失败不阻断),`finalize_run` + `commit`,返回 `ExecuteOutcome`。 + 5. **删除 `execute_precheck` 函数与 `POST /prechecks/{id}/execute` 路由**(hash/expires 门禁随之退役;`create_precheck` 仍照算 `precheck_hash` 留痕,`expires_at` 仍写仅作展示)。同步删除 `_expire`/`recompute_precheck_hash` 的调用点(函数若仅剩此处引用一并删除)。 + 6. `chat_actions.TransferExecuteAction.stream`:payload 仍为 `{precheck_id, invoice_nos}` → 用 `scope_item_query(restore 用的预检)` + `invoice_nos` 过滤出 ready 行的 item_ids → 调 `execute_items`;输出卡片不变。 + 7. API:`POST /items/execute`(`_require_user` + body item_ids 校验复用 `_require_item_ids`)。 +- [ ] **Step 4: 跑测试** PASS;全目录回归。 +- [ ] **Step 5: stage**。 + +--- + +### Task 4: 恢复处理收敛为行级重查(删 batch-resume 与 resume_service) + +**Files:** +- Delete: `backend/app/services/in_transit_transfer/resume_service.py`、`backend/tests/services/in_transit_transfer/test_resume_service.py` +- Modify: `backend/app/api/in_transit_transfer.py`(删 `POST /items/batch-resume` 路由与 import) +- Modify: `backend/app/services/in_transit_transfer/retry_service.py`(_recheck_item 续新鲜度) +- Modify: `backend/tests/services/in_transit_transfer/test_batch_actions.py` + +**Interfaces:** +- Produces: `requery_items_by_ids`(既有)成为"恢复处理"唯一后端语义;`_recheck_item` 成功/失败路径均显式 `item.updated_at = datetime.utcnow()`(重查即续新鲜度)。 +- Note: 本任务后前端 `batchResumeTransferItems` 调用会 404,由 Task 5 同一计划内修复(计划整体一次性交付)。 + +- [ ] **Step 1: 写失败测试**(test_batch_actions.py 追加): + +```python +def test_batch_requery_refreshes_freshness(transfer_db, dbs_ready_file): + # ready 前置:把行 updated_at 拨回 11 分钟前 → blocked(先 seed 不匹配库存造 blocked) + # 再 seed 正确库存 → requery_items_by_ids → 行 updated_at 恢复到当前时刻附近(断言 > 拨回值) +``` + +- [ ] **Step 2: 确认失败**(现状同值刷新不触发 onupdate,updated_at 不变)。 +- [ ] **Step 3: 实现**:`_recheck_item` 在每次状态落定后 `item.updated_at = datetime.utcnow()`(成功与降级两条路径都加)。 +- [ ] **Step 4:** 删除 resume_service.py、test_resume_service.py、batch-resume 路由与 import;跑全目录回归(chat/e2e 若引用 resume 端点一并清理)。 +- [ ] **Step 5: stage**。 + +--- + +### Task 5: 前端换接线(界面结构不变)+ 四语言 + +**Files:** +- Modify: `frontend/src/features/chat/api/transfer.api.ts`、`types/transfer.types.ts`、`composables/useChatTransfer.ts` +- Modify: `frontend/src/features/chat/components/messages/TransferMessageView.vue`、`TransferPrecheckCard.vue`、`TransferBacklogSummaryCard.vue` +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`、`errors.json` +- Modify: 相关 spec(`transferCards.spec.ts`、`TransferMessageView.spec.ts`、`transfer.api.spec.ts`) + +**Interfaces:** +- `executeTransferItems(itemIds: number[]) => POST /items/execute`;`TransferPrecheckItem` 增 `item_id: number; checked_at?: string|null; stale?: boolean; file_current?: boolean` +- `useChatTransfer.selected: Set`(勾选键从 invoice_no 改 item_id);`resume(itemIds)` = `batchRequery` 的语义别名(返回 results,由视图统计 recovered/still_blocked) +- 删除:`batchResumeTransferItems`、恢复跳预检卡导航逻辑、`toastResumeOpened/Refetching/Skipped/StillBlocked` 键 + +- [ ] **Step 1: 类型与 API**:`transfer.types.ts` 的 `TransferPrecheckItem` 加四字段;`transfer.api.ts` 新增 `executeTransferItems`(jsonHeaders POST `/items/execute`,body `{item_ids}`),删除 `batchResumeTransferItems`。更新 `transfer.api.spec.ts` 的 jsonHeaders 契约用例(新端点带 Content-Type)。 +- [ ] **Step 2: composable**:`selected` 改 `Set`(`executableInvoices`→`executableItemIds`;`applyDetail/applyPayload` 的默认勾选按 `item_id`);`execute()` 改 `executeTransferItems([...selected])`;删除 `batchResume`,新增 `resume(itemIds)` 直调 `batchRequeryTransferItems`(别名导出,视图统一走它)。 +- [ ] **Step 3: TransferPrecheckCard**:checkbox `:checked="selected.has(item.item_id)"`、emit toggle/execute 均带 `item_id`;库存数量单元格渲染 `{{ item.external_quantity ?? '—' }}` + 小字查询时刻(`checked_at` 的 HH:mm,`title` 用 `stockCheckedAtTitle`);`stale===true` 行加置灰 class + 「数据已过期,请重查」小标;`file_current===false` 加「文件已更新,请重新预检」小标;结果徽标映射加 `blocked_file_removed → resultFileRemoved`。对应更新 `transferCards.spec.ts`(勾选键、execute 参数为数组 item_id)。 +- [ ] **Step 4: TransferMessageView**:`onExecute(invoiceNos)` 改 `onExecute(itemIds)`;`onBacklogResume` 改为调 `transfer.resume(itemIds)` → `loadBacklog()` → 由 results 统计 `recovered`(status==='ready_to_execute')与 `still` → 提示 `toastRequeryRecovered({recovered, blocked})`;删除跳预检卡导航与 file_fetching/skipped 分支;恢复单行按钮走同一 handler。`TransferBacklogSummaryCard` 结果徽标映射补 `blocked_file_removed`。 +- [ ] **Step 5: 四语言**:新增键(chat.json):`stockCheckedAtTitle`("库存查询时刻:{time}")、`staleRow`("数据已过期,请重查")、`fileChangedRow`("文件已更新,请重新预检")、`resultFileRemoved`("文件已移除")、`toastExecuteStale`("{count} 笔数据已过期,请重查后生成")、`toastExecuteFileChanged`("{count} 笔文件已更新,请重新预检")、`toastRequeryRecovered`("恢复完成:{recovered} 笔已可执行 · {blocked} 笔仍阻断");errors.json 新增 `TRANSFER.ITEMS_STALE`/`TRANSFER.FILE_CHANGED`/`TRANSFER.EXECUTE_ITEMS_INVALID`;删除 `toastResumeOpened/toastResumeRefetching/toastResumeSkipped/toastResumeStillBlocked`。zh-TW/en/th 给出对应译文(en: "Stock checked at {time}" / "Stale — requery" / "File updated — re-precheck" / "Removed from file" / "{count} stale rows — requery before generating" / "{count} rows with file updated — re-precheck" / "Resume done: {recovered} executable · {blocked} still blocked")。 +- [ ] **Step 6: 验证**:`npm run build` 通过;`npx vitest run src/features/chat/` 全绿;`grep -rn "batchResume\|toastResume" frontend/src` 无残留。 +- [ ] **Step 7: stage**。 + +--- + +### Task 6: 批量库存查询对账排查(独立缺陷,探针 + 修复) + +**Files:** +- Create: `backend/tmp/diag_stock_batch.py`(仿 `backend/tmp/diag_precheck_empty.py` 的真实环境探针模式) +- Modify(若证实 bug): `backend/app/services/in_transit_transfer/capability_client.py` 或连接器查询映射层 + +**背景(实测矛盾)**:同一行(如 HOX260824001/002/007,CRANE 来源)预检批量查询得库存 0,单行重查得 30/40/36——两条路径必有一条错。 + +- [ ] **Step 1: 单元层复现尝试**:写 pytest 用 `FakeCapabilityClient` 构造"同 external_org 多 targets(≥3 个、含同料号不同批号/同批号不同料号)"场景,断言 `query_stock(...).lookup(material, warehouse, lot)` 与 seed 一一对应;若映射键冲突/覆盖可复现,即定位 `capability_client` 的结果装配逻辑缺陷并修复 + 回归(参考既有 `test_capability_client.py`、`test_query_inventory_gateway.py`)。 +- [ ] **Step 2: 真实数据探针**:`backend/tmp/diag_stock_batch.py`——对用户环境的三笔 Invoice(WTP26060612/HOX260824001/HOX260824007),分别走"批量 targets 一次查询"与"逐 target 单查询",打印两侧逐 target 结果与差异(只读,不写 ERP;复用 `transfer_deps.get_transfer_dependencies()`;真实连接器凭据由环境注入,脚本不得硬编码)。 +- [ ] **Step 3: 结论落档**:探针输出与根因写入 `docs/features/in-transit-transfer/technical.md` §6(运维关注点)新增小节;若修复,附回归测试;若需 ERP 侧核对,列出待确认清单交给用户。 +- [ ] **Step 4: stage**。 + +--- + +### Task 7: 全量回归 + 文档同步 + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md`(§4 API 表:+execute、-batch-resume/-prechecks/{id}/execute;§4.1 重写为"行不迁移/三层门禁/恢复=行级重查/预检=评估留痕";§6 补对账结论) +- Modify: `docs/funclist.md`(在途调拨表:改"最近预检恢复入口/待处理池批量操作"两行描述为最终语义;新增"按行执行与三层门禁"一行) + +- [ ] **Step 1:** `cd backend && python -m pytest tests/services/in_transit_transfer -q` 全绿(记录用例数)。 +- [ ] **Step 2:** `cd frontend && npm run build && npx vitest run` 全绿(记录用例数)。 +- [ ] **Step 3:** 更新两个文档(内容按本计划 Architecture 与 Task 3/4 的最终 API 面)。 +- [ ] **Step 4:** `git add` 全部改动文件;向用户汇报各步验证结果,等待提交批准。 + +--- + +## Self-Review 记录 + +- 规格覆盖:前端三区保留(Task 5 仅接线)✓;行不迁移(Task 1)✓;预检卡=范围视图(Task 2)✓;按行执行+TTL(Task 3)✓;hash 留痕不拦执行(Task 3 删执行链校验、create 保留计算)✓;文件版本对账+消失行(Task 1/3)✓;恢复=行级重查(Task 4+5)✓;库存查询时刻(Task 2 序列化 + Task 5 展示)✓;批量查询对账(Task 6)✓;文档(Task 7)✓。 +- 类型一致性:`item_id` 贯穿 serialize_item→DTO→前端类型→selected Set→execute(item_ids);`_item_evaluated_sha`/`scope_item_query` 定义于 Task 1、消费于 Task 2/3;错误码三处(service 抛/api envelope/errors.json)已对齐。 +- 已知取舍(已在对话向用户说明):restore 的 scope 视图会显示范围内所有行(含非本次评估新增行)——这是"实时视图"的既定语义;行新鲜度用 `updated_at` 近似(评估时显式赋值,关闭等操作也会刷新但那些状态本就不可执行)。 diff --git a/frontend/src/features/chat/api/transfer.api.spec.ts b/frontend/src/features/chat/api/transfer.api.spec.ts index a2cc4564..0f3dd6e9 100644 --- a/frontend/src/features/chat/api/transfer.api.spec.ts +++ b/frontend/src/features/chat/api/transfer.api.spec.ts @@ -23,10 +23,10 @@ vi.mock('@/shared/utils/auth', () => ({ import { cancelTransferRun, - createTransferPrecheck, - executeTransferPrecheck, + createTransferMatching, + executeTransferItems, getTransferBacklogSummary, - getTransferPrecheck, + getTransferMatching, getTransferRun, listTransferSources, manualCloseTransferItem, @@ -39,21 +39,24 @@ describe('transfer.api JSON request contract', () => { requestBlob.mockReset(); }); - it('创建预检 POST 带 Content-Type: application/json 与序列化 source_codes', () => { - createTransferPrecheck({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }); + it('创建匹配 POST 带 Content-Type: application/json 与序列化 source_codes', () => { + createTransferMatching({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' }); const [url, init] = requestJson.mock.calls[0] as [string, RequestInit]; - expect(url).toBe('/api/in-transit-transfer/prechecks'); + expect(url).toBe('/api/in-transit-transfer/matchings'); expect(init.method).toBe('POST'); expect((init.headers as Record)['Content-Type']).toBe('application/json'); expect(init.body).toBe(JSON.stringify({ source_codes: ['DBS-AWSBI'], business_date: '2026-08-18' })); }); - it('直接生成调拨单 POST 带 application/json', () => { - executeTransferPrecheck('TPC-1', ['INV-001']); - const [, init] = requestJson.mock.calls[0] as [string, RequestInit]; + it('按明细行执行调拨 POST /items/execute 带 application/json 与 item_ids 契约', () => { + // [断言意图] 行式执行(2026-09-23 item-centric 重构):执行不再挂在旧匹配详情端点下, + // 改为独立 items/execute,body 键从 invoice_nos 改为 item_ids;JSON 头契约不变。 + executeTransferItems([101, 102]); + const [url, init] = requestJson.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('/api/in-transit-transfer/items/execute'); expect(init.method).toBe('POST'); expect((init.headers as Record)['Content-Type']).toBe('application/json'); - expect(init.body).toBe(JSON.stringify({ invoice_nos: ['INV-001'] })); + expect(init.body).toBe(JSON.stringify({ item_ids: [101, 102] })); }); it('重试/关闭/取消 POST 带 application/json', () => { @@ -67,7 +70,7 @@ describe('transfer.api JSON request contract', () => { }); it('GET 端点只需鉴权头,不需要强制 Content-Type', () => { - getTransferPrecheck('TPC-1'); + getTransferMatching('MTG-1'); getTransferRun('RUN-1'); getTransferBacklogSummary(); listTransferSources(); diff --git a/frontend/src/features/chat/api/transfer.api.ts b/frontend/src/features/chat/api/transfer.api.ts index 8860f30f..4df446f7 100644 --- a/frontend/src/features/chat/api/transfer.api.ts +++ b/frontend/src/features/chat/api/transfer.api.ts @@ -10,9 +10,11 @@ import type { TransferActionResult, TransferBacklogItem, TransferBacklogSummary, + TransferBatchResult, TransferExecuteResponse, - TransferPrecheckDetail, - TransferPrecheckSummary, + TransferMatchingDetail, + TransferMatchingItem, + TransferMatchingSummary, TransferRunResult, TransferSourceFileStatus, TransferSourceOption, @@ -24,7 +26,7 @@ const BASE = '/api/in-transit-transfer'; /** JSON 请求头:除鉴权外必须带 Content-Type: application/json,否则 Flask request.get_json 解析不到 body。 */ const jsonHeaders = () => ({ 'Content-Type': 'application/json', ...getAuthHeaders() }); -export interface CreatePrecheckPayload { +export interface CreateMatchingPayload { source_codes: string[]; business_date?: string; receipt_date_from?: string; @@ -33,26 +35,33 @@ export interface CreatePrecheckPayload { transfer_type?: TransferType; } -/** 创建预检(只读) */ -export const createTransferPrecheck = (payload: CreatePrecheckPayload) => - requestJson(BASE + '/prechecks', { +/** 创建匹配(只读) */ +export const createTransferMatching = (payload: CreateMatchingPayload) => + requestJson(BASE + '/matchings', { method: 'POST', headers: jsonHeaders(), body: JSON.stringify(payload), }); -/** 恢复预检进度与明细 */ -export const getTransferPrecheck = (precheckId: string) => - requestJson(`${BASE}/prechecks/${precheckId}`, { +/** 恢复匹配进度与明细 */ +export const getTransferMatching = (matchingId: string) => + requestJson(`${BASE}/matchings/${matchingId}`, { headers: getAuthHeaders(), }); -/** 确认选择范围并直接生成执行 Run */ -export const executeTransferPrecheck = (precheckId: string, invoiceNos: string[]) => - requestJson(`${BASE}/prechecks/${precheckId}/execute`, { +/** 可调拨明细:全局可执行行队列(勾选后 executeTransferItems 按行生成调拨单) */ +export const listExecutableTransferItems = () => + requestJson<{ items: TransferMatchingItem[]; counts: { executable_count: number } }>( + `${BASE}/items/executable`, + { headers: getAuthHeaders() }, + ); + +/** 按明细行执行调拨(item-centric:body {item_ids};三层门禁在后端,失败抛 BusinessError) */ +export const executeTransferItems = (itemIds: number[]) => + requestJson(`${BASE}/items/execute`, { method: 'POST', headers: jsonHeaders(), - body: JSON.stringify({ invoice_nos: invoiceNos }), + body: JSON.stringify({ item_ids: itemIds }), }); /** 恢复 Run 最终结果 */ @@ -89,7 +98,7 @@ export const manualCloseTransferItem = (itemId: number, reason: string) => export const downloadTransferReceiptFiles = (runNo: string) => requestBlob(`${BASE}/runs/${runNo}/receipt-files`, { headers: getAuthHeaders() }); -/** 下载预检冻结的 ERP 库存表(csv) */ +/** 下载匹配冻结的 ERP 库存表(csv) */ export const downloadTransferErpInventory = (runNo: string) => requestBlob(`${BASE}/runs/${runNo}/external-inventory`, { headers: getAuthHeaders() }); @@ -97,10 +106,26 @@ export const downloadTransferErpInventory = (runNo: string) => export const downloadTransferExceptions = (runNo: string) => requestBlob(`${BASE}/runs/${runNo}/exceptions.xlsx`, { headers: getAuthHeaders() }); +/** 批量重查库存(待处理池多选;单行隔离,按明细 id 直取;恢复处理=重查的唯一后端) */ +export const batchRequeryTransferItems = (itemIds: number[]) => + requestJson(`${BASE}/items/batch-requery`, { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ item_ids: itemIds }), + }); + +/** 批量人工关闭异常项(原因整批共用;单行隔离) */ +export const batchManualCloseTransferItems = (itemIds: number[], reason: string) => + requestJson(`${BASE}/items/batch-manual-close`, { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ item_ids: itemIds, reason }), + }); + /** 批量重查 ERP 库存(可恢复阻断行;invoice_nos 缺省 = 全部阻断行) */ -export const requeryTransferItems = (precheckNo: string, invoiceNos?: string[]) => - requestJson<{ precheck_no: string; total: number; results: Array> }>( - `${BASE}/prechecks/${precheckNo}/items/requery`, +export const requeryTransferMatchingItems = (matchingNo: string, invoiceNos?: string[]) => + requestJson<{ matching_no: string; total: number; results: Array> }>( + `${BASE}/matchings/${matchingNo}/items/requery`, { method: 'POST', body: JSON.stringify(invoiceNos ? { invoice_nos: invoiceNos } : {}), headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' } }, ); diff --git a/frontend/src/features/chat/components/messages/ChatMessageBubble.vue b/frontend/src/features/chat/components/messages/ChatMessageBubble.vue index 2733adf2..5b3c2362 100644 --- a/frontend/src/features/chat/components/messages/ChatMessageBubble.vue +++ b/frontend/src/features/chat/components/messages/ChatMessageBubble.vue @@ -99,11 +99,11 @@ const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv'; const isContractReviewMessage = computed(() => message.type === 'procurement-contract-review'); const isTransferMessage = computed( () => - message.type === 'transfer-precheck' + message.type === 'transfer-match' || message.type === 'transfer-progress' || message.type === 'transfer-result', ); -/** 调拨消息带宽表格(预检明细 10+ 列),放宽气泡宽度上限避免横向挤压成局部布局。 */ +/** 调拨消息带宽表格(匹配明细 10+ 列),放宽气泡宽度上限避免横向挤压成局部布局。 */ const wideMessage = computed(() => isTransferMessage.value || isContractReviewMessage.value); const isLeaveMessage = computed(() => diff --git a/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue b/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue index acf6a5e0..2b18dc5c 100644 --- a/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue +++ b/frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue @@ -1,22 +1,93 @@