""" 用途:验证 RecoveryPlan 与库存准备谱系的结构化合同。 依赖:SQLAlchemy metadata、ShippingProcessRecoveryPlan、库存准备/Mapping 模型。 逻辑:只验证模型约束和关键状态字段,不触发外部 RPA 或业务恢复副作用。 """ from __future__ import annotations from sqlalchemy import UniqueConstraint from app.models import ( ShippingInventoryMapping, ShippingInventoryPreparationAttempt, ShippingInventoryPreparationSourceAttempt, ShippingProcessRecoveryPlan, ) def _unique_names(model) -> set[str]: return { str(item.name) for item in model.__table__.constraints if isinstance(item, UniqueConstraint) and item.name } def test_recovery_plan_has_idempotent_business_identity(): """RecoveryPlan 必须以 plan_no 和 execution+idempotency_key 形成业务幂等边界。""" names = _unique_names(ShippingProcessRecoveryPlan) assert 'uq_shipping_process_recovery_plans_no' in names assert 'uq_shipping_process_recovery_plans_execution_idempotency' in names assert 'status' in ShippingProcessRecoveryPlan.__table__.c assert 'invalidation_plan_json' in ShippingProcessRecoveryPlan.__table__.c def test_inventory_preparation_is_task_round_with_per_source_uniqueness(): """准备轮次和逐源 Attempt 均必须保留不可混淆的唯一范围。""" assert 'uq_shipping_inventory_preparation_task_attempt' in _unique_names(ShippingInventoryPreparationAttempt) assert 'uq_shipping_inventory_preparation_source_attempt' in _unique_names(ShippingInventoryPreparationSourceAttempt) assert {'source_code', 'status', 'inventory_file_id', 'rpa_attempt_id'} <= set( ShippingInventoryPreparationSourceAttempt.__table__.c.keys() ) def test_rpa_attempt_status_updates_its_bound_preparation_source(app): """RPA 回调必须更新既有 SourceAttempt,并聚合 PreparationAttempt 状态。""" from app import db from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt from app.services.shipping_notice.inventory_recovery_service import ( create_inventory_preparation_round, sync_inventory_preparation_round, sync_preparation_source_from_rpa_attempt, ) task = ShippingNotice(task_no='SN-PREP-LINEAGE-1', process_status='waiting_inventory') db.session.add(task) db.session.flush() preparation = create_inventory_preparation_round( task=task, execution_id=88, recovery_plan_id=None, action_code='retry_inventory_preparation', source_codes=['DBS'], gate_attempt_id=301, ) rpa = ShippingTaskInventoryRpaAttempt( task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-LINEAGE-1', status='queued', lease_token='lease-lineage', extra_json={}, callback_payload_json={}, ) db.session.add(rpa) db.session.flush() sync_inventory_preparation_round( preparation_attempt=preparation, result={'pending_source_codes': ['DBS'], 'source_attempts': {'DBS': {'attempt_id': rpa.id}}}, ) sync_preparation_source_from_rpa_attempt(rpa_attempt_id=rpa.id, rpa_status='succeeded') source = preparation.source_attempts[0] assert preparation.input_snapshot_json['gate_attempt_id'] == 301 assert preparation.gate_attempt_id == 301 assert source.rpa_attempt_id == rpa.id assert source.status == 'ready' assert preparation.status == 'succeeded' def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, app): """库存准备 Trigger 必须把 GateAttempt 身份原样带到 RPA。""" from app import db from app.models import ShippingNotice, ShippingProcessGate from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version from app.services.shipping_notice import per_source_rpa_service task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY', process_status='waiting_inventory') db.session.add(task) db.session.flush() execution = ensure_execution_for_workflow_version(task_id=int(task.id), actor_type='system') execution.current_gate_code = 'inventory_preparation' task.active_process_execution_id = int(execution.id) db.session.flush() gate = ShippingProcessGate.query.filter_by(execution_id=int(execution.id), gate_code='inventory_preparation').first() assert gate is not None db.session.commit() captured = {} monkeypatch.setattr( per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda task_no, source, payload=None: captured.update(payload or {}) or 'trigger.json', ) monkeypatch.setattr('app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda task: {'source_code': 'DBS', 'warehouse_id': 'WH-1'}) monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False) monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto') assert result.pending_source_codes == ['DBS'] assert captured['execution_id'] == task.active_process_execution_id assert captured['gate_id'] == gate.id assert captured['callback_id'].endswith(':C1') def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): """trigger 写入返回空路径时,Attempt 必须失败,禁止伪装 queued。""" from app import db from app.models import ShippingNotice from app.services.shipping_notice import per_source_rpa_service task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING', process_status='waiting_inventory') db.session.add(task) db.session.flush() monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False) monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda *args, **kwargs: None) monkeypatch.setattr( 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', lambda code: {'source_code': code, 'warehouse_id': 'WH-1'}, ) result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa') assert result.pending_source_codes == [] assert result.failed_source_codes == ['DBS'] attempt = per_source_rpa_service._latest_attempt(task.task_no, 'DBS') assert attempt.status == 'failed' assert attempt.error_code == 'trigger_not_written' def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkeypatch, app): """正式 Gate Worker 仅携带 operator_id 时,也必须先冻结快照再写 RPA trigger。""" from app import db from app.models import ShippingNotice, ShippingProcessExecution from app.services.shipping_notice import process_gate_executor task = ShippingNotice( task_no='SN-PREP-FREEZE-OPERATOR', process_status='waiting_inventory', order_snapshot_id=None, order_data_version=1, ) db.session.add(task) db.session.flush() execution = ShippingProcessExecution( execution_no='SPE-PREP-FREEZE-OPERATOR', task_id=task.id, current_gate_code='inventory_preparation', status='blocked', ) db.session.add(execution) db.session.flush() seen = {} monkeypatch.setattr( 'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot', lambda task, **kwargs: seen.update(kwargs) or object(), ) monkeypatch.setattr( 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', lambda **kwargs: None, ) monkeypatch.setattr( 'app.services.shipping_notice.inventory_workflow.ensure_inventory', lambda payload: {'status': 'running', 'data': {'rpa': {}}}, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', lambda **kwargs: None, ) gate = type('Gate', (), {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', 'blocking_reason_code': None})() result = process_gate_executor._handle_retry_inventory_preparation( execution=execution, gate=gate, payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77}, ) assert seen['actor_id'] == 77 assert result['outcome'] in {'blocked_retryable', 'blocked_manual'} def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): """旧 CandidateSet 回调必须在写入库存事实前被拒绝。""" from app import db from app.models import ( ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskInventoryRpaAttempt, ) from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY', process_status='waiting_inventory') db.session.add(task) db.session.flush() current = ShippingInventoryCandidateSet( task_id=task.id, set_version=2, lifecycle_status='frozen', input_fingerprint='b' * 64, ) db.session.add(current) db.session.flush() task.active_inventory_candidate_set_id = current.id attempt = ShippingTaskInventoryRpaAttempt( task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X', status='running', callback_id='PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C1', lease_token='lease-1', extra_json={ 'candidate_set_id': 999, 'execution_id': 88, 'gate_id': 901, 'expected_warehouse_id': 'WH-1', }, ) db.session.add(attempt) db.session.commit() result, handled = per_source_callback_handler( task, source_code='DBS', run_no=attempt.source_run_no, callback_payload={ 'schema_version': 'shipping_inventory_rpa.v2', 'callback_id': 'PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C2', 'task_no': task.task_no, 'source_code': 'DBS', 'source_run_no': attempt.source_run_no, 'attempt_no': 1, 'lease_token': 'lease-1', 'candidate_set_id': current.id, 'execution_id': 88, 'gate_id': 901, 'expected_warehouse_id': 'WH-1', 'status': 'success', }, ) assert result == 'identity_mismatch' assert handled is attempt db.session.refresh(attempt) assert attempt.status == 'running' def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): """统一单源回调入口遇到身份错配时必须拒绝且不得落入旧库存写入路径。""" from app import db from app.models import ShippingNotice, ShippingTaskEvent from app.services.shipping_notice import inventory_rpa_workflow task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY', process_status='waiting_inventory') db.session.add(task) db.session.commit() monkeypatch.setattr( inventory_rpa_workflow, '_validate_single_source_v2_contract', lambda task, payload: None, ) monkeypatch.setattr( 'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler', lambda task, source_code, run_no, callback_payload: ('identity_mismatch', object()), ) legacy_called = {'value': False} monkeypatch.setattr( inventory_rpa_workflow, '_lock_task_for_rpa_callback', lambda task: legacy_called.__setitem__('value', True) or task, ) response = inventory_rpa_workflow.rpa_report_inventory({ 'schema_version': 'shipping_inventory_rpa.v2', 'callback_id': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X:C1', 'task_no': task.task_no, 'task_id': task.task_no, 'source_code': 'DBS', 'source_run_no': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X', 'run_no': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X', 'attempt_no': 1, 'lease_token': 'lease-invalid', 'candidate_set_id': 999, 'execution_id': 88, 'gate_id': 901, 'status': 'success', }) assert response['status'] == 'failed' assert response['data']['error_code'] == 'callback_identity_mismatch' assert legacy_called['value'] is False assert db.session.query(ShippingTaskEvent).filter_by( task_id=task.id, event_type='rpa_callback_rejected', ).count() == 1 def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, monkeypatch): """PSR run_no 中 task_no 可含连字符,入口仍必须解析出真实 source_code。""" from app import db from app.models import ShippingNotice from app.services.shipping_notice import inventory_rpa_workflow task = ShippingNotice(task_no='SN-2026-001', process_status='waiting_inventory') db.session.add(task) db.session.commit() captured = {} monkeypatch.setattr(inventory_rpa_workflow, '_validate_single_source_v2_contract', lambda task, payload: None) monkeypatch.setattr( 'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler', lambda task, source_code, run_no, callback_payload: captured.update(source_code=source_code, run_no=run_no) or ('identity_mismatch', object()), ) inventory_rpa_workflow.rpa_report_inventory({ 'schema_version': 'shipping_inventory_rpa.v2', 'callback_id': 'PSR-SN-2026-001-DBS-A1-X:C1', 'task_no': task.task_no, 'task_id': task.task_no, 'source_code': 'DBS', 'source_run_no': 'PSR-SN-2026-001-DBS-A1-X', 'run_no': 'PSR-SN-2026-001-DBS-A1-X', 'attempt_no': 1, 'lease_token': 'lease-invalid', 'candidate_set_id': 999, 'execution_id': 88, 'gate_id': 901, 'status': 'success', }) assert captured == {'source_code': 'DBS', 'run_no': 'PSR-SN-2026-001-DBS-A1-X'} def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): """批量成功项也必须先通过逐源身份校验,不能先入库再拒绝。""" from app import db from app.models import ShippingNotice, ShippingTaskEvent from app.services.shipping_notice import inventory_rpa_workflow task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY', process_status='waiting_inventory') db.session.add(task) db.session.commit() monkeypatch.setattr( 'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler', lambda task, source_code, run_no, callback_payload: ('identity_mismatch', object()), ) legacy_called = {'value': False} monkeypatch.setattr( inventory_rpa_workflow, '_lock_task_for_rpa_callback', lambda task: legacy_called.__setitem__('value', True) or task, ) response = inventory_rpa_workflow.rpa_report_inventory_batch({ 'schema_version': 'shipping_inventory_rpa.v2', 'callback_id': 'batch-callback-identity', 'batch_run_no': 'BATCH-CALLBACK-IDENTITY', 'results': [{ 'task_no': task.task_no, 'source_code': 'DBS', 'source_run_no': 'PSR-SNCALLBACKBATCHIDENTITY-DBS-A1-X', 'callback_id': 'PSR-SNCALLBACKBATCHIDENTITY-DBS-A1-X:C1', 'status': 'success', 'warehouse_id': 'WH-1', }], }) assert response['failed_count'] == 1 assert response['data']['failed'][0]['error_code'] == 'callback_identity_mismatch' assert legacy_called['value'] is False assert db.session.query(ShippingTaskEvent).filter_by( task_id=task.id, event_type='rpa_callback_rejected', ).count() == 1 def test_batch_callback_inherits_authenticated_top_level_schema_version(): """Worker 将 schema_version 放在 batch 顶层时,结果项仍须通过逐源身份校验。""" from app.services.shipping_notice.inventory_rpa_workflow import _merge_batch_callback_item merged = _merge_batch_callback_item( { 'schema_version': 'shipping_inventory_rpa.v2', 'run_no': 'BATCH-1', 'task_no': 'SN-1', }, { 'source_code': 'DSV360_AWSSG', 'source_run_no': 'PSR-SN-1-DSV360_AWSSG-A1-ABC', }, ) assert merged['schema_version'] == 'shipping_inventory_rpa.v2' assert merged['run_no'] == 'BATCH-1' assert merged['task_no'] == 'SN-1' def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app): """RPA 已耗尽时自动轮询必须终态化,Gate 才能退出系统处理中。""" from app import db from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_service import queue_gate_attempt task = ShippingNotice( task_no='SN-RPA-FAILED-GATE', process_status='waiting_inventory', pending_human_reason='rpa_exhausted', error_message='RPA export failed', ) db.session.add(task) db.session.flush() execution = ShippingProcessExecution( execution_no='SPE-RPA-FAILED-GATE', task_id=task.id, status='waiting_external', current_gate_code='inventory_preparation', ) db.session.add(execution) db.session.flush() sync_fulfillment_gates_from_task(execution=execution) gate = ShippingProcessGate.query.filter_by( execution_id=execution.id, gate_code='inventory_preparation', ).one() auto_poll = queue_gate_attempt( execution_no=execution.execution_no, gate_code='inventory_preparation', trigger_type='auto', actor_type='system', idempotency_key='shipping-auto-progress:rpa-failed-poll', input_snapshot={'action_code': 'poll_inventory_preparation'}, ) db.session.flush() sync_fulfillment_gates_from_task(execution=execution) db.session.refresh(auto_poll) db.session.refresh(gate) assert auto_poll.status == 'superseded' assert auto_poll.error_code == 'rpa_callback_failed' assert ShippingProcessGateAttempt.query.filter( ShippingProcessGateAttempt.gate_id == gate.id, ShippingProcessGateAttempt.status.in_(('queued', 'running')), ).count() == 0 assert gate.status == 'blocked_manual' assert gate.blocking_reason_code == 'inventory_rpa_exhausted' db.session.refresh(execution) assert execution.status == 'blocked' def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch): """正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。""" from app import db from app.models import ( ShippingInventoryCandidateSet, ShippingInventoryPreparationAttempt, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt, ) from app.services.shipping_notice.process_gate_job_service import claim_and_run_gate_attempt from app.services.shipping_notice.process_gate_service import ( ensure_execution_for_workflow_version, queue_gate_attempt, ) task = ShippingNotice( task_no='SNFORMALPREPLINEAGE', process_status='waiting_inventory', inventory_source_code='DBS', ) db.session.add(task) db.session.flush() candidate = ShippingInventoryCandidateSet( task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64, ) db.session.add(candidate) db.session.flush() task.active_inventory_candidate_set_id = candidate.id execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') execution.candidate_set_id = candidate.id execution.current_gate_code = 'inventory_preparation' task.active_process_execution_id = execution.id gate = ShippingProcessGate.query.filter_by( execution_id=execution.id, gate_code='inventory_preparation', ).one() gate.status = 'pending' gate.next_action_code = 'retry_inventory_preparation' db.session.commit() captured_payload = {} monkeypatch.setattr( 'app.services.shipping_notice.inventory_workflow.ensure_inventory', lambda payload: captured_payload.update(payload) or { 'status': 'success', 'data': { 'rpa': { 'all_prepared': True, 'prepared_source_codes': ['DBS'], 'pending_source_codes': [], 'failed_source_codes': [], 'source_attempts': {}, }, }, }, ) attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='inventory_preparation', trigger_type='auto', actor_type='system', actor_id='test', idempotency_key='formal-prep-lineage-1', input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}}, ) result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='lineage-worker') db.session.refresh(attempt) db.session.refresh(gate) preparation = ShippingInventoryPreparationAttempt.query.filter_by( 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' assert len(preparation.source_attempts) == 1 assert preparation.source_attempts[0].source_code == 'DBS' assert preparation.source_attempts[0].status == 'ready' assert preparation.source_attempts[0].rpa_attempt_id is None db.session.refresh(execution) assert execution.current_gate_code != 'inventory_preparation' def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app): """正式起始 Gate 必须优先反映未完成的客户确认事实。""" from app import db from app.models import ShippingInventoryCandidateSet, ShippingNotice from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate task = ShippingNotice( task_no='SNSTARTCUSTOMERPENDING', process_status='created', current_order_extraction_id=101, order_snapshot_id=201, customer_resolution_status='pending', ) db.session.add(task) db.session.flush() candidate = ShippingInventoryCandidateSet( task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='d' * 64, ) db.session.add(candidate) db.session.flush() assert determine_formal_start_gate(task, candidate_set=candidate) == 'customer_resolution' def test_formal_start_gate_stops_at_field_conflict_before_inventory(app): """正式起始 Gate 必须优先反映尚未解决的订单字段冲突。""" from app import db from app.models import ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskFieldConflict from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate task = ShippingNotice( task_no='SNSTARTFIELDCONFLICT', process_status='created', current_order_extraction_id=101, order_snapshot_id=201, customer_resolution_status='confirmed', ) db.session.add(task) db.session.flush() db.session.add(ShippingTaskFieldConflict( task_id=task.id, field_name='part_number', status='open', )) candidate = ShippingInventoryCandidateSet( task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='e' * 64, ) db.session.add(candidate) db.session.flush() assert determine_formal_start_gate(task, candidate_set=candidate) == 'field_conflict_resolution' def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app): """候选重冻结必须同时终止旧正式 GateAttempt 与其 Job。""" from app import db from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessGateAttempt from app.services.shipping_notice.auto_progress_controller import supersede_auto_progress_for_candidate_refreeze from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version, queue_gate_attempt task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT', process_status='waiting_inventory') db.session.add(task) db.session.flush() old_candidate = ShippingInventoryCandidateSet( task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='f' * 64, ) db.session.add(old_candidate) db.session.flush() task.active_inventory_candidate_set_id = old_candidate.id execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') execution.candidate_set_id = old_candidate.id task.active_process_execution_id = execution.id db.session.flush() attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='inventory_preparation', trigger_type='auto', actor_type='system', actor_id='test', idempotency_key='candidate-refreeze-attempt-1', input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}}, ) job = Job.query.filter_by(id=attempt.job_id).one_or_none() if job is None: job = Job( domain='shipping_notice', job_type='shipping_process_gate', task_id=task.id, execution_id=execution.id, gate_id=attempt.gate_id, candidate_set_id=old_candidate.id, status='queued', payload_json={'attempt_id': attempt.id}, business_ref='candidate-refreeze-job', ) db.session.add(job) db.session.flush() attempt.job_id = job.id db.session.commit() supersede_auto_progress_for_candidate_refreeze(task) db.session.commit() db.session.refresh(attempt) db.session.refresh(job) assert attempt.status in {'superseded', 'cancelled'} assert job.status == 'cancelled' def test_legacy_workspace_forwarding_audit_is_structured(app): """旧工作台动作转发必须留下 legacy_forwarded 入口审计。""" from app import db from app.models import ShippingNotice, ShippingTaskEvent from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT', process_status='waiting_inventory') db.session.add(task) db.session.flush() audit_legacy_forwarded_entrypoint( task=task, action_code='match_inventory', actor_id=42, request_id='req-legacy-forward', ) row = ShippingTaskEvent.query.filter_by( task_id=task.id, event_type='shipping_legacy_entrypoint_forwarded', ).one() assert row.source == 'workspace_api' assert row.actor_id == 42 assert row.request_id == 'req-legacy-forward' assert row.detail_json == { 'entrypoint': 'legacy_forwarded', 'action_code': 'match_inventory', } def test_apx_runtime_audit_is_read_only_and_counts_active_states(app): """APX 清点只读统计运行中记录,不修改历史 Execution/Job。""" from app import db from app.models import Job, ShippingNotice, ShippingProcessExecution from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state task = ShippingNotice(task_no='SN-APX-AUDIT', process_status='waiting_inventory') db.session.add(task) db.session.flush() active = ShippingProcessExecution( execution_no='APX-20260811-ACTIVE', task_id=task.id, status='active', current_gate_code='inventory_snapshots_ready', ) historical = ShippingProcessExecution( execution_no='APX-20260811-HIST', task_id=task.id, status='completed', current_gate_code='inventory_matched', ) db.session.add_all([active, historical]) db.session.flush() job = Job( domain='shipping_notice', job_type='shipping_auto_progress', task_id=task.id, execution_id=active.id, status='queued', business_ref='APX-20260811-ACTIVE', ) db.session.add(job) db.session.commit() result = audit_apx_runtime_state() assert result['execution']['active_count'] == 1 assert result['execution']['historical_count'] == 1 assert result['job']['active_count'] == 1 assert ShippingProcessExecution.query.filter_by(id=active.id).one().status == 'active' assert Job.query.filter_by(id=job.id).one().status == 'queued' def test_inventory_mapping_is_versioned_and_immutable_by_shape(): """Mapping 必须按文件+版本唯一,旧版本通过 superseded_by_id 留谱系。""" assert 'uq_shipping_inventory_mapping_file_version' in _unique_names(ShippingInventoryMapping) assert {'version', 'status', 'mapping_json', 'input_fingerprint', 'superseded_by_id'} <= set( ShippingInventoryMapping.__table__.c.keys() ) def test_process_execution_projection_exposes_server_owned_recovery_targets(app): """Projection 必须只读暴露服务端 RecoveryPlan 目标,不让客户端自行推导 target Gate。""" from app import db from app.models import ShippingProcessExecution, ShippingProcessGate from app.services.shipping_notice.process_gate_projection import serialize_process_execution with app.app_context(): execution = ShippingProcessExecution( execution_no='EXE-PROJECTION-RECOVERY', status='blocked', current_gate_code='inventory_matching', lock_version=1, ) db.session.add(execution) db.session.flush() db.session.add(ShippingProcessGate( execution_id=execution.id, gate_code='inventory_matching', sequence_no=15, status='blocked_manual', evaluation_version=2, )) db.session.flush() projection = serialize_process_execution(execution) targets = {item['action_code']: item for item in projection['recovery_targets']} gate_targets = {item['action_code']: item for item in projection['current_gate']['recovery_targets']} assert targets['retry_inventory_from_preparation']['target_gate'] == 'inventory_preparation' assert gate_targets['retry_inventory_from_preparation']['target_gate'] == 'inventory_preparation' assert targets['retry_inventory_from_field_mapping']['resume_after_gate'] == 'inventory_matching' assert projection['active_recovery_plans'] == [] def test_recovery_plan_outcome_mapping_is_terminal_or_waiting(): """RecoveryPlan 必须将 Attempt 结果映射到可审计的计划状态。""" from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt class Plan: status = 'queued' action_code = 'retry_inventory_from_preparation' resume_after_gate = 'inventory_sufficiency' started_at = None completed_at = None failure_code = None failure_detail_json = None plan = Plan() complete_recovery_plan_for_attempt(plan=plan, outcome='passed') assert plan.status == 'succeeded' assert plan.completed_at is not None plan = Plan() complete_recovery_plan_for_attempt(plan=plan, outcome='waiting_external') assert plan.status == 'waiting_external' assert plan.completed_at is None def test_current_inventory_rematch_shortage_completes_recovery_plan(): """当前库存重匹配已完成但仍有缺口时,计划必须完成而非永久占用活动恢复位。""" from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt class Plan: status = 'queued' action_code = 'retry_inventory_from_matching' resume_after_gate = 'inventory_sufficiency' started_at = None completed_at = None failure_code = None failure_detail_json = None plan = Plan() complete_recovery_plan_for_attempt( plan=plan, outcome='blocked_manual', business_result_code='inventory_shortage_review_required', ) # 关键断言:重新匹配动作已完成;正式流程仍可由 Gate 16 表达缺口人工复核。 assert plan.status == 'succeeded' assert plan.completed_at is not None def test_inventory_rematch_shortage_is_business_result_not_technical_failure(monkeypatch): """库存 14、缺口 16 时,匹配 Attempt 成功收口到缺口复核。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching task = SimpleNamespace( match_status='partial', shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]}, ) monkeypatch.setattr( 'app.models.ShippingNotice.query', SimpleNamespace(get=lambda _task_id: task), ) monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.match_inventory', lambda _payload: {'status': 'needs_human', 'message': '当前 Gate 需要人工处理。'}, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', lambda **_: None, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor._task_payload', lambda _execution, _payload: {'_orchestrator_internal_dispatch': True}, ) result = _handle_retry_inventory_matching( execution=SimpleNamespace(task_id=13), gate=SimpleNamespace(gate_code='inventory_sufficiency'), payload={'actor_user_id': 1}, ) assert result['outcome'] == 'blocked_manual' assert result['blocking_reason_code'] == 'inventory_shortage_review_required' assert result['effective_result_json']['shortage']['lines'][0] == { 'available_qty': 14, 'shortage_qty': 16, } def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch): """字段映射恢复必须停留在 mapping handler,不得误建库存准备轮次。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _dispatch_action called = {'preparation': 0, 'matching': 0} monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_preparation', lambda **_: called.__setitem__('preparation', called['preparation'] + 1) or {'outcome': 'passed'}, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_from_field_mapping', lambda **_: {'outcome': 'blocked_manual'}, ) result = _dispatch_action( execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'), action_code='retry_inventory_from_field_mapping', payload={}, ) assert result['outcome'] == 'blocked_manual' assert called['preparation'] == 0 def test_field_mapping_recovery_resumes_matching_after_mapping_passes(monkeypatch): """字段映射完成后必须重跑匹配,不能把 mapping 成功误作 matching 成功。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_from_field_mapping called = {'matching': 0} monkeypatch.setattr( 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', lambda **_: {}, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_field_mapping', lambda **_: {'outcome': 'passed'}, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_matching', lambda **_: called.__setitem__('matching', called['matching'] + 1) or {'outcome': 'passed'}, ) result = _handle_retry_inventory_from_field_mapping( execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'), payload={}, ) assert result['outcome'] == 'passed' assert called['matching'] == 1 def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypatch): """Gate Attempt 内调用库存匹配时不得递归提交第二次 auto-progress。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _task_payload task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH') monkeypatch.setattr( 'app.models.ShippingNotice.query', SimpleNamespace(get=lambda _task_id: task), ) result = _task_payload( SimpleNamespace(task_id=123), {'actor_user_id': 9}, ) # 关键断言:由当前 Gate Worker 直接执行匹配原子步骤,不再绕回 facade。 assert result['_orchestrator_internal_dispatch'] is True assert result['task_id'] == 'SN-INTERNAL-DISPATCH' assert result['operator_id'] == 9 def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch): """旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation task = SimpleNamespace( order_snapshot_id=None, order_data_version=7, task_no='SN-LEGACY-SNAPSHOT-1', ) captured = {} monkeypatch.setattr( 'app.models.ShippingNotice.query', SimpleNamespace(get=lambda _task_id: task), ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor.db.session.flush', lambda: None, ) monkeypatch.setattr( 'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot', lambda target, **kwargs: captured.update(target=target, **kwargs) or setattr(target, 'order_snapshot_id', 901), ) monkeypatch.setattr( 'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round', lambda **_: None, ) monkeypatch.setattr( 'app.services.shipping_notice.inventory_workflow.ensure_inventory', lambda _payload: {'status': 'running', 'message': 'waiting RPA'}, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', lambda _task: 'inventory_preparation_failed', ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', lambda **_: None, ) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_executor._task_payload', lambda _execution, _payload: {'task_id': task.task_no}, ) result = _handle_retry_inventory_preparation( execution=SimpleNamespace(task_id=13, id=21), gate=SimpleNamespace(gate_code='inventory_preparation'), payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5}, ) # 关键断言:正式 Gate 入口也补冻结,后续才允许进入库存 RPA。 assert captured == { 'target': task, 'actor_id': 5, 'expected_order_data_version': 7, 'freeze_mode': 'manual', } assert task.order_snapshot_id == 901 assert result['outcome'] == 'waiting_external' def test_manual_business_block_is_a_successful_attempt(app): """库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。""" from app import db from app.models import ShippingProcessGateAttempt from app.services.shipping_notice.process_gate_service import ( complete_gate_attempt, ensure_execution_for_workflow_version, mark_attempt_running, queue_gate_attempt, ) from tests.test_shipping_process_gate_service import _seed_workflow_version with app.app_context(): _user, review_case_id, task_id = _seed_workflow_version(suffix='manual-block-success') execution = ensure_execution_for_workflow_version( review_case_id=review_case_id, task_id=task_id, ) attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code='inventory_sufficiency', trigger_type='user_retry', actor_type='user', actor_id=1, idempotency_key='manual-block-success', input_snapshot={'action_code': 'retry_inventory_from_matching', 'payload': {}}, ) mark_attempt_running(attempt_id=int(attempt.id), worker_id='test') gate = complete_gate_attempt( attempt_id=int(attempt.id), outcome='blocked_manual', blocking_reason_code='inventory_insufficient', effective_result_json={ 'match_status': 'partial', 'available_qty': 14, 'shortage_qty': 16, }, ) db.session.flush() refreshed_attempt = db.session.get(ShippingProcessGateAttempt, int(attempt.id)) # 关键断言:业务缺口不是执行器失败;数量事实保持只读并留在 Gate 结果。 assert refreshed_attempt.status == 'succeeded' assert gate.status == 'blocked_manual' assert gate.effective_result_json['available_qty'] == 14 assert gate.effective_result_json['shortage_qty'] == 16