diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 5a7f8929..e2618102 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -421,6 +421,16 @@ def is_business_user_action(action_code: str | None) -> bool: return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES +def inventory_preparation_primary_action(status: str | None) -> str | None: + """裁决库存准备 Gate 面向业务用户的主动作。""" + normalized_status = str(status or '').strip().lower() + if normalized_status == 'waiting_external': + return 'poll_inventory_preparation' + if normalized_status in {'blocked_manual', 'blocked_retryable'}: + return 'retry_inventory_preparation' + return None + + def is_technical_gate_party(responsible_party: str | None) -> bool: """判断责任方是否为技术自动 Gate(system/worker)。""" return str(responsible_party or '').strip() in PROCESS_GATE_TECHNICAL_PARTIES diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 99ac9328..83781229 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -779,7 +779,11 @@ def _handle_retry_inventory_preparation( operation_id=str(payload.get('operation_id') or '').strip() or None, gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None, ) - response = ensure_inventory(_task_payload(execution, payload)) + inventory_payload = _task_payload(execution, payload) + # 用户重试必须进入逐源 RPA Attempt,生成新的 inventory trigger;轮询动作继续复用普通模式。 + if payload.get('action_code') != 'poll_inventory_preparation': + inventory_payload['mode'] = 'retry_rpa' + response = ensure_inventory(inventory_payload) if preparation_round is not None: from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 519207e8..f4bf1aa0 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -30,6 +30,7 @@ from app.services.shipping_notice.process_gate_contract import ( PROCESS_GATE_RECOVERABLE_STATUSES, action_presentation, get_process_gate_definition, + inventory_preparation_primary_action, is_business_user_action, ) from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text @@ -83,6 +84,87 @@ def _projection_primary_next_action(*, gate_code: str, status: str) -> str | Non return str(value) if value else None +# 库存 RPA / 准备失败原因:统一由业务用户触发「重新获取库存」(retry_inventory_preparation)。 +# 与 error_explainability_contract.EXPLAINABILITY_REASON_META 中 inventory_file_empty 等 +# 的 prescribed action 保持一致;这些原因在 process_gate_contract 中分类为 retryable_tech, +# 但因 inventory_preparation 的 responsible_party='worker',历史投影会按「worker/retry_ 技术 +# 动作屏蔽」规则将其从业务按钮隐藏,导致用户只能看到被降级的人工上传入口。 +def _resolve_recovery_next_action( + *, blocking: dict[str, Any] | None, full: dict[str, Any], execution: Any, +) -> tuple[str | None, bool]: + """ + 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 + + [STEP 1] 库存 RPA 失败(inventory_preparation Gate + retryable_tech 原因码)统一下发 + ``retry_inventory_preparation``(重新获取库存),绕过历史「worker/retry_ 技术动作屏蔽」 + 分支,使业务用户在库存 RPA 失败时可直接重试,而非被降级为人工上传入口。 + [STEP 2] 货代上传 RPA / 人工交接失败保持统一 RPA 重试入口。 + [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留 + RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。 + """ + if not blocking: + return None, False + blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower() + normalized_reason = str((blocking or {}).get('blocking_reason_code') or '').strip().lower() + status = str((blocking or {}).get('status') or '').strip().lower() + + # [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。 + if blocking_gate_code == 'inventory_preparation': + inventory_action = inventory_preparation_primary_action(status) + if inventory_action: + return inventory_action, False + + # [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。 + if ( + blocking_gate_code == 'freight_upload_rpa' + and normalized_reason in {'upload_rpa_failed', 'upload_rpa_login_failed', 'upload_platform_rejected'} + ): + return 'retry_freight_upload_rpa', False + if ( + blocking_gate_code == 'manual_upload_handoff' + and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'} + ): + return 'retry_freight_upload_rpa', False + + # [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导)。 + next_action = full.get('primary_next_action_code') or _projection_primary_next_action( + gate_code=blocking_gate_code, status=status, + ) + technical_auto_only = False + # 技术责任方的 retry_* 只作为系统执行动作,不能直接充当业务用户主按钮; + # RecoveryPlan 仍可在下方投影为经过权限校验的恢复入口。 + if next_action and ( + not is_business_user_action(str(next_action)) + or ( + str(full.get('responsible_party') or '').strip().lower() in {'system', 'worker'} + and str(next_action).startswith('retry_') + ) + ): + next_action = None + technical_auto_only = True + + # RecoveryPlan 复核入口兜底(inventory_matching / inventory_sufficiency)。 + if not next_action: + recovery_targets = full.get('recovery_targets') or [] + if recovery_targets and blocking_gate_code == 'inventory_matching': + next_action = 'open_inventory_match_review' + technical_auto_only = False + elif recovery_targets and blocking_gate_code == 'inventory_sufficiency': + next_action = 'open_shortage_review' + technical_auto_only = False + # 库存准备/匹配/货代上传 RPA 在 blocked_retryable 时仍允许业务用户恢复。 + if not next_action and blocking_gate_code in { + 'inventory_preparation', 'inventory_matching', 'freight_upload_rpa', + }: + candidate = _projection_primary_next_action( + gate_code=blocking_gate_code, status=status, + ) + if candidate and is_business_user_action(candidate): + next_action = candidate + technical_auto_only = False + return next_action, technical_auto_only + + def serialize_gate_attempt( attempt: ShippingProcessGateAttempt | None, *, @@ -430,80 +512,13 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, if diagnostic_hint: break reason_code = (blocking or {}).get('blocking_reason_code') - next_action = full.get('primary_next_action_code') or ( - _projection_primary_next_action( - gate_code=str((blocking or {}).get('gate_code') or ''), - status=str((blocking or {}).get('status') or ''), - ) if blocking else None + # [STEP] 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 + # 库存 RPA 失败统一下发「重新获取库存」,不再因 worker 责任方被技术动作屏蔽。 + next_action, technical_auto_only = _resolve_recovery_next_action( + blocking=blocking, + full=full, + execution=execution, ) - # [STEP] 兼容历史 Gate 行:RPA 失败曾被旧契约错误写成 - # regenerate_manual_upload_todo;当前 Gate + 原因码才是履约真相, - # 统一纠正为用户可主动执行的 RPA 重试。AUTO_UPLOAD 只控制自动触发, - # 不参与手动动作投影。 - blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower() - normalized_reason = str(reason_code or '').strip().lower() - if ( - blocking_gate_code == 'freight_upload_rpa' - and normalized_reason in { - 'upload_rpa_failed', - 'upload_rpa_login_failed', - 'upload_platform_rejected', - } - ): - next_action = 'retry_freight_upload_rpa' - elif ( - blocking_gate_code == 'manual_upload_handoff' - and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'} - ): - # 人工交接仍保留人工登记入口(Footer),同时在 Gate 卡提供显式 RPA 重试。 - next_action = 'retry_freight_upload_rpa' - # [STEP] 所有冻结 Gate 动作均可投影到工作台;是否可执行由页面 canHandle - # 与 Workspace API 的权限/版本校验共同决定,禁止前端自行派生动作。 - technical_auto_only = False - # 技术责任方的 retry_* 只作为系统执行动作,不能直接充当业务用户主按钮; - # RecoveryPlan 仍可在下方投影为经过权限校验的恢复入口。 - if ( - next_action - and ( - not is_business_user_action(str(next_action)) - or ( - str(full.get('responsible_party') or '').strip().lower() in {'system', 'worker'} - and str(next_action).startswith('retry_') - ) - ) - ): - next_action = None - technical_auto_only = bool(blocking) - - # [STEP] 正式 OT 后的库存阻断仍需给业务用户提供精确入口:技术主动作 - # (retry_inventory_*)不直接暴露,但 RecoveryPlan 存在时必须保留当前 - # Gate 的复核入口,否则 apply_post_ot_gate_rules 会把整个阻断误判为系统态, - # 前端也就不会挂载 ProcessGateRecoveryCard。 - if blocking and not next_action: - gate_code = str(blocking.get('gate_code') or '').strip().lower() - recovery_targets = full.get('recovery_targets') or [] - if recovery_targets and gate_code == 'inventory_matching': - next_action = 'open_inventory_match_review' - technical_auto_only = False - elif recovery_targets and gate_code == 'inventory_sufficiency': - next_action = 'open_shortage_review' - technical_auto_only = False - - # 正式 OT 后仍需允许业务用户恢复履约链路中的技术失败: - # 库存准备/匹配以及货代上传 RPA 的动作码由 Gate 合同固定, - # 不把其他 system/worker 节点泛化为可人工操作。 - if not next_action and gate_code in { - 'inventory_preparation', - 'inventory_matching', - 'freight_upload_rpa', - }: - candidate = _projection_primary_next_action( - gate_code=gate_code, - status=str(blocking.get('status') or ''), - ) - if candidate and is_business_user_action(candidate): - next_action = candidate - technical_auto_only = False # 无当前阻断时禁止残留 confirm_customer,避免「客户已确认」仍显示为优先处理。 if not blocking and str(next_action or '').strip() == 'confirm_customer': next_action = None @@ -513,6 +528,11 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, if blocking: if next_action and is_business_user_action(str(next_action)): allowed_actions.append(str(next_action)) + if ( + str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation' + and next_action == 'retry_inventory_preparation' + ): + allowed_actions.append('upload_inventory_file') for target in full.get('recovery_targets') or []: code = str(target.get('action_code') or '').strip() if code and code not in allowed_actions and is_business_user_action(code): diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index 27290b96..61847ec3 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -20,6 +20,7 @@ from app.services.shipping_notice.fulfillment_audit import record_fulfillment_au from app.services.shipping_notice.process_gate_contract import ( PROCESS_GATE_ACTION_CODES, get_process_gate_definition, + inventory_preparation_primary_action, is_business_user_action, is_technical_gate_party, primary_next_action_for_gate, @@ -217,7 +218,8 @@ def request_gate_action( details={'gate_code': gate.gate_code, 'action_code': action}, ) - primary = gate.next_action_code or primary_next_action_for_gate( + primary = inventory_preparation_primary_action(gate.status) if gate.gate_code == 'inventory_preparation' else None + primary = primary or gate.next_action_code or primary_next_action_for_gate( gate_code=gate.gate_code, status=gate.status, ) # [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA @@ -236,6 +238,8 @@ def request_gate_action( 'adopt_rule_suggestion', 'keep_manual_inventory_decision', } + if gate.gate_code == 'inventory_preparation' and primary == 'retry_inventory_preparation': + allowed_side.add('upload_inventory_file') if primary and action != primary and action not in allowed_side and recovery_definition is None: raise ValidationError( 'Action is not the primary recovery action for this gate', diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index be767aaf..fe330717 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -10,6 +10,9 @@ services/shipping_notice/ui_state.py stp_facts、progress_nodes); 若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留 download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动); + [兼容] action_buttons 为只读兼容字段:权威可恢复操作入口已统一为 + process_gate.next_action_code(如 retry_inventory_preparation),本字段仅保留供 + 任务详情 / 聊天状态 / 旧入口消费,禁止再向其新增恢复动作;待确认无活跃消费者后删除。 Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); 批次 UI 仅作会话上传集合摘要,不作为履约写操作面。 """ @@ -631,6 +634,8 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]: "current_step": current_step, "steps": steps, "summary": summary, + # [兼容] action_buttons 为只读兼容字段(见模块 docstring);新 UI 应消费 + # summary.process_gate.next_action_code,本字段仅作历史消费者过渡,不再扩展。 "action_buttons": action_buttons, "process_gate": process_gate, "updated_at": task.updated_at.isoformat() if task.updated_at else None, diff --git a/backend/tests/test_shipping_process_gate_recovery_action_contract.py b/backend/tests/test_shipping_process_gate_recovery_action_contract.py new file mode 100644 index 00000000..d9da1fad --- /dev/null +++ b/backend/tests/test_shipping_process_gate_recovery_action_contract.py @@ -0,0 +1,148 @@ +""" +tests/test_shipping_process_gate_recovery_action_contract.py + +用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 失败统一下发 +「重新获取库存」(retry_inventory_preparation),不再因 inventory_preparation +Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽」规则 +降级为人工上传入口 (upload_inventory_file)。 + +依赖:process_gate_projection._resolve_recovery_next_action。 +逻辑:pure_unit 纯单测(不建 Flask/DB);以阻断原因码 / Gate 状态为输入, + 断言业务用户主恢复动作 next_action_code 与 technical_auto_only 标志。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.process_gate_projection import ( + _resolve_recovery_next_action, +) + + +@pytest.mark.pure_unit +def _mk(blocking: dict, *, primary_next_action_code=None, recovery_targets=None, + responsible_party='worker') -> dict: + """构造 _resolve_recovery_next_action 所需的 full / blocking 投影输入。""" + full = { + 'primary_next_action_code': primary_next_action_code, + 'responsible_party': responsible_party, + 'recovery_targets': recovery_targets or [], + } + return full, blocking + + +@pytest.mark.pure_unit +def test_inventory_file_empty_blocked_manual_resolves_to_retry(): + """核心回归:inventory_file_empty + blocked_manual 必须下发「重新获取库存」。 + + 真实任务 SN-20260811-717D2EAD 曾因 Gate 状态被写成 blocked_manual 而投影出 + upload_inventory_file;原因码 inventory_file_empty 在契约中属 retryable_tech, + 业务用户应可直接重试而非被迫人工上传。 + """ + full, blocking = _mk( + {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_file_empty'}, + primary_next_action_code='upload_inventory_file', + ) + action, tech_only = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'retry_inventory_preparation' + assert tech_only is False + + +@pytest.mark.pure_unit +@pytest.mark.parametrize('reason', [ + 'inventory_file_empty', + 'inventory_preparation_failed', + 'inventory_rpa_timeout', + 'inventory_rpa_login_failed', + 'inventory_rpa_export_failed', + 'inventory_file_identity_mismatch', + 'inventory_file_missing', + 'inventory_rpa_exhausted', +]) +def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason): + """全部库存 RPA 失败原因(无论 blocked_manual / blocked_retryable)均下发「重新获取库存」。""" + for status in ('blocked_manual', 'blocked_retryable'): + full, blocking = _mk( + {'gate_code': 'inventory_preparation', 'status': status, + 'blocking_reason_code': reason}, + ) + action, tech_only = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'retry_inventory_preparation', (reason, status) + assert tech_only is False + + +@pytest.mark.pure_unit +def test_inventory_rpa_exhausted_falls_back_to_manual_upload(): + """历史耗尽码仍允许用户手动重新获取库存。""" + full, blocking = _mk( + {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_rpa_exhausted'}, + ) + action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'retry_inventory_preparation' + + +@pytest.mark.pure_unit +def test_inventory_file_missing_falls_back_to_manual_upload(): + """缺库存文件时仍优先允许用户手动重新获取库存。""" + full, blocking = _mk( + {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_file_missing'}, + ) + action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'retry_inventory_preparation' + + +@pytest.mark.pure_unit +def test_freight_upload_rpa_failure_keeps_retry_entry(): + """货代上传 RPA 失败保持统一 RPA 重试入口(既有行为不回退)。""" + full, blocking = _mk( + {'gate_code': 'freight_upload_rpa', 'status': 'blocked_manual', + 'blocking_reason_code': 'upload_rpa_failed'}, + ) + action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'retry_freight_upload_rpa' + + +@pytest.mark.pure_unit +def test_inventory_matching_recovery_target_navigates_to_review(): + """inventory_matching 有 RecoveryPlan 时保留复核入口(既有兜底不回退)。""" + full, blocking = _mk( + {'gate_code': 'inventory_matching', 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_match_failed'}, + recovery_targets=[{'action_code': 'retry_inventory_matching'}], + ) + action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'open_inventory_match_review' + + +@pytest.mark.pure_unit +def test_inventory_preparation_retryable_without_reason_uses_contract_action(): + """无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。""" + full, blocking = _mk( + {'gate_code': 'inventory_preparation', 'status': 'blocked_retryable', + 'blocking_reason_code': None}, + ) + action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'retry_inventory_preparation' + + +@pytest.mark.pure_unit +def test_inventory_preparation_waiting_keeps_refresh_action(): + """RPA 正在执行时只允许刷新进度,不能重复提交获取库存。""" + full, blocking = _mk( + {'gate_code': 'inventory_preparation', 'status': 'waiting_external', + 'blocking_reason_code': 'inventory_rpa_queued'}, + ) + action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) + assert action == 'poll_inventory_preparation' + + +@pytest.mark.pure_unit +def test_no_blocking_returns_no_action(): + """无当前阻断时不下发给任何主恢复动作。""" + full, _ = _mk({'gate_code': 'inventory_preparation', 'status': 'passed'}) + action, _ = _resolve_recovery_next_action(blocking=None, full=full, execution=None) + assert action is None diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 05dcfa01..fc89de6c 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -348,9 +348,10 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo gate.next_action_code = 'retry_inventory_preparation' db.session.commit() + captured_payload = {} monkeypatch.setattr( 'app.services.shipping_notice.inventory_workflow.ensure_inventory', - lambda payload: { + lambda payload: captured_payload.update(payload) or { 'status': 'success', 'data': { 'rpa': { @@ -380,6 +381,7 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo task_id=task.id, execution_id=execution.id, gate_attempt_id=attempt.id, ).one() assert result.get('skipped') is False + assert captured_payload['mode'] == 'retry_rpa' assert attempt.status == 'succeeded' assert gate.status == 'passed' assert preparation.status == 'succeeded' diff --git a/docs/features/shipping-notice/process-gate-recovery-contract.md b/docs/features/shipping-notice/process-gate-recovery-contract.md new file mode 100644 index 00000000..a81684e0 --- /dev/null +++ b/docs/features/shipping-notice/process-gate-recovery-contract.md @@ -0,0 +1,290 @@ +# 货代发货通知 — 全门禁中断恢复契约(Phase 1) + +> **权威契约文档**:冻结 **20** 个业务门禁编码、状态、恢复动作、失效规则、权限与客户端 API 边界。 +> **代码真相源**:`backend/app/services/shipping_notice/process_gate_contract.py`、`process_gate_dependency.py`、`progress_audit_contract.py`(`PROCESS_GATE_AUDIT_EVENT_TYPES`)。 +> **运行时 / 部署 / Dify**:仍以 [technical.md](./technical.md) 为准;本文件不替代技术手册。 +> **阶段说明**:Phase 0(库存源路由独立重算)已闭环。**本契约以 `PROCESS_GATE_DEFINITIONS` 为唯一数量真相源**(禁止硬编码 19/20)。 +> **2026-08 增补**:业务人工 Gate vs 技术自动 Gate;业务用户不可见技术重试动作;建单前统一恢复协调器;行级先行履约规则(见 demand/tec)。 +> **2026-08-04 增补(多 EML / 直接 PDF)**:Gate 恢复对象将扩展为 `order_intake` / `order_task` 工作项(见 technical.md §1.6.2)。直接 PDF 解析失败走 Document/Layout Gate,不进入邮件裁决 Gate;EML 内关键字段 PDF 冲突可投影为 `field_conflict_resolution` 阻断。本文件门禁编码表暂不增删;阶段 4 接线时同步 `process_gate_bridge`。 + +契约版本:`shipping-process-gate-v2` + +### Gate 实施状态(v2) + +运行时由 `PROCESS_GATE_DEFINITIONS[].implementation_status` 下发,前端不得自行推导: + +- Gate 1–9:`supported`,已有文档/解析/订单裁决适配器或人工导航入口; +- Gate 10–20:`implemented`,库存与履约恢复闭环已接线; +- `adapter_required` / `blocked`:保留为显式未放行状态,当前 20 Gate 不使用。 + +--- + +## 1. 范围与阶段边界 + +| 阶段 | 内容 | 状态 | +| --- | --- | --- | +| Phase 0 | 库存源路由门禁纵向闭环(不重识别 PDF;人工决定优先;幂等与审计) | **已关闭** | +| 契约冻结 | 全部门禁 / 状态 / 动作 / 失效图 / 权限 / TS 类型与文档对齐 | **进行中(本文)** | +| 建单前恢复协调 | `order_review_resume_service`:Gate/资格/auto_gate 三层 + 幂等自动建单 | **已落地** | +| 行级先行履约 | 完整明细行波次 Task;禁止拆数量;`shipping_order_review_line_decisions` | **已落地(核心)** | +| 技术 Gate 业务用户收口 | `request_gate_action` fail-closed;投影 `technical_auto_only` | **已落地** | +| 技术 Gate 收口 | 业务用户只读技术状态;管理员诊断中心 | **规划中** | + +最终目标:某一门禁失败时只恢复该门禁,复用输入未变化的上游结果,精确失效受影响下游,并从最近合法检查点继续推进。 + +--- + +## 2. 二十个业务门禁 + +| 顺序 | `gate_code` | 业务标签 | 责任方 | 主要恢复动作(按阻断状态) | +| ---: | --- | --- | --- | --- | +| 1 | `document_materialization` | 文档和附件可用性 | system | `rematerialize_document` | +| 2 | `layout_parsing` | PDF 版面解析 | worker | `retry_layout_parsing` | +| 3 | `document_profile_routing` | Profile/模板路由 | system | `reroute_document_profile` / `open_profile_review`(只读) | +| 4 | `order_field_extraction` | 订单字段抽取 | worker | `retry_order_extraction` / `open_order_review` | +| 5 | `field_completeness` | 必填字段完整性 | owner | `edit_order_fields` | +| 6 | `reservation_validation` | Reservation 格式和证据 | owner | `revalidate_reservation` / `edit_reservation` | +| 7 | `customer_resolution` | 客户身份识别 | owner | `retry_customer_resolution` / `confirm_customer` | +| 8 | `duplicate_detection` | 重复订单/修订判断 | owner | `retry_duplicate_detection` / `adjudicate_duplicate` | +| 9 | `field_conflict_resolution` | 字段冲突 | owner | `resolve_field_conflicts` | +| 10 | `inventory_source_routing` | 库存源路由 | owner | `retry_with_latest_rules` / `open_inventory_source_review` | +| 11 | `order_freeze_readiness` | 订单冻结资格 | system | `recheck_freeze_readiness` / `open_order_review` | +| 12 | `task_creation` | ShippingTask 创建 | system | `retry_task_creation` | +| 13 | `inventory_preparation` | 库存文件或快照准备 | worker | 运行中 `poll_inventory_preparation`;未通过时主动作 `retry_inventory_preparation`,并保留 `upload_inventory_file` 作为辅助输入入口 | +| 14 | `inventory_field_mapping` | 库存字段映射 | owner | `retry_inventory_field_mapping` / `confirm_inventory_field_mapping` | +| 15 | `inventory_matching` | Reservation + 料号匹配 | worker | `retry_inventory_matching` / `open_inventory_match_review` | +| 16 | `inventory_sufficiency` | 库存满足性 | owner | `recheck_inventory_sufficiency` / `open_shortage_review` | +| 17 | `excel_readiness` | Excel 生成资格 | system | `recheck_excel_readiness` | +| 18 | `artifact_generation` | Excel Artifact | worker | `regenerate_excel_artifact` | +| 19 | `freight_upload_rpa` | 货代上传 RPA | worker | `poll_freight_upload_rpa` / `retry_freight_upload_rpa` | +| 20 | `manual_upload_handoff` | 人工上传交接 | owner | `regenerate_manual_upload_todo` | + +规则: + +- 每个 `gate_code` 全局唯一,`sequence_no` 连续 1..20。 +- 每种 Gate 状态最多一个主要 `next_action`;前端禁止本地推导动作码。 +- **业务用户**仅可见 `PROCESS_GATE_BUSINESS_USER_ACTION_CODES`;技术重试不对业务投影。 +- 库存源路由额外动作:`adopt_rule_suggestion`、`keep_manual_inventory_decision`。 +- **禁止**业务用户人工选择/切换 PDF Profile;`open_profile_review` 仅导航至只读模板区。 + +--- + +## 2.1 建单前恢复协调(增补) + +```text +业务裁决(客户/重复/冲突/校验) + → validate + Gate 同步 + → Candidate Qualification 重算 + → auto_gate? + ├─ true → 幂等 confirm_review_case + auto_progress + └─ false → 停在复核台「确认建单」 +``` + +`resume_outcome` 字段:`gate_recalculated` / `qualification_status` / `auto_gate_allowed` / `task_created` / `task_no` / `auto_progress_started` / `outcome`。 + +--- + +## 3. 状态枚举 + +### 3.1 Gate 状态(`ShippingProcessGateStatus`) + +```text +pending +queued +running +passed +blocked_retryable +blocked_manual +waiting_external +failed_terminal +invalidated +skipped +``` + +| 子集 | 成员 | +| --- | --- | +| 终态 | `passed`、`failed_terminal`、`skipped` | +| 可恢复 | `blocked_retryable`、`blocked_manual`、`waiting_external`、`invalidated`、`failed_terminal` | + +### 3.2 Execution 状态 + +```text +active | blocked | waiting_external | completed | cancelled | failed +``` + +### 3.3 Attempt 状态 + +```text +queued | running | succeeded | failed | cancelled | superseded +``` + +### 3.4 责任方(`ShippingProcessGateResponsibleParty`) + +```text +system | worker | owner | admin | external +``` + +### 3.5 触发类型 + +```text +auto | user_retry | user_manual | worker_takeover | upstream_invalidation | system_requeue +``` + +--- + +## 4. 动作码(`ShippingProcessGateActionCode`) + +完整集合与 Python `PROCESS_GATE_ACTION_CODES` 对齐,包括但不限于: + +`rematerialize_document`、`retry_layout_parsing`、`reroute_document_profile`、`open_profile_review`、`retry_order_extraction`、`open_order_review`、`edit_order_fields`、`revalidate_reservation`、`edit_reservation`、`retry_customer_resolution`、`confirm_customer`、`retry_duplicate_detection`、`adjudicate_duplicate`、`resolve_field_conflicts`、`retry_with_latest_rules`、`open_inventory_source_review`、`adopt_rule_suggestion`、`keep_manual_inventory_decision`、`recheck_freeze_readiness`、`retry_task_creation`、`retry_inventory_preparation`、`poll_inventory_preparation`、`upload_inventory_file`、`retry_inventory_field_mapping`、`confirm_inventory_field_mapping`、`retry_inventory_matching`、`open_inventory_match_review`、`recheck_inventory_sufficiency`、`open_shortage_review`、`recheck_excel_readiness`、`regenerate_excel_artifact`、`regenerate_manual_upload_todo`。 + +客户端恢复请求只允许提交服务端下发的 `action_code`(外加 `expected_gate_version` 与 `idempotency_key`)。 + +--- + +## 5. 状态边界 + +```text +ShippingProcessExecution / Gate / Attempt + = 业务状态真相(门禁是否通过、阻断原因、下一动作、输入指纹) + +Job + = 调度状态真相(排队、领取、重试、超时回收) + +WorkflowItem + = 用户业务台账与聚合进度(列表/时间线/待办投影) + +ShippingTask + = 冻结订单及履约实体(建单后事实) +``` + +禁止事项: + +- 不得用 `Job.status`、`step_payload_json` 或前端本地推导作为门禁恢复真相。 +- 不得引入 Temporal、Celery、Kafka 或新的工作流平台;继续复用现有 PostgreSQL Job + Shipping Worker。 + +--- + +## 6. 下游失效规则 + +上游输入变化时,必须精确失效依赖下游(不含变化源自身)。代码源:`PROCESS_GATE_INVALIDATION_RULES`。 + +| 变化类型(`change_type`) | 必须失效的下游门禁 | +| --- | --- | +| `pdf_or_extraction_changed` | `field_completeness` → … → `manual_upload_handoff`(字段完整性及之后全部履约门禁) | +| `reservation_changed` | `duplicate_detection`、`order_freeze_readiness`、`inventory_matching`、`inventory_sufficiency`、`excel_readiness`、`artifact_generation`、`manual_upload_handoff` | +| `part_number_changed` | `order_freeze_readiness`、`inventory_matching`、`inventory_sufficiency`、`excel_readiness`、`artifact_generation`、`manual_upload_handoff` | +| `quantity_changed` | 同 `part_number_changed` | +| `customer_changed` | `duplicate_detection`、`order_freeze_readiness`、`task_creation` 及全部库存/Excel/上传门禁 | +| `inventory_source_changed` | `inventory_preparation` → `manual_upload_handoff` | +| `inventory_file_changed` | `inventory_field_mapping` → `manual_upload_handoff` | +| `inventory_field_mapping_changed` | `inventory_matching` → `manual_upload_handoff` | +| `excel_regeneration_only` | 仅 `artifact_generation`、`manual_upload_handoff`(**不得**失效 `inventory_matching`) | + +旧 Artifact 不删除,标记为 `superseded`。前端禁止自行决定失效范围。 + +--- + +## 7. 客户端 API 约束(Phase 5 已接线) + +目标接口形态(实际前缀为 `/api/workspace/shipping-notice/...`): + +```http +GET /api/workspace/shipping-notice/process-executions/{execution_no} +GET /api/workspace/shipping-notice/process-executions/{execution_no}/gates +POST /api/workspace/shipping-notice/process-executions/{execution_no}/gates/{gate_code}/actions +GET /api/workspace/shipping-notice/process-executions/{execution_no}/audit-events +``` + +管理员诊断(`/api/admin/shipping-notice/process-executions...`)见 `backend/app/api/admin/shipping_process_gate.py`。 + +允许提交:`action_code`、`expected_gate_version`、`idempotency_key`(及动作所需的受控业务字段,如人工选择库存源)。 + +**客户端禁止提交:** + +- 起始阶段 / 起始门禁(`start_stage` / `start_gate`) +- 目标状态(`target_status`) +- Worker 名称或 Worker 实例标识 +- Python 工具名 / 内部 service 名 +- 任意下一节点或 DAG 跳转 +- 规则 SQL、表达式或未发布规则正文 + +403 / 409 均不得产生业务副作用;相同幂等键返回首次结果。 + +--- + +## 8. Finding 契约与原因唯一归属(Phase 1.5) + +### 8.1 Finding 标准结构 + +```json +{ + "finding_code": "optional_field_evidence_missing", + "owning_gate_code": "order_field_extraction", + "severity": "diagnostic", + "field_code": "ship_to_address", + "decision_id": 123, + "reason_code": "evidence_missing", + "user_visible": false, + "blocks_current_action": false +} +``` + +| 字段 | 规则 | +| --- | --- | +| `severity` | `blocking` 才可改变 Gate 状态;`diagnostic` 仅管理员诊断 | +| `owning_gate_code` | 必须属于 19 门禁之一;同一根因禁止多门禁平行用户阻断 | +| `user_visible` / `blocks_current_action` | 缺省由 severity 推导 | + +### 8.2 字段阻断资格 + +仅当 `required=true` **或** `auto_create_key_field=true` 时,字段质量问题可进入 `blocked_fields`。 +可选非关键字段(如 `ship_to_address`)证据不足 → diagnostic Finding,`blocked_fields=[]`。 + +### 8.3 原因唯一归属矩阵(摘录) + +完整矩阵见 `PROCESS_GATE_REASON_OWNING_GATE`。关键归属: + +| 原因 | owning_gate | +| --- | --- | +| Profile 未匹配 / 歧义 / 漂移 | `document_profile_routing` | +| 字段抽取技术失败 / 证据不足 | `order_field_extraction` | +| 必填字段缺失 | `field_completeness` | +| 客户未识别或不唯一 | `customer_resolution` | +| 自动冻结资格 / 客户范围 / 场景 / 紧急停止 | `order_freeze_readiness` | +| 无有效库存源 | `inventory_source_routing` | + +旧自动建单五门禁键经 `AUTO_BUILD_LEGACY_GATE_OWNING_MAP` 映射;用户端同一时间对自动冻结最多显示一次「自动建单策略尚未放行」。 + +--- + +## 9. 权限矩阵 + +| 主体 | 查看 | 恢复(retry / regenerate) | 人工决定(采用/保留/覆盖) | 审计详情 | +| --- | ---: | ---: | ---: | ---: | +| 任务所有者(owner) | 是 | 是 | 是 | 是 | +| 管理员(admin) | 是 | 是 | 是 | 是 | +| 其他授权人员 | 是 | 否(除非另行授权) | 否(除非另行授权) | 按权限 | +| Worker | 是(系统读) | 自动执行(非用户动作) | 否 | 写系统事件 | +| 未授权用户 | 否 | 否 | 否 | 否 | + +默认:非所有者只读;权限拒绝也写 `process_gate_permission_denied` 审计。 + +--- + +## 10. 审计事件与快照键 + +事件集合:`PROCESS_GATE_AUDIT_EVENT_TYPES`(含 `process_execution_created`、`process_gate_*` 等 16 项)。 + +快照白名单新增键:`gate_code`、`attempt_no`、`execution_no`、`next_action_code`、`blocking_reason_code`、`input_fingerprint`、`responsible_party`。禁止写入正文、规则 SQL、对象存储 URL、凭据。 + +--- + +## 11. 相关文档 + +- 技术手册(运行时 / Phase 0 库存路由恢复):[technical.md](./technical.md) +- 业务说明:[business.md](./business.md) +- 需求总览:`docs/demand.md` +- 技术架构:`docs/tec.md` +- 功能清单:`docs/funclist.md` +- 测试矩阵:`docs/test_plan_matrix.md` diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index 0808da9e..cad89a0e 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -3776,6 +3776,7 @@ watch( :summary="displayCase.process_gate" :can-handle="workbenchActionsExecutable" :navigation-context="reviewGateNavigationContext" + inventory-upload-mode="local" :field-labels="reviewFieldLabels" @refreshed="reloadLatestDraft" @refresh-needed="reloadLatestDraft" diff --git a/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts b/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts index 4816f378..e1c4386a 100644 --- a/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts +++ b/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts @@ -166,4 +166,52 @@ describe('ProcessGateRecoveryCard', () => { expect(wrapper.find('[data-testid="process-gate-recovery-targets"]').exists()).toBe(false); expect(wrapper.find('[data-testid="process-gate-recovery-primary"]').exists()).toBe(true); }); + + it('shows inventory upload as a secondary entry beside retrying inventory retrieval', async () => { + const wrapper = mount(ProcessGateRecoveryCard, { + props: { + summary: baseSummary({ + current_blocking_gate: { + ...baseSummary().current_blocking_gate!, + gate_code: 'inventory_preparation', + next_action_code: 'retry_inventory_preparation', + }, + next_action_code: 'retry_inventory_preparation', + allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'], + task_no: 'SN-TEST-001', + }), + canHandle: true, + }, + global: { plugins: [i18n] }, + }); + + const upload = wrapper.get('[data-testid="process-gate-inventory-upload"]'); + expect(upload.text()).toContain('上传库存文件'); + await upload.trigger('click'); + expect(wrapper.emitted('navigate')).toHaveLength(1); + }); + + it('opens local upload registration when requested by the order review workbench', async () => { + const wrapper = mount(ProcessGateRecoveryCard, { + props: { + summary: baseSummary({ + current_blocking_gate: { + ...baseSummary().current_blocking_gate!, + gate_code: 'inventory_preparation', + next_action_code: 'retry_inventory_preparation', + }, + next_action_code: 'retry_inventory_preparation', + allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'], + task_no: 'SN-TEST-001', + }), + canHandle: true, + inventoryUploadMode: 'local', + }, + global: { plugins: [i18n] }, + }); + + await wrapper.get('[data-testid="process-gate-inventory-upload"]').trigger('click'); + expect(wrapper.emitted('manualUpload')).toHaveLength(1); + expect(wrapper.emitted('navigate')).toBeUndefined(); + }); }); diff --git a/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue b/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue index e27d6f8e..de328bfd 100644 --- a/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue +++ b/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue @@ -22,6 +22,8 @@ const props = defineProps<{ summary: ShippingProcessGateUserSummary | null | undefined; canHandle: boolean; navigationContext?: ProcessGateNavigationContext; + /** 复核工作台直接打开人工上传登记;任务中心默认仍导航到任务详情。 */ + inventoryUploadMode?: 'navigate' | 'local'; /** 复核 Schema 的 field_code/field_id 到业务字段名映射。 */ fieldLabels?: Record; }>(); @@ -47,6 +49,11 @@ const showManualUploadAction = computed(() => ( String(blockingGate.value?.gate_code || '').trim().toLowerCase() === 'manual_upload_handoff' && nextActionCode.value === 'retry_freight_upload_rpa' )); +const showInventoryUploadAction = computed(() => ( + String(blockingGate.value?.gate_code || '').trim().toLowerCase() === 'inventory_preparation' + && nextActionCode.value === 'retry_inventory_preparation' + && (props.summary?.allowed_actions || []).includes('upload_inventory_file') +)); /** * 是否对业务用户展示「待处理事项」。 @@ -142,6 +149,19 @@ async function runPrimaryAction() { } } +async function runInventoryUpload() { + if (!props.summary || !props.canHandle || busy.value) return; + if (props.inventoryUploadMode === 'local') { + emit('manualUpload'); + return; + } + const result = await submitPrimaryAction(props.summary, { + actionCode: 'upload_inventory_file', + navigationContext: props.navigationContext, + }); + if (result.outcome === 'navigated') emit('navigate'); +} +