""" tests/test_shipping_process_gate_contract.py 用途:锁定全门禁中断恢复 Phase 1/1.5 契约与依赖图完整性(编码、动作、失效范围、原因归属)。 依赖:process_gate_contract、process_gate_dependency。 逻辑:调用 assert_*_integrity;断言 20 个唯一门禁(含 freight_upload_rpa)、 原因码唯一 owning_gate、字段阻断资格与 Excel 仅重生失效范围。 """ from __future__ import annotations from app.services.shipping_notice.process_gate_contract import ( AUTO_BUILD_LEGACY_GATE_OWNING_MAP, PROCESS_GATE_CODES, PROCESS_GATE_CODE_SET, PROCESS_GATE_DEFINITIONS, PROCESS_GATE_REASON_OWNING_GATE, assert_process_gate_contract_integrity, action_presentation, field_quality_may_block, owning_gate_for_reason, primary_next_action_for_gate, ) from app.services.shipping_notice.process_gate_dependency import ( PROCESS_GATE_INVALIDATION_RULES, assert_process_gate_dependency_integrity, compute_invalidated_gates, ) def test_process_gate_contract_integrity(): """ 校验门禁契约无重复编码、序号连续且动作/状态闭环。 核心逻辑:直接调用契约自检;再断言恰好 20 个唯一 gate_code。 """ # [STEP 1] 契约自检(重复码 / 序号 / 动作归属) assert_process_gate_contract_integrity() # [STEP 2] 冻结规模:20 门禁(含 freight_upload_rpa)且集合与有序列表一致 assert len(PROCESS_GATE_DEFINITIONS) == 20 assert len(PROCESS_GATE_CODES) == 20 assert len(PROCESS_GATE_CODE_SET) == 20 assert set(PROCESS_GATE_CODES) == PROCESS_GATE_CODE_SET assert 'freight_upload_rpa' in PROCESS_GATE_CODE_SET assert owning_gate_for_reason('upload_rpa_pending') == 'freight_upload_rpa' assert owning_gate_for_reason('manual_upload_pending') == 'manual_upload_handoff' def test_inventory_source_routing_primary_retry_action(): """ 库存源路由在 blocked_retryable 时主恢复动作必须为按最新规则重试。 核心逻辑:primary_next_action_for_gate 禁止前端本地推导。 """ action = primary_next_action_for_gate( gate_code='inventory_source_routing', status='blocked_retryable', ) assert action == 'retry_with_latest_rules' def test_inventory_sufficiency_actions_keep_business_specific_labels(): """库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。""" assert action_presentation('open_shortage_review') == { 'code': 'open_shortage_review', 'label_key': 'workspace.shippingNotice.processGate.actionCodes.open_shortage_review', 'kind': 'current_gate', 'dispatch': 'navigation', } assert action_presentation('retry_inventory_from_matching') == { 'code': 'retry_inventory_from_matching', 'label_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_from_matching', 'kind': 'recovery', 'dispatch': 'mutation', } def test_process_gate_reason_ownership_is_unique(): """ 每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。 核心逻辑:契约自检 + 显式抽查自动冻结与字段完整性归属。 """ assert_process_gate_contract_integrity() assert owning_gate_for_reason('profile_manual_confirmation_required') == 'order_freeze_readiness' assert owning_gate_for_reason('required_field_missing') == 'field_completeness' assert owning_gate_for_reason('customer_unresolved') == 'customer_resolution' assert owning_gate_for_reason('evidence_missing') == 'order_field_extraction' # 旧五门禁键不得再各自成为用户阻断真相。 assert AUTO_BUILD_LEGACY_GATE_OWNING_MAP['quality_gate_passed'] == 'order_freeze_readiness' assert AUTO_BUILD_LEGACY_GATE_OWNING_MAP['approved_template'] == 'order_freeze_readiness' assert len(PROCESS_GATE_REASON_OWNING_GATE) == len(set(PROCESS_GATE_REASON_OWNING_GATE.keys())) def test_field_quality_block_eligibility(): """仅 required 或 auto_create_key_field 可因字段质量阻断。""" assert field_quality_may_block(required=True, auto_create_key_field=False) is True assert field_quality_may_block(required=False, auto_create_key_field=True) is True assert field_quality_may_block(required=False, auto_create_key_field=False) is False def test_projection_marks_apx_gate_as_readonly_without_executable_actions(app, monkeypatch): """APX 历史 Gate 只可审计展示,不能再投影为可恢复业务 Gate。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection gate = SimpleNamespace( id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='pending', evaluation_version=1, input_fingerprint=None, blocking_reason_code=None, blocking_reason_json=None, recommendation_json=None, effective_result_json={}, findings_json=None, next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None, ) monkeypatch.setattr( projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False, ) payload = projection.serialize_process_gate(gate, include_diagnostics=False) assert payload['gate_code'] == 'inventory_candidates_calculated' assert payload['legacy_readonly'] is True assert payload['allowed_actions'] == [] assert payload['recovery_targets'] == [] assert len(PROCESS_GATE_DEFINITIONS) == 20 def test_user_gate_summary_marks_apx_execution_readonly(app, monkeypatch): """APX Execution 不能向用户下发主动作或恢复目标。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection execution = SimpleNamespace( id=1, execution_no='APX-1', status='blocked', current_gate_code='inventory_candidates_calculated', last_passed_gate_code=None, primary_next_action_code=None, responsible_party='system', lock_version=1, review_case_id=None, task_id=1, updated_at=None, ) gate = SimpleNamespace( id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='blocked_retryable', evaluation_version=1, input_fingerprint=None, blocking_reason_code='inventory_candidates_required', blocking_reason_json=None, recommendation_json=None, effective_result_json={}, next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None, ) query = projection.ShippingProcessGate.query monkeypatch.setattr(query, 'filter_by', lambda **_kwargs: query) monkeypatch.setattr(query, 'order_by', lambda *_args: query) monkeypatch.setattr(query, 'all', lambda: [gate]) monkeypatch.setattr(projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False) summary = projection.project_user_gate_summary(execution) assert summary['status'] == 'legacy_readonly' assert summary['legacy_readonly'] is True assert summary['next_action_code'] is None assert summary['allowed_actions'] == [] def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technical(app, monkeypatch): """库存匹配技术重试被隐藏时,跨阶段 RecoveryPlan 仍必须保留人工复核入口。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection execution = SimpleNamespace( id=1, execution_no='EXE-INV-1', status='blocked', current_gate_code='inventory_matching', primary_next_action_code='retry_inventory_matching', responsible_party='worker', lock_version=1, review_case_id=None, task_id=None, ) monkeypatch.setattr( projection, 'serialize_process_execution', lambda _execution, include_diagnostics=False: { 'execution_no': 'EXE-INV-1', 'status': 'blocked', 'primary_next_action_code': 'retry_inventory_matching', 'responsible_party': 'worker', 'current_gate': { 'gate_code': 'inventory_matching', 'status': 'blocked_manual', 'blocking_reason_code': 'inventory_match_incomplete', 'next_action_code': 'retry_inventory_matching', }, 'recovery_targets': [ {'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'}, ], 'gates': [], 'active_recovery_plans': [], }, ) summary = projection.project_user_gate_summary(execution) assert summary['current_blocking_gate']['gate_code'] == 'inventory_matching' assert summary['next_action_code'] == 'open_inventory_match_review' assert summary['owner_type'] == 'human' assert summary['technical_auto_only'] is False assert summary['allowed_actions'] == [ 'open_inventory_match_review', 'retry_inventory_from_preparation', ] def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch): """正式 OT 库存匹配阻断不得投影无写操作的复核入口。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection execution = SimpleNamespace( id=1, execution_no='EXE-INV-OT-1', status='blocked', current_gate_code='inventory_matching', primary_next_action_code='open_inventory_match_review', responsible_party='worker', lock_version=1, review_case_id=None, task_id=99, ) monkeypatch.setattr( projection, 'serialize_process_execution', lambda _execution, include_diagnostics=False: { 'execution_no': 'EXE-INV-OT-1', 'status': 'blocked', 'primary_next_action_code': 'open_inventory_match_review', 'responsible_party': 'worker', 'current_gate': { 'gate_code': 'inventory_matching', 'status': 'blocked_manual', 'blocking_reason_code': 'inventory_match_incomplete', 'next_action_code': 'open_inventory_match_review', }, 'recovery_targets': [ {'action_code': 'open_inventory_match_review', 'target_gate': 'inventory_matching'}, {'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'}, ], 'gates': [], 'active_recovery_plans': [], }, ) summary = projection.project_user_gate_summary(execution) assert summary['next_action_code'] == 'retry_inventory_matching' assert summary['allowed_actions'] == [ 'retry_inventory_matching', 'retry_inventory_from_preparation', ] assert summary['recovery_targets'] == [ {'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'}, ] def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch): """所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection execution = SimpleNamespace( id=1, execution_no='EXE-FAIL-1', status='blocked', current_gate_code='artifact_generation', primary_next_action_code='regenerate_excel_artifact', responsible_party='system', lock_version=1, review_case_id=None, task_id=None, ) monkeypatch.setattr( projection, 'serialize_process_execution', lambda _execution, include_diagnostics=False: { 'execution_no': 'EXE-FAIL-1', 'status': 'blocked', 'primary_next_action_code': 'regenerate_excel_artifact', 'responsible_party': 'system', 'recovery_targets': [], 'gates': [], 'active_recovery_plans': [], 'current_gate': { 'gate_code': 'artifact_generation', 'status': 'blocked_retryable', 'blocking_reason_code': 'artifact_generation_failed', 'next_action_code': 'regenerate_excel_artifact', 'latest_attempt': { 'attempt_no': 7, 'status': 'failed', 'error_code': 'SHIPPING.EXCEL_ARTIFACT_WRITE_FAILED', 'error_summary': r'Excel 写入失败 at C:\worker\output.xlsx password=secret', }, }, }, ) summary = projection.project_user_gate_summary(execution) assert summary['failure_detail'] is not None assert 'Excel 写入失败' in summary['failure_detail'] assert '[path]' in summary['failure_detail'] assert 'secret' not in summary['failure_detail'] def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch): """历史 Gate 19 即使持久化了人工待办动作,也必须投影为 RPA 重试。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection execution = SimpleNamespace( id=1, execution_no='EXE-RPA-STALE', status='blocked', current_gate_code='freight_upload_rpa', primary_next_action_code='regenerate_manual_upload_todo', responsible_party='worker', lock_version=1, review_case_id=None, task_id=None, ) monkeypatch.setattr( projection, 'serialize_process_execution', lambda _execution, include_diagnostics=False: { 'execution_no': 'EXE-RPA-STALE', 'status': 'blocked', 'primary_next_action_code': 'regenerate_manual_upload_todo', 'responsible_party': 'worker', 'recovery_targets': [], 'active_recovery_plans': [], 'gates': [], 'current_gate': { 'gate_code': 'freight_upload_rpa', 'status': 'blocked_manual', 'blocking_reason_code': 'upload_platform_rejected', 'next_action_code': 'regenerate_manual_upload_todo', }, }, ) summary = projection.project_user_gate_summary(execution) assert summary['next_action_code'] == 'retry_freight_upload_rpa' assert summary['owner_type'] == 'human' def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch): """Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection execution = SimpleNamespace( id=1, execution_no='EXE-MANUAL-RPA', status='blocked', current_gate_code='manual_upload_handoff', primary_next_action_code='regenerate_manual_upload_todo', responsible_party='owner', lock_version=1, review_case_id=None, task_id=None, ) monkeypatch.setattr( projection, 'serialize_process_execution', lambda _execution, include_diagnostics=False: { 'execution_no': 'EXE-MANUAL-RPA', 'status': 'blocked', 'primary_next_action_code': 'regenerate_manual_upload_todo', 'responsible_party': 'owner', 'recovery_targets': [], 'active_recovery_plans': [], 'gates': [], 'current_gate': { 'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual', 'blocking_reason_code': 'manual_upload_pending', 'next_action_code': 'regenerate_manual_upload_todo', }, }, ) summary = projection.project_user_gate_summary(execution) assert summary['next_action_code'] == 'retry_freight_upload_rpa' assert summary['owner_type'] == 'human' def test_process_gate_dependency_integrity_and_excel_only_scope(): """ 校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。 核心逻辑:依赖自检 + excel_regeneration_only 显式排除 inventory_matching。 """ # [STEP 1] 前置依赖与失效规则仅引用已知门禁 assert_process_gate_dependency_integrity() # [STEP 2] 仅重生 Excel:失效 artifact + 人工上传,不碰库存匹配 excel_only = compute_invalidated_gates('excel_regeneration_only') assert 'inventory_matching' not in excel_only assert 'artifact_generation' in excel_only assert 'freight_upload_rpa' in excel_only assert 'manual_upload_handoff' in excel_only assert set(excel_only) == set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only'])