test(shipping): 更新订单复核库存与通知流程测试
This commit is contained in:
1 parent
8ec028e6a3
commit
265a6e179a
168 files changed
+9420
-4613
No files matched your search
@@ -13,6 +13,7 @@ from app.models import (
|
||||
ShippingInventoryMapping,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessRecoveryPlan,
|
||||
)
|
||||
|
||||
@@ -43,6 +44,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
@@ -53,7 +55,8 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
)
|
||||
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')
|
||||
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',
|
||||
@@ -64,7 +67,9 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
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.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={},
|
||||
@@ -75,7 +80,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
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',
|
||||
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=owner.id, status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
)
|
||||
db.session.add_all([extraction, execution])
|
||||
@@ -88,14 +93,14 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
status='ready',
|
||||
)
|
||||
reservation = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
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=task.id, status='completed', result_json={})
|
||||
verification = ShippingInventoryVerification(task_id=owner.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,
|
||||
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()
|
||||
@@ -126,8 +131,6 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
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
|
||||
|
||||
@@ -276,8 +279,10 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
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',
|
||||
'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'])
|
||||
@@ -285,9 +290,11 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
|
||||
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')
|
||||
# 逐源身份键现在随批次条目投递;顶层仅保留批次级载荷。
|
||||
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):
|
||||
@@ -302,10 +309,10 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
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(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: {'source_code': code, 'warehouse_id': 'WH-1'},
|
||||
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 == []
|
||||
@@ -319,16 +326,13 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
|
||||
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。"""
|
||||
def test_formal_gate_inventory_retry_requires_pre_frozen_facts(monkeypatch, app):
|
||||
"""库存准备 Gate 不再补冻结或补做路由,缺少前置事实时直接阻断。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution
|
||||
from app.models import ShippingOrderTask, 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,
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-PREP-FREEZE-OPERATOR', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
@@ -361,8 +365,9 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
|
||||
execution=execution, gate=gate,
|
||||
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
|
||||
)
|
||||
assert seen['actor_id'] == 77
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
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):
|
||||
@@ -431,11 +436,12 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
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.models import ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY')
|
||||
task = ShippingOrderTask(task_no='SNCALLBACKIDENTITYENTRY', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -482,11 +488,12 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app,
|
||||
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.models import ShippingOrderTask
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SN-2026-001')
|
||||
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 = {}
|
||||
|
||||
@@ -518,11 +525,12 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
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.models import ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
|
||||
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY')
|
||||
task = ShippingOrderTask(task_no='SNCALLBACKBATCHIDENTITY', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -551,7 +559,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
}],
|
||||
})
|
||||
|
||||
assert response['failed_count'] == 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(
|
||||
@@ -588,8 +596,8 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
|
||||
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',
|
||||
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)
|
||||
@@ -638,16 +646,33 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
|
||||
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.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-LATE-SUCCESS',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf',
|
||||
pending_human_reason='rpa_exhausted',
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}],
|
||||
)
|
||||
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'}],
|
||||
)
|
||||
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 = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
@@ -675,12 +700,12 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
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 = ShippingNotice(task_no='SN-STALE-PREP-POLL')
|
||||
task = ShippingOrderTask(task_no='OT-STALE-PREP-POLL', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
@@ -709,12 +734,93 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
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,
|
||||
ShippingNotice,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
@@ -725,7 +831,10 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail')
|
||||
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(
|
||||
@@ -733,11 +842,33 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp
|
||||
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={},
|
||||
)
|
||||
@@ -791,8 +922,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
)
|
||||
@@ -802,9 +934,10 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNFORMALPREPLINEAGE',
|
||||
inventory_source_code='DBS',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OTFORMALPREPLINEAGE',
|
||||
user_id=1,
|
||||
source_type='direct_pdf',
|
||||
# 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。
|
||||
order_snapshot_id=1,
|
||||
)
|
||||
@@ -815,6 +948,14 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
)
|
||||
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
|
||||
@@ -875,17 +1016,46 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
|
||||
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.models import (
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTCUSTOMERPENDING',
|
||||
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,
|
||||
customer_resolution_status='pending',
|
||||
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,
|
||||
)
|
||||
@@ -898,14 +1068,15 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
|
||||
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.models import ShippingInventoryCandidateSet, ShippingOrderTask, ShippingTaskFieldConflict
|
||||
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SNSTARTFIELDCONFLICT',
|
||||
task = ShippingOrderTask(
|
||||
task_no='OTSTARTFIELDCONFLICT',
|
||||
user_id=1,
|
||||
source_type='direct_pdf',
|
||||
current_order_extraction_id=101,
|
||||
order_snapshot_id=201,
|
||||
customer_resolution_status='confirmed',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -972,10 +1143,10 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app):
|
||||
def test_legacy_workspace_forwarding_audit_is_structured(app):
|
||||
"""旧工作台动作转发必须留下 legacy_forwarded 入口审计。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
|
||||
|
||||
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT')
|
||||
task = ShippingOrderTask(task_no='OTLEGACYFORWARDAUDIT', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
@@ -1131,22 +1302,30 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan():
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch):
|
||||
"""已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。"""
|
||||
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 ShippingExportArtifact, ShippingNotice
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL')
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
ShippingExportArtifact,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))),
|
||||
)
|
||||
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: pytest.fail('existing Artifact must not be regenerated'),
|
||||
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(
|
||||
@@ -1155,19 +1334,21 @@ def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch):
|
||||
payload={'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_manual'
|
||||
assert outcome['blocking_reason_code'] == 'notice_excel_already_generated'
|
||||
# 关键断言:已生成裁决由 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, ShippingNotice
|
||||
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(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
monkeypatch.setattr(
|
||||
ShippingExportArtifact,
|
||||
'query',
|
||||
@@ -1254,11 +1435,12 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
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.ShippingNotice.query',
|
||||
'app.models.ShippingOrderTask.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -1273,6 +1455,19 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
'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),
|
||||
@@ -1284,7 +1479,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
# 不能把业务缺口回写成 inventory_matching 的技术失败。
|
||||
assert result['outcome'] == 'passed'
|
||||
assert 'blocking_reason_code' not in result
|
||||
assert result['effective_result_json']['shortage']['lines'][0] == {
|
||||
assert result['effective_result_json']['shortage'][0] == {
|
||||
'available_qty': 14,
|
||||
'shortage_qty': 16,
|
||||
}
|
||||
@@ -1355,7 +1550,7 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa
|
||||
|
||||
task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH')
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingNotice.query',
|
||||
'app.models.ShippingOrderTask.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
|
||||
@@ -1370,8 +1565,8 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa
|
||||
assert result['operator_id'] == 9
|
||||
|
||||
|
||||
def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch):
|
||||
"""旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。"""
|
||||
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
|
||||
|
||||
@@ -1382,7 +1577,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
|
||||
)
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
'app.models.ShippingNotice.query',
|
||||
'app.models.ShippingOrderTask.query',
|
||||
SimpleNamespace(get=lambda _task_id: task),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -1420,15 +1615,11 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
|
||||
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'
|
||||
# 关键断言:正式 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_manual_business_block_is_a_successful_attempt(app):
|
||||
|
||||
Reference in new issue
Block a user