- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更 - 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配 - 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定 - 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口 - 同步四语言文案、技术文档与实施计划
1788 lines
74 KiB
Python
1788 lines
74 KiB
Python
"""
|
||
用途:验证 RecoveryPlan 与库存准备谱系的结构化合同。
|
||
依赖:SQLAlchemy metadata、ShippingProcessRecoveryPlan、库存准备/Mapping 模型。
|
||
逻辑:只验证模型约束和关键状态字段,不触发外部 RPA 或业务恢复副作用。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
from sqlalchemy import UniqueConstraint
|
||
|
||
from app.models import (
|
||
ShippingInventoryMapping,
|
||
ShippingInventoryPreparationAttempt,
|
||
ShippingInventoryPreparationSourceAttempt,
|
||
ShippingOrderTask,
|
||
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,
|
||
ShippingOrderTask,
|
||
ShippingNoticeLineInventoryMatch,
|
||
ShippingOrderExtraction,
|
||
ShippingOrderSchema,
|
||
ShippingOrderSchemaVersion,
|
||
ShippingProcessExecution,
|
||
ShippingReservation,
|
||
ShippingUploadAttempt,
|
||
)
|
||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
|
||
|
||
owner = ShippingOrderTask(task_no='OT-EXCEL-REGEN-ONLY', user_id=1, source_type='direct_pdf')
|
||
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', order_task_id=None)
|
||
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([owner, task, template, profile, schema])
|
||
db.session.flush()
|
||
task.order_task_id = owner.id
|
||
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=owner.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=owner.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=owner.id, status='completed', result_json={})
|
||
match = ShippingNoticeLineInventoryMatch(
|
||
task_id=owner.id, snapshot_line_id=1, line_no=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 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_batch_trigger',
|
||
lambda run_no, sources, payload=None: captured.update(
|
||
{'run_no': run_no, 'sources': [dict(item) for item in sources], 'payload': dict(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['sources'][0]['execution_id'] == task.active_process_execution_id
|
||
assert captured['sources'][0]['gate_id'] == gate.id
|
||
assert captured['sources'][0]['callback_id'].endswith(':C1')
|
||
assert captured['sources'][0]['task_no'] == task.task_no
|
||
|
||
|
||
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_batch_trigger', lambda *args, **kwargs: None)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||
lambda code, **kwargs: {'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_requires_pre_frozen_facts(monkeypatch, app):
|
||
"""库存准备 Gate 不再补冻结或补做路由,缺少前置事实时直接阻断。"""
|
||
from app import db
|
||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||
from app.services.shipping_notice import process_gate_executor
|
||
|
||
task = ShippingOrderTask(task_no='OT-PREP-FREEZE-OPERATOR', user_id=1, source_type='direct_pdf')
|
||
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 == {}
|
||
assert result['outcome'] == 'blocked_retryable'
|
||
assert result['blocking_reason_code'] == 'inventory_source_routing_required'
|
||
|
||
|
||
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 ShippingOrderTask, ShippingTaskEvent
|
||
from app.services.shipping_notice import inventory_rpa_workflow
|
||
|
||
task = ShippingOrderTask(task_no='SNCALLBACKIDENTITYENTRY', user_id=1, source_type='direct_pdf')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
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 ShippingOrderTask
|
||
from app.services.shipping_notice import inventory_rpa_workflow
|
||
|
||
task = ShippingOrderTask(task_no='SN-2026-001', user_id=1, source_type='direct_pdf')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
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 ShippingOrderTask, ShippingTaskEvent
|
||
from app.services.shipping_notice import inventory_rpa_workflow
|
||
|
||
task = ShippingOrderTask(task_no='SNCALLBACKBATCHIDENTITY', user_id=1, source_type='direct_pdf')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
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['data']['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 = ShippingOrderTask(
|
||
task_no='OT-RPA-FAILED-GATE', user_id=1, source_type='direct_pdf',
|
||
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 (
|
||
ShippingInventoryFile,
|
||
ShippingOrderTask,
|
||
ShippingProcessGate,
|
||
ShippingProcessGateAttempt,
|
||
ShippingTaskInventoryLink,
|
||
)
|
||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||
|
||
task = ShippingOrderTask(
|
||
task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf',
|
||
pending_human_reason='rpa_exhausted',
|
||
)
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
inv_file = ShippingInventoryFile(
|
||
inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx',
|
||
source_file_name='inv.xlsx', snapshot_status='ready', line_count=1,
|
||
inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}],
|
||
mapping_confirmed=True,
|
||
)
|
||
db.session.add(inv_file)
|
||
db.session.flush()
|
||
db.session.add(ShippingTaskInventoryLink(
|
||
task_id=task.id, inventory_file_id=inv_file.id, is_active=True,
|
||
))
|
||
db.session.flush()
|
||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||
for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter(
|
||
ShippingProcessGate.execution_id == int(execution.id),
|
||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||
).all():
|
||
attempt.status = 'superseded'
|
||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||
if gate.gate_code == 'inventory_preparation':
|
||
gate.status = 'blocked_retryable'
|
||
gate.blocking_reason_code = 'inventory_rpa_exhausted'
|
||
gate.next_action_code = 'retry_inventory_preparation'
|
||
elif gate.gate_code in {'inventory_field_mapping', 'inventory_matching'}:
|
||
gate.status = 'pending'
|
||
gate.next_action_code = None
|
||
elif int(gate.sequence_no) < 13:
|
||
gate.status = 'passed'
|
||
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()
|
||
# 领域事实已有库存行时,不得把尚未执行的 matching 投影成 match_failed(--)。
|
||
assert matching.status != 'blocked_retryable'
|
||
assert matching.blocking_reason_code != 'inventory_match_failed'
|
||
assert matching.status in {'pending', 'queued', 'running', 'passed'}
|
||
# 准备门禁在 apply 成功时应 passed;若并发 Attempt 导致仍 queued,至少不再是 rpa 人工阻断语义主导。
|
||
if preparation.status == 'passed':
|
||
assert preparation.blocking_reason_code is None
|
||
|
||
|
||
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 ShippingOrderTask, 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 = ShippingOrderTask(task_no='OT-STALE-PREP-POLL', user_id=1, source_type='direct_pdf')
|
||
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_external_wait_poll_reuses_single_gate_attempt(app):
|
||
"""库存等待轮询只创建延迟 Job,不新增 Gate Attempt。"""
|
||
from datetime import datetime
|
||
|
||
from app import db
|
||
from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||
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 = ShippingOrderTask(task_no='OT-SINGLE-POLL-ATTEMPT', user_id=1, source_type='direct_pdf')
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
execution = ShippingProcessExecution(
|
||
execution_no='SPE-SINGLE-POLL-ATTEMPT', task_id=task.id, status='waiting_external',
|
||
current_gate_code='inventory_preparation',
|
||
)
|
||
db.session.add(execution)
|
||
db.session.flush()
|
||
gate = ShippingProcessGate(
|
||
execution_id=execution.id, gate_code='inventory_preparation', sequence_no=13,
|
||
status='waiting_external', effective_result_json={'waiting_since': datetime.utcnow().isoformat()},
|
||
)
|
||
db.session.add(gate)
|
||
db.session.flush()
|
||
attempt = queue_gate_attempt(
|
||
execution_no=execution.execution_no,
|
||
gate_code=gate.gate_code,
|
||
trigger_type='system_requeue', actor_type='system', actor_id='test',
|
||
idempotency_key='single-poll-attempt',
|
||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||
)
|
||
gate.status = 'waiting_external'
|
||
attempt.status = 'succeeded'
|
||
attempt.finished_at = datetime.utcnow()
|
||
db.session.flush()
|
||
|
||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is not None
|
||
db.session.flush()
|
||
|
||
assert ShippingProcessGateAttempt.query.filter_by(gate_id=gate.id).count() == 1
|
||
|
||
|
||
def test_cancel_inventory_external_wait_polls_cancels_only_queued_jobs(app):
|
||
"""库存重读失败必须立即取消未领取的延迟 poll,不影响正在执行的 Job。"""
|
||
from app import db
|
||
from app.jobs.types import JobType
|
||
from app.models import Job
|
||
from app.services.shipping_notice.process_gate_job_service import (
|
||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||
cancel_inventory_external_wait_polls,
|
||
)
|
||
|
||
queued = Job(
|
||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||
status='queued', business_ref='external-wait:1333:4', payload_json={'external_wait_poll_gate_id': 1333},
|
||
)
|
||
running = Job(
|
||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||
status='running', business_ref='external-wait:1333:3', payload_json={'external_wait_poll_gate_id': 1333},
|
||
)
|
||
other = Job(
|
||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||
status='queued', business_ref='external-wait:1334:1', payload_json={'external_wait_poll_gate_id': 1334},
|
||
)
|
||
db.session.add_all([queued, running, other])
|
||
db.session.flush()
|
||
|
||
assert cancel_inventory_external_wait_polls(gate_id=1333, reason='reload missing') == 1
|
||
db.session.flush()
|
||
db.session.refresh(queued)
|
||
db.session.refresh(running)
|
||
db.session.refresh(other)
|
||
assert queued.status == 'cancelled'
|
||
assert running.status == 'running'
|
||
assert other.status == 'queued'
|
||
|
||
|
||
def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch):
|
||
"""已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。"""
|
||
from app import db
|
||
from app.models import (
|
||
ShippingInventoryCandidateSet,
|
||
ShippingInventoryCandidateSource,
|
||
ShippingInventoryPreparationAttempt,
|
||
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 = ShippingOrderTask(
|
||
task_no='OT-POLL-KEEPS-RPA-TIMEOUT', user_id=1,
|
||
pending_human_reason='inv_unavail', order_snapshot_id=1,
|
||
)
|
||
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
|
||
# 上一轮准备已裁决并冻结库存源候选:poll 前置的补裁决必须被跳过,否则
|
||
# adjudicate_and_apply_inventory_source 会新创建/替换 CandidateSet 并把
|
||
# execution.candidate_set_id 刷新为新的 id(≠ 本轮失败 Preparation 的 candidate_set_id),
|
||
# 导致 failed_preparation 过滤不到而误调 RPA。
|
||
candidate = ShippingInventoryCandidateSet(
|
||
task_id=task.id, set_version=1, lifecycle_status='frozen',
|
||
input_fingerprint='b' * 64,
|
||
)
|
||
db.session.add(candidate)
|
||
db.session.flush()
|
||
db.session.add(ShippingInventoryCandidateSource(
|
||
candidate_set_id=candidate.id, source_code='DSV360_AWSDU',
|
||
candidate_order=1, candidate_origin='rule',
|
||
))
|
||
from app.models import ShippingInventoryCandidateLine
|
||
db.session.add(ShippingInventoryCandidateLine(
|
||
candidate_set_id=candidate.id, line_no=1, source_codes_json=['DSV360_AWSDU'],
|
||
))
|
||
db.session.flush()
|
||
task.active_inventory_candidate_set_id = candidate.id
|
||
execution.candidate_set_id = candidate.id
|
||
preparation = ShippingInventoryPreparationAttempt(
|
||
task_id=task.id,
|
||
execution_id=execution.id,
|
||
attempt_no=1,
|
||
status='failed',
|
||
candidate_set_id=candidate.id,
|
||
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,
|
||
ShippingInventoryCandidateSource,
|
||
ShippingInventoryPreparationAttempt,
|
||
ShippingOrderTask,
|
||
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 = ShippingOrderTask(
|
||
task_no='OTFORMALPREPLINEAGE',
|
||
user_id=1,
|
||
source_type='direct_pdf',
|
||
# 该用例从 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()
|
||
db.session.add(ShippingInventoryCandidateSource(
|
||
candidate_set_id=candidate.id, source_code='DBS', candidate_order=1, candidate_origin='rule',
|
||
))
|
||
from app.models import ShippingInventoryCandidateLine
|
||
db.session.add(ShippingInventoryCandidateLine(
|
||
candidate_set_id=candidate.id, line_no=1, source_codes_json=['DBS'],
|
||
))
|
||
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 (
|
||
ShippingCustomerShadowResolution,
|
||
ShippingInventoryCandidateSet,
|
||
ShippingOrderCandidate,
|
||
ShippingOrderIntake,
|
||
ShippingOrderTask,
|
||
)
|
||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||
|
||
intake = ShippingOrderIntake(
|
||
intake_no='INT-START-CUSTOMER-PENDING', asset_id=1, user_id=1, parser_version='test',
|
||
)
|
||
db.session.add(intake)
|
||
db.session.flush()
|
||
order_candidate = ShippingOrderCandidate(
|
||
candidate_no='CAND-START-CUSTOMER-PENDING', intake_id=intake.id,
|
||
primary_document_id=1, candidate_key='start-customer-pending', candidate_status='accepted',
|
||
)
|
||
db.session.add(order_candidate)
|
||
db.session.flush()
|
||
task = ShippingOrderTask(
|
||
task_no='OTSTARTCUSTOMERPENDING',
|
||
user_id=1,
|
||
source_type='direct_pdf',
|
||
current_order_extraction_id=101,
|
||
order_snapshot_id=201,
|
||
candidate_id=order_candidate.id,
|
||
)
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
db.session.add(ShippingCustomerShadowResolution(
|
||
candidate_id=order_candidate.id,
|
||
intake_id=intake.id,
|
||
resolution_version='test.v1',
|
||
status='failed',
|
||
evidence_json=[],
|
||
candidate_matches_json=[],
|
||
resolution_context_json={},
|
||
))
|
||
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, ShippingOrderTask, ShippingTaskFieldConflict
|
||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||
|
||
task = ShippingOrderTask(
|
||
task_no='OTSTARTFIELDCONFLICT',
|
||
user_id=1,
|
||
source_type='direct_pdf',
|
||
current_order_extraction_id=101,
|
||
order_snapshot_id=201,
|
||
)
|
||
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 ShippingOrderTask, ShippingTaskEvent
|
||
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
|
||
|
||
task = ShippingOrderTask(task_no='OTLEGACYFORWARDAUDIT', user_id=1, source_type='direct_pdf')
|
||
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_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_process_execution_projection_batch_loads_latest_attempts(app):
|
||
"""serialize_process_execution 必须批量预取 LatestAttempt 并写入会话读缓存,避免逐 Gate N+1。"""
|
||
from app import db
|
||
from app.models import (
|
||
ShippingProcessExecution,
|
||
ShippingProcessGate,
|
||
ShippingProcessGateAttempt,
|
||
)
|
||
from app.services.shipping_notice.process_gate_projection import serialize_process_execution
|
||
|
||
with app.app_context():
|
||
execution = ShippingProcessExecution(
|
||
execution_no='EXE-BATCH-ATTEMPT', status='blocked',
|
||
current_gate_code='inventory_matching', lock_version=1,
|
||
)
|
||
db.session.add(execution)
|
||
db.session.flush()
|
||
gate = ShippingProcessGate(
|
||
execution_id=execution.id, gate_code='inventory_matching', sequence_no=15,
|
||
status='blocked_manual', evaluation_version=2,
|
||
)
|
||
db.session.add(gate)
|
||
db.session.flush()
|
||
attempt = ShippingProcessGateAttempt(
|
||
gate_id=gate.id, attempt_no=1, status='failed',
|
||
idempotency_key='exec-batch-attempt-1',
|
||
)
|
||
db.session.add(attempt)
|
||
db.session.flush()
|
||
# 把 Gate 的最新 attempt 指针指向该 attempt。
|
||
gate.latest_attempt_id = attempt.id
|
||
db.session.flush()
|
||
|
||
# 先清除任何遗留的会话读缓存,模拟工作台路径(ui_state 不预置缓存)。
|
||
db.session.info.pop('shipping_conversation_projection_read_cache', None)
|
||
projection = serialize_process_execution(execution)
|
||
|
||
# 调用后应把本 Execution 的 gates + latest_attempt 写入读缓存。
|
||
cache = db.session.info.get('shipping_conversation_projection_read_cache') or {}
|
||
gates_by_execution = cache.get('gates_by_execution_id', {})
|
||
latest_by_id = cache.get('latest_attempt_by_id', {})
|
||
assert int(execution.id) in gates_by_execution
|
||
assert any(gate.id == g.id for g in gates_by_execution[int(execution.id)])
|
||
# current_gate 的 latest 信息必须命中缓存里预取的 attempt,而不是触发额外的 query.get()。
|
||
current_gate_latest = projection.get('current_gate', {}).get('latest_attempt')
|
||
# 未提供 attempt snapshot / error 时也可能为 None;关键断言是缓存已填充。
|
||
assert int(attempt.id) in latest_by_id
|
||
|
||
|
||
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_delegates_artifact_lock_to_generate_excel(monkeypatch):
|
||
"""已有 Excel 时由 generate_excel 拒绝重生;Gate 执行器不再自身预检 Artifact。
|
||
|
||
[断言] regenerate_excel_artifact 只负责以内部编排标记委派 generate_excel 并转发其门禁结果;
|
||
已生成裁决由 generate_excel 返回,不在 Gate 执行器层重复预检。
|
||
"""
|
||
from types import SimpleNamespace
|
||
from app.models import ShippingOrderTask
|
||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||
|
||
task = SimpleNamespace(id=1, task_no='OT-ONE-EXCEL')
|
||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||
captured: dict = {}
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||
lambda payload: captured.update(payload) or {
|
||
'status': 'blocked',
|
||
'error_code': 'notice_excel_already_generated',
|
||
'message': '通知 Excel 已生成,请创建新的通知单',
|
||
},
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||
lambda **kwargs: None,
|
||
)
|
||
|
||
outcome = _handle_regenerate_excel(
|
||
execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1),
|
||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||
payload={'actor_user_id': 9},
|
||
)
|
||
|
||
# 关键断言:已生成裁决由 generate_excel 表达,执行器携内部编排标记委派并转发结果。
|
||
assert captured['_orchestrator_internal_dispatch'] is True
|
||
assert outcome['outcome'] == 'blocked_retryable'
|
||
assert outcome['blocking_reason_code'] == 'artifact_generation_failed'
|
||
|
||
|
||
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
|
||
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
|
||
from types import SimpleNamespace
|
||
from app.models import ShippingExportArtifact, ShippingOrderTask
|
||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||
|
||
synced = []
|
||
task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL')
|
||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||
monkeypatch.setattr(
|
||
ShippingExportArtifact,
|
||
'query',
|
||
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: None)),
|
||
)
|
||
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(
|
||
id=13,
|
||
match_status='partial',
|
||
shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]},
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.models.ShippingOrderTask.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},
|
||
)
|
||
# 门禁重匹配按当前行级匹配事实推导:匹配完成(有缺口)→ 缺口归属满足性 Gate。
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete',
|
||
lambda _task: True,
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.fulfillment_workflow.match_completed',
|
||
lambda _task: False,
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task',
|
||
lambda _task_id: {1: {'available_qty': 14, 'shortage_qty': 16}},
|
||
)
|
||
|
||
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'][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.ShippingOrderTask.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_rejects_legacy_task_without_snapshot(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.ShippingOrderTask.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 == {}
|
||
assert task.order_snapshot_id is None
|
||
assert result['outcome'] == 'blocked_retryable'
|
||
assert result['blocking_reason_code'] == 'inventory_source_routing_required'
|
||
|
||
|
||
def test_inventory_preparation_mode_maps_by_action_code(monkeypatch):
|
||
"""库存准备执行器按已有动作码映射 ensure_inventory mode,禁止人工入口一律 retry_rpa。"""
|
||
from types import SimpleNamespace
|
||
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
|
||
|
||
task = SimpleNamespace(id=1, order_snapshot_id=10, task_no='SN-MODE-MAP')
|
||
captured: list[dict] = []
|
||
line = SimpleNamespace(source_codes_json=['DBS'])
|
||
candidate_set = SimpleNamespace(id=1)
|
||
sources = [SimpleNamespace(source_code='DBS')]
|
||
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||
lambda _execution: task,
|
||
)
|
||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact + 候选源刷新前置(查库)依赖;
|
||
# 本用例聚焦动作码→mode 映射,打桩为「Excel 已生成」使刷新块短路,隔离刷新链副作用。
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||
lambda _task: SimpleNamespace(id=77),
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||
lambda _task: candidate_set,
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||
lambda _task: [line],
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||
lambda _task: sources,
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||
lambda **_: None,
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
|
||
lambda **_: {},
|
||
)
|
||
monkeypatch.setattr(
|
||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||
lambda payload: captured.append(dict(payload)) or {'status': 'running', 'data': {'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, '_orchestrator_internal_dispatch': True},
|
||
)
|
||
# poll 路径会查失败 Attempt;无失败行时继续 ensure_inventory。
|
||
monkeypatch.setattr(
|
||
'app.models.ShippingInventoryPreparationAttempt.query',
|
||
SimpleNamespace(
|
||
filter_by=lambda **_: SimpleNamespace(
|
||
filter=lambda *_a, **_k: SimpleNamespace(
|
||
order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||
),
|
||
order_by=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||
),
|
||
),
|
||
)
|
||
|
||
execution = SimpleNamespace(task_id=1, id=21, candidate_set_id=None)
|
||
gate = SimpleNamespace(gate_code='inventory_preparation')
|
||
|
||
captured.clear()
|
||
_handle_retry_inventory_preparation(
|
||
execution=execution, gate=gate,
|
||
payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5},
|
||
)
|
||
# 显式强制 RPA 码 → mode=retry_rpa。
|
||
assert captured[-1].get('mode') == 'retry_rpa'
|
||
|
||
captured.clear()
|
||
_handle_retry_inventory_preparation(
|
||
execution=execution, gate=gate,
|
||
payload={'action_code': 'poll_inventory_preparation', 'actor_user_id': 5},
|
||
)
|
||
# 只读轮询:默认 auto,禁止自动再试。
|
||
assert captured[-1].get('mode') in (None, 'auto')
|
||
assert captured[-1].get('allow_auto_retry') is False
|
||
|
||
captured.clear()
|
||
_handle_retry_inventory_preparation(
|
||
execution=execution, gate=gate,
|
||
payload={
|
||
'action_code': 'retry_inventory_preparation',
|
||
'trigger': 'gate_attempt_passed',
|
||
'actor_user_id': 5,
|
||
},
|
||
)
|
||
# 首次自动投递:不强制 retry_rpa,保留默认 auto(先复用快照)。
|
||
assert captured[-1].get('mode') in (None, 'auto')
|
||
|
||
|
||
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
|