chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑
This commit is contained in:
1 parent
5ef8329bd8
commit
4ec4e57005
183 files changed
+14653
-3936
No files matched your search
@@ -56,6 +56,28 @@ def test_claim_next_shipping_recovers_stale_layout_jobs(app, monkeypatch):
|
||||
assert recovered == [True]
|
||||
|
||||
|
||||
def test_claim_next_shipping_claims_inventory_callback_process_job(app):
|
||||
"""库存 RPA 回调收件 Job 必须由 shipping worker 消费,不能永久停在 queued。"""
|
||||
from app import db
|
||||
from app.jobs import store
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value,
|
||||
status='queued',
|
||||
payload_json={'callback_id': 'callback-test'},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
claimed = store.claim_next(queues=['shipping'])
|
||||
|
||||
assert claimed is not None
|
||||
assert claimed['id'] == job.id
|
||||
assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS
|
||||
|
||||
|
||||
def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
from app import db
|
||||
from app.jobs.queue import _find_shipping_notice_job_id
|
||||
|
||||
@@ -132,6 +132,20 @@ def test_p3_t4_primary_action_matrix(bcode, actions_in, retryable, expected_pa_c
|
||||
assert got['variant'] == variant, label
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_resolved_field_conflict_has_no_current_task_cta():
|
||||
"""字段冲突清零后,保存校验留在底栏,当前任务不得再制造 CTA。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import project_case_primary_action
|
||||
|
||||
action = project_case_primary_action(
|
||||
'waiting_human',
|
||||
{},
|
||||
['view', 'validate'],
|
||||
)
|
||||
|
||||
assert action is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_p3_t2_allowed_actions_inject_reconcile_and_remove_retry():
|
||||
"""[P3 T2] 业务阻断 → REMOVE_SET 删除 retry_stp_auto_create 且注入 reconcile_and_progress。"""
|
||||
@@ -183,6 +197,95 @@ def test_p3_t5_bundle_six_fields_shapes():
|
||||
assert bundle['primary_action'] is None or isinstance(bundle['primary_action'], dict)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'_project_case_formal_gate_summary',
|
||||
lambda _case: {
|
||||
'current_gate': {
|
||||
'gate_code': 'field_completeness',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'next_action_code': 'edit_order_fields',
|
||||
},
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'field_completeness',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'next_action_code': 'edit_order_fields',
|
||||
},
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'next_action_code': 'edit_order_fields',
|
||||
},
|
||||
)
|
||||
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': False, 'can_auto_create': False},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
assert bundle['current_gate']['gate_code'] == 'field_completeness'
|
||||
assert bundle['current_gate']['blocking_reason_code'] == 'required_field_missing'
|
||||
assert bundle['blocking_reason']['code'] == 'required_field_missing'
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
_project_case_formal_gate_facts,
|
||||
)
|
||||
|
||||
facts = _project_case_formal_gate_facts({
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'status': 'pending',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
},
|
||||
'current_blocking_gate': None,
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
})
|
||||
|
||||
assert facts is not None
|
||||
current_gate, blocking_reason, user_status = facts
|
||||
assert current_gate['gate_code'] == 'inventory_source_routing'
|
||||
assert blocking_reason['code'] is None
|
||||
assert user_status == 'running'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation():
|
||||
"""建单前校验未提交时必须提示人工保存,不能伪装为自动处理中。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
_project_case_formal_gate_facts,
|
||||
)
|
||||
|
||||
facts = _project_case_formal_gate_facts({
|
||||
'current_gate': {
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
'status': 'pending',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
},
|
||||
})
|
||||
|
||||
assert facts is not None
|
||||
current_gate, blocking_reason, user_status = facts
|
||||
assert current_gate['gate_code'] == 'order_freeze_readiness'
|
||||
assert blocking_reason['code'] is None
|
||||
assert user_status == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询)
|
||||
# ============================================================
|
||||
|
||||
@@ -4,6 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -60,3 +62,44 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
|
||||
content = sentinel.read_text(encoding="utf-8")
|
||||
assert "scope_id=hxops-rpa-test-data" in content
|
||||
assert "host=WIN-RPA-01" in content
|
||||
|
||||
|
||||
def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_path, monkeypatch):
|
||||
"""断言底层 HTTP 卡住时,主 Worker 仍能立即继续扫描 Trigger。"""
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
release_request = threading.Event()
|
||||
request_started = threading.Event()
|
||||
calls: list[dict] = []
|
||||
|
||||
def stalled_post(payload):
|
||||
calls.append(payload)
|
||||
request_started.set()
|
||||
release_request.wait(timeout=2)
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(module, "post_heartbeat", stalled_post)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15")
|
||||
started = time.monotonic()
|
||||
sent_at = module.maybe_send_heartbeat(
|
||||
trigger_dir=tmp_path,
|
||||
drop_dir=tmp_path,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
|
||||
# 核心断言:投递而非等待卡住的 HTTP 请求,扫描循环可立即继续。
|
||||
assert time.monotonic() - started < 0.2
|
||||
assert sent_at > 0
|
||||
assert request_started.wait(timeout=0.5)
|
||||
|
||||
module.maybe_send_heartbeat(
|
||||
trigger_dir=tmp_path,
|
||||
drop_dir=tmp_path,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
# 同一时刻只允许一个后台请求,避免后端异常时线程无限累积。
|
||||
assert len(calls) == 1
|
||||
release_request.set()
|
||||
assert module._HEARTBEAT_THREAD is not None
|
||||
module._HEARTBEAT_THREAD.join(timeout=1)
|
||||
@@ -185,6 +185,138 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
}
|
||||
|
||||
|
||||
def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_path):
|
||||
"""Crane 动态 Warehouse 在导出前未知时,v2 trigger 不应被身份校验拒绝。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_crane_dynamic.json"
|
||||
source = {
|
||||
"source_code": "CRANE",
|
||||
"connector_type": "crane",
|
||||
"task_no": "SN-CRANE-DYNAMIC",
|
||||
"callback_id": "PSR-CRANE-DYNAMIC:C1",
|
||||
"source_run_no": "PSR-CRANE-DYNAMIC",
|
||||
"attempt_no": 2,
|
||||
"lease_token": "lease-crane",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-CRANE-DYNAMIC:batch:C1",
|
||||
"batch_run_no": "BATCH-CRANE-DYNAMIC",
|
||||
"task_no": "SN-CRANE-DYNAMIC",
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
assert completed["results"][0]["callback_id"] == "PSR-CRANE-DYNAMIC:C1"
|
||||
assert completed["results"][0]["expected_warehouse_id"] is None
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch, tmp_path):
|
||||
"""可识别的非法 batch trigger 必须回传 batch callback_id,供平台记录拒绝终态。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_invalid.json"
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-INVALID:batch:C1",
|
||||
"batch_run_no": "BATCH-INVALID",
|
||||
"task_no": "SN-BATCH-INVALID",
|
||||
"inventory_sources": [{
|
||||
"source_code": "DBS",
|
||||
"connector_type": "dbs",
|
||||
"task_no": "SN-BATCH-INVALID",
|
||||
"callback_id": "PSR-BATCH-INVALID:C1",
|
||||
"source_run_no": "PSR-BATCH-INVALID",
|
||||
"attempt_no": 2,
|
||||
"lease_token": "lease-batch",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] == "BATCH-INVALID:batch:C1"
|
||||
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
|
||||
|
||||
|
||||
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
|
||||
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_interrupt.json"
|
||||
source = {
|
||||
"source_code": "CRANE",
|
||||
"connector_type": "crane",
|
||||
"task_no": "SN-CRANE-INTERRUPT",
|
||||
"callback_id": "PSR-CRANE-INTERRUPT:C1",
|
||||
"source_run_no": "PSR-CRANE-INTERRUPT",
|
||||
"attempt_no": 1,
|
||||
"lease_token": "lease-interrupt",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": "BATCH-INTERRUPT:batch:C1",
|
||||
"batch_run_no": "BATCH-INTERRUPT",
|
||||
"task_no": "SN-CRANE-INTERRUPT",
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
stopped = []
|
||||
|
||||
class _Context:
|
||||
def close(self):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
class _Playwright:
|
||||
def stop(self):
|
||||
stopped.append(True)
|
||||
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda *_args, **_kwargs: (_Playwright(), _Context(), object(), tmp_path / "profile"))
|
||||
monkeypatch.setattr(worker, "_ensure_crane_session", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(worker, "_export_crane_inventory_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert stopped == [True]
|
||||
assert [path for path, _body in callbacks] == ["/api/shipping-notice/rpa/inventory-batch-claimed"]
|
||||
assert trigger_path.is_file()
|
||||
assert not (processed_dir / trigger_path.name).exists()
|
||||
|
||||
|
||||
def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1108,6 +1240,45 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
}
|
||||
|
||||
|
||||
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
|
||||
"""DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
class _FakePage:
|
||||
def set_default_timeout(self, value: int) -> None:
|
||||
observed["timeout"] = value
|
||||
|
||||
class _FakeContext:
|
||||
pages = [_FakePage()]
|
||||
|
||||
class _FakeChromium:
|
||||
def launch_persistent_context(self, profile: str, **kwargs):
|
||||
observed["profile"] = profile
|
||||
return _FakeContext()
|
||||
|
||||
class _FakePlaywright:
|
||||
chromium = _FakeChromium()
|
||||
|
||||
class _FakeStarter:
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
tmp_path / "downloads", reuse_dsv_session=True
|
||||
)
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
assert profile_dir == tmp_path / "profile" / "dsv360_session"
|
||||
assert observed["profile"] == str(profile_dir)
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
|
||||
|
||||
def test_is_dsv_username_page_ignores_login_method_page_text():
|
||||
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -16,6 +16,10 @@ def _load_dsv_report_export():
|
||||
return _load_rpa_module("dsv_report_export")
|
||||
|
||||
|
||||
def _load_dsv_auth_login_flow():
|
||||
return _load_rpa_module("dsv_auth_login_flow")
|
||||
|
||||
|
||||
def _load_rpa_module(module_name: str):
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
|
||||
scripts_dir = str(module_path.parent)
|
||||
@@ -195,6 +199,128 @@ def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(
|
||||
reset.assert_not_called()
|
||||
|
||||
|
||||
def test_dsv_session_prepare_emits_elapsed_stage_logs(monkeypatch):
|
||||
"""DSV session 准备应记录完整耗时,供真实运行区分认证和首页等待。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
chain = MagicMock()
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
|
||||
monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(worker, "_is_dsv_in_report_navigation_context", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", MagicMock())
|
||||
|
||||
worker._ensure_dsv_session(page, "https://s360.dbschenker.com/")
|
||||
|
||||
assert [call.args[:2] for call in chain.call_args_list] == [
|
||||
("session_prepare", "start"),
|
||||
("session_prepare", "end"),
|
||||
]
|
||||
|
||||
|
||||
def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch):
|
||||
"""Reports 到参数页的整段导航应记录耗时,不能只依赖零散 DOM 调试日志。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
chain = MagicMock()
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
|
||||
monkeypatch.setattr(worker, "_env", lambda _key, default=None: "")
|
||||
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
|
||||
worker._navigate_dsv_to_report_form(
|
||||
page,
|
||||
{"navigation": {"program_label": "AWS", "report_name": "On Hand Inventory by Location"}},
|
||||
)
|
||||
|
||||
assert [call.args[:2] for call in chain.call_args_list] == [
|
||||
("report_navigation", "start"),
|
||||
("report_navigation", "end"),
|
||||
]
|
||||
|
||||
|
||||
def test_dsv_menu_item_uses_compatibility_fallback_only_after_fast_path_misses(monkeypatch):
|
||||
"""快速菜单点击未确认下一级时,必须保留原兼容路径,避免降低 DSV 成功率。"""
|
||||
navigation = _load_rpa_module("dsv_navigation")
|
||||
page = MagicMock()
|
||||
compatibility = MagicMock()
|
||||
monkeypatch.setattr(navigation, "_try_dsv_menu_item_fast_path", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(navigation, "_click_dsv_menu_item_compat", compatibility)
|
||||
|
||||
navigation._click_dsv_menu_item(page, "AWS", next_text="Inventory")
|
||||
|
||||
compatibility.assert_called_once_with(page, "AWS", next_text="Inventory")
|
||||
|
||||
|
||||
def test_dsv_report_group_skips_compatibility_fallback_after_fast_path_confirms(monkeypatch):
|
||||
"""快速路径确认报表已展开后,不应再触发耗时的 Report Group 兼容点击。"""
|
||||
navigation = _load_rpa_module("dsv_navigation")
|
||||
page = MagicMock()
|
||||
compatibility = MagicMock()
|
||||
monkeypatch.setattr(navigation, "_try_dsv_report_group_fast_path", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(navigation, "_click_dsv_report_group_compat", compatibility)
|
||||
|
||||
navigation._click_dsv_report_group(page, "Inventory", next_text="On Hand Inventory by Location")
|
||||
|
||||
compatibility.assert_not_called()
|
||||
|
||||
|
||||
def test_dsv_report_execution_emits_parameter_and_download_stage_logs(monkeypatch):
|
||||
"""报表结果就绪与 Excel 下载应分段计时,且不应等待不可靠的 networkidle。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
download = MagicMock()
|
||||
download_context = MagicMock()
|
||||
download_context.__enter__.return_value = MagicMock(value=download)
|
||||
download_context.__exit__.return_value = False
|
||||
page.expect_download.return_value = download_context
|
||||
chain = MagicMock()
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
|
||||
monkeypatch.setattr(worker, "_fill_report_parameters", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_view_report", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_dsv_report_has_inventory_data_rows", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(worker, "_click_dsv_export_excel", MagicMock())
|
||||
|
||||
assert worker._run_dsv_inventory_export_from_form(page, {}) is download
|
||||
|
||||
assert [call.args[:2] for call in chain.call_args_list] == [
|
||||
("report_parameter_fill", "start"),
|
||||
("report_parameter_fill", "end"),
|
||||
("report_execute_and_download", "start"),
|
||||
("report_result_ready", "start"),
|
||||
("report_result_ready", "end"),
|
||||
("excel_export_and_download", "start"),
|
||||
("excel_download_event", "start"),
|
||||
("excel_download_event", "end"),
|
||||
("excel_export_and_download", "end"),
|
||||
("report_execute_and_download", "end"),
|
||||
]
|
||||
page.wait_for_load_state.assert_not_called()
|
||||
|
||||
|
||||
def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
|
||||
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
|
||||
flow = _load_dsv_auth_login_flow()
|
||||
page = MagicMock()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password")
|
||||
selector_wait = MagicMock()
|
||||
auth_ready = MagicMock()
|
||||
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
|
||||
monkeypatch.setattr(flow, "_wait_for_visible_selector", selector_wait)
|
||||
monkeypatch.setattr(flow, "_wait_for_dsv_auth_page_ready", auth_ready)
|
||||
|
||||
flow._maybe_auto_login_dsv(page)
|
||||
|
||||
# 核心断言:会话已在 Portal 时,不能走用户名 15 秒探测或认证页轮询。
|
||||
selector_wait.assert_not_called()
|
||||
auth_ready.assert_not_called()
|
||||
|
||||
|
||||
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
|
||||
"""program/report 变化时仍应回 portal 首页。"""
|
||||
worker = _load_dsv_report_export()
|
||||
|
||||
@@ -205,6 +205,84 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a
|
||||
assert count >= 1
|
||||
|
||||
|
||||
def test_contract_04a_sweeper_skips_manual_draft_waiting_for_user_validation(app):
|
||||
"""人工草稿等待“保存并校验”时,恢复扫描不得再次改写 Draft 版本。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
manual_case = SimpleNamespace(
|
||||
id=41,
|
||||
case_no='SORC-P1-04A',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
current_draft=SimpleNamespace(
|
||||
header_values_json={},
|
||||
lines_json=[{'values': {'part_number': {'source': 'manual', 'value': 'P-1'}}}],
|
||||
),
|
||||
)
|
||||
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[41]), patch.object(
|
||||
sw, '_scan_stale_inventory_attempts', return_value=0,
|
||||
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
|
||||
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
|
||||
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as review_case, patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
) as coordinator:
|
||||
mock_session = MagicMock()
|
||||
mock_session.begin_nested.return_value = MagicMock()
|
||||
type(mock_db).session = mock_session
|
||||
review_case.query.filter_by.return_value.with_for_update.return_value.first.return_value = manual_case
|
||||
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
# 这条 Case 必须留给用户显式保存;后台补偿不应启动校验或推进。
|
||||
assert count == 0
|
||||
coordinator.assert_not_called()
|
||||
|
||||
|
||||
def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
"""批量协调也不得为人工草稿重复写入 validation 版本。"""
|
||||
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
|
||||
|
||||
run = SimpleNamespace(id=42, run_no='SNER-P1-04B')
|
||||
case = SimpleNamespace(
|
||||
id=42,
|
||||
case_no='SORC-P1-04B',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=420,
|
||||
candidate_id=42,
|
||||
run_id=42,
|
||||
run=run,
|
||||
owner_user_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=8,
|
||||
header_values_json={},
|
||||
lines_json=[{'values': {'part_number': {'source': 'manual', 'value': 'P-1'}}}],
|
||||
),
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.ShippingOrderReviewCase',
|
||||
) as review_case, patch.object(
|
||||
coord.db, 'session', MagicMock(),
|
||||
) as session_mock, patch.object(
|
||||
coord, '_customer_step_for_case', return_value=('skipped', None),
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.validate_draft',
|
||||
) as validate_mock, patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'waiting_manual_validation'},
|
||||
):
|
||||
review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
|
||||
SimpleNamespace(id=42),
|
||||
]
|
||||
session_mock.get.return_value = case
|
||||
|
||||
result = coord.reconcile_run_review_cases_for_auto_progress(run=run)
|
||||
|
||||
validate_mock.assert_not_called()
|
||||
assert result[0]['validate_status'] == 'waiting_manual_validation'
|
||||
|
||||
|
||||
def test_contract_05_recovery_tick_scans_stale_inventory_attempts(app):
|
||||
"""合同 5:shipping recovery tick 必须调用逐源库存超时扫描。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
@@ -9,6 +9,8 @@ tests/test_shipping_auto_progress_p0_3.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
@@ -137,6 +139,34 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 1
|
||||
|
||||
|
||||
def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
|
||||
"""人工导航动作不得因 Gate 责任方为 worker 而被自动投递执行。"""
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=903, task_id=int(task.id))
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_rpa_timeout'
|
||||
gate.next_action_code = 'upload_inventory_file'
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'upload_inventory_file'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
# 同步事实是本用例之外的职责;这里固定复现“同步后仍需人工导航”的当前 Gate。
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
):
|
||||
result = submit_auto_progress(task=task, trigger='callback_recovery')
|
||||
|
||||
assert result['status'] == 'waiting_human'
|
||||
assert result['gate_code'] == 'inventory_preparation'
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
|
||||
|
||||
|
||||
def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -42,9 +42,11 @@ def test_manual_upload_records_receipt_asset(app):
|
||||
)
|
||||
attempt = record_manual_upload(
|
||||
task, artifact_id=artifact.id, evidence_asset_no=payload['asset_no'], operator_id=user.id,
|
||||
freight_ref_no='FREIGHT-RECEIPT-1',
|
||||
)
|
||||
assert attempt.mode == 'manual'
|
||||
assert attempt.status == 'succeeded'
|
||||
assert attempt.evidence_asset_id is not None
|
||||
assert attempt.freight_ref_no == 'FREIGHT-RECEIPT-1'
|
||||
assert db.session.get(type(reservation), reservation.id).status == 'uploaded'
|
||||
assert ShippingUploadAttempt.query.count() == 1
|
||||
@@ -34,6 +34,13 @@ def _with_v2_batch_envelope(payload: dict) -> dict:
|
||||
return v2_inventory_batch_payload(payload)
|
||||
|
||||
|
||||
def _process_batch_callback(payload: dict) -> dict:
|
||||
"""在测试中执行 Worker 的异步 batch 处理体,保留既有业务断言。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
||||
|
||||
return process_rpa_report_inventory_batch(_with_v2_batch_envelope(payload))
|
||||
|
||||
|
||||
def _tool_headers():
|
||||
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
|
||||
|
||||
@@ -418,11 +425,11 @@ def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path):
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-EMPTY-ITEM",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{}],
|
||||
}))
|
||||
})
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "failed"
|
||||
assert result["data"]["result_status"] == "failed"
|
||||
@@ -444,7 +451,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-MIXED",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [
|
||||
@@ -462,7 +469,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
"error_message": "timeout",
|
||||
},
|
||||
],
|
||||
}))
|
||||
})
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "partial_failed"
|
||||
assert result["data"]["result_status"] == "partial_failed"
|
||||
@@ -484,11 +491,11 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-MAPPING-CONFIRMED",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
|
||||
}))
|
||||
})
|
||||
assert result["success_count"] == 1
|
||||
snapshot = ShippingInventoryFile.query.filter_by(rpa_run_no="RUN-MAPPING-CONFIRMED").one()
|
||||
assert snapshot.mapping_source == "parsing_profile"
|
||||
@@ -503,7 +510,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-ALL-FAIL",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{
|
||||
@@ -513,7 +520,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
|
||||
"success": False,
|
||||
"error_message": "timeout",
|
||||
}],
|
||||
}))
|
||||
})
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "failed"
|
||||
assert result["failed_count"] == 1
|
||||
@@ -597,8 +604,9 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
|
||||
|
||||
|
||||
def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
"""batch 顶层 run_no 应注入 result item,带 task_no 的成功项可入库。"""
|
||||
"""任务型 RPA 回调只收件入队,不得同步解析 Excel 或推进库存任务。"""
|
||||
from app import db
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
@@ -625,7 +633,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
receipt = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
"run_no": "RUN-BATCH-TOP",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
@@ -636,11 +644,40 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
}],
|
||||
})
|
||||
}))
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["success_count"] == 1
|
||||
assert receipt["status"] == "ok"
|
||||
assert receipt["result_status"] == "accepted"
|
||||
assert task.inventory_snapshot_id is None
|
||||
job = db.session.get(Job, int(receipt["data"]["job_id"]))
|
||||
assert job is not None
|
||||
assert job.status == "queued"
|
||||
assert job.job_type == "shipping_inventory_callback_process"
|
||||
assert job.payload_json["batch_run_no"] == "RUN-BATCH-TOP"
|
||||
received_path = Path(job.payload_json["results"][0]["file_path"])
|
||||
assert received_path.is_file()
|
||||
assert received_path != sample
|
||||
assert received_path.parent.name == "test-callback_RUN-BATCH-TOP"
|
||||
sample.unlink()
|
||||
replay = rpa_report_inventory_batch(_with_v2_batch_envelope({
|
||||
"run_no": "RUN-BATCH-TOP",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
"task_no": task.task_no,
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(sample),
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
}],
|
||||
}))
|
||||
assert replay["result_status"] == "accepted"
|
||||
assert replay["data"]["job_id"] == job.id
|
||||
|
||||
result = _process_batch_callback(job.payload_json)
|
||||
db.session.refresh(task)
|
||||
assert result["result_status"] == "success"
|
||||
assert task.inventory_snapshot_id is not None
|
||||
|
||||
|
||||
@@ -669,7 +706,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-BATCH-FAIL",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
@@ -683,7 +720,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.pending_human_reason == "rpa_pending"
|
||||
assert task.pending_human_reason == "rpa_exhausted"
|
||||
assert task.error_message
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
@@ -745,7 +782,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
|
||||
|
||||
with app.app_context():
|
||||
before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
|
||||
result = rpa_report_inventory_batch({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-UNKNOWN-TASK",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
@@ -819,7 +856,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-BATCH-NO-IDENT",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
@@ -855,7 +892,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
warmup = rpa_report_inventory_batch({
|
||||
warmup = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "scheduled",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
@@ -886,7 +923,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "on_demand",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
@@ -931,7 +968,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
wb.close()
|
||||
|
||||
with app.app_context():
|
||||
first_result = rpa_report_inventory_batch({
|
||||
first_result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "scheduled",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
@@ -944,7 +981,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
original_lines = list(snap.inventory_lines_json or [])
|
||||
assert first_result["success_count"] == 1
|
||||
|
||||
second_result = rpa_report_inventory_batch({
|
||||
second_result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "scheduled",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
@@ -1012,7 +1049,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
db.session.commit()
|
||||
before_b_status = task_b.pending_human_reason
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "on_demand",
|
||||
"results": [
|
||||
@@ -1040,6 +1077,65 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
assert task_b.pending_human_reason == before_b_status
|
||||
|
||||
|
||||
def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, monkeypatch):
|
||||
"""Excel 入库失败前不得把逐源 RPA Attempt 标为成功或触发自动推进。"""
|
||||
from app import db
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "failed_before_confirm.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
callback_calls: list[dict] = []
|
||||
|
||||
def fail_loaded(*_args, **_kwargs):
|
||||
raise RuntimeError("loaded boom")
|
||||
|
||||
def record_per_source_callback(*_args, **kwargs):
|
||||
callback_payload = dict(kwargs.get("callback_payload") or {})
|
||||
if callback_payload.get("inventory_file_no"):
|
||||
callback_calls.append(callback_payload)
|
||||
return "succeeded", None
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response",
|
||||
fail_loaded,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler",
|
||||
record_per_source_callback,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-DEFER-CONFIRM",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-DEFER-CONFIRM")
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-BATCH-DEFER-CONFIRM",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
"DSV360_AWSDU",
|
||||
success=True,
|
||||
file_path=str(sample),
|
||||
task_no=task.task_no,
|
||||
)],
|
||||
})
|
||||
|
||||
assert result["failed_count"] == 1
|
||||
# 关键断言:保存点内入库失败时,禁止先写 RPA 成功事实并创建后续自动推进。
|
||||
assert callback_calls == []
|
||||
|
||||
|
||||
def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, monkeypatch):
|
||||
"""共享快照被另一任务复用失败时,不得影响已关联任务的 active link。"""
|
||||
from app import db
|
||||
@@ -1075,7 +1171,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
db.session.add_all([task_ok, task_fail])
|
||||
db.session.commit()
|
||||
|
||||
ok_result = rpa_report_inventory_batch({
|
||||
ok_result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "on_demand",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
@@ -1097,7 +1193,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
"app.services.shipping_notice.inventory_rpa_workflow.ingest_inventory_file",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("ingest boom")),
|
||||
)
|
||||
fail_result = rpa_report_inventory_batch({
|
||||
fail_result = _process_batch_callback({
|
||||
"run_no": run_no,
|
||||
"trigger_type": "on_demand",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
@@ -1282,7 +1378,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
|
||||
"run_no": "RUN-MOVE-FAIL",
|
||||
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
|
||||
}
|
||||
result = rpa_report_inventory_batch(payload)
|
||||
result = _process_batch_callback(payload)
|
||||
queue = callback_cleanup_queue_dir()
|
||||
jobs = list(queue.glob("move_*.json")) if queue else []
|
||||
|
||||
@@ -1328,7 +1424,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
|
||||
"run_no": "RUN-QUARANTINE-FAIL",
|
||||
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
|
||||
}
|
||||
result = rpa_report_inventory_batch(payload)
|
||||
result = _process_batch_callback(payload)
|
||||
queue = callback_cleanup_queue_dir()
|
||||
jobs = list(queue.glob("move_*.json")) if queue else []
|
||||
|
||||
|
||||
@@ -398,7 +398,7 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-REV-DL')
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='TODO-REV-DL')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
@@ -408,6 +408,15 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
'conflicts': [],
|
||||
}],
|
||||
}
|
||||
from app.models import ShippingOrderCandidate
|
||||
|
||||
db.session.add(ShippingOrderCandidate(
|
||||
candidate_no='CAND-TODO-REV-DL',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='todo-review-deep-link',
|
||||
order_extraction_run_id=run.id,
|
||||
))
|
||||
db.session.commit()
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
assert cases
|
||||
@@ -423,12 +432,38 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
assert hit['conversation_id'] == session.session_id
|
||||
assert hit['can_handle'] is True
|
||||
assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench'
|
||||
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
|
||||
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
|
||||
'available', 'current', 'unavailable', 'unavailable',
|
||||
]
|
||||
|
||||
counts = count_my_todos(user.id)
|
||||
assert counts['pending'] >= 1
|
||||
assert counts['total_pending_badge'] == counts['pending']
|
||||
|
||||
|
||||
def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
|
||||
"""历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-EMPTY-CASE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': []}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||||
hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no)
|
||||
assert hit['ui_state']['lifecycle_stage'] is None
|
||||
assert hit['ui_state']['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_list_my_todos_includes_orphan_parse_failed_intake(app):
|
||||
"""
|
||||
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
|
||||
@@ -483,6 +518,8 @@ def test_list_my_todos_includes_orphan_parse_failed_intake(app):
|
||||
assert hit['source_file_name'] == 'orphan-fail.pdf'
|
||||
assert hit['can_handle'] is True
|
||||
assert hit['ui_state']['summary']['entry_surface'] == 'conversation_processing'
|
||||
assert hit['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
assert hit['ui_state']['lifecycle_entries'] == []
|
||||
|
||||
filtered = list_my_todos(
|
||||
user.id, bucket='pending', page=1, page_size=50, todo_category='intake_parse',
|
||||
|
||||
@@ -6,7 +6,9 @@ tests/test_shipping_notice_ui_state.py
|
||||
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
|
||||
"""
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_PARSE_REVIEW,
|
||||
@@ -80,6 +82,19 @@ def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
assert "stp_facts" not in state["summary"]
|
||||
|
||||
|
||||
def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
"""列表等轻量调用默认不得加载阶段工作面详情。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual")
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
detailed_state = build_task_ui_state(task, include_stage_context=True)
|
||||
|
||||
# 关键断言:只有详情接口显式请求时才查询行、Artifact 和上传 Attempt。
|
||||
assert "stage_context" not in state
|
||||
assert "stage_context" in detailed_state
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
|
||||
"""业务 UI 只消费四阶段与后端统一 actions,不再要求前端解释旧七步。"""
|
||||
with app.app_context():
|
||||
@@ -98,6 +113,111 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap
|
||||
assert all("code" in item and "kind" in item for item in state["actions"]["secondary"])
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
|
||||
"""正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-LIFECYCLE-ENTRIES",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
assert state["lifecycle_stage"] == "order_review"
|
||||
assert state["lifecycle_entries"] == [
|
||||
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
]
|
||||
|
||||
|
||||
def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
|
||||
"""被替代的 Execution 不能继续给正式工作台下发历史 Gate 或按钮。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
)
|
||||
|
||||
user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.status = 'superseded'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['process_gate'] is None
|
||||
|
||||
|
||||
def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
|
||||
"""正式 Gate 与旧任务字段冲突时,任务详情必须与批次中心同样以 Gate 裁决阶段。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-UI-GATE-AUTHORITY',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
# 模拟历史字段尚未同步:旧字段仍像解析复核。
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.current_gate_code = 'inventory_matching'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
assert state['stage']['code'] == 'fulfillment_prep'
|
||||
assert state['current_step']['code'] == 'fulfillment_prep'
|
||||
assert [entry['state'] for entry in state['lifecycle_entries']] == [
|
||||
'available', 'available', 'current', 'unavailable',
|
||||
]
|
||||
|
||||
|
||||
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
|
||||
"""正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-UI-UPLOAD-GATE-AUTHORITY',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
|
||||
execution.current_gate_code = 'manual_upload_handoff'
|
||||
db.session.flush()
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['lifecycle_stage'] == 'upload_complete'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
assert state['stage']['code'] == 'upload_complete'
|
||||
assert [entry['state'] for entry in state['lifecycle_entries']] == [
|
||||
'available', 'available', 'available', 'current',
|
||||
]
|
||||
|
||||
|
||||
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
|
||||
"""库存匹配/上传结果只映射四个业务阶段。"""
|
||||
with app.app_context():
|
||||
@@ -113,7 +233,10 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(
|
||||
upload_status="uploaded",
|
||||
)
|
||||
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
|
||||
assert build_task_ui_state(upload)["stage"]["code"] == "upload_complete"
|
||||
upload_state = build_task_ui_state(upload, include_stage_context=True)
|
||||
assert upload_state["stage"]["code"] == "upload_complete"
|
||||
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
|
||||
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
|
||||
|
||||
|
||||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
@@ -130,7 +253,7 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
|
||||
|
||||
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
"""Excel 待人工上传登记应进入任务处理工作台(下载 + 登记)。"""
|
||||
"""Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-EXPORT",
|
||||
@@ -149,10 +272,59 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
assert "download_excel" in button_ids
|
||||
# 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。
|
||||
assert "download_excel" not in button_ids
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypatch) -> None:
|
||||
"""下载入口必须由后端 Artifact 解析结果裁决,而不是由遗留文件名裁决。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-RESOLVED-EXPORT",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/shipping-export.xlsx",
|
||||
export_file_name="shipping-export.xlsx",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (object(), 'shipping-export.xlsx'),
|
||||
)
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
|
||||
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-GATE-EXPORT", source_type="manual")
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (None, 'shipping-export.xlsx'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda _task: {
|
||||
'current_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
|
||||
'current_blocking_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
|
||||
'primary_action': {'code': 'retry_freight_upload_rpa', 'label': '重新上传'},
|
||||
'action_presentation': [],
|
||||
},
|
||||
)
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['actions']['primary']['code'] == 'retry_freight_upload_rpa'
|
||||
assert [item['code'] for item in state['actions']['secondary']] == ['download_excel']
|
||||
|
||||
|
||||
def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
|
||||
with app.app_context():
|
||||
@@ -203,12 +375,263 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
],
|
||||
},
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
state = build_task_ui_state(task, include_stage_context=True)
|
||||
rows = state["summary"]["stp_facts"]["line_resolutions"]
|
||||
assert rows[0]["effective_reservation_id"] == "3000092917"
|
||||
assert rows[0]["part_number"] == "PN-1"
|
||||
assert rows[0]["resolved_inventory_source_code"] == "DBS_DUB"
|
||||
assert rows[0]["inventory_file_no"] == "INV-1"
|
||||
stage_context = state["stage_context"]
|
||||
assert stage_context["preparation"]["status"] == "ready"
|
||||
assert stage_context["preparation"]["lines"] == [{
|
||||
"line_key": None,
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"required_qty": None,
|
||||
"available_qty": None,
|
||||
"shortage_qty": None,
|
||||
"source_code": "DBS_DUB",
|
||||
"status": "ok",
|
||||
}]
|
||||
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
|
||||
assert stage_context["upload"]["outcome"] == "not_started"
|
||||
|
||||
|
||||
def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
|
||||
"""通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STRUCTURED-MATCH",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_source_code="DBS_DUB",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
line_results_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="7",
|
||||
matched_qty="7",
|
||||
shortage_qty="3",
|
||||
reservation_id="RSV-1",
|
||||
part_number="PN-1",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
assert preparation["has_match_result"] is True
|
||||
assert preparation["lines"] == [{
|
||||
"line_key": "line-1",
|
||||
"reservation_id": "RSV-1",
|
||||
"part_number": "PN-1",
|
||||
"required_qty": "10",
|
||||
"available_qty": "7",
|
||||
"shortage_qty": "3",
|
||||
"source_code": "DBS_DUB",
|
||||
"status": "matched",
|
||||
}]
|
||||
|
||||
|
||||
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
|
||||
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLine(
|
||||
notice_id=task.id,
|
||||
position=0,
|
||||
line_key="line-frozen-1",
|
||||
reservation_id="RSV-FROZEN",
|
||||
part_number="PN-FROZEN",
|
||||
required_qty="6",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
|
||||
|
||||
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
|
||||
assert preparation["frozen_order_lines"] == [{
|
||||
"line_key": "line-frozen-1",
|
||||
"reservation_id": "RSV-FROZEN",
|
||||
"part_number": "PN-FROZEN",
|
||||
"required_qty": "6.00000000",
|
||||
}]
|
||||
assert preparation["lines"] == []
|
||||
assert preparation["has_match_result"] is False
|
||||
|
||||
|
||||
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
||||
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
with app.app_context():
|
||||
inventory_path = tmp_path / "task-inventory.xlsx"
|
||||
inventory_path.write_bytes(b"inventory-content")
|
||||
task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual")
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no="SIF-UI-DOWNLOAD",
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name="task-inventory.xlsx",
|
||||
snapshot_status="ready",
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
db.session.flush()
|
||||
|
||||
# 未建立 task link 时不得因为文件存在而放行下载。
|
||||
assert resolve_task_inventory_download(task) is None
|
||||
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
is_active=True,
|
||||
access_mode="readonly",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
resolved = resolve_task_inventory_download(task)
|
||||
assert resolved is not None
|
||||
assert resolved[0] == inventory_path.resolve()
|
||||
assert resolved[1] == "task-inventory.xlsx"
|
||||
|
||||
|
||||
def test_workspace_inventory_download_requires_owned_active_file(app, client, tmp_path) -> None:
|
||||
"""库存下载路由只能返回当前用户任务的 active link 文件,不能泄漏其他任务或无关联文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='inventory-download-owner', email='inventory-download-owner@example.com')
|
||||
other = User(username='inventory-download-other', email='inventory-download-other@example.com')
|
||||
db.session.add_all([owner, other])
|
||||
db.session.flush()
|
||||
inventory_path = tmp_path / 'inventory-download.xlsx'
|
||||
inventory_path.write_bytes(b'inventory-download-content')
|
||||
task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual')
|
||||
no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual')
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
|
||||
storage_path=str(inventory_path),
|
||||
source_file_name='inventory-download.xlsx',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, no_file_task, inventory_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=task.id,
|
||||
inventory_file_id=inventory_file.id,
|
||||
is_active=True,
|
||||
access_mode='readonly',
|
||||
))
|
||||
db.session.commit()
|
||||
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
|
||||
|
||||
# 关键断言:活动 link 文件可下载,并以服务端原始内容响应。
|
||||
success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
|
||||
assert success.status_code == 200
|
||||
assert success.data == b'inventory-download-content'
|
||||
assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '')
|
||||
|
||||
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
|
||||
missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
|
||||
assert missing.status_code == 404
|
||||
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
|
||||
forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
|
||||
assert forbidden.status_code == 404
|
||||
|
||||
|
||||
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
|
||||
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STRUCTURED-PARTIAL",
|
||||
source_type="manual",
|
||||
match_status="partial",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={"line_inventory_resolutions": [{
|
||||
"line_index": 0,
|
||||
"line_key": "line-1",
|
||||
"effective_reservation_id": "RSV-LEGACY",
|
||||
"part_number": "PN-LEGACY",
|
||||
"inventory_file_no": "INV-1",
|
||||
"disposition": "ok",
|
||||
}]},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="10",
|
||||
available_qty="8",
|
||||
shortage_qty="2",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
line = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]["lines"][0]
|
||||
assert line["reservation_id"] == "RSV-LEGACY"
|
||||
assert line["part_number"] == "PN-LEGACY"
|
||||
assert line["available_qty"] == "8"
|
||||
|
||||
|
||||
def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch) -> None:
|
||||
"""正式详情接口必须原样携带通知准备摘要,供工作台首屏消费。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.api.workspace import shipping_notice as api
|
||||
from app.services.shipping_notice import query_service
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-DETAIL-CONTEXT",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_method="stp_line_match",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
line_key="line-1",
|
||||
line_index=0,
|
||||
match_result="matched",
|
||||
inventory_status="ready",
|
||||
required_qty="2",
|
||||
available_qty="2",
|
||||
shortage_qty="0",
|
||||
reservation_id="RSV-DETAIL",
|
||||
part_number="PN-DETAIL",
|
||||
inventory_source_code="DBS_DUB",
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1, role='user'))
|
||||
monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task)
|
||||
monkeypatch.setattr(api, '_ok', lambda data: data)
|
||||
|
||||
payload = api.workspace_shipping_task_detail(task.task_no)
|
||||
preparation = payload['ui_state']['stage_context']['preparation']
|
||||
assert preparation['has_match_result'] is True
|
||||
assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL'
|
||||
|
||||
|
||||
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
|
||||
@@ -1380,7 +1380,9 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='preview-admin', email='preview-admin@example.com', role='admin', status='active')
|
||||
other_user = User(username='other-admin', email='other-admin@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.add(other_user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-PREVIEW-SAMPLE', owner_user_id=user.id, original_filename='preview.pdf',
|
||||
@@ -1410,7 +1412,6 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
'profile_code': 'PREVIEW_V2', 'display_name': 'Preview', 'schema_version_id': schema.id,
|
||||
'document_id': document.id, 'definition': _coordinate_definition(),
|
||||
}, actor_id=user.id)
|
||||
db.session.commit()
|
||||
document_id = document.id
|
||||
profile_id = draft['id']
|
||||
|
||||
@@ -1460,6 +1461,63 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
assert candidates.status_code == 200
|
||||
assert 'html' not in str(parse_api_data(candidates.get_json()))
|
||||
|
||||
# 坐标模板与 XFA 必须共用原 PDF + PDF.js 的受控画布入口;模板类型不得扩大样本读取范围。
|
||||
raw_coordinate_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
assert raw_coordinate_authorized.status_code == 200
|
||||
raw_coordinate_grant = parse_api_data(raw_coordinate_authorized.get_json())
|
||||
assert 'storage_bucket' not in str(raw_coordinate_grant) and 'storage_key' not in str(raw_coordinate_grant)
|
||||
raw_coordinate_pdf = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_coordinate_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_coordinate_pdf.status_code == 200
|
||||
assert raw_coordinate_pdf.mimetype == 'application/pdf'
|
||||
assert raw_coordinate_pdf.data == b'%PDF-preview'
|
||||
assert raw_coordinate_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
profile.template_mode = 'xfa_dataset'
|
||||
db.session.commit()
|
||||
|
||||
# XFA 编辑画布可短时读取绑定原件,但绝不获得对象存储地址或可重放下载链接。
|
||||
raw_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
assert raw_authorized.status_code == 200
|
||||
assert raw_authorized.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
raw_grant = parse_api_data(raw_authorized.get_json())
|
||||
assert 'storage_bucket' not in str(raw_grant) and 'storage_key' not in str(raw_grant)
|
||||
foreign = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']},
|
||||
headers={'X-Username': 'other-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert foreign.status_code == 404
|
||||
raw_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
raw_grant = parse_api_data(raw_authorized.get_json())
|
||||
raw_pdf = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_pdf.status_code == 200
|
||||
assert raw_pdf.mimetype == 'application/pdf'
|
||||
assert raw_pdf.data == b'%PDF-preview'
|
||||
assert raw_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
assert b'private-bucket' not in raw_pdf.data and b'internal/preview.pdf' not in raw_pdf.data
|
||||
raw_replay = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_replay.status_code == 404
|
||||
|
||||
|
||||
def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, monkeypatch):
|
||||
"""预览授权依赖 Redis 且只能读取 Profile 已绑定样本,不能降级为进程内或任意文档读取。"""
|
||||
|
||||
@@ -37,7 +37,10 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
cancellation_actor_id=None,
|
||||
cancellation_reason=None,
|
||||
cancellation_reason_code=None,
|
||||
id=None,
|
||||
run_no='OER-TEST',
|
||||
reparse_source=None,
|
||||
superseding_run=None,
|
||||
auto_freeze_policy_json=None,
|
||||
review_cases=[],
|
||||
)
|
||||
@@ -151,7 +154,9 @@ def test_build_handling_items_splits_pending_freeze_review_and_failure():
|
||||
assert 'candidate_missing_info' in categories
|
||||
assert 'candidate_conflict' in categories
|
||||
assert 'auto_freeze_blocked' in categories
|
||||
assert 'budget_stopped' in categories
|
||||
# 未提供受限文件引用时,预算停扩只能作为 Run 历史上下文,不能伪造一个
|
||||
# 文件级处理事项参与统计;否则同一 PDF 会被多类事项重复相加。
|
||||
assert 'budget_stopped' not in categories
|
||||
assert items[0]['primary_action'] == 'retry_failed_attachments'
|
||||
missing = next(item for item in items if item['category'] == 'candidate_missing_info')
|
||||
assert missing['primary_action'] == 'review_candidate'
|
||||
@@ -191,6 +196,233 @@ def test_build_handling_items_budget_stopped_includes_attachment_refs():
|
||||
assert budget['affected_refs'][0]['document_id'] == 42
|
||||
|
||||
|
||||
def test_build_handling_items_counts_one_document_in_only_one_primary_category():
|
||||
"""同一 PDF 同时存在解析复核、候选待补和预算原因时,只能计入最高优先级事项。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={
|
||||
'pending_count': 1,
|
||||
'pending_orders': [{
|
||||
'candidate_no': 'C-9',
|
||||
'po_number': 'PO-9',
|
||||
'document_id': 99,
|
||||
'reasons': ['required_field_missing'],
|
||||
'missing_fields': ['qty'],
|
||||
}],
|
||||
'budget_stopped': True,
|
||||
},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [{
|
||||
'selected': False,
|
||||
'filename': 'same.pdf',
|
||||
'document_id': 99,
|
||||
'skip_reason_codes': ['budget_initial_limit'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [SimpleNamespace(
|
||||
id=9,
|
||||
document_id=99,
|
||||
status='review_required',
|
||||
reason_code='row_needs_review',
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['document_review']
|
||||
assert items[0]['count'] == 1
|
||||
|
||||
|
||||
def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id():
|
||||
"""预算快照仅保留哈希时,仍不得把同一 PDF 与复核事项重复统计。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={'budget_stopped': True, 'pending_count': 0},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [{
|
||||
'selected': False,
|
||||
'filename': 'same.pdf',
|
||||
# 历史预算计划可能没有 document_id,但保留了冻结时的内容哈希。
|
||||
'content_hash': 'same-content-hash',
|
||||
'skip_reason_codes': ['budget_initial_limit'],
|
||||
}],
|
||||
},
|
||||
},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [SimpleNamespace(
|
||||
id=10,
|
||||
document_id=100,
|
||||
content_hash='same-content-hash',
|
||||
status='review_required',
|
||||
reason_code='row_needs_review',
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
# 文档复核优先级更高;预算原因可作为解释存在,但不能再增加第二个文件计数。
|
||||
assert [item['category'] for item in items] == ['document_review']
|
||||
assert items[0]['count'] == 1
|
||||
|
||||
|
||||
def test_build_handling_items_keeps_unclaimed_candidate_ready_unit_as_confirmation():
|
||||
"""没有 pending_orders 时,候选就绪文件仍应稳定生成唯一待确认事项。"""
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={'pending_count': 1},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [SimpleNamespace(
|
||||
id=12,
|
||||
document_id=120,
|
||||
content_hash='candidate-ready-hash',
|
||||
status='candidate_ready',
|
||||
reason_code=None,
|
||||
technical_failure_reason_code=None,
|
||||
)]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['candidate_confirmation']
|
||||
assert items[0]['count'] == 1
|
||||
assert items[0]['affected_refs'][0]['document_id'] == 120
|
||||
|
||||
|
||||
def test_build_handling_items_deduplicates_confirmation_candidates_by_document():
|
||||
"""同一 PDF 的多个仅待确认 Candidate 只能统计为一个文件待办。"""
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={
|
||||
'pending_count': 2,
|
||||
'pending_orders': [
|
||||
{
|
||||
'candidate_no': 'C-SAME-1',
|
||||
'po_number': 'PO-SAME-1',
|
||||
'document_id': 101,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
},
|
||||
{
|
||||
'candidate_no': 'C-SAME-2',
|
||||
'po_number': 'PO-SAME-2',
|
||||
'document_id': 101,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
},
|
||||
],
|
||||
},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['candidate_confirmation']
|
||||
assert items[0]['count'] == 1
|
||||
assert items[0]['affected_refs'] == [{
|
||||
'type': 'candidate',
|
||||
'candidate_no': 'C-SAME-1',
|
||||
'po_number': 'PO-SAME-1',
|
||||
'document_id': 101,
|
||||
}]
|
||||
|
||||
|
||||
def test_build_handling_items_keeps_confirmation_for_other_document_after_conflict():
|
||||
"""某 PDF 冲突时,其他 PDF 的待确认事项仍须保留且互不重复计数。"""
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={
|
||||
'pending_count': 2,
|
||||
'pending_orders': [
|
||||
{
|
||||
'candidate_no': 'C-CONFLICT',
|
||||
'po_number': 'PO-CONFLICT',
|
||||
'document_id': 201,
|
||||
'reasons': ['email_supplement_conflict'],
|
||||
'missing_fields': [],
|
||||
},
|
||||
{
|
||||
'candidate_no': 'C-CONFIRM',
|
||||
'po_number': 'PO-CONFIRM',
|
||||
'document_id': 202,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
},
|
||||
],
|
||||
},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == [
|
||||
'candidate_conflict', 'candidate_confirmation',
|
||||
]
|
||||
assert [item['count'] for item in items] == [1, 1]
|
||||
assert items[1]['affected_refs'][0]['document_id'] == 202
|
||||
|
||||
|
||||
def test_build_handling_items_claims_all_documents_before_limiting_refs():
|
||||
"""超过展示上限时,同一 PDF 仍只能归入一个最高优先级处理事项。"""
|
||||
pending_orders = [
|
||||
{
|
||||
'candidate_no': f'C-CONFLICT-{document_id}',
|
||||
'po_number': f'PO-{document_id}',
|
||||
'document_id': document_id,
|
||||
'reasons': ['email_supplement_conflict'],
|
||||
'missing_fields': [],
|
||||
}
|
||||
for document_id in range(1, 12)
|
||||
]
|
||||
# 第 11 份 PDF 同时带有低优先级的待确认记录;截断前认领才能防止重复。
|
||||
pending_orders.append({
|
||||
'candidate_no': 'C-DUPLICATE-11',
|
||||
'po_number': 'PO-11',
|
||||
'document_id': 11,
|
||||
'reasons': [],
|
||||
'missing_fields': [],
|
||||
})
|
||||
run = SimpleNamespace(
|
||||
status='review_required',
|
||||
result_json={'pending_count': len(pending_orders), 'pending_orders': pending_orders},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
|
||||
assert [item['category'] for item in items] == ['candidate_conflict']
|
||||
# 统计使用全量互斥文件集合,affected_refs 仅为最多 20 条的展示样本。
|
||||
assert items[0]['count'] == 11
|
||||
assert len(items[0]['affected_refs']) == 11
|
||||
|
||||
|
||||
def test_planned_documents_inherit_failed_run_status_before_units_exist():
|
||||
"""Job 在 Unit 物化前失败时,右侧每份 PDF 必须显示失败而非处理中。"""
|
||||
run = SimpleNamespace(
|
||||
|
||||
@@ -9,10 +9,13 @@ tests/test_shipping_order_review_field_conflict.py
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_field_conflict_service import (
|
||||
project_review_case_field_conflicts,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import _sync_review_gates_safe
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
|
||||
def test_project_review_case_field_conflicts_builds_stable_keys():
|
||||
@@ -88,3 +91,94 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
|
||||
"""无 Candidate 时投影为空列表。"""
|
||||
case = SimpleNamespace(candidate_id=None, current_draft=None)
|
||||
assert project_review_case_field_conflicts(case) == []
|
||||
|
||||
|
||||
def test_project_review_case_field_conflicts_keeps_single_value_evidence_gap_actionable():
|
||||
"""证据缺失不是双值冲突,也必须投影字段和行号,供用户手工补证据/裁决。"""
|
||||
candidate = SimpleNamespace(
|
||||
conflicts_json=[{
|
||||
'field': 'part_number',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
}],
|
||||
structured_result_json={},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
candidate_id=1,
|
||||
current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]),
|
||||
)
|
||||
|
||||
from app.services.shipping_notice import order_review_field_conflict_service as svc
|
||||
|
||||
original = svc._candidate_for_case
|
||||
svc._candidate_for_case = lambda _case: candidate
|
||||
try:
|
||||
items = project_review_case_field_conflicts(case)
|
||||
finally:
|
||||
svc._candidate_for_case = original
|
||||
|
||||
# 关键断言:不可自动建单的证据缺失不能在字段冲突投影层静默丢失。
|
||||
assert items == [{
|
||||
'conflict_key': '0:part_number',
|
||||
'field_code': 'part_number',
|
||||
'line_index': 0,
|
||||
'line_key': 'line-1',
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
'options': [],
|
||||
'observation_ids': [],
|
||||
}]
|
||||
|
||||
|
||||
def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict():
|
||||
"""草稿字段已齐全时,Gate 必须通过完整性并把最新证据冲突归属到字段冲突门禁。"""
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-TEST',
|
||||
current_draft=SimpleNamespace(draft_version=9),
|
||||
)
|
||||
validation = {
|
||||
'assessment': {'missing_required_fields': [], 'invalid_lines': []},
|
||||
'failed_gates': ['field_conflicts_resolved'],
|
||||
'issues': [{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'reason_code': 'field_conflict',
|
||||
'owning_gate_code': 'field_conflict_resolution',
|
||||
'severity': 'auto_create_blocking',
|
||||
'field_code': None,
|
||||
'line_index': None,
|
||||
}],
|
||||
'line_projections': [],
|
||||
}
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_review_gate_for_case',
|
||||
) as sync_gate, patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_inventory_routing_gate_for_case',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._candidate_conflict_locator',
|
||||
return_value={'field_code': 'part_number', 'line_index': 0},
|
||||
):
|
||||
_sync_review_gates_safe(case=case, user_id=7, validation=validation)
|
||||
|
||||
calls = {call.kwargs['gate_code']: call.kwargs for call in sync_gate.call_args_list}
|
||||
# 关键断言:旧 required_field_missing 不得滞留为当前阻断。
|
||||
assert calls['field_completeness']['passed'] is True
|
||||
# 关键断言:自动建单证据冲突必须带字段/行号成为用户可见的正式 Gate。
|
||||
assert calls['field_conflict_resolution']['passed'] is False
|
||||
assert calls['field_conflict_resolution']['blocking_reason_code'] == 'field_conflict'
|
||||
assert calls['field_conflict_resolution']['details']['field_code'] == 'part_number'
|
||||
assert calls['field_conflict_resolution']['details']['line_index'] == 0
|
||||
|
||||
|
||||
def test_not_found_error_preserves_stale_conflict_key_details():
|
||||
"""过期冲突操作必须返回可处理的 404 业务错误,不能因错误构造器再次抛出 TypeError。"""
|
||||
error = NotFoundError(
|
||||
'Field conflict not found',
|
||||
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
|
||||
details={'conflict_key': '-1:part_number'},
|
||||
)
|
||||
|
||||
# 关键断言:前端可据此识别“页面数据过期”并刷新,而非收到 500。
|
||||
assert error.http_status == 404
|
||||
assert error.details == {'conflict_key': '-1:part_number'}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
@@ -16,6 +17,9 @@ from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
FileAsset,
|
||||
ShippingAuditEvent,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingOrderCandidate,
|
||||
@@ -26,7 +30,14 @@ from app.models import (
|
||||
ShippingNotice,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case, serialize_review_run
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
serialize_review_case,
|
||||
serialize_review_run,
|
||||
serialize_review_queue,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_reservation_service import (
|
||||
project_review_case_reservation,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
ensure_review_case_for_unit,
|
||||
@@ -34,7 +45,203 @@ from app.services.shipping_notice.order_review_service import (
|
||||
get_review_case_visible_to_user,
|
||||
get_review_run_visible_to_user,
|
||||
get_user_review_case,
|
||||
get_review_queue_visible_to_user,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import find_execution_for_case
|
||||
|
||||
|
||||
def test_review_queue_aggregates_active_runs_in_same_conversation(app):
|
||||
"""会话队列汇总同一对话的多个有效 Run,并排除已被替代的版本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE')
|
||||
first = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
ensure_run_review_cases(run=first)
|
||||
|
||||
second_asset = FileAsset(
|
||||
asset_no='FA-RUN-REVIEW-QUEUE-SECOND',
|
||||
owner_user_id=user.id,
|
||||
original_filename='orders-review-queue-second.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/orders-review-queue-second.pdf',
|
||||
content_hash='c' * 64,
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(second_asset)
|
||||
db.session.flush()
|
||||
second_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-RUN-REVIEW-QUEUE-SECOND',
|
||||
asset_id=second_asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='second order input',
|
||||
structured_result_json={},
|
||||
)
|
||||
db.session.add(second_intake)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=second_intake.id,
|
||||
asset_id=second_asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-review-queue-second.pdf',
|
||||
filename='orders-review-queue-second.pdf',
|
||||
content_hash='b' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO REVIEW QUEUE SECOND',
|
||||
))
|
||||
db.session.commit()
|
||||
second = _materialized_run(user=user, agent=agent, session=session, intake=second_intake)
|
||||
ensure_run_review_cases(run=second)
|
||||
|
||||
replacement_asset = FileAsset(
|
||||
asset_no='FA-RUN-REVIEW-QUEUE-REPLACEMENT',
|
||||
owner_user_id=user.id,
|
||||
original_filename='orders-review-queue-replacement.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/orders-review-queue-replacement.pdf',
|
||||
content_hash='d' * 64,
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(replacement_asset)
|
||||
db.session.flush()
|
||||
replacement_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-RUN-REVIEW-QUEUE-REPLACEMENT',
|
||||
asset_id=replacement_asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='replacement order input',
|
||||
structured_result_json={},
|
||||
)
|
||||
db.session.add(replacement_intake)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=replacement_intake.id,
|
||||
asset_id=replacement_asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-review-queue-replacement.pdf',
|
||||
filename='orders-review-queue-replacement.pdf',
|
||||
content_hash='e' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO REVIEW QUEUE REPLACEMENT',
|
||||
))
|
||||
db.session.commit()
|
||||
replacement = _materialized_run(user=user, agent=agent, session=session, intake=replacement_intake)
|
||||
ensure_run_review_cases(run=replacement)
|
||||
second.superseded_by_run_id = replacement.id
|
||||
db.session.commit()
|
||||
|
||||
queue = serialize_review_queue(get_review_queue_visible_to_user(
|
||||
first.run_no, user.id, is_admin=False,
|
||||
))
|
||||
|
||||
assert [item['source_run_no'] for item in queue['items']] == [first.run_no, replacement.run_no]
|
||||
assert queue['items'][0]['case_no'] == first.review_cases[0].case_no
|
||||
assert queue['summary']['total'] == 2
|
||||
|
||||
|
||||
def test_review_queue_projects_each_case_po_and_lifecycle_stage(app):
|
||||
"""工作台左侧队列须为每个文件下发后端裁决的 PO 与生命周期,不由前端跨 Case 拼接。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-LIFECYCLE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-LIFECYCLE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-lifecycle',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-001',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
assert item['case_no'] == case.case_no
|
||||
assert item['po_number'] == 'PO-QUEUE-001'
|
||||
assert item['lifecycle_stage'] == 'order_review'
|
||||
assert [entry['state'] for entry in item['lifecycle_entries']] == [
|
||||
'available', 'current', 'unavailable', 'unavailable',
|
||||
]
|
||||
|
||||
|
||||
def test_review_queue_uses_formal_task_lifecycle_stage(app):
|
||||
"""Case 已绑定正式任务后,队列阶段必须随正式 Gate/领域事实推进。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-FORMAL-STAGE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-QUEUE-FORMAL-STAGE',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='review-queue-formal-stage',
|
||||
order_extraction_run_id=run.id,
|
||||
po_number='PO-QUEUE-002',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-REVIEW-QUEUE-FORMAL-STAGE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
source_candidate_id=candidate.id,
|
||||
match_status='partial',
|
||||
inventory_lines_json=[{'part_number': 'PN-QUEUE-002'}],
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = notice.id
|
||||
db.session.commit()
|
||||
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
|
||||
assert item['po_number'] == 'PO-QUEUE-002'
|
||||
assert item['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert [entry['state'] for entry in item['lifecycle_entries']] == [
|
||||
'available', 'available', 'current', 'unavailable',
|
||||
]
|
||||
|
||||
|
||||
def test_review_case_projects_replacement_upload_as_its_own_permission(app):
|
||||
"""替代件上传必须独立于质量异常标记权限,前端不得以别的动作码推断。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REPLACEMENT-ACTION')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
draft_actions = serialize_review_case(case)['available_actions']
|
||||
assert 'upload_replacement' in draft_actions
|
||||
assert 'mark_quality_issue' in draft_actions
|
||||
|
||||
case.status = 'quality_issue'
|
||||
db.session.commit()
|
||||
quality_actions = serialize_review_case(case)['available_actions']
|
||||
assert 'upload_replacement' in quality_actions
|
||||
assert 'mark_quality_issue' in quality_actions
|
||||
|
||||
case.status = 'confirmed'
|
||||
db.session.commit()
|
||||
assert 'upload_replacement' not in serialize_review_case(case)['available_actions']
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
add_line,
|
||||
adopt_inventory_routing_suggestion,
|
||||
@@ -48,6 +255,7 @@ from app.services.shipping_notice.order_review_draft_service import (
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_evidence_service import (
|
||||
get_case_intake_parse_context,
|
||||
get_case_email_evidence_text,
|
||||
get_case_evidence,
|
||||
list_case_evidence,
|
||||
@@ -96,6 +304,103 @@ def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'res
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_reservation_summary_reads_current_draft_value_before_async_validation():
|
||||
"""合法预约号已保存但校验 Job 未落投影时,右栏不得误报缺失。"""
|
||||
case = SimpleNamespace(
|
||||
run=SimpleNamespace(input_snapshot_json={
|
||||
'schema': {'definition': {'fields': [{
|
||||
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
}]}},
|
||||
}),
|
||||
current_draft=SimpleNamespace(
|
||||
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
|
||||
lines_json=[{
|
||||
'line_key': 'line-1',
|
||||
'values': {'reservation-id': {'value': '33874', 'source': 'manual'}},
|
||||
}],
|
||||
),
|
||||
)
|
||||
|
||||
result = project_review_case_reservation(case)
|
||||
|
||||
# 关键断言:33874 符合 5 位预约号契约;未完成异步校验不等于缺少预约号。
|
||||
assert result['status'] == 'ok'
|
||||
assert result['needs_attention'] is False
|
||||
assert result['lines'][0]['effective_reservation_id'] == '33874'
|
||||
|
||||
|
||||
def test_reservation_summary_uses_line_field_when_header_and_line_share_code():
|
||||
"""同名表头字段不得遮蔽明细 Reservation,避免有效预约号被投影为缺失。"""
|
||||
case = SimpleNamespace(
|
||||
run=SimpleNamespace(input_snapshot_json={
|
||||
'schema': {'definition': {'fields': [
|
||||
{'field_id': 'header-reservation-id', 'field_code': 'reservation_id', 'scope': 'header'},
|
||||
{'field_id': 'line-reservation-id', 'field_code': 'reservation_id', 'scope': 'line'},
|
||||
]}},
|
||||
}),
|
||||
current_draft=SimpleNamespace(
|
||||
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
|
||||
lines_json=[{
|
||||
'line_key': 'line-1',
|
||||
'values': {'line-reservation-id': {'value': '33894', 'source': 'manual'}},
|
||||
}],
|
||||
),
|
||||
)
|
||||
|
||||
result = project_review_case_reservation(case)
|
||||
|
||||
# 关键断言:字段身份是 (field_code, scope),必须读取 line.reservation_id。
|
||||
assert result['reservation_field_id'] == 'line-reservation-id'
|
||||
assert result['status'] == 'ok'
|
||||
assert result['lines'][0]['effective_reservation_id'] == '33894'
|
||||
|
||||
|
||||
def test_reservation_summary_keeps_missing_value_blocked_before_async_validation():
|
||||
"""校验 Job 尚未落投影时,空预约号仍必须显示为真正的待处理问题。"""
|
||||
case = SimpleNamespace(
|
||||
run=SimpleNamespace(input_snapshot_json={
|
||||
'schema': {'definition': {'fields': [{
|
||||
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
}]}},
|
||||
}),
|
||||
current_draft=SimpleNamespace(
|
||||
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
|
||||
lines_json=[{'line_key': 'line-1', 'values': {}}],
|
||||
),
|
||||
)
|
||||
|
||||
result = project_review_case_reservation(case)
|
||||
|
||||
# 关键断言:仅修复合法 Draft 值的漏读,不能放宽缺失 Reservation 的门禁。
|
||||
assert result['status'] == 'needs_attention'
|
||||
assert result['needs_attention'] is True
|
||||
assert result['lines'][0]['effective_reservation_id'] is None
|
||||
|
||||
|
||||
def test_reservation_summary_reads_machine_value_before_async_validation():
|
||||
"""未被人工修改的机器预约号也须与 Draft 编辑工作面一致。"""
|
||||
case = SimpleNamespace(
|
||||
run=SimpleNamespace(input_snapshot_json={
|
||||
'schema': {'definition': {'fields': [{
|
||||
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
}]}},
|
||||
}),
|
||||
current_draft=SimpleNamespace(
|
||||
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
|
||||
lines_json=[{
|
||||
'line_key': 'line-1',
|
||||
'machine_fields': [{'field_id': 'reservation-id', 'observations': [{'value': '33874'}]}],
|
||||
}],
|
||||
),
|
||||
)
|
||||
|
||||
result = project_review_case_reservation(case)
|
||||
|
||||
# 关键断言:values 缺失时,必须回退同一 Draft 的冻结机器值,而不是显示为空。
|
||||
assert result['status'] == 'ok'
|
||||
assert result['lines'][0]['effective_reservation_id'] == '33874'
|
||||
|
||||
|
||||
def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app):
|
||||
"""同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。"""
|
||||
with app.app_context():
|
||||
@@ -130,6 +435,197 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
|
||||
assert db.session.get(ShippingOrderCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
|
||||
|
||||
|
||||
def test_review_case_initialization_closes_legacy_extraction_gates(app):
|
||||
"""候选已落为 Review Case 时,正式流程不得仍把当前阶段裁决为接收解析。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-GATE-RECONCILE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-GATE', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='review-gate',
|
||||
order_extraction_run_id=run.id, missing_fields_json=['qty'],
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
execution = find_execution_for_case(case)
|
||||
db.session.flush()
|
||||
|
||||
gates = {row.gate_code: row for row in execution.gates}
|
||||
# Candidate 已形成是更高层业务事实;旧解析 Gate 必须以 skipped 收口,
|
||||
# 不能伪造为各技术步骤都曾成功执行。
|
||||
assert gates['document_materialization'].status == 'skipped'
|
||||
assert gates['document_materialization'].effective_result_json['disposition'] == 'superseded_by_candidate'
|
||||
assert gates['document_materialization'].effective_result_json['candidate_id'] == candidate.id
|
||||
# 缺字段为空时 field_completeness 可继续自动通过;关键不变量是当前 Gate
|
||||
# 不得再回退到任何旧解析节点。
|
||||
assert execution.current_gate_code not in {
|
||||
'document_materialization', 'layout_parsing',
|
||||
'document_profile_routing', 'order_field_extraction',
|
||||
}
|
||||
assert gates['field_completeness'].status == 'blocked_manual'
|
||||
|
||||
# 批次中心与 Case 详情均经共享 bundle;正式 Gate 的缺字段阻断不能在
|
||||
# Case 草稿投影时回退为 order_review_build / idle。
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=None,
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
assert bundle['current_gate']['gate_code'] == 'field_completeness'
|
||||
assert bundle['blocking_reason']['code'] == 'required_field_missing'
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app):
|
||||
"""Candidate 形成时必须终止旧解析 Attempt,迟到结果不能夺回当前阶段。"""
|
||||
with app.app_context():
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
complete_gate_attempt,
|
||||
mark_attempt_running,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-GATE-ACTIVE-ATTEMPT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-GATE-ACTIVE', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='review-gate-active',
|
||||
order_extraction_run_id=run.id, candidate_status='provisional',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
# 先构造已经关联 Candidate 的 Case 与正在执行的旧解析 Attempt,再触发收口。
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SNRC-REVIEW-GATE-ACTIVE', run_id=run.id, unit_id=unit.id,
|
||||
document_id=document.id, candidate_id=candidate.id, owner_user_id=user.id,
|
||||
status='unreviewed',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=case.id, actor_type='system')
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='document_materialization',
|
||||
trigger_type='system_requeue', actor_type='system', actor_id='test',
|
||||
idempotency_key='candidate-supersedes-active-attempt',
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
)
|
||||
mark_attempt_running(attempt_id=attempt.id, worker_id='test')
|
||||
from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case
|
||||
reconcile_extraction_gates_for_review_case(case=case)
|
||||
db.session.refresh(attempt)
|
||||
gate = next(row for row in execution.gates if row.gate_code == 'document_materialization')
|
||||
|
||||
assert attempt.status == 'superseded'
|
||||
assert gate.status == 'skipped'
|
||||
assert execution.current_gate_code not in {
|
||||
'document_materialization', 'layout_parsing',
|
||||
'document_profile_routing', 'order_field_extraction',
|
||||
}
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
complete_gate_attempt(attempt_id=attempt.id, outcome='passed')
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_GATE_ATTEMPT_IMMUTABLE'
|
||||
|
||||
|
||||
def test_candidate_gate_reconciliation_is_idempotent_and_corrects_legacy_compatibility_pass(app):
|
||||
"""Candidate 收口重试不制造重复审计,旧 candidate_ready 伪 passed 会被纠正。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-GATE-IDEMPOTENT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-GATE-IDEMPOTENT', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='review-gate-idempotent',
|
||||
order_extraction_run_id=run.id, candidate_status='provisional',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
execution = find_execution_for_case(case)
|
||||
gate = next(row for row in execution.gates if row.gate_code == 'layout_parsing')
|
||||
first_version = gate.evaluation_version
|
||||
|
||||
from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case
|
||||
reconcile_extraction_gates_for_review_case(case=case)
|
||||
db.session.refresh(gate)
|
||||
assert gate.evaluation_version == first_version
|
||||
|
||||
# 模拟历史代码遗留的 candidate_ready/passed,下一次收口应只修正该兼容错误。
|
||||
gate.status = 'passed'
|
||||
gate.effective_result_json = {'source': 'candidate_ready'}
|
||||
db.session.flush()
|
||||
reconcile_extraction_gates_for_review_case(case=case)
|
||||
db.session.refresh(gate)
|
||||
assert gate.status == 'skipped'
|
||||
assert gate.effective_result_json['disposition'] == 'superseded_by_candidate'
|
||||
|
||||
|
||||
def test_review_case_without_candidate_does_not_close_legacy_extraction_gates(app):
|
||||
"""空 Review Case 只是人工容器,不能被误判为候选已生成并跳过接收解析。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-GATE-NO-CANDIDATE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
|
||||
# 核心断言:没有 Candidate 时不创建正式 Execution,更不能将解析 Gate 标为 passed。
|
||||
assert case is not None
|
||||
assert case.candidate_id is None
|
||||
assert find_execution_for_case(case) is None
|
||||
item = serialize_review_queue([run])['items'][0]
|
||||
# 空 Case 是解析处置对象:不得标为订单复核,更不能下发生命周期入口。
|
||||
assert item['lifecycle_stage'] == 'intake_parse'
|
||||
assert item['lifecycle_entries'] == []
|
||||
# 解析上下文读取是独立 capability,不能通过伪造生命周期入口授权。
|
||||
assert item['intake_parse_authorized'] is True
|
||||
|
||||
|
||||
def test_find_execution_for_case_ignores_superseded_execution(app):
|
||||
"""已替代 Execution 只能审计,Case 实时读取不得重新使用其旧 Gate。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
)
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SUPERSEDED-EXECUTION')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUPERSEDED-EXECUTION', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='superseded-execution',
|
||||
order_extraction_run_id=run.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
old = find_execution_for_case(case)
|
||||
assert old is not None
|
||||
old.status = 'superseded'
|
||||
db.session.flush()
|
||||
|
||||
current = ensure_execution_for_workflow_version(
|
||||
review_case_id=case.id, actor_type='system', actor_id='test',
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
assert current.id != old.id
|
||||
assert ShippingProcessExecution.query.filter_by(review_case_id=case.id).count() == 2
|
||||
assert find_execution_for_case(case).id == current.id
|
||||
|
||||
|
||||
def test_review_cases_follow_each_ready_unit_for_any_pdf_count_and_completion_order(app):
|
||||
"""任意数量 PDF 乱序完成时,只能为当前已就绪 Unit 建 Case,兄弟 PDF 不得被提前初始化。"""
|
||||
with app.app_context():
|
||||
@@ -594,6 +1090,185 @@ def test_review_email_evidence_preview_reads_only_the_sibling_email_body(app):
|
||||
}
|
||||
|
||||
|
||||
def test_case_intake_parse_context_returns_own_attachment_and_sibling_email(app):
|
||||
"""上下文只能投影当前 Case 附件及同一 Intake 的已解析邮件正文。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT')
|
||||
body = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='body',
|
||||
filename='source.eml',
|
||||
content_hash='a' * 64,
|
||||
classification='email_body',
|
||||
parse_status='parsed',
|
||||
extracted_text='approved body text',
|
||||
)
|
||||
db.session.add(body)
|
||||
db.session.commit()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
context = get_case_intake_parse_context(user_id=user.id, case_no=case.case_no)
|
||||
|
||||
assert context == {
|
||||
'case_no': case.case_no,
|
||||
'attachment': {
|
||||
'document_id': attachment.id,
|
||||
'filename': attachment.filename,
|
||||
'mime_type': 'application/pdf',
|
||||
'preview_kind': 'pdf',
|
||||
},
|
||||
'email': {
|
||||
'document_id': body.id,
|
||||
'filename': 'source.eml',
|
||||
'text': 'approved body text',
|
||||
},
|
||||
}
|
||||
assert 'storage_key' not in str(context)
|
||||
|
||||
|
||||
def test_case_intake_parse_context_never_reads_email_from_another_intake(app):
|
||||
"""跨 Intake 邮件正文不能混入新上下文 DTO,当前 Case 只读自身正文。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT-OWN')
|
||||
own_body = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='body',
|
||||
filename='own.eml',
|
||||
content_hash='a' * 64,
|
||||
classification='email_body',
|
||||
parse_status='parsed',
|
||||
extracted_text='only own body',
|
||||
)
|
||||
db.session.add(own_body)
|
||||
db.session.flush()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
other_asset = FileAsset(
|
||||
asset_no='FA-REVIEW-INTAKE-CONTEXT-OTHER',
|
||||
owner_user_id=user.id,
|
||||
original_filename='other.eml',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/other.eml',
|
||||
content_hash='b' * 64,
|
||||
file_size=100,
|
||||
mime_type='message/rfc822',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(other_asset)
|
||||
db.session.flush()
|
||||
other_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-REVIEW-INTAKE-CONTEXT-OTHER',
|
||||
asset_id=other_asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(other_intake)
|
||||
db.session.flush()
|
||||
other_body = ShippingOrderDocument(
|
||||
intake_id=other_intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='body',
|
||||
filename='other.eml',
|
||||
content_hash='b' * 64,
|
||||
classification='email_body',
|
||||
parse_status='parsed',
|
||||
extracted_text='must not leak',
|
||||
)
|
||||
db.session.add(other_body)
|
||||
db.session.commit()
|
||||
|
||||
context = get_case_intake_parse_context(user_id=user.id, case_no=case.case_no)
|
||||
|
||||
assert context['email'] == {
|
||||
'document_id': own_body.id,
|
||||
'filename': 'own.eml',
|
||||
'text': 'only own body',
|
||||
}
|
||||
assert other_body.id != context['email']['document_id']
|
||||
assert 'must not leak' not in str(context)
|
||||
|
||||
|
||||
def test_case_intake_parse_context_rejects_another_owner_and_missing_attachment(app):
|
||||
"""Case owner 与主附件均是上下文边界;任一边界失效都不得回退到其他记录。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT-NOT-FOUND')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
other = User(
|
||||
username='review-intake-context-other',
|
||||
email='review-intake-context-other@example.com',
|
||||
password_hash='x',
|
||||
)
|
||||
db.session.add(other)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(NotFoundError):
|
||||
get_case_intake_parse_context(user_id=other.id, case_no=case.case_no)
|
||||
|
||||
case.document_id = 999_999
|
||||
db.session.commit()
|
||||
with pytest.raises(NotFoundError) as exc:
|
||||
get_case_intake_parse_context(user_id=user.id, case_no=case.case_no)
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_INTAKE_CONTEXT_NOT_FOUND'
|
||||
|
||||
|
||||
def test_case_intake_parse_context_returns_no_email_for_direct_pdf_and_api_audits(app):
|
||||
"""直接 PDF 即使遗留正文也不得投影;读取 API 必须记脱敏访问审计。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT-PDF')
|
||||
intake.source_type = 'direct_pdf'
|
||||
# 模拟历史异常数据:direct_pdf Intake 仍残留同 Intake email_body。
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='legacy-body',
|
||||
filename='legacy.eml',
|
||||
content_hash='c' * 64,
|
||||
classification='email_body',
|
||||
parse_status='parsed',
|
||||
extracted_text='must not appear for direct PDF',
|
||||
))
|
||||
db.session.commit()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
|
||||
client = app.test_client()
|
||||
response = client.get(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/intake-parse-context',
|
||||
headers={'Authorization': f'Bearer {issue_local_access_token(user)}'},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.get_json()['data']
|
||||
assert payload['attachment']['document_id'] == attachment.id
|
||||
assert payload['attachment']['preview_kind'] == 'pdf'
|
||||
assert payload['email'] is None
|
||||
assert 'storage_key' not in str(payload)
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_resource_accessed',
|
||||
action='view_order_review_intake_parse_context',
|
||||
review_case_no=case.case_no,
|
||||
).one()
|
||||
assert audit.aggregate_type == 'order_review_case'
|
||||
assert audit.document_id == str(attachment.id)
|
||||
assert audit.metadata_json == {
|
||||
'access_action': 'view_order_review_intake_parse_context',
|
||||
'workbench_event': 'intake_parse_context_viewed',
|
||||
'attachment_preview_kind': 'pdf',
|
||||
'has_email_context': False,
|
||||
}
|
||||
|
||||
|
||||
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
|
||||
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -15,6 +15,7 @@ from unittest.mock import patch
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
resolve_pre_confirm_stage,
|
||||
resolve_processing_stage_for_progress_event,
|
||||
sync_order_task_stage_for_notice,
|
||||
write_run_unified_processing_stage,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
@@ -183,3 +184,38 @@ def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage():
|
||||
assert result is order_task
|
||||
assert order_task.stage == 'inventory_matching'
|
||||
sync_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task_stage():
|
||||
"""正式 Execution 已进入库存准备时,同步不得把 OT 保留在 waiting_review。"""
|
||||
notice = SimpleNamespace(
|
||||
id=14,
|
||||
order_task_id=81,
|
||||
active_process_execution_id=92,
|
||||
current_step=None,
|
||||
upload_status=None,
|
||||
export_file_path=None,
|
||||
pending_human_reason=None,
|
||||
review_status=None,
|
||||
match_status=None,
|
||||
lifecycle_status='active',
|
||||
inventory_lines_json=None,
|
||||
)
|
||||
order_task = SimpleNamespace(stage='waiting_review', status='waiting_review')
|
||||
execution = SimpleNamespace(
|
||||
current_gate_code='inventory_preparation',
|
||||
status='waiting_external',
|
||||
)
|
||||
with patch('app.services.shipping_notice.order_task_stage_machine.db') as mock_db, patch(
|
||||
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
|
||||
) as sync_mock:
|
||||
mock_db.session.get.side_effect = [order_task, execution]
|
||||
sync_order_task_stage_for_notice(notice)
|
||||
|
||||
sync_mock.assert_called_once_with(
|
||||
order_task,
|
||||
stage='inventory_fetching',
|
||||
status='automating',
|
||||
reason_code='notice_fulfillment_sync',
|
||||
source='order_task_stage_machine',
|
||||
)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
tests/test_shipping_pdf_automark.py
|
||||
|
||||
用途:验证统一 PDF 自动标记 Job 对不同 PDF 能力输出同一候选契约。
|
||||
依赖:order_document_profile_pdf_automark_service、pytest mock。
|
||||
逻辑:普通 PDF 复用坐标重建与 OCR 回退;XFA 复用多源融合执行器,但调用方不传类型。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_document_profile_pdf_automark_service import (
|
||||
execute_pdf_automark_job,
|
||||
)
|
||||
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_coordinate_pdf_automark_retries_with_ocr_and_returns_candidates():
|
||||
"""关键断言:普通 PDF 在坐标不足时由统一 Job 触发 OCR 后仍返回 candidates[]。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
reconstruction = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
|
||||
fields = {'order_field_candidates': [], 'page_no': 1}
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [
|
||||
ValidationError('missing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
|
||||
reconstruction,
|
||||
]
|
||||
coordinate.suggest_order_field_layouts.return_value = fields
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service',
|
||||
coordinate,
|
||||
create=True,
|
||||
):
|
||||
# execute 函数内部延迟导入,直接替换模块缓存中的服务对象。
|
||||
with patch.dict('sys.modules', {
|
||||
'app.services.shipping_notice.order_document_profile_service': coordinate,
|
||||
}):
|
||||
result = execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'schema_version_id': 3, 'page_no': 1,
|
||||
})
|
||||
|
||||
assert result['kind'] == 'coordinate_regions'
|
||||
assert [item['candidate_kind'] for item in result['candidates']] == ['coordinate_reconstruction', 'order_fields']
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(document_id=77, table_id='table-1', actor_id=None)
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_delegates_multi_source_evidence_to_same_contract():
|
||||
"""关键断言:XFA 由 Profile 能力自动识别,不要求客户端传类型且仍返回 candidates[]。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={'template_mode': 'xfa_dataset'}, status='draft')
|
||||
xfa = MagicMock()
|
||||
xfa.execute_xfa_ocr_automark_job.return_value = {
|
||||
'status': 'success', 'suggestions': [{'suggestion_id': 's-1'}], 'error_code': None,
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch.dict('sys.modules', {
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service': xfa,
|
||||
}):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77})
|
||||
|
||||
assert result['kind'] == 'visual_binding'
|
||||
assert result['candidates'] == [{'suggestion_id': 's-1'}]
|
||||
assert result['diagnostics']['evidence'] == ['pdfium', 'acroform_widget', 'ocr', 'xfa_datasets']
|
||||
@@ -168,6 +168,41 @@ def test_inventory_matching_retryable_exposes_retry_action():
|
||||
assert technical_auto_only is False
|
||||
|
||||
|
||||
def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_sufficiency(app, monkeypatch):
|
||||
"""匹配已完成但存在缺口时,当前匹配 Gate 必须通过并交给满足性 Gate。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
from app.models import ShippingNotice
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='SN-SHORTAGE-1',
|
||||
match_status='partial',
|
||||
shortage_json=[{'line_key': 'L1', 'shortage_qty': '2'}],
|
||||
)
|
||||
execution = SimpleNamespace(task_id=7)
|
||||
gate = SimpleNamespace(gate_code='inventory_matching')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
|
||||
lambda _payload: {'status': 'needs_human'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
|
||||
|
||||
with app.app_context():
|
||||
outcome = executor._handle_retry_inventory_matching(
|
||||
execution=execution,
|
||||
gate=gate,
|
||||
payload={},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'passed'
|
||||
assert outcome['output_snapshot']['business_result'] == 'inventory_shortage'
|
||||
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_inventory_preparation_retryable_without_reason_uses_contract_action():
|
||||
"""无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。"""
|
||||
|
||||
@@ -14,10 +14,11 @@ from unittest.mock import MagicMock, patch
|
||||
from app import db
|
||||
from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.models import Job, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
enqueue_gate_attempt_job,
|
||||
schedule_waiting_external_poll,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
@@ -114,3 +115,155 @@ def test_gate_failure_does_not_auto_retry(app):
|
||||
)
|
||||
assert queued_jobs == 0
|
||||
assert int(first_job_id) > 0
|
||||
|
||||
|
||||
def test_gate_waiting_external_schedules_next_poll(app):
|
||||
"""外部等待的 Gate Job 成功后必须创建下一次延迟轮询,不能永久停在处理中。"""
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-poll')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='wait-poll',
|
||||
idempotency_key='wait-poll-1',
|
||||
input_snapshot={'action_code': 'retry_layout_parsing', 'payload': {}},
|
||||
)
|
||||
job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id))
|
||||
job = db.session.get(Job, int(job_id))
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
db.session.commit()
|
||||
|
||||
ctx = MagicMock()
|
||||
ctx.extras = {'worker_label': 'wait-poll-worker'}
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt',
|
||||
return_value={
|
||||
'attempt_id': int(attempt.id),
|
||||
'gate_code': 'inventory_preparation',
|
||||
'gate_status': 'waiting_external',
|
||||
},
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_process_gate.schedule_waiting_external_poll',
|
||||
return_value=999,
|
||||
) as schedule_poll:
|
||||
run_shipping_process_gate(ctx, {'attempt_id': int(attempt.id), 'job_id': int(job_id)})
|
||||
|
||||
schedule_poll.assert_called_once_with(attempt_id=int(attempt.id))
|
||||
completed_job = db.session.get(Job, int(job_id))
|
||||
assert completed_job is not None
|
||||
assert completed_job.status == 'success'
|
||||
|
||||
|
||||
def test_waiting_inventory_gate_timeout_uses_timeout_reason(app):
|
||||
"""库存 RPA 外部等待超时时须改为 timeout 原因,不可遗留 queued 文案。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-timeout')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
assert execution.task_id == task_id
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='wait-timeout',
|
||||
idempotency_key='wait-timeout-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
assert gate is not None
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_queued'
|
||||
gate.effective_result_json = {
|
||||
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
|
||||
}
|
||||
# schedule_waiting_external_poll 只会在上一轮 Attempt 已正常收口后执行;
|
||||
# 保持该前置条件,避免 queued Attempt 触发并发保护而掩盖超时分支。
|
||||
attempt.status = 'succeeded'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
with app.app_context():
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
|
||||
db.session.commit()
|
||||
|
||||
# 前面的 nested app context 使用了独立 scoped session;清掉外层 identity map,
|
||||
# 才能断言内层同步实际提交的 Gate 事实,而不是旧会话中的 waiting_external 缓存。
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(ShippingProcessGate, int(gate.id))
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == 'blocked_manual'
|
||||
assert refreshed.blocking_reason_code == 'inventory_rpa_timeout'
|
||||
|
||||
|
||||
def test_waiting_inventory_gate_timeout_rechecks_callback_facts_before_blocking(app, monkeypatch):
|
||||
"""迟到的超时轮询不得覆盖已经成功落库的库存回调事实。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-timeout-callback-won')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
assert execution.task_id == task_id
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='wait-timeout-callback-won',
|
||||
idempotency_key='wait-timeout-callback-won-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
assert gate is not None
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_queued'
|
||||
gate.effective_result_json = {
|
||||
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
|
||||
}
|
||||
task = db.session.get(ShippingNotice, task_id)
|
||||
assert task is not None
|
||||
task.inventory_lines_json = [{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}]
|
||||
assert task.inventory_lines_json
|
||||
attempt.status = 'succeeded'
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
sync_calls = []
|
||||
|
||||
def _sync_callback_success(*, execution, **_kwargs):
|
||||
sync_calls.append(int(execution.id))
|
||||
refreshed_gate = db.session.get(ShippingProcessGate, int(gate.id))
|
||||
assert refreshed_gate is not None
|
||||
refreshed_gate.status = 'passed'
|
||||
refreshed_gate.blocking_reason_code = None
|
||||
db.session.flush()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
_sync_callback_success,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
|
||||
db.session.commit()
|
||||
|
||||
# nested app context 已提交同步结果;外层会话须失效旧 Gate 缓存后再读取。
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(ShippingProcessGate, int(gate.id))
|
||||
assert sync_calls == [int(execution.id)]
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == 'passed'
|
||||
assert refreshed.blocking_reason_code is None
|
||||
@@ -173,6 +173,106 @@ def test_ensure_execution_creates_all_contract_gates(gate_execution):
|
||||
|
||||
|
||||
|
||||
def test_ensure_execution_for_task_ignores_superseded_execution(app):
|
||||
|
||||
"""Task 指针指向已替代 Execution 时必须创建新正式链,不能复用历史 Gate。"""
|
||||
|
||||
with app.app_context():
|
||||
|
||||
_user, _review_case_id, task_id = _seed_workflow_version(suffix='superseded-task')
|
||||
|
||||
old = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
|
||||
|
||||
old.status = 'superseded'
|
||||
|
||||
db.session.flush()
|
||||
|
||||
current = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
|
||||
|
||||
assert current.id != old.id
|
||||
|
||||
assert current.status == 'active'
|
||||
|
||||
|
||||
|
||||
def test_auto_progress_does_not_queue_manual_inventory_retry(gate_execution, monkeypatch):
|
||||
|
||||
"""自动推进不得把用户恢复动作 retry_inventory_preparation 重新触发为 RPA。"""
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
for prior_gate in (
|
||||
ShippingProcessGate.query
|
||||
.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
prior_gate.status = 'passed'
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
process_gate_service,
|
||||
'queue_gate_attempt',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
)
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(
|
||||
execution=gate_execution,
|
||||
gate=gate,
|
||||
)
|
||||
|
||||
assert queued == []
|
||||
|
||||
|
||||
def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution, monkeypatch):
|
||||
"""库存已入库后的 upload_inventory_file 是导航动作,不能被自动续跑执行。"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
for prior_gate in (
|
||||
ShippingProcessGate.query
|
||||
.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
prior_gate.status = 'passed'
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_rpa_timeout'
|
||||
gate.next_action_code = 'upload_inventory_file'
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
process_gate_service,
|
||||
'queue_gate_attempt',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
)
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(
|
||||
execution=gate_execution,
|
||||
gate=gate,
|
||||
)
|
||||
|
||||
assert queued == []
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution):
|
||||
@@ -684,3 +784,29 @@ def test_idempotent_key_conflicts_across_execution(app):
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
|
||||
|
||||
|
||||
def test_superseded_execution_rejects_late_business_gate_result(app):
|
||||
"""候选版本已替换后,迟到结果不得重新写回旧 Gate。"""
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='superseded-sync')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
)
|
||||
execution.status = 'superseded'
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
sync_gate_from_business_result(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
passed=False,
|
||||
blocking_reason_code='inventory_preparation_failed',
|
||||
effective_result_json={'findings': []},
|
||||
idempotency_key='late-result-must-not-write-superseded-execution',
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_EXECUTION_SUPERSEDED'
|
||||
@@ -80,6 +80,83 @@ def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
|
||||
assert preparation.status == 'succeeded'
|
||||
|
||||
|
||||
def test_rpa_callback_completes_waiting_preparation_recovery_plan(app):
|
||||
"""RPA 成功回调完成准备轮次后,关联恢复计划不得继续占用 waiting_external。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingProcessExecution,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_recovery_service import (
|
||||
create_inventory_preparation_round,
|
||||
sync_inventory_preparation_round,
|
||||
sync_preparation_source_from_rpa_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-PLAN-COMPLETE')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-PREP-PLAN-COMPLETE', task_id=int(task.id), status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
plan = ShippingProcessRecoveryPlan(
|
||||
plan_no='RCP-PREP-PLAN-COMPLETE', execution_id=int(execution.id),
|
||||
current_gate='inventory_matching', action_code='retry_inventory_from_preparation',
|
||||
target_gate='inventory_preparation', resume_after_gate='inventory_matching',
|
||||
status='waiting_external', invalidation_plan_json={},
|
||||
idempotency_key='prep-plan-complete', actor_type='user',
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
preparation = create_inventory_preparation_round(
|
||||
task=task, execution_id=int(execution.id), recovery_plan_id=int(plan.id),
|
||||
action_code='retry_inventory_from_preparation', source_codes=['DBS'], gate_attempt_id=None,
|
||||
)
|
||||
rpa = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-PREP-PLAN-COMPLETE',
|
||||
status='queued', lease_token='lease-prep-plan', extra_json={}, callback_payload_json={},
|
||||
)
|
||||
db.session.add(rpa)
|
||||
db.session.flush()
|
||||
sync_inventory_preparation_round(
|
||||
preparation_attempt=preparation,
|
||||
result={'pending_source_codes': ['DBS'], 'source_attempts': {'DBS': {'attempt_id': rpa.id}}},
|
||||
)
|
||||
|
||||
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(rpa.id), rpa_status='succeeded')
|
||||
|
||||
db.session.refresh(plan)
|
||||
assert preparation.status == 'succeeded'
|
||||
assert plan.status == 'succeeded'
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_per_source_summary_exposes_attempt_id_for_preparation_lineage(app):
|
||||
"""新建 RPA Attempt 的汇总必须返回主键,准备轮次才能被回调准确收口。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice.per_source_rpa_service import _attempts_summary
|
||||
|
||||
task = ShippingNotice(task_no='SN-PREP-SUMMARY-ID')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
attempt = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='DBS', attempt_no=1,
|
||||
source_run_no='PSR-PREP-SUMMARY-ID', status='queued',
|
||||
lease_token='lease-prep-summary', extra_json={}, callback_payload_json={},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
|
||||
summary = _attempts_summary(task.task_no, source_codes=['DBS'])
|
||||
|
||||
assert summary['DBS']['attempt_id'] == int(attempt.id)
|
||||
|
||||
|
||||
def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, app):
|
||||
"""库存准备 Trigger 必须把 GateAttempt 身份原样带到 RPA。"""
|
||||
from app import db
|
||||
@@ -186,7 +263,7 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
|
||||
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
|
||||
)
|
||||
assert seen['actor_id'] == 77
|
||||
assert result['outcome'] in {'blocked_retryable', 'blocked_manual'}
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
|
||||
|
||||
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
@@ -340,7 +417,7 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
|
||||
|
||||
def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
|
||||
"""批量成功项也必须先通过逐源身份校验,不能先入库再拒绝。"""
|
||||
"""异步批量处理体必须先通过逐源身份校验,不能先入库再拒绝。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice import inventory_rpa_workflow
|
||||
@@ -360,7 +437,8 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
lambda task: legacy_called.__setitem__('value', True) or task,
|
||||
)
|
||||
|
||||
response = inventory_rpa_workflow.rpa_report_inventory_batch({
|
||||
# HTTP 入口只负责受控收件和入队;身份围栏属于 Worker 正式处理体。
|
||||
response = inventory_rpa_workflow.process_rpa_report_inventory_batch({
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'callback_id': 'batch-callback-identity',
|
||||
'batch_run_no': 'BATCH-CALLBACK-IDENTITY',
|
||||
@@ -458,6 +536,80 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
assert execution.status == 'active'
|
||||
|
||||
|
||||
def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
"""迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no='SN-RPA-LATE-SUCCESS',
|
||||
pending_human_reason='rpa_exhausted',
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
|
||||
preparation = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_preparation',
|
||||
).one()
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_matching',
|
||||
).one()
|
||||
assert preparation.status == 'passed'
|
||||
assert preparation.blocking_reason_code is None
|
||||
# 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。
|
||||
assert matching.status == 'blocked_retryable'
|
||||
assert matching.blocking_reason_code == 'inventory_match_failed'
|
||||
|
||||
|
||||
def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
"""跨 Gate 恢复后,旧准备轮询不得在库存匹配 Gate 产生技术失败。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
task = ShippingNotice(task_no='SN-STALE-PREP-POLL')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-STALE-PREP-POLL', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_matching',
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_matching',
|
||||
).one()
|
||||
gate.status = 'waiting_external'
|
||||
gate.next_action_code = 'poll_inventory_preparation'
|
||||
gate.effective_result_json = {'waiting_since': datetime.utcnow().isoformat()}
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code=gate.gate_code,
|
||||
trigger_type='user_retry', actor_type='system', actor_id='test',
|
||||
idempotency_key='stale-preparation-poll',
|
||||
input_snapshot={'action_code': 'retry_inventory_from_preparation', 'payload': {}},
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
|
||||
assert attempt.job_id is None
|
||||
|
||||
|
||||
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
|
||||
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
|
||||
from app import db
|
||||
@@ -956,7 +1108,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
|
||||
'freeze_mode': 'manual',
|
||||
}
|
||||
assert task.order_snapshot_id == 901
|
||||
assert result['outcome'] == 'blocked_retryable'
|
||||
assert result['outcome'] == 'waiting_external'
|
||||
|
||||
|
||||
def test_manual_business_block_is_a_successful_attempt(app):
|
||||
|
||||
@@ -14,7 +14,10 @@ from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
|
||||
from app.services.shipping_notice.processing_ownership import (
|
||||
assert_notice_task_ownership,
|
||||
record_projection_inconsistency_audit,
|
||||
)
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
|
||||
@@ -65,6 +68,24 @@ def test_reconcile_marks_inconsistency_and_strips_fulfillment():
|
||||
assert len(payload['stage_nodes']) == 15
|
||||
|
||||
|
||||
def test_projection_inconsistency_audit_uses_allowed_failure_result(app):
|
||||
"""不一致审计必须以 audit_service 接受的 failure 落库,不能在 GET 路径反复报参数非法。"""
|
||||
with app.app_context():
|
||||
with patch(
|
||||
'app.services.shipping_notice.processing_ownership.append_shipping_audit_event',
|
||||
) as append_mock, patch(
|
||||
'app.services.shipping_notice.processing_ownership.db.session.flush',
|
||||
):
|
||||
record_projection_inconsistency_audit({
|
||||
'projection_inconsistency_code': PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
'work_item_no': 'OT-9',
|
||||
'shipping_notice_no': 'SN-9',
|
||||
'stage': 'waiting_review',
|
||||
})
|
||||
|
||||
assert append_mock.call_args.kwargs['result'] == 'failure'
|
||||
|
||||
|
||||
def test_assert_ownership_noop_without_expected_context():
|
||||
"""未传期望 OT/Case/Run 时不拦截(兼容旧客户端)。"""
|
||||
task = SimpleNamespace(id=1, task_no='SN-1', order_task_id=None)
|
||||
|
||||
@@ -83,6 +83,29 @@ def test_projection_fact_read_failure_is_fail_closed():
|
||||
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
|
||||
|
||||
|
||||
def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason():
|
||||
"""库存缺口 Gate 不能只保留内部码而遗漏批次/工作台的统一阻塞原因。"""
|
||||
payload = apply_user_projection_fields(reconcile_processing_projection_facts({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_matching',
|
||||
'source_type': 'eml',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked_manual',
|
||||
'next_action_code': 'open_shortage_review',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
},
|
||||
'available_actions': ['open_shortage_review'],
|
||||
}))
|
||||
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'inventory_shortage_review_required',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.inventory_shortage_review_required',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_normalize_unknown_action_codes():
|
||||
"""未知 / 别名动作码映射到契约或丢弃。"""
|
||||
assert normalize_action_code('retry_failed_documents') == 'retry'
|
||||
@@ -295,6 +318,93 @@ def test_inventory_snapshot_missing_projects_retryable_inventory_action():
|
||||
}
|
||||
|
||||
|
||||
def test_formal_blocked_gate_overrides_stale_preparation_running_state():
|
||||
"""正式 Gate 已阻断时,旧库存准备 waiting 不能把用户态降回系统处理中。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'processing',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_retryable',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'technical_failure_present',
|
||||
},
|
||||
'available_actions': ['retry_inventory_preparation'],
|
||||
})
|
||||
|
||||
# 关键断言:Gate 是业务裁决真相;Preparation Attempt 只能作为过程明细。
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
|
||||
|
||||
def test_formal_inventory_matching_retry_projects_business_i18n_key():
|
||||
"""正式 OT 的库存重试不得让页面回退展示内部 action code。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_matching',
|
||||
'source_type': 'order_task',
|
||||
'shipping_notice_no': 'SN-RETRY-MATCH',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_matching',
|
||||
'status': 'blocked_retryable',
|
||||
'next_action_code': 'retry_inventory_matching',
|
||||
'blocking_reason_code': 'inventory_match_failed',
|
||||
},
|
||||
'available_actions': ['retry_inventory_matching'],
|
||||
})
|
||||
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_matching',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_matching',
|
||||
'parameters': {},
|
||||
}
|
||||
|
||||
|
||||
def test_formal_inventory_gate_overrides_stale_waiting_review_compatibility_fields():
|
||||
"""正式库存 Gate 必须覆盖历史 OT 的 waiting_review,防止阶段回退。"""
|
||||
payload = reconcile_processing_projection_facts({
|
||||
'work_item_no': 'OT-GATE-OVERRIDE',
|
||||
'shipping_notice_no': 'SN-GATE-OVERRIDE',
|
||||
'status': 'waiting_review',
|
||||
'stage': 'waiting_review',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_manual',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'inventory_rpa_timeout',
|
||||
},
|
||||
'available_actions': ['open_order_review'],
|
||||
})
|
||||
|
||||
assert payload['status'] == 'waiting_review'
|
||||
assert payload['stage'] == 'inventory_fetching'
|
||||
assert 'projection_inconsistency_code' not in payload
|
||||
assert payload['available_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_inventory_file_missing_exposes_a_user_facing_reason_i18n_key():
|
||||
"""库存文件缺失需携带可翻译原因,批次中心不得回显内部原因码。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_file_missing',
|
||||
},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'inventory_file_missing',
|
||||
'i18n_key': 'chat.shippingProcessing.reasonCode.inventory_file_missing',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
|
||||
"""库存文件缺失必须保留 Gate 重试,不得降级为线外上传或空按钮。"""
|
||||
payload = apply_user_projection_fields({
|
||||
|
||||
@@ -23,6 +23,7 @@ from app import db
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderSubmission,
|
||||
User,
|
||||
)
|
||||
@@ -33,7 +34,11 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
)
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
_aggregate_eml_order_task_work_items,
|
||||
_batch_file_counts,
|
||||
_batch_four_stage_nodes,
|
||||
_batch_ui_state_from_items,
|
||||
_conversation_processing_from_work_items,
|
||||
_processing_ui_state_from_item,
|
||||
_project_order_task_work_item,
|
||||
map_run_status_to_processing_status,
|
||||
map_run_to_processing_stage,
|
||||
@@ -85,6 +90,566 @@ def test_map_run_status_to_processing_status() -> None:
|
||||
assert map_run_status_to_processing_status('unknown') == 'processing'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('stage', 'expected_lifecycle_stage'),
|
||||
[
|
||||
('inventory_preparation', 'fulfillment_prep'),
|
||||
('inventory_candidates_calculated', 'fulfillment_prep'),
|
||||
('inventory_candidates_frozen', 'fulfillment_prep'),
|
||||
('inventory_snapshots_ready', 'fulfillment_prep'),
|
||||
('inventory_matched', 'fulfillment_prep'),
|
||||
('excel_generated', 'fulfillment_prep'),
|
||||
('upload_receipt_recorded', 'upload_complete'),
|
||||
],
|
||||
)
|
||||
def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
|
||||
stage: str,
|
||||
expected_lifecycle_stage: str,
|
||||
) -> None:
|
||||
"""自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
'stage': stage,
|
||||
'user_stage': stage,
|
||||
'status': 'running',
|
||||
'user_status': 'running',
|
||||
}])
|
||||
|
||||
summaries = {node['code']: node['summary']['total'] for node in nodes}
|
||||
assert summaries[expected_lifecycle_stage] == 1
|
||||
assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('item', 'expected_lifecycle_stage'),
|
||||
[
|
||||
({'user_stage': 'inventory_match'}, 'fulfillment_prep'),
|
||||
({'user_stage': 'freight_upload'}, 'upload_complete'),
|
||||
({'user_stage': 'customer_resolving'}, 'order_review'),
|
||||
({'user_stage': 'duplicate_checking'}, 'order_review'),
|
||||
({'user_stage': 'waiting_human_review'}, 'order_review'),
|
||||
# Case bundle 已归一化为业务阶段时,批次摘要与生命周期入口必须直接识别,
|
||||
# 不能错误落入 unclassified 并禁用订单复核入口。
|
||||
({'user_stage': 'order_review'}, 'order_review'),
|
||||
# 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。
|
||||
({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'),
|
||||
({'stage': 'document_parsing', 'user_current_gate_code': 'inventory_matching'}, 'fulfillment_prep'),
|
||||
# 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。
|
||||
({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'),
|
||||
({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'),
|
||||
],
|
||||
)
|
||||
def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases(
|
||||
item: dict[str, object],
|
||||
expected_lifecycle_stage: str,
|
||||
) -> None:
|
||||
"""批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
**item,
|
||||
'status': 'waiting_human',
|
||||
'user_status': 'waiting_human',
|
||||
}])
|
||||
|
||||
summaries = {node['code']: node['summary']['total'] for node in nodes}
|
||||
assert summaries[expected_lifecycle_stage] == 1
|
||||
assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0)
|
||||
|
||||
|
||||
def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> None:
|
||||
"""通知准备未完成时通知完成必须由后端裁决为不可进入,不能由前端自行限制。"""
|
||||
fulfillment_state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'inventory_match',
|
||||
'current_gate': {'gate_code': 'inventory_matching'},
|
||||
'source_summary': {'candidate_count': 1},
|
||||
'run_no': 'SNER-LIFECYCLE',
|
||||
'case_no': 'SNRC-LIFECYCLE',
|
||||
'root_order_task_no': 'OT-LIFECYCLE',
|
||||
'primary_action': {'code': 'open_inventory_match_review'},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert fulfillment_state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert fulfillment_state['lifecycle_entries'] == [
|
||||
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
]
|
||||
assert fulfillment_state['primary_action']['execution_mode'] == 'navigate'
|
||||
assert fulfillment_state['primary_action']['target_surface'] == 'order_lifecycle_workbench'
|
||||
assert fulfillment_state['primary_action']['target_lifecycle_stage'] == 'fulfillment_prep'
|
||||
|
||||
secondary_state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'inventory_match',
|
||||
'current_gate': {'gate_code': 'inventory_matching'},
|
||||
'source_summary': {'candidate_count': 1},
|
||||
'run_no': 'SNER-LIFECYCLE-SECONDARY',
|
||||
'case_no': 'SNRC-LIFECYCLE-SECONDARY',
|
||||
'root_order_task_no': 'OT-LIFECYCLE-SECONDARY',
|
||||
'available_actions': ['view_result'],
|
||||
})
|
||||
assert secondary_state['secondary_actions'] == [{
|
||||
'code': 'view_result',
|
||||
'enabled': True,
|
||||
'execution_mode': 'navigate',
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
'target_lifecycle_stage': 'fulfillment_prep',
|
||||
}]
|
||||
|
||||
legacy_view_state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'waiting_review',
|
||||
'source_summary': {'candidate_count': 1},
|
||||
'run_no': 'SNER-LIFECYCLE-VIEW',
|
||||
'case_no': 'SNRC-LIFECYCLE-VIEW',
|
||||
'root_order_task_no': 'OT-LIFECYCLE-VIEW',
|
||||
# 历史 Review 投影仍可能下发 view;它与 view_result 一样只是后端已授权的查看入口。
|
||||
'available_actions': ['view'],
|
||||
})
|
||||
assert legacy_view_state['secondary_actions'] == [{
|
||||
'code': 'view',
|
||||
'enabled': True,
|
||||
'execution_mode': 'navigate',
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
'target_lifecycle_stage': 'order_review',
|
||||
}]
|
||||
|
||||
review_state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'waiting_review',
|
||||
'source_summary': {'candidate_count': 1},
|
||||
'run_no': 'SNER-REVIEW',
|
||||
'case_no': 'SNRC-REVIEW',
|
||||
'root_order_task_no': 'OT-REVIEW',
|
||||
'available_actions': [],
|
||||
})
|
||||
assert review_state['lifecycle_entries'] == [
|
||||
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
]
|
||||
|
||||
|
||||
def test_processing_ui_state_exposes_shared_gate_authority() -> None:
|
||||
"""批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。"""
|
||||
state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'document_parsing',
|
||||
'current_gate': {'gate_code': 'inventory_matching'},
|
||||
'source_summary': {'candidate_count': 1},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert state['lifecycle_stage'] == 'fulfillment_prep'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
|
||||
|
||||
def test_processing_ui_state_without_candidate_does_not_expose_lifecycle_entries() -> None:
|
||||
"""仅有解析任务标识不等于订单候选,三个入口必须全部缺席。"""
|
||||
state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'waiting_human_review',
|
||||
'source_summary': {'candidate_count': 0},
|
||||
'run_no': 'SNER-NO-CANDIDATE',
|
||||
'case_no': None,
|
||||
# 解析任务也可有 root OT 导航标识;它不能错误开放三阶段工作台。
|
||||
'root_order_task_no': 'OT-PARSING-ONLY',
|
||||
'available_actions': [],
|
||||
})
|
||||
assert state['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_processing_ui_state_empty_review_case_does_not_expose_lifecycle_entries() -> None:
|
||||
"""Review Case 未关联 Candidate 时仍属解析中,不能以 Case 编号开放生命周期。"""
|
||||
state = _processing_ui_state_from_item({
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'waiting_human_review',
|
||||
'source_summary': {'candidate_count': 0},
|
||||
'run_no': 'SNER-EMPTY-CASE',
|
||||
'case_no': 'SORC-EMPTY-CANDIDATE',
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert state['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_intake_candidate_context_ignores_superseded_candidate(app) -> None:
|
||||
"""历史 Candidate 只能审计,不能重新打开当前文件的生命周期入口。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SUPERSEDED-CANDIDATE')
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUPERSEDED-CONTEXT',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='superseded-context',
|
||||
is_current_version=False,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
|
||||
assert item['source_summary']['candidate_count'] == 0
|
||||
assert _processing_ui_state_from_item(item)['lifecycle_entries'] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate_status', ('rejected', 'expired'))
|
||||
def test_intake_candidate_context_ignores_non_reviewable_current_candidate(app, candidate_status: str) -> None:
|
||||
"""当前版本但已拒绝/过期的 Candidate 不能重新开放订单生命周期入口。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix=f'NON-REVIEWABLE-{candidate_status}')
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-NON-REVIEWABLE-{candidate_status}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key=f'non-reviewable-{candidate_status}',
|
||||
is_current_version=True,
|
||||
candidate_status=candidate_status,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
|
||||
assert item['source_summary']['candidate_count'] == 0
|
||||
assert _processing_ui_state_from_item(item)['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_order_task_current_gate_ignores_empty_review_case(app) -> None:
|
||||
"""空 Case 不能回退合成订单复核 Gate;当前阶段仍须由真实解析链路负责。"""
|
||||
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.models import ShippingOrderReviewCase, ShippingOrderTask
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='EMPTY-CASE-GATE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-EMPTY-CASE-GATE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=run.id,
|
||||
candidate_id=None,
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
)
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SORC-EMPTY-GATE',
|
||||
run_id=run.id,
|
||||
unit_id=run.extraction_plan.units[0].id,
|
||||
document_id=document.id,
|
||||
candidate_id=None,
|
||||
owner_user_id=user.id,
|
||||
status='unreviewed',
|
||||
)
|
||||
db.session.add_all([task, case])
|
||||
db.session.commit()
|
||||
|
||||
item = _project_order_task_work_item(run, order_task=task)
|
||||
|
||||
assert item is not None
|
||||
assert item['current_gate'] is None
|
||||
|
||||
|
||||
def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None:
|
||||
"""历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。"""
|
||||
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.models import ShippingOrderTask
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SUPERSEDED-OT-CANDIDATE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
old = ShippingOrderCandidate(
|
||||
candidate_no='CAND-OLD-OT', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='old-ot',
|
||||
order_extraction_run_id=run.id, is_current_version=False,
|
||||
)
|
||||
current = ShippingOrderCandidate(
|
||||
candidate_no='CAND-CURRENT-OTHER', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='current-other',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
)
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-SUPERSEDED-CANDIDATE', user_id=user.id,
|
||||
conversation_id=session.session_id, extraction_run_id=run.id,
|
||||
candidate_id=None, status='processing', stage='candidate_creating',
|
||||
)
|
||||
db.session.add_all([old, current])
|
||||
db.session.flush()
|
||||
task.candidate_id = old.id
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
item = _project_order_task_work_item(run, order_task=task)
|
||||
|
||||
assert item is not None
|
||||
assert item['source_summary']['candidate_count'] == 0
|
||||
assert _processing_ui_state_from_item(item)['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None:
|
||||
"""四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
|
||||
projection = _conversation_processing_from_work_items([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW',
|
||||
'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf',
|
||||
'source_summary': {'document_id': 1, 'filename': 'review.pdf'},
|
||||
'user_status': 'waiting_human', 'user_stage': 'waiting_review',
|
||||
'blocking_reason': {'code': 'order_review_required'},
|
||||
'available_actions': [],
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-UNKNOWN',
|
||||
'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf',
|
||||
'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'},
|
||||
'user_status': 'running', 'user_stage': 'unmapped_legacy_stage',
|
||||
'available_actions': [],
|
||||
},
|
||||
])
|
||||
|
||||
nodes = {node['code']: node for node in projection['four_stage_nodes']}
|
||||
assert nodes['order_review']['status'] == 'blocked'
|
||||
assert nodes['intake_parse']['status'] == 'pending'
|
||||
assert projection['unclassified_summary'] == {'count': 1}
|
||||
|
||||
|
||||
def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
|
||||
"""同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'INTAKE:SNI-DOUBLE',
|
||||
'source_type': 'eml',
|
||||
'user_status': 'waiting_human',
|
||||
'user_stage': 'order_review',
|
||||
'aggregate_children': [
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-1',
|
||||
'user_status': 'waiting_human', 'user_stage': 'order_review',
|
||||
'current_gate': {'gate_code': 'field_completeness'},
|
||||
'blocking_reason': {'code': 'required_field_missing'},
|
||||
'source_summary': {'document_id': 301, 'filename': 'first.pdf'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-2',
|
||||
'user_status': 'waiting_human', 'user_stage': 'order_review',
|
||||
'current_gate': {'gate_code': 'field_completeness'},
|
||||
'blocking_reason': {'code': 'required_field_missing'},
|
||||
'source_summary': {'document_id': 302, 'filename': 'second.pdf'},
|
||||
},
|
||||
],
|
||||
}])
|
||||
|
||||
order_review = next(node for node in nodes if node['code'] == 'order_review')
|
||||
assert order_review['status'] == 'blocked'
|
||||
assert order_review['summary']['total'] == 2
|
||||
assert order_review['summary']['needs_action'] == 2
|
||||
|
||||
|
||||
def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection() -> None:
|
||||
"""同一 PDF 的历史失败投影不能与当前通知准备投影重复计数或覆盖当前阶段。"""
|
||||
nodes = _batch_four_stage_nodes([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'last_activity_at': '2026-08-15T09:00:00Z',
|
||||
'blocking_reason': {'code': 'intake_parse_failed'},
|
||||
'source_summary': {'document_id': 401, 'filename': 'same.pdf'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
|
||||
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
|
||||
'last_activity_at': '2026-08-15T10:00:00Z',
|
||||
'blocking_reason': {'code': 'inventory_match_failed'},
|
||||
'source_summary': {'document_id': 401, 'filename': 'same.pdf'},
|
||||
},
|
||||
])
|
||||
|
||||
by_stage = {node['code']: node['summary'] for node in nodes}
|
||||
assert by_stage['intake_parse']['total'] == 0
|
||||
assert by_stage['fulfillment_prep'] == {
|
||||
'total': 1, 'completed': 0, 'needs_action': 1, 'processing': 0,
|
||||
'failed': 0, 'blocking_reason': {'code': 'inventory_match_failed'},
|
||||
}
|
||||
|
||||
|
||||
def test_batch_file_counts_uses_the_same_current_file_representative_as_stage_summary() -> None:
|
||||
"""同一 PDF 的历史失败项不能同时计入失败和当前处理中的文件数量。"""
|
||||
work_items = [
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'last_activity_at': '2026-08-15T09:00:00Z',
|
||||
'source_summary': {'document_id': 501, 'filename': 'same.pdf'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
|
||||
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
|
||||
'last_activity_at': '2026-08-15T10:00:00Z',
|
||||
'source_summary': {'document_id': 501, 'filename': 'same.pdf'},
|
||||
},
|
||||
]
|
||||
|
||||
assert _batch_file_counts(work_items) == {
|
||||
'total_files': 1,
|
||||
'failed_files': 0,
|
||||
'waiting_human_files': 1,
|
||||
'processing_files': 0,
|
||||
'completed_files': 0,
|
||||
}
|
||||
|
||||
|
||||
def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None:
|
||||
"""待处理组不能因旧 user_status=running 被阶段卡错误显示为处理中。"""
|
||||
work_items = [{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'OT-GROUP-OVERRIDES-STATUS',
|
||||
'user_group': 'waiting_human',
|
||||
'user_status': 'running',
|
||||
'user_stage': 'inventory_matching',
|
||||
'source_summary': {'document_id': 502, 'filename': 'waiting.pdf'},
|
||||
}]
|
||||
|
||||
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
|
||||
fulfillment = next(
|
||||
node for node in _batch_four_stage_nodes(work_items)
|
||||
if node['code'] == 'fulfillment_prep'
|
||||
)
|
||||
assert fulfillment['summary']['needs_action'] == 1
|
||||
assert fulfillment['summary']['processing'] == 0
|
||||
|
||||
|
||||
def test_conversation_status_groups_use_the_same_current_file_representative() -> None:
|
||||
"""文件清单不能保留旧失败项,否则会与互斥统计和当前 CTA 相互矛盾。"""
|
||||
projection = _conversation_processing_from_work_items([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-HISTORY-LIST',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'user_group': 'failed', 'last_activity_at': '2026-08-15T09:00:00Z',
|
||||
'source_summary': {'document_id': 525, 'filename': 'same.pdf'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT-LIST',
|
||||
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
|
||||
'user_group': 'waiting_human', 'last_activity_at': '2026-08-15T10:00:00Z',
|
||||
'source_summary': {'document_id': 525, 'filename': 'same.pdf'},
|
||||
},
|
||||
])
|
||||
|
||||
assert projection['summary']['total_files'] == 1
|
||||
assert projection['status_groups']['failed'] == []
|
||||
assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [
|
||||
'OT-CURRENT-LIST',
|
||||
]
|
||||
|
||||
|
||||
def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None:
|
||||
"""历史失败项不得在互斥统计后仍抢走批次当前按钮。"""
|
||||
work_items = [
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-HISTORY',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'last_activity_at': '2026-08-15T09:00:00Z',
|
||||
'primary_action': {'code': 'retry_parse'},
|
||||
'available_actions': ['retry_parse'],
|
||||
'blocking_reason': {'code': 'intake_parse_failed'},
|
||||
'source_summary': {'document_id': 551, 'filename': 'same.pdf'},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
|
||||
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
|
||||
'last_activity_at': '2026-08-15T10:00:00Z',
|
||||
'primary_action': {'code': 'open_inventory_match_review'},
|
||||
'available_actions': ['open_inventory_match_review'],
|
||||
'blocking_reason': {'code': 'inventory_match_failed'},
|
||||
'source_summary': {'document_id': 551, 'filename': 'same.pdf'},
|
||||
},
|
||||
]
|
||||
|
||||
assert _batch_ui_state_from_items(work_items) == {
|
||||
'status': 'waiting_human',
|
||||
'stage': 'inventory_matching',
|
||||
'blocking_reason': {'code': 'inventory_match_failed'},
|
||||
'primary_action': {'code': 'open_inventory_match_review'},
|
||||
'secondary_actions': [],
|
||||
}
|
||||
|
||||
|
||||
def test_batch_file_counts_deduplicates_reparse_versions_by_content_hash() -> None:
|
||||
"""重解析产生新 document_id 时,内容哈希相同的 PDF 仍只计当前一项。"""
|
||||
work_items = [
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-V1',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'last_activity_at': '2026-08-15T09:00:00Z',
|
||||
'source_summary': {
|
||||
'document_id': 601, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64,
|
||||
},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-V2',
|
||||
'user_status': 'waiting_human', 'user_stage': 'order_review',
|
||||
'last_activity_at': '2026-08-15T10:00:00Z',
|
||||
'source_summary': {
|
||||
'document_id': 602, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
assert _batch_file_counts(work_items)['total_files'] == 1
|
||||
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
|
||||
|
||||
|
||||
def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids() -> None:
|
||||
"""同内容 PDF 重传即使根文档不同,也只能保留最新一份实时投影。"""
|
||||
work_items = [
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V1',
|
||||
'user_status': 'failed', 'user_stage': 'document_parsing',
|
||||
'last_activity_at': '2026-08-15T09:00:00Z',
|
||||
'source_summary': {
|
||||
'document_id': 701, 'root_document_id': 701,
|
||||
'filename': 'same-content.pdf', 'content_hash': 'b' * 64,
|
||||
},
|
||||
},
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V2',
|
||||
'user_status': 'waiting_human', 'user_stage': 'order_review',
|
||||
'last_activity_at': '2026-08-15T10:00:00Z',
|
||||
'source_summary': {
|
||||
'document_id': 702, 'root_document_id': 702,
|
||||
'filename': 'same-content.pdf', 'content_hash': 'b' * 64,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
assert _batch_file_counts(work_items)['total_files'] == 1
|
||||
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
|
||||
|
||||
|
||||
def test_batch_output_artifacts_only_projects_formal_downloadable_artifact() -> None:
|
||||
"""批次下载资格必须来自正式 Artifact,不得由旧 notice 路径字段伪造。"""
|
||||
from app.services.shipping_notice.shipping_processing_projection import _batch_output_artifacts
|
||||
|
||||
with patch('app.services.shipping_notice.shipping_processing_projection.ShippingOrderTask.query') as task_query:
|
||||
task_query.filter_by.return_value.first.return_value = SimpleNamespace(shipping_notice_id=9)
|
||||
with patch('app.services.shipping_notice.shipping_processing_projection.db.session.get') as get_notice:
|
||||
get_notice.return_value = SimpleNamespace(
|
||||
id=9,
|
||||
task_no='OT-EXPORT',
|
||||
export_file_name='legacy.xlsx',
|
||||
export_file_path='D:/legacy.xlsx',
|
||||
)
|
||||
with patch('app.services.shipping_notice.shipping_processing_projection.resolve_task_export_download', return_value=None):
|
||||
assert _batch_output_artifacts([{'root_order_task_no': 'OT-EXPORT'}]) == []
|
||||
|
||||
|
||||
def test_aggregate_eml_work_items_uses_upload_completion_not_candidate_completion() -> None:
|
||||
"""同一 EML 聚合卡仅在所有附件上传成功后完成,候选生成仍属于处理中。"""
|
||||
base = {
|
||||
@@ -372,7 +937,68 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
|
||||
|
||||
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'}
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'open_order_review'
|
||||
# 空 Candidate Case 的入口只打开接收解析处置面,不能伪装为订单复核。
|
||||
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
assert leaf['ui_state']['primary_action']['target_lifecycle_stage'] == 'intake_parse'
|
||||
# 无 Candidate 的人工解析 Case 仍可进入解析复核,但不得伪装成订单生命周期。
|
||||
assert leaf['source_summary']['candidate_count'] == 0
|
||||
assert leaf['ui_state']['lifecycle_entries'] == []
|
||||
assert leaf['intake_parse_authorized'] is True
|
||||
|
||||
|
||||
def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document(app) -> None:
|
||||
"""有效 Candidate 只为其主 PDF 开放订单生命周期,兄弟 PDF 必须保持关闭。"""
|
||||
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, first_pdf = _seed_run_input(
|
||||
suffix='EML-CANDIDATE-LEAF-LIFECYCLE',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
second_pdf = ShippingOrderDocument(
|
||||
intake_id=int(intake.id), document_type='attachment',
|
||||
attachment_key='candidate-sibling.pdf', filename='candidate-sibling.pdf',
|
||||
content_hash='7' * 64, classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(second_pdf)
|
||||
db.session.flush()
|
||||
first_unit = next(unit for unit in run.extraction_plan.units if int(unit.document_id) == int(first_pdf.id))
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-EML-LEAF-LIFECYCLE', intake_id=intake.id,
|
||||
order_extraction_run_id=run.id, primary_document_id=first_pdf.id,
|
||||
candidate_key='eml-candidate-leaf-lifecycle', is_current_version=True,
|
||||
candidate_status='provisional',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
first_unit.status = 'review_required'
|
||||
first_unit.reason_code = 'required_field_missing'
|
||||
review_case = ensure_review_case_for_unit(run=run, unit=first_unit)
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
by_document_id = {
|
||||
int(child['source_summary']['document_id']): child
|
||||
for child in item['aggregate_children']
|
||||
}
|
||||
candidate_leaf = by_document_id[int(first_pdf.id)]
|
||||
sibling_leaf = by_document_id[int(second_pdf.id)]
|
||||
|
||||
assert review_case is not None
|
||||
assert candidate_leaf['source_summary']['candidate_count'] == 1
|
||||
# 顶层字段与 ui_state 必须是同一次后端裁决,供批次与工作台共用。
|
||||
assert candidate_leaf['lifecycle_stage'] == candidate_leaf['ui_state']['lifecycle_stage']
|
||||
assert candidate_leaf['lifecycle_entries'] == candidate_leaf['ui_state']['lifecycle_entries']
|
||||
assert [entry['state'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [
|
||||
'available', 'current', 'unavailable', 'unavailable',
|
||||
]
|
||||
assert sibling_leaf['source_summary']['candidate_count'] == 0
|
||||
assert sibling_leaf['lifecycle_entries'] == sibling_leaf['ui_state']['lifecycle_entries']
|
||||
assert sibling_leaf['ui_state']['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
|
||||
@@ -422,6 +1048,14 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
|
||||
assert projection['summary']['total_files'] == 2
|
||||
assert projection['four_stage_nodes'][1] == {
|
||||
'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked',
|
||||
'summary': {
|
||||
'total': 1,
|
||||
'completed': 0,
|
||||
'needs_action': 1,
|
||||
'processing': 0,
|
||||
'failed': 1,
|
||||
'blocking_reason': {'code': 'intake_parse_failed'},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -738,6 +1372,7 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
|
||||
# 顶层工作项与会话状态组均消费同一后端 ui_state;前端无需读取 Gate 补按钮。
|
||||
assert solo['ui_state']['status'] == 'running'
|
||||
assert solo['ui_state']['stage'] == 'document_parsing'
|
||||
assert solo['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
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']
|
||||
@@ -863,8 +1498,11 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
|
||||
|
||||
assert item['work_item_type'] == 'order_task'
|
||||
assert item['current_gate'] is not None
|
||||
assert item['current_gate']['status'] == 'blocked'
|
||||
assert item['current_gate']['next_action_code'] == 'open_order_review'
|
||||
# 未确认 Case 的当前 Gate / 下一步必须来自 Review Case bundle,
|
||||
# 不再保留旧 OT 的 open_order_review 伪门禁。
|
||||
assert item['current_gate']['gate_code'] == 'order_review_build'
|
||||
assert item['current_gate']['next_action_code'] == 'mark_non_order'
|
||||
assert item['user_stage'] == 'order_review'
|
||||
assert item['source_summary']['candidate_count'] >= 1
|
||||
assert item['source_summary']['po_number'] == 'PO-OT-1'
|
||||
assert item['source_summary']['customer_name'] == 'ACME Co'
|
||||
@@ -874,6 +1512,49 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
|
||||
assert item['source_summary']['filename'] == document.filename
|
||||
|
||||
|
||||
def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shipping_user):
|
||||
"""候选已生成且 Case 未终态时,EML 叶子必须进入订单复核,不能回退为接收解析。"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.models import ShippingOrderCandidate
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
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, document = _seed_run_input(suffix='EML-CASE-LEAF')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'OCAND-EML-{uuid.uuid4().hex[:8]}', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='eml-case-leaf',
|
||||
order_extraction_run_id=run.id, is_current_version=True,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
assert unit.status == 'candidate_ready'
|
||||
assert case.status == 'unreviewed'
|
||||
db.session.commit()
|
||||
|
||||
result = _aggregate_eml_order_task_work_items([{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-EML-CASE',
|
||||
'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no,
|
||||
'status': 'processing', 'stage': 'candidate_creating', 'user_status': 'running',
|
||||
'user_stage': 'candidate_creating', 'user_group': 'processing',
|
||||
'last_activity_at': '', 'available_actions': [], 'facts': {'upload_state': 'not_created'},
|
||||
'source_summary': {'document_id': 0, 'filename': 'mail.eml'},
|
||||
}])
|
||||
leaf = result[0]['aggregate_children'][0]
|
||||
|
||||
assert result[0]['user_status'] == 'waiting_human'
|
||||
assert result[0]['user_stage'] == 'order_review'
|
||||
assert leaf['case_no'] == case.case_no
|
||||
assert leaf['user_status'] == 'idle'
|
||||
assert leaf['user_stage'] == 'order_review'
|
||||
assert leaf['current_gate']['gate_code'] == 'order_review_build'
|
||||
assert 'edit_draft' in leaf['available_actions']
|
||||
|
||||
|
||||
def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user):
|
||||
"""
|
||||
BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。
|
||||
|
||||
@@ -100,6 +100,56 @@ def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app):
|
||||
assert new_job.retry_of_job_id == 50
|
||||
|
||||
|
||||
def test_worker_revalidation_preserves_current_manual_validation_confirmation(app):
|
||||
"""手动保存校验后的同版本 STP 重验不得丢失确认身份并误判 needs_review。"""
|
||||
from app.services.shipping_notice import order_stp_auto_create_service as svc
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=3,
|
||||
case_no='SORC-STP-MANUAL-CONFIRMED',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=12,
|
||||
candidate_id=None,
|
||||
disposition=None,
|
||||
run_id=3,
|
||||
run=SimpleNamespace(run_no='SNER-TEST-MANUAL-CONFIRMED', id=3),
|
||||
owner_user_id=1,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=4,
|
||||
validation_result_json={
|
||||
'status': 'ready', 'can_build': True, 'can_auto_create': True,
|
||||
'validation_version': 4,
|
||||
},
|
||||
issue_summary_json=[],
|
||||
header_values_json={},
|
||||
lines_json=[{
|
||||
'line_key': 'machine-1',
|
||||
'values': {'part-id': {'value': 'D4-A08AR12000001', 'source': 'manual'}},
|
||||
}],
|
||||
),
|
||||
)
|
||||
new_job = SimpleNamespace(id=52, status='queued', retry_of_job_id=None)
|
||||
refreshed = {'status': 'ready', 'can_build': True, 'can_auto_create': True, 'issues': []}
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_is_xfa_case', return_value=False,
|
||||
), patch.object(svc, '_validation', return_value=refreshed), patch.object(
|
||||
svc, 'find_active_stp_job', return_value=None,
|
||||
), patch.object(svc, 'find_latest_stp_job', return_value=None), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-MANUAL-CONFIRMED:doc-12:v4',
|
||||
), patch.object(svc, 'enqueue', return_value=52), patch.object(
|
||||
svc, 'record_fulfillment_audit',
|
||||
), patch.object(svc, 'db') as mock_db:
|
||||
mock_db.session.get.return_value = new_job
|
||||
mock_db.session.flush = MagicMock()
|
||||
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False, refresh_validation=True)
|
||||
|
||||
# 关键断言:重新计算资格事实不等于撤销同一 Draft 版本已完成的人工保存校验。
|
||||
assert result['status'] == 'queued'
|
||||
assert case.current_draft.validation_result_json['validation_version'] == 4
|
||||
|
||||
|
||||
def test_retry_stp_auto_create_for_case_rejects_confirmed(app):
|
||||
"""已 confirmed Case 不得走 STP retry,须走确认后推进重试。"""
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
@@ -181,6 +181,80 @@ def test_execute_blank_native_pdf_returns_empty_suggestions():
|
||||
assert profile.definition_json['xfa_ocr_automark']['suggestion_count'] == 0
|
||||
|
||||
|
||||
def test_execute_automark_collects_widget_before_failing_unavailable_ocr():
|
||||
"""关键断言:OCR 是强制证据,但其失败不得阻止独立 Widget 采集和审计。"""
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.order_document_profile_xfa_automark_service import (
|
||||
execute_xfa_ocr_automark_job,
|
||||
)
|
||||
|
||||
profile = MagicMock(
|
||||
id=12,
|
||||
status='draft',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json=_definition_with_binding(),
|
||||
)
|
||||
native = {
|
||||
'pages': [{'page_no': 1, 'png_bytes': b'png'}],
|
||||
'page_count': 1,
|
||||
'preview_render_checksum': 'sha256:' + ('d' * 64),
|
||||
'renderer_version': 'hxops.native_pdf.v1',
|
||||
'render_mode': 'native_pdf',
|
||||
}
|
||||
widget = {
|
||||
'field_key': 'path-po',
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
|
||||
'confidence': 0.95,
|
||||
}
|
||||
merged = {
|
||||
'suggested_visual_bindings': [{
|
||||
**widget,
|
||||
'source': 'acroform_widget',
|
||||
'match_class': 'high',
|
||||
'suggestion_origin': 'widget_template',
|
||||
}],
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr',
|
||||
return_value=native,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._dataset_targets_flat',
|
||||
return_value=[{'field_key': 'path-po', 'value': 'PO-1'}],
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._widget_candidates_for_page',
|
||||
return_value=[widget],
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.recognize_preview_page',
|
||||
side_effect=ServiceUnavailableError('OCR unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE'),
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.merge_visual_binding_suggestions',
|
||||
return_value=merged,
|
||||
) as merge_mock, patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._audit_automark',
|
||||
) as audit_mock, patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.db',
|
||||
):
|
||||
with pytest.raises(Exception, match='XFA native PDF OCR is unavailable'):
|
||||
execute_xfa_ocr_automark_job({
|
||||
'profile_id': 12,
|
||||
'document_id': 77,
|
||||
'actor_id': 1,
|
||||
'job_id': 9,
|
||||
})
|
||||
|
||||
# Widget 已独立采集;OCR 缺失时不产生不完整的融合建议。
|
||||
assert merge_mock.call_count == 0
|
||||
assert any(
|
||||
call.kwargs.get('event_type') == 'xfa_ocr_failed'
|
||||
and call.kwargs.get('detail', {}).get('widget_candidate_count') == 1
|
||||
for call in audit_mock.call_args_list
|
||||
)
|
||||
|
||||
|
||||
def test_accept_high_requires_checksum_and_confirms(app):
|
||||
"""关键断言:high 接受走 confirm,且须携带 preview_render_checksum。"""
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
tests/test_worker_shipping.py
|
||||
|
||||
用途:验证 Shipping Worker 在 Windows spawn 模式下使用启动它的虚拟环境解释器。
|
||||
依赖:worker_shipping、pytest monkeypatch。
|
||||
逻辑:避免 multiprocessing 子进程回退到系统 Python,导致 OCR 等可选依赖从错误环境加载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
import worker_shipping
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice import queue_service
|
||||
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_configure_shipping_worker_process_executable_uses_current_interpreter(monkeypatch):
|
||||
"""子进程解释器必须与 Worker 主进程一致,防止环境混用。"""
|
||||
recorded: list[str] = []
|
||||
monkeypatch.setattr(worker_shipping.mp, 'set_executable', recorded.append)
|
||||
|
||||
worker_shipping.configure_shipping_worker_process_executable()
|
||||
|
||||
# 关键断言:Windows spawn 子进程不能回退到 PATH 上的系统 Python。
|
||||
assert recorded == [sys.executable]
|
||||
|
||||
|
||||
def test_assert_shipping_worker_capabilities_rejects_missing_xfa_ocr(monkeypatch):
|
||||
"""关键断言:shipping Worker 在领取 Job 前必须拒绝缺少 XFA OCR 的运行环境。"""
|
||||
monkeypatch.setattr(worker_shipping, 'is_ocr_engine_available', lambda: False)
|
||||
|
||||
with pytest.raises(RuntimeError, match='XFA OCR dependency is unavailable'):
|
||||
worker_shipping.assert_shipping_worker_capabilities()
|
||||
|
||||
|
||||
def test_assert_shipping_worker_capabilities_accepts_complete_xfa_ocr(monkeypatch):
|
||||
"""关键断言:完整 OCR 环境允许 shipping Worker 启动并消费队列。"""
|
||||
monkeypatch.setattr(worker_shipping, 'is_ocr_engine_available', lambda: True)
|
||||
|
||||
worker_shipping.assert_shipping_worker_capabilities()
|
||||
|
||||
|
||||
def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch):
|
||||
"""统一自动标注必须进入 shipping worker 的领取白名单,不能永久 queued。"""
|
||||
received: dict[str, object] = {}
|
||||
|
||||
def claim_next_job(**kwargs):
|
||||
received.update(kwargs)
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.jobs.queue.claim_next_job', claim_next_job)
|
||||
|
||||
queue_service.claim_next_shipping_notice_job()
|
||||
|
||||
assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types']
|
||||
Reference in new issue
Block a user