feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估

- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
This commit is contained in:
hugo committed 2026-08-02 19:26:35 +08:00
1 parent cef3d5b26a
commit 3a9fbac2fc
226 files changed
+25010 -2098

No files matched your search

+28 -4
View File
@@ -4,7 +4,8 @@ tests/conftest.py
用途:Flask testing app、库存配置种子与测试隔离夹具。
依赖:pytest、app.create_app、shipping inventory 模型。
逻辑:各测试用例共享;Windows 下将 basetemp 固定到 backend/.pytest_tmp,
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError。
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError;
pure_unit 标记跳过 Flask/DB 创建,供契约类纯单测加速。
"""
import shutil
@@ -13,6 +14,18 @@ from pathlib import Path
import pytest
def pytest_configure(config):
"""
注册自定义标记,避免 PytestUnknownMarkWarning。
pure_unit:契约类纯单测,跳过 Flask/DB 创建(见 _shipping_notice_stable_auto_config)。
"""
config.addinivalue_line(
'markers',
'pure_unit: skip Flask app/DB creation unless the test requests the app fixture',
)
@pytest.fixture(autouse=True)
def _capture_legacy_order_rows_for_tests(monkeypatch):
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
@@ -94,8 +107,15 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
def _shipping_notice_stable_auto_config(request, monkeypatch):
"""
发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。
标记 pure_unit 且未显式请求 app 的用例跳过 Flask/DB 创建,显著降低契约类单测耗时。
"""
if request.node.get_closest_marker("pure_unit") and "app" not in request.fixturenames:
return
app = request.getfixturevalue("app")
tmp_path = request.getfixturevalue("tmp_path")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
@@ -109,10 +129,14 @@ def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready",
lambda: None,
)
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
# STP 首期禁止货代 RPA 自动上传;单测默认与产品一致关闭。
# 货代自动上传默认 fail-closed;单测与产品默认一致关闭。
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
app.config["ENV_NAME"] = "dev"
@@ -375,7 +375,11 @@ def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
error_event = next(event for event in events if event.get("event") == "error")
# 关键断言:持久化返回的主键必须沿原 error 事件继续向 relay 传播。
assert error_event["chat_log_id"] == 42
assert error_event["message"]
assert error_event["message"] == "当前服务连接超时,请稍后重试。"
assert error_event["answer"] == error_event["message"]
serialized = json.dumps(error_event, ensure_ascii=False)
for technical_text in ("Dify", "API Key", "Base URL", "connect timed out", "[Error:"):
assert technical_text not in serialized
def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeypatch):
+21 -1
View File
@@ -17,7 +17,10 @@ SCHEMA = {'fields': [
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
{'field_id': 'qty', 'field_code': 'qty'},
{'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'aliases': ['Reservation ID']},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['Reservation ID', 'External reservation ID'],
},
{'field_id': 'allocation', 'field_code': 'allocation_id'},
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
]}
@@ -63,6 +66,23 @@ def test_email_supplement_html_grid_merges_by_po_and_mpn_without_overwriting_pdf
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_external_reservation_id_alias_merges_real_mail_header():
"""真实邮件的 External reservation ID 表头必须按 Schema 别名补到订单行。"""
supplement = parse_email_allocation_tables(
content_hash='e' * 64,
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>External reservation ID</th><th>Source Type</th><th>Allocated Qty</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>3000099143</td><td>DBS SIN</td><td>20</td></tr></table>'''],
schema_definition=SCHEMA,
)
merged = merge_email_supplements(
orders=[_order()], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
)
assert supplement['rows'][0]['reservation_id'] == '3000099143'
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == '3000099143'
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_po_fallback_requires_one_reservation():
"""缺 MPN 时只有唯一 Reservation 的 PO 可广播;多 Reservation 必须复核。"""
one = {'document_id': 44, 'rows': [{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}}]}
@@ -22,13 +22,14 @@ def _field(
code: str,
aliases: list[str],
*,
scope: str = 'line',
value_type: str = 'string',
enabled: bool = True,
collection_mode: str = 'llm_extraction',
) -> dict:
"""构造一个启用的最小 Schema 字段配置。"""
return {
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
'field_id': f'id-{scope}-{code}', 'field_code': code, 'scope': scope,
'value_type': value_type, 'enabled': enabled, 'display_name': code,
'aliases': aliases, 'normalizer_key': 'trim',
'validator_keys': ['positive_decimal'] if code == 'qty' else [],
@@ -70,12 +71,36 @@ def test_table_contract_allows_case_distinct_aliases_and_matches_exact_case():
assert 'CUSTOMER PN' not in contract.header_to_field
def test_table_contract_rejects_forbidden_reservation_header():
"""管理员不得把 Allocation/Internal/UUID 类表头配置成 Reservation ID。"""
with pytest.raises(ValidationError) as caught:
compile_table_header_contract(_definition(_field('reservation_id', ['Allocation ID'])))
def test_table_contract_allows_explicit_reservation_alias():
"""显式 Schema 别名是表格字段映射的唯一来源,不受全局英文黑名单否定。"""
contract = compile_table_header_contract(_definition(_field('reservation_id', ['Allocation ID'])))
assert caught.value.details['forbidden_reservation_headers'] == ['Allocation ID']
assert contract.header_to_field['Allocation ID'] == 'reservation_id'
def test_table_contract_allows_same_alias_across_header_and_line_scopes():
"""订单头和明细字段可同名;表格契约只消费 line scope 的列定义。"""
contract = compile_table_header_contract(_definition(
_field('reservation_id', ['Reservation ID'], scope='header'),
_field('reservation_id', ['Reservation ID'], scope='line'),
))
assert contract.header_to_field['Reservation ID'] == 'reservation_id'
assert contract.fields_by_code['reservation_id']['scope'] == 'line'
def test_table_contract_rejects_duplicate_alias_within_line_scope():
"""同一明细列不能映射到两个不同业务字段,错误需标明冲突双方。"""
with pytest.raises(ValidationError) as caught:
compile_table_header_contract(_definition(
_field('part_number', ['Part Number']),
_field('customer_part_number', ['Part Number']),
))
collision = caught.value.details['table_header_collisions'][0]
assert collision['field_code'] == 'customer_part_number'
assert collision['conflicts_with'] == 'part_number'
assert collision['scope'] == collision['conflicts_with_scope'] == 'line'
def test_table_contract_includes_internal_line_number():
+76 -2
View File
@@ -1,9 +1,9 @@
"""
backend/tests/test_rpa_worker_heartbeat.py
用途:货代库存 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配与 fail-fast 断言。
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。
"""
from __future__ import annotations
@@ -15,10 +15,14 @@ import pytest
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa_worker_heartbeat import (
FREIGHT_UPLOAD_CAPABILITY,
INVENTORY_EXPORT_CAPABILITY,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE,
assert_freight_upload_rpa_ready,
assert_inventory_rpa_worker_ready,
check_freight_upload_rpa_ready,
check_inventory_rpa_worker_ready,
record_rpa_worker_heartbeat,
resolve_backend_rpa_environment,
@@ -371,3 +375,73 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path)
with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data"
def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
"""配置货代上传 trigger/queue 与心跳策略,供上传就绪单测复用。"""
upload_trigger = tmp_path / "upload_triggers"
upload_queue = tmp_path / "upload_queue"
upload_trigger.mkdir()
upload_queue.mkdir()
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
return upload_trigger
def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app, tmp_path):
"""仅 inventory_export 能力时货代上传不得 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
assert result.ready is False
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
assert result.ready is True
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
_enable_freight_upload_checks(app, tmp_path)
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
app.config.pop("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", None)
reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_freight_upload_rpa_ready()
assert exc_info.value.message == RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
reasons = (exc_info.value.details or {}).get("reasons", [])
assert "credential_key_missing" in reasons
@@ -1,9 +1,9 @@
"""
tests/test_shipping_auto_build_workflow_gate.py
用途:验收自动建单五门禁——失败仅 Review Case、禁止 STP 自动建单;can_build 仍供人工确认。
用途:验收自动建单门禁——失败仅 Review Case、禁止 STP 自动建单;can_build 仍供人工确认。
依赖:order_build_eligibility_service、types.SimpleNamespace。
逻辑:构造五门全绿 / 单门失败用例;断言 can_auto_create 与 failed_gates。
逻辑:构造 Candidate Qualification 全绿 / 单门失败用例;断言 can_auto_create 与 failed_gates。
"""
from __future__ import annotations
@@ -17,23 +17,43 @@ from app.services.shipping_notice.order_build_eligibility_service import (
)
def test_auto_build_gates_pass_when_all_five_green():
"""五门全绿时 can_auto_create=True。"""
candidate = SimpleNamespace(
def _candidate(**overrides):
"""构造默认可通过资格的 Candidate 替身。"""
base = dict(
acceptance_mode='automatic',
candidate_status='accepted',
extraction_source='profile',
classification_confidence=0.96,
evidence_json=[{'field': 'po'}],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
missing_fields_json=[],
field_confidence_json={},
consumed_task_id=None,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
validation_status='ready',
)
base.update(overrides)
return SimpleNamespace(**base)
def test_auto_build_gates_pass_when_qualification_green(monkeypatch):
"""统一资格全绿时 can_auto_create=True。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
unit = SimpleNamespace(route_decision_json={'auto_create_approved': True})
run = SimpleNamespace(auto_freeze_policy_json={'enabled': True})
result = assess_auto_build_gates(
fields_complete=True,
candidate=candidate,
unit=unit,
run=run,
candidate=_candidate(),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=True,
)
assert result['can_auto_create'] is True
assert result['failed_gates'] == []
@@ -41,53 +61,82 @@ def test_auto_build_gates_pass_when_all_five_green():
assert all(result['gates'].values())
def test_auto_build_gates_fail_without_approved_template():
"""模板未批准 → Review Case,禁止自动建单。"""
def test_auto_build_gates_allow_without_approved_template(monkeypatch):
"""模板未批准不再单独阻断自动建单(合格 Candidate 仍可放行)。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=SimpleNamespace(
acceptance_mode='manual',
candidate_status='provisional',
evidence_json=[{'field': 'po'}],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
),
candidate=_candidate(acceptance_mode='manual', candidate_status='provisional'),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=True,
)
assert result['can_auto_create'] is False
assert 'approved_template' in result['failed_gates']
assert result['can_auto_create'] is True
assert 'approved_template' not in result['failed_gates']
def test_auto_build_gates_fail_on_conflict_or_missing_quality(app):
"""冲突或质量门禁未过 → 不能自动建单。"""
def test_auto_build_gates_fail_on_conflict_or_disabled_switch(monkeypatch):
"""冲突或自动建单开关关闭 → 不能自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=SimpleNamespace(
acceptance_mode='automatic',
candidate_status='accepted',
evidence_json=[{'field': 'po'}],
conflicts_json=[{'code': 'qty_conflict'}],
duplicate_status='none',
duplicate_resolution=None,
),
candidate=_candidate(conflicts_json=[{'code': 'qty_conflict'}]),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False, 'emergency_stop': False}),
customer_resolved=True,
# schema 开关由参数控制
)
# 通过 monkeypatch 关闭 schema 开关
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': False},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=_candidate(conflicts_json=[{'code': 'qty_conflict'}]),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False, 'emergency_stop': False}),
customer_resolved=True,
)
assert result['can_auto_create'] is False
assert 'no_conflict_or_duplicate' in result['failed_gates']
assert 'quality_gate_passed' in result['failed_gates']
assert 'field_conflicts_resolved' in result['failed_gates']
assert 'auto_create_enabled' in result['failed_gates']
def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch):
"""
五门失败不阻断人工确认 can_build(库存/Reservation 齐备时)。
资格失败不阻断人工确认 can_build(库存/Reservation 齐备时)。
"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': False},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'DBS_DUB'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.classify_inventory_source_codes',
lambda codes: {
'available': list(codes or []),
'unavailable': [],
'unavailable_reasons': {},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.evaluate_inventory_source_rules_for_field_values',
lambda **kwargs: SimpleNamespace(
@@ -96,6 +145,7 @@ def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch
can_build=True,
block_reason=None,
matched_rule_ids=[1],
matched_rules=(),
evidence={},
),
)
@@ -109,19 +159,46 @@ def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch
header_by_code={},
lines=[{'reservation_id': '2000484577', 'part_number': 'PN-1', 'qty': '2'}],
line_metas=[{'line_key': 'L1'}],
candidate=SimpleNamespace(
candidate=_candidate(
acceptance_mode='manual',
candidate_status='provisional',
evidence_json=[],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
customer_resolved=True,
)
# 关键断言:人工可建单,但自动建单被五门阻断。
# 关键断言:人工可建单,但自动建单被阻断;用户侧仅一条资格阻断 Finding。
assert result['can_build'] is True
assert result['can_auto_create'] is False
assert 'approved_template' in result['failed_gates']
assert any(item.get('severity') == 'auto_create_blocking' for item in result['issues'])
assert 'auto_create_enabled' in result['failed_gates'] or 'evidence_complete' in result['failed_gates']
auto_issues = [item for item in result['issues'] if item.get('severity') == 'auto_create_blocking']
assert len(auto_issues) == 1
assert auto_issues[0].get('code') == 'candidate_qualification_blocked'
assert not any(str(item.get('code') or '').startswith('auto_build_gate_') for item in result['issues'])
def test_auto_build_customer_failure_owns_customer_resolution(monkeypatch):
"""客户未确认归属 customer_resolution,不平行投影多个用户阻断。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=_candidate(
structured_result_json={'customer': {'resolution_status': 'ambiguous'}},
),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=None,
)
assert result['can_auto_create'] is False
assert result['user_blocking_finding']['owning_gate_code'] == 'customer_resolution'
assert result['user_blocking_finding']['reason_code'] == 'customer_ambiguous'
blocking = [f for f in result['findings'] if f.get('severity') == 'blocking']
assert len(blocking) == 1
@@ -0,0 +1,36 @@
"""
tests/test_shipping_auto_upload_config_align.py
用途:锁定 AUTO_UPLOAD 配置默认与服务层回退一致(生产安全 fail-closed)。
依赖:fulfillment_workflow、pytest、Flask app。
逻辑:断言键缺失时回退 False;显式 true/false 时尊重配置。
"""
from __future__ import annotations
def test_auto_upload_defaults_false_when_config_key_missing(app) -> None:
"""配置键缺失时与 settings 默认一致为 False,禁止缺省即自动上传。"""
with app.app_context():
from app.services.shipping_notice.fulfillment_workflow import is_auto_upload_enabled
app.config.pop('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', None)
assert is_auto_upload_enabled() is False
def test_auto_upload_respects_explicit_false(app) -> None:
"""显式关闭时必须为 False。"""
with app.app_context():
from app.services.shipping_notice.fulfillment_workflow import is_auto_upload_enabled
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = False
assert is_auto_upload_enabled() is False
def test_auto_upload_respects_explicit_true(app) -> None:
"""显式开启时必须为 True。"""
with app.app_context():
from app.services.shipping_notice.fulfillment_workflow import is_auto_upload_enabled
app.config['SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED'] = True
assert is_auto_upload_enabled() is True
@@ -0,0 +1,286 @@
"""
tests/test_shipping_candidate_qualification.py
用途:验收 Candidate 统一自动建单资格——三种解析来源、模板未批准可放行、LLM 可放行。
依赖:candidate_qualification_service、types.SimpleNamespace。
逻辑:构造合格/失败候选;断言 status、原因码与 parser_trace 不含硬性模板门禁。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.candidate_qualification_service import (
evaluate_candidate_qualification,
)
from app.services.shipping_notice.order_build_eligibility_service import assess_auto_build_gates
def _eligible_candidate(**overrides):
"""构造默认可通过资格评估的 Candidate 替身。"""
base = dict(
candidate_status='accepted',
acceptance_mode='automatic',
extraction_source='profile',
classification_confidence=0.96,
confidence=0.96,
missing_fields_json=[],
field_confidence_json={},
evidence_json=[{'field': 'po_number'}],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
consumed_task_id=None,
structured_result_json={
'customer': {'resolution_status': 'user_confirmed'},
},
validation_status='ready',
)
base.update(overrides)
return SimpleNamespace(**base)
def test_profile_unapproved_but_qualified_candidate_is_eligible(monkeypatch):
"""模板未批准但 Candidate 合格 → eligible,允许自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(extraction_source='profile')
unit = SimpleNamespace(route_decision_json={
'route_type': 'profile_deterministic',
'auto_create_approved': False,
'selected_profile_id': 12,
'selected_profile_code': 'DEMO',
})
result = evaluate_candidate_qualification(
candidate=candidate,
unit=unit,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['status'] == 'eligible'
assert result['can_auto_create'] is True
assert result['parser_trace']['profile_auto_create_approved'] is False
assert 'profile_not_auto_freeze_approved' not in result['blocking_reason_codes']
def test_llm_candidate_can_pass_unified_gates(monkeypatch):
"""LLM Candidate 具备分类/字段置信度与证据时可通过统一门禁 → eligible。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True, 'minimum_confidence': 0.85},
)
candidate = _eligible_candidate(
extraction_source='llm',
classification_confidence=0.96,
field_confidence_json={
'po_number': {
'confidence': 0.95,
'minimum_confidence': 0.85,
'auto_create_key_field': True,
},
},
evidence_json=[{'field': 'po_number'}],
)
unit = SimpleNamespace(route_decision_json={
'route_type': 'llm_assisted_review',
'auto_create_approved': False,
})
result = evaluate_candidate_qualification(
candidate=candidate,
unit=unit,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['status'] == 'eligible'
assert result['parser_trace']['parser_source'] == 'llm_assisted'
assert result['confidence_policy']['source'] == 'schema_auto_creation_policy'
assert 'llm_path_cannot_auto_freeze' not in result['blocking_reason_codes']
def test_missing_classification_confidence_blocks(monkeypatch):
"""分类置信度缺失时 fail-closed(无人工确认)。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
classification_confidence=None,
confidence=None,
)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'classification_confidence' in result['failed_gates']
def test_llm_missing_field_confidence_blocks(monkeypatch):
"""LLM 路径缺少字段级置信度时不得自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
extraction_source='llm',
field_confidence_json={},
)
unit = SimpleNamespace(route_decision_json={'route_type': 'llm_assisted'})
result = evaluate_candidate_qualification(
candidate=candidate,
unit=unit,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'key_fields_minimum_confidence' in result['failed_gates']
def test_deterministic_without_confidence_requires_validation_ready(monkeypatch):
"""确定性解析器无字段置信度时,validation 未就绪不得隐式放行。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
extraction_source='profile',
field_confidence_json={},
validation_status='pending',
missing_fields_json=['po_number'],
)
result = evaluate_candidate_qualification(
candidate=candidate,
unit=SimpleNamespace(route_decision_json={'route_type': 'profile_deterministic'}),
fields_complete=None,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'key_fields_minimum_confidence' in result['failed_gates']
assert result['confidence_policy']['source'] in {
'schema_auto_creation_policy',
'key_field_minimum_confidence',
'default_fallback_0_85',
}
def test_generic_candidate_failure_has_concrete_reason_codes(monkeypatch):
"""通用解析失败 Candidate 必须给出具体原因码。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
extraction_source='generic',
evidence_json=[],
conflicts_json=[{'code': 'qty_conflict'}],
classification_confidence=0.2,
duplicate_status='unchecked',
)
result = evaluate_candidate_qualification(
candidate=candidate,
unit=SimpleNamespace(route_decision_json={'route_type': 'generic_deterministic'}),
fields_complete=False,
customer_resolved=False,
schema_auto_create_enabled=True,
)
assert result['status'] in {'blocked', 'review_required'}
assert result['can_auto_create'] is False
assert 'evidence_missing' in result['blocking_reason_codes']
assert 'field_conflict' in result['blocking_reason_codes']
assert 'required_field_missing' in result['blocking_reason_codes']
assert 'duplicate_unresolved' in result['blocking_reason_codes'] or 'duplicate_resolved' in result['failed_gates']
assert any(code.startswith('customer_') for code in result['blocking_reason_codes'])
def test_duplicate_unchecked_blocks_auto_create(monkeypatch):
"""重复检测未完成(unchecked)不得放行自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(duplicate_status='unchecked', duplicate_resolution=None)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'duplicate_resolved' in result['failed_gates']
def test_duplicate_create_revision_and_force_create_count_as_resolved(monkeypatch):
"""复核裁决 create_revision / force_create 须通过 duplicate_resolved 门禁。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
for action in ('create_revision', 'force_create'):
candidate = _eligible_candidate(
duplicate_status='possible_duplicate',
duplicate_resolution=action,
)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['gates']['duplicate_resolved'] is True, action
assert 'duplicate_resolved' not in result['failed_gates'], action
def test_evidence_without_field_binding_blocks(monkeypatch):
"""证据条目未绑定字段时不得仅凭非空 list 放行。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(evidence_json=[{'page': 1, 'note': 'unrelated'}])
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['can_auto_create'] is False
assert 'evidence_complete' in result['failed_gates']
def test_assess_auto_build_gates_no_longer_requires_approved_template(monkeypatch):
"""建单资格服务不再把 approved_template 作为必要门禁。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
result = assess_auto_build_gates(
fields_complete=True,
candidate=_eligible_candidate(),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True, 'emergency_stop': False}),
customer_resolved=True,
)
# 关键断言:模板未批准仍可自动建单;门禁键不含 approved_template。
assert 'approved_template' not in result['gates']
assert result['can_auto_create'] is True
assert result['qualification']['status'] == 'eligible'
@@ -0,0 +1,98 @@
"""
tests/test_shipping_chat_workbench_audit.py
用途:锁定双工作台阶段 5–6 对话侧 / 资格 / 节点审计字典与查询分组。
依赖:progress_audit_contract、audit_query_service、pytest。
逻辑:断言 chat_* / qualification / workflow_node 事件冻结;分组筛选映射正确。
"""
from __future__ import annotations
from app.services.shipping_notice.audit_query_service import _apply_filters
from app.services.shipping_notice.progress_audit_contract import (
CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES,
CHAT_WORKBENCH_AUDIT_EVENT_TYPES,
PROCESS_GATE_AUDIT_EVENT_TYPES,
WORKFLOW_NODE_AUDIT_EVENT_TYPES,
)
from app.services.shipping_notice.process_gate_recovery_service import (
_chat_process_gate_event_type,
)
def test_chat_workbench_audit_events_are_frozen() -> None:
"""对话侧恢复与轻量动作事件必须冻结,禁止前端私造。"""
required = {
'chat_candidate_viewed',
'chat_task_viewed',
'chat_task_refocused',
'chat_customer_confirmed',
'chat_task_retried',
'chat_process_gate_taken_over',
'chat_process_gate_retried',
'chat_process_gate_skipped',
}
assert required.issubset(CHAT_WORKBENCH_AUDIT_EVENT_TYPES)
def test_qualification_and_workflow_node_audit_events_are_frozen() -> None:
"""资格评估与节点生命周期事件字典须覆盖阶段 6 清单关键项。"""
assert 'candidate_qualification_evaluated' in CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES
assert 'review_qualification_evaluated' in CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES
for code in (
'task_created',
'workflow_node_started',
'workflow_node_succeeded',
'workflow_node_failed',
'workflow_node_retried',
'workflow_node_taken_over',
'upload_rpa_triggered',
):
assert code in WORKFLOW_NODE_AUDIT_EVENT_TYPES
def test_chat_process_gate_event_mapping() -> None:
"""retry → retried;人工动作 → taken_over;skip → skipped。"""
assert _chat_process_gate_event_type(
action_code='retry_inventory_matching',
trigger_type='user_retry',
) == 'chat_process_gate_retried'
assert _chat_process_gate_event_type(
action_code='open_order_review',
trigger_type='user_manual',
) == 'chat_process_gate_taken_over'
assert _chat_process_gate_event_type(
action_code='skip_gate_demo',
trigger_type='user_manual',
) == 'chat_process_gate_skipped'
def test_audit_event_type_group_filters_use_frozen_dictionaries(app) -> None:
"""
event_type_group 须映射到冻结字典(编译为 IN 子句)。
断言:各分组产生的 SQL 文本包含对应字典中至少一个已知事件码。
"""
from app.models import ShippingAuditEvent
with app.app_context():
base = ShippingAuditEvent.query
cases = (
('chat_workbench', 'chat_process_gate_retried'),
('process_gate', 'process_gate_recovery_requested'),
('candidate_qualification', 'candidate_qualification_evaluated'),
('workflow_node', 'upload_rpa_triggered'),
('review_workbench', 'review_confirmed'),
)
for group, marker in cases:
filtered = _apply_filters(base, filters={'event_type_group': group})
sql = str(filtered.statement.compile(compile_kwargs={'literal_binds': True}))
# 关键断言:分组筛选把冻结事件码编入 WHERE IN。
assert marker in sql
assert 'event_type' in sql.lower()
def test_process_gate_dictionary_still_covers_recovery() -> None:
"""Process Gate 原事件字典不得因 chat_* 语义事件而缺恢复码。"""
assert 'process_gate_recovery_requested' in PROCESS_GATE_AUDIT_EVENT_TYPES
assert 'process_gate_technical_retry' in PROCESS_GATE_AUDIT_EVENT_TYPES
@@ -170,12 +170,15 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
db.session.commit()
task_no = task.task_no
customer_id = customer.id
short_code = customer.short_code
username = user.username
headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'}
options_response = client.get('/api/workspace/shipping-customers?q=GAA', headers=headers)
options_response = client.get(f'/api/workspace/shipping-customers?q={short_code}', headers=headers)
assert options_response.status_code == 200
assert options_response.get_json()[0]['short_code'] == 'GAA'
options_payload = options_response.get_json()
assert options_payload['success'] is True
assert options_payload['data'][0]['short_code'] == short_code
confirm_response = client.post(
f'/api/workspace/shipping-tasks/{task_no}/confirm-customer',
@@ -183,10 +186,12 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
headers=headers,
)
assert confirm_response.status_code == 200
payload = confirm_response.get_json()
envelope = confirm_response.get_json()
assert envelope['success'] is True
payload = envelope['data']
assert payload['customer_resolution_status'] == 'confirmed'
assert payload['customer_id'] == customer_id
assert payload['business_no'].startswith('GAA')
assert payload['business_no'].startswith(short_code)
other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'}
forbidden_response = client.post(
@@ -0,0 +1,60 @@
"""
tests/test_shipping_document_layout_cell_coordinate_status.py
用途:锁定阶段 3 Cell 坐标来源分级与高风险字段门禁。
依赖:cell_coordinate_status。
逻辑:pure_unit;覆盖 native verified / OCR candidate / HTML unavailable / 高风险缺 token。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.document_layout.cell_coordinate_status import (
HIGH_RISK_FIELD_CODES,
classify_cell_coordinate_status,
)
pytestmark = pytest.mark.pure_unit
def test_native_unique_glyph_is_verified():
"""原生 glyph 唯一对齐且置信度满值 → verified。"""
grade = classify_cell_coordinate_status(
source='native_text', has_bbox=True, has_token_ids=True, confidence=1.0,
field_code='qty',
)
assert grade['highlight_quality'] == 'verified'
assert grade['highlight_source'] == 'native_glyph'
def test_ocr_and_opencv_remain_candidate():
"""OCR / OpenCV 三重校验通过后仍不得自动升 verified。"""
ocr = classify_cell_coordinate_status(
source='ocr', has_bbox=True, has_token_ids=True, confidence=0.95,
)
opencv = classify_cell_coordinate_status(
source='opencv', has_bbox=True, has_token_ids=True, confidence=1.0,
)
assert ocr['highlight_quality'] == 'candidate'
assert opencv['highlight_quality'] == 'candidate'
def test_html_only_is_unavailable():
"""仅 HTML 行列不得伪造 PDF bbox。"""
grade = classify_cell_coordinate_status(
source='html', has_bbox=False, has_token_ids=False,
)
assert grade['highlight_quality'] == 'unavailable'
assert 'html_only_no_pdf_bbox' in grade['coordinate_issue_codes']
def test_high_risk_field_without_tokens_unavailable():
"""高风险字段缺 token 时禁止 candidate 高亮。"""
assert 'part_number' in HIGH_RISK_FIELD_CODES
grade = classify_cell_coordinate_status(
source='opencv', has_bbox=True, has_token_ids=False, confidence=1.0,
field_code='part_number',
)
assert grade['highlight_quality'] == 'unavailable'
assert 'cell_token_unbound' in grade['coordinate_issue_codes']
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_document_layout_ocr_pdf.py
用途:验证 RapidOCR 多边形坐标适配和扫描表三重门禁。
用途:验证 RapidOCR 多边形坐标适配和扫描表三重门禁(阶段 2)。
依赖:ocr_pdf、OpenCV 几何结果、HTML 网格。
逻辑:覆盖坐标缩放、低置信过滤、引擎不可用与完整 cell 文本验收。
逻辑:覆盖坐标缩放、低置信过滤、引擎不可用、完整 cell 文本验收与 candidate 状态。
"""
from __future__ import annotations
@@ -18,6 +18,7 @@ from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrLine,
build_ocr_table_evidence,
extract_ocr_lines,
page_bbox_to_normalized,
)
from app.services.shipping_notice.document_layout.opencv_table import (
OpenCVCellGeometry,
@@ -25,6 +26,14 @@ from app.services.shipping_notice.document_layout.opencv_table import (
)
def _ocr_line(text: str, bbox: LayoutBBox, confidence: float, *, index: int) -> OcrLine:
"""构造带行 ID 与渲染尺寸的 OCR 行。"""
return OcrLine(
text=text, bbox=bbox, confidence=confidence,
line_id=f'ocr-line-{index}', polygon=[], image_width=200, image_height=100,
)
def test_rapidocr_polygon_is_scaled_to_pdf_page_and_filters_low_confidence():
"""OCR 像素框必须按渲染图与 PDF 页面比例转换,低置信结果不得保留。"""
image = np.zeros((200, 400, 3), dtype=np.uint8)
@@ -39,6 +48,20 @@ def test_rapidocr_polygon_is_scaled_to_pdf_page_and_filters_low_confidence():
assert len(lines) == 1
assert lines[0].text == 'Part'
assert lines[0].bbox.model_dump() == {'x0': 20.0, 'y0': 10.0, 'x1': 60.0, 'y1': 30.0}
assert lines[0].line_id == 'ocr-line-0'
assert lines[0].polygon == [[40.0, 20.0], [120.0, 20.0], [120.0, 60.0], [40.0, 60.0]]
assert lines[0].image_width == 400
assert lines[0].image_height == 200
def test_page_bbox_to_normalized_roundtrip_within_tolerance():
"""页面坐标归一化误差必须落在页面短边 1% 内(阶段 2 换算验收)。"""
bbox = LayoutBBox(x0=20, y0=10, x1=60, y1=30)
normalized = page_bbox_to_normalized(bbox, page_width=200, page_height=100)
assert normalized.model_dump() == {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.3}
short_side = 100
restored_x0 = normalized.x0 * 200
assert abs(restored_x0 - bbox.x0) <= short_side * 0.01
def test_ocr_table_requires_geometry_and_all_cell_text():
@@ -64,8 +87,8 @@ def test_ocr_table_requires_geometry_and_all_cell_text():
],
)
lines = [
OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=50, y1=30), confidence=.99),
OcrLine(text='Qty', bbox=LayoutBBox(x0=120, y0=10, x1=150, y1=30), confidence=.98),
_ocr_line('Part', LayoutBBox(x0=10, y0=10, x1=50, y1=30), .99, index=0),
_ocr_line('Qty', LayoutBBox(x0=120, y0=10, x1=150, y1=30), .98, index=1),
]
with patch(
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', return_value=lines,
@@ -80,6 +103,8 @@ def test_ocr_table_requires_geometry_and_all_cell_text():
assert result.ready is True
assert [item.line_indices for item in result.cells] == [[0], [1]]
assert all(item.status == 'candidate' for item in result.cells)
assert all(item.normalized_bbox is not None for item in result.cells)
def test_ocr_engine_failure_is_safe_unsupported_candidate():
@@ -144,11 +144,71 @@ def test_layout_mapping_preserves_real_cell_and_token_evidence_and_zero_qty():
assert part['cell_id'] == 'v-part'
assert part['token_ids'] == ['t-v-part']
assert part['evidence_ref'] == 'layout:21:p1:table-main:v-part'
# 阶段 1:原生 cell 坐标必须进入字段候选,供复核高亮投影,不得丢失。
assert part['value_bbox'] == {'x0': 0.0, 'y0': 60.0, 'x1': 100.0, 'y1': 90.0}
assert part['cell_bbox'] == part['value_bbox']
assert part['bbox_text'] == 'A-1'
assert part['quote'] == 'A-1'
assert part['quote_source'] == 'bbox_tokens'
assert part['highlight_quality'] == 'verified'
assert part['source'] == 'native_glyph'
assert part['page_no'] == 1
deleted = next(row for row in mapped['rows'] if row['row_index'] == 3)
assert deleted['role'] == 'deleted'
assert deleted['fields'] == []
def test_layout_mapping_value_bbox_uses_token_union_not_full_cell():
"""value_bbox 必须是 token 并集;整格 cell_bbox 可更大,避免框住空白单元格。"""
layout = _layout()
cell = next(
cell
for row in layout.pages[0].tables[0].rows
for cell in row.cells
if cell.cell_id == 'v-part'
)
token = next(item for item in layout.pages[0].tokens if item.token_id == 't-v-part')
# 模拟 OpenCV 大格 + 紧致 glyph:cell 宽于文字
cell.bbox = LayoutBBox(x0=0, y0=60, x1=100, y1=90)
cell.normalized_bbox = LayoutBBox(x0=0, y0=0.5, x1=1 / 3, y1=0.75)
token.bbox = LayoutBBox(x0=10, y0=65, x1=40, y1=85)
token.normalized_bbox = LayoutBBox(x0=0.03, y0=0.54, x1=0.13, y1=0.71)
token.text = 'A-1'
mapped = map_layout_document_to_schema(layout, contract=_contract())[0]
data = next(row for row in mapped['rows'] if row['row_index'] == 2)
part = next(field for field in data['fields'] if field['field_id'] == 'part-id')
# 关键断言:高亮用紧致 token 并集,cell_bbox 保留整格
assert part['value_bbox'] == {'x0': 10.0, 'y0': 65.0, 'x1': 40.0, 'y1': 85.0}
assert part['cell_bbox'] == {'x0': 0.0, 'y0': 60.0, 'x1': 100.0, 'y1': 90.0}
assert part['quote_source'] == 'bbox_tokens'
assert part['bbox_text'] == 'A-1'
def test_layout_mapping_null_value_bbox_without_tokens():
"""无 token 时 value_bbox/normalized_bbox 必须为 null,仅保留 cell_bbox 供诊断。"""
layout = _layout()
cell = next(
item
for row in layout.pages[0].tables[0].rows
for item in row.cells
if item.cell_id == 'v-part'
)
# 须先改 source 再清空 token,否则 native_text 校验会拒绝空 token_ids
cell.source = 'html'
cell.token_ids = []
mapped = map_layout_document_to_schema(layout, contract=_contract())[0]
data = next(row for row in mapped['rows'] if row['row_index'] == 2)
part = next(field for field in data['fields'] if field['field_id'] == 'part-id')
# 关键断言:禁止把整格几何冒充为字段值级 value_bbox
assert part['value_bbox'] is None
assert part['normalized_bbox'] is None
assert part['has_value_coordinate'] is False
assert part['cell_bbox'] == {'x0': 0.0, 'y0': 60.0, 'x1': 100.0, 'y1': 90.0}
assert part['quote_source'] == 'layout_cell_text'
assert part['highlight_quality'] == 'unavailable'
def test_layout_mapping_blocks_duplicate_target_columns():
"""同一字段命中两列时两列均 ambiguous,禁止选择左/右列。"""
mapped = map_layout_document_to_schema(_layout(duplicate_part=True), contract=_contract())[0]
@@ -60,7 +60,9 @@ def test_repeated_text_is_rejected_instead_of_selected_by_position():
assert result.complete is False
assert result.cells == []
assert result.issues == ['text_cell_alignment_text_not_unique']
assert 'text_cell_alignment_text_not_unique' in result.issues
# 关键断言:对外稳定 issue 与高亮契约对齐,禁止第 N 个重复值绑定。
assert 'duplicate_text_coordinate_ambiguous' in result.issues
def test_empty_and_missing_cells_remain_unmatched():
@@ -87,7 +89,8 @@ def test_overlapping_unique_substrings_do_not_share_glyphs():
assert result.complete is False
assert result.matched_cell_count == 1
assert result.issues == ['text_cell_alignment_glyph_overlap']
assert 'text_cell_alignment_glyph_overlap' in result.issues
assert 'coordinate_shared_token_conflict' in result.issues
def test_invalid_page_glyph_is_dropped_without_adjusting_coordinates():
@@ -151,3 +154,34 @@ def test_unique_string_split_across_visual_rows_is_rejected():
assert result.complete is False
assert result.cells == []
assert result.issues == ['text_cell_alignment_geometry_discontinuous']
def test_unique_match_is_verified_and_empty_cells_do_not_block_completeness():
"""唯一匹配通过门禁后为 verified;空 cell 不参与定位也不阻断 complete。"""
result = _align(
'<table><tr><td>A1</td><td></td><td>20</td></tr></table>',
'A120',
)
assert result.complete is True
assert result.expected_cell_count == 2
assert result.matched_cell_count == 2
assert all(cell.status == 'verified' for cell in result.cells)
assert 'text_cell_alignment_empty_cell' in result.issues
def test_value_box_outside_table_is_rejected():
"""值框并集超出表格 bbox 时不得产出坐标。"""
characters = [
{'text': 'A', 'bbox': {'x0': 10, 'y0': 20, 'x1': 14, 'y1': 30}},
{'text': '1', 'bbox': {'x0': 150, 'y0': 20, 'x1': 154, 'y1': 30}},
]
result = align_html_cells_from_positioned_text(
parse_html_grid('<table><tr><td>A1</td></tr></table>', table_id='outside'),
characters=characters,
table_bbox=LayoutBBox(x0=0, y0=0, x1=100, y1=100),
page_width=200,
page_height=100,
)
# '1' 中心在表外被过滤后文本不完整;或并集越界——均不得高亮。
assert result.cells == []
assert result.complete is False
@@ -0,0 +1,543 @@
"""
tests/test_shipping_error_explainability_contract.py
用途:锁定错误可解释性契约——分层原因码、别名归一、统一投影、审计覆盖矩阵与库存源三类语义。
依赖:error_explainability_contract、order_build_eligibility_service、process_gate_contract、
tool_common、process_gate_projection。
逻辑:模块默认 pure_unit(不拉 Flask/DB);仅库存源集成断言显式请求 app;
契约自检 + 别名归一 + request_id 边界 + 审计覆盖矩阵 100% 源码接线举证。
"""
from __future__ import annotations
from pathlib import Path
import pytest
from app.services.shipping_notice.attachment_integrity import (
attachment_incomplete_error_details,
)
from app.services.shipping_notice.error_explainability_contract import (
ATTACHMENT_REASON_CODES_EMITTED,
AUDIT_COVERAGE_MATRIX,
DOCUMENT_PARSE_REASON_CODES_EMITTED,
ERROR_EXPLAINABILITY_CONTRACT_VERSION,
EXCEL_UPLOAD_REASON_CODES_EMITTED,
INVENTORY_MATCH_REASON_CODES_EMITTED,
INVENTORY_PREP_REASON_CODES_EMITTED,
INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED,
INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED,
ORDER_BUILD_REASON_CODES_EMITTED,
ORDER_FIELD_REASON_CODES_EMITTED,
TASK_CLOSE_REASON_CODES_EMITTED,
UNKNOWN_BUSINESS_FAILURE_REASON_CODE,
assert_error_explainability_contract_integrity,
build_explainability_reason,
canonicalize_reason_code,
classify_excel_generate_error,
classify_inventory_match_reason,
map_attachment_warning_to_reason_code,
message_zh_for_reason,
primary_attachment_reason_from_warnings,
required_audit_coverage_nodes,
)
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_REASON_OWNING_GATE
# 纯契约断言默认跳过 Flask app/DB 创建(conftest._shipping_notice_stable_auto_config)。
pytestmark = pytest.mark.pure_unit
def test_error_explainability_contract_integrity():
"""
校验分层原因码集合、meta 责任方/动作与门禁归属不冲突。
核心逻辑:调用契约自检;再断言契约版本与已接线子集非空。
"""
# [STEP 1] 契约自检
assert_error_explainability_contract_integrity()
# [STEP 2] 版本与已接线库存源子集冻结
assert ERROR_EXPLAINABILITY_CONTRACT_VERSION == 'shipping-error-explainability-v1'
assert 'source_disabled' in INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED
assert 'inventory_source_unavailable' in INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED
# 单源明细码不得拥有 owning_gate
for code in INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED:
assert code not in PROCESS_GATE_REASON_OWNING_GATE
def test_canonicalize_reason_alias():
"""方案别名必须归一到既有稳定码,禁止并列同义码。"""
assert canonicalize_reason_code('no_inventory_source_rule_matched') == 'no_inventory_source_candidates'
assert canonicalize_reason_code('order_freeze_not_ready') == 'freeze_not_ready'
assert canonicalize_reason_code('source_disabled') == 'source_disabled'
def test_message_zh_for_reason_and_rpa_meta():
"""已接线库存 RPA / 空表原因必须有中文兜底与 owning gate。"""
from app.services.shipping_notice.process_gate_contract import owning_gate_for_reason
assert message_zh_for_reason('business_table_empty')
assert message_zh_for_reason('inventory_rpa_exhausted')
assert owning_gate_for_reason('inventory_rpa_exhausted') == 'inventory_preparation'
assert owning_gate_for_reason('upload_rpa_failed') == 'freight_upload_rpa'
assert message_zh_for_reason('totally_unknown_xyz') is None
def test_inventory_preparation_reason_code_from_pending():
"""履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。"""
from types import SimpleNamespace
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
from app.services.shipping_notice.process_gate_bridge import (
inventory_preparation_reason_code,
manual_upload_reason_code,
)
queued = SimpleNamespace(id=None, pending_human_reason=PH_RPA_PENDING, inventory_lines_json=None)
exhausted = SimpleNamespace(id=None, pending_human_reason=PH_RPA_EXHAUSTED, inventory_lines_json=None)
# 空列表=已落文件但无有效行;None=尚未生成库存文件
empty = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=[])
missing = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=None)
assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued'
assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted'
assert inventory_preparation_reason_code(empty) == 'inventory_file_empty'
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
upload_failed = SimpleNamespace(
id=None, pending_human_reason='upload_rpa_failed', process_status='upload_failed',
)
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
def test_build_explainability_reason_unknown_requires_request_id():
"""
未知原因必须降级为 unknown_business_failure,并暴露 request_id 语义。
核心逻辑:禁止只显示「系统错误」而不带追溯号。
"""
# [STEP 1] 已知码保留责任方与动作
known = build_explainability_reason(
reason_code='source_disabled',
details={'source_code': 'DSV360_AWSSG'},
)
assert known['reason_code'] == 'source_disabled'
assert known['responsible_party'] == 'admin'
assert known['next_action'] == 'open_inventory_source_review'
assert known['details']['source_code'] == 'DSV360_AWSSG'
# [STEP 2] 未知码强制降级并要求 request_id
unknown = build_explainability_reason(
reason_code='totally_invented_reason_xyz',
request_id='req-test-001',
)
assert unknown['reason_code'] == UNKNOWN_BUSINESS_FAILURE_REASON_CODE
assert unknown['request_id'] == 'req-test-001'
missing = build_explainability_reason(reason_code='another_invented_code')
assert missing['reason_code'] == UNKNOWN_BUSINESS_FAILURE_REASON_CODE
assert missing['details'].get('request_id_missing') is True
# [STEP 3] 订单识别 Run.error_code 别名映射到稳定业务原因
layout = build_explainability_reason(
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED',
request_id='req-layout-1',
)
assert layout['reason_code'] == 'layout_parse_failed'
assert layout['responsible_party'] == 'worker'
assert layout.get('request_id') == 'req-layout-1'
def test_technical_failure_alias_and_gate_request_id_fallback():
"""
technical_failure 须归一为 technical_retry_exhausted;Gate 投影无 HTTP 上下文时回退 execution_no。
核心逻辑:别名对齐契约;_resolve_explainability_request_id 保证未知失败可追溯。
"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_projection import (
_resolve_explainability_request_id,
)
# [STEP 1] 历史写入码归一到契约稳定码
assert canonicalize_reason_code('technical_failure') == 'technical_retry_exhausted'
assert message_zh_for_reason('technical_retry_exhausted')
# [STEP 2] Worker 无 HTTP request_id 时不得用 execution_no 冒充
execution = SimpleNamespace(execution_no='PEX-TEST-001')
rid = _resolve_explainability_request_id(
execution=execution,
blocking={'blocking_reason': {'reason_code': 'totally_invented'}},
details={},
)
assert rid is None
# [STEP 3] details 中已有真实 request_id 时使用;execution_no 形态须拒绝
rid_from_details = _resolve_explainability_request_id(
execution=execution,
blocking=None,
details={'request_id': 'req-from-details'},
)
assert rid_from_details == 'req-from-details'
assert _resolve_explainability_request_id(
execution=execution,
blocking=None,
details={'request_id': 'PEX-FAKE'},
) is None
# [STEP 4] 抽取失败/取消别名不得再降级为 unknown
assert canonicalize_reason_code('SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED') == 'order_extraction_failed'
assert canonicalize_reason_code('SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED') == 'order_extraction_cancelled'
assert message_zh_for_reason('technical_retry_exhausted')
failed = build_explainability_reason(reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED')
assert failed['reason_code'] == 'order_extraction_failed'
assert failed['next_action'] == 'retry_order_extraction'
cancelled = build_explainability_reason(reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED')
assert cancelled['reason_code'] == 'order_extraction_cancelled'
assert cancelled['next_action'] == 'open_order_review'
retry_meta = build_explainability_reason(reason_code='technical_retry_exhausted')
assert retry_meta['next_action'] == 'open_order_review'
def test_layer_c_emitted_includes_profile_and_excel_template():
"""Layer C EMITTED 须包含 Profile/Excel 模板不可用码。"""
assert 'source_profile_disabled' in INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED
assert 'source_excel_template_unavailable' in INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED
assert message_zh_for_reason('source_profile_disabled')
assert message_zh_for_reason('attachment_replaced')
def test_emitted_subsets_for_attachment_prep_excel_close():
"""附件/准备/Excel/关闭已接线子集须非空且文案可解析。"""
assert 'attachment_size_exceeded' in ATTACHMENT_REASON_CODES_EMITTED
assert 'inventory_rpa_exhausted' in INVENTORY_PREP_REASON_CODES_EMITTED
assert 'excel_not_ready' in EXCEL_UPLOAD_REASON_CODES_EMITTED
assert 'task_cancelled_by_user' in TASK_CLOSE_REASON_CODES_EMITTED
assert message_zh_for_reason('task_voided_for_correction')
assert message_zh_for_reason('excel_downloaded')
def test_order_field_and_reservation_aliases_own_review_gates():
"""
客户/Reservation/重复订单已接线码须归属复核门禁,别名须归一。
关键断言:draft issue 别名 → 稳定码;稳定码 owning_gate 唯一。
"""
assert canonicalize_reason_code('effective_reservation_missing') == 'reservation_missing'
assert canonicalize_reason_code('reservation_duplicated_in_order') == 'reservation_duplicate'
assert 'reservation_missing' in ORDER_FIELD_REASON_CODES_EMITTED
assert 'customer_unresolved' in ORDER_FIELD_REASON_CODES_EMITTED
assert 'order_extraction_failed' in DOCUMENT_PARSE_REASON_CODES_EMITTED
assert PROCESS_GATE_REASON_OWNING_GATE['reservation_missing'] == 'reservation_validation'
assert PROCESS_GATE_REASON_OWNING_GATE['reservation_duplicate'] == 'reservation_validation'
assert PROCESS_GATE_REASON_OWNING_GATE['customer_unresolved'] == 'customer_resolution'
assert PROCESS_GATE_REASON_OWNING_GATE['duplicate_unresolved'] == 'duplicate_detection'
def test_map_attachment_warning_to_reason_code():
"""EML/附件 warning 须映射到 ATTACHMENT 稳定码。"""
assert map_attachment_warning_to_reason_code(
'eml_total_attachment_size_exceeded:10485760',
) == 'attachment_size_exceeded'
assert map_attachment_warning_to_reason_code('unsupported_file_type:.xyz') == (
'attachment_format_unsupported'
)
assert primary_attachment_reason_from_warnings(
['ok', 'eml_nested_message_unreadable'],
) == 'attachment_corrupted'
assert map_attachment_warning_to_reason_code('eml_nesting_depth_exceeded:3') == (
'attachment_security_blocked'
)
assert map_attachment_warning_to_reason_code('eml_attachment_limit_exceeded:50') == (
'attachment_size_exceeded'
)
assert map_attachment_warning_to_reason_code('notice_text_truncated:1024') == (
'attachment_corrupted'
)
def test_attachment_incomplete_error_details_has_explainability():
"""
INTAKE_ATTACHMENTS_INCOMPLETE details 须含稳定 reason_code 与 explainability。
关键断言:阻断 warning 投影为 attachment_size_exceeded,并带统一投影结构。
"""
details = attachment_incomplete_error_details(
{'warnings': ['eml_total_attachment_size_exceeded:10485760']},
intake_nos=['IN-1'],
reason='attachment_parse_incomplete',
)
assert details['reason_code'] == 'attachment_size_exceeded'
assert details['explainability']['reason_code'] == 'attachment_size_exceeded'
assert details['intake_nos'] == ['IN-1']
assert 'attachment_size_exceeded' in ATTACHMENT_REASON_CODES_EMITTED
def test_emitted_subsets_cover_match_build_and_close():
"""匹配/建单/关闭已接线子集须非空且可解析文案。"""
assert 'inventory_match_failed' in INVENTORY_MATCH_REASON_CODES_EMITTED
assert 'inventory_multi_file_conflict' in INVENTORY_MATCH_REASON_CODES_EMITTED
assert 'inventory_source_conflicted' in INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED
assert 'profile_not_auto_freeze_approved' in ORDER_BUILD_REASON_CODES_EMITTED
assert 'order_freeze_not_ready' in ORDER_BUILD_REASON_CODES_EMITTED
assert 'task_closed_after_upload' in TASK_CLOSE_REASON_CODES_EMITTED
assert 'late_callback_ignored' in TASK_CLOSE_REASON_CODES_EMITTED
assert 'excel_template_missing' in EXCEL_UPLOAD_REASON_CODES_EMITTED
assert 'business_table_not_found' in DOCUMENT_PARSE_REASON_CODES_EMITTED
assert 'document_layout_parse_failed' in DOCUMENT_PARSE_REASON_CODES_EMITTED
assert message_zh_for_reason('inventory_shortage_review_required')
assert canonicalize_reason_code('manual_rejected') == 'task_rejected_by_user'
assert canonicalize_reason_code('document_layout_parse_failed') == 'layout_parse_failed'
def test_classify_excel_and_match_reason_helpers():
"""Excel / 匹配细分分类器须落到已接线稳定码。"""
assert classify_excel_generate_error('库存源未绑定已发布的发货 Excel 模板') == (
'excel_template_missing'
)
assert classify_excel_generate_error('发货 Excel 模板文件缺失或校验失败') == (
'artifact_validation_failed'
)
assert classify_excel_generate_error('缺少已解析的 Warehouse ID,不能生成发货 Excel') == (
'excel_input_incomplete'
)
assert classify_inventory_match_reason(
line_results=[{'disposition': 'multi_file_conflict'}],
) == 'inventory_multi_file_conflict'
assert classify_inventory_match_reason(
line_results=[{'disposition': 'not_found', 'part_number': 'SKU-1'}],
) == 'inventory_sku_not_found'
def test_audit_reason_code_mapping_for_rpa_and_notice_replace():
"""
任务事件双写审计须能映射到可解释性稳定码。
核心逻辑:inventory_rpa_failed 按 error 细分;notice_replaced → attachment_replaced。
"""
from app.services.shipping_notice.tool_common import _audit_reason_code_for_task_event
assert _audit_reason_code_for_task_event('inventory_rpa_exhausted', {}) == 'inventory_rpa_exhausted'
assert _audit_reason_code_for_task_event(
'inventory_rpa_failed', {'error': 'login timeout'},
) == 'inventory_rpa_timeout'
assert _audit_reason_code_for_task_event(
'inventory_rpa_failed', {'error': 'auth rejected'},
) == 'inventory_rpa_login_failed'
assert _audit_reason_code_for_task_event('notice_replaced', {}) == 'attachment_replaced'
assert _audit_reason_code_for_task_event(
'notice_replace_extract_failed', {},
) == 'document_text_unavailable'
assert _audit_reason_code_for_task_event(
'notice_replace_extract_failed',
{'warnings': ['unsupported_file_type:.bin']},
) == 'attachment_format_unsupported'
def _published_line_fields() -> dict[str, str]:
"""创建并发布行级路由测试所需字段契约。"""
from app.services.shipping_notice.order_schema import service as order_schema_service
order_schema_service.initialize_schema({'display_name': '可解释性字段'}, actor_id=None)
reservation = order_schema_service.save_field(
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
part_number = order_schema_service.save_field(
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
qty = order_schema_service.save_field(
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
)
draft = order_schema_service.create_draft({}, actor_id=None)
def _cfg(field_id: str, name: str, purpose: str, value_type: str = 'string') -> dict:
return {
'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [],
'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None,
'business_purpose': purpose,
}
saved = order_schema_service.save_draft(draft['id'], {
'fields': [
_cfg(reservation['id'], '预定单号', 'reservation_id'),
_cfg(part_number['id'], '料号', 'part_number'),
_cfg(qty['id'], '数量', 'quantity', 'decimal'),
],
'expected_lock_version': draft['lock_version'],
}, actor_id=None)
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
return {
'reservation_id': reservation['id'],
'part_number': part_number['id'],
'qty': qty['id'],
}
def test_inventory_all_sources_disabled_blocks_as_unavailable(app):
"""
规则命中但全部源未启用时,block_reason 必须是 inventory_source_unavailable。
核心断言:不得误标为 no_inventory_source_candidates(规则未命中)。
本用例显式请求 app,仍会创建 Flask/DB(不受 pure_unit 跳过影响)。
"""
from app.extensions import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingInventorySource,
ShippingRpaProfile,
)
from app.services.shipping_notice.order_build_eligibility_service import (
project_line_inventory_candidates,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
with app.app_context():
field_ids = _published_line_fields()
contract = order_schema_service.get_published_contract()
fields = {
str(item['field_id']): item
for item in contract['fields']
if str(item['field_id']) in set(field_ids.values())
}
# [STEP 1] 创建未启用库存源 + 命中该源的规则
profile = ShippingRpaProfile(
profile_code='RPA_AWSSG', display_name='AWSSG', connector_type='dbs',
login_url='https://test.invalid/awssg', login_config_json={'auth_mode': 'password'},
)
parsing = ShippingInventoryParsingProfile(
profile_code='PARSE_AWSSG', display_name='AWSSG Parse', version=1,
status='published', file_format='xlsx', definition_json={'match_keys': []},
)
template = ShippingExcelTemplate(
template_code='XLS_AWSSG', display_name='AWSSG XLS', version=1,
status='published', storage_provider='minio', storage_bucket='test',
storage_key='test/awssg.xlsx', original_filename='t.xlsx',
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
source = ShippingInventorySource(
source_code='DSV360_AWSSG', display_name='AWSSG',
connector_type='dbs', rpa_profile=profile, parsing_profile=parsing,
excel_template=template, warehouse_resolution_mode='fixed',
fixed_warehouse_id='SIN', report_path_json={'program_group': 'Bison'},
query_parameters_json=[], enabled=False,
)
db.session.add_all([profile, parsing, template, source])
db.session.add(ShippingInventoryRoutingRule(
rule_code='ROUTE_HINT_AWSSG', rule_name='ROUTE_HINT_AWSSG',
scope='line', priority=100, match_mode='all', status='published',
action_type='add_source_candidates',
action_payload_json={'source_codes': ['DSV360_AWSSG']}, version=1,
conditions=[ShippingInventoryRoutingRuleCondition(
condition_group=1, source_kind='order_field',
order_field_id=field_ids['reservation_id'],
operator='prefix', expected_value_json='3', sequence=1,
)],
))
db.session.commit()
# [STEP 2] 投影行级候选
routing = project_line_inventory_candidates(
fields=fields,
header_by_code={},
line_by_code={
'part_number': 'ABC-001', 'qty': '10', 'reservation_id': '3000099143',
},
line_meta={'line_key': 'line-1'},
)
# [STEP 3] 关键断言:命中但不可用 ≠ 规则未命中
assert routing['raw_rule_source_codes'] == ['DSV360_AWSSG']
assert routing['unavailable_source_codes'] == ['DSV360_AWSSG']
assert routing['unavailable_reasons']['DSV360_AWSSG'] == 'source_disabled'
assert routing['block_reason'] == 'inventory_source_unavailable'
assert routing['block_reason'] != 'no_inventory_source_candidates'
assert routing['can_build'] is False
def test_audit_coverage_matrix_wires_100_percent_in_source():
"""
关键失败/关闭类审计节点必须在源码中保留顶层 reason_code 接线标记。
核心断言:required_audit_coverage_nodes 覆盖率 100%;每个 wire_marker 出现在声明模块。
"""
services_root = Path(__file__).resolve().parents[1] / 'app' / 'services' / 'shipping_notice'
required = required_audit_coverage_nodes()
assert required, 'audit coverage matrix must include required nodes'
assert len(required) == len([item for item in AUDIT_COVERAGE_MATRIX if not item.get('allow_empty')])
missing: list[str] = []
for item in AUDIT_COVERAGE_MATRIX:
module_name = str(item['source_module'])
source_path = services_root / module_name
assert source_path.is_file(), f"missing source module for {item['node']}: {module_name}"
text = source_path.read_text(encoding='utf-8')
marker = str(item['wire_marker'])
if marker not in text:
missing.append(f"{item['node']}: {marker} not in {module_name}")
# 失败/关闭节点额外要求事件类型字符串存在,防止只写码不写审计入口
if not item.get('allow_empty'):
event_type = str(item['event_type'])
for part in event_type.split('|'):
part = part.strip()
if part and part not in text:
missing.append(f"{item['node']}: event_type {part} not in {module_name}")
assert not missing, 'audit coverage gaps:\n' + '\n'.join(missing)
# 关键断言:失败/关闭类节点覆盖率必须为 100%(无 allow_empty 漏项)。
assert len(required) / len(required) == 1.0
def test_late_callback_ignored_maps_to_stable_audit_reason():
"""
迟到/重放 RPA 回调须映射顶层 late_callback_ignored,供审计筛选。
核心逻辑:task 事件 rpa_callback_rejected → tool_common 审计映射。
"""
from app.services.shipping_notice.tool_common import _audit_reason_code_for_task_event
assert _audit_reason_code_for_task_event('rpa_callback_rejected', {}) == 'late_callback_ignored'
assert _audit_reason_code_for_task_event('late_callback_ignored', {}) == 'late_callback_ignored'
assert _audit_reason_code_for_task_event(
'matched_multi_file_conflict', {},
) == 'inventory_multi_file_conflict'
assert _audit_reason_code_for_task_event(
'matched_shortage', {},
) == 'inventory_shortage_review_required'
def test_request_id_resolution_keeps_http_worker_callback_boundaries():
"""
锁定 request_id 语义边界:HTTP 真值 / Worker 不回退 / details 透传 / 拒绝 PEX- 冒充。
"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_projection import (
_resolve_explainability_request_id,
)
execution = SimpleNamespace(execution_no='PEX-WORKER-9')
# Worker:无 HTTP 上下文、无载荷 → None(execution_no 仅能进 details)
assert _resolve_explainability_request_id(
execution=execution, blocking=None, details={'execution_no': 'PEX-WORKER-9'},
) is None
# 回调/阻断载荷携带真实 request_id
assert _resolve_explainability_request_id(
execution=execution,
blocking={'request_id': 'req-callback-77'},
details=None,
) == 'req-callback-77'
# PEX-/EXEC- 形态不得冒充 request_id
assert _resolve_explainability_request_id(
execution=execution,
blocking={'request_id': 'PEX-FAKE-1'},
details={'request_id': 'EXEC-FAKE-2'},
) is None
@@ -0,0 +1,108 @@
"""
tests/test_shipping_evidence_value_bbox_no_root_fallback.py
用途:锁定证据投影禁止在 value_bbox=None 时回退 observation 根级 bbox。
依赖:order_review_evidence_service._resolve_highlight_bbox / list_case_evidence。
逻辑:显式 has_value_coordinate=False 时即使根级有 bbox 也不得绘制。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.field_highlight_contract import build_field_highlight_projection
from app.services.shipping_notice.order_review_evidence_service import (
_layout_has_value_coordinate,
_observation_raw_bbox_flags,
_resolve_highlight_bbox,
)
pytestmark = pytest.mark.pure_unit
class _CaseStub:
"""最小 Case 桩:无冻结 layout,强制走 observation 自身坐标路径。"""
document_id = 1
run = type('R', (), {'input_snapshot_json': {}})()
@property
def unit(self):
return type('U', (), {'result_json': {}})()
def test_explicit_no_value_coordinate_blocks_root_bbox_fallback():
"""has_value_coordinate=False 时不得用 observation 根级 bbox 冒充字段级高亮。"""
observation = {
'value': 'EA',
'quote': 'EA',
'page_no': 1,
'bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.4},
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.4},
'layout_evidence': {
'page_no': 1,
'value_bbox': None,
'normalized_bbox': None,
'has_value_coordinate': False,
'cell_bbox': {'x0': 10, 'y0': 20, 'x1': 90, 'y1': 40},
'quote_source': 'layout_cell_text',
},
}
layout = observation['layout_evidence']
assert _layout_has_value_coordinate(layout) is False
page, bbox, _source = _resolve_highlight_bbox(
_CaseStub(), observation, layout_evidence=layout,
)
# 关键断言:显式无字段值坐标时 bbox 必须为空,禁止根级/整格回退
assert page == 1
assert bbox is None
def test_legacy_without_declaration_still_allows_frozen_cell_path_shape():
"""旧数据未声明 has_value_coordinate 时,解析函数可继续尝试冻结 cell(无 stub layout 则为空)。"""
observation = {
'value': 'PART-1',
'page_no': 1,
'table_id': 'table-lines',
'cell_id': 'line-0-part',
'layout_evidence': {'page_no': 1, 'table_id': 'table-lines', 'cell_id': 'line-0-part'},
}
layout = observation['layout_evidence']
assert _layout_has_value_coordinate(layout) is None
_page, bbox, source = _resolve_highlight_bbox(
_CaseStub(), observation, layout_evidence=layout,
)
# 无冻结 layout 时 bbox 为空;不得回退到不存在的根级框
assert bbox is None
assert source in {None, 'machine_extraction', 'frozen_layout_cell'}
def test_incomplete_root_bbox_marks_invalid_without_drawing():
"""根级 bbox 缺键时质量为 invalid,且不得把根级框当作 highlight_bbox。"""
observation = {
'value': 'PO-1',
'page_no': 2,
'quote': '<b>PO-1</b>',
'bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3},
}
page, bbox, _source = _resolve_highlight_bbox(
_CaseStub(), observation, layout_evidence={},
)
raw_present, raw_invalid = _observation_raw_bbox_flags(observation, resolved_bbox=bbox)
highlight = build_field_highlight_projection(
normalized_bbox=bbox,
raw_bbox_present=raw_present,
raw_bbox_invalid=raw_invalid,
page_no=page or 2,
machine_value='PO-1',
quote='<b>PO-1</b>',
observation=observation,
)
# 关键断言:非法几何 → invalid;无绘制框(根级不得冒充字段级高亮)
assert page is None or page == 2
assert bbox is None
assert raw_present is True
assert raw_invalid is True
assert highlight['highlight_quality'] == 'invalid'
assert highlight['highlight_bbox'] is None
assert 'coordinate_bbox_invalid' in highlight['coordinate_issue_codes']
@@ -0,0 +1,58 @@
"""
tests/test_shipping_field_highlight_audit.py
用途:锁定阶段 5 坐标高亮审计摘要与事件字典完整性。
依赖:order_review_evidence_service.build_highlight_audit_summary、progress_audit_contract。
逻辑:pure_unit;禁止摘要含 PDF 正文/URL/密钥;事件码必须在工作台冻结集合内。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.order_review_evidence_service import build_highlight_audit_summary
from app.services.shipping_notice.progress_audit_contract import (
REVIEW_WORKBENCH_ACCESS_ACTIONS,
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES,
)
pytestmark = pytest.mark.pure_unit
def test_highlight_audit_events_are_frozen():
"""坐标相关审计事件与访问 action 必须已冻结。"""
assert 'review_evidence_list_viewed' in REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
assert 'review_evidence_focused' in REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
assert 'review_highlight_diagnostic_viewed' in REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
assert 'review_coordinate_corrected' in REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
assert 'review_field_restored_machine' in REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
assert 'review_version_history_viewed' in REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
assert 'view_order_review_highlight_diagnostic' in REVIEW_WORKBENCH_ACCESS_ACTIONS
def test_highlight_audit_summary_omits_sensitive_payload():
"""审计摘要不得包含 PDF 正文、存储键或 URL。"""
summary = build_highlight_audit_summary({
'evidence_id': 'qty:header:0',
'field_id': 'qty',
'page_no': 1,
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'ocr',
'coordinate_issue_codes': ['ocr_confidence_insufficient'],
'highlight_bbox': None,
'evidence_ref': 'layout:1:p1:table-1:cell-r2-c6',
'table_id': 'table-1',
'cell_id': 'cell-r2-c6',
'quote': 'SECRET-PDF-BODY',
'machine_value': '20',
'storage_key': 'minio://bucket/key',
'url': 'https://example.invalid/secret',
})
raw = str(summary)
assert 'SECRET-PDF-BODY' not in raw
assert 'minio://' not in raw
assert 'https://' not in raw
assert summary['highlight_quality'] == 'unavailable'
assert summary['has_drawable_bbox'] is False
assert 'ocr_confidence_insufficient' in summary['coordinate_issue_codes']
@@ -0,0 +1,198 @@
"""
tests/test_shipping_field_highlight_contract.py
用途:锁定字段精确高亮契约——质量状态、issue code、投影规则与四态 API 形状。
依赖:field_highlight_contract、order_review_evidence_service(集成四态用例)。
逻辑:纯契约断言默认 pure_unit;禁止 quote=machine_value 自证 matched;
非法 bbox 不得进入 drawable 字段。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.field_highlight_contract import (
COORDINATE_ISSUE_CODES,
DRAWABLE_HIGHLIGHT_QUALITIES,
FIELD_HIGHLIGHT_CONTRACT_VERSION,
HIGHLIGHT_QUALITY_VALUES,
assert_field_highlight_contract_integrity,
build_field_highlight_projection,
classify_value_match_status,
should_draw_highlight,
)
pytestmark = pytest.mark.pure_unit
def test_field_highlight_contract_integrity():
"""冻结集合与绘制规则必须自洽。"""
assert_field_highlight_contract_integrity()
assert FIELD_HIGHLIGHT_CONTRACT_VERSION == 'shipping-field-highlight-v1'
assert HIGHLIGHT_QUALITY_VALUES == {'verified', 'candidate', 'unavailable', 'invalid'}
assert DRAWABLE_HIGHLIGHT_QUALITIES == {'verified', 'candidate', 'unavailable', 'invalid'}
assert 'duplicate_text_coordinate_ambiguous' in COORDINATE_ISSUE_CODES
assert 'quote_not_independent' in COORDINATE_ISSUE_CODES
def test_self_reported_quote_cannot_match():
"""quote 等于 machine_value 但无独立来源时必须 unchecked,不得自证 matched。"""
# 关键断言:禁止用识别值回声绕过 bbox 文本校验
assert classify_value_match_status(
machine_value='20',
quote='20',
) == 'unchecked'
assert classify_value_match_status(
machine_value='20',
quote='20',
quote_source='machine_value',
) == 'unchecked'
assert classify_value_match_status(
machine_value='20',
quote='20',
bbox_text='20',
quote_source='bbox_tokens',
) == 'matched'
assert classify_value_match_status(
machine_value='20',
quote='20',
quote_source='layout_cell_text',
) == 'matched'
def test_projection_four_states_and_no_forged_bbox():
"""
API 契约覆盖四种 highlight_quality;非法/不可用时 highlight_bbox 必为 null。
"""
verified = build_field_highlight_projection(
normalized_bbox={'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.4},
page_no=1,
source='pdf_coordinate',
machine_value='20',
quote='20',
bbox_text='20',
quote_source='bbox_tokens',
evidence_ref='layout:1:p1:table-1:cell-r2-c6',
token_ids=['p1-glyph-81'],
observation={'highlight_quality': 'verified'},
)
# 关键断言:上游 verified + 合法 bbox + 独立文本 → 可绘制 verified
assert verified['highlight_quality'] == 'verified'
assert verified['coordinate_status'] == 'verified'
assert verified['highlight_bbox'] == {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.4}
assert should_draw_highlight(verified['highlight_quality'])
assert verified['value_match_status'] == 'matched'
assert verified['evidence_ref'] == 'layout:1:p1:table-1:cell-r2-c6'
assert verified['token_ids'] == ['p1-glyph-81']
assert verified['drawable'] is True
assert verified['reliable'] is True
assert verified['requires_review'] is False
candidate = build_field_highlight_projection(
normalized_bbox={'x0': 0.12, 'y0': 0.36, 'x1': 0.19, 'y1': 0.39},
page_no=1,
source='pdf_coordinate',
machine_value='PO-1',
quote='PO-1',
quote_source='layout_cell_text',
)
# 有合法坐标但无完整门禁 → candidate,不得静默升 verified
assert candidate['highlight_quality'] == 'candidate'
assert candidate['highlight_bbox'] is not None
assert should_draw_highlight(candidate['highlight_quality'])
assert candidate['drawable'] is True
assert candidate['reliable'] is False
assert candidate['requires_review'] is True
# 自报 quote:即使上游误标 verified,也只能降为 candidate
self_reported = build_field_highlight_projection(
normalized_bbox={'x0': 0.12, 'y0': 0.36, 'x1': 0.19, 'y1': 0.39},
page_no=1,
source='pdf_coordinate',
machine_value='PO-1',
quote='PO-1',
observation={'highlight_quality': 'verified'},
)
assert self_reported['highlight_quality'] == 'candidate'
assert self_reported['value_match_status'] == 'unchecked'
assert 'quote_not_independent' in self_reported['coordinate_issue_codes']
unavailable = build_field_highlight_projection(
normalized_bbox=None,
page_no=2,
source='machine_extraction',
machine_value='EA',
quote='EA',
quote_source='layout_cell_text',
)
assert unavailable['highlight_quality'] == 'unavailable'
assert unavailable['highlight_bbox'] is None
assert 'coordinate_missing' in unavailable['coordinate_issue_codes']
# 无 bbox 时仍不会绘制;质量函数只表达该状态允许被颜色化展示。
assert should_draw_highlight(unavailable['highlight_quality'])
invalid = build_field_highlight_projection(
normalized_bbox=None,
raw_bbox_present=True,
raw_bbox_invalid=True,
page_no=1,
source='pdf_coordinate',
machine_value='20',
quote='20',
quote_source='bbox_tokens',
)
assert invalid['highlight_quality'] == 'invalid'
assert invalid['highlight_bbox'] is None
assert 'coordinate_bbox_invalid' in invalid['coordinate_issue_codes']
assert should_draw_highlight(invalid['highlight_quality'])
def test_mismatched_value_blocks_drawing():
"""值与独立引文不一致时即使有 bbox 也必须降为 invalid 且清空绘制坐标。"""
payload = build_field_highlight_projection(
normalized_bbox={'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.4},
page_no=1,
machine_value='20',
quote='999',
bbox_text='999',
quote_source='bbox_tokens',
observation={'highlight_quality': 'verified'},
)
assert payload['highlight_quality'] == 'invalid'
# 值不一致降为红色诊断,但保留合法 bbox 供用户核对原文位置。
assert payload['highlight_bbox'] is not None
assert payload['value_match_status'] == 'mismatched'
assert 'value_bbox_text_mismatch' in payload['coordinate_issue_codes']
def test_highlight_projection_does_not_emit_confirmation_gates():
"""高亮投影不得夹带自动确认/建单门禁字段。"""
payload = build_field_highlight_projection(
normalized_bbox={'x0': 0.1, 'y0': 0.1, 'x1': 0.2, 'y1': 0.2},
page_no=1,
machine_value='A',
quote='A',
quote_source='layout_cell_text',
)
forbidden = {
'auto_confirm', 'auto_confirmed', 'build_eligible', 'confirmation_status',
'gate_status', 'blocking_reason_code',
}
assert forbidden.isdisjoint(payload.keys())
def test_ocr_source_cannot_auto_elevate_to_verified():
"""阶段 2:OCR 即使上游误标 verified 也必须降为 candidate。"""
payload = build_field_highlight_projection(
normalized_bbox={'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.4},
page_no=1,
source='ocr',
machine_value='20',
quote='20',
bbox_text='20',
quote_source='bbox_tokens',
observation={'highlight_quality': 'verified'},
)
assert payload['highlight_quality'] == 'candidate'
assert payload['highlight_source'] == 'ocr'
assert payload['highlight_bbox'] is not None
@@ -0,0 +1,45 @@
"""
tests/test_shipping_generic_order_evidence_quote.py
用途:锁定 generic_order_evidence 不得用识别值自报 quote。
依赖:generic_order_evidence.build_field_observation。
逻辑:pure_unit;quote 仅来自 bbox_text / 上游独立 quote。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.generic_order_evidence import build_field_observation
pytestmark = pytest.mark.pure_unit
def test_build_field_observation_never_uses_machine_value_as_quote():
"""识别值不得写入 quote;缺独立文本时 quote 为空。"""
# 关键断言:即使 value 有值,也不得回声为 quote
observation = build_field_observation(
field={'value': 'EA', 'page_no': 1, 'table_id': 't1', 'cell_id': 'c1'},
document_id=9,
)
assert observation['value'] == 'EA'
assert observation['quote'] == ''
assert 'quote_source' not in observation['layout_evidence']
def test_build_field_observation_prefers_bbox_text_quote():
"""有 bbox_text 时 quote/quote_source 必须透传独立区域文本。"""
observation = build_field_observation(
field={
'value': 'EA',
'bbox_text': 'EA',
'quote_source': 'bbox_tokens',
'page_no': 1,
'token_ids': ['tok-1'],
'evidence_ref': 'layout:9:p1:t1:c1',
},
document_id=9,
)
assert observation['quote'] == 'EA'
assert observation['layout_evidence']['bbox_text'] == 'EA'
assert observation['layout_evidence']['quote_source'] == 'bbox_tokens'
@@ -3,7 +3,7 @@ tests/test_shipping_generic_order_gate.py
用途:锁定通用确定性解析完整性门禁的 fail-closed 行为与 workflow 路由接线。
依赖:generic_order_gate、generic_order_parser、order_extraction_workflow。
逻辑:未映射列、多客户、续行与 LLM 必填字段必须阻断;layout_drift 禁止降级。
逻辑:未映射列、多客户、续行与必填字段缺失必须阻断;layout_drift 禁止降级。
"""
from __future__ import annotations
@@ -14,6 +14,7 @@ from types import SimpleNamespace
from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate
from app.services.shipping_notice.order_extraction_workflow import (
_apply_stp_route_adjudication,
_profile_table_candidates,
_should_attempt_generic_extraction,
route_deterministic_unit,
)
@@ -97,6 +98,23 @@ def test_stp_needs_review_strips_acceptance_marker():
assert '_hxops_acceptance' not in result.orders[0]
def test_stp_profile_unapproved_still_straight_through_with_acceptance():
"""模板未批准不得阻断 STP 直通;自动建单另由 Candidate Qualification 裁决。"""
orders = [{'_hxops_acceptance': 'approved_deterministic_profile_v1', 'lines': []}]
result = _apply_stp_route_adjudication(
{
'route_type': 'profile_deterministic',
'fallback_reason_codes': ['profile_auto_create_not_approved'],
'auto_create_approved': False,
},
execution_mode='deterministic',
orders=orders,
)
assert result.decision['route_decision'] == 'straight_through'
assert result.orders[0].get('_hxops_acceptance') == 'approved_deterministic_profile_v1'
assert 'profile_auto_create_not_approved' not in (result.decision.get('fallback_reason_codes') or [])
def test_gate_blocks_unmapped_nonempty_column():
"""非空未映射列必须 fail-closed。"""
candidate = _good_candidate()
@@ -154,14 +172,42 @@ def test_gate_blocks_repeated_header_as_continuation_row():
assert 'continuation_row' in gate.gate_reason_codes
def test_gate_blocks_llm_only_required_field():
"""必填但不在表格字段集的字段意味着 LLM 参与,必须阻断。"""
def test_gate_allows_deterministic_value_for_llm_extraction_header():
"""llm_extraction 表示可回退 LLM;已有确定性证据的必填 Header 不得因采集模式被阻断。"""
candidate = _good_candidate()
candidate['columns'].append({
'column_index': 2, 'header_path': ['PO Number'], 'field_code': 'customer_po_number',
'field_id': 'id-customer_po_number', 'status': 'mapped', 'candidates': ['customer_po_number'],
})
candidate['rows'][0]['fields'].append({
'field_id': 'id-customer_po_number', 'field_code': 'customer_po_number', 'value': 'PO-1001',
'page_no': 1, 'table_id': 'table-1', 'row_index': 1, 'column_index': 2,
'cell_id': 'c3', 'evidence_ref': 'ref-3', 'token_ids': ['t3'],
})
gate = evaluate_generic_extraction_gate(
candidates=[candidate],
definition={'fields': [
_field('part_number', required=True),
_field('qty', required=True),
_field('customer_po_number', scope='header', required=True, collection_mode='llm_extraction'),
]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
unit=SimpleNamespace(document_id=11),
)
assert gate.passed is True
assert gate.gate_reason_codes == []
def test_gate_blocks_missing_required_llm_extraction_header():
"""确定性解析缺少必填 Header 时仍应转入 LLM/人工复核,不得通过通用直通门禁。"""
gate = evaluate_generic_extraction_gate(
candidates=[_good_candidate()],
definition={'fields': [
_field('part_number', required=True),
_field('qty', required=True),
{'field_id': 'id-custom-note', 'field_code': 'custom_note', 'scope': 'header', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'},
_field('customer_po_number', scope='header', required=True, collection_mode='llm_extraction'),
]},
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-001'},
@@ -169,7 +215,9 @@ def test_gate_blocks_llm_only_required_field():
)
assert gate.passed is False
assert 'llm_involvement' in gate.gate_reason_codes
assert gate.parse_result is not None
assert gate.parse_result.reason_code == 'required_field_missing'
assert 'required_field_missing' in gate.reason_codes
def test_should_attempt_generic_extraction_rejects_layout_drift():
@@ -188,6 +236,85 @@ def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
) is True
def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkeypatch):
"""自适应模板的完整业务行不得按子布局数量误判跨页,成功匹配必须上送路由审计。"""
profile = {
'profile_id': 52,
'profile_code': 'ODP-PRODUCTION',
'version': 1,
'checksum': 'b' * 64,
'schema_version_id': 31,
'auto_create_approved': False,
'definition': {'contract_version': 'order_coordinate_profile.v2'},
}
document = {
'document_id': 66,
'layout_snapshot': {
'status': 'ready',
'layout_candidate': {'pages': []},
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': []},
},
'tables': [],
},
}
run = SimpleNamespace(
schema_version_id=31,
input_snapshot_json={
'schema': {'definition': {'fields': []}},
'order_document_profiles': [profile],
'intakes': [{'intake_no': 'SNI-PRODUCTION', 'documents': [document]}],
},
)
unit = SimpleNamespace(document_id=66, intake_id=1)
match = SimpleNamespace(
status='unique_match', profile_code='ODP-PRODUCTION', version=1, checksum='b' * 64,
model_dump=lambda **_kwargs: {
'status': 'unique_match', 'profile_code': 'ODP-PRODUCTION', 'version': 1,
'checksum': 'b' * 64, 'candidates': [],
},
)
region = SimpleNamespace(
region_id='order-lines',
line_layouts=[object(), object(), object(), object()],
row_reconstruction_mode='adaptive_record_columns',
continuation_rule=SimpleNamespace(allow_cross_page=False),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
lambda *_args, **_kwargs: ({'intake_no': 'SNI-PRODUCTION'}, document),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.match_frozen_coordinate_profiles',
lambda **_kwargs: match,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._profile_snapshot_targets_valid',
lambda *_args, **_kwargs: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._coordinate_v2_profile_rows',
lambda **_kwargs: [{
'row_index': 0, 'status': 'parsed', 'fields': [{'field_id': 'part-id', 'value': 'PART-A'}],
'issues': [], '_coordinate_region_id': 'order-lines', '_coordinate_row_count': 2,
}],
)
result = _profile_table_candidates(run, unit=unit)
# 关键断言:完整行保留为业务表,且路由可记录实际命中的模板,而不是回退 no_match。
assert result['matched'] is True
assert len(result['tables']) == 1
assert len(result['tables'][0]['rows']) == 1
assert result['match']['status'] == 'unique_match'
assert result['match']['profile_code'] == 'ODP-PRODUCTION'
def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch):
"""无模板且开关开启时 route_type 应为 generic_deterministic。"""
candidate = _good_candidate()
@@ -238,8 +365,58 @@ def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch):
assert route.orders[0]['_hxops_acceptance'] == 'approved_generic_deterministic_v1'
def test_route_deterministic_unit_never_generic_on_layout_drift(monkeypatch):
"""layout_drift 时即使开关开启也不得进入 generic。"""
def test_template_parse_failure_falls_back_to_generic(monkeypatch):
"""模板候选存在但模板解析失败时,仍按既定优先级降级到通用解析。"""
candidate = _good_candidate()
run = SimpleNamespace(
schema_version_id=1,
input_snapshot_json={
'schema': {
'extraction_contract': {'schema_version_id': 1, 'checksum': 'a' * 64},
'definition': {'fields': [_field('part_number', required=True), _field('qty', required=True)]},
},
'order_document_profiles': [{'schema_version_id': 1}],
'intakes': [{
'intake_no': 'SNI-001',
'documents': [{
'document_id': 55,
'layout_snapshot': {'status': 'ready', 'tables': []},
'layout_schema_candidates': [candidate],
}],
}],
},
)
unit = SimpleNamespace(document_id=55, intake_id=1)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled',
lambda: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
lambda *_args, **_kwargs: {
'matched': False, 'blocking': True, 'tables': [],
'issues': ['order_profile_layout_drift'],
'match': {'status': 'layout_drift', 'candidates': []},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
lambda *_args, **_kwargs: (
{'intake_no': 'SNI-001'},
run.input_snapshot_json['intakes'][0]['documents'][0],
),
)
route = route_deterministic_unit(run, unit=unit)
assert route.execution_mode == 'deterministic'
assert route.decision['route_type'] == 'generic_deterministic'
assert route.orders
def test_route_deterministic_unit_attempts_generic_after_layout_drift(monkeypatch):
"""模板漂移不再终止路由;应先尝试通用门禁,失败才进入复核/LLM。"""
run = SimpleNamespace(
schema_version_id=1,
input_snapshot_json={
@@ -269,5 +446,34 @@ def test_route_deterministic_unit_never_generic_on_layout_drift(monkeypatch):
route = route_deterministic_unit(run, unit=unit)
assert route.execution_mode == 'review_required'
assert route.decision.get('route_type') != 'generic_deterministic'
assert 'profile_drift_detected' in route.decision['fallback_reason_codes']
assert isinstance(route.decision.get('generic_completeness'), dict)
assert route.decision['route_type'] == 'llm_assisted_review'
assert route.decision['fallback_reason_codes']
def test_legacy_five_auto_build_gates_do_not_parallel_user_block():
"""
Phase 1.5:旧自动建单五门禁不得平行产生用户阻断。
核心逻辑:失败统一折叠到 owning_gate Finding;blocking Finding 仅冻结就绪一条。
"""
from app.services.shipping_notice.order_build_eligibility_service import assess_auto_build_gates
result = assess_auto_build_gates(
fields_complete=False,
candidate=SimpleNamespace(
acceptance_mode='manual',
candidate_status='provisional',
evidence_json=[],
conflicts_json=[{'x': 1}],
duplicate_status='same_business_content',
duplicate_resolution=None,
),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
)
assert result['can_auto_create'] is False
assert len(result['failed_gates']) >= 2
blocking = [f for f in result['findings'] if f.get('severity') == 'blocking']
assert len(blocking) == 1
assert blocking[0]['owning_gate_code'] == 'order_freeze_readiness'
@@ -193,6 +193,11 @@ def test_ambiguous_multi_candidate_can_build(app):
assert len(result.source_codes) == 2
assert result.can_build is True
assert result.block_reason is None
# 关键断言:命中规则附带版本摘要,供重路由审计。
assert result.matched_rules
assert result.rule_versions
assert result.rule_versions[0]['rule_code'] == 'RSV_PREFIX_1'
assert result.evidence.get('raw_source_codes') == ['DBS_DUB', 'DBS_RTM']
def test_unresolved_and_conflicted_cannot_build(app):
@@ -221,4 +226,5 @@ def test_unresolved_and_conflicted_cannot_build(app):
assert unresolved.block_reason == 'no_inventory_source_candidates'
assert conflicted.status == 'conflicted'
assert conflicted.can_build is False
# action_type=require_manual_review → 保留 require_manual_review,非 inventory_source_conflicted
assert conflicted.block_reason == 'require_manual_review'
+21 -2
View File
@@ -213,6 +213,7 @@ def test_workspace_submit_decision_updates_reference_context_last_action(app, cl
)
db.session.add_all([batch, task])
db.session.commit()
actor_user_id = int(user.id)
res = client.post(
"/api/workspace/shipping-tasks/SN-WS-CONFIRM-001/submit-decision",
@@ -221,9 +222,10 @@ def test_workspace_submit_decision_updates_reference_context_last_action(app, cl
)
assert res.status_code == 200
data = res.get_json()
data = _unwrap_ok(res)
assert data["status"] in {"ok", "running"}
with app.app_context():
from app.models import ShippingAuditEvent
task = ShippingTask.query.filter_by(task_no="SN-WS-CONFIRM-001").one()
event = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="parse_confirmed")
@@ -233,6 +235,23 @@ def test_workspace_submit_decision_updates_reference_context_last_action(app, cl
assert event is not None
assert event.detail_json["action"] == "confirm"
assert event.detail_json["source"] == "workspace_api"
# 关键断言:工作台决策须带操作人、前后快照,并双写统一审计。
assert event.actor_id == actor_user_id
assert isinstance(event.before_json, dict)
assert isinstance(event.after_json, dict)
audit = (
ShippingAuditEvent.query.filter_by(
aggregate_type='shipping_task',
aggregate_id='SN-WS-CONFIRM-001',
action='confirm_parse',
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert audit is not None
assert int(audit.actor_id or 0) == actor_user_id
assert audit.before_snapshot_json is not None
assert audit.after_snapshot_json is not None
inputs = dify_inputs.build_dify_chat_inputs("conv-ws-confirm-001")
runtime_context = json.loads(inputs["agent_runtime_context"])
@@ -289,7 +308,7 @@ def test_workspace_switch_focus_updates_reference_context(app, client):
)
assert res.status_code == 200
data = res.get_json()
data = _unwrap_ok(res)
assert data["batch"]["current_focus_task_no"] == "SN-WS-FOCUS-002"
with app.app_context():
target = ShippingTask.query.filter_by(task_no="SN-WS-FOCUS-002").one()
@@ -10,7 +10,7 @@ import pytest
from app import db
from app.core.errors import ConflictError
from app.models import ShippingCase, ShippingTask
from app.models import ShippingCase, ShippingCustomer, ShippingTask
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task
@@ -26,6 +26,14 @@ def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int |
)
def _active_customer(*, short_code: str = 'CASE') -> ShippingCustomer:
"""创建启用标准客户,供建 Task 前客户门禁使用。"""
customer = ShippingCustomer(standard_name=f'Test Customer {short_code}', short_code=short_code, status='active')
db.session.add(customer)
db.session.flush()
return customer
def test_normal_and_force_create_use_different_cases(app):
"""普通建单和强制新建必须各自创建独立业务单。"""
with app.app_context():
@@ -97,19 +105,38 @@ def test_revision_chain_reuses_root_case(app):
def test_create_task_assigns_case_and_serializes_it(app):
"""真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。"""
with app.app_context():
result = create_task({'source_type': 'manual', 'raw_content': 'customer notice'})
customer = _active_customer(short_code='CRT')
result = create_task({
'source_type': 'manual',
'raw_content': 'customer notice',
'customer_id': customer.id,
})
task = ShippingTask.query.filter_by(task_no=result['task_id']).one()
assert task.shipping_case_id is not None
assert task.customer_resolution_status == 'confirmed'
assert result['data']['shipping_case_id'] == task.shipping_case_id
assert result['data']['case_no'] == task.shipping_case.case_no
assert result['data']['business_no'] is None
assert task.shipping_case.customer_id == customer.id
def test_create_task_rejects_without_customer(app):
"""未确认客户时禁止创建 Task,避免落入 customer_review。"""
with app.app_context():
with pytest.raises(ConflictError) as exc_info:
create_task({'source_type': 'manual', 'raw_content': 'customer notice'})
assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK'
def test_batch_revision_inherits_parent_case(app):
"""真实批量建单路径中的 revision 必须继承父任务业务单。"""
with app.app_context():
customer = _active_customer(short_code='REV')
case = resolve_shipping_case_for_new_task(created_by_id=None)
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
parent = _task('SN-CASE-BATCH-PARENT', case_id=case.id)
parent.customer_resolution_status = 'confirmed'
db.session.add(parent)
db.session.commit()
@@ -126,12 +153,14 @@ def test_batch_revision_inherits_parent_case(app):
task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
assert task.shipping_case_id == case.id
assert task.supersedes_task_id == parent.id
assert task.customer_resolution_status == 'confirmed'
assert ShippingCase.query.count() == 1
def test_batch_force_create_uses_new_case(app):
"""真实批量建单路径中的 force_create 必须创建独立业务单。"""
with app.app_context():
customer = _active_customer(short_code='FRC')
original_case = resolve_shipping_case_for_new_task(created_by_id=None)
original = _task('SN-CASE-FORCE-SOURCE', case_id=original_case.id)
db.session.add(original)
@@ -143,10 +172,12 @@ def test_batch_force_create_uses_new_case(app):
'raw_text': 'forced notice',
'duplicate_source_task_id': original.id,
'duplicate_resolution_type': 'force_create',
'customer_id': customer.id,
}],
'defer_parse': True,
})
task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
assert task.shipping_case_id != original_case.id
assert task.duplicate_source_task_id == original.id
assert task.customer_resolution_status == 'confirmed'
assert ShippingCase.query.count() == 2
@@ -75,14 +75,56 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
assert result.get("checkpoint") == CP_PARSE_REVIEW
def test_try_auto_chain_never_calls_upload_even_when_auto_upload_enabled(app, monkeypatch) -> None:
"""场景:禁 RPA 上传 — 即便 AUTO_UPLOAD=true,匹配后串联也不得调用 upload_to_freight。"""
def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch) -> None:
"""场景:AUTO_UPLOAD=true 时匹配后串联须调用 upload_to_freight(mode=auto)。"""
with app.app_context():
from app import db
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
task = ShippingTask(
task_no="SN-STP-RPA-ON",
process_status="matched",
match_status="fulfillable",
source_type="manual",
line_results_json=[{"line_status": "ok"}],
export_file_path="/tmp/already.xlsx",
export_file_name="already.xlsx",
)
db.session.add(task)
db.session.commit()
upload_calls: list[dict] = []
def _fake_upload(payload):
upload_calls.append(dict(payload or {}))
return {"status": "running", "message": "rpa-triggered"}
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.upload_to_freight",
_fake_upload,
)
result = try_auto_chain_after_match(
task,
{"status": "ok", "message": "matched"},
payload={"task_id": task.task_no},
)
# 关键断言:自动链接入货代上传 RPA。
assert len(upload_calls) == 1
assert upload_calls[0].get("mode") == "auto"
assert result["status"] == "running"
def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch) -> None:
"""场景:AUTO_UPLOAD=false 时停在人工上传,不调用 upload_to_freight。"""
with app.app_context():
from app import db
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
task = ShippingTask(
task_no="SN-STP-NO-RPA",
process_status="matched",
@@ -163,15 +163,15 @@ def test_evaluate_run_auto_freeze_policy_keeps_fail_closed_with_run_blockers(app
assert policy['selected_profile_id'] == profile.id
assert policy['qualification_id'] == qualification.id
assert policy['qualification_status'] == 'auto_freeze_approved'
# Run 级仅保留技术/预算等硬阻断;客户/场景/pending 改由 Candidate Qualification 裁决。
assert set(policy['blocking_reason_codes']) >= {
'technical_failure_present',
'budget_stopped',
'review_required',
'pending_orders_present',
'customer_scope_not_configured',
'business_scenario_not_configured',
'customer_confirmation_required',
}
assert policy.get('candidate_qualification_required') is True
assert 'customer_scope_not_configured' in (
policy.get('parser_quality') or {}
).get('customer_scope_reason_codes', [])
def test_evaluate_run_auto_freeze_policy_blocks_suspended_profile(app):
@@ -227,8 +227,11 @@ def test_evaluate_run_auto_freeze_policy_blocks_suspended_profile(app):
assert policy['enabled'] is False
assert policy['qualification_status'] == 'auto_freeze_suspended'
# 管理员显式暂停仍为 Run 级硬阻断;客户范围改记入 parser_quality。
assert 'profile_auto_freeze_suspended' in policy['blocking_reason_codes']
assert 'customer_scope_not_configured' in policy['blocking_reason_codes']
assert 'customer_scope_not_configured' in (
policy.get('parser_quality') or {}
).get('customer_scope_reason_codes', [])
def test_evaluate_run_auto_freeze_policy_matches_customer_and_business_scope(app):
@@ -301,14 +304,15 @@ def test_evaluate_run_auto_freeze_policy_matches_customer_and_business_scope(app
assert 'business_scenario_out_of_scope' not in policy['blocking_reason_codes']
assert 'customer_confirmation_required' not in policy['blocking_reason_codes']
# Worker 提交本 Unit 的候选时,Run 可能尚未转为 review_required;Unit 事实必须先阻断副作用。
# 单 Unit 待复核不再硬关整 Run.enabled;该 Unit 的 Candidate Qualification 独立裁决。
unit.status = 'review_required'
run.status = 'processing'
db.session.flush()
blocked = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
still = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
assert blocked['enabled'] is False
assert 'unit_review_required' in blocked['blocking_reason_codes']
assert still['enabled'] is True
assert 'unit_review_required' not in still['blocking_reason_codes']
assert still.get('candidate_qualification_required') is True
def test_evaluate_run_auto_freeze_policy_ignores_placeholder_pending_orders(app):
@@ -475,7 +479,7 @@ def test_generic_deterministic_needs_review_cannot_auto_freeze(app, monkeypatch)
policy = evaluate_run_auto_freeze_policy(run=run, submission_result={'pending_count': 0})
# 断言:不得因 decision=deterministic 误判为可冻结。
# 断言:不得因 decision=deterministic 误判为可冻结;needs_review 通用路径无 freeze_source。
assert policy['enabled'] is False
assert policy.get('freeze_source') != 'generic_deterministic'
assert 'profile_not_auto_freeze_approved' in policy['blocking_reason_codes']
assert policy.get('candidate_qualification_required') is True
@@ -103,12 +103,62 @@ def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tupl
def test_multi_candidate_routing_allows_build(app):
"""两位候选库存源(ambiguous)仍满足建单库存门禁 can_build=True。"""
"""两位可用候选库存源(ambiguous)仍满足建单库存门禁 can_build=True。"""
with app.app_context():
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingRpaProfile,
)
from app.services.shipping_notice.inventory_structure_fingerprint import (
FINGERPRINT_VERSION, compatibility_fingerprint, exact_fingerprint, structure_definition,
)
import hashlib
import json
field_ids = _published_line_fields()
fields = _schema_fields_map(field_ids)
# 注入第二个可用库存源,保证两枚候选均通过启停/Profile 过滤。
field_mapping = {'warehouse_id': 'Warehouse ID'}
match_keys = [{'fields': ['warehouse_id']}]
definition = {
'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': field_mapping, 'match_keys': match_keys,
}
structure = structure_definition(
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
headers=['Warehouse ID', 'SKU', 'Reservation ID', 'Qty'],
)
checksum = hashlib.sha256(
json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
).hexdigest()
parsing = ShippingInventoryParsingProfile(
profile_code='TEST_RTM', display_name='Test RTM', version=1, status='published',
file_format='xlsx', definition_json=definition, checksum=checksum,
structure_definition_json=structure,
exact_structure_fingerprint=exact_fingerprint(structure),
compatibility_fingerprint=compatibility_fingerprint(
definition=structure, field_mapping=field_mapping, match_keys=match_keys,
),
fingerprint_version=FINGERPRINT_VERSION,
)
excel = ShippingExcelTemplate(
template_code='TEST_RTM', display_name='Test RTM', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/rtm/template.xlsx',
original_filename='template.xlsx',
file_checksum='1' * 64, definition_json={}, definition_checksum='1' * 64,
)
profile = ShippingRpaProfile(
profile_code='DBS_RTM_TEST', display_name='DBS RTM', connector_type='dbs',
login_url='https://test.invalid/dbs-rtm', login_config_json={'auth_mode': 'password'},
)
second = ShippingInventorySource(
source_code='DSV360_AWSRTM', display_name='DBS RTM', connector_type='dbs',
rpa_profile=profile, parsing_profile=parsing, excel_template=excel,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSRTM',
report_path_json={'program_group': 'Bison'}, query_parameters_json=[], enabled=True,
)
db.session.add_all([parsing, excel, profile, second])
db.session.add(_rule(
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
code='RSV_PREFIX_1', priority=100, sources=['DSV360_AWSDU', 'DSV360_AWSRTM'],
conditions=[(field_ids['reservation_id'], 'prefix', '1')],
))
db.session.commit()
@@ -122,10 +172,76 @@ def test_multi_candidate_routing_allows_build(app):
line_metas=[{'line_key': 'line-1'}],
)
# 关键断言:多候选 status=ambiguous 但不阻断建单。
# 关键断言:多可用候选 status=ambiguous 但不阻断建单。
assert result['can_build'] is True
assert result['line_projections'][0]['routing_status'] == 'ambiguous'
assert set(result['line_projections'][0]['candidate_inventory_source_codes']) == {'DBS_DUB', 'DBS_RTM'}
assert set(result['line_projections'][0]['candidate_inventory_source_codes']) == {
'DSV360_AWSDU', 'DSV360_AWSRTM',
}
def test_unavailable_rule_candidates_are_filtered(app):
"""停用或不存在的规则候选不进入有效结果,但保留在原始/不可用列表。"""
with app.app_context():
field_ids = _published_line_fields()
fields = _schema_fields_map(field_ids)
db.session.add(_rule(
code='HINT_DBS_SIN', priority=100,
sources=['DSV360_AWSSG', 'DSV360_AWSDU'],
conditions=[(field_ids['reservation_id'], 'prefix', '1')],
))
db.session.commit()
routing = project_line_inventory_candidates(
fields=fields,
header_by_code={},
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '1000123456'},
line_meta={'line_key': 'line-1'},
)
# 关键断言:不存在的 AWSSG 进入 unavailable 且原因为 source_not_found;
# 可用 AWSDU 成为唯一有效候选(≠ 规则未命中)。
assert 'DSV360_AWSSG' in routing['raw_rule_source_codes']
assert 'DSV360_AWSSG' in routing['unavailable_source_codes']
assert routing['unavailable_reasons']['DSV360_AWSSG'] == 'source_not_found'
assert routing['block_reason'] is None
assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
assert routing['routing_status'] == 'resolved'
assert routing['can_build'] is True
def test_manual_decision_not_silently_overwritten_by_rule_suggestion(app):
"""人工决定优先;规则建议可并存但不覆盖有效候选。"""
with app.app_context():
field_ids = _published_line_fields()
fields = _schema_fields_map(field_ids)
db.session.add(_rule(
code='FORCE_OTHER', priority=100, sources=['DSV360_AWSDU'],
conditions=[(field_ids['reservation_id'], 'is_not_empty', None)],
))
db.session.commit()
line_meta = {
'line_key': 'line-1',
'inventory_routing': {
'selection_mode': 'manual',
'candidate_inventory_source_codes': ['DSV360_AWSDU'],
'manual_reason': 'planner confirmed',
'suggestion_pending': True,
'rule_suggestion': {'source_codes': ['DSV360_AWSDU']},
},
}
routing = project_line_inventory_candidates(
fields=fields,
header_by_code={},
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'},
line_meta=line_meta,
)
# 关键断言:有效候选仍是人工值;selection_mode 保持 manual。
assert routing['selection_mode'] == 'manual'
assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
assert routing['can_build'] is True
def test_zero_candidates_blocks_build(app):
@@ -256,3 +372,77 @@ def test_manual_selection_without_reason_is_blocked(app):
# 关键断言:缺原因不得放行建单。
assert routing['can_build'] is False
assert routing['block_reason'] == 'manual_inventory_source_reason_required'
def test_auto_freeze_reasons_own_single_user_blocking_finding(app, monkeypatch):
"""资格失败只产生一条用户阻断 Finding,不平行产生多个 auto_build_gate_*。"""
from types import SimpleNamespace
from app.services.shipping_notice.order_build_eligibility_service import assess_order_build_eligibility
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': False},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': 'DBS_DUB'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.classify_inventory_source_codes',
lambda codes: {
'available': list(codes or []),
'unavailable': [],
'unavailable_reasons': {},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_build_eligibility_service.evaluate_inventory_source_rules_for_field_values',
lambda **kwargs: SimpleNamespace(
status='resolved',
source_codes=['DBS_DUB'],
can_build=True,
block_reason=None,
matched_rule_ids=[1],
matched_rules=(),
evidence={},
),
)
with app.app_context():
field_ids = _published_line_fields()
fields = _schema_fields_map(field_ids)
result = assess_order_build_eligibility(
fields=fields,
header_by_code={},
lines=[{'reservation_id': '2000484577', 'part_number': 'PN-1', 'qty': '2'}],
line_metas=[{'line_key': 'L1'}],
run=SimpleNamespace(auto_freeze_policy_json={
'enabled': False,
'emergency_stop': False,
}),
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
candidate=SimpleNamespace(
acceptance_mode='automatic',
candidate_status='accepted',
evidence_json=[{'x': 1}],
conflicts_json=None,
duplicate_status='none',
duplicate_resolution=None,
missing_fields_json=[],
field_confidence_json={},
classification_confidence=0.96,
consumed_task_id=None,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
),
customer_resolved=True,
)
auto_issues = [i for i in result['issues'] if i.get('severity') == 'auto_create_blocking']
assert result['can_build'] is True
assert result['can_auto_create'] is False
assert len(auto_issues) == 1
assert auto_issues[0]['code'] == 'candidate_qualification_blocked'
assert auto_issues[0]['reason_code'] == 'auto_create_disabled'
assert not any(str(i.get('code') or '').startswith('auto_build_gate_') for i in result['issues'])
@@ -1519,6 +1519,7 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
)
# The v2 field region contains the line number and produces a logical row.
assert preview['field_codes'] == ['customer_po_line_no']
assert preview['rows'] == [['customer_po_line_no'], ['10']]
assert preview['source_row_indices'] == [[], [0]]
@@ -1554,6 +1555,7 @@ def test_profile_region_preview_uses_schema_field_order(app, monkeypatch):
)
# 断言先标注的 part_number 仍排在 Schema 中更靠前的 customer_po_line_no 之后。
assert preview['field_codes'] == ['customer_po_line_no', 'part_number']
assert preview['rows'][0] == ['customer_po_line_no', 'part_number']
@@ -368,3 +368,18 @@ def test_guide_defines_independent_prompts_for_each_status_renderer():
assert '任务状态 Tool 返回:' in task_section
assert 'stop_agent_turn=true' in task_section
assert 'forbidden_next_tools' in task_section
def test_general_chat_prompt_forbids_inventing_shipping_platform_steps():
"""普通聊天必须只引导已确认入口,避免模型虚构外部平台或审核流程。"""
source = _guide_source()
general_section = source[
source.index('## 18. CHAT_GENERAL_LLM'):
source.index('## 19. CHAT Answer 和降级终端节点')
]
assert '当前助手中上传客户发来的发货通知文件' in general_section
assert '右侧“本次处理”查看进度' in general_section
assert '如何创建新的发货通知' in general_section
assert '不得根据通用货代经验补全流程' in general_section
assert '不得虚构登录、菜单、新建、草稿、审核或外部平台步骤' in source
@@ -292,6 +292,45 @@ def test_create_run_reparses_empty_email_supplement_from_frozen_html_tables(app)
assert body['email_supplement']['rows'][0]['reservation_id'] == '4000111701'
def test_create_run_reparses_partial_email_supplement_from_frozen_html_tables(app):
"""历史正文已有部分行时,Run 仍须按冻结 Schema 重建新增的预约号列。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-HTML-PARTIAL')
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
schema.definition_json = {'fields': [
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN']},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['External reservation ID'],
},
]}
intake.structured_result_json = {
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>MPN</th><th>External reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>3000099143</td></tr></table>''']},
}
db.session.add(ShippingNoticeDocument(
intake_id=intake.id,
document_type='email_body',
attachment_key='__email_body__',
filename='email-body.html',
content_hash='f' * 64,
classification='email_context',
parse_status='parsed',
extracted_text='Outlook flattened text without table columns',
order_extraction_result_json={'email_supplement': {'rows': [{
'po_number': '4518838154', 'mpn': 'B3-AR1000270A1',
}], 'issues': []}},
))
db.session.commit()
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
assert body['email_supplement']['rows'][0]['reservation_id'] == '3000099143'
def test_worker_materialization_preserves_request_snapshot_on_retry(app):
"""Worker 重试可复用执行计划,但不得改写发送时的请求快照与幂等审计锚点。"""
with app.app_context():
@@ -2388,6 +2427,34 @@ def test_reparse_submission_accepts_orphaned_consumed_intake(app):
assert ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0
def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app):
"""PDF 重识别按 Unit 落库时,也必须允许复用未建 Task/Batch 的 consumed Intake。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-UNIT-SUBMISSION')
source, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
ensure_order_extraction_plan(source)
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1})
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = None
intake.consumed_task_id = None
db.session.commit()
replacement, _ = reparse_order_extraction_run(
user_id=user.id, run_no=source.run_no, reason='rule_updated',
)
ensure_order_extraction_plan(replacement)
unit = replacement.extraction_plan.units[0]
result = submit_order_extraction_unit_result(run=replacement, unit=unit, orders=[])
# 关键断言:合法重识别不会被旧版 consumed 标记误判为重复订单抽取。
assert result['unit_id'] == unit.id
assert ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0
def test_failed_run_with_current_candidate_can_recover_to_review(app):
"""仅候选已成功落库的技术失败 Run 可恢复为人工复核,普通失败仍不可跳过。"""
with app.app_context():
@@ -0,0 +1,84 @@
"""
tests/test_shipping_order_review_field_conflict.py
用途:验收建单前复核字段冲突投影(conflict_key / options / line_key)。
依赖:order_review_field_conflict_service、types.SimpleNamespace。
逻辑:构造 Case + Candidate 替身;断言投影稳定键与候选展示值,不落库。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.order_review_field_conflict_service import (
project_review_case_field_conflicts,
)
def test_project_review_case_field_conflicts_builds_stable_keys():
"""Candidate.conflicts_json 投影为 conflict_key + options,并按 line_index 挂 line_key。"""
candidate = SimpleNamespace(
conflicts_json=[{
'field': 'qty',
'line_index': 0,
'severity': 'blocking',
'reason': 'cross_source_conflict',
'values': ['10', '12'],
'observation_ids': ['obs-a', 'obs-b'],
}],
structured_result_json={
'extraction': {
'field_adjudication': {
'observations': [
{
'observation_id': 'obs-a',
'field': 'qty',
'value': '10',
'source': 'table',
},
{
'observation_id': 'obs-b',
'field': 'qty',
'value': '12',
'source': 'header',
},
],
},
},
},
)
case = SimpleNamespace(
candidate_id=1,
current_draft=SimpleNamespace(
lines_json=[{
'line_key': 'line-1',
'line_index': 0,
'values': {},
}],
),
)
# 绕过 ORM:直接注入 Candidate。
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 len(items) == 1
item = items[0]
assert item['conflict_key'] == '0:qty'
assert item['field_code'] == 'qty'
assert item['line_key'] == 'line-1'
assert item['reason'] == 'cross_source_conflict'
assert [opt['display_value'] for opt in item['options']] == ['10', '12']
assert item['options'][0]['sources'] == ['table']
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) == []
@@ -0,0 +1,82 @@
"""
tests/test_shipping_order_review_profile_match.py
用途:验收建单前复核模板匹配只读投影。
依赖:order_review_profile_match_service、types.SimpleNamespace。
逻辑:注入 RouteDecision 替身;断言 selected_profile / candidates / needs_review。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice import order_review_profile_match_service as svc
def test_project_review_case_profile_match_ambiguous():
"""ambiguous 路由决策投影 needs_review,并展示候选分。"""
route = SimpleNamespace(
match_status='ambiguous',
decision='review_required',
selected_profile_id=None,
selected_profile_code=None,
selected_profile_version=None,
selected_profile_checksum=None,
auto_create_approved=False,
candidate_count=2,
matched_table_count=0,
parsed_table_count=0,
approved_table_count=0,
candidate_summary_json=[
{
'profile_code': 'ACME_PO',
'version': 3,
'score': 0.82,
'hard_match': False,
'reason_codes': ['anchor_partial'],
},
{
'profile_code': 'ACME_PO_V2',
'version': 1,
'score': 0.79,
'hard_match': False,
'reason_codes': [],
},
{
'_contract': 'order-extraction-route.v1',
'route_type': 'manual_review',
},
],
fallback_reason_codes_json=['profile_ambiguous'],
)
case = SimpleNamespace(
unit_id=11,
run=SimpleNamespace(input_snapshot_json={
'order_document_profiles': [
{'code': 'ACME_PO', 'version': 3, 'display_name': 'ACME PO'},
],
}),
)
original = svc._latest_route_decision
svc._latest_route_decision = lambda _case: route
try:
payload = svc.project_review_case_profile_match(case)
finally:
svc._latest_route_decision = original
assert payload['available'] is True
assert payload['needs_review'] is True
assert payload['status'] == 'ambiguous'
assert payload['route_type'] == 'manual_review'
assert payload['selected_profile'] is None
assert payload['candidates'][0]['display_name'] == 'ACME PO'
assert payload['candidates'][0]['score'] == 0.82
assert 'profile_ambiguous' in payload['fallback_reason_codes']
def test_project_review_case_profile_match_missing_route():
"""无 RouteDecision 时 available=false。"""
case = SimpleNamespace(unit_id=None, run=SimpleNamespace(input_snapshot_json={}))
payload = svc.project_review_case_profile_match(case)
assert payload['available'] is False
assert payload['status'] == 'unknown'
@@ -34,9 +34,13 @@ from app.services.shipping_notice.order_review_service import (
)
from app.services.shipping_notice.order_review_draft_service import (
add_line,
adopt_inventory_routing_suggestion,
delete_line,
keep_manual_inventory_routing,
patch_header_field,
patch_line_field,
reroute_inventory_routing,
set_line_inventory_candidates,
validate_draft,
)
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence, list_case_evidence
@@ -214,6 +218,9 @@ def test_review_projection_uses_frozen_schema_and_enforces_case_owner(app):
assert detail['document']['file_name']
assert 'extracted_text' not in str(detail)
assert listing['items'][0]['case_no'] == case.case_no
# 未确认 Case 不投影推进恢复字段。
assert detail.get('confirmed_task_no') is None
assert detail.get('post_confirm_auto_progress') is None
try:
get_user_review_case(user_id=other.id, case_no=case.case_no)
except NotFoundError:
@@ -281,7 +288,7 @@ def test_review_visible_helpers_allow_admin_readonly_but_write_stays_owner_only(
def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(app):
"""单字段人工编辑不覆盖机器快照;旧版本写入被拒绝且每次变更都有独立审计。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-DRAFT')
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-DRAFT')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
schema = dict(snapshot['schema'])
@@ -304,6 +311,12 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap
{'field_id': 'reservation-id', 'observations': [{'value': '3000092917'}]},
]}],
}]}
# 建单资格 fail-closed:客户未确认时 validate 只能 needs_review,与坐标高亮无关。
db.session.add(ShippingNoticeCandidate(
candidate_no='CAND-REVIEW-DRAFT', intake_id=intake.id, primary_document_id=document.id,
candidate_key='review-draft', order_extraction_run_id=run.id,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
))
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
@@ -407,6 +420,11 @@ def test_review_evidence_is_case_scoped_and_omits_untrusted_bbox(app):
assert item['page_no'] == 2
assert item['quote'] == '<b>PO-1</b>'
assert item['bbox'] is None
assert item['highlight_bbox'] is None
assert item['highlight_quality'] == 'invalid'
assert item['coordinate_status'] == 'invalid'
assert 'coordinate_bbox_invalid' in item['coordinate_issue_codes']
assert item['machine_value'] == 'PO-1'
assert 'storage_key' not in str(payload)
@@ -430,6 +448,8 @@ def test_review_evidence_normalizes_frozen_layout_coordinates(app):
'value': 'Example', 'quote': 'Example',
'layout_evidence': {
'page_no': 2, 'source': 'pdf_coordinate',
'quote_source': 'bbox_tokens',
'bbox_text': 'Example',
'value_bbox': {'x0': 80, 'y0': 200, 'x1': 400, 'y1': 300},
},
}],
@@ -442,6 +462,12 @@ def test_review_evidence_normalizes_frozen_layout_coordinates(app):
assert item['page_no'] == 2
assert item['source'] == 'pdf_coordinate'
assert item['bbox'] == {'x0': 0.1, 'y0': 0.2, 'x1': 0.5, 'y1': 0.3}
# 阶段 0:合法坐标默认 candidate,不静默升 verified;字段值不受影响。
assert item['highlight_quality'] == 'candidate'
assert item['highlight_bbox'] == item['bbox']
assert item['highlight_source'] == 'pdf_coordinate'
assert item['machine_value'] == 'Example'
assert item['value_match_status'] == 'matched'
def test_review_evidence_resolves_line_cell_bbox_from_frozen_layout(app):
@@ -481,6 +507,117 @@ def test_review_evidence_resolves_line_cell_bbox_from_frozen_layout(app):
assert item['page_no'] == 1
assert item['source'] == 'frozen_layout_cell'
assert item['bbox'] == {'x0': 0.1, 'y0': 0.4, 'x1': 0.35, 'y1': 0.5}
assert item['highlight_quality'] == 'candidate'
assert item['highlight_source'] == 'frozen_layout_cell'
assert item['highlight_bbox'] == item['bbox']
assert item['machine_value'] == 'PART-1'
def test_review_evidence_resolves_nested_layout_evidence_cell_ids(app):
"""通用订单路径仅在 layout_evidence 内携带 table/cell 时仍须能反查冻结 bbox。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-NESTED-CELL')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
intake_snapshot = dict(snapshot['intakes'][0])
document_snapshot = dict(intake_snapshot['documents'][0])
document_snapshot['layout_snapshot'] = {
'layout_candidate': {
'pages': [{
'page_no': 1, 'width': 1000, 'height': 500,
'tables': [{'table_id': 'table-nested', 'rows': [{'cells': [{
'cell_id': 'nested-qty', 'bbox': {'x0': 200, 'y0': 100, 'x1': 300, 'y1': 150},
}]}]}],
}],
},
}
intake_snapshot['documents'] = [document_snapshot]
snapshot['intakes'] = [intake_snapshot]
run.input_snapshot_json = snapshot
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [{
'field_id': 'qty', 'observations': [{
'value': '20', 'quote': '20',
'layout_evidence': {
'page_no': 1,
'table_id': 'table-nested',
'cell_id': 'nested-qty',
'token_ids': ['tok-1'],
'evidence_ref': 'layout:1:p1:table-nested:nested-qty',
},
}],
}]}]}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
# 关键断言:嵌套身份仍可定位冻结 cell,且 evidence_ref/token 进入高亮 DTO。
assert item['table_id'] == 'table-nested'
assert item['cell_id'] == 'nested-qty'
assert item['source'] == 'frozen_layout_cell'
assert item['bbox'] == {'x0': 0.2, 'y0': 0.2, 'x1': 0.3, 'y1': 0.3}
assert item['highlight_bbox'] == item['bbox']
assert item['evidence_ref'] == 'layout:1:p1:table-nested:nested-qty'
assert item['token_ids'] == ['tok-1']
assert item['machine_value'] == '20'
def test_review_evidence_highlight_verified_and_unavailable_states(app):
"""证据 API 须覆盖 verified / unavailable;缺失坐标不影响 machine_value。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-HIGHLIGHT-STATES')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
intake_snapshot = dict(snapshot['intakes'][0])
document_snapshot = dict(intake_snapshot['documents'][0])
document_snapshot['layout_snapshot'] = {
'coordinate_evidence': {'pages': {'1': {'width': 1000, 'height': 1000}}},
}
intake_snapshot['documents'] = [document_snapshot]
snapshot['intakes'] = [intake_snapshot]
run.input_snapshot_json = snapshot
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [
{
'field_id': 'qty', 'observations': [{
'value': '20', 'quote': '20',
'layout_evidence': {
'page_no': 1, 'source': 'pdf_coordinate',
'highlight_quality': 'verified',
'quote_source': 'bbox_tokens',
'bbox_text': '20',
'evidence_ref': 'layout:1:p1:table-1:cell-r2-c6',
'token_ids': ['p1-glyph-81', 'p1-glyph-82'],
'value_bbox': {'x0': 120, 'y0': 360, 'x1': 190, 'y1': 390},
},
}],
},
{
'field_id': 'uom', 'observations': [{
'value': 'EA', 'quote': 'EA', 'page_no': 1,
}],
},
], 'lines': []}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
items = {item['field_id']: item for item in list_case_evidence(user_id=user.id, case_no=case.case_no)['items']}
verified = items['qty']
assert verified['highlight_quality'] == 'verified'
assert verified['coordinate_status'] == 'verified'
assert verified['highlight_bbox'] == {'x0': 0.12, 'y0': 0.36, 'x1': 0.19, 'y1': 0.39}
assert verified['evidence_ref'] == 'layout:1:p1:table-1:cell-r2-c6'
assert verified['token_ids'] == ['p1-glyph-81', 'p1-glyph-82']
assert verified['machine_value'] == '20'
assert verified['value_match_status'] == 'matched'
unavailable = items['uom']
assert unavailable['highlight_quality'] == 'unavailable'
assert unavailable['highlight_bbox'] is None
assert unavailable['bbox'] is None
assert unavailable['machine_value'] == 'EA'
assert 'coordinate_missing' in unavailable['coordinate_issue_codes']
def test_manual_draft_and_dispositions_are_case_scoped_and_preserve_machine_facts(app):
@@ -544,6 +681,10 @@ def test_document_reparse_uses_one_document_and_restores_old_draft_when_new_run_
assert reused_duplicate is True
assert duplicate.id == replacement.id
transition_order_extraction_run(replacement, target_status='processing')
transition_order_extraction_run(
replacement, target_status='failed', error_code='TEST_REPARSE_FAILED', error_message='test',
)
finalize_document_reparse(run=replacement, succeeded=False)
assert case.status == 'unreviewed'
finalize_document_reparse(run=replacement, succeeded=True)
@@ -552,6 +693,15 @@ def test_document_reparse_uses_one_document_and_restores_old_draft_when_new_run_
assert case.current_draft is not None
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id, event_type='document_reparse_failed').count() == 1
retry, retry_reused = reparse_case_document(
user_id=user.id, case_no=case.case_no, reason='document_quality', comment='retry after failure',
)
# 关键断言:失败后必须创建新的重识别尝试,不能把失败 Run 当作幂等成功结果返回。
assert retry_reused is False
assert retry.id != replacement.id
assert retry.run_no != replacement.run_no
assert retry.input_snapshot_json['review_reparse']['attempt_no'] == 1
def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(app):
"""成功后旧 Case 才只读替代;已确认/非订单 PDF 永远不能再次处置或重识别。"""
@@ -652,7 +802,12 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
]}]}]}
machine = ShippingNoticeCandidate(
candidate_no='CAND-REVIEW-CONFIRM', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-confirm', order_extraction_run_id=run.id, structured_result_json={'machine': 'unchanged'},
candidate_key='machine-confirm', order_extraction_run_id=run.id,
# 客户已确认是建单前置条件;机器 Candidate 只读快照不得被确认覆盖。
structured_result_json={
'machine': 'unchanged',
'customer': {'resolution_status': 'confirmed'},
},
)
db.session.add(machine)
db.session.commit()
@@ -681,14 +836,17 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
assert task.pending_human_reason is None
assert revision.task_id == task.id
assert revision.header_values_json['values']['po-id']['value'] == 'PO-CONFIRMED'
assert db.session.get(ShippingNoticeCandidate, machine.id).structured_result_json == {'machine': 'unchanged'}
assert db.session.get(ShippingNoticeCandidate, machine.id).structured_result_json == {
'machine': 'unchanged',
'customer': {'resolution_status': 'confirmed'},
}
assert case.status == 'confirmed'
def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutations(app):
"""同键确认回放同一任务;旧版本确认、确认后编辑和处置均不能流入下游。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-CONFIRM-REPLAY')
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-CONFIRM-REPLAY')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
schema = dict(snapshot['schema'])
@@ -707,6 +865,11 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati
{'field_id': 'qty-id', 'observations': [{'value': '3'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092918'}]},
]}]}]}
db.session.add(ShippingNoticeCandidate(
candidate_no='CAND-REVIEW-CONFIRM-REPLAY', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-confirm-replay', order_extraction_run_id=run.id,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
))
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
@@ -731,3 +894,227 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati
assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_CASE_NOT_EDITABLE'
else:
raise AssertionError('confirmed case must be read-only')
def test_confirm_review_case_rejects_when_customer_unresolved(app):
"""客户未确认时不得创建 Task(阶段 4 fail-closed)。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-CONFIRM-NOCUST')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
schema = dict(snapshot['schema'])
definition = dict(schema['definition'])
definition['fields'] = [
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
]
schema['definition'] = definition
snapshot['schema'] = schema
run.input_snapshot_json = snapshot
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'A009'}]},
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092999'}]},
]}]}]}
db.session.add(ShippingNoticeCandidate(
candidate_no='CAND-REVIEW-NOCUST', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-no-customer', order_extraction_run_id=run.id,
structured_result_json={'customer': {'resolution_status': 'unresolved'}},
))
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
db.session.commit()
try:
confirm_review_case(
user_id=user.id, case_no=case.case_no, expected_draft_version=1,
idempotency_key='review-no-customer-1',
)
except Exception as exc:
# 关键断言:校验失败或建单前客户门禁均阻断;不得落 Task。
assert getattr(exc, 'code', None) in {
'SHIPPING.REVIEW_CONFIRM_VALIDATION_FAILED',
'SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
}
else:
raise AssertionError('confirm without customer must be rejected')
assert ShippingTask.query.filter_by(source_type='review_confirmation').count() == 0
def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app):
"""重路由读取最新规则与启停状态;人工决定不被静默覆盖;同幂等键只生效一次。"""
with app.app_context():
from app.models import ShippingAuditEvent
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REROUTE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
schema = dict(snapshot['schema'])
definition = dict(schema['definition'])
definition['fields'] = [
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
]
schema['definition'] = definition
snapshot['schema'] = schema
run.input_snapshot_json = snapshot
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'A003'}]},
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '1000123456'}]},
]}]}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
line_key = case.current_draft.lines_json[0]['line_key']
# 旧规则指向不存在源;人工已选定可用源。
db.session.add(ShippingInventoryRoutingRule(
rule_code='OLD_AWSSG', rule_name='Old AWS SG', scope='line', priority=80,
match_mode='all', status='published', action_type='add_source_candidates',
action_payload_json={'source_codes': ['DSV360_AWSSG']}, version=1,
conditions=[ShippingInventoryRoutingRuleCondition(
condition_group=1, source_kind='order_field', order_field_id='reservation-id',
operator='prefix', expected_value_json='1', sequence=1,
)],
))
db.session.commit()
set_line_inventory_candidates(
user_id=user.id, case_no=case.case_no, line_key=line_key,
source_codes=['DSV360_AWSDU'], reason='planner keep AWSDU',
expected_draft_version=case.current_draft.draft_version,
)
db.session.commit()
db.session.refresh(case.current_draft)
manual_version = int(case.current_draft.draft_version)
# 发布更高优先级新规则,指向可用源。
db.session.add(ShippingInventoryRoutingRule(
rule_code='NEW_AWSDU', rule_name='New AWSDU', scope='line', priority=120,
match_mode='all', status='published', action_type='add_source_candidates',
action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=18,
conditions=[ShippingInventoryRoutingRuleCondition(
condition_group=1, source_kind='order_field', order_field_id='reservation-id',
operator='prefix', expected_value_json='1', sequence=1,
)],
))
db.session.commit()
first = reroute_inventory_routing(
user_id=user.id, case_no=case.case_no, expected_draft_version=manual_version,
idempotency_key='reroute-key-1', line_key=line_key,
)
db.session.commit()
replay = reroute_inventory_routing(
user_id=user.id, case_no=case.case_no, expected_draft_version=manual_version,
idempotency_key='reroute-key-1', line_key=line_key,
)
# 关键断言:人工有效候选不变;规则建议更新;同幂等键不二次升版本。
projection = first['draft']['build_eligibility']['line_projections'][0]
assert projection['selection_mode'] == 'manual'
assert projection['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
assert 'DSV360_AWSDU' in (projection.get('rule_suggestion_source_codes') or [])
assert any(item.get('rule_code') == 'NEW_AWSDU' for item in (projection.get('rule_versions') or []))
assert replay['draft']['draft_version'] == first['draft']['draft_version']
assert ShippingOrderReviewCaseEvent.query.filter_by(
case_id=case.id, event_type='inventory_routing_rerouted',
).count() == 1
assert ShippingAuditEvent.query.filter_by(
review_case_no=case.case_no, action='inventory_routing_rerouted',
).count() >= 1
# [ASSERT] 新幂等键覆盖“最近一次”后,旧键携带最新版本重试仍只重放、不升版本。
second = reroute_inventory_routing(
user_id=user.id, case_no=case.case_no,
expected_draft_version=first['draft']['draft_version'],
idempotency_key='reroute-key-2', line_key=line_key,
)
db.session.commit()
version_after_second = second['draft']['draft_version']
reroute_events = ShippingOrderReviewCaseEvent.query.filter_by(
case_id=case.id, event_type='inventory_routing_rerouted',
).count()
assert reroute_events == 2
stale_replay = reroute_inventory_routing(
user_id=user.id, case_no=case.case_no,
expected_draft_version=version_after_second,
idempotency_key='reroute-key-1', line_key=line_key,
)
assert stale_replay['draft']['draft_version'] == version_after_second
assert ShippingOrderReviewCaseEvent.query.filter_by(
case_id=case.id, event_type='inventory_routing_rerouted',
).count() == reroute_events
# 采用规则建议后有效候选切到规则结果。
adopted = adopt_inventory_routing_suggestion(
user_id=user.id, case_no=case.case_no, line_key=line_key,
expected_draft_version=version_after_second,
idempotency_key='adopt-key-1', reason='accept latest rule',
)
db.session.commit()
adopted_proj = adopted['draft']['build_eligibility']['line_projections'][0]
assert adopted_proj['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
assert adopted_proj.get('suggestion_pending') is False
def test_inventory_routing_keep_manual_clears_pending_suggestion(app):
"""保留人工结果会清除 suggestion_pending,且不改有效候选。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-KEEP-MANUAL')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
snapshot = dict(run.input_snapshot_json)
schema = dict(snapshot['schema'])
definition = dict(schema['definition'])
definition['fields'] = [
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
]
schema['definition'] = definition
snapshot['schema'] = schema
run.input_snapshot_json = snapshot
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'A004'}]},
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '1000999999'}]},
]}]}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
line_key = case.current_draft.lines_json[0]['line_key']
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
set_line_inventory_candidates(
user_id=user.id, case_no=case.case_no, line_key=line_key,
source_codes=['DSV360_AWSDU'], reason='manual keep',
expected_draft_version=case.current_draft.draft_version,
)
db.session.commit()
db.session.refresh(case.current_draft)
# 人为制造 pending 建议差异:写入不同 suggestion 标记。
lines = list(case.current_draft.lines_json or [])
lines[0]['inventory_routing'] = {
**(lines[0].get('inventory_routing') or {}),
'suggestion_pending': True,
'rule_suggestion': {'source_codes': ['DSV360_AWSDU'], 'routing_status': 'resolved'},
}
case.current_draft.lines_json = lines
db.session.flush()
version = int(case.current_draft.draft_version)
kept = keep_manual_inventory_routing(
user_id=user.id, case_no=case.case_no, line_key=line_key,
expected_draft_version=version, idempotency_key='keep-key-1',
reason='keep planner decision',
)
db.session.commit()
proj = kept['draft']['build_eligibility']['line_projections'][0]
# 关键断言:有效候选仍为人工值,待确认建议已清除。
assert proj['selection_mode'] == 'manual'
assert proj['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
assert proj.get('suggestion_pending') is False
@@ -1223,3 +1223,78 @@ def test_dynamic_schema_rejects_quote_absent_from_frozen_and_legacy_text(app):
assert result['blocked_fields'] == ['part_number']
assert result['lines'] == [{}]
def test_optional_non_key_field_evidence_missing_is_diagnostic_only(app):
"""可选非关键字段证据不足:blocked_fields 为空,仍有 diagnostic Finding。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
addr = service.save_field({'field_code': 'ship_to_address', 'scope': 'header', 'value_type': 'string'}, actor_id=None)
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
addr_cfg = _config(addr['id'], '收货地址', value_type='string')
addr_cfg['required'] = False
addr_cfg['auto_create_key_field'] = False
published = _save_and_publish(draft, [
addr_cfg,
_config(part['id'], '内部料号', value_type='string'),
])
intake_id, documents, actor_id = _seed_documents()
document = documents[1]
document.extracted_text = 'Part No: ABC-123'
result = persist_dynamic_order(
raw_order={
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'header_fields': [{'field_id': addr['id'], 'observations': [{
'value': 'Somewhere', 'document_id': document.id, 'quote': 'not-in-text',
}]}],
'lines': [{'fields': [{'field_id': part['id'], 'observations': [{
'value': 'ABC-123', 'document_id': document.id, 'quote': 'Part No: ABC-123',
}]}]}],
},
intake_id=intake_id, snapshot_hash='o' * 64, documents=documents, actor_id=actor_id,
)
assert 'ship_to_address' not in (result.get('blocked_fields') or [])
findings = result.get('findings') or []
diagnostic = [
item for item in findings
if item.get('field_code') == 'ship_to_address' and item.get('severity') == 'diagnostic'
]
assert diagnostic, findings
assert diagnostic[0].get('blocks_current_action') is False
assert diagnostic[0].get('user_visible') is False
def test_key_field_quality_issue_still_blocks(app):
"""auto_create_key_field 字段证据不足必须进入 blocked_fields(即使 required=false)。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
part_cfg = _config(part['id'], '内部料号', value_type='string')
part_cfg.update({'required': False, 'auto_create_key_field': True, 'minimum_confidence': 0.95})
published = _save_and_publish(draft, [part_cfg])
intake_id, documents, actor_id = _seed_documents()
document = documents[1]
document.extracted_text = 'Part No: ABC-123'
result = persist_dynamic_order(
raw_order={
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'header_fields': [],
'lines': [{'fields': [{'field_id': part['id'], 'observations': [{
'value': 'ABC-123', 'document_id': document.id,
'quote': 'not-in-document-text', 'confidence': 0.99,
}]}]}],
},
intake_id=intake_id, snapshot_hash='p' * 64, documents=documents, actor_id=actor_id,
)
assert 'part_number' in (result.get('blocked_fields') or [])
blocking = [
item for item in (result.get('findings') or [])
if item.get('field_code') == 'part_number' and item.get('severity') == 'blocking'
]
assert blocking
@@ -3,8 +3,8 @@ tests/test_shipping_process_gate_contract.py
用途:锁定全门禁中断恢复 Phase 1/1.5 契约与依赖图完整性(编码、动作、失效范围、原因归属)。
依赖:process_gate_contract、process_gate_dependency。
逻辑:调用 assert_*_integrity;断言 19 个唯一门禁、原因码唯一 owning_gate、
字段阻断资格与 Excel 仅重生失效范围。
逻辑:调用 assert_*_integrity;断言 20 个唯一门禁(含 freight_upload_rpa)、
原因码唯一 owning_gate、字段阻断资格与 Excel 仅重生失效范围。
"""
from __future__ import annotations
@@ -31,16 +31,19 @@ def test_process_gate_contract_integrity():
"""
校验门禁契约无重复编码、序号连续且动作/状态闭环。
核心逻辑:直接调用契约自检;再断言恰好 19 个唯一 gate_code。
核心逻辑:直接调用契约自检;再断言恰好 20 个唯一 gate_code。
"""
# [STEP 1] 契约自检(重复码 / 序号 / 动作归属)
assert_process_gate_contract_integrity()
# [STEP 2] 冻结规模:19 门禁且集合与有序列表一致
assert len(PROCESS_GATE_DEFINITIONS) == 19
assert len(PROCESS_GATE_CODES) == 19
assert len(PROCESS_GATE_CODE_SET) == 19
# [STEP 2] 冻结规模:20 门禁(含 freight_upload_rpa)且集合与有序列表一致
assert len(PROCESS_GATE_DEFINITIONS) == 20
assert len(PROCESS_GATE_CODES) == 20
assert len(PROCESS_GATE_CODE_SET) == 20
assert set(PROCESS_GATE_CODES) == PROCESS_GATE_CODE_SET
assert 'freight_upload_rpa' in PROCESS_GATE_CODE_SET
assert owning_gate_for_reason('upload_rpa_pending') == 'freight_upload_rpa'
assert owning_gate_for_reason('manual_upload_pending') == 'manual_upload_handoff'
def test_inventory_source_routing_primary_retry_action():
@@ -93,5 +96,6 @@ def test_process_gate_dependency_integrity_and_excel_only_scope():
excel_only = compute_invalidated_gates('excel_regeneration_only')
assert 'inventory_matching' not in excel_only
assert 'artifact_generation' in excel_only
assert 'freight_upload_rpa' in excel_only
assert 'manual_upload_handoff' in excel_only
assert set(excel_only) == set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only'])
@@ -3,8 +3,8 @@ tests/test_shipping_process_gate_retry_cap.py
用途:验证门禁技术失败跨 force_new Job 累计重试上限,并在耗尽后收口 Attempt/Gate。
依赖:Flask testing app、run_shipping_process_gate handler、process_gate_service。
逻辑:mock claim_and_run 持续抛错;断言最多 TECHNICAL_RETRIES 次失败后
Attempt/Gate 进入 failed_terminal,且不再入队新的重试 Job。
逻辑:mock claim_and_run 持续抛错;按 failed Job 累计;断言 TECHNICAL_RETRIES 次后
Attempt/Gate 进入 failed_terminal、input_snapshot Hash 一致、且不再入队重试 Job。
"""
from __future__ import annotations
@@ -84,6 +84,11 @@ def test_technical_retries_cap_across_force_new_jobs(app):
assert attempt_final.error_code == 'TECHNICAL_RETRY_EXHAUSTED'
# 敏感 URL 不得原样落库
assert 'erp.example.com' not in str(attempt_final.error_summary or '')
# [ASSERT] 技术重试不得污染业务输入快照,Hash 须与正文一致
snap = attempt_final.input_snapshot_json if isinstance(attempt_final.input_snapshot_json, dict) else {}
assert 'technical_retry_count' not in snap
from app.services.shipping_notice.process_gate_service import _stable_hash
assert attempt_final.input_snapshot_hash == _stable_hash(snap)
failed_jobs = (
Job.query
@@ -0,0 +1,251 @@
"""
tests/test_shipping_review_confirm_auto_progress.py
用途:覆盖复核确认建单后自动推进的持久化调度与幂等补推。
依赖:pytest、Flask app fixture、order_review_confirmation_service、Job 模型。
逻辑:验证同事务入队、幂等回放在悬挂态补推、已推进后不再入队;
resolve_confirm_outcome 区分建单成功与推进失败。
"""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from app import db
from app.jobs.types import JobType
from app.models import Job, ShippingTask
from app.services.shipping_notice.order_review_confirmation_service import (
_task_needs_post_confirm_auto_progress,
schedule_auto_progress_after_review_confirm,
)
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
def test_resolve_confirm_outcome_distinguishes_progress_failure():
"""confirm_ok 成功 envelope 下必须用 confirm_outcome 区分推进失败。"""
from app.services.shipping_notice.order_review_confirmation_service import resolve_confirm_outcome
# 关键断言:推进失败不得与「已入队」共用 outcome。
assert resolve_confirm_outcome({'status': 'enqueue_failed', 'auto_progress_started': False}) == (
'confirmed_auto_progress_failed'
)
assert resolve_confirm_outcome({'status': 'queued', 'auto_progress_started': True}) == (
'confirmed_and_auto_progress_started'
)
assert resolve_confirm_outcome(None) == 'confirmed_auto_progress_not_scheduled'
def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monkeypatch):
"""已确认且任务仍 created+Extraction 时,投影需 needs_retry 供前端刷新恢复。"""
from app.services.shipping_notice import order_review_projection as projection
case = MagicMock(status='confirmed', confirmed_task_id=9)
stuck = MagicMock(task_no='SN-STUCK-1', process_status='created', current_order_extraction_id=3)
with app.app_context():
monkeypatch.setattr(projection.db.session, 'get', lambda model, pk: stuck)
summary = projection._project_post_confirm_auto_progress(case)
# 关键断言:刷新后可据此恢复琥珀色重试入口。
assert summary is not None
assert summary['task_no'] == 'SN-STUCK-1'
assert summary['needs_retry'] is True
assert summary['status'] == 'needs_retry'
def test_task_needs_post_confirm_auto_progress_requires_created_with_extraction():
"""仅 created 且已挂 Extraction 的任务需要确认后补推。"""
stuck = MagicMock(
process_status='created',
current_order_extraction_id=12,
)
progressed = MagicMock(
process_status='waiting_upload',
current_order_extraction_id=12,
)
shell = MagicMock(
process_status='created',
current_order_extraction_id=None,
)
assert _task_needs_post_confirm_auto_progress(stuck) is True
assert _task_needs_post_confirm_auto_progress(progressed) is False
assert _task_needs_post_confirm_auto_progress(shell) is False
assert _task_needs_post_confirm_auto_progress(None) is False
def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
"""commit=False 时写入 Job 但不提交,供与确认事务同提交。"""
with app.app_context():
task = ShippingTask(
task_no='SN-CONFIRM-AP-1',
user_id=1,
process_status='created',
current_order_extraction_id=99,
)
db.session.add(task)
db.session.flush()
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker')
schedule = schedule_auto_progress_after_review_confirm(
task_no=task.task_no,
idempotent_replay=False,
created_by_id=1,
commit=False,
)
assert schedule is not None
assert schedule.get('auto_progress_started') is True
job = (
db.session.query(Job)
.filter(
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_NOTICE_RUN.value,
Job.business_ref == task.task_no,
Job.status == 'queued',
)
.one()
)
job_id = int(job.id)
assert job_id > 0
# 关键断言:未 commit 前外层可 rollback,Job 行随之消失。
db.session.rollback()
assert db.session.get(Job, job_id) is None
def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkeypatch):
"""幂等回放在任务仍悬挂于 created 时必须补推,不能无条件跳过。"""
with app.app_context():
task = ShippingTask(
task_no='SN-CONFIRM-AP-2',
user_id=1,
process_status='created',
current_order_extraction_id=88,
)
db.session.add(task)
db.session.commit()
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker')
first = schedule_auto_progress_after_review_confirm(
task_no=task.task_no,
idempotent_replay=True,
created_by_id=1,
commit=True,
)
assert first is not None
assert first.get('auto_progress_started') is True
# 已有 active Job 时 dedupe 复用,仍视为已调度。
second = schedule_auto_progress_after_review_confirm(
task_no=task.task_no,
idempotent_replay=True,
created_by_id=1,
commit=True,
)
assert second is not None
assert second.get('auto_progress_started') is True
assert (
db.session.query(Job)
.filter(
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_NOTICE_RUN.value,
Job.business_ref == task.task_no,
Job.status.in_(('queued', 'running')),
)
.count()
== 1
)
def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch):
"""任务已离开 created 时幂等回放不再入队。"""
with app.app_context():
task = ShippingTask(
task_no='SN-CONFIRM-AP-3',
user_id=1,
process_status='waiting_upload',
current_order_extraction_id=77,
)
db.session.add(task)
db.session.commit()
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker')
schedule = schedule_auto_progress_after_review_confirm(
task_no=task.task_no,
idempotent_replay=True,
created_by_id=1,
commit=True,
)
assert schedule is None
assert (
db.session.query(Job)
.filter(
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
Job.business_ref == task.task_no,
)
.count()
== 0
)
def test_finalize_sync_auto_progress_swallows_execution_errors():
"""sync Job 抛错时必须返回 sync_execution_failed,不得向上抛出。"""
from app.services.shipping_notice.order_review_confirmation_service import (
finalize_sync_auto_progress_after_commit,
)
schedule = {
'auto_progress_started': True,
'status': 'queued',
'sync_pending_job_id': 42,
'enqueue_result': 'queued_sync_pending:42',
}
import app.services.shipping_notice.queue_service as queue_service
def _boom(_payload):
raise RuntimeError('sync job boom')
original = queue_service.run_shipping_notice_job
queue_service.run_shipping_notice_job = _boom # type: ignore[assignment]
try:
result = finalize_sync_auto_progress_after_commit(schedule)
finally:
queue_service.run_shipping_notice_job = original # type: ignore[assignment]
assert result is not None
assert result['status'] == 'sync_execution_failed'
assert result['auto_progress_started'] is True
assert result.get('sync_pending_job_id') is None
assert '确认建单已成功' in str(result.get('message') or '')
def test_run_single_task_auto_progresses_created_task_with_extraction(app, monkeypatch):
"""复核确认后的 created+Extraction 任务必须由编排器调用 auto_progress。"""
from app.models import ShippingBatch
from app.services.shipping_notice import batch_orchestrator
with app.app_context():
batch = ShippingBatch(batch_no='SB-CONFIRM-AP', file_count=1)
task = ShippingTask(
task_no='SN-CONFIRM-AP-4',
batch=batch,
user_id=1,
source_type='review_confirmation',
process_status='created',
current_order_extraction_id=66,
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_auto_progress(payload):
called['payload'] = payload
return {'status': 'ok', 'message': 'advanced'}
monkeypatch.setattr(batch_orchestrator, 'auto_progress', fake_auto_progress)
result = batch_orchestrator._run_single_task(task_no)
# 关键断言:与无抽取壳任务不同,确认建单任务不得停在「重新上传」。
assert result['status'] == 'ok'
assert isinstance(called.get('payload'), dict)
assert called['payload']['task_id'] == task_no
@@ -0,0 +1,71 @@
"""
tests/test_shipping_review_workbench_audit.py
用途:锁定复核工作台布局相关审计事件字典、敏感访问 action 与快照黑名单边界。
依赖:progress_audit_contract、pytest。
逻辑:校验阶段 0/5 冻结的写操作与敏感读取事件均在契约内;禁止键不得放宽。
"""
from __future__ import annotations
from app.services.shipping_notice.progress_audit_contract import (
AUDIT_FORBIDDEN_KEYS,
LLM_SUGGESTION_PROGRESS_EVENT_CODES,
REVIEW_WORKBENCH_ACCESS_ACTIONS,
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES,
WORKFLOW_ITEM_AUDIT_EVENT_TYPES,
)
def test_review_workbench_write_and_sensitive_events_are_frozen() -> None:
"""关键写操作与敏感读取事件必须出现在复核工作台字典中。"""
required = {
'review_draft_changed',
'review_confirmed',
'review_marked_non_order',
'review_marked_quality_issue',
'inventory_routing_rerouted',
'inventory_routing_suggestion_adopted',
'inventory_routing_manual_kept',
'llm_review_requested',
'llm_suggestion_accepted',
'llm_suggestion_modified',
'llm_suggestion_rejected',
'sensitive_evidence_viewed',
'review_evidence_focused',
'review_version_history_viewed',
'review_eligibility_details_viewed',
'review_workbench_opened',
'review_document_switched',
}
assert required.issubset(REVIEW_WORKBENCH_AUDIT_EVENT_TYPES)
assert required.issubset(WORKFLOW_ITEM_AUDIT_EVENT_TYPES)
def test_inventory_routing_events_are_in_workflow_audit_dictionary() -> None:
"""库存路由恢复三类写事件不得再游离于冻结字典之外。"""
for event_type in (
'inventory_routing_rerouted',
'inventory_routing_suggestion_adopted',
'inventory_routing_manual_kept',
):
assert event_type in WORKFLOW_ITEM_AUDIT_EVENT_TYPES
def test_llm_suggestion_codes_align_with_workbench_dictionary() -> None:
"""LLM 建议进度码须被复核工作台审计字典覆盖。"""
assert LLM_SUGGESTION_PROGRESS_EVENT_CODES.issubset(REVIEW_WORKBENCH_AUDIT_EVENT_TYPES)
def test_review_workbench_access_actions_cover_sensitive_reads() -> None:
"""PDF 预览与证据定位访问 action 必须冻结,供访问审计 metadata 对齐。"""
assert 'preview_order_review_document' in REVIEW_WORKBENCH_ACCESS_ACTIONS
assert 'view_order_review_evidence' in REVIEW_WORKBENCH_ACCESS_ACTIONS
assert 'view_order_review_version_history' in REVIEW_WORKBENCH_ACCESS_ACTIONS
assert 'view_order_review_eligibility_details' in REVIEW_WORKBENCH_ACCESS_ACTIONS
def test_audit_forbidden_keys_still_block_secrets_and_storage_urls() -> None:
"""普通审计账本禁止键不得因布局重构放宽。"""
for key in ('password', 'token', 'prompt', 'minio', 'object_url', 'secret'):
assert key in AUDIT_FORBIDDEN_KEYS
@@ -0,0 +1,74 @@
"""
tests/test_shipping_stp_progress_nodes.py
用途:验收阶段 4 固定 progress_nodes 投影——顺序、状态映射、货代节点非自动 RPA。
依赖:stp_progress_contract、types.SimpleNamespace。
逻辑:构造 Task 替身;断言节点码顺序与 WorkflowNodeStatus;禁止前端百分比语义。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.stp_progress_contract import (
STP_PROGRESS_NODE_DEFS,
derive_overall_node_status,
project_task_progress_nodes,
)
def test_progress_nodes_follow_fixed_order_and_manual_freight():
"""Excel 就绪后货代节点为 manual_takeover,不得投影为 running(首期无货代 RPA)。"""
task = SimpleNamespace(
customer_resolution_status='confirmed',
process_status='waiting_upload',
pending_human_reason=None,
match_status='matched',
review_status=None,
export_file_name='SN-001.xlsx',
)
nodes = project_task_progress_nodes(task)
assert [item['code'] for item in nodes] == [item['code'] for item in STP_PROGRESS_NODE_DEFS]
by_code = {item['code']: item['status'] for item in nodes}
# 关键断言:前序节点已成功,货代等待人工上传登记。
assert by_code['customer_confirm'] == 'succeeded'
assert by_code['task_create'] == 'succeeded'
assert by_code['inventory_prepare'] == 'succeeded'
assert by_code['inventory_match'] == 'succeeded'
assert by_code['freight_upload'] == 'manual_takeover'
assert by_code['freight_upload'] != 'running'
assert derive_overall_node_status(nodes) == 'manual_takeover'
def test_progress_nodes_mark_inventory_rpa_retrying():
"""库存 RPA 等待中投影为 retrying/running,匹配节点保持 pending。"""
task = SimpleNamespace(
customer_resolution_status='confirmed',
process_status='waiting_inventory',
pending_human_reason='rpa_pending',
match_status=None,
review_status=None,
export_file_name=None,
)
nodes = project_task_progress_nodes(task)
by_code = {item['code']: item['status'] for item in nodes}
assert by_code['inventory_rpa'] == 'retrying'
assert by_code['inventory_match'] == 'pending'
assert by_code['freight_upload'] == 'pending'
def test_progress_nodes_customer_pending_blocks_downstream():
"""客户未确认时下游库存节点保持 pending。"""
task = SimpleNamespace(
customer_resolution_status='pending',
process_status='created',
pending_human_reason=None,
match_status=None,
review_status=None,
export_file_name=None,
)
nodes = project_task_progress_nodes(task)
by_code = {item['code']: item['status'] for item in nodes}
assert by_code['customer_confirm'] == 'pending'
assert by_code['task_create'] == 'succeeded'
assert by_code['inventory_prepare'] == 'pending'
@@ -2,9 +2,15 @@
from app import db
from app.core.errors import ConflictError
from app.models import ShippingCase, ShippingTask, ShippingTaskEvent, ShippingTaskPurgeAudit
from app.models import (
ShippingAuditEvent,
ShippingCase,
ShippingTask,
ShippingTaskEvent,
ShippingTaskPurgeAudit,
User,
)
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.shipping_notice.task_disposition_service import (
archive_task,
move_task_to_recycle_bin,
@@ -39,6 +45,14 @@ def test_plain_created_task_can_be_deleted_and_restored(app):
assert task.deleted_at is not None
assert task_is_active(task) is False
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type='task_deleted').count() == 1
# 关键断言:统一审计双写稳定 reason_code,供审计中心筛选。
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_task_disposition',
task_no='SN-DISPOSITION-DELETE-001',
).order_by(ShippingAuditEvent.id.desc()).first()
assert audit is not None
assert audit.reason_code == 'task_cancelled_by_user'
assert audit.action == 'task_deleted'
restore_task_from_recycle_bin(task, actor_id=1, request_id='req-restore')
db.session.commit()
@@ -64,6 +78,12 @@ def test_internal_business_task_is_voided_before_recycle_bin(app):
assert task.lifecycle_status == 'voided'
assert task.void_reason == '重复建单'
assert task_disposition_capability(task, 'restore').allowed is False
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_task_disposition',
task_no='SN-DISPOSITION-VOID-001',
).order_by(ShippingAuditEvent.id.desc()).first()
assert audit is not None
assert audit.reason_code == 'task_voided_for_correction'
def test_external_fulfillment_can_only_be_archived(app):
@@ -82,6 +102,12 @@ def test_external_fulfillment_can_only_be_archived(app):
assert task.lifecycle_status == 'archived'
assert task.upload_status == 'running'
assert task_is_active(task) is False
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_task_disposition',
task_no='SN-DISPOSITION-EXTERNAL-001',
).order_by(ShippingAuditEvent.id.desc()).first()
assert audit is not None
assert audit.reason_code == 'task_archived'
def test_void_requires_reason_and_rejects_successor(app):
@@ -175,9 +201,11 @@ def test_workspace_list_hides_deleted_tasks_and_exposes_recycle_bin(app, client)
normal = client.get('/api/workspace/shipping-tasks', headers=headers).get_json()
recycle_bin = client.get('/api/workspace/shipping-tasks?lifecycle_status=deleted', headers=headers).get_json()
# 关键断言:默认查询仅活动任务,回收站查询仅已删除任务。
assert [item['task_no'] for item in normal['items']] == ['SN-DISPOSITION-LIST-ACTIVE']
assert [item['task_no'] for item in recycle_bin['items']] == ['SN-DISPOSITION-LIST-DELETED']
# 关键断言:列表走标准 envelope;默认查询仅活动任务,回收站查询仅已删除任务。
assert normal['success'] is True
assert recycle_bin['success'] is True
assert [item['task_no'] for item in normal['data']['items']] == ['SN-DISPOSITION-LIST-ACTIVE']
assert [item['task_no'] for item in recycle_bin['data']['items']] == ['SN-DISPOSITION-LIST-DELETED']
def test_workspace_voided_filter_includes_voided_recycle_bin_task(app, client):
@@ -195,7 +223,9 @@ def test_workspace_voided_filter_includes_voided_recycle_bin_task(app, client):
response = client.get('/api/workspace/shipping-tasks?lifecycle_status=voided', headers=headers)
# 关键断言:作废任务即使同时在回收站,仍可通过已作废筛选追溯。
assert [item['task_no'] for item in response.get_json()['items']] == ['SN-DISPOSITION-LIST-VOIDED']
payload = response.get_json()
assert payload['success'] is True
assert [item['task_no'] for item in payload['data']['items']] == ['SN-DISPOSITION-LIST-VOIDED']
def test_admin_can_purge_only_pure_deleted_task_and_audit_is_retained(app, client):
@@ -234,3 +234,41 @@ def test_pending_review_without_case_cannot_reparse(app):
assert 'reparse' not in payload['available_actions']
assert payload['reparse_kind'] is None
assert 'cancel' in payload['available_actions']
def test_upload_rpa_pending_projection_is_not_waiting_manual(app):
"""
RPA 运行中 lifecycle 仍可落在 manual_upload_pending 桶,但投影必须标明非人工待办。
"""
with app.app_context():
user, agent, session, _intake, document = _seed_run_input(suffix='WFP-RPA')
workflow = create_workflow(
conversation_id=session.session_id,
owner_user_id=int(user.id),
owner_agent_id=int(agent.id),
)
item = ensure_workflow_item_for_document(
workflow=workflow,
conversation_id=session.session_id,
owner_user_id=int(user.id),
document_id=int(document.id),
)
transition_item_status(
item=item,
lifecycle_status='manual_upload_pending',
stage='upload_rpa_pending',
actor_type='system',
actor_id='test',
)
db.session.commit()
payload = serialize_workflow_item(item)
# 关键断言:禁止调用方用 lifecycle 推断人工待办。
assert payload['lifecycle_status'] == 'manual_upload_pending'
assert payload['display_lifecycle_status'] == 'upload_rpa_pending'
assert payload['upload_phase'] == 'rpa_pending'
assert payload['is_waiting_manual_upload'] is False
workflow_payload = serialize_workflow(workflow, user_id=int(user.id), include_items=True)
assert workflow_payload['counts']['waiting_manual_upload'] == 0
assert workflow_payload['counts']['processing'] == 1
@@ -0,0 +1,93 @@
"""
tests/test_shipping_workspace_legacy_audit.py
用途:证明旧工作台写入口(retry / confirm-inventory-source)具备审计四要素。
依赖:Flask app/client fixture、ShippingTaskEvent、ShippingAuditEvent。
逻辑:模拟工作台 JWT 用户调用旧路由,断言操作人、时间、内容与前后快照均落库。
"""
from __future__ import annotations
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import (
ShippingAuditEvent,
ShippingCase,
ShippingCustomer,
ShippingTask,
ShippingTaskEvent,
User,
)
def _workspace_headers(app, username: str = 'legacy-audit-user') -> tuple[dict[str, str], int]:
"""签发工作台用户头,并返回 headers 与 user_id。"""
with app.app_context():
user = User.query.filter_by(username=username).first()
if user is None:
user = User(username=username, email=f'{username}@example.com', role='user')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}, int(user.id)
def test_workspace_retry_records_actor_and_snapshots(app, client):
"""retry 须写入 TaskEvent + ShippingAuditEvent,含操作人与前后快照。"""
headers, user_id = _workspace_headers(app, 'legacy-audit-retry')
with app.app_context():
customer = ShippingCustomer(standard_name='Legacy Audit Co', short_code='LGA', status='active')
case = ShippingCase(case_no='SC-LEGACY-AUDIT-RETRY', customer=customer)
task = ShippingTask(
task_no='SN-LEGACY-AUDIT-RETRY',
user_id=user_id,
shipping_case=case,
source_type='manual',
process_status='failed',
review_status='parse_review',
pending_human_reason='low_confidence',
error_message='timeout',
customer_resolution_status='confirmed',
raw_content='客户:ACME\nA001 x 1',
)
db.session.add_all([customer, case, task])
db.session.commit()
res = client.post(
'/api/workspace/shipping-tasks/SN-LEGACY-AUDIT-RETRY/retry',
headers=headers,
json={'comment': '人工重试'},
)
assert res.status_code == 200
envelope = res.get_json()
assert envelope['success'] is True
with app.app_context():
task = ShippingTask.query.filter_by(task_no='SN-LEGACY-AUDIT-RETRY').one()
event = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type='task_retry_requested')
.order_by(ShippingTaskEvent.id.desc())
.first()
)
# 关键断言:旧 retry 入口不再匿名,且前后状态可对比。
assert event is not None
assert event.actor_id == user_id
assert event.created_at is not None
assert event.before_json.get('status') == 'failed'
assert event.after_json.get('status') in {'created', 'parsed'}
audit = (
ShippingAuditEvent.query.filter_by(
aggregate_type='shipping_task',
aggregate_id='SN-LEGACY-AUDIT-RETRY',
action='retry_task',
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert audit is not None
assert int(audit.actor_id or 0) == user_id
assert audit.before_snapshot_json is not None
assert audit.after_snapshot_json is not None
assert audit.created_at is not None