refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段

统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
hugo committed 2026-08-15 10:19:10 +08:00
1 parent 6684e7181a
commit 5ef8329bd8
178 files changed
+5091 -1734

No files matched your search

@@ -26,7 +26,6 @@ from app.services.shipping_notice.stp_line_inventory_match import prepare_candid
def _task(task_no: str) -> ShippingNotice:
task = ShippingNotice(
task_no=task_no,
process_status='created',
source_type='manual',
)
db.session.add(task)
@@ -19,7 +19,7 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py
b) legacy_job_id=999 + is_admin=False → 422
[P4 T7] ownership_anomaly BRANCH F:
断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写
(这里只测 ValidationError 降级情形 hasattr(case,process_status)=False)。
(这里只测 ValidationError 降级情形,Review Case 不含旧流程字段)。
全部为 pure_unit 或 DB 无关单测,不启动 Flask/Worker,不写 DB。
"""
@@ -336,7 +336,7 @@ def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch):
# ============================================================
# [P4 T7] BRANCH F ownership_anomaly 422 降级(process_status 不存在)
# [P4 T7] BRANCH F ownership_anomaly 422 降级(Review Case 不含旧流程字段)
# ============================================================
@pytest.mark.pure_unit
@@ -363,8 +363,7 @@ def test_p4_t7_branch_f_ownership_anomaly_throws_validation(monkeypatch):
{'step': 'L3_AMBIGUOUS', 'matched': True},
],
}
# 关键:模拟 ReviewCase 没有 process_status 列 → BRANCH F 必须抛 422(而非软返回 outcome)
assert not hasattr(case, 'process_status')
# 关键:Review Case 不含旧流程字段 → BRANCH F 必须抛 422(而非软返回 outcome)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
@@ -522,7 +522,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
db.session.flush()
task = ShippingNotice(
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
source_type='manual', process_status='parsed', customer_resolution_status='pending',
source_type='manual', customer_resolution_status='pending',
)
db.session.add(task)
db.session.commit()
@@ -111,7 +111,6 @@ def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch
user_id=user.id,
conversation_id='conv-shipping-start-001',
source_type='manual',
process_status='created',
)
db.session.add(task)
db.session.commit()
-1
View File
@@ -57,7 +57,6 @@ def _create_task_for_user(user_id: int) -> str:
task_no="SN-20260706-ABCD1234",
user_id=user_id,
source_type="manual",
process_status="created",
)
db.session.add(task)
db.session.commit()
@@ -152,7 +152,7 @@ def test_waiting_inventory_maps_to_inventory_fetching_stage():
)
status, stage = map_notice_to_processing_status_stage(
SimpleNamespace(process_status='waiting_inventory', current_step=None, export_file_path=None),
SimpleNamespace(current_step=None, export_file_path=None),
)
assert status == 'automating'
assert stage == 'inventory_fetching'
@@ -30,7 +30,7 @@ from app.services.shipping_notice.process_gate_service import ensure_execution_f
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
task = ShippingNotice(task_no='APX-P0-3-001', process_status='created')
task = ShippingNotice(task_no='APX-P0-3-001')
db.session.add(task)
db.session.flush()
candidate = ShippingInventoryCandidateSet(
@@ -37,7 +37,6 @@ def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
shipping_case_id=case.id,
customer_resolution_status="pending",
source_type="manual",
process_status="parsed",
)
db.session.add(task)
db.session.commit()
@@ -79,7 +78,6 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
supersedes_task_id=task.id,
customer_resolution_status="confirmed",
source_type="manual",
process_status="parsed",
)
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
db.session.add_all([revision, forced_case])
@@ -89,7 +87,6 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
shipping_case_id=forced_case.id,
customer_resolution_status="pending",
source_type="manual",
process_status="parsed",
)
db.session.add(forced_task)
db.session.commit()
@@ -157,7 +154,6 @@ def test_business_number_query_returns_latest_revision(app):
document_version=2,
customer_resolution_status="confirmed",
source_type="manual",
process_status="parsed",
)
db.session.add(revision)
db.session.commit()
@@ -32,7 +32,6 @@ def _create_task(user_id: int) -> str:
batch=batch,
user_id=user_id,
source_type="manual",
process_status="matched",
match_status="ok",
)
db.session.add_all([batch, task])
@@ -127,7 +127,7 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
db.session.flush()
task = ShippingNotice(
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
user_id=user.id, source_type="email_attachment", process_status="parsed",
user_id=user.id, source_type="email_attachment",
customer_resolution_status="pending",
)
db.session.add(task)
@@ -418,13 +418,13 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
db.session.flush()
first = ShippingNotice(
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
source_type="manual", process_status="parsed", customer_resolution_status="pending",
source_type="manual", customer_resolution_status="pending",
)
db.session.add(first)
db.session.flush()
latest = ShippingNotice(
task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2,
supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload",
supersedes_task_id=first.id, source_type="manual", upload_status="pending",
customer_resolution_status="pending", inventory_source_code="DSV",
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
match_status="fulfillable", line_results_json=[{"sku": "A"}],
@@ -457,7 +457,7 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
assert latest.inventory_source_status is None
assert latest.inventory_lines_json is None
assert latest.export_file_path is None
assert latest.process_status == "parsed"
assert latest.source_type == "manual"
assert get_task_by_ref(old_business_no).id == latest.id
assert get_task_by_ref(replacement.business_no).id == latest.id
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
@@ -476,7 +476,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
db.session.flush()
task = ShippingNotice(
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
source_type="manual", process_status="parsed", customer_resolution_status="pending",
source_type="manual", customer_resolution_status="pending",
)
db.session.add(task)
db.session.commit()
@@ -487,7 +487,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
db.session.rollback()
task.process_status = "uploaded"
task.upload_status = "uploaded"
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
@@ -47,7 +47,6 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto
task_no=f'SN-GATE-{user.id}', user_id=user.id,
shipping_case_id=case.id if case else None,
customer_resolution_status='pending' if case else None,
process_status='parsed',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
inventory_source_status='user_confirmed', inventory_source_code='DSV',
)
@@ -119,7 +118,6 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
revision = ShippingNotice(
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
process_status='parsed',
)
db.session.add(revision)
db.session.commit()
@@ -110,7 +110,7 @@ def test_inventory_preparation_reason_code_from_pending():
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
upload_failed = SimpleNamespace(
id=None, pending_human_reason='upload_rpa_failed', process_status='upload_failed',
id=None, pending_human_reason='upload_rpa_failed',
)
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
@@ -22,7 +22,6 @@ def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int |
shipping_case_id=case_id,
supersedes_task_id=supersedes_task_id,
source_type='manual',
process_status='created',
)
@@ -189,7 +189,6 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
task_no='SN-PENDING-1',
user_id=dedup_user.id,
source_type='manual',
process_status='pending_review',
business_fingerprint=fp['fingerprint'],
fingerprint_version=fp['version'],
document_version=1,
@@ -225,7 +224,6 @@ def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
intake.duplicate_matches_json = [
{
'task_no': 'SN-OLD',
'process_status': 'waiting_inventory',
'document_version': 1,
'match_type': 'weak_fingerprint',
'matched_fields': ['line_digest'],
@@ -256,7 +254,6 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
task_no='SN-EXISTING-PO-A',
user_id=dedup_user.id,
source_type='manual',
process_status='pending_review',
business_fingerprint=existing_fp['fingerprint'],
fingerprint_version=existing_fp['version'],
source_content_hash='hash-other-file',
@@ -379,7 +376,6 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
task_no='SN-REFRESH-EXISTING',
user_id=dedup_user.id,
source_type='manual',
process_status='pending_review',
business_fingerprint=existing_fp['fingerprint'],
fingerprint_version=existing_fp['version'],
source_content_hash='hash-refresh-other',
@@ -487,7 +483,6 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
task_no='SN-CONTENT-EXISTING',
user_id=dedup_user.id,
source_type='manual',
process_status='pending_review',
business_fingerprint=identity['fingerprint'],
fingerprint_version=identity['version'],
content_fingerprint=content['fingerprint'],
@@ -149,7 +149,6 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
task_no='SN-CANDIDATE-EXISTING-001',
user_id=owner.id,
source_content_hash=asset.content_hash,
process_status='created',
)
db.session.add_all([document, existing])
db.session.flush()
@@ -224,7 +223,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
with app.app_context():
db.session.add(ShippingNotice(
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
source_content_hash='candidate-api-content-hash', process_status='created',
source_content_hash='candidate-api-content-hash',
))
db.session.commit()
@@ -582,7 +581,7 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
task_no='SN-REV-LOCK-BASE',
user_id=shipping_user.id,
source_type='manual',
process_status='uploaded',
upload_status='uploaded',
document_version=1,
)
db.session.add(base)
@@ -591,7 +590,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
task_no='SN-REV-LOCK-V2',
user_id=shipping_user.id,
source_type='manual',
process_status='pending_review',
document_version=2,
supersedes_task_id=base.id,
duplicate_resolution_type='revision',
@@ -315,7 +315,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
with app.app_context():
task = ShippingNotice(
task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory',
task_no='SN-MANUAL-PROFILE-001', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
)
_confirm_direct_rpa_task_customer(task)
@@ -332,7 +332,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
assert result['status'] == 'ok'
assert result['checkpoint'] == 'ready_to_match'
assert task.process_status == 'inventory_ready'
assert task.inventory_snapshot_id is not None
assert task.review_status is None
assert task.pending_human_reason is None
snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id)
@@ -366,7 +366,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
with app.app_context():
task = ShippingNotice(
task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory',
task_no='SN-MANUAL-DRIFT-001', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
)
_confirm_direct_rpa_task_customer(task)
@@ -564,7 +564,6 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
task = ShippingNotice(
task_no="SN-CONFIRM-SOURCE-RPA",
source_type="pdf",
process_status="pending_review",
current_step="step2_parse_confirm",
pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
@@ -589,7 +588,7 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
db.session.refresh(task)
assert result["status"] == "ok"
assert "库存源已确认" in result["message"]
assert task.process_status == "parsed"
assert task.pending_human_reason is None
assert task.pending_human_reason is None
assert task.error_message is None
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
@@ -615,7 +614,6 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
task = ShippingNotice(
task_no="SN-BATCH-RUNNO",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -643,7 +641,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
assert result["status"] == "ok"
assert result["success_count"] == 1
assert task.process_status == "inventory_ready"
assert task.inventory_snapshot_id is not None
def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
@@ -660,7 +658,6 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
task = ShippingNotice(
task_no="SN-BATCH-FAIL-TASK",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -686,7 +683,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.error_message
failed_events = ShippingTaskEvent.query.filter_by(
task_id=task.id,
@@ -704,7 +701,6 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
task = ShippingNotice(
task_no="SN-FAIL-NO-IDENT",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -815,7 +811,6 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
task = ShippingNotice(
task_no="SN-BATCH-NO-IDENT",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -838,7 +833,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch):
@@ -883,7 +878,6 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
task = ShippingNotice(
task_no="SN-REUSE-INGEST-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -910,7 +904,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
assert snap_after.snapshot_status == "ready"
assert Path(snap_after.storage_path).is_file()
assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
@@ -999,14 +993,12 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
task_a = ShippingNotice(
task_no="SN-BATCH-OK",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
task_b = ShippingNotice(
task_no="SN-BATCH-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
)
@@ -1018,7 +1010,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
seed_rpa_inventory_trigger(task_b, run_no=run_no)
db.session.add_all([task_a, task_b])
db.session.commit()
before_b_status = task_b.process_status
before_b_status = task_b.pending_human_reason
result = rpa_report_inventory_batch({
"run_no": run_no,
@@ -1045,7 +1037,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
assert result["failed_count"] == 1
assert task_a.inventory_rpa_consumed_run_no == run_no
assert task_b.inventory_rpa_consumed_run_no is None
assert task_b.process_status == before_b_status
assert task_b.pending_human_reason == before_b_status
def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, monkeypatch):
@@ -1065,14 +1057,12 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
task_ok = ShippingNotice(
task_no="SN-SHARED-OK",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
task_fail = ShippingNotice(
task_no="SN-SHARED-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
)
@@ -1154,7 +1144,6 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
task = ShippingNotice(
task_no="SN-POST-COMMIT-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -1199,7 +1188,6 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
task = ShippingNotice(
task_no="SN-PROMOTE-FAIL-REBUILD",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
@@ -1237,7 +1225,6 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
task = ShippingNotice(
task_no="SN-REPAIR-ATTACH",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -1395,7 +1382,6 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
task = ShippingNotice(
task_no="SN-REPAIR-REJECT",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -630,7 +630,7 @@ def test_order_field_display_uses_current_catalog_sequence(app):
).all():
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
task = ShippingNotice(
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual',
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
)
db.session.add(task)
@@ -908,7 +908,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
task_no='SN-ORDER-EXISTING-001',
user_id=int(user.id),
source_type='manual',
process_status='waiting_inventory',
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
)
db.session.add(existing)
db.session.flush()
@@ -926,7 +926,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{
'task_no': existing.task_no,
'process_status': existing.process_status,
'match_status': existing.match_status,
'match_type': 'business_fingerprint',
}],
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
@@ -1046,7 +1046,6 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
source_type='manual',
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
error_message='解析失败:未识别到 Reservation ID',
@@ -1099,7 +1098,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
assert values['part_number'] == 'P123456'
assert values['qty'] == 24
assert values['reservation_id'] == '1000140351'
assert existing.process_status == 'pending_review'
assert existing.review_status == 'rsv_req'
assert existing.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (existing.step_payload_json or {})
assert existing.error_message is None
@@ -1198,7 +1197,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
@pytest.mark.parametrize(
'task_overrides',
[
{'process_status': 'waiting_inventory'},
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]},
{'match_status': 'matched'},
{'export_file_path': '/tmp/shipment.xlsx'},
@@ -1211,7 +1210,6 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}",
'po_number': '4510038672',
'source_type': 'manual',
'process_status': 'pending_review',
'review_status': 'rsv_req',
'pending_human_reason': 'rsv_req',
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
@@ -1256,7 +1254,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
task_no='SN-RSV-BACKFILL-CONFLICT',
po_number='4510038672',
source_type='manual',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
@@ -1265,7 +1262,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
po_number='4510038672',
source_type='manual',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[
@@ -1277,7 +1273,6 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET',
po_number='4510038672',
source_type='manual',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24}],
@@ -1327,7 +1322,6 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
po_number='4510038672',
source_type='manual',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
@@ -1369,7 +1363,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
source_type='manual',
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='waiting_inventory',
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
@@ -1400,7 +1394,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
assert result['pending_count'] == 0
assert candidate.consumed_task_id == int(existing.id)
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}]
assert existing.process_status == 'waiting_inventory'
assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}]
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
@@ -1444,7 +1438,6 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
source_type='manual',
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
@@ -24,12 +24,37 @@ from app.services.shipping_notice.query_service import (
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
def test_chat_match_result_payload_uses_unified_actions_only():
"""Chat 匹配结果不得再把旧 action_buttons 作为按钮来源。"""
from app.services.shipping_notice.chat_action_handlers import _match_result_payload
payload = _match_result_payload(
"SN-ACTIONS-ONLY",
{
"data": {
"match_status": "shortage",
"line_results": [],
"shortage": {"lines": []},
},
"action_buttons": [{"id": "legacy_retry"}],
"ui_state": {
"actions": {
"primary": {"code": "open_shortage_review", "enabled": True},
"secondary": [],
},
},
},
)
assert payload["actions"]["primary"]["code"] == "open_shortage_review"
assert "action_buttons" not in payload
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
"""task_no 与数字主键均应能解析到同一任务。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-TEST-QUERY-001",
process_status="created",
source_type="manual",
)
from app import db
@@ -47,28 +72,28 @@ def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
"""库存缺口筛选应读取复核状态,而不是要求不存在的 process_status。"""
"""库存缺口筛选应读取领域事实和复核状态。"""
with app.app_context():
from app import db
shortage = ShippingNotice(
task_no="SN-FILTER-SHORTAGE",
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
user_id=999999,
)
ordinary = ShippingNotice(
task_no="SN-FILTER-PARSE",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=2,
)
db.session.add_all([shortage, ordinary])
db.session.commit()
rows = list_tasks_for_user(999999, process_status="shortage_review")
rows = list_tasks_for_user(999999)
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"]
@@ -79,7 +104,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
from app import db
db.session.add_all([
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual")
for index in range(1, 6)
])
db.session.commit()
@@ -105,13 +130,13 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
from app import db
db.session.add_all([
ShippingNotice(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"),
])
db.session.commit()
result = list_tasks_page_for_user(999999, process_status="created", page=1, page_size=10)
result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10)
# 关键断言:uploaded 任务既不在 items 中,也不计入总数。
assert result["total"] == 2
@@ -123,12 +148,11 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
def test_task_export_error_message_distinct_for_missing_path(app):
"""无导出路径与磁盘缺失应返回不同错误文案。"""
with app.app_context():
empty = ShippingNotice(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual")
assert task_export_error_message(empty) == "export file not found"
missing = ShippingNotice(
task_no="SN-MISSING-FILE",
process_status="matched",
source_type="manual",
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
)
@@ -140,7 +164,6 @@ def test_task_projection_tool_strips_internal_fields(app):
with app.app_context():
task = ShippingNotice(
task_no="SN-PROJ-TOOL",
process_status="waiting_inventory",
review_status="align_review",
match_status="pending",
pending_human_reason="rpa_pending",
@@ -161,12 +184,11 @@ def test_task_projection_internal_keeps_status_fields(app):
with app.app_context():
task = ShippingNotice(
task_no="SN-PROJ-INT",
process_status="parsed",
review_status="parse_review",
source_type="manual",
)
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
assert data["process_status"] == "parsed"
assert "review_status" in data
assert data["review_status"] == "parse_review"
@@ -177,7 +199,6 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
task = ShippingNotice(
task_no="SN-CONV-1",
conversation_id="conv-abc",
process_status="parsed",
source_type="manual",
)
from app import db
@@ -202,13 +223,11 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
ShippingNotice(
task_no="SN-CONV-MULTI-1",
conversation_id="conv-multi",
process_status="parsed",
source_type="manual",
),
ShippingNotice(
task_no="SN-CONV-MULTI-2",
conversation_id="conv-multi",
process_status="pending_review",
source_type="manual",
),
]
@@ -232,13 +251,11 @@ def test_task_can_handle_only_creator(app):
owned = ShippingNotice(
task_no="SN-HANDLE-OWN",
process_status="created",
source_type="manual",
user_id=42,
)
orphan = ShippingNotice(
task_no="SN-HANDLE-ORPHAN",
process_status="created",
source_type="manual",
user_id=None,
)
@@ -263,13 +280,11 @@ def test_get_task_for_user_rejects_null_owner(app):
orphan = ShippingNotice(
task_no="SN-NULL-OWNER",
process_status="created",
source_type="manual",
user_id=None,
)
owned = ShippingNotice(
task_no="SN-OWNED",
process_status="created",
source_type="manual",
user_id=7,
)
@@ -291,7 +306,6 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
task = ShippingNotice(
task_no="SN-ENRICH-1",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -306,7 +320,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
assert data["todo_category"] == "review"
assert data["created_by"] == 11
assert data["can_handle"] is True
assert data["ui_state"]["checkpoint"] == "parse_review"
assert data["ui_state"]["checkpoint"]["code"] == "parse_review"
assert data["artifact_summary"]["export_file_name"] == "a.xlsx"
no_viewer = serialize_task_summary(task)
@@ -322,7 +336,6 @@ def test_list_my_todos_and_count_buckets(app):
owner = 55
review = ShippingNotice(
task_no="SN-TODO-REVIEW",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -330,7 +343,6 @@ def test_list_my_todos_and_count_buckets(app):
)
upload = ShippingNotice(
task_no="SN-TODO-UPLOAD",
process_status="matched",
source_type="manual",
user_id=owner,
export_file_path="/tmp/u.xlsx",
@@ -338,13 +350,12 @@ def test_list_my_todos_and_count_buckets(app):
)
done = ShippingNotice(
task_no="SN-TODO-DONE",
process_status="uploaded",
source_type="manual",
user_id=owner,
upload_status="uploaded",
)
other = ShippingNotice(
task_no="SN-TODO-OTHER",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -422,7 +433,7 @@ def test_list_my_todos_includes_orphan_parse_failed_intake(app):
"""
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
"""
with app.app_context():
from app import db
@@ -527,7 +538,6 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
tasks = [
ShippingNotice(
task_no=f"SN-TODO-PAGE-{index:04d}",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -578,7 +588,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
fixtures = [
ShippingNotice(
task_no="SN-LW-REVIEW",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -586,7 +595,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
),
ShippingNotice(
task_no="SN-LW-UPLOAD",
process_status="matched",
source_type="manual",
user_id=owner,
export_file_path="/tmp/lw.xlsx",
@@ -595,7 +603,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
ShippingNotice(
task_no="SN-LW-SHORTAGE",
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
process_status="parsed",
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
@@ -603,13 +610,12 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
),
ShippingNotice(
task_no="SN-LW-DONE",
process_status="uploaded",
upload_status="uploaded",
source_type="manual",
user_id=owner,
),
ShippingNotice(
task_no="SN-LW-PROGRESS",
process_status="parsed",
source_type="manual",
user_id=owner,
),
@@ -620,7 +626,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
category_expr = _task_todo_category_sql_expr()
for task in fixtures:
row = SimpleNamespace(
process_status=task.process_status,
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
shipping_case_id=task.shipping_case_id,
@@ -630,6 +635,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
inventory_lines_json=task.inventory_lines_json,
match_status=task.match_status,
export_file_path=task.export_file_path,
upload_status=task.upload_status,
)
expected = task_todo_category(task)
# 轻量路径与 ORM 路径同分类。
@@ -18,6 +18,7 @@ from app.services.shipping_notice.constants import (
)
from app.services.shipping_notice.state_machine import (
CheckpointKind,
build_checkpoint_catalog,
checkpoint_kind_for,
resolve_task_ui_state,
validate_registry,
@@ -29,6 +30,13 @@ def test_validate_registry_has_no_errors() -> None:
assert validate_registry() == []
def test_checkpoint_catalog_uses_unified_actions_shape() -> None:
"""检查点目录也不得继续暴露旧 action_buttons 字段。"""
catalog = build_checkpoint_catalog()
assert all("action_buttons" not in item for item in catalog["checkpoints"])
assert all(set(item["actions"]) == {"primary", "secondary"} for item in catalog["checkpoints"])
def test_checkpoint_kinds_for_stp_stop_points() -> None:
"""STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。"""
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
@@ -41,7 +49,6 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-SM-PARSE",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
@@ -56,7 +63,6 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-SM-EXPORT",
process_status="matched",
source_type="manual",
export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx",
@@ -68,11 +74,11 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
"""process_status=uploaded 应为 complete。"""
"""upload_status=uploaded 应为 complete。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-SM-UPLOADED",
process_status="uploaded",
upload_status="uploaded",
source_type="manual",
)
ui = resolve_task_ui_state(task)
@@ -83,7 +89,7 @@ def test_resolve_task_ui_state_uploaded_complete(app) -> None:
def test_resolve_with_mocked_simple_namespace_attributes() -> None:
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
task = SimpleNamespace(
process_status="uploaded",
upload_status="uploaded",
review_status=None,
pending_human_reason=None,
shipping_case_id=None,
@@ -38,7 +38,6 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
task = ShippingNotice(
task_no="SN-STP-WAIT-UPLOAD",
process_status="matched",
source_type="manual",
export_file_path="/tmp/stp-export.xlsx",
export_file_name="stp-export.xlsx",
@@ -62,7 +61,6 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
task = ShippingNotice(
task_no="SN-STP-MUST-HUMAN",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
@@ -85,7 +83,6 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch)
task = ShippingNotice(
task_no="SN-STP-RPA-ON",
process_status="matched",
match_status="fulfillable",
source_type="manual",
line_results_json=[{"line_status": "ok"}],
@@ -127,7 +124,6 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch)
task = ShippingNotice(
task_no="SN-STP-NO-RPA",
process_status="matched",
match_status="fulfillable",
source_type="manual",
line_results_json=[{"line_status": "ok"}],
@@ -166,7 +162,6 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
task = ShippingNotice(
task_no="SN-STP-MANUAL-CFM",
process_status="waiting_upload",
source_type="manual",
export_file_path="/tmp/m.xlsx",
export_file_name="m.xlsx",
@@ -235,7 +230,6 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
task = ShippingNotice(
task_no="SN-STP-CLOSE-FAIL",
process_status="waiting_upload",
source_type="manual",
export_file_path="/tmp/m.xlsx",
export_file_name="m.xlsx",
@@ -301,17 +295,21 @@ def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-STP-ENTRY",
process_status="matched",
source_type="manual",
export_file_path="/tmp/x.xlsx",
export_file_name="x.xlsx",
)
state = build_task_ui_state(task)
assert state["checkpoint_kind"] == "wait_manual_upload"
assert state["checkpoint"]["kind"] == "wait_manual_upload"
assert state["summary"]["entry_surface"] == "task_workbench"
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
button_ids = [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
assert "mark_manual_uploaded" in button_ids
assert "download_excel" in button_ids
assert "action_buttons" not in state
def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
@@ -339,7 +337,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
mine = ShippingNotice(
task_no="SN-STP-OWN",
user_id=owner.id,
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
@@ -347,7 +344,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
waiting_upload = ShippingNotice(
task_no="SN-STP-UPLOAD",
user_id=owner.id,
process_status="matched",
source_type="manual",
export_file_path="/tmp/own.xlsx",
export_file_name="own.xlsx",
@@ -355,7 +351,6 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
other = ShippingNotice(
task_no="SN-STP-OTHER",
user_id=admin.id,
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
+11 -21
View File
@@ -304,7 +304,6 @@ def test_confirm_inventory_source_route_returns_json(app, client):
task = ShippingNotice(
task_no="SN-HTTP-CONFIRM-SRC",
source_type="manual",
process_status="pending_review",
pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
@@ -339,7 +338,7 @@ def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory")
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual")
db.session.add(task)
db.session.commit()
@@ -363,7 +362,6 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
task = ShippingNotice(
task_no="SN-REUPLOAD-INVENTORY",
source_type="manual",
process_status="matched",
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
match_status="fulfillable",
line_results_json=[{"part_number": "A001"}],
@@ -403,7 +401,7 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
assert link.is_active is False
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inv_unavail"
assert task.pending_human_reason == "inv_unavail"
assert task.inventory_lines_json is None
assert task.match_status is None
@@ -519,7 +517,6 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "inventory_ready"
task.review_status = None
task.pending_human_reason = "inv_unavail"
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
@@ -542,7 +539,6 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.process_status = "parsed"
db.session.commit()
from app.services.shipping_notice import decision_workflow
@@ -555,7 +551,7 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.pending_human_reason == "rpa_pending"
assert task.review_status is None
assert task.inventory_lines_json is None
@@ -601,7 +597,6 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
"rpa_inventory_source": {
@@ -628,7 +623,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["status"] == "needs_human"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
@@ -665,7 +660,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_EXHAUSTED
task.step_payload_json = {
"rpa_inventory_source": {
@@ -677,7 +671,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.process_status = "parsed"
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
@@ -700,7 +693,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.pending_human_reason == "rpa_pending"
assert task.error_message is None
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
@@ -749,7 +742,6 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
"rpa_inventory_source": {
@@ -777,7 +769,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
assert task is not None
assert result["started"] == 1
assert result["skipped"] == 0
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
@@ -791,7 +783,6 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
first = ShippingNotice(
task_no="SN-MULTI-CONV-001",
conversation_id="conv-test-multi",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -800,7 +791,6 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
second = ShippingNotice(
task_no="SN-MULTI-CONV-002",
conversation_id="conv-test-multi",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
@@ -835,8 +825,8 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
.order_by(ShippingNotice.task_no)
.all()
}
assert rows["SN-MULTI-CONV-001"].process_status == "pending_review"
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
assert rows["SN-MULTI-CONV-001"].review_status == "parse_review"
assert rows["SN-MULTI-CONV-002"].review_status == "parse_review"
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
@@ -892,10 +882,10 @@ def test_chat_actions_empty_when_task_rejected(app):
task = ShippingNotice(
task_no="SN-20260101-TEST0001",
source_type="manual",
process_status="rejected",
review_status="rejected",
)
assert human_options_for_task(task) == []
ui_state = build_task_ui_state(task)
assert ui_state["checkpoint"] == "rejected"
assert ui_state["action_buttons"] == []
assert ui_state["checkpoint"]["code"] == "rejected"
assert ui_state["actions"] == {"primary": None, "secondary": []}
assert "action_buttons" not in ui_state
+76 -9
View File
@@ -14,6 +14,7 @@ from app.services.shipping_notice.constants import (
RS_PARSE_REVIEW,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
from app.services.shipping_notice.ui_state import _unified_actions
_REQUIRED_SUMMARY_KEYS = {
@@ -31,29 +32,95 @@ _REQUIRED_SUMMARY_KEYS = {
}
def test_unified_actions_deduplicates_gate_primary_action():
"""Gate 主动作同时出现在展示列表时,只能渲染一次。"""
state = _unified_actions(
process_gate={
"primary_action": {"code": "open_order_review", "label": "进入订单复核"},
"action_presentation": [
{"code": "open_order_review", "label": "进入订单复核"},
{"code": "view_audit", "label": "查看审计", "kind": "view"},
],
},
action_buttons=[],
)
assert state["primary"]["code"] == "open_order_review"
assert [item["code"] for item in state["secondary"]] == ["view_audit"]
def test_unified_action_shape_contains_gate_version_fields():
"""统一动作 DTO 必须包含前端提交所需的版本与禁用字段。"""
state = _unified_actions(
process_gate={
"lock_version": 7,
"current_gate": {"evaluation_version": 3},
"primary_action": {"code": "retry_inventory_matching", "label": "重新匹配"},
"action_presentation": [],
},
action_buttons=[],
)
assert state["primary"]["expected_gate_version"] == 3
assert "disabled_reason" in state["primary"]
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
"""summary 必须包含 STP 可解释字段全集。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-SUMMARY",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
assert state["checkpoint"] == CP_PARSE_REVIEW
assert state["checkpoint"]["code"] == CP_PARSE_REVIEW
assert state["checkpoint_kind"] == "must_human"
assert "stp_facts" not in state["summary"]
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
"""业务 UI 只消费四阶段与后端统一 actions,不再要求前端解释旧七步。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STAGE-ACTIONS",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert state["stage"]["code"] == "order_review"
assert state["stage"]["index"] == 2
assert state["stage"]["total"] == 4
assert state["actions"]["primary"] is not None
assert state["actions"]["primary"]["code"] == "confirm"
assert all("code" in item and "kind" in item for item in state["actions"]["secondary"])
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
"""库存匹配/上传结果只映射四个业务阶段。"""
with app.app_context():
fulfillment = ShippingNotice(
task_no="SN-UI-FULFILLMENT",
source_type="manual",
match_status="partial",
inventory_lines_json=[{"part_number": "P-1"}],
)
upload = ShippingNotice(
task_no="SN-UI-UPLOAD",
source_type="manual",
upload_status="uploaded",
)
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
assert build_task_ui_state(upload)["stage"]["code"] == "upload_complete"
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
"""解析复核应进入人工复核工作台。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-REVIEW",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
@@ -67,18 +134,21 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-EXPORT",
process_status="matched",
source_type="manual",
export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx",
)
state = build_task_ui_state(task)
assert state["checkpoint"] == CP_EXPORT_READY
assert state["checkpoint"]["code"] == CP_EXPORT_READY
assert state["checkpoint_kind"] == "wait_manual_upload"
assert state["summary"]["entry_surface"] == "task_workbench"
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
assert "登记凭据" in str(state["summary"].get("pause_reason") or "")
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
button_ids = [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
assert "download_excel" in button_ids
assert "mark_manual_uploaded" in button_ids
@@ -88,7 +158,6 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STP-FROZEN",
process_status="waiting_inventory",
source_type="manual",
inventory_source_status="candidates_frozen",
inventory_source_method="stp_build_freeze",
@@ -111,7 +180,6 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STP-LINES",
process_status="matched",
source_type="manual",
match_status="fulfillable",
inventory_source_status="resolved",
@@ -150,7 +218,6 @@ def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STP-MULTI",
process_status="matched",
review_status=RS_SHORTAGE_REVIEW,
pending_human_reason="shortage",
source_type="manual",
@@ -19,7 +19,6 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
"""
task = ShippingNotice(
task_no="SN-TEST-RPA-PENDING",
process_status="waiting_inventory",
pending_human_reason=PH_RPA_PENDING,
)
@@ -9,6 +9,7 @@ from app.jobs.handlers.shipping_order_extraction import (
_pending_snapshot_batches,
_process_unit_with_retries,
_result_requires_review,
_should_activate_planned_batches,
_should_expand_after_wave,
_units_for_batch,
)
@@ -474,6 +475,12 @@ def test_should_expand_after_wave_when_current_wave_needs_more_evidence():
) is False
def test_planned_attachment_batch_activates_without_sibling_field_gate():
"""计划内附件必须独立消费,首轮字段完整与否不得阻止下一批激活。"""
assert _should_activate_planned_batches(pending_batches=[2]) is True
assert _should_activate_planned_batches(pending_batches=[]) is False
def test_auto_freeze_blocked_task_requires_run_review():
"""自动冻结的 Task 级门禁拒绝必须把 Run 收口为需人工处理,而非 completed。"""
assert _result_requires_review(
@@ -47,7 +47,11 @@ from app.services.shipping_notice.order_review_draft_service import (
set_line_inventory_candidates,
validate_draft,
)
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence, list_case_evidence
from app.services.shipping_notice.order_review_evidence_service import (
get_case_email_evidence_text,
get_case_evidence,
list_case_evidence,
)
from app.services.shipping_notice.order_review_disposition_service import (
create_manual_draft,
finalize_document_reparse,
@@ -520,6 +524,76 @@ def test_review_evidence_is_case_scoped_and_omits_untrusted_bbox(app):
assert 'storage_key' not in str(payload)
def test_review_evidence_keeps_the_email_document_identity(app):
"""邮件正文 Observation 必须返回其 EML Document,前端不得回退打开主 PDF。"""
with app.app_context():
user, agent, session, intake, pdf_document = _seed_run_input(suffix='REVIEW-EMAIL-EVIDENCE')
email_document = ShippingOrderDocument(
intake_id=intake.id,
document_type='email_body',
attachment_key='body',
filename='review-email.eml',
content_hash='e' * 64,
classification='email_body',
parse_status='parsed',
extracted_text='Reservation Number: 33894',
)
db.session.add(email_document)
db.session.commit()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [
{'field_id': 'reservation', 'observations': [{
'value': '33894',
'quote': 'Reservation Number: 33894',
'document_id': email_document.id,
'source_type': 'email_body_table',
}]},
], 'lines': []}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
assert item['document_id'] == email_document.id
assert item['document_type'] == 'email_body'
assert item['source_type'] == 'email_body_table'
def test_review_email_evidence_preview_reads_only_the_sibling_email_body(app):
"""邮件证据预览只允许当前 Case 同 Intake 的已解析正文,不能读取 PDF 或原始附件。"""
with app.app_context():
user, agent, session, intake, _pdf_document = _seed_run_input(suffix='REVIEW-EMAIL-PREVIEW')
email_document = ShippingOrderDocument(
intake_id=intake.id,
document_type='email_body',
attachment_key='body',
filename='review-email.eml',
content_hash='f' * 64,
classification='email_body',
parse_status='parsed',
extracted_text='Reservation Number: 33894',
)
db.session.add(email_document)
db.session.commit()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
preview = get_case_email_evidence_text(
user_id=user.id,
case_no=case.case_no,
document_id=email_document.id,
)
assert preview == {
'document_id': email_document.id,
'document_type': 'email_body',
'filename': 'review-email.eml',
'text': 'Reservation Number: 33894',
}
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
with app.app_context():
@@ -981,7 +1055,7 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
# 关键断言:复核确认建单必须同步冻结,库存/RPA 不可消费可变解析结果。
assert task.order_snapshot_id is not None
# 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。
assert task.process_status == 'parsed'
assert task.customer_resolution_status == 'confirmed'
assert task.review_status is None
assert task.pending_human_reason is None
# 关键断言:人工 Candidate 必须保留受控字段证据,建单后资格不能反向变成 evidence_missing。
@@ -1500,14 +1574,12 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app):
user_id=user.id,
source_type='review_confirmation',
source_content_hash=content_hash,
process_status='parsed',
)
other = ShippingNotice(
task_no='SN-WAVE-OTHER',
user_id=user.id,
source_type='manual',
source_content_hash=content_hash,
process_status='parsed',
)
db.session.add_all([own, other])
db.session.commit()
@@ -310,8 +310,45 @@ def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch)
assert summary['owner_type'] == 'human'
def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
"""Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。"""
def test_inventory_preparation_keeps_controlled_upload_as_a_secondary_gate_action(app, monkeypatch):
"""库存准备以重试为主动作,受控上传仅保留给 Gate 工作台。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-INVENTORY-1', status='blocked',
current_gate_code='inventory_preparation',
primary_next_action_code='upload_inventory_file',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-INVENTORY-1', 'status': 'blocked',
'primary_next_action_code': 'upload_inventory_file',
'responsible_party': 'worker', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
'blocking_reason_code': 'inventory_file_empty',
'next_action_code': 'upload_inventory_file', 'evaluation_version': 3,
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'retry_inventory_preparation'
assert summary['primary_action']['code'] == 'retry_inventory_preparation'
assert summary['allowed_actions'] == [
'retry_inventory_preparation',
'upload_inventory_file',
]
def test_user_gate_summary_exposes_manual_gate_evidence_confirmation(app, monkeypatch):
"""Gate 20 只下发受控凭据登记,不把 RPA 重试伪装为人工上传确认。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
@@ -338,10 +375,75 @@ def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
assert summary['next_action_code'] == 'mark_manual_uploaded'
assert summary['allowed_actions'] == ['mark_manual_uploaded']
assert summary['owner_type'] == 'human'
def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(app, monkeypatch):
"""Gate 20 必须引导受控凭据登记,不得再重生待办或直接声称上传完成。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-MANUAL-CONFIRM', status='blocked',
current_gate_code='manual_upload_handoff',
primary_next_action_code='regenerate_manual_upload_todo',
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-MANUAL-CONFIRM', 'status': 'blocked',
'primary_next_action_code': 'regenerate_manual_upload_todo',
'responsible_party': 'owner', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
'blocking_reason_code': 'manual_upload_pending',
'next_action_code': 'regenerate_manual_upload_todo', 'evaluation_version': 3,
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'mark_manual_uploaded'
assert summary['allowed_actions'] == ['mark_manual_uploaded']
def test_inventory_source_gate_summary_does_not_expose_line_decision_side_actions(app, monkeypatch):
"""规则建议和保留人工决定只属于订单复核明细行,不能泄漏到 Gate 卡。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-ROUTING', status='blocked',
current_gate_code='inventory_source_routing', primary_next_action_code='open_inventory_source_review',
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-ROUTING', 'status': 'blocked',
'primary_next_action_code': 'open_inventory_source_review',
'responsible_party': 'owner', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'inventory_source_routing', 'status': 'blocked_manual',
'blocking_reason_code': 'no_inventory_source_candidates',
'next_action_code': 'open_inventory_source_review', 'evaluation_version': 3,
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['allowed_actions'] == ['open_inventory_source_review']
def test_process_gate_dependency_integrity_and_excel_only_scope():
"""
校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。
@@ -116,7 +116,6 @@ def _seed_workflow_version(
source_type='manual',
process_status='waiting_inventory',
)
@@ -52,7 +52,7 @@ def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
sync_preparation_source_from_rpa_attempt,
)
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1', process_status='waiting_inventory')
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1')
db.session.add(task)
db.session.flush()
preparation = create_inventory_preparation_round(
@@ -87,7 +87,7 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
from app.services.shipping_notice import per_source_rpa_service
task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY', process_status='waiting_inventory')
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')
@@ -120,7 +120,7 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
from app.models import ShippingNotice
from app.services.shipping_notice import per_source_rpa_service
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING', process_status='waiting_inventory')
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'])
@@ -134,7 +134,11 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa')
assert result.pending_source_codes == []
assert result.failed_source_codes == ['DBS']
attempt = per_source_rpa_service._latest_attempt(task.task_no, 'DBS')
# 读取真实数据库记录,避免被用于构造场景的 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'
@@ -146,7 +150,7 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
from app.services.shipping_notice import process_gate_executor
task = ShippingNotice(
task_no='SN-PREP-FREEZE-OPERATOR', process_status='waiting_inventory',
task_no='SN-PREP-FREEZE-OPERATOR',
order_snapshot_id=None, order_data_version=1,
)
db.session.add(task)
@@ -195,7 +199,7 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
)
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY', process_status='waiting_inventory')
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY')
db.session.add(task)
db.session.flush()
current = ShippingInventoryCandidateSet(
@@ -254,7 +258,7 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app,
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice import inventory_rpa_workflow
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY', process_status='waiting_inventory')
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY')
db.session.add(task)
db.session.commit()
@@ -305,7 +309,7 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
from app.models import ShippingNotice
from app.services.shipping_notice import inventory_rpa_workflow
task = ShippingNotice(task_no='SN-2026-001', process_status='waiting_inventory')
task = ShippingNotice(task_no='SN-2026-001')
db.session.add(task)
db.session.commit()
captured = {}
@@ -341,7 +345,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice import inventory_rpa_workflow
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY', process_status='waiting_inventory')
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY')
db.session.add(task)
db.session.commit()
@@ -408,7 +412,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
task = ShippingNotice(
task_no='SN-RPA-FAILED-GATE', process_status='waiting_inventory',
task_no='SN-RPA-FAILED-GATE',
pending_human_reason='rpa_exhausted', error_message='RPA export failed',
)
db.session.add(task)
@@ -430,6 +434,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
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'},
)
@@ -448,7 +453,9 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
assert gate.status == 'blocked_manual'
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
db.session.refresh(execution)
assert execution.status == 'blocked'
# Gate 已进入可人工恢复的 blocked_manual;Execution 仍保持 active,
# 由当前业务阶段/Gate 投影表达阻断,不再回写旧的 execution blocked 状态。
assert execution.status == 'active'
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
@@ -469,8 +476,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo
task = ShippingNotice(
task_no='SNFORMALPREPLINEAGE',
process_status='waiting_inventory',
inventory_source_code='DBS',
# 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。
order_snapshot_id=1,
)
db.session.add(task)
db.session.flush()
@@ -544,7 +552,6 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
task = ShippingNotice(
task_no='SNSTARTCUSTOMERPENDING',
process_status='created',
current_order_extraction_id=101,
order_snapshot_id=201,
customer_resolution_status='pending',
@@ -568,7 +575,6 @@ def test_formal_start_gate_stops_at_field_conflict_before_inventory(app):
task = ShippingNotice(
task_no='SNSTARTFIELDCONFLICT',
process_status='created',
current_order_extraction_id=101,
order_snapshot_id=201,
customer_resolution_status='confirmed',
@@ -594,7 +600,7 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app):
from app.services.shipping_notice.auto_progress_controller import supersede_auto_progress_for_candidate_refreeze
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version, queue_gate_attempt
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT', process_status='waiting_inventory')
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT')
db.session.add(task)
db.session.flush()
old_candidate = ShippingInventoryCandidateSet(
@@ -641,7 +647,7 @@ def test_legacy_workspace_forwarding_audit_is_structured(app):
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT', process_status='waiting_inventory')
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT')
db.session.add(task)
db.session.flush()
@@ -670,7 +676,7 @@ def test_apx_runtime_audit_is_read_only_and_counts_active_states(app):
from app.models import Job, ShippingNotice, ShippingProcessExecution
from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state
task = ShippingNotice(task_no='SN-APX-AUDIT', process_status='waiting_inventory')
task = ShippingNotice(task_no='SN-APX-AUDIT')
db.session.add(task)
db.session.flush()
active = ShippingProcessExecution(
@@ -950,7 +956,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
'freeze_mode': 'manual',
}
assert task.order_snapshot_id == 901
assert result['outcome'] == 'waiting_external'
assert result['outcome'] == 'blocked_retryable'
def test_manual_business_block_is_a_successful_attempt(app):
@@ -200,17 +200,17 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
)
uploaded = SimpleNamespace(
process_status='uploaded', current_step='', upload_status='', export_file_path=None,
current_step='', upload_status='uploaded', export_file_path=None,
)
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
waiting = SimpleNamespace(
process_status='waiting_upload', current_step='', upload_status='', export_file_path='/x.xlsx',
current_step='', upload_status='pending', export_file_path='/x.xlsx',
)
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
matching = SimpleNamespace(
process_status='matching', current_step='step5_match', upload_status='', export_file_path=None,
current_step='step5_match', upload_status='', match_status='matching', export_file_path=None,
)
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
@@ -224,7 +224,6 @@ def test_map_notice_unknown_status_fail_closed():
)
unknown = SimpleNamespace(
process_status='totally_unknown_xyz',
current_step='',
upload_status='',
export_file_path=None,
@@ -288,7 +287,37 @@ def test_inventory_snapshot_missing_projects_retryable_inventory_action():
assert payload['user_status'] == 'retryable'
assert payload['retryable'] is True
assert payload['primary_action']['code'] == 'retry'
# 主动作必须保留 Gate 原始码,前端才能提交到正确的库存准备执行器。
assert payload['primary_action'] == {
'code': 'retry_inventory_preparation',
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
'parameters': {},
}
def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
"""库存文件缺失必须保留 Gate 重试,不得降级为线外上传或空按钮。"""
payload = apply_user_projection_fields({
'status': 'processing',
'stage': 'inventory_fetching',
'source_type': 'order_task',
'shipping_notice_no': 'SN-1',
'current_gate': {
'gate_code': 'inventory_preparation',
'status': 'blocked_manual',
'next_action_code': 'retry_inventory_preparation',
'blocking_reason_code': 'inventory_file_empty',
},
'available_actions': ['retry_inventory_preparation'],
})
assert payload['user_status'] == 'waiting_human'
assert payload['primary_action'] == {
'code': 'retry_inventory_preparation',
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
'parameters': {},
}
assert payload['available_actions'] == ['retry_inventory_preparation']
def test_waiting_human_reconcile_action_uses_projected_available_actions():
@@ -10,15 +10,22 @@ backend/tests/test_shipping_processing_projection_stage4.py
from __future__ import annotations
import uuid
import re
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from sqlalchemy import event
from werkzeug.datastructures import FileStorage
from app import db
from app.models import ShippingOrderIntake, ShippingOrderSubmission, User
from app.models import (
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderSubmission,
User,
)
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
from app.services.shipping_notice.progress_audit_contract import (
@@ -143,8 +150,339 @@ def test_aggregate_single_eml_attachment_is_still_an_intake_card() -> None:
assert result[0]['aggregate_summary']['processing'] == 1
def test_aggregate_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
"""建单前 STP 失败的内部阶段码不得泄漏到会话聚合摘要。"""
def test_eml_aggregate_projects_every_business_document_when_some_lack_order_tasks(app) -> None:
"""EML 父卡的数量与展开叶子同源,未建 OT 附件只展示真实解析态且不伪造动作。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
_user, _agent, _session, intake, first_document = _seed_run_input(
suffix='EML-LEAF-COVERAGE',
)
intake.source_type = 'eml'
second_document = ShippingOrderDocument(
intake_id=int(intake.id),
document_type='attachment',
attachment_key='eml-unassigned.pdf',
filename='eml-unassigned.pdf',
content_hash='c' * 64,
classification='order_notice',
parse_status='parsed',
order_extraction_status='not_started',
)
# 邮件正文不是可展开的业务附件,不能被混进 EML 文件数。
email_body = ShippingOrderDocument(
intake_id=int(intake.id),
document_type='email_body',
attachment_key='__email_body__',
filename='mail.eml',
content_hash='d' * 64,
classification='unknown',
parse_status='parsed',
)
db.session.add_all([second_document, email_body])
db.session.commit()
existing_task = {
'work_item_type': 'order_task',
'work_item_no': 'OT-EML-ASSIGNED',
'source_type': 'eml',
'intake_no': intake.intake_no,
'root_order_task_no': 'OT-EML-ASSIGNED',
'last_activity_at': '2026-08-14T00:00:00Z',
'status': 'processing',
'stage': 'candidate_creating',
'user_status': 'running',
'user_stage': 'candidate_creating',
'current_gate': None,
'available_actions': [],
'primary_action': None,
'blocking_reason': None,
'facts': {'upload_state': 'not_created'},
'source_summary': {
'document_id': int(first_document.id),
'document_count': 1,
'filename': first_document.filename,
'parsed_document_count': 1,
'candidate_count': 0,
},
'child_order_tasks': [],
}
aggregate = _aggregate_eml_order_task_work_items([existing_task])[0]
children = aggregate['aggregate_children']
assert aggregate['source_summary']['document_count'] == 2
assert aggregate['aggregate_summary'] == {
'intake_no': intake.intake_no,
'total': 2,
'completed': 0,
'processing': 2,
'needs_action': 0,
'failed': 0,
'stages': ['candidate_creating'],
'reason_codes': [],
'upload_states': ['not_created'],
}
assert {child['source_summary']['document_id'] for child in children} == {
int(first_document.id), int(second_document.id),
}
unassigned = next(
child for child in children
if child['source_summary']['document_id'] == int(second_document.id)
)
assert unassigned['work_item_no'] == f'DOCUMENT:{second_document.id}'
assert unassigned['user_status'] == 'running'
assert unassigned['ui_state']['primary_action'] is None
assert unassigned['available_actions'] == []
def test_eml_order_intake_projects_business_documents_without_candidates_as_processing(app) -> None:
"""无 OT/候选的 EML 仍完整展示业务附件;未形成候选不是异常或待人工门禁。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
_user, _agent, _session, intake, pdf = _seed_run_input(
suffix='EML-INTAKE-LEAF-COVERAGE',
)
intake.source_type = 'eml'
intake.parse_status = 'parsed'
intake.order_extraction_status = 'partially_completed'
spreadsheet = ShippingOrderDocument(
intake_id=int(intake.id),
document_type='attachment',
attachment_key='po-info.xlsx',
filename='po-info.xlsx',
content_hash='e' * 64,
classification='unknown',
parse_status='empty',
order_extraction_status='not_started',
)
email_body = ShippingOrderDocument(
intake_id=int(intake.id),
document_type='email_body',
attachment_key='__email_body__',
filename='mail.eml',
content_hash='f' * 64,
classification='email_context',
parse_status='parsed',
)
db.session.add_all([spreadsheet, email_body])
db.session.commit()
item = project_intake_work_item(intake)
assert item['work_item_type'] == 'order_intake'
assert item['source_summary']['document_count'] == 2
assert item['source_summary']['parsed_document_count'] == 1
assert item['status'] == 'processing'
assert item['user_status'] == 'running'
assert item['user_group'] == 'processing'
assert item['aggregate_summary'] == {
'intake_no': intake.intake_no,
'total': 2,
'completed': 0,
'processing': 2,
'needs_action': 0,
'failed': 0,
'stages': ['candidate_creating'],
'reason_codes': [],
'upload_states': ['not_created'],
}
assert {child['source_summary']['document_id'] for child in item['aggregate_children']} == {
int(pdf.id), int(spreadsheet.id),
}
assert all(child['available_actions'] == [] for child in item['aggregate_children'])
def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_tasks(app) -> None:
"""EML 无 Candidate/OT 时仍以最新 Run Unit 的正式 review_required 裁决为准。"""
with app.app_context():
from datetime import datetime
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, pdf = _seed_run_input(
suffix='EML-UNIT-REVIEW-PROJECTION',
)
intake.source_type = 'eml'
spreadsheet = ShippingOrderDocument(
intake_id=int(intake.id),
document_type='attachment',
attachment_key='po-info.xlsx',
filename='po-info.xlsx',
content_hash='u' * 64,
classification='unknown',
parse_status='empty',
order_extraction_status='not_started',
)
db.session.add(spreadsheet)
db.session.flush()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
assert {int(unit.document_id) for unit in run.extraction_plan.units} == {
int(pdf.id), int(spreadsheet.id),
}
for unit in run.extraction_plan.units:
unit.status = 'review_required'
unit.reason_code = 'profile_ambiguous'
run.status = 'review_required'
run.phase = 'review_required'
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.order_extraction_status = 'partially_completed'
# 真实历史 Run 可能已释放 Intake 链接,投影仍必须能读取其最终裁决。
run.intakes[0].released_at = datetime.utcnow()
db.session.commit()
item = project_intake_work_item(intake)
assert item['status'] == 'waiting_review'
assert item['user_status'] == 'waiting_human'
assert item['user_group'] == 'waiting_human'
assert item['aggregate_summary']['needs_action'] == 2
assert item['aggregate_summary']['processing'] == 0
assert {child['source_summary']['document_id'] for child in item['aggregate_children']} == {
int(pdf.id), int(spreadsheet.id),
}
assert all(child['status'] == 'waiting_review' for child in item['aggregate_children'])
assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children'])
def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None:
"""待人工附件已有 Review Case 时,叶子 ui_state 必须给出进入订单处理动作。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
user, agent, session, intake, _pdf = _seed_run_input(
suffix='EML-LEAF-REVIEW-ACTION',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.status = 'review_required'
unit.reason_code = 'generic_extraction_disabled'
review_case = ensure_review_case_for_unit(run=run, unit=unit)
db.session.commit()
item = project_intake_work_item(intake)
leaf = next(child for child in item['aggregate_children'] if child['work_item_no'] == f'DOCUMENT:{unit.document_id}')
assert leaf['run_no'] == run.run_no
assert leaf['case_no'] == review_case.case_no
assert leaf['ui_state']['primary_action'] == {'code': 'open_order_review'}
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
"""会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。"""
with app.app_context():
items = _aggregate_eml_order_task_work_items([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-BATCH-FAILED',
'source_type': 'eml', 'intake_no': 'SNI-BATCH-1',
'root_order_task_no': 'OT-BATCH-FAILED',
'last_activity_at': '2026-08-14T00:00:00Z',
'source_summary': {
'document_id': 101, 'document_count': 1, 'filename': 'a.pdf',
'email_subject': 'FWD: Shanghai shipping notice',
},
'status': 'failed', 'stage': 'waiting_review',
'user_status': 'failed', 'user_stage': 'waiting_review',
'available_actions': ['retry_parse'],
'primary_action': {'code': 'retry_parse'},
'blocking_reason': {'code': 'intake_parse_failed'},
'facts': {'upload_state': 'not_created'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-BATCH-RUNNING',
'source_type': 'eml', 'intake_no': 'SNI-BATCH-1',
'root_order_task_no': 'OT-BATCH-RUNNING',
'last_activity_at': '2026-08-14T00:00:01Z',
'source_summary': {
'document_id': 102, 'document_count': 1, 'filename': 'b.pdf',
'email_subject': 'FWD: Shanghai shipping notice',
},
'status': 'processing', 'stage': 'document_parsing',
'user_status': 'running', 'user_stage': 'document_parsing',
'available_actions': [], 'facts': {'upload_state': 'not_created'},
},
])
projection = _conversation_processing_from_work_items(items)
failed = projection['status_groups']['failed']
assert len(failed) == 1
assert failed[0]['user_task_no'] == 'INTAKE:SNI-BATCH-1'
assert failed[0]['title'] == 'FWD: Shanghai shipping notice'
assert len(failed[0]['aggregate_children']) == 2
assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'}
assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'}
assert projection['summary']['total_files'] == 2
assert projection['four_stage_nodes'][1] == {
'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked',
}
def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) -> None:
"""会话与批次中心均以 Intake 原始 EML 文件名标识同一邮件。"""
with app.app_context():
projection = _conversation_processing_from_work_items([{
'work_item_type': 'order_task',
'work_item_no': 'INTAKE:SNI-EML-TITLE-1',
'source_type': 'eml',
'intake_no': 'SNI-EML-TITLE-1',
'source_summary': {
'document_count': 2,
'filename': 'original-shipping-notice.eml',
'email_subject': 'FWD: Shanghai shipping notice',
},
'status': 'processing', 'stage': 'document_parsing',
'user_status': 'processing', 'user_stage': 'document_parsing',
'available_actions': [], 'facts': {'upload_state': 'not_created'},
}])
assert projection['status_groups']['processing'][0]['title'] == 'original-shipping-notice.eml'
def test_eml_aggregate_action_uses_the_same_priority_as_its_status(app) -> None:
"""失败附件即使排在待人工附件之后,EML 父卡也不能显示待人工按钮。"""
with app.app_context():
result = _aggregate_eml_order_task_work_items([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-WAITING',
'source_type': 'eml', 'intake_no': 'SNI-PRIORITY-1',
'last_activity_at': '2026-08-14T00:00:00Z',
'source_summary': {'document_id': 201, 'document_count': 1, 'filename': 'waiting.pdf'},
'status': 'waiting_human', 'stage': 'waiting_review',
'user_status': 'waiting_human', 'user_stage': 'waiting_review',
'blocking_reason': {'code': 'customer_confirmation_required'},
'primary_action': {'code': 'confirm_customer'},
'available_actions': ['confirm_customer'], 'facts': {'upload_state': 'not_created'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-FAILED',
'source_type': 'eml', 'intake_no': 'SNI-PRIORITY-1',
'last_activity_at': '2026-08-14T00:00:01Z',
'source_summary': {'document_id': 202, 'document_count': 1, 'filename': 'failed.pdf'},
'status': 'failed', 'stage': 'document_parsing',
'user_status': 'failed', 'user_stage': 'document_parsing',
'blocking_reason': {'code': 'intake_parse_failed'},
'primary_action': {'code': 'retry_parse'},
'available_actions': ['retry_parse'], 'facts': {'upload_state': 'not_created'},
},
])[0]
assert result['user_group'] == 'failed'
assert result['blocking_reason'] == {'code': 'intake_parse_failed'}
assert result['primary_action'] == {'code': 'retry_parse'}
conversation = _conversation_processing_from_work_items([result])
assert conversation['status_groups']['failed'][0]['ui_state']['primary_action'] == {'code': 'retry_parse'}
def test_direct_pdf_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
"""建单前 STP 失败的内部阶段码不得透传给直接 PDF 的用户投影。"""
item = {
'work_item_type': 'order_task', 'work_item_no': 'OT-STP-FAIL',
'source_type': 'direct_pdf', 'intake_no': 'SNI-STP-FAIL',
@@ -157,12 +495,12 @@ def test_aggregate_maps_internal_pre_ot_stp_stage_for_user_summary() -> None:
'facts': {'upload_state': 'not_created'},
}
aggregate = _aggregate_eml_order_task_work_items([item])[0]
projected = _aggregate_eml_order_task_work_items([item])[0]
assert aggregate['stage'] == 'order_creating'
assert aggregate['user_stage'] == 'order_creating'
assert aggregate['aggregate_summary']['stages'] == ['order_creating']
assert 'pre_ot_stp' not in aggregate['aggregate_summary']['stages']
assert projected['stage'] == 'order_creating'
assert projected['user_stage'] == 'order_creating'
# 直接 PDF 不是 EML 聚合根,不能伪造 aggregate_summary。
assert 'aggregate_summary' not in projected
def test_eml_aggregate_prefers_cancelled_over_completed_child() -> None:
@@ -368,10 +706,20 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
intake.parse_status = 'queued'
db.session.commit()
payload = project_conversation_processing_items(
user_id=shipping_user.id,
conversation_id=conversation_id,
)
run_selects: list[str] = []
def _capture_run_selects(_conn, _cursor, statement, _parameters, _context, _executemany):
if re.search(r'\bfrom\s+shipping_order_processing_runs\b', statement, re.IGNORECASE):
run_selects.append(statement)
event.listen(db.engine, 'before_cursor_execute', _capture_run_selects)
try:
payload = project_conversation_processing_items(
user_id=shipping_user.id,
conversation_id=conversation_id,
)
finally:
event.remove(db.engine, 'before_cursor_execute', _capture_run_selects)
assert 'projection_version' not in payload
assert payload['conversation_id'] == conversation_id
assert isinstance(payload['work_items'], list)
@@ -387,6 +735,22 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
assert solo['source_type'] == 'direct_pdf'
assert solo['stage'] == 'document_parsing'
assert solo['status'] == 'processing'
# 顶层工作项与会话状态组均消费同一后端 ui_state;前端无需读取 Gate 补按钮。
assert solo['ui_state']['status'] == 'running'
assert solo['ui_state']['stage'] == 'document_parsing'
assert solo['ui_state']['blocking_reason'] is None
assert solo['ui_state']['primary_action'] is None
assert [action['code'] for action in solo['ui_state']['secondary_actions']] == solo['available_actions']
assert all(action['enabled'] is True for action in solo['ui_state']['secondary_actions'])
conversation_row = next(
row
for row in payload['conversation_processing']['status_groups']['processing']
if row['user_task_no'] == solo['work_item_no']
)
assert conversation_row['ui_state'] == solo['ui_state']
# 仅 Intake 的会话没有任何 OT;读取 Projection 不得扫描历史 Run,
# 否则空白/刚上传首屏会随历史 Run 数量线性变慢。
assert run_selects == []
def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, shipping_user):
@@ -407,6 +771,8 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s
intake = ShippingOrderIntake.query.filter_by(intake_no=created['intake_no']).one()
intake.parse_status = 'consumed'
intake.consumed_at = intake.created_at
# 消费标记仅表示已交给订单识别;尚无 OT/Candidate 的部分识别结果仍必须处理中。
intake.order_extraction_status = 'partially_completed'
db.session.commit()
payload = project_conversation_processing_items(
@@ -421,6 +787,7 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s
and row.get('intake_no') == intake.intake_no
and row.get('status') == 'processing'
and row.get('stage') == 'candidate_creating'
and row.get('user_status') == 'running'
for row in payload['work_items']
)
@@ -530,7 +897,6 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
user_id=user.id,
conversation_id=session.session_id,
source_type='manual',
process_status='waiting_upload',
current_step='step7_upload_freight',
)
db.session.add(notice)
@@ -561,7 +927,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
assert synced['stage'] == 'freight_uploading'
# 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。
notice.process_status = 'uploaded'
notice.upload_status = 'uploaded'
order_task.status = 'automating'
order_task.stage = 'freight_uploading'
db.session.commit()
@@ -35,7 +35,6 @@ def test_sync_order_task_stage_must_be_processing_stage(app):
notice = ShippingNotice(
task_no='SN-CROSS-SURFACE-001',
source_type='manual',
process_status='matched',
po_number='PO-CROSS-001',
order_lines_migration_status='pending',
)
@@ -43,7 +43,7 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
from app.services.shipping_notice import order_review_workbench_projection as workbench
case = MagicMock(status='confirmed', confirmed_task_id=9)
stuck = MagicMock(task_no='SN-STUCK-1', process_status='created', current_order_extraction_id=3)
stuck = MagicMock(task_no='SN-STUCK-1', current_order_extraction_id=3)
finished = NS(
id=55,
status='success',
@@ -83,19 +83,16 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction():
"""created/parsed 且已挂 Extraction 的任务需要确认后补推。"""
stuck = MagicMock(
process_status='created',
current_order_extraction_id=12,
)
parsed = MagicMock(
process_status='parsed',
current_order_extraction_id=12,
)
progressed = MagicMock(
process_status='waiting_upload',
upload_status='pending',
current_order_extraction_id=12,
)
shell = MagicMock(
process_status='created',
current_order_extraction_id=None,
)
assert _task_needs_post_confirm_auto_progress(stuck) is True
@@ -111,7 +108,6 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
task = ShippingNotice(
task_no='SN-CONFIRM-AP-1',
user_id=1,
process_status='created',
current_order_extraction_id=99,
)
db.session.add(task)
@@ -144,12 +140,11 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch):
"""确认后 process_status=parsed 仍须入队(CONFIRM_PARSE 后常见态)。"""
"""确认后已有解析结果仍须入队(CONFIRM_PARSE 后常见态)。"""
with app.app_context():
task = ShippingNotice(
task_no='SN-CONFIRM-AP-PARSED',
user_id=1,
process_status='parsed',
current_order_extraction_id=99,
)
db.session.add(task)
@@ -185,7 +180,6 @@ def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkey
task = ShippingNotice(
task_no='SN-CONFIRM-AP-2',
user_id=1,
process_status='created',
current_order_extraction_id=88,
)
db.session.add(task)
@@ -229,7 +223,7 @@ def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch):
task = ShippingNotice(
task_no='SN-CONFIRM-AP-3',
user_id=1,
process_status='waiting_upload',
upload_status='pending',
current_order_extraction_id=77,
)
db.session.add(task)
@@ -295,7 +289,6 @@ def test_run_single_task_auto_progresses_created_task_with_extraction(app, monke
task_no='SN-CONFIRM-AP-4',
user_id=1,
source_type='review_confirmation',
process_status='created',
current_order_extraction_id=66,
)
db.session.add(task)
@@ -154,7 +154,6 @@ def _task(**kwargs) -> ShippingNotice:
task = ShippingNotice(
task_no=kwargs.pop('task_no', 'SN-FORMAL-EDIT-001'),
source_type='manual',
process_status=kwargs.pop('process_status', 'matched'),
po_number=kwargs.pop('po_number', 'PO-FORMAL-001'),
match_status=kwargs.pop('match_status', 'matched'),
line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]),
@@ -54,12 +54,12 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id))
task1 = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
user_id=int(user.id), source_type='review_confirmation',
source_file_name=document.filename, source_content_hash=document.content_hash,
)
task2 = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
user_id=int(user.id), source_type='review_confirmation',
source_file_name=document.filename, source_content_hash=document.content_hash,
)
db.session.add_all([task1, task2])
@@ -114,7 +114,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
for _ in range(2):
task = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
user_id=int(user.id), source_type='review_confirmation', process_status='parsed',
user_id=int(user.id), source_type='review_confirmation',
source_file_name=document.filename, source_content_hash=document.content_hash,
)
db.session.add(task)
@@ -220,12 +220,11 @@ def test_task_missing_does_not_reopen_confirm():
assert result['reason_code'] == 'task_missing'
def test_project_stage_for_task_created_is_order_creating():
"""正式 OT 仍为 created 时阶段统一为 order_creating,label_key=waiting_system_start。"""
def test_project_stage_for_task_without_domain_facts_is_order_creating():
"""没有履约领域事实时,内部 OT 阶段投影保持 order_creating。"""
task = SimpleNamespace(
id=1,
order_task_id=None,
process_status='created',
current_step=None,
stage_nodes_json=None,
step_payload_json=None,
@@ -233,7 +232,7 @@ def test_project_stage_for_task_created_is_order_creating():
stage = project_stage_for_task(task)
assert stage['code'] == 'order_creating'
assert stage['label_key'] == 'waiting_system_start'
assert stage['source'] == 'process_status'
assert stage['source'] == 'domain_facts'
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
@@ -241,7 +240,7 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
task = SimpleNamespace(
id=1,
order_task_id=9,
process_status='uploaded',
upload_status='uploaded',
current_step='step6_generate_file',
stage_nodes_json=None,
step_payload_json=None,
@@ -261,7 +260,6 @@ def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeyp
task = NS(
task_no='SN-HANG-1',
process_status='created',
current_order_extraction_id=9,
)
finished = NS(
@@ -167,7 +167,7 @@ def test_automation_failed_retryable_when_post_confirm_needs_retry():
'task_no': 'SN-1',
'needs_retry': True,
'status': 'needs_retry',
'task_process_status': 'created',
'task_stage': 'order_review',
},
)
assert result['status'] == 'failed'
@@ -79,7 +79,6 @@ def test_excel_ready_requires_ready_artifact(app) -> None:
task = ShippingNotice(
task_no='SN-EXCEL-READY-BE09',
source_type='manual',
process_status='matched',
export_file_path='/tmp/be09.xlsx',
export_file_name='be09.xlsx',
order_data_version=1,
@@ -31,7 +31,6 @@ def test_log_task_event_dual_write_keeps_match_detail(monkeypatch):
task = SimpleNamespace(
id=1,
task_no='T-STP-1',
process_status='pending_review',
)
tool_common_mod.log_task_event(
task,
@@ -21,7 +21,6 @@ def test_progress_nodes_follow_fixed_order_and_manual_freight():
"""Excel 就绪后货代节点为 manual_takeover,不得投影为 running(首期无货代 RPA)。"""
task = SimpleNamespace(
customer_resolution_status='confirmed',
process_status='waiting_upload',
pending_human_reason=None,
match_status='matched',
review_status=None,
@@ -44,7 +43,6 @@ def test_progress_nodes_mark_inventory_rpa_retrying():
"""库存 RPA 等待中投影为 retrying/running,匹配节点保持 pending。"""
task = SimpleNamespace(
customer_resolution_status='confirmed',
process_status='waiting_inventory',
pending_human_reason='rpa_pending',
match_status=None,
review_status=None,
@@ -61,7 +59,6 @@ def test_progress_nodes_customer_pending_blocks_downstream():
"""客户未确认时下游库存节点保持 pending。"""
task = SimpleNamespace(
customer_resolution_status='pending',
process_status='created',
pending_human_reason=None,
match_status=None,
review_status=None,
@@ -26,7 +26,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl
user_id=user.id,
conversation_id=session.session_id,
source_type='manual',
process_status='waiting_upload',
current_step='step7_upload_freight',
)
db.session.add(notice)
@@ -24,8 +24,8 @@ from app.services.shipping_notice.batch_orchestrator import _should_orchestrate_
def _task(task_no: str, **kwargs) -> ShippingNotice:
"""构造最小发货任务,便于隔离验证处置状态与原流程状态。"""
return ShippingNotice(task_no=task_no, process_status='created', source_type='manual', **kwargs)
"""构造最小发货任务,便于隔离验证生命周期处置。"""
return ShippingNotice(task_no=task_no, source_type='manual', **kwargs)
def test_plain_created_task_can_be_deleted_and_restored(app):
@@ -38,9 +38,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app):
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='误建任务', request_id='req-delete')
db.session.commit()
# 关键断言:删除不篡改 process_status,异步门禁仅因回收站状态停止任务。
# 关键断言:删除仅改变生命周期,异步门禁据此停止任务。
assert outcome == 'deleted'
assert task.process_status == 'created'
assert task.lifecycle_status == 'active'
assert task.deleted_at is not None
assert task_is_active(task) is False
@@ -135,8 +134,8 @@ def test_void_requires_reason_and_rejects_successor(app):
assert task_disposition_capability(task, 'delete').code == 'SHIPPING.TASK_SUCCESSOR_VOID_BLOCKED'
def test_disposition_stops_backend_orchestration_without_changing_process_status(app):
"""后台编排必须读取独立生命周期,不能依赖 process_status 被伪造为 rejected。"""
def test_disposition_stops_backend_orchestration_from_lifecycle(app):
"""后台编排必须读取独立生命周期。"""
with app.app_context():
task = _task('SN-DISPOSITION-ORCHESTRATOR-001')
db.session.add(task)
@@ -145,8 +144,7 @@ def test_disposition_stops_backend_orchestration_without_changing_process_status
assert _should_orchestrate_task(task) is True
move_task_to_recycle_bin(task, actor_id=1, reason='取消处理')
# 关键断言:任务仍为 created,但回收站状态已让编排器停止执行。
assert task.process_status == 'created'
# 关键断言:回收站状态已让编排器停止执行。
assert _should_orchestrate_task(task) is False
@@ -41,7 +41,6 @@ def _task(**kwargs) -> ShippingNotice:
task = ShippingNotice(
task_no=kwargs.pop('task_no', 'SN-RECON-001'),
source_type='manual',
process_status=kwargs.pop('process_status', 'pending_review'),
pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'),
po_number=kwargs.pop('po_number', 'PO-100'),
lines_json=kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]),
@@ -238,7 +237,6 @@ def test_update_notice_line_version_mismatch(app):
"""改单携带过期 order_data_version 不得覆盖。"""
with app.app_context():
task = _task(
process_status='parsed',
pending_human_reason=None,
lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
)
@@ -80,7 +80,6 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
task_no='SN-PARSED-PROJECTION-001',
user_id=user.id,
source_type='manual',
process_status='pending_review',
po_number='4510038672',
source_candidate_id=int(candidate.id),
lines_json=[{
@@ -13,10 +13,10 @@ from app.services.shipping_notice.task_supersession_service import assert_task_n
def _tasks(*, uploaded: bool) -> tuple[ShippingNotice, ShippingNotice, User]:
user = User(username=f'supersession-{uploaded}', email=f'supersession-{uploaded}@example.test', password_hash='x')
old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=None, process_status='uploaded' if uploaded else 'parsed', upload_status='uploaded' if uploaded else None, freight_ref_no='F-1' if uploaded else None)
old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=None, upload_status='uploaded' if uploaded else None, freight_ref_no='F-1' if uploaded else None)
db.session.add_all([user, old]); db.session.flush()
old.user_id = user.id
new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, supersedes_task_id=old.id, process_status='created')
new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, supersedes_task_id=old.id)
db.session.add(new); db.session.commit()
return old, new, user
@@ -52,7 +52,7 @@ def test_inventory_callback_id_is_checked_before_attempt_identity(app):
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
with app.app_context():
task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual', process_status='waiting_inventory')
task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual')
db.session.add(task)
db.session.flush()
first = ShippingTaskInventoryRpaAttempt(
@@ -31,7 +31,6 @@ def workbench_chain_ids(app):
user_id=user.id,
conversation_id=session.session_id,
source_type='manual',
process_status='draft',
current_step='step3_confirm_customer',
)
db.session.add(notice)
@@ -93,7 +92,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'building_order'
notice.review_status = 'pending_confirm'
notice.current_step = 'step4_match_inventory'
notice.customer_id = 1
db.session.commit()
@@ -114,7 +113,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'inventory_matching'
notice.match_status = 'matched'
notice.current_step = 'step4_match_inventory'
db.session.commit()
@@ -132,7 +131,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'waiting_upload'
notice.upload_status = 'pending'
notice.current_step = 'step7_upload_freight'
notice.export_file_path = '/tmp/fake-shipping.xlsx'
db.session.commit()
@@ -151,7 +150,6 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids)
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'upload_failed'
notice.current_step = 'step7_upload_freight'
notice.upload_status = 'failed'
notice.export_file_path = '/tmp/fake-shipping.xlsx'
@@ -45,7 +45,6 @@ def test_workspace_retry_records_actor_and_snapshots(app, client):
user_id=user_id,
shipping_case=case,
source_type='manual',
process_status='failed',
review_status='parse_review',
pending_human_reason='low_confidence',
error_message='timeout',
@@ -27,7 +27,7 @@ def _task(**kwargs):
defaults = {
'task_no': 'OT-1',
'id': 1,
'process_status': 'parsed',
'upload_status': None,
'pending_human_reason': None,
'inventory_lines_json': None,
'inventory_snapshot_id': None,
@@ -57,14 +57,14 @@ def test_project_line_retryable_hides_shortage_and_running():
def test_decide_completed_is_noop():
task = _task(process_status='completed')
task = _task(upload_status='uploaded')
decided = decide_retry_action_only(task, scope='task')
assert decided['action'] == ACTION_NOOP
assert decided['reason_code'] == 'already_completed'
def test_decide_missing_snapshot_fetch(monkeypatch):
task = _task(process_status='parsed', inventory_snapshot_id=None, inventory_lines_json=None)
task = _task(inventory_snapshot_id=None, inventory_lines_json=None)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable',
lambda _t: True,
@@ -74,7 +74,7 @@ def test_decide_missing_snapshot_fetch(monkeypatch):
def test_decide_rpa_pending_already_running():
task = _task(pending_human_reason='rpa_pending', process_status='waiting_inventory')
task = _task(pending_human_reason='rpa_pending')
decided = decide_retry_action_only(task, scope='task')
assert decided['action'] == ACTION_NOOP
assert decided['reason_code'] == 'already_running'
@@ -83,7 +83,6 @@ def test_decide_rpa_pending_already_running():
def test_fulfillable_task_without_excel_continues_auto_progress(monkeypatch):
"""库存已完全匹配但 Excel 尚未生成时,任务级重试必须推进后续 Gate。"""
task = _task(
process_status='matched',
inventory_snapshot_id=7,
inventory_lines_json=[{'part_number': 'PN-1'}],
)