""" backend/tests/test_shipping_processing_projection_invariants.py 用途:验收统一投影 status/stage/gate/action 不变量与 15 阶节点事实。 依赖:processing_projection_invariants、pytest。 逻辑:不连库;断言 Gate 复核强制 waiting_review、Run completed 非全流程完成、 动作契约映射与 stage_nodes 权威输出。 """ from __future__ import annotations from app.services.shipping_notice.processing_projection_invariants import ( apply_user_projection_fields, build_stage_nodes, derivation_status_for_extraction_run, normalize_action_code, reconcile_processing_projection_facts, ) def test_run_completed_is_not_workflow_completed_before_review(): """识别 Run completed + candidate_creating 不得映射为全流程 completed。""" assert derivation_status_for_extraction_run('completed', stage='candidate_creating') == 'processing' assert derivation_status_for_extraction_run('completed', stage='waiting_review') == 'waiting_review' assert derivation_status_for_extraction_run('completed', stage='completed') == 'completed' def test_open_order_review_gate_forces_waiting_review_stage(): """Gate 要求进入复核时,stage/status 必须对齐 waiting_review。""" payload = reconcile_processing_projection_facts({ 'status': 'processing', 'stage': 'candidate_creating', 'source_type': 'direct_pdf', 'current_gate': { 'gate_code': 'order_freeze_readiness', 'status': 'blocked', 'next_action_code': 'open_order_review', 'blocking_reason_code': 'waiting_review', 'attempt_no': 0, }, 'available_actions': ['view_details', 'open_order_review'], }) assert payload['status'] == 'waiting_review' assert payload['stage'] == 'waiting_review' assert payload['available_actions'][0] == 'open_order_review' current = next(n for n in payload['stage_nodes'] if n['stage'] == 'waiting_review') assert current['status'] == 'blocked' assert next(n for n in payload['stage_nodes'] if n['stage'] == 'email_parsing')['status'] == 'skipped' def test_completed_clears_write_actions_and_gate(): """status=completed 时 stage 必须 completed,且不得残留写操作。""" payload = reconcile_processing_projection_facts({ 'status': 'completed', 'stage': 'excel_generating', 'source_type': 'eml', 'current_gate': { 'gate_code': 'x', 'status': 'blocked', 'next_action_code': 'open_order_review', }, 'available_actions': ['open_order_review', 'retry'], }) assert payload['stage'] == 'completed' assert payload['current_gate'] is None assert 'open_order_review' not in payload['available_actions'] assert payload['available_actions'] == ['view_result'] def test_projection_fact_read_failure_is_fail_closed(): """关键事实读取失败时必须进入人工诊断态,不得静默返回旧动作。""" payload = reconcile_processing_projection_facts({ 'status': 'running', 'stage': 'onhand_preparation', 'source_type': 'eml', 'projection_data_inconsistent': True, 'available_actions': ['retry_onhand_preparation'], }) assert payload['status'] == 'waiting_human' assert 'retryable' not in payload assert payload['primary_action'] is None assert payload['available_actions'] == [] assert payload['blocking_reason']['code'] == 'projection_data_inconsistent' def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason(): """库存缺口 Gate 不能只保留内部码而遗漏批次/工作台的统一阻塞原因。""" payload = apply_user_projection_fields(reconcile_processing_projection_facts({ 'status': 'blocked', 'stage': 'onhand_matching', 'source_type': 'eml', 'current_gate': { 'gate_code': 'onhand_sufficiency', 'status': 'blocked_manual', 'next_action_code': 'open_shortage_review', 'blocking_reason_code': 'inventory_shortage_review_required', }, 'available_actions': ['open_shortage_review'], })) assert payload['user_status'] == 'waiting_human' assert payload['blocking_reason'] == { 'code': 'inventory_shortage_review_required', 'i18n_key': 'workspace.shippingNotice.processGate.reasons.inventory_shortage_review_required', 'details': {}, } def test_normalize_unknown_action_codes(): """未知 / 别名动作码映射到契约或丢弃。""" assert normalize_action_code('retry_failed_documents') == 'retry_failed_documents' assert normalize_action_code('open_fulfillment') == 'view_result' assert normalize_action_code('not_a_real_action') is None def test_stage_nodes_length_is_fifteen(): """stage_nodes 恒为 15 阶权威事实。""" nodes = build_stage_nodes( stage='onhand_matching', status='automating', source_type='eml', ) assert len(nodes) == 15 assert nodes[11]['stage'] == 'onhand_matching' assert nodes[11]['status'] == 'running' assert nodes[10]['status'] == 'passed' assert nodes[12]['status'] == 'pending' def test_invalidated_from_stage_marks_nodes_pending(): """BE-01:改单失效起点及之后(当前游标之前)不得再标 passed。""" nodes = build_stage_nodes( stage='onhand_matching', status='processing', source_type='eml', invalidated_from_stage='onhand_source_resolving', ) # inventory_source_resolving 在当前游标之前且位于失效起点,应标 pending。 inv_node = next(n for n in nodes if n['stage'] == 'onhand_source_resolving') assert inv_node['status'] == 'pending' waiting = next(n for n in nodes if n['stage'] == 'waiting_review') assert waiting['status'] == 'pending' # 失效起点之前仍可为 passed。 dup_node = next(n for n in nodes if n['stage'] == 'duplicate_checking') assert dup_node['status'] == 'passed' current = next(n for n in nodes if n['stage'] == 'onhand_matching') assert current['status'] == 'running' def test_download_excel_requires_excel_ready_fact(): """BE-04:仅 stage=excel_generating 不得推出 download_excel。""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) without_ready = derive_available_actions( status='blocked', stage='excel_generating', gate=None, excel_ready=False, ) assert 'download_excel' not in without_ready assert 'regenerate_excel' in without_ready with_ready = derive_available_actions( status='blocked', stage='freight_uploading', gate={ 'gate_code': 'manual_upload_handoff', 'next_action_code': 'wait_manual_upload', }, excel_ready=True, ) assert 'download_excel' in with_ready assert 'open_manual_upload' in with_ready assert 'regenerate_excel' not in with_ready def test_artifact_gate_overrides_stale_inventory_stage_and_action(): """Gate 18 阻断时不得继续展示旧库存匹配阶段或 match_inventory。""" payload = reconcile_processing_projection_facts({ 'status': 'automating', 'stage': 'onhand_matching', 'source_type': 'order_task', 'shipping_notice_no': 'SN-1', 'current_gate': { 'gate_code': 'artifact_generation', 'status': 'blocked_retryable', 'next_action_code': 'regenerate_excel_artifact', 'blocking_reason_code': 'artifact_generation_failed', }, 'available_actions': ['match_inventory'], }) assert payload['status'] == 'blocked' assert payload['stage'] == 'excel_generating' assert payload['stage_label_key'] == 'excel_generating' assert payload['current_gate']['next_action_code'] == 'regenerate_excel_artifact' assert payload['available_actions'] == ['regenerate_excel'] def test_artifact_gate_primary_action_uses_gate_not_legacy_stage(): """用户态主动作必须投影为重新生成 Excel。""" payload = apply_user_projection_fields({ 'status': 'blocked', 'stage': 'excel_generating', 'source_type': 'order_task', 'shipping_notice_no': 'SN-1', 'current_gate': { 'gate_code': 'artifact_generation', 'status': 'blocked_retryable', 'next_action_code': 'regenerate_excel_artifact', 'blocking_reason_code': 'artifact_generation_failed', }, 'available_actions': ['regenerate_excel'], }) assert payload['user_status'] == 'retryable' assert payload['primary_action']['code'] == 'regenerate_excel' def test_map_notice_to_processing_status_stage_domain_mapping(): """BE-05:Notice 履约态映射属领域层,写/读共用。""" from types import SimpleNamespace from app.services.shipping_notice.processing_projection_invariants import ( map_notice_to_processing_status_stage, ) # [BE-05] Notice 履约态由领域事实(step / 上传 Attempt / 导出 Artifact)派生, # 不再读取已迁移下线的 Notice.upload_status / export_file_path 聚合字段。无 Attempt # 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。 uploaded = SimpleNamespace( id=None, current_step='freight_uploading', upload_status='uploaded', export_file_path=None, ) # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。 assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading') waiting = SimpleNamespace( current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx', ) assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading') matching = SimpleNamespace( current_step='onhand_matching', upload_status='', match_status='matching', export_file_path=None, ) assert map_notice_to_processing_status_stage(matching) == ('automating', 'onhand_matching') def test_map_notice_unknown_status_fail_closed(): """BE-03: unknown Notice status must fail-closed, not order_creating.""" from types import SimpleNamespace from app.services.shipping_notice.processing_projection_invariants import ( map_notice_to_processing_status_stage, ) unknown = SimpleNamespace( current_step='', upload_status='', export_file_path=None, ) assert map_notice_to_processing_status_stage(unknown) == ('blocked', 'waiting_review') def test_derive_available_actions_without_gate_fails_closed(): """BE-04: no Gate and no object authorization must not invent an action.""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) actions = derive_available_actions( status='blocked', stage='onhand_source_resolving', gate={ 'gate_code': 'inventory_source', 'status': 'blocked', 'next_action_code': 'confirm_inventory_source', }, excel_ready=False, ) assert actions == [] def test_derive_available_actions_failed_without_gate_does_not_add_retry(): """BE-04: failed status alone cannot authorize a generic retry.""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) actions = derive_available_actions( status='failed', stage='document_parsing', gate=None, excel_ready=False, ) assert actions == ['view_result'] def test_retryable_projection_uses_technical_failure_reason_mapping(): """重试兜底原因必须生成可展示的技术失败 i18n 键,而不能抛 KeyError。""" payload = apply_user_projection_fields({ 'status': 'processing', 'stage': 'onhand_preparation', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_preparation', 'blocking_reason_code': 'technical_failure_present', }, 'available_actions': ['retry'], }) assert payload['user_status'] == 'retryable' assert payload['blocking_reason'] == { 'code': 'technical_failure_present', 'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_failure_present', 'details': {}, } def test_inventory_snapshot_missing_projects_retryable_inventory_action(): """库存快照缺失属于可恢复技术阻断,用户态必须保留重试动作。""" payload = apply_user_projection_fields({ 'status': 'blocked', 'stage': 'onhand_preparation', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_preparation', 'blocking_reason_code': 'inventory_snapshot_missing', }, 'retry_decision': { 'retryable': True, 'reason_code': 'inventory_snapshot_missing', }, 'available_actions': ['retry_onhand_preparation'], }) assert payload['user_status'] == 'retryable' assert 'retryable' not in payload # 主动作必须保留 Gate 原始码,前端才能提交到正确的库存准备执行器。 assert payload['primary_action'] == { 'code': 'retry_onhand_preparation', 'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', 'parameters': {}, } def test_formal_blocked_gate_overrides_stale_preparation_running_state(): """正式 Gate 已阻断时,旧库存准备 waiting 不能把用户态降回系统处理中。""" payload = apply_user_projection_fields({ 'status': 'processing', 'stage': 'onhand_preparation', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_preparation', 'blocking_reason_code': 'technical_failure_present', }, 'available_actions': ['retry_onhand_preparation'], }) # 关键断言:Gate 是业务裁决真相;Preparation Attempt 只能作为过程明细。 assert payload['user_status'] == 'retryable' assert payload['primary_action']['code'] == 'retry_onhand_preparation' def test_retryable_projection_exposes_technical_failure_reason_without_retry_decision(): """AutoProgress 超时未生成 Retry Decision 时,工作项读取仍必须返回可翻译原因。""" payload = apply_user_projection_fields({ 'status': 'blocked', 'stage': 'onhand_preparation', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_retryable', 'blocking_reason_code': 'technical_failure_present', }, 'available_actions': [], }) assert payload['user_status'] == 'retryable' assert payload['blocking_reason'] == { 'code': 'technical_failure_present', 'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_failure_present', 'details': {}, } def test_formal_inventory_matching_retry_projects_business_i18n_key(): """正式 OT 的库存重试不得让页面回退展示内部 action code。""" payload = apply_user_projection_fields({ 'status': 'blocked', 'stage': 'onhand_matching', 'source_type': 'order_task', 'shipping_notice_no': 'SN-RETRY-MATCH', 'current_gate': { 'gate_code': 'onhand_matching', 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_matching', 'blocking_reason_code': 'inventory_match_failed', }, 'available_actions': ['retry_onhand_matching'], }) assert payload['primary_action'] == { 'code': 'retry_onhand_matching', 'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', 'parameters': {}, } def test_formal_inventory_gate_overrides_stale_waiting_review_compatibility_fields(): """正式库存 Gate 必须覆盖历史 OT 的 waiting_review,防止阶段回退。""" payload = reconcile_processing_projection_facts({ 'work_item_no': 'OT-GATE-OVERRIDE', 'shipping_notice_no': 'SN-GATE-OVERRIDE', 'status': 'waiting_review', 'stage': 'waiting_review', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_manual', 'next_action_code': 'retry_onhand_preparation', 'blocking_reason_code': 'onhand_rpa_timeout', }, 'available_actions': ['open_order_review'], }) assert payload['status'] == 'waiting_review' assert payload['stage'] == 'onhand_fetching' assert 'projection_inconsistency_code' not in payload assert payload['available_actions'] == ['retry_onhand_preparation'] def test_inventory_file_missing_exposes_a_user_facing_reason_i18n_key(): """库存文件缺失需携带可翻译原因,批次中心不得回显内部原因码。""" payload = apply_user_projection_fields({ 'status': 'blocked', 'stage': 'onhand_preparation', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_manual', 'blocking_reason_code': 'inventory_file_missing', }, 'available_actions': [], }) assert payload['blocking_reason'] == { 'code': 'inventory_file_missing', 'i18n_key': 'chat.shippingProcessing.reasonCode.inventory_file_missing', 'details': {}, } def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action(): """库存文件缺失必须保留 Gate 重试,不得降级为线外上传或空按钮。""" payload = apply_user_projection_fields({ 'status': 'processing', 'stage': 'onhand_fetching', 'source_type': 'order_task', 'shipping_notice_no': 'SN-1', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'blocked_manual', 'next_action_code': 'retry_onhand_preparation', 'blocking_reason_code': 'inventory_file_empty', }, 'available_actions': ['retry_onhand_preparation'], }) assert payload['user_status'] == 'waiting_human' assert payload['primary_action'] == { 'code': 'retry_onhand_preparation', 'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', 'parameters': {}, } assert payload['available_actions'] == ['retry_onhand_preparation'] def test_waiting_human_reconcile_action_uses_gate_action(): """人工阻断的统一对账动作必须由正式 Gate 明确下发。""" payload = apply_user_projection_fields({ 'status': 'waiting_review', 'stage': 'onhand_matching', 'current_gate': { 'gate_code': 'inventory_candidates_calculated', 'status': 'blocked', 'blocking_reason_code': 'inventory_candidates_required', 'next_action_code': 'reconcile_and_progress', }, 'available_actions': ['view_details'], }) # 关键断言:只能选中 Gate 明示的统一恢复入口。 assert payload['user_status'] == 'waiting_human' assert payload['primary_action']['code'] == 'reconcile_and_progress' def test_waiting_human_without_reconcile_action_has_no_false_primary_action(): """未知人工阻断未提供统一对账动作时,不得凭空生成可执行主动作。""" payload = apply_user_projection_fields({ 'status': 'waiting_review', 'stage': 'onhand_matching', 'current_gate': { 'gate_code': 'inventory_candidates_calculated', 'status': 'blocked', 'blocking_reason_code': 'inventory_candidates_required', }, 'available_actions': ['view_details'], }) # 关键断言:没有正式动作事实时保持 None,避免前端展示无效恢复按钮。 assert payload['user_status'] == 'waiting_human' assert payload['primary_action'] is None def test_in_flight_gate_projects_running_not_waiting_human(): """RPA 在途(Gate waiting_external)必须投影 running,不得误报待人工。 Notice 生成前 OT.status 停留在建单前的 waiting_review;若在途期被投影成 waiting_human,前端会把任务当终态停止投影轮询,RPA 回调完成将永远无法被 感知(库存匹配表格冻结在「库存文件未准备」)。与门禁契约 GATE_STATUS_TO_USER_STATUS['waiting_external']=='running' 对齐。 """ payload = apply_user_projection_fields({ 'status': 'waiting_review', 'stage': 'onhand_preparation', 'source_type': 'order_task', 'current_gate': { 'gate_code': 'onhand_preparation', 'status': 'waiting_external', }, 'available_actions': [], }) # 关键断言:Gate 在途 = 系统处理中;待人工只属于 blocked_manual 等人工阻断。 assert payload['user_status'] == 'running' def test_apply_user_projection_fields_fail_closes_inconsistent_projection(): """事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。""" payload = apply_user_projection_fields({ 'status': 'running', 'stage': 'onhand_preparation', 'current_gate': {'gate_code': 'onhand_preparation', 'status': 'running'}, 'available_actions': ['retry_onhand_preparation'], 'projection_data_inconsistent': True, }) assert payload['user_status'] == 'waiting_human' assert 'retryable' not in payload assert payload['primary_action'] is None assert payload['available_actions'] == [] assert payload['blocking_reason']['code'] == 'projection_data_inconsistent' def test_inventory_milestones_are_projection_facts_not_runtime_gate_codes(): """四个 MVP 库存里程碑必须由正式 Gate 和结构化事实派生,不能创建 APX Gate。""" payload = apply_user_projection_fields({ 'status': 'automating', 'stage': 'onhand_matching', 'current_gate': {'gate_code': 'onhand_matching', 'status': 'running'}, 'available_actions': [], }) assert payload['facts']['inventory_milestones'] == { 'candidates_calculated': 'completed', 'candidates_frozen': 'completed', 'snapshots_ready': 'completed', 'matched': 'pending', }