Files
syops/backend/tests/test_shipping_process_recovery_plan.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

1489 lines
61 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
用途:验证 RecoveryPlan 与库存准备谱系的结构化合同。
依赖:SQLAlchemy metadata、ShippingProcessRecoveryPlan、库存准备/Mapping 模型。
逻辑:只验证模型约束和关键状态字段,不触发外部 RPA 或业务恢复副作用。
"""
from __future__ import annotations
import pytest
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_excel_regeneration_invalidation_preserves_inventory_facts(app):
"""仅重生 Excel 只替代旧产物和未完成上传,不能重算库存或抹掉短缺放行事实。"""
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryParsingProfile,
ShippingInventoryVerification,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingProcessExecution,
ShippingReservation,
ShippingUploadAttempt,
)
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx')
template = ShippingExcelTemplate(
template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published',
storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='REGEN-ONLY', display_name='Regen only', version=1,
status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only')
db.session.add_all([task, template, profile, schema])
db.session.flush()
schema_version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={},
)
db.session.add(schema_version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted',
)
execution = ShippingProcessExecution(
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked',
current_gate_code='manual_upload_handoff',
)
db.session.add_all([extraction, execution])
db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='EXP-EXCEL-REGEN-ONLY', task_id=task.id, template_id=template.id,
order_schema_version_id=schema_version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path='old.xlsx', file_name='old.xlsx', file_checksum='d' * 64, file_size=1,
status='ready',
)
reservation = ShippingReservation(
task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
part_number='PN-1', po_number_normalized='PO-1', required_qty=1,
status='artifact_reserved', current_artifact_id=None,
)
verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={})
match = ShippingNoticeLineInventoryMatch(
task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY',
part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True,
)
db.session.add_all([artifact, reservation, verification, match])
db.session.flush()
reservation.current_artifact_id = artifact.id
upload = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=1, mode='manual',
idempotency_key='excel-regen-only', status='pending',
)
db.session.add(upload)
db.session.flush()
result = invalidate_excel_regeneration_only(
execution=execution,
attempt_id=17,
actor_id=9,
)
db.session.refresh(task)
db.session.refresh(artifact)
db.session.refresh(upload)
db.session.refresh(reservation)
db.session.refresh(verification)
db.session.refresh(match)
assert result['artifacts'] == [artifact.id]
assert result['uploads'] == [upload.id]
assert artifact.status == 'superseded'
assert upload.status == 'failed'
assert upload.invalidated_at is not None
assert reservation.status == 'available'
assert reservation.current_artifact_id is None
assert task.export_file_path is None
assert task.export_file_name is None
assert verification.status == 'completed'
assert match.is_current is True
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')
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_rpa_callback_completes_waiting_preparation_recovery_plan(app):
"""RPA 成功回调完成准备轮次后,关联恢复计划不得继续占用 waiting_external。"""
from app import db
from app.models import (
ShippingNotice,
ShippingProcessExecution,
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-PLAN-COMPLETE')
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-PREP-PLAN-COMPLETE', task_id=int(task.id), status='active',
current_gate_code='inventory_preparation',
)
db.session.add(execution)
db.session.flush()
plan = ShippingProcessRecoveryPlan(
plan_no='RCP-PREP-PLAN-COMPLETE', execution_id=int(execution.id),
current_gate='inventory_matching', action_code='retry_inventory_from_preparation',
target_gate='inventory_preparation', resume_after_gate='inventory_matching',
status='waiting_external', invalidation_plan_json={},
idempotency_key='prep-plan-complete', actor_type='user',
)
db.session.add(plan)
db.session.flush()
preparation = create_inventory_preparation_round(
task=task, execution_id=int(execution.id), recovery_plan_id=int(plan.id),
action_code='retry_inventory_from_preparation', source_codes=['DBS'], gate_attempt_id=None,
)
rpa = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-PREP-PLAN-COMPLETE',
status='queued', lease_token='lease-prep-plan', 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=int(rpa.id), rpa_status='succeeded')
db.session.refresh(plan)
assert preparation.status == 'succeeded'
assert plan.status == 'succeeded'
assert plan.completed_at is not None
def test_per_source_summary_exposes_attempt_id_for_preparation_lineage(app):
"""新建 RPA Attempt 的汇总必须返回主键,准备轮次才能被回调准确收口。"""
from app import db
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.services.shipping_notice.per_source_rpa_service import _attempts_summary
task = ShippingNotice(task_no='SN-PREP-SUMMARY-ID')
db.session.add(task)
db.session.flush()
attempt = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='DBS', attempt_no=1,
source_run_no='PSR-PREP-SUMMARY-ID', status='queued',
lease_token='lease-prep-summary', extra_json={}, callback_payload_json={},
)
db.session.add(attempt)
db.session.flush()
summary = _attempts_summary(task.task_no, source_codes=['DBS'])
assert summary['DBS']['attempt_id'] == int(attempt.id)
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')
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')
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']
# 读取真实数据库记录,避免被用于构造场景的 monkeypatch 查询函数遮蔽。
from app.models import ShippingTaskInventoryRpaAttempt
attempt = ShippingTaskInventoryRpaAttempt.query.filter_by(
task_no=task.task_no, source_code='DBS', attempt_no=1,
).one()
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',
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'] == 'waiting_external'
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')
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')
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')
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')
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,
)
# HTTP 入口只负责受控收件和入队;身份围栏属于 Worker 正式处理体。
response = inventory_rpa_workflow.process_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_exhausted_history_is_retryable_not_waiting_external(app):
"""历史 RPA 耗尽必须退出系统处理中,且不得封锁用户重试入口。"""
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',
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',
actor_id=None,
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_retryable'
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
db.session.refresh(execution)
# Gate 已进入可人工恢复的 blocked_manual;Execution 仍保持 active,
# 由当前业务阶段/Gate 投影表达阻断,不再回写旧的 execution blocked 状态。
assert execution.status == 'active'
def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
"""迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。"""
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
task = ShippingNotice(
task_no='SN-RPA-LATE-SUCCESS',
pending_human_reason='rpa_exhausted',
inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}],
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
current_gate_code='inventory_preparation',
)
db.session.add(execution)
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
preparation = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_preparation',
).one()
matching = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_matching',
).one()
assert preparation.status == 'passed'
assert preparation.blocking_reason_code is None
# 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。
assert matching.status == 'blocked_retryable'
assert matching.blocking_reason_code == 'inventory_match_failed'
def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
"""跨 Gate 恢复后,旧准备轮询不得在库存匹配 Gate 产生技术失败。"""
from datetime import datetime
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
task = ShippingNotice(task_no='SN-STALE-PREP-POLL')
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-STALE-PREP-POLL', task_id=task.id, status='active',
current_gate_code='inventory_matching',
)
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_matching',
).one()
gate.status = 'waiting_external'
gate.next_action_code = 'poll_inventory_preparation'
gate.effective_result_json = {'waiting_since': datetime.utcnow().isoformat()}
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code=gate.gate_code,
trigger_type='user_retry', actor_type='system', actor_id='test',
idempotency_key='stale-preparation-poll',
input_snapshot={'action_code': 'retry_inventory_from_preparation', 'payload': {}},
)
db.session.flush()
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
assert attempt.job_id is None
def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch):
"""已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。"""
from app import db
from app.models import (
ShippingInventoryPreparationAttempt,
ShippingNotice,
ShippingProcessGate,
ShippingTaskEvent,
)
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
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='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail')
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(
task_id=task.id,
start_gate_code='inventory_preparation',
)
task.active_process_execution_id = execution.id
preparation = ShippingInventoryPreparationAttempt(
task_id=task.id,
execution_id=execution.id,
attempt_no=1,
status='failed',
input_snapshot_json={},
output_snapshot_json={},
)
db.session.add_all([
preparation,
ShippingTaskEvent(
task_id=task.id,
event_type='inventory_rpa_failed',
detail_json={'error': 'Crane scheduled report not ready for download within 300000ms'},
),
])
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
gate = ShippingProcessGate.query.filter_by(
execution_id=execution.id,
gate_code='inventory_preparation',
).one()
assert gate.status == 'blocked_retryable'
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
rpa_calls = {'count': 0}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda _payload: rpa_calls.__setitem__('count', rpa_calls['count'] + 1),
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id='external-wait-poll',
idempotency_key='poll-keeps-rpa-timeout-1',
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {'poll': True}},
)
db.session.commit()
result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='timeout-poll-worker')
db.session.refresh(gate)
db.session.refresh(execution)
assert result['skipped'] is False
assert rpa_calls['count'] == 0
assert gate.status == 'blocked_retryable'
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
assert gate.next_action_code == 'retry_inventory_preparation'
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',
inventory_source_code='DBS',
# 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。
order_snapshot_id=1,
)
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',
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',
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')
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')
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')
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_excel_regeneration_completion_preserves_manual_upload_gate():
"""跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。"""
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
class Plan:
status = 'queued'
action_code = 'regenerate_excel_artifact'
resume_after_gate = 'manual_upload_handoff'
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='manual_upload_pending',
)
assert plan.status == 'succeeded'
assert plan.completed_at is not None
def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch):
"""Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
invalidated = {}
monkeypatch.setattr(
'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only',
lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda _payload: {'status': 'ok'},
)
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},
)
outcome = _handle_regenerate_excel(
execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
payload={'attempt_id': 3, 'actor_user_id': 9},
)
assert invalidated['attempt_id'] == 3
assert outcome['outcome'] == 'blocked_manual'
assert outcome['blocking_reason_code'] == 'manual_upload_pending'
assert outcome['output_snapshot']['invalidation']['artifacts'] == [10]
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
synced = []
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda _payload: {'status': 'failed', 'message': 'template unavailable'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **kwargs: synced.append(kwargs),
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
)
execution = SimpleNamespace(execution_no='SPE-EXCEL-FAILED', task_id=1)
outcome = _handle_regenerate_excel(
execution=execution,
gate=SimpleNamespace(gate_code='artifact_generation'),
payload={'actor_user_id': 9},
)
assert outcome['outcome'] == 'blocked_retryable'
assert outcome['blocking_reason_code'] == 'artifact_generation_failed'
assert synced == [{
'execution': execution,
'actor_type': 'system',
'actor_id': 9,
}]
def test_executor_accepts_bound_cross_gate_excel_recovery_plan(monkeypatch):
"""已绑定的 Gate 20 Excel RecoveryPlan 必须能通过 Worker 归属复核。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_executor as executor
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._handle_regenerate_excel',
lambda **_: {'outcome': 'blocked_manual'},
)
monkeypatch.setattr(
executor.db.session,
'get',
lambda _model, _id: SimpleNamespace(
id=81,
execution_id=1,
current_gate='manual_upload_handoff',
action_code='regenerate_excel_artifact',
target_gate='artifact_generation',
resume_after_gate='manual_upload_handoff',
),
)
result = executor._dispatch_action(
execution=SimpleNamespace(id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
action_code='regenerate_excel_artifact',
payload={'recovery_plan_id': 81},
)
assert result['outcome'] == 'blocked_manual'
def test_executor_rejects_unbound_cross_gate_excel_recovery_plan():
"""Gate 20 的跨阶段 Excel 动作没有已绑定计划时必须 fail-closed。"""
from types import SimpleNamespace
from app.core.errors import ValidationError
from app.services.shipping_notice.process_gate_executor import _dispatch_action
with pytest.raises(ValidationError, match='Recovery plan is required'):
_dispatch_action(
execution=SimpleNamespace(id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
action_code='regenerate_excel_artifact',
payload={},
)
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},
)
# 匹配动作已成功完成;库存缺口由 inventory_sufficiency Gate 单独阻断,
# 不能把业务缺口回写成 inventory_matching 的技术失败。
assert result['outcome'] == 'passed'
assert 'blocking_reason_code' not in result
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 import process_gate_executor as executor
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'},
)
monkeypatch.setattr(
executor.db.session,
'get',
lambda _model, _id: SimpleNamespace(
execution_id=1,
current_gate='inventory_matching',
action_code='retry_inventory_from_field_mapping',
target_gate='inventory_field_mapping',
resume_after_gate='inventory_matching',
),
)
result = executor._dispatch_action(
execution=SimpleNamespace(id=1), gate=SimpleNamespace(gate_code='inventory_matching'),
action_code='retry_inventory_from_field_mapping', payload={'recovery_plan_id': 7},
)
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