From 44c3bd0e80f82608ffe84a5f854894d4242ecd28 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 15 Sep 2026 10:29:59 +0800 Subject: [PATCH] =?UTF-8?q?fix(shipping-notice):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E9=98=B6=E6=AE=B5=E6=8A=95=E5=BD=B1=E4=B8=8E?= =?UTF-8?q?=E5=A4=8D=E6=A0=B8=E5=86=BB=E7=BB=93=E9=97=A8=E7=A6=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../shipping_notice/process_gate_executor.py | 12 +++- .../processing_projection_invariants.py | 22 +++++-- .../shipping_processing_projection.py | 24 ++++++- .../app/services/shipping_notice/ui_state.py | 37 ++++++++++- .../tests/test_shipping_notice_ui_state.py | 64 ++++++++++++++++++- ...t_shipping_processing_projection_stage4.py | 54 ++++++++++++++++ ...st_shipping_projection_gate_equivalence.py | 6 +- ...t_shipping_recheck_freeze_ot_extraction.py | 57 +++++++++++++++++ 8 files changed, 259 insertions(+), 17 deletions(-) create mode 100644 backend/tests/test_shipping_recheck_freeze_ot_extraction.py diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 55a1f473..096b034c 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -1788,7 +1788,12 @@ def _handle_recheck_freeze( gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """重新评估冻结就绪;有 Task+Extraction 时走标准 Gate 评估。""" + """ + 重新评估冻结就绪;有 OT + Extraction 时走标准 Gate 评估。 + + 核心逻辑:Execution.task_id → OT;Extraction 取自 OT.current_order_extraction_id + (禁止读不存在的 order_extraction_id)。 + """ from app.models import ShippingOrderExtraction, ShippingNotice from app.services.shipping_notice.freeze_readiness_service import evaluate_freeze_readiness_gate @@ -1813,8 +1818,9 @@ def _handle_recheck_freeze( } task = _resolve_order_task(execution) extraction = None - if task is not None and task.order_extraction_id: - extraction = ShippingOrderExtraction.query.get(int(task.order_extraction_id)) + extraction_id = getattr(task, 'current_order_extraction_id', None) if task is not None else None + if extraction_id is not None: + extraction = ShippingOrderExtraction.query.get(int(extraction_id)) if task is None or extraction is None: return { 'outcome': 'blocked_manual', diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 4bd1e701..c99030a2 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -6,7 +6,8 @@ services/shipping_notice/processing_projection_invariants.py 依赖:progress_audit_contract(15 阶 / 节点态 / 动作意图词典)、logging。 逻辑:由 shipping_processing_projection 与 order_task_stage_machine 共用;不读写数据库; Notice→(status,stage) 领域映射供写/读两侧;Extraction Run 完成 ≠ 全流程 completed; - Gate 要求复核时强制 waiting_review;download_excel 依赖 excel_ready; + Gate 要求复核时仅在未越过 waiting_review 时强制该阶(后半段不得拉回); + download_excel 依赖 excel_ready; stage_nodes 可表达 invalidated_from_stage 失效; Notice 号与建单前 stage 不一致时 fail-closed 清空履约动作并打结构化告警。 """ @@ -509,7 +510,8 @@ def reconcile_processing_projection_facts( 在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。 核心逻辑: - 1. Gate open_order_review → status/stage = waiting_review; + 1. Gate open_order_review → 仅当 stage 未越过 waiting_review 时强制 waiting_review; + 后半段(order_creating+)不得被拉回订单复核; 2. status=completed ⇒ stage=completed 且清空写动作与 current_gate; 3. stage=freight_uploading 时剔除 open_order_review; 4. Extraction 完成但 stage 未 completed 时不得保持 status=completed; @@ -598,12 +600,18 @@ def reconcile_processing_projection_facts( gate = None gate_action = None - # [BE-04] Gate 要求进入复核 ⇒ 进度必须停在 waiting_review(不得被 completed 误伤)。 + # [BE-04] Gate 要求进入复核 ⇒ 仅当处理阶段尚未越过 waiting_review 时停在该阶。 + # 已进入 order_creating / 库存 / Excel 等后半段时,不得被陈旧 open_order_review + # 把批次中心拉回「订单复核」(与上方 completed 分支同理)。 if gate_action == 'open_order_review' and status != 'completed': - status = 'waiting_review' if status not in {'failed', 'cancelled'} else status - stage = 'waiting_review' - if isinstance(gate, dict): - gate = {**gate, 'next_action_code': 'open_order_review'} + if stage_idx is None or stage_idx <= waiting_idx: + status = 'waiting_review' if status not in {'failed', 'cancelled'} else status + stage = 'waiting_review' + if isinstance(gate, dict): + gate = {**gate, 'next_action_code': 'open_order_review'} + else: + gate = None + gate_action = None if stage == 'freight_uploading' and gate_action == 'open_order_review': gate = None diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 1001f1c2..a80932ba 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -1501,7 +1501,8 @@ def _order_task_current_gate( 核心逻辑:优先开放 Review Case 上的真实 ProcessExecution;其次 OT 活跃 Execution (含尚未创建 Notice 的履约门禁,如库存满足性);无 Execution 时回退 Run·OT - 失败/waiting_review 合成摘要;处理中不造假门禁。 + 失败/waiting_review 合成摘要——但 OT.stage 已越过 waiting_review 时禁止再合成 + open_order_review;处理中不造假门禁。 Args: run: Processing Run。 @@ -1567,6 +1568,17 @@ def _order_task_current_gate( # 外层单独透传完整摘要;current_gate 保持轻量展示形状。 '_process_gate_summary': summary, } + # 开放 Case 无 Execution:仅当 OT 仍停在复核及以前才合成 open_order_review。 + # OT.stage 已进入 order_creating+ 时禁止伪造,避免 BE-04 拉回「订单复核」。 + if order_task is not None: + from app.services.shipping_notice.processing_projection_invariants import ( + shipping_processing_stage_index, + ) + ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() + ot_stage_idx = shipping_processing_stage_index(ot_stage) + waiting_idx = shipping_processing_stage_index('waiting_review') or 8 + if ot_stage_idx is not None and ot_stage_idx > waiting_idx: + return None return { 'gate_code': 'order_freeze_readiness', 'status': 'blocked', @@ -1607,6 +1619,16 @@ def _order_task_current_gate( 'attempt_no': 0, } if status in {'review_required', 'waiting_review', 'pending_review'}: + # OT.status 可能仍停在 waiting_review,但 stage 已推进到 order_creating+。 + # 禁止再合成 open_order_review,否则 BE-04 会把五阶段拉回「订单复核」。 + from app.services.shipping_notice.processing_projection_invariants import ( + shipping_processing_stage_index, + ) + ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() + ot_stage_idx = shipping_processing_stage_index(ot_stage) + waiting_idx = shipping_processing_stage_index('waiting_review') or 8 + if ot_stage_idx is not None and ot_stage_idx > waiting_idx: + return None return { 'gate_code': 'order_freeze_readiness', 'status': 'blocked', diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 38b755b3..aa9ace77 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -9,6 +9,8 @@ services/shipping_notice/ui_state.py order_review_workbench_projection、inventory_source_repository(preparation.source_options)。 逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode); Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id); + 五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列), + 禁止仅靠 Gate 兜底把 order_freeze 误映射为订单复核; stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT), 行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源); 短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line; @@ -106,10 +108,23 @@ _PAUSE_REASON_BY_POSITION: dict[str, tuple[str, str]] = { def _task_lifecycle( *, task: ShippingNotice, position: str | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: - """以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。""" + """以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。 + + 核心逻辑:``processing_stage`` 与批次/工作台同源——优先实体 ``stage``, + Notice 无 stage 列时经 ``order_task_id`` 读 OT.stage;再用正式 Gate 做 + **仅向前**抬升(与 reconcile BE-08 / sync_order_task_stage_for_notice 同表)。 + ``order_freeze_readiness`` 不在抬升表中,故不能把 OT.stage=order_creating + 压回「订单复核」。 + """ del position # 生命周期不再由位置码推导。 gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate') from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.processing_projection_invariants import ( + shipping_processing_stage_index, + ) + from app.services.shipping_notice.order_task_stage_machine import ( + _PROCESS_GATE_TO_PROCESSING_STAGE, + ) # 有正式 Gate 或已验证上传时才开放五阶段入口;否则保持 unclassified(禁止旧 CP 冒充)。 has_formal = bool( @@ -120,6 +135,24 @@ def _task_lifecycle( or process_gate.get('current_gate') ) ) + # [STEP 1] Notice 无 stage 列;进度权威在 OT。 + processing_stage = str(getattr(task, 'stage', None) or '').strip() or None + if not processing_stage: + order_task = _resolve_order_task_for_gate_lookup(task) + if order_task is not None: + processing_stage = str(getattr(order_task, 'stage', None) or '').strip() or None + # [STEP 2] Gate→15 阶仅向前抬升;禁止 freeze 等建单前 Gate 回拉后半段。 + gate_code = '' + if isinstance(gate, dict): + gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() + if not gate_code and isinstance(process_gate, dict): + gate_code = str(process_gate.get('current_gate_code') or '').strip().lower() + gate_as_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code) + if gate_as_stage: + stage_idx = shipping_processing_stage_index(processing_stage) + gate_idx = shipping_processing_stage_index(gate_as_stage) + if stage_idx is None or (gate_idx is not None and gate_idx >= stage_idx): + processing_stage = gate_as_stage return project_lifecycle( current_gate=gate if isinstance(gate, dict) else None, blocking_reason=( @@ -129,7 +162,7 @@ def _task_lifecycle( ), has_candidate_context=has_formal or has_verified_upload_success(task), verified_upload_success=has_verified_upload_success(task), - processing_stage=getattr(task, 'stage', None), + processing_stage=processing_stage, ) diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index 0fb1eed8..92f621db 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -167,6 +167,67 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: assert "stage_context" in detailed_state +def test_build_task_ui_state_notice_uses_ot_stage_not_freeze_gate_lifecycle(app) -> None: + """ + Notice 路径必须读 OT.stage 做五阶段,禁止仅靠 order_freeze→order_review 兜底。 + + 断言意图:OT.stage=order_creating 时,任务中心/详情与批次同为 fulfillment_prep, + 不得因 Notice 无 stage 列 + freeze Gate 显示「订单复核」。 + """ + with app.app_context(): + from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + ) + from app.services.shipping_notice.ui_state import ( + _process_gate_user_summary_for_task, + _task_lifecycle, + ) + + user = User( + username='ui-notice-ot-stage', + email='ui-notice-ot-stage@example.com', + password_hash='x', + ) + db.session.add(user) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-UI-NOTICE-OT-STAGE', + user_id=user.id, + source_type='direct_pdf', + status='waiting_review', + stage='order_creating', + progress_version=1, + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-UI-NOTICE-OT-STAGE', + user_id=user.id, + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() + execution = ensure_execution_for_workflow_version( + task_id=int(order_task.id), actor_type='system', + ) + execution.status = 'blocked' + execution.current_gate_code = 'order_freeze_readiness' + order_task.active_process_execution_id = int(execution.id) + # ensure_execution 在已有 Notice 时会 sync_order_task_stage_for_notice, + # 可能把 stage 写成 waiting_review;本用例要验证「已写入的 order_creating」权威。 + order_task.stage = 'order_creating' + order_task.status = 'waiting_review' + db.session.commit() + + process_gate = _process_gate_user_summary_for_task(notice) + lifecycle = _task_lifecycle(task=notice, position=None, process_gate=process_gate) + + assert lifecycle['lifecycle_stage'] == 'fulfillment_prep' + assert lifecycle['lifecycle_authority'] == 'processing_stage' + assert lifecycle['lifecycle_stage'] != 'order_review' + + def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: """无正式 Gate 时位置不能再推导五阶段或任何可写 UI 动作。""" with app.app_context(): @@ -245,7 +306,8 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None: state = build_task_ui_state(task) assert state['lifecycle_stage'] == 'fulfillment_prep' - assert state['lifecycle_authority'] == 'process_gate' + # Notice/OT 无合法 stage 时由 Gate 抬升为 inventory_matching,权威记为 processing_stage。 + assert state['lifecycle_authority'] == 'processing_stage' assert state['stage']['code'] == 'fulfillment_prep' assert state['current_step']['code'] == 'fulfillment_prep' assert [entry['state'] for entry in state['lifecycle_entries']] == [ diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 54cb3462..7027e5ce 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -586,6 +586,60 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None assert str(primary.get('code') or '') != 'open_order_review' +def test_order_creating_ot_not_pulled_back_to_order_review_by_stale_open_order_review(app) -> None: + """ + OT.stage 已 order_creating 时,不得因 status=waiting_review 合成 open_order_review + 把批次五阶段拉回「订单复核」。 + + 断言意图:工作台按 OT.stage→通知准备;批次须同源,禁止再显示订单复核。 + """ + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + from app.services.shipping_notice.shipping_processing_projection import ( + get_shipping_processing_work_item, + ) + + user, agent, session, intake, _document = _seed_run_input(suffix='OT-STAGE-NO-REWIND') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + task = ShippingOrderTask( + task_no='OT-STAGE-NO-REWIND', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=run.id, + owner_agent_id=int(agent.id), + candidate_id=None, + status='waiting_review', + stage='order_creating', + progress_version=2, + ) + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-OT-STAGE-NO-REWIND', + task_id=int(task.id), + status='blocked', + current_gate_code='order_freeze_readiness', + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + task.active_process_execution_id = int(execution.id) + run.user_task_no = task.task_no + db.session.commit() + + item = get_shipping_processing_work_item( + user_id=user.id, + work_item_type='order_task', + work_item_no=task.task_no, + ) + + # 阶段文案治本:不得被 BE-04 / status 启发式拉回 order_review。 + assert item['stage'] == 'order_creating' + assert item['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert item['ui_state']['lifecycle_stage'] != 'order_review' + + def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None: """历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。""" with app.app_context(): diff --git a/backend/tests/test_shipping_projection_gate_equivalence.py b/backend/tests/test_shipping_projection_gate_equivalence.py index 6dcd4c61..00777dfd 100644 --- a/backend/tests/test_shipping_projection_gate_equivalence.py +++ b/backend/tests/test_shipping_projection_gate_equivalence.py @@ -405,9 +405,9 @@ def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario): """五阶段门禁→生命周期 唯一映射必须正确(B 侧,真实 Notice 路径)。 `LIFECYCLE_STAGE_BY_GATE`(lifecycle_projection.py:30)是正式 Gate→五阶段业务码的唯一表。 - B(build_task_ui_state on Notice,processing_stage=None)经 project_lifecycle 走 Gate 兜底, - 必须按该表落到正确业务码。**freight_upload_rpa / manual_upload_handoff 必须属于 freight_upload** - —— 这是用户确认的契约(方案 A)。 + B(build_task_ui_state on Notice)经 OT.stage + Gate 仅向前抬升后调用 project_lifecycle; + 履约 Gate(inventory_* / freight_*)须落到正确业务码。**freight_upload_rpa / + manual_upload_handoff 必须属于 freight_upload** —— 这是用户确认的契约(方案 A)。 """ gate_code, expected_stage = scenario with app.app_context(): diff --git a/backend/tests/test_shipping_recheck_freeze_ot_extraction.py b/backend/tests/test_shipping_recheck_freeze_ot_extraction.py new file mode 100644 index 00000000..e56135b8 --- /dev/null +++ b/backend/tests/test_shipping_recheck_freeze_ot_extraction.py @@ -0,0 +1,57 @@ +""" +tests/test_shipping_recheck_freeze_ot_extraction.py + +用途:锁定冻结就绪重检从 OT 读 current_order_extraction_id,禁止 AttributeError。 +依赖:process_gate_executor._handle_recheck_freeze、unittest.mock。 +逻辑:模拟 OT(仅有 current_order_extraction_id)触发 recheck;断言能取到 Extraction 并调用评估。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import patch + +from app.services.shipping_notice import process_gate_executor as executor + + +def test_handle_recheck_freeze_uses_current_order_extraction_id(): + """ + OT 无 order_extraction_id 字段;必须用 current_order_extraction_id,否则 Job 直接 failed。 + + 断言意图:复现测试环境 AttributeError,修复后应进入评估而非 missing 短路。 + """ + task = SimpleNamespace(id=7, current_order_extraction_id=42) + assert not hasattr(task, 'order_extraction_id') + extraction = SimpleNamespace(id=42) + eval_calls: list[dict] = [] + + def _fake_eval(**kwargs): + eval_calls.append(kwargs) + return { + 'passed': False, + 'blocking_reason_code': 'freeze_not_ready', + 'issues': [], + 'findings': [], + } + + with ( + patch.object(executor, '_resolve_order_task', return_value=task), + patch('app.models.ShippingOrderExtraction') as extraction_model, + patch( + 'app.services.shipping_notice.freeze_readiness_service.evaluate_freeze_readiness_gate', + side_effect=_fake_eval, + ), + ): + extraction_model.query.get.return_value = extraction + result = executor._handle_recheck_freeze( + execution=SimpleNamespace(task_id=7), + gate=SimpleNamespace(), + payload={'freeze_mode': 'manual'}, + ) + + assert result['outcome'] == 'blocked_manual' + assert result.get('output_snapshot', {}).get('missing') is not True + extraction_model.query.get.assert_called_once_with(42) + assert len(eval_calls) == 1 + assert eval_calls[0]['task'] is task + assert eval_calls[0]['extraction'] is extraction