feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

+10 -10
View File
@@ -29,9 +29,9 @@ def pytest_configure(config):
@pytest.fixture(autouse=True)
def _capture_legacy_order_rows_for_tests(monkeypatch):
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
from app.models import ShippingTask
from app.models import ShippingNotice
original_init = ShippingTask.__init__
original_init = ShippingNotice.__init__
legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date')
def _init(self, **kwargs):
@@ -44,11 +44,11 @@ def _capture_legacy_order_rows_for_tests(monkeypatch):
for key, value in header_values.items():
setattr(self, f'_test_{key}', value)
monkeypatch.setattr(ShippingTask, '__init__', _init)
monkeypatch.setattr(ShippingNotice, '__init__', _init)
for key in (*legacy_headers, 'lines_json'):
storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows'
monkeypatch.setattr(
ShippingTask,
ShippingNotice,
key,
property(
lambda task, name=storage: getattr(task, name, None),
@@ -189,11 +189,11 @@ def _shipping_test_default_destination(monkeypatch, request):
def seed_task_inventory_source(
task: "ShippingTask",
task: "ShippingNotice",
*,
source_code: str = "DSV360_AWSDU",
) -> None:
"""测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。"""
"""测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。"""
_ensure_test_task_dynamic_order(task)
from app.services.shipping_notice.inventory_source_rules import (
compute_routing_fingerprint,
@@ -225,7 +225,7 @@ def seed_task_inventory_source(
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
def _ensure_test_task_dynamic_order(task: "ShippingTask") -> None:
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
"""将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。"""
from decimal import Decimal
@@ -304,7 +304,7 @@ def _ensure_test_task_dynamic_order(task: "ShippingTask") -> None:
def seed_rpa_inventory_trigger(
task: "ShippingTask",
task: "ShippingNotice",
*,
run_no: str = "RUN-TEST-001",
trigger_path: str | None = None,
@@ -364,7 +364,7 @@ def inventory_csv_with_warehouse(
return buf
def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
return {
"source_code": str(task.inventory_source_code or ""),
@@ -388,7 +388,7 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
def rpa_callback_payload(
task: "ShippingTask",
task: "ShippingNotice",
file_path: str | Path,
*,
run_no: str = "RUN-TEST-001",
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Desensitized synthetic XFA datasets fixture for Phase 0 path/fingerprint tests.
Not a real customer packet; values mirror annotation expected.json structure only.
-->
<data>
<HEADER>
<EBELN>4510039227</EBELN>
<BEDAT>2026-07-07</BEDAT>
<WAERS>USD</WAERS>
<TOTAL_AMOUNT>26961.60</TOTAL_AMOUNT>
</HEADER>
<ITEMS>
<DATA>
<EBELP>00010</EBELP>
<MATNR>TEMP-S000218922</MATNR>
<MENGE>30.000</MENGE>
<NETPR>898.72 / 1</NETPR>
<PEINH>1</PEINH>
<AMOUNT>26961.60</AMOUNT>
<EINDT>2026-07-14</EINDT>
</DATA>
</ITEMS>
<ITEMS1>
<DATA>
<EBELP>00010</EBELP>
<MATNR>TEMP-S000218922</MATNR>
<MENGE>30.000</MENGE>
<NETPR>898.72 / 1</NETPR>
<PEINH>1</PEINH>
<AMOUNT>26961.60</AMOUNT>
<EINDT>2026-07-14</EINDT>
</DATA>
</ITEMS1>
</data>
@@ -0,0 +1,65 @@
{
"fixture_role": "annotation",
"fixture_id": "xfa-annotation-po-4510039227",
"content_identity": {
"logical_document_id": "annotation-4510039227",
"content_hash": "sha256:annotation-fixture-content-v1-not-real-pdf",
"note": "与 blind_test 的 content_hash / logical_document_id 必须完全独立;禁止兼作盲测。"
},
"document_kind": "xfa_hybrid",
"business_confirmed": true,
"business_confirmed_note": "字段预期来自实施方案与验收文档对真实样本 4510039227 的只读验证结论;正式 PDF 不入库,仅保留脱敏期望。",
"header": {
"customer_po_no": "4510039227",
"supplier_name": "DESENSITIZED_SUPPLIER",
"order_date": "2026-07-07",
"currency": "USD",
"total_amount": "26961.60"
},
"lines": [
{
"customer_po_line_no": "00010",
"material_no": "TEMP-S000218922",
"quantity_raw": "30.000",
"quantity": "30",
"uom": "PC",
"unit_price": "898.72",
"price_unit": "1",
"amount": "26961.60",
"delivery_date": "2026-07-14"
}
],
"collections": {
"authoritative_line_collection_path": "/data/ITEMS/DATA",
"mirror_collection_paths": ["/data/ITEMS1/DATA"],
"mirror_equals_authoritative_when_normalized": true
},
"paths": {
"customer_po_no": "/data/HEADER/EBELN",
"order_date": "/data/HEADER/BEDAT",
"currency": "/data/HEADER/WAERS",
"total_amount": "/data/HEADER/TOTAL_AMOUNT",
"customer_po_line_no": "/data/ITEMS/DATA/EBELP",
"material_no": "/data/ITEMS/DATA/MATNR",
"quantity": "/data/ITEMS/DATA/MENGE",
"unit_price": "/data/ITEMS/DATA/NETPR",
"amount": "/data/ITEMS/DATA/AMOUNT",
"delivery_date": "/data/ITEMS/DATA/EINDT"
},
"acroform_display_samples": {
"quantity": "30",
"amount": "26,961.6",
"delivery_date": "14/07/2026"
},
"normalization_expectations": {
"quantity": {"from": "30.000", "to": "30"},
"unit_price": {"from": "898.72 / 1", "to": "898.72"},
"price_unit": {"from": "1", "to": "1", "also_from_netpr_composite": true},
"amount": {"from": "26961.60", "to": "26961.60"},
"delivery_date": {"from": "2026-07-14", "to": "2026-07-14"}
},
"coverage_notes": {
"multi_line_coverage": "missing",
"multi_line_coverage_note": "试点仅 1 条明细;允许发布和试点,生产扩大前须补多明细样本。"
}
}
@@ -0,0 +1,41 @@
{
"fixture_role": "blind_test",
"fixture_id": "xfa-blind-test-po-independent-001",
"content_identity": {
"logical_document_id": "blind-test-independent-001",
"content_hash": "sha256:blind-test-fixture-content-v1-independent",
"note": "与 annotation 文件身份和内容哈希完全独立;真值不得从普通 DTO/审计/网络响应泄露。"
},
"document_kind": "xfa_hybrid",
"business_confirmed": true,
"header": {
"customer_po_no": "4510099999",
"supplier_name": "DESENSITIZED_SUPPLIER_BT",
"order_date": "2026-07-08",
"currency": "USD",
"total_amount": "1797.44"
},
"lines": [
{
"customer_po_line_no": "00010",
"material_no": "TEMP-S000299999",
"quantity_raw": "2.000",
"quantity": "2",
"uom": "PC",
"unit_price": "898.72",
"price_unit": "1",
"amount": "1797.44",
"delivery_date": "2026-07-20"
}
],
"collections": {
"authoritative_line_collection_path": "/data/ITEMS/DATA",
"mirror_collection_paths": ["/data/ITEMS1/DATA"],
"mirror_equals_authoritative_when_normalized": true
},
"required_accuracy": {
"required_fields": 1.0,
"line_count": 1.0,
"quantity_amount_date_normalization": 1.0
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"fixture_manifest_version": "shipping-xfa-golden.v1",
"roles": {
"annotation": {
"expected": "annotation/expected.json",
"datasets_sample": "annotation/datasets_sample.xml",
"pdf": null,
"pdf_note": "真实/脱敏 PDF 不入库;阶段 1+ 本地挂载后按 content_hash 校验。"
},
"blind_test": {
"expected": "blind_test/expected.json",
"pdf": null
}
},
"acceptance_fields": {
"customer_po_no": "4510039227",
"material_no": "TEMP-S000218922",
"quantity": "30",
"unit_price": "898.72",
"price_unit": "1",
"amount": "26961.60",
"delivery_date": "2026-07-14"
}
}
@@ -0,0 +1,120 @@
"""
backend/tests/performance/test_shipping_conversation_processing_load.py
用途:会话多任务 processing 投影与统一提交的负载冒烟(阶段 5)。
依赖:project_conversation_processing、submit_order_extraction、ShippingOrderProcessingRun。
逻辑:同会话植入约 20 个 OT;断言投影耗时门槛与结果稳定;提交幂等重放不增 Run。
"""
from __future__ import annotations
import time
import uuid
from datetime import datetime
from app import db
from app.models import ShippingOrderProcessingRun
from app.services.shipping_notice.conversation_processing_projection import (
project_conversation_processing,
)
from app.services.shipping_notice.order_extraction_run_service import (
submit_order_extraction,
)
from app.services.shipping_notice.order_schema.runtime import published_version
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _seed_parallel_runs(*, user, agent, session, count: int = 20) -> list[ShippingOrderProcessingRun]:
"""为同一会话轻量写入多个用户可见任务(跳过完整 Intake 解析链路)。"""
schema_version = published_version()
runs: list[ShippingOrderProcessingRun] = []
now = datetime.utcnow()
for index in range(count):
run_no = f'SNER-LOAD-{index:02d}-{uuid.uuid4().hex[:6].upper()}'
status = 'queued' if index % 3 == 0 else ('failed' if index % 3 == 1 else 'completed')
lifecycle = 'open' if status == 'queued' else ('frozen' if status == 'failed' else 'closed')
run = ShippingOrderProcessingRun(
run_no=run_no,
user_task_no=f'OT-{run_no}',
user_id=user.id,
owner_agent_id=agent.id,
parser_engine_version='load-test',
parser_policy_version='load-test',
auto_freeze_policy_json={'enabled': False},
conversation_id=session.session_id,
schema_version_id=schema_version.id,
request_snapshot_hash=f'hash-{index}-{uuid.uuid4().hex}',
request_snapshot_json={'intakes': []},
input_snapshot_hash=f'hash-{index}-{uuid.uuid4().hex}',
input_snapshot_json={'intakes': []},
idempotency_key=f'idem-load-{index}-{uuid.uuid4().hex}',
status=status,
phase=status,
input_lifecycle=lifecycle,
input_frozen_at=None if lifecycle == 'open' else now,
submission_ordinal=index + 1,
created_at=now,
updated_at=now,
last_activity_at=now,
)
db.session.add(run)
runs.append(run)
db.session.commit()
return runs
def test_processing_projection_for_twenty_tasks_meets_latency_budget(app):
"""约 20 个 OT 投影可重入;单次 P95 门槛放宽为 < 500ms(本地 SQLite 冒烟)。"""
with app.app_context():
user, agent, session, _intake, _ = _seed_run_input(suffix='PROC-LOAD')
_seed_parallel_runs(user=user, agent=agent, session=session, count=20)
latencies_ms: list[float] = []
summaries = []
for _ in range(10):
started = time.perf_counter()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
latencies_ms.append((time.perf_counter() - started) * 1000)
summaries.append(projection['summary']['total_tasks'])
assert summaries == [20] * 10
p95 = sorted(latencies_ms)[int(0.95 * (len(latencies_ms) - 1))]
assert p95 < 500, f'processing P95 {p95:.1f}ms exceeds 500ms budget; samples={latencies_ms}'
def test_submission_idempotent_replay_stays_under_latency_budget(app):
"""同 submission_id 连续重放不增 Run,且单次 < 800ms。"""
with app.app_context():
user, agent, session, intake, _ = _seed_run_input(suffix='SUB-LOAD')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-LOAD-IDEM-1',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
latencies_ms: list[float] = []
for _ in range(5):
started = time.perf_counter()
replay = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-LOAD-IDEM-1',
upload_batch_id=intake.upload_batch_id,
)
latencies_ms.append((time.perf_counter() - started) * 1000)
db.session.commit()
assert replay['reused'] is True
assert replay['run_no'] == first['run_no']
assert ShippingOrderProcessingRun.query.count() == 1
p95 = sorted(latencies_ms)[int(0.95 * (len(latencies_ms) - 1))]
assert p95 < 800, f'submission replay P95 {p95:.1f}ms exceeds 800ms; samples={latencies_ms}'
@@ -0,0 +1,50 @@
"""
backend/tests/performance/test_shipping_xfa_extraction_load.py
用途:阶段 6 XFA 解析资源上限与超时冒烟(不声称生产 5 日 shadow 已完成)。
依赖:xfa_dataset 安全解析与默认资源上限。
逻辑:构造超限 XML / 正常小样本;断言超限 fail-closed 且正常样本在预算内完成。
"""
from __future__ import annotations
import time
import pytest
from app.services.shipping_notice.document_layout.xfa_dataset import (
XfaDatasetParseError,
parse_xfa_datasets,
)
def _minimal_datasets_xml(*, depth: int = 2, nodes: int = 8) -> bytes:
"""生成可控深度/节点数的最小 datasets XML。"""
body = '<HEADER><EBELN>4510039227</EBELN></HEADER>'
open_tags = ''.join(f'<L{i}>' for i in range(depth))
close_tags = ''.join(f'</L{i}>' for i in reversed(range(depth)))
extras = ''.join(f'<N{i}>v</N{i}>' for i in range(max(0, nodes - depth - 2)))
xml = (
'<?xml version="1.0"?>'
f'<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">'
f'<xfa:data><data>{open_tags}{body}{extras}{close_tags}</data></xfa:data>'
f'</xfa:datasets>'
)
return xml.encode('utf-8')
def test_xfa_parse_respects_node_limit_fail_closed():
"""节点超限在限制点终止,不拖垮 Worker。"""
xml = _minimal_datasets_xml(depth=3, nodes=80)
with pytest.raises(XfaDatasetParseError):
parse_xfa_datasets(xml, limits={'max_xml_nodes': 20, 'max_xml_depth': 64, 'max_line_rows': 2000})
def test_xfa_normal_sample_parses_within_latency_budget():
"""正常小样本解析应在本地冒烟预算内完成(<< 30s)。"""
xml = _minimal_datasets_xml(depth=2, nodes=10)
started = time.perf_counter()
result = parse_xfa_datasets(xml, limits={'max_xml_nodes': 100000, 'max_xml_depth': 64, 'max_line_rows': 2000})
elapsed = time.perf_counter() - started
assert result is not None
assert elapsed < 5.0
@@ -27,7 +27,7 @@ from app.models import (
ShippingOrderSchemaVersion,
ShippingOrderCustomerMatch,
ShippingCustomer,
ShippingTask,
ShippingNotice,
User,
)
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
@@ -43,7 +43,7 @@ from app.services.shipping_notice.order_freeze_service import (
def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False, suffix: str = '001'):
"""创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。"""
user = User(username=f'snapshot-user-{suffix}', email=f'snapshot-user-{suffix}@example.test', password_hash='x')
task = ShippingTask(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7)
task = ShippingNotice(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order')
db.session.add_all([user, task, schema])
db.session.flush()
@@ -17,13 +17,13 @@ from app.models import (
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingCustomerShadowResolution,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderField,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingTask,
ShippingNotice,
User,
)
from tests.conftest import parse_api_data, parse_api_error
@@ -413,18 +413,18 @@ def test_shipping_customer_shadow_report_and_label_api(app, client):
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-SHADOW-API', asset_id=asset.id, user_id=admin.id, parser_version='v6', parse_status='parsed',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
classification='order_notice', parse_status='parsed',
)
db.session.add(document)
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate = ShippingOrderCandidate(
candidate_no='SNC-SHADOW-API', intake_id=intake.id, primary_document_id=document.id,
candidate_key='document:1', validation_status='ready',
)
@@ -474,7 +474,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending')
db.session.add_all([wrong, correct, case])
db.session.flush()
task = ShippingTask(
task = ShippingNotice(
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
source_type='manual', process_status='parsed', customer_resolution_status='pending',
)
+21 -17
View File
@@ -3,7 +3,8 @@ tests/test_chat_dify_start_inputs.py
用途:迭代 5 验收 — Executor / completions 向 Dify Start 注入 agent_runtime_context。
依赖:agent_runtime_context.bootstrap、chat.executors、models、pytest。
逻辑:覆盖 generic / shipping_notice / file_check 三类 Agent 的 Dify inputs 契约。
逻辑:覆盖 generic / shipping_notice / file_check 三类 Agent 的 Dify inputs 契约;
co8 后 shipping 用例仅挂 ShippingNotice(无 ShippingBatch)。
"""
from __future__ import annotations
@@ -11,14 +12,13 @@ from __future__ import annotations
import json
from types import SimpleNamespace
import pytest
from app.models import ShippingBatch, ShippingTask, User
from app.models import ShippingNotice, User
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.agent_runtime_context.bootstrap import load_context_adapters
from app.services.agent_runtime_context.registry import build_chat_dify_inputs
from app.services.chat.executors import stream_chat_via_executor
import pytest
@pytest.fixture(autouse=True)
@@ -77,7 +77,11 @@ def test_dify_executor_injects_generic_agent_runtime_context(app, monkeypatch):
def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch):
"""shipping_notice hybrid Agent 应注入含 refs 的 agent_runtime_context。"""
"""
shipping_notice hybrid Agent 应注入含 task refs 的 agent_runtime_context。
关键断言:co8 后无 batch_no;focus_object 为单票任务。
"""
from app import db
from app.services.agent_registry.handlers.bootstrap import load_handlers
@@ -94,26 +98,28 @@ def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch
with app.app_context():
load_handlers()
batch = ShippingBatch(
batch_no='SB-START-001',
conversation_id='conv-shipping-start-001',
current_focus_task_no='SN-START-001',
file_count=1,
user = User(
username='start-inputs-ship',
email='start-inputs-ship@example.com',
role='user',
status='active',
)
task = ShippingTask(
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no='SN-START-001',
batch=batch,
user_id=user.id,
conversation_id='conv-shipping-start-001',
source_type='manual',
process_status='created',
)
db.session.add_all([batch, task])
db.session.add(task)
db.session.commit()
ctx = ChatStreamContext(
query='继续',
display_query='继续',
user=SimpleNamespace(id=1),
user=SimpleNamespace(id=user.id),
agent=_agent(
agent_code='shipping_notice',
runtime_provider='hybrid',
@@ -125,18 +131,16 @@ def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch
adapter_hints={
'shipping_notice': {
'task_id': 'SN-START-001',
'batch_no': 'SB-START-001',
}
},
shipping_task_id='SN-START-001',
shipping_batch_no='SB-START-001',
)
list(stream_chat_via_executor(ctx))
payload = json.loads(captured['inputs'][AGENT_RUNTIME_CONTEXT_INPUT])
assert payload['agent_code'] == 'shipping_notice'
assert payload['refs']['task_no'] == 'SN-START-001'
assert payload['refs']['batch_no'] == 'SB-START-001'
assert 'batch_no' not in (payload.get('refs') or {})
assert payload['reference_context']['focus_object']['id'] == 'SN-START-001'
+19 -24
View File
@@ -8,6 +8,8 @@ from __future__ import annotations
import json
import pytest
from app import db
from app.models import Agent, ChatLog, User
@@ -48,21 +50,16 @@ def _create_user() -> User:
def _create_task_for_user(user_id: int) -> str:
from app.models import ShippingBatch, ShippingTask
"""创建无 batch 绑定的最小 ShippingNotice(co8 后 shipping_batches 已 DROP)。"""
from app.models import ShippingNotice
batch = ShippingBatch(
batch_no="BATCH-TURN-001",
user_id=user_id,
file_count=1,
)
task = ShippingTask(
task = ShippingNotice(
task_no="SN-20260706-ABCD1234",
batch=batch,
user_id=user_id,
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.add(task)
db.session.commit()
return task.task_no
@@ -158,24 +155,17 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkeypatch, tmp_path):
"""multipart 上传发货通知时,agent_id 应从 form 字段解析,而非 JSON body。"""
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_path):
"""
multipart 上传时 agent_id 应从 form 字段解析;create_batch_from_notices 已下线为 410。
关键断言:form 带 agent_id 时 run 能启动;建批动作固定 BATCHES_REMOVED(非 agent 解析失败)。
"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
monkeypatch.setattr(
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
lambda **kwargs: {
"status": "ok",
"batch_no": "SB-MULTIPART-001",
"data": {
"tasks": [{"task_id": "SN-MULTIPART-001"}],
"focus_task": {"task_no": "SN-MULTIPART-001"},
},
},
)
res = client.post(
"/api/chat/turns/stream",
@@ -199,8 +189,11 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkey
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "run.completed" in event_names
assert "run.failed" not in event_names
assert "run.failed" in event_names
assert "run.completed" not in event_names
failed = next(item for item in events if item.get("event") == "run.failed")
# 关键断言:SSE run.failed 顶层带业务 code(非嵌套 data)。
assert failed.get("code") == "SHIPPING.BATCHES_REMOVED"
def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch):
@@ -247,6 +240,7 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie
assert all('schema_preview' not in payload for payload in assistant_payloads)
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
"""shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
from io import BytesIO
@@ -298,6 +292,7 @@ def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatc
assert notice_items[0].get("source_content_hash")
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path):
"""相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。"""
from io import BytesIO
+44 -2
View File
@@ -624,13 +624,24 @@ def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch,
def text_content(self, **_kwargs) -> str:
return "FREIGHT-REF-001"
def evaluate(self, _script: str) -> str:
return '<div id="success">ok</div>'
class _Page:
url = "https://freight.example/upload"
def goto(self, url: str, **_kwargs) -> None:
events.append(("goto", url))
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
def content(self) -> str:
return "<html><body><div id='success'>ok</div></body></html>"
def screenshot(self, **_kwargs) -> bytes:
return b"PNG-BYTES"
class _Context:
def close(self) -> None:
events.append(("context_close", None))
@@ -643,7 +654,17 @@ def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch,
runtime_profile.mkdir()
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
assert worker._upload_shipment_with_browser(workbook) == "FREIGHT-REF-001"
result = worker._upload_shipment_with_browser(workbook)
assert result['reference'] == 'FREIGHT-REF-001'
evidence = result['success_evidence']
assert evidence['kind'] == 'configured_success_selector'
assert evidence['selector'] == '#success'
assert evidence['filename'] == workbook.name
assert evidence['reference'] == 'FREIGHT-REF-001'
assert evidence['observed_at']
assert evidence['page_url']
assert evidence['dom_snippet']
assert evidence['dom_sha256']
assert events[:4] == [
("goto", "https://freight.example/upload"),
("file", str(workbook)),
@@ -753,14 +774,35 @@ def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeyp
def click(self, **_kwargs) -> None:
return None
def evaluate(self, _script: str) -> str:
return '<em class="fa fa-circle success-color status-icon"></em>'
class _Page:
url = "https://dsv.example/history"
def get_by_text(self, _text: str, **_kwargs) -> _Locator:
return _Locator()
def evaluate(self, _script: str, _arg: dict) -> dict:
return {"found": True, "succeeded": True, "reference": "556833"}
assert worker._wait_for_dsv_upload_history_receipt(_Page(), "DUBH26072304.xlsx") == "556833"
def locator(self, _selector: str) -> _Locator:
return _Locator()
def content(self) -> str:
return "<html><body>history</body></html>"
def screenshot(self, **_kwargs) -> bytes:
return b"PNG"
result = worker._wait_for_dsv_upload_history_receipt(_Page(), "DUBH26072304.xlsx")
assert result["reference"] == "556833"
evidence = result["success_evidence"]
assert evidence["kind"] == "dsv_history_green_dom"
assert evidence["filename"] == "DUBH26072304.xlsx"
assert evidence["dom_snippet"]
assert evidence["dom_sha256"]
assert evidence["page_url"]
def test_dsv_upload_falls_back_to_apps_menu(monkeypatch):
@@ -41,7 +41,7 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
seed = ShippingOrderDocumentProfile(
profile_code='SEED_PROFILE', display_name='Seed', version=1, status='draft',
schema_version_id=schema.id, structure_fingerprint='a' * 64,
definition_json={}, template_mode='coordinate_v2', lock_version=1,
definition_json={}, template_mode='coordinate', lock_version=1,
)
db.session.add(seed)
db.session.commit()
@@ -73,7 +73,7 @@ def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
seed = ShippingOrderDocumentProfile(
profile_code='SEED_BAD', display_name='Seed', version=1, status='draft',
schema_version_id=schema.id, structure_fingerprint='b' * 64,
definition_json={}, template_mode='coordinate_v2', lock_version=1,
definition_json={}, template_mode='coordinate', lock_version=1,
)
db.session.add(seed)
db.session.commit()
@@ -84,3 +84,74 @@ def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
assert ShippingOrderDocumentProfile.query.count() == 1
assert ShippingOrderDocumentProfileDraftRevision.query.count() == 0
assert ShippingOrderDocumentProfileEditLease.query.count() == 0
def test_wizard_xfa_mode_requires_authoritative_collection_not_table(app, monkeypatch):
"""关键断言:XFA 样本向导拒绝缺失权威集合,且不要求 main_table_id。"""
from hashlib import sha256
from app.models import User
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf, persist_xfa_structure_analysis
from app.services.shipping_notice.document_layout.xfa_dataset import _path_id_for
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: pdf_bytes)
with app.app_context():
user = User(username='xfa-create', email='xfa-create@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
schema = _schema_version()
content_hash = sha256(pdf_bytes).hexdigest()
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
asset = FileAsset(
asset_no='FA-XFA-WIZ', owner_user_id=user.id, original_filename='xfa.pdf',
storage_provider='minio', storage_bucket='test', storage_key='xfa.pdf',
content_hash=content_hash, file_size=len(pdf_bytes), mime_type='application/pdf',
upload_status='ready', lifecycle_status='referenced',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-XFA-WIZ', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='xfa.pdf', filename='xfa.pdf', content_hash=content_hash,
classification='supporting', parse_status='parsed',
)
db.session.add(document)
db.session.flush()
outcome = analyze_xfa_pdf(pdf_bytes)
layout = dict(outcome.snapshot)
layout['status'] = 'ready'
layout['provider'] = 'xfa'
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
layout_version = record_inline_layout_snapshot(document, layout)
persist_xfa_structure_analysis(
document_id=document.id, layout_version_id=layout_version.id,
source_content_hash=content_hash, outcome=outcome,
)
db.session.commit()
with pytest.raises(Exception) as missing:
creation_service.complete_wizard({
'display_name': 'XFA', 'schema_version_id': schema.id, 'document_id': document.id,
'browser_session_id': 'tab', 'operation_id': 'op-missing-auth',
}, actor_id=user.id)
assert getattr(missing.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
created = creation_service.complete_wizard({
'display_name': 'XFA', 'schema_version_id': schema.id, 'document_id': document.id,
'authoritative_collection_path_id': _path_id_for('/data/ITEMS/DATA'),
'browser_session_id': 'tab', 'operation_id': 'op-xfa-ok',
}, actor_id=user.id)
assert created['template_mode'] == 'xfa_dataset'
assert ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=created['id'], sample_role='annotation', table_id=None,
).count() == 1
@@ -69,7 +69,6 @@ def _anchor(anchor_id: str, text: str) -> dict:
def _definition() -> dict:
"""构造具备表格、订单字段、终止与排除区的最小可比较定义。"""
return {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {
'document_type': 'purchase_order',
'page_pattern': 'one_or_more',
@@ -152,7 +151,7 @@ def _detail(*, profile_id: int, profile_code: str, version: int, definition: dic
'definition': definition,
'checksum': f'{version}' * 64,
'migration_status': 'normal',
'template_mode': 'coordinate_v2',
'template_mode': 'coordinate',
'schema_summary': {'id': 1, 'version': 1, 'checksum': 'a' * 64},
'frozen_evidence': {'status': 'ready', 'sample_count': sample_count, 'frozen_sample_count': sample_count, 'audit_ready': True},
'auto_freeze_qualification': {
@@ -186,7 +185,7 @@ def _profile(
structure_fingerprint=(str(version) * 64)[:64],
definition_json=definition,
checksum=(str(version) * 64)[:64] if status in {'published', 'retired'} else None,
template_mode='coordinate_v2',
template_mode='coordinate',
published_at=datetime.utcnow() if status == 'published' else None,
retired_at=datetime.utcnow() if status == 'retired' else None,
lock_version=1,
@@ -18,14 +18,14 @@ from app.models import (
Agent,
FileAsset,
Job,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderExtractionPlan,
ShippingOrderExtractionRouteDecision,
ShippingOrderExtractionRun,
ShippingOrderExtractionUnit,
ShippingOrderProcessingPlan,
ShippingOrderRouteDecision,
ShippingOrderProcessingRun,
ShippingOrderProcessingUnit,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
@@ -80,14 +80,13 @@ def _profile(schema_version_id: int, *, profile_code: str = 'GOV_PROFILE', versi
schema_version_id=schema_version_id,
structure_fingerprint='b' * 64,
definition_json={
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'document_type': 'purchase_order', 'page_pattern': 'one_or_more', 'required_anchors': [], 'optional_anchors': [], 'minimum_score': 1, 'minimum_margin': 0},
'table_regions': [],
'order_field_layouts': [],
'draft_unbound_order_field_layouts': [],
},
checksum='c' * 64,
template_mode='coordinate_v2',
template_mode='coordinate',
published_at=datetime.utcnow(),
lock_version=1,
)
@@ -96,7 +95,7 @@ def _profile(schema_version_id: int, *, profile_code: str = 'GOV_PROFILE', versi
return row
def _document_and_intake(user_id: int, *, suffix: str) -> tuple[ShippingNoticeIntake, ShippingNoticeDocument]:
def _document_and_intake(user_id: int, *, suffix: str) -> tuple[ShippingOrderIntake, ShippingOrderDocument]:
"""创建 usage 投影需要的最小 Intake/Document。"""
asset = FileAsset(
asset_no=f'FA-GOV-{suffix}',
@@ -113,7 +112,7 @@ def _document_and_intake(user_id: int, *, suffix: str) -> tuple[ShippingNoticeIn
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f'SNI-GOV-{suffix}',
asset_id=asset.id,
user_id=user_id,
@@ -123,7 +122,7 @@ def _document_and_intake(user_id: int, *, suffix: str) -> tuple[ShippingNoticeIn
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
@@ -142,7 +141,7 @@ def _run_context(
schema_version_id: int,
*,
suffix: str,
) -> tuple[User, Agent, ShippingOrderExtractionRun, ShippingOrderExtractionPlan]:
) -> tuple[User, Agent, ShippingOrderProcessingRun, ShippingOrderProcessingPlan]:
"""创建 usage 投影需要的最小 Run。"""
user = User(username=f'usage-user-{suffix}', email=f'usage-user-{suffix}@example.com', role='admin', status='active')
agent = Agent(
@@ -155,7 +154,7 @@ def _run_context(
)
db.session.add_all([user, agent])
db.session.flush()
run = ShippingOrderExtractionRun(
run = ShippingOrderProcessingRun(
run_no=f'RUN-{suffix}',
user_id=user.id,
owner_agent_id=agent.id,
@@ -171,7 +170,7 @@ def _run_context(
)
db.session.add(run)
db.session.flush()
plan = ShippingOrderExtractionPlan(
plan = ShippingOrderProcessingPlan(
run_id=run.id,
plan_version='plan.v1',
input_snapshot_hash=run.input_snapshot_hash,
@@ -291,7 +290,7 @@ def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, adm
db.session.add_all([job_one, job_two, job_three])
db.session.flush()
unit_one = ShippingOrderExtractionUnit(
unit_one = ShippingOrderProcessingUnit(
plan_id=plan.id,
intake_id=intake_one.id,
document_id=document_one.id,
@@ -301,7 +300,7 @@ def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, adm
status='candidate_ready',
attempt_count=2,
)
unit_two = ShippingOrderExtractionUnit(
unit_two = ShippingOrderProcessingUnit(
plan_id=plan.id,
intake_id=intake_two.id,
document_id=document_two.id,
@@ -317,7 +316,7 @@ def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, adm
plan.unit_count = 2
db.session.add_all([
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit_one.id,
job_id=job_one.id,
@@ -339,7 +338,7 @@ def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, adm
candidate_summary_json=[],
fallback_reason_codes_json=[],
),
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit_one.id,
job_id=job_two.id,
@@ -361,7 +360,7 @@ def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, adm
candidate_summary_json=[],
fallback_reason_codes_json=[],
),
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit_two.id,
job_id=job_three.id,
@@ -398,7 +397,7 @@ def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, adm
assert payload['items'][0]['run_no'] == 'RUN-USAGE'
assert payload['items'][0]['identity_match_mode'] in {'direct_profile_id', 'snapshot_identity_match'}
assert {item['identity_match_mode'] for item in payload['items']} == {'direct_profile_id', 'snapshot_identity_match'}
assert all(item['diagnostic_entry']['route_name'] == 'AdminShippingOrderExtractionRuns' for item in payload['items'])
assert all(item['diagnostic_entry']['route_name'] == 'AdminShippingOrderProcessingRuns' for item in payload['items'])
assert all(item['document_label'] != 'usage-ONE.pdf' for item in payload['items'])
with app.app_context():
@@ -425,7 +424,7 @@ def test_retired_profile_usage_route_still_returns_historical_records(app, admin
db.session.add(job)
db.session.flush()
unit = ShippingOrderExtractionUnit(
unit = ShippingOrderProcessingUnit(
plan_id=plan.id,
intake_id=intake.id,
document_id=document.id,
@@ -439,7 +438,7 @@ def test_retired_profile_usage_route_still_returns_historical_records(app, admin
db.session.flush()
plan.unit_count = 1
db.session.add(
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -0,0 +1,51 @@
"""
tests/test_order_document_profile_overlap_summary.py
用途:验证跨模板重叠摘要聚合逻辑的通过/失败判定。
依赖:order_document_profile_validation_service.build_cross_template_overlap_summary。
逻辑:用纯 outcome 输入覆盖自命中率、误命中、歧义与 parse 失败分支。
"""
from __future__ import annotations
from app.services.shipping_notice.order_document_profile_validation_service import build_cross_template_overlap_summary
def test_overlap_summary_passes_when_all_self_unique():
"""关键断言:训练 100% 自命中且无冲突时应 passed。"""
status, summary, snapshot = build_cross_template_overlap_summary(
profile_code='PO_A',
profile_version=2,
thresholds={'minimum_score': 0.9, 'minimum_margin': 0.12, 'evidence_coverage_minimum': 0.7},
training_outcomes=[{
'self_unique': True, 'false_hit_other': False, 'ambiguous': False,
'evidence_coverage': 0.95, 'margin': 0.2, 'score': 0.96,
'coverage_ok': True, 'margin_ok': True, 'score_ok': True, 'parse_failed': False,
}],
blind_outcomes=[],
reverse_outcomes=[],
)
assert status == 'passed'
assert summary['self_unique_hit_rate_training'] == 1.0
assert summary['false_hit_other_count'] == 0
assert snapshot['conflict_profiles'] == []
def test_overlap_summary_fails_on_false_hit_and_builds_conflicts():
"""关键断言:误命中其他模板时 failed 且生成 conflict_profiles。"""
status, summary, snapshot = build_cross_template_overlap_summary(
profile_code='PO_A',
profile_version=2,
thresholds={'minimum_score': 0.9, 'minimum_margin': 0.12, 'evidence_coverage_minimum': 0.7},
training_outcomes=[{
'self_unique': False, 'false_hit_other': True, 'ambiguous': False,
'evidence_coverage': 0.95, 'margin': 0.2, 'score': 0.96,
'coverage_ok': True, 'margin_ok': True, 'score_ok': True, 'parse_failed': False,
'matched_profile_code': 'PO_B', 'matched_version': 1,
}],
blind_outcomes=[],
reverse_outcomes=[],
)
assert status == 'failed'
assert summary['false_hit_other_count'] == 1
assert snapshot['conflict_profiles'][0]['profile_code'] == 'PO_B'
assert 'false_hit' in snapshot['conflict_profiles'][0]['reason_codes']
@@ -15,7 +15,7 @@ import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ShippingOrderDocumentProfileSample, ShippingNoticeDocument, User
from app.models import FileAsset, ShippingOrderDocumentProfileSample, ShippingOrderDocument, User
from app.services.shipping_notice import document_profile_quality_service as quality_service
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
from app.services.shipping_notice import order_document_profile_service as profile_service
@@ -120,6 +120,19 @@ def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatc
assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND'
def test_publishing_profile_retains_sample_asset_for_history_preview(app, monkeypatch):
"""发布冻结样本必须清除临时 TTL,否则历史版本过期后无法读取 PDF。"""
profile_id, _sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
with app.app_context():
document = db.session.get(ShippingOrderDocument, document_id)
asset = db.session.get(FileAsset, document.asset_id)
assert asset is not None
assert int(asset.reference_count or 0) == 1
assert asset.lifecycle_status == 'referenced'
assert asset.expires_at is None
assert profile_id > 0
def test_frozen_sample_preview_rejects_unfrozen_sample_binding(app, monkeypatch, admin_headers_factory):
"""未发布样本没有冻结证据时,详情页样本画布必须显式报错而不是降级读取当前文档。"""
with app.app_context():
@@ -152,7 +165,7 @@ def test_frozen_sample_preview_uses_frozen_layout_instead_of_current_layout(app,
"""文档后来出现新 current layout 时,历史版本只读画布仍必须绑定发布时冻结的 layout_version。"""
profile_id, sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
with app.app_context():
document = db.session.get(ShippingNoticeDocument, document_id)
document = db.session.get(ShippingOrderDocument, document_id)
assert document is not None
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1',
@@ -281,3 +294,88 @@ def test_frozen_sample_region_diagnostics_reads_only_configured_regions_in_visua
assert set(by_id['plant_value']) == {
'region_id', 'kind', 'label', 'recognized_value', 'configured_value', 'matches_configured',
}
def test_frozen_sample_region_diagnostics_without_coordinate_evidence_returns_empty(app, monkeypatch):
"""缺少字符坐标证据时诊断为空,但不能把可预览 PDF 误报为页面不存在。"""
profile = SimpleNamespace(id=9, definition_json={})
sample = SimpleNamespace(id=8)
document = SimpleNamespace(id=7)
layout = SimpleNamespace(payload_json={'tables': []})
monkeypatch.setattr(
preview_service, '_frozen_sample_context',
lambda **_kwargs: (profile, sample, document, layout, SimpleNamespace()),
)
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
with app.app_context():
result = preview_service.frozen_sample_region_diagnostics(
9, sample_binding_id=8, page_no=1, actor_id=1,
)
assert result == {'sample_binding_id': 8, 'page_no': 1, 'items': []}
def test_frozen_sample_region_diagnostics_recovers_historical_pdf_page_coordinates(app, monkeypatch):
"""历史冻结布局仅有 table glyph 时,应从同哈希原 PDF 临时恢复整页坐标并显示字段值。"""
profile = SimpleNamespace(id=9, definition_json={
'document_match': {'required_anchors': []},
'table_regions': [],
'draft_unbound_order_field_layouts': [],
'order_field_layouts': [{
'layout_id': 'po-number', 'field_code': 'customer_po_number',
'page_scope': 'first_page', 'page_no': None, 'anchor': None,
'absolute_value_region': None,
'fallback_value_region': {'x0': .45, 'y0': .1, 'x1': .9, 'y1': .3},
}],
})
sample = SimpleNamespace(id=8)
document = SimpleNamespace(id=7, filename='historical.pdf')
asset = SimpleNamespace(id=6)
layout = SimpleNamespace(payload_json={
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {'tables': {'table-1': [{'text': 'table-only'}]}},
})
characters = [
SimpleNamespace(model_dump=lambda mode='json', char=char, index=index: {
'text': char,
'bbox': {'x0': 100 + index * 8, 'y0': 12, 'x1': 107 + index * 8, 'y1': 22},
})
for index, char in enumerate('1000050215')
]
monkeypatch.setattr(
preview_service, '_frozen_sample_context',
lambda **_kwargs: (profile, sample, document, layout, asset),
)
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-historical')
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content, render_images=False: [SimpleNamespace(
page_no=1, width=200, height=100, characters=characters,
)],
)
with app.app_context():
result = preview_service.frozen_sample_region_diagnostics(
9, sample_binding_id=8, page_no=1, actor_id=1,
)
assert result['items'][0]['region_id'] == 'po-number'
assert result['items'][0]['recognized_value'] == '1000050215'
def test_publish_freeze_requires_complete_page_coordinate_evidence():
"""新发布版本只有 table glyph 时不得视为完整,pages/page_glyphs/source 齐全后才可冻结。"""
incomplete = {
'coordinate_evidence': {'tables': {'table-1': [{'text': 'table-only'}]}},
}
complete = {
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': [{'text': 'A'}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
assert not profile_service._layout_has_page_coordinate_evidence(incomplete, page_nos={1})
assert profile_service._layout_has_page_coordinate_evidence(complete, page_nos={1})
@@ -9,11 +9,18 @@ from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.extensions import db
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileValidationRun
from app.models import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileValidationRun,
User,
)
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
from app.services.shipping_notice import order_document_profile_service as profiles
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
from tests.test_shipping_order_document_profile_service import _data, _schema_version
@@ -33,14 +40,65 @@ def _passing_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun:
return row
def _signature_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun:
"""构造有效 layout_signature 运行并写入 Profile 轻量引用。"""
row = ShippingOrderDocumentProfileValidationRun(
profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'],
definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'],
run_type='layout_signature', status='passed',
summary_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'},
result_snapshot_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'},
operation_id='signature-validation',
)
db.session.add(row); db.session.flush()
entity = db.session.get(ShippingOrderDocumentProfile, profile['id'])
entity.matching_signature_run_id = row.id
entity.matching_signature_checksum = 'sig-checksum'
entity.matching_signature_version = 'order-profile-layout-signature'
db.session.commit()
return row
def _overlap_run(profile: dict, *, status: str = 'passed') -> ShippingOrderDocumentProfileValidationRun:
"""构造 cross_template_overlap 运行摘要。"""
row = ShippingOrderDocumentProfileValidationRun(
profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'],
definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'],
run_type='cross_template_overlap', status=status,
summary_json={
'matcher_policy_version': 'profile-layout-matcher',
'self_unique_hit_rate_training': 1.0,
'self_unique_hit_rate_blind': 1.0,
'false_hit_other_count': 0,
'reverse_false_hit_count': 0,
'ambiguous_count': 0,
'min_evidence_coverage': 0.9,
'min_margin': 0.2,
'parse_validation_failed_count': 0,
'sample_role_pollution': False,
'thresholds': {'minimum_score': 0.9, 'minimum_margin': 0.12, 'evidence_coverage_minimum': 0.7},
},
result_snapshot_json={'conflict_profiles': []},
operation_id='overlap-validation',
)
db.session.add(row); db.session.commit()
return row
def test_report_invalidates_when_draft_changes(app, monkeypatch):
"""关键断言:报告冻结 lock/checksum,草稿任何有效保存后查询立即变 invalidated。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-create')
lease = _lease(draft['id']); run = _passing_run(draft)
report = checks.create_report(draft['id'], data={'validation_run_id': run.id}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-report')
changed = _data(schema.id); changed['expected_lock_version'] = draft['lock_version']; changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = .62
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft); overlap = _overlap_run(draft)
monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'})
report = checks.create_report(
draft['id'], data={'validation_run_id': run.id, 'overlap_validation_run_id': overlap.id},
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-report',
)
changed = _data(schema.id)
changed['expected_lock_version'] = draft['lock_version']
changed['display_name'] = f"{draft['display_name']} revised"
profiles.save_draft(changed, actor_id=None, profile_id=draft['id'], browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-change', enforce_lease=True)
assert checks.get_report(draft['id'], report['report_no'])['status'] == 'invalidated'
@@ -61,8 +119,13 @@ def test_report_consumes_once_after_each_warning_confirmation(app, monkeypatch):
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
# 本测试聚焦报告消费原子性;样本证据冻结由既有发布服务测试单独覆盖。
monkeypatch.setattr('app.services.shipping_notice.order_document_profile_service._freeze_profile_sample_evidence', lambda *_args, **_kwargs: 0)
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-consume-create'); lease = _lease(draft['id']); run = _passing_run(draft)
report = checks.create_report(draft['id'], data={'validation_run_id': run.id}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume-report')
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-consume-create')
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft); overlap = _overlap_run(draft)
monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'})
report = checks.create_report(
draft['id'], data={'validation_run_id': run.id, 'overlap_validation_run_id': overlap.id},
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume-report',
)
keys = [str(item['key']) for item in report['warning_items']]
if keys:
with pytest.raises(Exception):
@@ -71,3 +134,125 @@ def test_report_consumes_once_after_each_warning_confirmation(app, monkeypatch):
retried = checks.consume_report(draft['id'], report['report_no'], data={'confirmed_warning_keys': keys}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume')
assert published['status'] == retried['status'] == 'published'
assert db.session.get(ShippingOrderDocumentProfile, draft['id']).status == 'published'
def test_report_blocks_when_signature_missing(app, monkeypatch):
"""关键断言:缺少版面签名时发布检查报告含 signature_required 阻断项。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
monkeypatch.setattr(
validation_service, '_resolve_layout_signature_run',
lambda *args, **kwargs: (_ for _ in ()).throw(
ValidationError(
'Layout signature is required before overlap validation',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_REQUIRED',
)
),
)
monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': 0, 'status': 'failed'})
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-sig-create')
lease = _lease(draft['id']); run = _passing_run(draft)
report = checks.create_report(
draft['id'], data={'validation_run_id': run.id}, actor_id=None,
browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-sig-report',
)
keys = {str(item.get('key')) for item in report['blocking_items']}
assert 'signature_required' in keys or 'overlap_validation_required' in keys
def test_report_blocks_when_overlap_failed(app, monkeypatch):
"""关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-overlap-create')
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft)
failed_overlap = _overlap_run(draft, status='failed')
monkeypatch.setattr(
validation_service, 'run_cross_template_overlap',
lambda *args, **kwargs: {'id': failed_overlap.id, 'status': 'failed', 'stored_status': 'failed'},
)
report = checks.create_report(
draft['id'], data={'validation_run_id': run.id, 'overlap_validation_run_id': failed_overlap.id},
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-overlap-report',
)
keys = {str(item.get('key')) for item in report['blocking_items']}
assert 'overlap_validation_stale' in keys or 'overlap_validation_required' in keys or 'self_match_not_unique' in keys
assert report['overlap_validation_run_id'] == failed_overlap.id
def test_report_invalidates_when_signature_cleared(app, monkeypatch):
"""关键断言:草稿签名引用清空后既有报告查询即 invalidated。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-clear-create')
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft)
overlap = _overlap_run(draft)
monkeypatch.setattr(
validation_service, 'run_cross_template_overlap',
lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'},
)
report = checks.create_report(
draft['id'], data={'validation_run_id': run.id, 'overlap_validation_run_id': overlap.id},
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-clear-report',
)
entity = db.session.get(ShippingOrderDocumentProfile, draft['id'])
profiles.clear_matching_signature_refs(entity, actor_id=None, reason='test_clear')
db.session.commit()
refreshed = checks.get_report(draft['id'], report['report_no'])
assert refreshed['status'] == 'invalidated'
def test_consume_report_blocks_editor_self_approval(app, monkeypatch):
"""职责分离:最近映射编辑者不得消费自己的发布检查报告。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._freeze_profile_sample_evidence',
lambda *_args, **_kwargs: 0,
)
editor = User(username='split-editor', email='split-editor@test.local', password_hash='x')
db.session.add(editor)
db.session.commit()
schema = _schema_version()
draft = profiles.save_draft(_data(schema.id), actor_id=editor.id, operation_id='pc-sod-create')
db.session.add(ShippingOrderDocumentProfileAudit(
profile_id=draft['id'],
event_type='xfa_mapping_saved',
actor_id=editor.id,
detail_json={'operation_id': 'pc-sod-create'},
))
db.session.commit()
lease = lease_service.acquire_lease(
draft['id'],
actor_id=editor.id,
browser_session_id='publish-check-tab',
operation_id='pc-sod-lease',
)
run = _passing_run(draft)
_signature_run(draft)
overlap = _overlap_run(draft)
monkeypatch.setattr(
validation_service, 'run_cross_template_overlap',
lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'},
)
report = checks.create_report(
draft['id'],
data={'validation_run_id': run.id, 'overlap_validation_run_id': overlap.id},
actor_id=editor.id,
browser_session_id='publish-check-tab',
lease_token=lease['lease_token'],
operation_id='pc-sod-report',
)
keys = [str(item['key']) for item in report['warning_items']]
with pytest.raises(ValidationError) as error:
checks.consume_report(
draft['id'],
report['report_no'],
data={'confirmed_warning_keys': keys},
actor_id=editor.id,
browser_session_id='publish-check-tab',
lease_token=lease['lease_token'],
operation_id='pc-sod-consume',
)
assert error.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID'
assert (error.value.details or {}).get('key') == 'editor_cannot_approve_own_version'
@@ -0,0 +1,109 @@
"""
tests/test_order_document_profile_publish_check_xfa_phase4.py
用途:阶段 4 XFA 发布检查阻断项与结构签名消费 focused 验收。
依赖:publish_check_service、validation helpers。
逻辑:构造 XFA 草稿摘要阻断;验证缺失路径/对账失败会进入 blocking_items。
"""
from __future__ import annotations
import pytest
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileValidationRun
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
def test_blocking_xfa_definition_flags_missing_paths_and_collection():
"""关键断言:缺失权威集合与路径覆盖会生成稳定阻断项。"""
profile = ShippingOrderDocumentProfile(
profile_code='XFA_BLOCK',
display_name='XFA Block',
version=1,
status='draft',
schema_version_id=1,
structure_fingerprint='a' * 64,
template_mode='xfa_dataset',
definition_json={
'template_mode': 'xfa_dataset',
'source_contract': {
'template_packet_checksum': '',
'dataset_structure_fingerprint': '',
'dataset_root_path': '/data',
'authoritative_line_collection_path': '',
'mirror_collection_paths': [],
},
'header_mappings': [],
'line_mapping': {'row_path': '', 'fields': []},
'cross_checks': {
'acroform_enabled': False,
'mirror_collection_policy': 'must_match_when_present',
'line_amount_formula': 'disabled',
'total_amount_policy': 'disabled',
},
},
)
# schema_version 关系在纯函数测试中可缺省;_blocking 只读 definition。
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
{'field_id': 'f-po', 'field_code': 'customer_po_no', 'enabled': True, 'required': True},
]}})()
blocking = checks._blocking_xfa_definition(profile, None)
keys = {item['key'] for item in blocking}
assert 'xfa_structure_identity_missing' in keys
assert 'xfa_authoritative_collection_missing' in keys
assert 'xfa_required_path_coverage_incomplete' in keys
def test_blocking_xfa_definition_flags_stale_and_reconciliation():
"""关键断言:stale 验证与对账失败码进入发布阻断。"""
profile = ShippingOrderDocumentProfile(
profile_code='XFA_RECON',
display_name='XFA Recon',
version=1,
status='draft',
schema_version_id=1,
structure_fingerprint='b' * 64,
template_mode='xfa_dataset',
definition_json={
'template_mode': 'xfa_dataset',
'source_contract': {
'template_packet_checksum': 'sha256:t',
'dataset_structure_fingerprint': 'sha256:f',
'dataset_root_path': '/data',
'authoritative_line_collection_path': '/data/ITEMS/DATA',
'mirror_collection_paths': [],
},
'header_mappings': [{
'mapping_id': 'm1', 'field_id': 'f-po', 'field_code': 'customer_po_no',
'data_path': '/data/HEADER/EBELN', 'path_id': 'p1', 'value_type': 'string',
}],
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
'cross_checks': {
'acroform_enabled': True,
'mirror_collection_policy': 'must_match_when_present',
'line_amount_formula': 'disabled',
'total_amount_policy': 'disabled',
},
},
)
profile.schema_version = type('SV', (), {'definition_json': {'fields': []}})()
validation = ShippingOrderDocumentProfileValidationRun(
profile_id=1,
revision_no=1,
definition_checksum='stale-checksum',
schema_version_id=1,
run_type='current_sample',
status='passed',
summary_json={
'cross_check_failures': ['xfa_mirror_collection_mismatch', 'xfa_acroform_mismatch'],
'header_required_missing_count': 0,
'auto_create_key_missing_count': 0,
},
result_snapshot_json={},
operation_id='recon',
)
blocking = checks._blocking_xfa_definition(profile, validation)
keys = {item['key'] for item in blocking}
assert 'current_validation_stale' in keys
assert 'xfa_collection_ambiguity' in keys
assert 'xfa_reconciliation_failed' in keys
@@ -40,7 +40,8 @@ def test_instant_run_freezes_revision_and_becomes_stale_without_history_mutation
stored = db.session.get(ShippingOrderDocumentProfileValidationRun, run['id'])
frozen_checksum = stored.definition_checksum
changed = _data(schema.id)
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.61
# 缩短首字段右边界,保证与相邻字段不重叠且 definition checksum 变化。
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.15
changed['expected_lock_version'] = draft['lock_version']
profile_service.save_draft(
changed, actor_id=None, profile_id=draft['id'], browser_session_id='validation-test-tab',
@@ -0,0 +1,216 @@
"""
tests/test_order_document_profile_validation_service_xfa_phase4.py
用途:阶段 4 XFA current_sample / xfa_structure_signature / stale 门禁 focused 验收。
依赖:validation_service、creation_service、xfa helpers、pytest app fixture。
逻辑:合成 XFA PDF → 向导草稿 → 保存映射 → 验证运行与结构签名;definition 变更后旧签名 stale。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app.extensions import db
from app.models import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileSample,
ShippingOrderDocumentProfileValidationRun,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
from app.services.shipping_notice.document_layout.xfa_dataset import _path_id_for
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io, _seed_xfa_sample
def _schema_with_auto_create() -> ShippingOrderSchemaVersion:
"""发布含 required + auto_create_key 字段的 Schema。"""
schema = ShippingOrderSchema(schema_code='XFA_P4', display_name='XFA Phase4')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id,
version=1,
status='published',
checksum='d' * 64,
published_at=datetime.utcnow(),
definition_json={'fields': [
{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'required': True,
'auto_create_key_field': True,
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['xfa_dataset'],
},
{
'field_id': 'f-mat', 'field_code': 'material_no', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'auto_create_key_field': True,
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['xfa_dataset'],
},
{
'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line',
'value_type': 'decimal', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': ['positive_decimal'], 'allowed_sources': ['xfa_dataset'],
},
]},
)
db.session.add(version)
db.session.commit()
return version
def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> tuple[dict, dict[str, str], str]:
"""创建已映射 Header/Line 的 XFA 草稿并返回 lease token。"""
document, paths, _ = _seed_xfa_sample(user=user)
created = creation_service.complete_wizard({
'display_name': 'XFA Phase4 Draft',
'schema_version_id': schema.id,
'document_id': document.id,
'authoritative_collection_path_id': paths['ITEMS_DATA'],
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
'browser_session_id': 'xfa-p4-tab',
'operation_id': 'xfa-p4-wizard',
}, actor_id=user.id)
lease = created['edit_lease']
definition = dict(created['definition'])
definition['header_mappings'] = [{
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'],
'value_type': 'string', 'normalizer_key': 'trim',
}]
definition['line_mapping'] = {
'row_path': '/data/ITEMS/DATA',
'fields': [
{
'mapping_id': 'm-mat', 'field_id': 'f-mat', 'field_code': 'material_no',
'data_path': '/data/ITEMS/DATA/MATNR', 'path_id': paths['MATNR'],
'value_type': 'string', 'normalizer_key': 'trim',
},
{
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
'data_path': '/data/ITEMS/DATA/MENGE', 'path_id': _path_id_for('/data/ITEMS/DATA/MENGE'),
'value_type': 'decimal', 'normalizer_key': 'trim',
},
],
}
definition['cross_checks'] = {
'acroform_enabled': False,
'mirror_collection_policy': 'must_match_when_present',
'line_amount_formula': 'disabled',
'total_amount_policy': 'disabled',
}
saved = profile_service.save_draft({
'display_name': created['display_name'],
'schema_version_id': schema.id,
'definition': definition,
'expected_lock_version': created['lock_version'],
'sample_document_id': document.id,
}, actor_id=user.id, profile_id=created['id'],
browser_session_id='xfa-p4-tab',
lease_token=lease['lease_token'],
operation_id='xfa-p4-map',
enforce_lease=True,
)
return saved, paths, lease['lease_token']
def test_xfa_current_sample_summary_rejects_auto_create_missing():
"""关键断言:auto_create_key 缺值时当前样本摘要必须失败。"""
status, summary, _ = validation_service._current_sample_summary(
line_field_count=2, line_value_count=2, header_field_count=1, header_value_count=1,
header_required_missing_count=0, auto_create_key_missing_count=1,
sample_role='annotation', template_mode='xfa_dataset',
)
assert status == 'failed'
assert summary['failure_code'] == 'order_profile_current_sample_auto_create_key_missing'
def test_xfa_current_sample_and_structure_signature_pass(app, _patch_xfa_io):
"""关键断言:XFA current_sample 与 xfa_structure_signature 可通过并写入匹配引用。"""
with app.app_context():
user = User(username='xfa-p4-val', email='xfa-p4-val@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
schema = _schema_with_auto_create()
draft, _paths, lease_token = _create_mapped_draft(user=user, schema=schema)
sample = ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=draft['id'], sample_role='annotation',
).first()
instant = validation_service.run_instant_check(
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
lease_token=lease_token, operation_id='xfa-p4-instant',
)
assert instant['status'] == 'passed'
assert instant['summary']['template_mode'] == 'xfa_dataset'
current = validation_service.run_current_sample(
draft['id'], data={'sample_binding_id': sample.id}, actor_id=user.id,
browser_session_id='xfa-p4-tab', lease_token=lease_token, operation_id='xfa-p4-current',
)
assert current['status'] == 'passed'
assert current['summary']['template_mode'] == 'xfa_dataset'
assert int(current['summary'].get('header_required_missing_count') or 0) == 0
assert int(current['summary'].get('auto_create_key_missing_count') or 0) == 0
signature = validation_service.run_xfa_structure_signature(
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
lease_token=lease_token, operation_id='xfa-p4-sig',
)
assert signature['status'] == 'passed'
assert signature['run_type'] == 'xfa_structure_signature'
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
assert profile.matching_signature_run_id == signature['id']
assert profile.matching_signature_checksum
assert profile.matching_signature_version.startswith('xfa-structure-signature')
def test_xfa_structure_signature_becomes_stale_after_definition_change(app, _patch_xfa_io):
"""关键断言:definition checksum 变化后旧 xfa_structure_signature 查询态为 stale。"""
with app.app_context():
user = User(username='xfa-p4-stale', email='xfa-p4-stale@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
schema = _schema_with_auto_create()
draft, paths, lease_token = _create_mapped_draft(user=user, schema=schema)
signature = validation_service.run_xfa_structure_signature(
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
lease_token=lease_token, operation_id='xfa-p4-sig-stale',
)
stored = db.session.get(ShippingOrderDocumentProfileValidationRun, signature['id'])
frozen = stored.definition_checksum
definition = dict(draft['definition'])
definition['header_mappings'] = [{
'mapping_id': 'm-po2', 'field_id': 'f-po', 'field_code': 'customer_po_no',
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'],
'value_type': 'string', 'normalizer_key': 'trim',
}]
# 重新获取租约(保存后可能仍有效)
lease = lease_service.acquire_lease(
draft['id'], actor_id=user.id, browser_session_id='xfa-p4-tab', operation_id='xfa-p4-release',
)
profile_service.save_draft({
'display_name': draft['display_name'],
'schema_version_id': schema.id,
'definition': definition,
'expected_lock_version': draft['lock_version'],
'sample_document_id': ShippingOrderDocumentProfileSample.query.filter_by(
profile_id=draft['id'], sample_role='annotation',
).first().document_id,
}, actor_id=user.id, profile_id=draft['id'],
browser_session_id='xfa-p4-tab',
lease_token=lease['lease_token'],
operation_id='xfa-p4-change',
enforce_lease=True,
)
listed = validation_service.list_runs(draft['id'])
stale = next(item for item in listed if item['id'] == signature['id'])
assert stale['status'] == 'stale'
assert stored.definition_checksum == frozen
assert stored.status == 'passed'
@@ -14,8 +14,8 @@ from app.models import (
ShippingDocumentProfileTestRun,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileSample,
ShippingOrderSchema,
@@ -77,7 +77,6 @@ def _profile(
schema_version_id=schema_version_id,
structure_fingerprint=f'{version}' * 64,
definition_json={
'contract_version': 'order_coordinate_profile.v2',
'document_match': {
'document_type': 'purchase_order',
'page_pattern': 'one_or_more',
@@ -100,7 +99,7 @@ def _profile(
return profile
def _document(owner: User, *, filename: str, content_hash: str) -> ShippingNoticeDocument:
def _document(owner: User, *, filename: str, content_hash: str) -> ShippingOrderDocument:
"""创建版本详情需要的安全样本文档实体。"""
asset = FileAsset(
asset_no=f'FA-{filename}',
@@ -117,7 +116,7 @@ def _document(owner: User, *, filename: str, content_hash: str) -> ShippingNotic
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f'SNI-{filename}'.upper(),
asset_id=asset.id,
user_id=owner.id,
@@ -127,7 +126,7 @@ def _document(owner: User, *, filename: str, content_hash: str) -> ShippingNotic
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
@@ -0,0 +1,87 @@
"""
tests/test_order_document_profile_version_service_xfa_phase4.py
用途:阶段 4 XFA 版本详情安全摘要与只读映射边界 focused 验收。
依赖:version_service、preview_service。
逻辑:definition_stats / xfa_structure_identity / readonly mapping 不含盲测真值与空白 PDF。
"""
from __future__ import annotations
from app.services.shipping_notice.order_document_profile_preview_service import (
build_xfa_readonly_mapping_evidence,
)
from app.services.shipping_notice.order_document_profile_version_service import (
_definition_scale_summary,
_xfa_structure_identity_summary,
)
from app.models import ShippingOrderDocumentProfile
def test_xfa_definition_scale_and_identity_summary():
"""关键断言:XFA 版本统计返回映射规模与结构身份,不含坐标表区域。"""
definition = {
'template_mode': 'xfa_dataset',
'source_contract': {
'template_packet_checksum': 'sha256:tpl',
'dataset_structure_fingerprint': 'sha256:fp',
'dataset_root_path': '/data',
'authoritative_line_collection_path': '/data/ITEMS/DATA',
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
},
'header_mappings': [{'mapping_id': 'm1', 'field_code': 'customer_po_no'}],
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': [{'mapping_id': 'm2'}]},
}
stats = _definition_scale_summary(definition)
assert stats['template_mode'] == 'xfa_dataset'
assert stats['header_mapping_count'] == 1
assert stats['line_mapping_count'] == 1
assert stats['table_region_count'] == 0
identity = _xfa_structure_identity_summary(definition)
assert identity['template_packet_checksum'] == 'sha256:tpl'
assert identity['dataset_structure_fingerprint'] == 'sha256:fp'
assert 'blind' not in str(identity).lower()
def test_xfa_readonly_mapping_evidence_has_no_pdf_preview():
"""关键断言:只读映射 DTO 明确禁用 PDF 预览且不含盲测真值键。"""
profile = ShippingOrderDocumentProfile(
id=1,
profile_code='XFA_RO',
display_name='XFA RO',
version=1,
status='published',
schema_version_id=1,
structure_fingerprint='c' * 64,
checksum='d' * 64,
template_mode='xfa_dataset',
matching_signature_checksum='sig',
matching_signature_version='xfa-structure-signature.v1',
definition_json={
'template_mode': 'xfa_dataset',
'source_contract': {
'template_packet_checksum': 'sha256:tpl',
'dataset_structure_fingerprint': 'sha256:fp',
'dataset_root_path': '/data',
'authoritative_line_collection_path': '/data/ITEMS/DATA',
'mirror_collection_paths': [],
},
'header_mappings': [{
'mapping_id': 'm1', 'field_id': 'f-po', 'field_code': 'customer_po_no',
'path_id': 'p1', 'value_type': 'string',
}],
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
'cross_checks': {
'acroform_enabled': False,
'mirror_collection_policy': 'ignore',
'line_amount_formula': 'disabled',
'total_amount_policy': 'disabled',
},
},
)
evidence = build_xfa_readonly_mapping_evidence(profile)
assert evidence['pdf_preview_available'] is False
assert evidence['template_mode'] == 'xfa_dataset'
assert 'expected_rows' not in evidence
assert 'expected_order_fields' not in evidence
assert evidence['header_mappings'][0]['field_code'] == 'customer_po_no'
+58 -5
View File
@@ -3,7 +3,9 @@ backend/tests/test_order_extraction_merge.py
用途:验证跨文档订单保守合并、证据保留与错误拆分边界。
依赖:order_extraction_merge、冻结 Schema 稳定字段 ID。
逻辑:PO 或强行身份可合并;弱身份不得合并;冲突 Observation 全量保留给后续裁决。
逻辑:阶段 2 默认 keep_primary_documents_separate=True(多 PDF 各成 Candidate);
PO 或强行身份可合并仅在同 primary_document_id 或显式 False 时;
弱身份不得合并;冲突 Observation 全量保留给后续裁决。
"""
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
@@ -53,17 +55,55 @@ def _partial_line(document_id, *, part: str, reservation: str | None = None, qty
def test_same_po_merges_observations_and_preserves_conflicting_values():
"""同一 PO 合并后 Qty 冲突证据必须同时存在,交由动态字段裁决阻断。"""
"""
阶段 2 默认 keep_primary_documents_separate=True:同 PO 不同 PDF 保持两个订单。
断言:len==2;各自保留本 Document 的 Qty Observation。
"""
merged = merge_unit_orders(
orders=[_order(1, qty=1), _order(2, qty=2)], schema_definition=DEFINITION,
)
assert len(merged) == 2
assert {tuple(item['source_document_ids']) for item in merged} == {(1,), (2,)}
qtys = {
item['primary_document_id']: next(
field for field in item['lines'][0]['fields'] if field['field_id'] == 'qty-id'
)['observations'][0]['value']
for item in merged
}
assert qtys == {1: 1, 2: 2}
def test_same_po_merges_when_keep_primary_documents_separate_disabled():
"""
显式 keep_primary_documents_separate=False 保留历史跨文档合并行为。
断言:合并为 1 单;Qty 冲突 Observation 全量保留。
"""
merged = merge_unit_orders(
orders=[_order(1, qty=1), _order(2, qty=2)],
schema_definition=DEFINITION,
keep_primary_documents_separate=False,
)
assert len(merged) == 1
assert merged[0]['source_document_ids'] == [1, 2]
qty = next(item for item in merged[0]['lines'][0]['fields'] if item['field_id'] == 'qty-id')
assert {item['value'] for item in qty['observations']} == {1, 2}
def test_keep_primary_documents_separate_keeps_two_pdfs_apart():
"""两个 primary_document_id 即使 PO/行身份相同也不得并成同一 Candidate。"""
merged = merge_unit_orders(
orders=[_order(10, po='PO-X', part='PN-A', reservation='1000111111'),
_order(20, po='PO-X', part='PN-A', reservation='1000111111')],
schema_definition=DEFINITION,
)
assert len(merged) == 2
assert {item['primary_document_id'] for item in merged} == {10, 20}
def test_part_number_without_same_reservation_does_not_merge_without_po():
"""只有料号相同属于弱身份,Reservation 不同且无 PO 时必须保持两个订单。"""
merged = merge_unit_orders(
@@ -83,7 +123,11 @@ def test_same_po_uniquely_merges_pdf_line_with_email_reservation_in_either_order
email = _partial_order(2, lines=[_partial_line(2, part='PN-1', reservation='1000123456')])
for orders in ([pdf, email], [email, pdf]):
merged = merge_unit_orders(orders=orders, schema_definition=DEFINITION)
merged = merge_unit_orders(
orders=orders,
schema_definition=DEFINITION,
keep_primary_documents_separate=False,
)
assert len(merged) == 1
assert len(merged[0]['lines']) == 1
@@ -101,7 +145,11 @@ def test_same_po_duplicate_part_number_does_not_guess_reservation_line():
])
email = _partial_order(2, lines=[_partial_line(2, part='PN-1', reservation='1000123456')])
merged = merge_unit_orders(orders=[pdf, email], schema_definition=DEFINITION)
merged = merge_unit_orders(
orders=[pdf, email],
schema_definition=DEFINITION,
keep_primary_documents_separate=False,
)
assert len(merged) == 1
assert len(merged[0]['lines']) == 3
@@ -116,7 +164,11 @@ def test_same_po_conflicting_reservations_do_not_merge_lines():
first = _partial_order(1, lines=[_partial_line(1, part='PN-1', reservation='1000123456', qty=30)])
second = _partial_order(2, lines=[_partial_line(2, part='PN-1', reservation='1000123457')])
merged = merge_unit_orders(orders=[first, second], schema_definition=DEFINITION)
merged = merge_unit_orders(
orders=[first, second],
schema_definition=DEFINITION,
keep_primary_documents_separate=False,
)
assert len(merged) == 1
assert len(merged[0]['lines']) == 2
@@ -133,6 +185,7 @@ def test_same_po_conflicting_line_no_does_not_merge_same_part_number():
merged = merge_unit_orders(
orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])],
schema_definition=definition,
keep_primary_documents_separate=False,
)
assert len(merged) == 1
@@ -8,6 +8,9 @@ backend/tests/test_shipping_audit_event.py
from __future__ import annotations
import ast
from pathlib import Path
import pytest
from app import db
@@ -178,3 +181,41 @@ def test_stage0_i18n_key_inventory_is_frozen():
assert 'shippingOrderExtractionHealthTip.processing_attention' in joined
assert 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED' in joined
assert 'admin.shippingAudit.export' in joined
def test_shipping_audit_result_literals_follow_service_contract():
"""生产代码中的审计 result 字面量必须受统一枚举约束,禁止 ok/failed/needs_review 等业务状态越界。"""
allowed_results = {'success', 'failure', 'rejected', 'ignored'}
backend_app = Path(__file__).resolve().parents[1] / 'app'
invalid_literals: list[str] = []
def _result_literal_values(node: ast.AST) -> list[str]:
"""提取 result 表达式实际可能返回的字符串分支,不把比较条件中的事件名误判为结果值。"""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return [node.value]
if isinstance(node, ast.IfExp):
return _result_literal_values(node.body) + _result_literal_values(node.orelse)
return []
# 关键断言:递归检查条件表达式中的所有字符串分支,避免只验证最终运行到的单一路径。
for source_path in backend_app.rglob('*.py'):
tree = ast.parse(source_path.read_text(encoding='utf-8-sig'), filename=str(source_path))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
function_name = (
node.func.id if isinstance(node.func, ast.Name)
else node.func.attr if isinstance(node.func, ast.Attribute)
else ''
)
if function_name not in {'append_shipping_audit_event', '_layout_job_audit'}:
continue
result_keyword = next((item for item in node.keywords if item.arg == 'result'), None)
if result_keyword is None:
continue
for result_value in _result_literal_values(result_keyword.value):
if result_value not in allowed_results:
relative_path = source_path.relative_to(backend_app.parent)
invalid_literals.append(f'{relative_path}:{node.lineno}:{result_value}')
assert invalid_literals == []
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_audit_immutability.py
用途:验收 ShippingAuditEvent ORM 层 append-only 与哈希链字段落库。
依赖:ShippingAuditEvent 模型事件守卫、audit_service.append_shipping_audit_event。
逻辑:已提交事件禁止 ORM update/delete;新写入必须带 event_hash / previous_event_hash 字段语义。
用途:验收 ShippingAuditEvent / ShippingXfaAuditSnapshot ORM 层 append-only 与哈希链字段落库。
依赖:模型事件守卫、audit_service、audit_snapshot_service。
逻辑:已提交事件与 XFA 快照禁止 ORM update/delete;新写入必须带 event_hash 语义。
"""
from __future__ import annotations
@@ -12,8 +12,9 @@ import pytest
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.audit_snapshot_service import create_xfa_audit_snapshot
def test_shipping_audit_event_orm_update_raises(app):
@@ -82,3 +83,36 @@ def test_append_only_persists_hash_chain_fields(app):
assert second.event_hash
assert second.previous_event_hash == first.event_hash
assert first.diff_json is not None or first.after_snapshot_json is not None
def test_xfa_audit_snapshot_orm_update_and_delete_blocked(app):
"""XFA 加密快照更新与删除被服务层阻断。"""
with app.app_context():
if not str(app.config.get('SECRET_KEY') or '').strip():
app.config['SECRET_KEY'] = 'test-shipping-xfa-audit-secret'
row = create_xfa_audit_snapshot(
payload={'definition_checksum': 'cs-1', 'definition': {'template_mode': 'xfa_dataset'}},
object_type='shipping_order_document_profile',
object_id='7',
purpose='full',
operation_id='op-imm-xfa',
)
db.session.commit()
snap_id = int(row.id)
persisted = db.session.get(ShippingXfaAuditSnapshot, snap_id)
persisted.ciphertext = 'tampered'
with pytest.raises(ValidationError, match='append-only'):
db.session.commit()
db.session.rollback()
persisted = db.session.get(ShippingXfaAuditSnapshot, snap_id)
db.session.delete(persisted)
with pytest.raises(ValidationError, match='append-only'):
db.session.commit()
db.session.rollback()
# 关键断言:改删失败后快照仍在且密文未变。
again = db.session.get(ShippingXfaAuditSnapshot, snap_id)
assert again is not None
assert again.ciphertext != 'tampered'
@@ -184,3 +184,90 @@ def test_association_chain_expands_across_workflow_keys(app):
event_type='audit_access', action='list_audit_association_chain',
).count()
assert access >= 1
def test_xfa_full_snapshot_requires_sensitive_read_and_re_audits(app):
"""只有 audit_sensitive_read 可读完整快照;每次读取再写访问审计。"""
from app.services.shipping_notice.audit_query_service import get_xfa_audit_full_snapshot
from app.services.shipping_notice.audit_snapshot_service import create_xfa_audit_snapshot
with app.app_context():
if not str(app.config.get('SECRET_KEY') or '').strip():
app.config['SECRET_KEY'] = 'test-shipping-xfa-audit-secret'
row = create_xfa_audit_snapshot(
payload={'secret_po': '4510039227', 'definition_checksum': 'cs'},
object_type='shipping_order_document_profile',
object_id='88',
purpose='after',
operation_id='op-sens-read',
)
db.session.commit()
ref = row.snapshot_ref
redacted = get_xfa_audit_full_snapshot(
admin_user_id=9,
request_id='req-xfa-deny',
snapshot_ref=ref,
include_sensitive=False,
)
# 关键断言:无权限仅脱敏摘要,无完整 payload。
assert redacted['sensitive_redacted'] is True
assert redacted['payload'] is None
assert 'secret_po' not in str(redacted.get('summary') or {})
allowed = get_xfa_audit_full_snapshot(
admin_user_id=9,
request_id='req-xfa-allow',
snapshot_ref=ref,
include_sensitive=True,
)
assert allowed['sensitive_redacted'] is False
assert allowed['payload']['secret_po'] == '4510039227'
views = (
ShippingAuditEvent.query
.filter_by(event_type='xfa_audit_snapshot_viewed', aggregate_id=ref)
.order_by(ShippingAuditEvent.id.asc())
.all()
)
# 关键断言:拒绝与允许各产生一条访问审计。
assert len(views) >= 2
actions = {v.action for v in views}
assert 'read_xfa_snapshot_redacted' in actions
assert 'read_xfa_snapshot_full' in actions
def test_ordinary_export_is_redacted_summary_only(app):
"""普通导出仅含脱敏摘要,不含完整快照正文。"""
from app.services.shipping_notice.audit_query_service import export_shipping_audit_events
with app.app_context():
if not str(app.config.get('SECRET_KEY') or '').strip():
app.config['SECRET_KEY'] = 'test-shipping-xfa-audit-secret'
app.config['SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED'] = True
append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='export-1',
actor_type='admin',
actor_id=1,
operation_id='op-export',
request_id='req-export',
result='success',
sensitivity_level='sensitive',
after={'definition_checksum': 'exp-cs', 'template_mode': 'xfa_dataset'},
full_after={'definition': {'po': 'SECRET-PO'}, 'definition_checksum': 'exp-cs'},
)
db.session.commit()
exported = export_shipping_audit_events(
admin_user_id=1,
request_id='req-export-run',
filters={'aggregate_id': 'export-1'},
limit=50,
format='json',
)
content = exported['content']
# 关键断言:导出不含完整 definition 或 SECRET-PO。
assert 'SECRET-PO' not in content
assert 'ciphertext' not in content
@@ -1,24 +1,40 @@
"""
backend/tests/test_shipping_audit_snapshot_service.py
用途:验收审计快照白名单、Diff 计算与同聚合 event_hash 哈希链完整性。
依赖:audit_snapshot_service、audit_service、ShippingAuditEvent、SQLAlchemy Core UPDATE。
逻辑:sanitize/diff 只保留白名单键;连续 append 形成 previous→event 链;
Core UPDATE 篡改后 verify_event_hash_chain 必须失败。
用途:验收审计快照白名单/Diff/哈希链,以及 XFA 加密不可变完整快照(阶段 5)。
依赖:audit_snapshot_service、audit_service、ShippingAuditEvent、ShippingXfaAuditSnapshot。
逻辑:sanitize/diff 白名单;连续 append 形成哈希链;Core 篡改后链校验失败;
XFA 完整快照用 SECRET_KEY 派生 Fernet 加密入库(无独立审计密钥);
缺 SECRET_KEY 失败关闭、密文静态不可读、脱敏摘要可导出。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from sqlalchemy import text
from app import db
from app.models import ShippingAuditEvent
from app.core.errors import ServiceUnavailableError
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.audit_snapshot_service import (
compute_snapshot_diff,
create_xfa_audit_snapshot,
decrypt_xfa_audit_snapshot_row,
require_xfa_audit_crypto,
sanitize_snapshot,
serialize_xfa_audit_snapshot_summary,
verify_event_hash_chain,
)
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
def _ensure_secret_key(app) -> None:
"""确保 SECRET_KEY 可用于派生 XFA 审计快照 Fernet(无独立审计密钥)。"""
if not str(app.config.get('SECRET_KEY') or '').strip():
app.config['SECRET_KEY'] = 'test-shipping-xfa-audit-secret'
def test_sanitize_snapshot_whitelists_keys(app):
@@ -133,3 +149,208 @@ def test_verify_event_hash_chain_fails_after_core_tamper(app):
# 关键断言:至少一条 event_hash_mismatch 或后续 previous_hash_mismatch。
assert ok is False
assert any(row['reason'] in {'event_hash_mismatch', 'previous_hash_mismatch'} for row in failures)
def test_xfa_audit_event_types_cover_plan_nodes(app):
"""方案文档列出的 XFA 操作节点均已注册为可审计事件码。"""
with app.app_context():
# 关键断言:阶段 0 冻结的 XFA 审计事件集合非空且含关键写/读/运行节点。
required = {
'xfa_sample_uploaded',
'xfa_parse_started',
'xfa_parse_completed',
'xfa_mapping_saved',
'xfa_sensitive_sample_value_read',
'xfa_profile_matched',
'xfa_extraction_completed',
'xfa_audit_snapshot_viewed',
}
assert required.issubset(XFA_AUDIT_EVENT_TYPES)
def test_xfa_encrypted_snapshot_not_plaintext_and_roundtrip(app):
"""完整快照密文静态不可读;解密后与原文一致。"""
with app.app_context():
_ensure_secret_key(app)
payload = {
'definition': {'template_mode': 'xfa_dataset', 'header_mappings': [{'field_code': 'po'}]},
'definition_checksum': 'abc123',
'raw_sample': '4510039227',
}
row = create_xfa_audit_snapshot(
payload=payload,
object_type='shipping_order_document_profile',
object_id='99',
purpose='after',
actor_id=7,
operation_id='op-xfa-1',
request_id='req-xfa-1',
)
db.session.commit()
persisted = db.session.get(ShippingXfaAuditSnapshot, row.id)
assert persisted is not None
# 关键断言:库内仅密文,不含明文订单号。
assert '4510039227' not in persisted.ciphertext
assert persisted.ciphertext_sha256
assert persisted.plaintext_sha256
assert persisted.retention_expires_at is not None
# 保留期约 3 年(1095 天 ± 1 天缓冲)。
delta = persisted.retention_expires_at - datetime.utcnow()
assert timedelta(days=1090) <= delta <= timedelta(days=1100)
summary = serialize_xfa_audit_snapshot_summary(persisted)
assert 'ciphertext' not in summary
assert summary['redacted_summary'].get('definition_checksum') == 'abc123'
assert 'raw_sample' not in (summary.get('redacted_summary') or {})
decrypted = decrypt_xfa_audit_snapshot_row(persisted)
assert decrypted['raw_sample'] == '4510039227'
assert decrypted['definition_checksum'] == 'abc123'
def test_xfa_sensitive_write_fails_closed_without_master_key(app):
"""缺少 SECRET_KEY 时敏感写(加密快照)失败关闭。"""
with app.app_context():
app.config['SECRET_KEY'] = ''
with pytest.raises(ServiceUnavailableError) as caught:
require_xfa_audit_crypto()
assert caught.value.code == 'SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_SECRET_MISSING'
with pytest.raises(ServiceUnavailableError):
append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='1',
actor_type='admin',
actor_id=1,
operation_id='op-no-key',
result='success',
sensitivity_level='sensitive',
after={'definition_checksum': 'x', 'template_mode': 'xfa_dataset'},
full_after={'definition': {'template_mode': 'xfa_dataset'}, 'definition_checksum': 'x'},
)
def test_xfa_change_event_includes_checksum_diff_and_snapshot_refs(app):
"""变更事件含 before/after checksum、脱敏 diff 与完整快照引用;同事务可回滚。"""
with app.app_context():
_ensure_secret_key(app)
event = append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='42',
actor_type='admin',
actor_id=3,
operation_id='op-map-1',
request_id='req-map-1',
result='success',
sensitivity_level='sensitive',
before={'definition_checksum': 'before-cs', 'template_mode': 'xfa_dataset', 'bound_field_count': 1},
after={'definition_checksum': 'after-cs', 'template_mode': 'xfa_dataset', 'bound_field_count': 2},
full_before={'definition': {'v': 1}, 'definition_checksum': 'before-cs'},
full_after={'definition': {'v': 2}, 'definition_checksum': 'after-cs'},
)
db.session.commit()
# 关键断言:actor/time/request/operation/对象/结果齐全。
assert event.actor_id == '3'
assert event.created_at is not None
assert event.request_id == 'req-map-1'
assert event.operation_id == 'op-map-1'
assert event.aggregate_id == '42'
assert event.result == 'success'
assert event.before_hash
assert event.after_hash
assert event.diff_json is not None
assert event.diff_json['changed']['definition_checksum']['from'] == 'before-cs'
ctx = event.context_refs_json or {}
assert ctx.get('snapshot_before_ref', '').startswith('xfa-snap-')
assert ctx.get('snapshot_after_ref', '').startswith('xfa-snap-')
assert ShippingXfaAuditSnapshot.query.count() >= 2
def test_audit_failure_rolls_back_business_marker(app):
"""审计/快照失败时业务写入不得提交(同事务回滚)。"""
with app.app_context():
prior_secret = app.config.get('SECRET_KEY')
app.config['SECRET_KEY'] = ''
try:
# 同事务先写入一条普通审计作为“业务侧事实”,再触发敏感快照失败。
append_shipping_audit_event(
event_type='xfa_draft_created',
aggregate_type='shipping_order_document_profile',
aggregate_id='rollback-1',
actor_type='admin',
actor_id=1,
result='success',
after={'template_mode': 'xfa_dataset', 'definition_checksum': 'draft'},
)
with pytest.raises(ServiceUnavailableError):
append_shipping_audit_event(
event_type='xfa_mapping_saved',
aggregate_type='shipping_order_document_profile',
aggregate_id='rollback-1',
actor_type='admin',
actor_id=1,
result='success',
sensitivity_level='sensitive',
after={'definition_checksum': 'x', 'template_mode': 'xfa_dataset'},
full_after={'definition': {'template_mode': 'xfa_dataset'}, 'definition_checksum': 'x'},
)
db.session.rollback()
# 关键断言:失败回滚后该聚合无任何审计事件。
assert (
ShippingAuditEvent.query
.filter_by(aggregate_type='shipping_order_document_profile', aggregate_id='rollback-1')
.count()
) == 0
assert ShippingXfaAuditSnapshot.query.filter_by(object_id='rollback-1').count() == 0
finally:
app.config['SECRET_KEY'] = prior_secret
def test_stp_auto_create_nodes_write_traceable_audit(app):
"""自动建单尝试/成功/幂等/失败均可追溯到 Run、Candidate、Profile。"""
with app.app_context():
for event_type, result, action in (
('candidate_qualification_evaluated', 'success', 'evaluate'),
('order_stp_auto_create_attempted', 'success', 'attempt'),
('order_stp_auto_create_succeeded', 'success', 'create'),
('order_stp_auto_create_idempotent_replay', 'ignored', 'replay'),
('order_stp_auto_create_failed', 'failure', 'create'),
):
append_shipping_audit_event(
event_type=event_type,
aggregate_type='shipping_order_candidate',
aggregate_id='CAND-XFA-1',
run_no='SNER-XFA-1',
actor_type='system',
result=result,
action=action,
operation_id=f'op-{action}',
request_id=f'req-{action}',
after={
'candidate_no': 'CAND-XFA-1',
'run_no': 'SNER-XFA-1',
'profile_code': 'XFA_PO_V1',
'profile_version': 1,
'definition_checksum': 'pub-cs',
},
metadata={'revision_no': 3},
)
db.session.commit()
rows = (
ShippingAuditEvent.query
.filter(ShippingAuditEvent.aggregate_id == 'CAND-XFA-1')
.order_by(ShippingAuditEvent.id.asc())
.all()
)
# 关键断言:五条节点均带 Run/Candidate/Profile 身份与 operation_id。
assert len(rows) == 5
for row in rows:
assert row.run_no == 'SNER-XFA-1'
assert row.operation_id
assert row.request_id
assert (row.after_snapshot_json or {}).get('profile_code') == 'XFA_PO_V1'
@@ -12,7 +12,7 @@ import pytest
from app import db
from app.core.errors import ConflictError
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.business_numbering_service import (
assign_business_number,
format_business_no,
@@ -32,7 +32,7 @@ def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending")
db.session.add_all([customer, case])
db.session.flush()
task = ShippingTask(
task = ShippingNotice(
task_no=task_no,
shipping_case_id=case.id,
customer_resolution_status="pending",
@@ -73,7 +73,7 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
with app.app_context():
task, case, customer = _seed_case()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
revision = ShippingTask(
revision = ShippingNotice(
task_no="SN-NUMBER-REV",
shipping_case_id=case.id,
supersedes_task_id=task.id,
@@ -84,7 +84,7 @@ def test_revision_inherits_and_force_case_uses_next_sequence(app):
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
db.session.add_all([revision, forced_case])
db.session.flush()
forced_task = ShippingTask(
forced_task = ShippingNotice(
task_no="SN-NUMBER-FORCED",
shipping_case_id=forced_case.id,
customer_resolution_status="pending",
@@ -139,7 +139,7 @@ def test_numbering_failure_rolls_back_customer_confirmation(app):
db.session.rollback()
db.session.expire_all()
persisted_case = db.session.get(ShippingCase, case.id)
persisted_task = db.session.get(ShippingTask, task.id)
persisted_task = db.session.get(ShippingNotice, task.id)
assert persisted_case.customer_id is None
assert persisted_case.business_no is None
assert persisted_task.customer_resolution_status == "pending"
@@ -150,7 +150,7 @@ def test_business_number_query_returns_latest_revision(app):
with app.app_context():
task, case, customer = _seed_case()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
revision = ShippingTask(
revision = ShippingNotice(
task_no="SN-NUMBER-QUERY-REV",
shipping_case_id=case.id,
supersedes_task_id=task.id,
@@ -1,80 +0,0 @@
"""
tests/test_shipping_cancelled_task_readonly.py
用途:验收建单后取消将 Task 置 pending_void、Excel/Version 只读,禁止物理删除。
依赖:freight_cancellation_service、workflow_ledger_service、_seed_run_input。
逻辑:断言 lifecycle、void_reason、version.is_readonly、审计 before/after、文件路径保留。
"""
from __future__ import annotations
from app import db
from app.models import ShippingTask
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowItemVersion
from app.services.shipping_notice.freight_cancellation_service import mark_cancelled_task_readonly
from app.services.shipping_notice.workflow_ledger_service import (
ensure_open_workflow,
ensure_workflow_item_for_document,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
def test_mark_cancelled_task_readonly_sets_pending_void_without_delete(app):
"""取消后 Task 为 pending_void,导出路径保留,Version 只读。"""
with app.app_context():
user, agent, session, _intake, document = _seed_run_input(suffix='CANCEL-RO')
workflow = ensure_open_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),
)
task = ShippingTask(
task_no='SN-CANCEL-RO-1',
user_id=int(user.id),
conversation_id=session.session_id,
process_status='waiting_upload',
lifecycle_status='active',
export_file_path='/tmp/keep-excel.xlsx',
export_file_name='keep-excel.xlsx',
source_type='review_confirmation',
)
db.session.add(task)
db.session.flush()
item.current_task_no = task.task_no
version = (
ShippingNoticeWorkflowItemVersion.query
.filter_by(workflow_item_id=int(item.id), is_current=True)
.first()
)
assert version is not None
version.task_id = int(task.id)
version.task_no = task.task_no
version.excel_artifact_no = 'ART-1'
version.is_readonly = False
db.session.commit()
result = mark_cancelled_task_readonly(
task=task,
actor_id=int(user.id),
reason='user cancelled after excel',
workflow_item_no=item.item_no,
)
db.session.commit()
# 关键断言:软作废 + 文件保留 + Version 只读。
assert task.lifecycle_status == 'pending_void'
assert task.void_reason == 'user cancelled after excel'
assert task.export_file_path == '/tmp/keep-excel.xlsx'
assert result['physical_delete'] is False
assert result['readonly'] is True
assert result['before']['lifecycle_status'] == 'active'
assert result['after']['lifecycle_status'] == 'pending_void'
refreshed = db.session.get(ShippingNoticeWorkflowItemVersion, int(version.id))
assert refreshed is not None
assert refreshed.is_readonly is True
@@ -12,8 +12,10 @@ from types import SimpleNamespace
from app.services.shipping_notice.candidate_qualification_service import (
evaluate_candidate_qualification,
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.order_build_eligibility_service import assess_auto_build_gates
from app.services.shipping_notice.candidate_service import evaluate_candidate_stp_gate
def _eligible_candidate(**overrides):
@@ -40,6 +42,14 @@ def _eligible_candidate(**overrides):
return SimpleNamespace(**base)
def test_review_case_customer_confirmation_does_not_fall_back_to_another_pdf_in_same_run():
"""当前 Case 无确认客户时,同 Run 其他 PDF 的确认结果不得让它通过客户门禁。"""
case = SimpleNamespace(run_id=123)
# 关键断言:没有当前 Candidate/Extraction 的确认记录时必须 fail-closed。
assert resolve_review_case_customer_resolved(case=case, candidate=None) is False
def test_profile_unapproved_but_qualified_candidate_is_eligible(monkeypatch):
"""模板未批准但 Candidate 合格 → eligible,允许自动建单。"""
monkeypatch.setattr(
@@ -70,6 +80,37 @@ def test_profile_unapproved_but_qualified_candidate_is_eligible(monkeypatch):
assert 'profile_not_auto_freeze_approved' not in result['blocking_reason_codes']
def test_layout_table_review_diagnostic_does_not_block_auto_create(monkeypatch):
"""版面表格诊断只影响高亮质量,不得伪装成字段冲突阻断自动建单。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(conflicts_json=[{
'field': 'document_layout',
'severity': 'blocking',
'reason': 'layout_table_needs_review',
'document_id': 117,
}])
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
# 关键断言:诊断仍可保留在 Candidate,但不进入字段冲突建单门禁。
assert result['gates']['field_conflicts_resolved'] is True
assert result['can_auto_create'] is True
assert 'field_conflict' not in result['blocking_reason_codes']
passed, reason_codes = evaluate_candidate_stp_gate(candidate)
# 关键断言:旧 Candidate 仍携带该诊断时,最终 STP 履约校验也不得二次拦截。
assert passed is True
assert 'blocking_conflict' not in reason_codes
def test_llm_candidate_can_pass_unified_gates(monkeypatch):
"""LLM Candidate 具备分类/字段置信度与证据时可通过统一门禁 → eligible。"""
monkeypatch.setattr(
@@ -284,3 +325,35 @@ def test_assess_auto_build_gates_no_longer_requires_approved_template(monkeypatc
assert 'approved_template' not in result['gates']
assert result['can_auto_create'] is True
assert result['qualification']['status'] == 'eligible'
def test_pdf_preferred_critical_conflict_blocks_auto_create_with_review(monkeypatch):
"""
PDF 关键冲突须阻断自动建单,并映射为 review_required + 细因码。
断言:can_auto_create=False;blocking_reason_codes 含 pdf_preferred_critical_conflict。
"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
candidate = _eligible_candidate(
conflicts_json=[{
'field': 'po_number',
'severity': 'blocking',
'reason': 'pdf_preferred_critical_conflict',
'owning_gate_code': 'field_conflict_resolution',
}],
validation_status='needs_review',
)
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 'field_conflicts_resolved' in result['failed_gates']
assert 'pdf_preferred_critical_conflict' in result['blocking_reason_codes']
assert 'field_conflict' not in result['blocking_reason_codes']
assert result['status'] == 'review_required'
@@ -24,10 +24,10 @@ from app.services.shipping_notice.chat_action_handlers import (
def _create_task(user_id: int) -> str:
from app.models import ShippingBatch, ShippingTask
from app.models import ShippingBatch, ShippingNotice
batch = ShippingBatch(batch_no="BATCH-HANDLER-001", user_id=user_id, file_count=1)
task = ShippingTask(
task = ShippingNotice(
task_no="SN-20260706-EFGH5678",
batch=batch,
user_id=user_id,
@@ -7,7 +7,7 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ForbiddenError
from app.models import Agent, ChatSession, ShippingTask, User
from app.models import Agent, ChatSession, ShippingNotice, User
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability
@@ -18,8 +18,8 @@ def test_chat_capability_rejects_cross_task_and_expired_scope(app):
agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True)
db.session.add_all([user, agent]); db.session.flush()
session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id)
own = ShippingTask(task_no='SN-CAP-OWN', user_id=user.id, source_type='test')
other = ShippingTask(task_no='SN-CAP-OTHER', source_type='test')
own = ShippingNotice(task_no='SN-CAP-OWN', user_id=user.id, source_type='test')
other = ShippingNotice(task_no='SN-CAP-OTHER', source_type='test')
db.session.add_all([session, own, other]); db.session.commit()
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None)
assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id
@@ -83,6 +83,7 @@ def test_audit_event_type_group_filters_use_frozen_dictionaries(app) -> None:
('candidate_qualification', 'candidate_qualification_evaluated'),
('workflow_node', 'upload_rpa_triggered'),
('review_workbench', 'review_confirmed'),
('conversation_processing', 'conversation_processing_task_submission_decided'),
)
for group, marker in cases:
filtered = _apply_filters(base, filters={'event_type_group': group})
@@ -0,0 +1,108 @@
"""
backend/tests/test_shipping_conversation_processing_api.py
用途:验收统一 shipping-processing / focus / viewed 工作台 API 信封。
依赖:Flask 测试客户端、JWT、_seed_run_input、create_order_extraction_run、order_task_service。
逻辑:Candidate 前仅 order_intake;分配 OT 后可 focus/viewed;旧 /processing GET 已移除。
"""
from __future__ import annotations
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_task_service import (
allocate_user_task_no_for_run,
upsert_order_task_from_run,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
def test_workspace_shipping_processing_and_focus_viewed_api(app, client):
"""Candidate 前仅 intake;形成 OT 后 focus/viewed 可用。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='API-PROC')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
token = issue_local_access_token(user)
session_id = session.session_id
intake_no = intake.intake_no
run_id = int(run.id)
intake_id = int(intake.id)
document_id = int(document.id)
assert run.user_task_no is None
headers = {'Authorization': f'Bearer {token}'}
processing = client.get(
f'/api/workspace/shipping-processing/conversations/{session_id}',
headers=headers,
)
assert processing.status_code == 200, processing.get_json()
body = processing.get_json()
assert body['success'] is True
work_items = body['data'].get('work_items') or []
assert any(
str(row.get('work_item_type') or '') == 'order_intake'
and str(row.get('work_item_no') or '') == intake_no
for row in work_items
if isinstance(row, dict)
)
assert not any(
str(row.get('work_item_type') or '') == 'order_task'
for row in work_items
if isinstance(row, dict)
)
legacy = client.get(
f'/api/workspace/shipping-notice/conversations/{session_id}/processing',
headers=headers,
)
assert legacy.status_code == 404
with app.app_context():
run = db.session.get(ShippingOrderProcessingRun, run_id)
assert run is not None
candidate = ShippingOrderCandidate(
candidate_no=f'SNC-API-PROC-{run_id}',
intake_id=intake_id,
primary_document_id=document_id,
candidate_key=f'key-api-proc-{run_id}',
order_extraction_run_id=run_id,
is_current_version=True,
candidate_status='provisional',
structured_result_json={},
)
db.session.add(candidate)
db.session.flush()
allocate_user_task_no_for_run(run)
upsert_order_task_from_run(
run,
intake_id=intake_id,
candidate_id=int(candidate.id),
source_type='direct_pdf',
stage='candidate_created',
)
db.session.commit()
user_task_no = str(run.user_task_no)
focus = client.post(
f'/api/workspace/shipping-notice/conversation-tasks/{user_task_no}/focus',
json={'conversation_id': session_id},
headers=headers,
)
assert focus.status_code == 200, focus.get_json()
assert focus.get_json()['data']['focused_task_no'] == user_task_no
viewed = client.post(
f'/api/workspace/shipping-notice/conversation-tasks/{user_task_no}/viewed',
json={'conversation_id': session_id},
headers=headers,
)
assert viewed.status_code == 200, viewed.get_json()
@@ -0,0 +1,259 @@
"""
backend/tests/test_shipping_conversation_processing_audit.py
用途:验收会话多任务提交/聚焦/查看的审计闭环与追加优先级(composer > focus)。
依赖:Flask/SQLite 夹具、submit_order_extraction、focus/viewed、ShippingAuditEvent。
逻辑:Candidate 前 user_task_no 为 NULL;审计用 run_no / effective 派生键;
focus/viewed 仅在分配真实 OT 后可用。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ShippingAuditEvent, ShippingOrderCandidate, ShippingOrderProcessingRun
from app.services.shipping_notice.order_extraction_run_service import (
_effective_user_task_no,
create_order_extraction_run,
focus_conversation_task,
mark_conversation_task_viewed,
submit_order_extraction,
)
from app.services.shipping_notice.order_task_service import (
allocate_user_task_no_for_run,
upsert_order_task_from_run,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _audit_types_for_run(run_no: str) -> set[str]:
rows = ShippingAuditEvent.query.filter(
ShippingAuditEvent.run_no == run_no,
).all()
return {str(row.event_type) for row in rows}
def test_submit_created_writes_decision_and_created_audits(app):
"""新建提交写 submission_decided + created;Candidate 前 user_task_no 为 NULL。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUD-CRT')
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-AUD-CREATE-1',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-AUD-1',
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['user_task_no'] is None
events = ShippingAuditEvent.query.filter(
ShippingAuditEvent.conversation_id == session.session_id,
ShippingAuditEvent.run_no == payload['run_no'],
).all()
types = {str(row.event_type) for row in events}
assert 'conversation_processing_task_submission_decided' in types
assert (
'conversation_processing_task_created_new_run' in types
or 'conversation_processing_task_created' in types
)
def test_submit_cross_intake_writes_created_audit(app):
"""跨 Intake 提交因裁决边界新建 Run,写 created + submission_decided。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='AUD-APP')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-AUD-APP-1',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-AUD-APP',
)
db.session.commit()
_, _, _, second_intake, _ = _seed_run_input(
suffix='AUD-APP-2',
agent_code='shipping_notice_aud_app_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
second_intake.upload_batch_id = intake.upload_batch_id
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-AUD-APP-2',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-AUD-APP',
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['run_no'] != first['run_no']
types = _audit_types_for_run(payload['run_no'])
assert 'conversation_processing_task_submission_decided' in types
def test_composer_context_prefers_matching_appendable_run(app):
"""composer_context_id 优先于会话内最近可追加任务;跨 Intake 因边界新建。"""
with app.app_context():
user, agent, session, intake_a, _ = _seed_run_input(suffix='CMP-A')
run_a, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_a.intake_no],
keep_input_open=True,
composer_context_id='CMP-TARGET',
)
db.session.commit()
_, _, _, intake_b, _ = _seed_run_input(
suffix='CMP-B',
agent_code='shipping_notice_cmp_b',
)
intake_b.user_id = user.id
intake_b.conversation_id = session.session_id
db.session.commit()
run_b, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_b.intake_no],
keep_input_open=True,
composer_context_id='CMP-OTHER',
allow_parallel_conversation_runs=True,
)
db.session.commit()
assert run_b.created_at is not None and run_a.created_at is not None
assert run_b.created_at >= run_a.created_at
_, _, _, intake_c, _ = _seed_run_input(
suffix='CMP-C',
agent_code='shipping_notice_cmp_c',
)
intake_c.user_id = user.id
intake_c.conversation_id = session.session_id
intake_c.upload_batch_id = intake_a.upload_batch_id
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_c.intake_no],
submission_id='SUB-CMP-PREF-1',
upload_batch_id=intake_a.upload_batch_id,
composer_context_id='CMP-TARGET',
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['reason_code'] == 'adjudication_unit_boundary'
assert payload['run_no'] != run_a.run_no
def test_focus_and_viewed_write_audits_and_projection(app):
"""focus/viewed 在真实 OT 分配后写审计。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='AUD-FOCUS')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
db.session.commit()
candidate = ShippingOrderCandidate(
candidate_no=f'SNC-AUD-FOCUS-{run.id}',
intake_id=int(intake.id),
primary_document_id=int(document.id),
candidate_key=f'key-aud-focus-{run.id}',
order_extraction_run_id=int(run.id),
is_current_version=True,
candidate_status='provisional',
structured_result_json={},
)
db.session.add(candidate)
db.session.flush()
allocate_user_task_no_for_run(run)
upsert_order_task_from_run(
run,
intake_id=int(intake.id),
candidate_id=int(candidate.id),
source_type='direct_pdf',
stage='candidate_created',
)
db.session.commit()
task_no = str(run.user_task_no)
focused = focus_conversation_task(
user_id=user.id,
conversation_id=session.session_id,
task_no=task_no,
)
db.session.commit()
assert focused['focused_task_no'] == task_no
assert focused['processing']['focused_task_no'] == task_no
viewed = mark_conversation_task_viewed(
user_id=user.id,
conversation_id=session.session_id,
task_no=task_no,
)
db.session.commit()
refreshed = ShippingOrderProcessingRun.query.filter_by(id=run.id).one()
assert refreshed.seen_at is not None
assert viewed['processing']['summary']['total_tasks'] >= 1
def test_frozen_run_creates_new_task_with_audit(app):
"""输入冻结后新建 Run,审计含 submission_decided。"""
with app.app_context():
user, agent, session, intake, _ = _seed_run_input(suffix='AUD-FRZ')
first_payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-AUD-FRZ-1',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
first = ShippingOrderProcessingRun.query.filter_by(run_no=first_payload['run_no']).one()
first.input_lifecycle = 'frozen'
first.input_frozen_at = datetime.utcnow()
db.session.commit()
_, _, _, second_intake, _ = _seed_run_input(
suffix='AUD-FRZ-2',
agent_code='shipping_notice_aud_frz_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-AUD-FRZ-2',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['run_no'] != first_payload['run_no']
types = _audit_types_for_run(payload['run_no'])
assert 'conversation_processing_task_submission_decided' in types
@@ -0,0 +1,77 @@
"""
backend/tests/test_shipping_conversation_processing_contract_stage0.py
用途:验收会话多任务聚合阶段 0 契约冻结(事件字典、分组、追加阻断码、决策码)。
依赖:progress_audit_contract、audit_query_service、pytest。
逻辑:仅断言词典完备与查询分组映射;写路径与 UI 在阶段 1+ 接线,本文件不测业务副作用。
"""
from __future__ import annotations
from app.services.shipping_notice.audit_query_service import _apply_filters
from app.services.shipping_notice.progress_audit_contract import (
CONVERSATION_PROCESSING_APPEND_BLOCK_REASONS,
CONVERSATION_PROCESSING_SUBMISSION_DECISIONS,
CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES,
CONVERSATION_PROCESSING_TASK_GROUPS,
CONVERSATION_USER_TASK_INPUT_LIFECYCLES,
)
def test_conversation_processing_task_audit_events_are_frozen() -> None:
"""会话多任务 10 个审计事件码必须冻结,禁止前端/Worker 私造。"""
required = {
'conversation_processing_task_created',
'conversation_processing_task_submission_decided',
'conversation_processing_task_appended',
'conversation_processing_task_created_new_run',
'conversation_processing_task_version_replaced',
'conversation_processing_task_version_restored',
'conversation_processing_task_append_rejected',
'conversation_processing_task_focused',
'conversation_processing_task_viewed',
'conversation_processing_task_acknowledged',
}
# 关键断言:集合相等,防止悄悄增删未评审事件名。
assert CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES == required
def test_conversation_processing_group_and_decision_dictionaries() -> None:
"""顶层分组、提交决策、输入生命周期与追加阻断原因须形成唯一词典。"""
assert CONVERSATION_PROCESSING_TASK_GROUPS == {
'needs_action',
'processing',
'completed',
'history',
}
assert CONVERSATION_PROCESSING_SUBMISSION_DECISIONS == {'appended', 'created'}
assert CONVERSATION_USER_TASK_INPUT_LIFECYCLES == {
'open',
'freezing',
'frozen',
'closed',
}
assert 'input_already_frozen' in CONVERSATION_PROCESSING_APPEND_BLOCK_REASONS
assert 'no_appendable_context' in CONVERSATION_PROCESSING_APPEND_BLOCK_REASONS
assert 'composer_context_mismatch' in CONVERSATION_PROCESSING_APPEND_BLOCK_REASONS
def test_conversation_processing_event_type_group_filter(app) -> None:
"""
event_type_group=conversation_processing 须映射到冻结字典。
断言:编译后的 SQL 包含已知会话多任务事件码。
"""
from app.models import ShippingAuditEvent
with app.app_context():
base = ShippingAuditEvent.query
for group in (
'conversation_processing',
'conversation_processing_task',
'conversation_tasks',
):
filtered = _apply_filters(base, filters={'event_type_group': group})
sql = str(filtered.statement.compile(compile_kwargs={'literal_binds': True}))
assert 'conversation_processing_task_submission_decided' in sql
assert 'event_type' in sql.lower()
@@ -12,6 +12,7 @@ from pydantic import ValidationError
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
_text_in_region,
reconstruct_coordinate_profile_rows,
reconstruct_table_from_positioned_text,
resolve_line_start_field_code,
@@ -19,17 +20,8 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
suggest_header_regions,
suggest_multi_subrow_layouts,
)
from app.services.shipping_notice.document_layout.order_profile import (
CoordinateReconstructionProfile,
OrderDocumentProfile,
OrderProfileColumnRule,
TableRegionProfile,
order_profile_structure_fingerprint,
parse_html_table_with_order_profile,
reconstruct_order_profile_html,
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile
from app.services.shipping_notice.order_extraction_workflow import (
_build_approved_profile_order,
_validate_table_header_outputs,
@@ -72,6 +64,25 @@ def _adaptive_layouts() -> list[dict]:
]
def test_table_region_text_prefers_explicit_pdf_space_boundary():
"""明细自由文本列应恢复 PDF 原始词边界,同时不依赖降低全局几何阈值。"""
glyphs = [
(index, PositionedCharacter(
text=character,
source_index=source_index,
boundary_before='space' if character == 'A' else 'none',
bbox=LayoutBBox(x0=x0, y0=20, x1=x0 + 6, y1=28),
))
for index, (character, source_index, x0) in enumerate([
('S', 0, 10), ('h', 1, 16), ('i', 2, 22), ('p', 3, 28),
('A', 5, 36.8), ('d', 6, 42.8), ('d', 7, 48.8), ('r', 8, 54.8),
])
]
# gap=2.8 低于该链路旧阈值 3.9,必须由明确文本流边界恢复。
assert _text_in_region(glyphs, LayoutBBox(x0=0, y0=0, x1=100, y1=50)) == 'Ship Addr'
def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows():
"""显式策略应同时读取同一行或拆行的数量、单位、日期与金额,旧默认策略不受影响。"""
compact = reconstruct_coordinate_profile_rows(
@@ -433,6 +444,31 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
assert [(row.fields['customer_po_line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
def test_coordinate_profile_rows_deleted_marker_keeps_next_record_and_field_evidence():
"""精确删除标记应排除前一条并继续读取下一条,同时保留字段实际 glyph 坐标。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-DELETED', 65)],
[('** Item deleted **', 65)],
[('00020', 10), ('PART-KEEP', 65), ('36', 145)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .7, 'y1': 1}},
{'field_code': 'qty', 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}},
]}], exclusion_regions=[{'x0': .25, 'y0': .3, 'x1': .8, 'y1': .5}],
)
assert [row.fields for row in rows] == [{
'customer_po_line_no': '00020', 'part_number': 'PART-KEEP', 'qty': '36',
}]
evidence = rows[0].field_evidence['qty']
assert evidence['bbox_text'] == '36'
assert evidence['value_bbox'] == {'x0': 145.0, 'y0': 48.0, 'x1': 152.0, 'y1': 58.0}
assert len(evidence['glyph_indices']) == 2
def test_coordinate_profile_rows_ignore_unconfigured_deleted_marker():
"""关键断言:没有排除区授权时,删除文字不能擅自删除前一条有效订单明细。"""
rows = reconstruct_coordinate_profile_rows(
@@ -803,6 +839,34 @@ def test_currency_composite_output_becomes_header_only_when_all_rows_agree():
) is None
def test_profile_order_carries_coordinate_field_evidence_into_observation():
"""坐标重建字段的页码、值框与 token 必须完整进入最终机器 Observation。"""
definition = {'fields': [{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'enabled': True, 'collection_mode': 'llm_extraction', 'required': True,
}]}
table = {'rows': [{'status': 'parsed', 'issues': [], 'fields': [{
'field_id': 'part-id', 'field_code': 'part_number', 'value': 'PART-A', 'quote': 'PART-A',
'page_no': 1, 'table_id': 'table-1',
'value_bbox': {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30},
'glyph_indices': [5, 6, 7], 'token_ids': ['g5', 'g6', 'g7'],
'bbox_text': 'PART-A', 'quote_source': 'glyph_region',
'source': 'pdf_coordinate', 'has_value_coordinate': True,
'coordinate_status': 'candidate', 'highlight_quality': 'candidate',
}]}]}
order = _build_approved_profile_order(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-9'},
schema={'schema_version_id': 1, 'checksum': 'a' * 64}, definition=definition, table=table,
)
observation = order['lines'][0]['fields'][0]['observations'][0]
assert observation['value'] == 'PART-A'
assert observation['layout_evidence']['page_no'] == 1
assert observation['layout_evidence']['value_bbox'] == {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30}
assert observation['layout_evidence']['token_ids'] == ['g5', 'g6', 'g7']
def test_coordinate_reconstruction_uses_x_y_and_continuation_rules():
"""行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。"""
result = _reconstruct(_glyphs(
@@ -828,39 +892,6 @@ def test_coordinate_reconstruction_only_attaches_deleted_marker_to_prior_line():
assert unattached.issues == ['coordinate_reconstruction_deleted_row_unattached']
def test_reconstructed_profile_html_uses_confirmed_relative_column_boundaries():
"""坐标模板用稳定虚拟表头并合并续行,不能回退到错误 HTML 的行列关系。"""
html = reconstruct_order_profile_html(
characters=_glyphs(
[('ITEM NO', 12), ('MATERIAL', 62)],
[('00010', 12), ('PART-A', 62)],
[('PART-A-DETAIL', 62)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 120, 'y1': 70},
reconstruction=CoordinateReconstructionProfile(column_boundaries=[0, 0.4, 1]),
)
assert 'coordinate_column_1' in html
assert 'ITEM NO' not in html
assert 'PART-A PART-A-DETAIL' in html
assert html.count('<tr ') == 2
def test_reconstructed_profile_html_marks_deleted_and_stops_at_summary():
"""删除标记回写最近明细;TOTAL AMOUNT 之后的文本不得进入逻辑明细。"""
html = reconstruct_order_profile_html(
characters=_glyphs(
[('00010', 12), ('PART-A', 62)],
[('** Item deleted **', 62)],
[('TOTAL AMOUNT', 62), ('100.00', 150)],
[('00020', 12), ('PART-B', 62)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
reconstruction=CoordinateReconstructionProfile(column_boundaries=[0, 0.3, 0.7, 1]),
)
assert 'data-row-role="deleted"' in html
assert 'PART-B' not in html
def test_coordinate_reconstruction_uses_fixed_field_content_for_boundary_tie():
"""字符恰好跨数量与单位边界时,固定字段类型只能作为几何并列的辅助证据。"""
result = reconstruct_table_from_positioned_text(
@@ -878,161 +909,6 @@ def test_coordinate_reconstruction_uses_fixed_field_content_for_boundary_tie():
assert result.rows[0].cells[0].text == 'EA'
def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
"""端到端验证:一条数据行加两条续行只能产出一条可审核订单明细。"""
settings = CoordinateReconstructionProfile(
column_boundaries=[0, 0.2, 0.7, 1],
column_field_codes=['customer_po_line_no', 'part_number', 'qty'],
)
html = reconstruct_order_profile_html(
characters=_glyphs(
[('00020', 12), ('6Y70B2501901', 52), ('30', 160)],
[('D4-A08AR1200002', 52)],
[('RoHS2', 52)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
reconstruction=settings,
)
grid = parse_html_grid(html, table_id='inventec')
profile = OrderDocumentProfile(
profile_code='INVENTEC_PO', version=1,
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
header_row_index=0, data_start_row_index=1,
column_rules=[
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['part_number']),
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
],
coordinate_reconstruction=settings,
)
contract = compile_table_header_contract({'fields': [
{'field_code': 'customer_po_line_no', 'display_name': 'Customer PO Line', 'enabled': True},
{'field_code': 'part_number', 'display_name': 'Part', 'enabled': True},
{'field_code': 'qty', 'display_name': 'Qty', 'value_type': 'decimal', 'enabled': True},
]})
parsed = parse_html_table_with_order_profile(html, table_id='inventec', profile=profile, contract=contract)
assert parsed.matched is True
assert len(parsed.rows) == 1
assert parsed.rows[0].fields == {
'customer_po_line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
}
def test_multi_subrow_profile_uses_independent_overlapping_boundaries():
"""主行和补充行可在相同横坐标表达不同字段,并合并为一条逻辑明细。"""
settings = CoordinateReconstructionProfile(subrow_layouts=[
{
'role': 'main', 'row_offset': 0,
'column_boundaries': [0, 0.12, 0.32, 0.5, 0.68, 0.84, 1],
'column_field_codes': ['customer_po_line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
},
{
'role': 'continuation', 'row_offset': 1,
'column_boundaries': [0, 0.18, 0.48, 0.7, 1],
'column_field_codes': [None, 'customer_part_number', 'required_date', 'remark'],
},
{
'role': 'continuation', 'row_offset': 2,
'column_boundaries': [0, 0.25, 0.55, 1],
'column_field_codes': [None, 'inventory_source_hint', 'remark'],
},
])
html = reconstruct_order_profile_html(
characters=_glyphs(
[('00020', 12), ('6Y70B2501901', 46), ('SET,RACK', 102), ('941.76', 154), ('30', 208), ('EA', 260)],
[('D4-A08AR1200002', 58), ('06/29/2026', 150), ('Ship by land', 220)],
[('RoHS2', 82), ('EXW AWS HUB', 180)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
reconstruction=settings,
)
assert html.count('data-row-role="data"') == 1
assert '6Y70B2501901' in html
assert 'D4-A08AR1200002' in html
assert '06/29/2026' in html
assert 'EXW AWS HUB' in html
assert 'data-source-rows="0,1,2"' in html
def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser():
"""多子行输出必须继续由既有固定列 Profile 解析器消费,避免另造运行链路。"""
settings = CoordinateReconstructionProfile(subrow_layouts=[
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
'column_field_codes': [None, 'required_date', 'line_remark']},
])
html = reconstruct_order_profile_html(
characters=_glyphs(
[('00020', 12), ('PART-20', 70), ('30', 240)],
[('06/29/2026', 135), ('Ship by land', 235)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
reconstruction=settings,
)
grid = parse_html_grid(html, table_id='multi-subrow')
headers = ['customer_po_line_no', 'part_number', 'qty', 'required_date', 'line_remark']
profile = OrderDocumentProfile(
profile_code='MULTI_SUBROW', version=1,
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
header_row_index=0, data_start_row_index=1,
column_rules=[
OrderProfileColumnRule(column_index=index, extractor_key='direct', target_field_codes=[code])
for index, code in enumerate(headers)
],
coordinate_reconstruction=settings,
)
contract = compile_table_header_contract({'fields': [
{'field_code': 'customer_po_line_no', 'enabled': True},
{'field_code': 'part_number', 'enabled': True},
{'field_code': 'qty', 'value_type': 'decimal', 'enabled': True},
{'field_code': 'required_date', 'value_type': 'date', 'enabled': True},
{'field_code': 'line_remark', 'enabled': True},
]})
parsed = parse_html_table_with_order_profile(html, table_id='multi-subrow', profile=profile, contract=contract)
assert parsed.matched is True
assert len(parsed.rows) == 1
assert parsed.rows[0].fields['part_number'] == 'PART-20'
assert parsed.rows[0].fields['qty'] == 30
assert parsed.rows[0].fields['required_date'] == '2026-06-29'
assert parsed.rows[0].fields['line_remark'] == 'Ship by land'
def test_multi_subrow_profile_supports_four_or_more_physical_rows():
"""逻辑明细行数由模板动态定义,四行版式不得被固定三行实现截断。"""
settings = CoordinateReconstructionProfile(subrow_layouts=[
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
'column_field_codes': [None, 'customer_part_number']},
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
'column_field_codes': [None, 'required_date']},
{'role': 'continuation', 'row_offset': 3, 'column_boundaries': [0, 0.5, 1],
'column_field_codes': [None, 'remark']},
])
html = reconstruct_order_profile_html(
characters=_glyphs(
[('10', 12), ('PART-10', 100), ('3', 270)],
[('VENDOR-10', 180)],
[('05/05/2026', 180)],
[('R2_SA;HF_SA', 180)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 320, 'y1': 100},
reconstruction=settings,
)
assert html.count('data-row-role="data"') == 1
assert 'data-source-rows="0,1,2,3"' in html
assert 'VENDOR-10' in html
assert '05/05/2026' in html
assert 'R2_SA;HF_SA' in html
def test_layout_suggestion_uses_real_rows_and_dynamic_column_counts():
"""自动建议应从真实横坐标生成动态行数,并忽略表头和合计区域。"""
suggestions = suggest_multi_subrow_layouts(
@@ -2,7 +2,7 @@
backend/tests/test_shipping_customer_auto_resolution.py
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
依赖:客户主数据/证据、Candidate 影子结果、ShippingTask/Case、customer_auto_resolution。
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice/Case、customer_auto_resolution。
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
"""
@@ -20,16 +20,16 @@ from app.models import (
ShippingIdentityDefinition,
ShippingIdentityEvidence,
ShippingIdentityRuleSet,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingTask,
ShippingNotice,
ShippingTaskEvent,
User,
)
@@ -105,19 +105,19 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f"AUTO-INTAKE-{user.id}", asset_id=asset.id, user_id=user.id,
parser_version="v6", parse_status="parsed", structured_result_json={"email": {"from": sender}},
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type="attachment", attachment_key="file",
filename="notice.pdf", classification="order_notice", parse_status="parsed",
)
db.session.add(document)
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate = ShippingOrderCandidate(
candidate_no=f"AUTO-CAND-{user.id}", intake_id=intake.id, primary_document_id=document.id,
candidate_key="document:1", validation_status="ready", selected=True,
structured_result_json={"business_summary": {"customer_name": "unstable name"}},
@@ -125,7 +125,7 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending")
db.session.add_all([candidate, case])
db.session.flush()
task = ShippingTask(
task = ShippingNotice(
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
user_id=user.id, source_type="email_attachment", process_status="parsed",
customer_resolution_status="pending",
@@ -278,7 +278,7 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
db.session.rollback()
db.session.expire_all()
persisted_task = db.session.get(ShippingTask, task_id)
persisted_task = db.session.get(ShippingNotice, task_id)
persisted_case = db.session.get(ShippingCase, case_id)
assert persisted_task.customer_resolution_status == "pending"
assert persisted_case.customer_id is None
@@ -416,13 +416,13 @@ def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending")
db.session.add_all([wrong, correct, case])
db.session.flush()
first = ShippingTask(
first = ShippingNotice(
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
source_type="manual", process_status="parsed", customer_resolution_status="pending",
)
db.session.add(first)
db.session.flush()
latest = ShippingTask(
latest = ShippingNotice(
task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2,
supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload",
customer_resolution_status="pending", inventory_source_code="DSV",
@@ -474,7 +474,7 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending")
db.session.add_all([wrong, correct, case])
db.session.flush()
task = ShippingTask(
task = ShippingNotice(
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
source_type="manual", process_status="parsed", customer_resolution_status="pending",
)
@@ -15,7 +15,7 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent, User
from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
from app.services.shipping_notice.customer_identity_gate import (
assert_customer_identity_gate,
confirm_task_customer,
@@ -31,7 +31,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.task_workflow import retry_task
def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustomer, User]:
def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
"""创建待确认任务、启用客户和任务用户。"""
sequence = db.session.query(User).count()
user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user')
@@ -43,7 +43,7 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustome
if case:
db.session.add(case)
db.session.flush()
task = ShippingTask(
task = ShippingNotice(
task_no=f'SN-GATE-{user.id}', user_id=user.id,
shipping_case_id=case.id if case else None,
customer_resolution_status='pending' if case else None,
@@ -116,7 +116,7 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
"""客户确认同步同业务单全部任务,并在同事务生成正式业务号。"""
with app.app_context():
task, customer, user = _seed_task()
revision = ShippingTask(
revision = ShippingNotice(
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
process_status='parsed',
@@ -15,8 +15,8 @@ import pytest
from app import db
from app.models import (
FileAsset, ShippingCase, ShippingCustomer, ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution, ShippingCustomerSite, ShippingNoticeCandidate,
ShippingNoticeDocument, ShippingNoticeIntake, ShippingOrderExtraction, ShippingOrderField,
ShippingCustomerShadowResolution, ShippingCustomerSite, ShippingOrderCandidate,
ShippingOrderDocument, ShippingOrderIntake, ShippingOrderExtraction, ShippingOrderField,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchema,
ShippingOrderSchemaVersion, User,
)
@@ -38,19 +38,19 @@ def _seed_candidate(*, sender: str = ''):
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f'SNI-{user.id}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
structured_result_json={'email': {'from': sender}},
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
filename='notice.pdf', classification='order_notice', parse_status='parsed', extracted_text='template text',
)
db.session.add(document)
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate = ShippingOrderCandidate(
candidate_no=f'SNC-{user.id}', intake_id=intake.id, primary_document_id=document.id,
candidate_key='document:1', validation_status='ready',
structured_result_json={'business_summary': {'customer_name': 'RAW LLM VALUE MUST NOT BE USED'}},
@@ -56,6 +56,54 @@ def test_layout_job_completes_version_and_updates_document_current(app):
assert version.lease_token is None
assert document.current_layout_version_id == version.id
assert job.status == 'success'
assert job.result_json['status'] == 'ready'
assert job.result_json['provider_status'] == 'ready'
assert job.message == '文档版面解析完成'
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
"""表内坐标可按需恢复时 Job/Layout 成功,并保留模板解析所需表格结构。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context():
document, version, job = _running_layout_job(app)
snapshot = {
**_snapshot(marker='compacted-worker'),
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'X' * 3000}]},
'tables': {'table-1': [{'text': 'Y' * 5000}]},
},
'layout_candidate': {'table_count': 1, 'tables': [{'table_id': 'table-1'}]},
}
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
), patch(
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
return_value=snapshot,
):
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(document)
db.session.refresh(job)
assert version.status == 'ready'
assert document.current_layout_version_id == version.id
assert job.status == 'success'
assert job.result_json['status'] == 'ready'
assert job.message == '文档版面解析完成'
assert version.payload_json['tables'] == snapshot['tables']
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in version.payload_json['coordinate_evidence']
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json
def test_layout_job_failure_requeues_version_and_clears_lease(app):
@@ -104,3 +152,57 @@ def test_layout_job_exhaustion_fails_version_without_leaking_provider_error(app)
assert version.status == 'failed'
assert version.lease_token is None
assert 'shipping_document_layout_job_exhausted' in version.issues_json
def test_layout_job_xfa_hybrid_skips_mineru_path(app):
"""XFA hybrid 文档不得进入 MinerU/PDFium 表格路径。"""
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
with app.app_context():
document, version, job = _running_layout_job(app)
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
with patch(
'app.jobs.handlers.shipping_document_layout.read_asset_bytes',
return_value=pdf_bytes,
), patch(
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
) as mineru_mock:
run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}),
{'job_id': job.id},
)
db.session.refresh(version)
db.session.refresh(document)
db.session.refresh(job)
mineru_mock.assert_not_called()
assert version.status == 'ready'
assert version.payload_json.get('provider') == 'xfa'
assert version.payload_json.get('tables') == []
assert version.payload_json['xfa_capability']['structure_analysis_ready'] is True
assert document.current_layout_version_id == version.id
assert job.status == 'success'
def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
"""runtime 在 XFA hybrid 探测成功后不得调用 MinerU。"""
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
with app.app_context():
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
with patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
) as mineru_client:
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
snapshot = build_mineru_table_snapshot(
filename='sample.pdf',
content=pdf_bytes,
document_id=1,
content_hash='a' * 64,
)
mineru_client.assert_not_called()
assert snapshot is not None
assert snapshot['provider'] == 'xfa'
assert snapshot['tables'] == []
@@ -2,14 +2,16 @@
backend/tests/test_shipping_document_layout_lifecycle.py
用途:验证 L1 版面快照 checksum、版本幂等、容量门禁和当前成功版本保护。
依赖:ShippingNoticeDocument/LayoutVersion、document_layout.lifecycle、Flask 测试库。
依赖:ShippingOrderDocument/LayoutVersion、document_layout.lifecycle、Flask 测试库。
逻辑:相同快照复用;新失败/超限版本保留审计但不覆盖旧成功引用。
"""
from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import Job, ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake, FileAsset, User
from app.models import Job, ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake, FileAsset, User
from app.services.shipping_notice.document_layout.lifecycle import (
canonical_layout_payload,
claim_layout_version,
@@ -21,9 +23,12 @@ from app.services.shipping_notice.document_layout.lifecycle import (
sync_layout_after_job_recovery,
)
from app.services.shipping_notice.document_layout import lifecycle as layout_lifecycle
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
ensure_on_demand_coordinate_evidence,
)
def _document() -> ShippingNoticeDocument:
def _document() -> ShippingOrderDocument:
"""创建带稳定内容哈希的最小附件 Document。"""
user = User(username='layout-owner', email='layout-owner@example.com', role='user', status='active')
db.session.add(user)
@@ -36,13 +41,13 @@ def _document() -> ShippingNoticeDocument:
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-L1', asset_id=asset.id, user_id=user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='sample.pdf', filename='sample.pdf', content_hash='a' * 64,
classification='order_notice', parse_status='parsed',
@@ -57,7 +62,9 @@ def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict:
return {
'snapshot_version': 'shipping_document_table_snapshot.v1',
'provider': 'mineru', 'provider_version': '3.1.14', 'backend': 'pipeline',
'status': status, 'tables': [], 'issues': [], 'marker': marker,
'status': status, 'tables': [], 'layout_candidate': {},
'coordinate_evidence': {'pages': {}, 'page_glyphs': {}},
'issues': [], 'marker': marker,
}
@@ -80,13 +87,13 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app):
def test_failed_or_oversized_layout_does_not_replace_last_good_version(app):
"""失败/超限版本必须可审计,但绝不能覆盖 Document 上一次成功布局。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 200
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 500
with app.app_context():
document = _document()
good = record_inline_layout_snapshot(document, _snapshot())
failed = record_inline_layout_snapshot(document, _snapshot(status='failed', marker='failed'))
oversized = record_inline_layout_snapshot(document, {
**_snapshot(marker='large'), 'tables': [{'html': 'X' * 500}],
**_snapshot(marker='large'), 'tables': [{'html': 'X' * 5000}],
})
db.session.commit()
@@ -125,14 +132,14 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
with app.app_context():
original = _document()
ready = record_inline_layout_snapshot(original, _snapshot())
duplicate_intake = ShippingNoticeIntake(
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id,
user_id=db.session.get(ShippingNoticeIntake, original.intake_id).user_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingNoticeDocument(
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
attachment_key='duplicate.pdf', filename='duplicate.pdf', content_hash=original.content_hash,
classification='order_notice', parse_status='parsed',
@@ -152,6 +159,37 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
assert ShippingDocumentLayoutVersion.query.count() == 2
def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
"""ready 快照缺整页证据但原 PDF 可读时应复用,正式识别再按需恢复坐标。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context():
original = _document()
incomplete = record_inline_layout_snapshot(original, {
**_snapshot(), 'coordinate_evidence': {'tables': {}},
})
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
attachment_key='duplicate-incomplete.pdf', filename='duplicate-incomplete.pdf',
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
)
db.session.add(duplicate)
db.session.flush()
scheduled = schedule_layout_version(duplicate)
db.session.commit()
assert incomplete.status == 'ready'
assert scheduled.status == 'ready'
assert scheduled.id != incomplete.id
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
"""布局实现指纹变化后自动创建新版本,不依赖人工修改环境变量。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
@@ -209,18 +247,167 @@ def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app):
assert document.current_layout_version_id == ready.id
def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app):
"""PDF 原件仍可读时,压缩整页/表内字符不得丢失模板所需表格结构。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context():
document = _document()
pending = schedule_layout_version(document, force=True)
job = db.session.get(Job, pending.job_id)
job.status = 'running'
job.attempts = 1
db.session.commit()
claimed = claim_layout_version(pending.id, job_id=job.id, owned_attempt=1)
assert claimed is not None
_version, lease = claimed
snapshot = {
**_snapshot(),
'tables': [{
'table_id': 'table-1',
'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'X' * 3000}]},
'tables': {'table-1': [{'text': 'Y' * 5000}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
'layout_candidate': {'table_count': 1, 'tables': [{'table_id': 'table-1'}]},
}
assert complete_layout_version(pending.id, lease_token=lease, snapshot=snapshot) is True
db.session.refresh(pending)
db.session.refresh(document)
assert pending.status == 'ready'
assert document.current_layout_version_id == pending.id
assert pending.payload_json['tables'] == snapshot['tables']
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in pending.payload_json['coordinate_evidence']
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence']
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json
assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json
def test_inline_layout_compacts_table_glyphs_without_changing_template_structures(app):
"""普通上传内联布局同样只压缩可恢复字符,模板表格与候选结构保持原样。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context():
document = _document()
snapshot = {
**_snapshot(marker='inline-compacted'),
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'X' * 3000}]},
'tables': {'table-1': [{'text': 'Y' * 5000}]},
},
'layout_candidate': {'table_count': 1, 'tables': [{'table_id': 'table-1'}]},
}
version = record_inline_layout_snapshot(document, snapshot)
assert version.status == 'ready'
assert version.payload_json['tables'] == snapshot['tables']
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in version.payload_json['coordinate_evidence']
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json
def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app):
"""压缩后顶层业务 tables 列表不得进入坐标映射并触发 dict 转换异常。"""
with app.app_context():
document = _document()
layout = {
**_snapshot(),
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
'html': '<table><tr><td>PO-1</td></tr></table>',
'cells': [], 'rows': [], 'columns': [], 'source': 'native', 'status': 'ready',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
record_inline_layout_snapshot(document, layout)
restored = ensure_on_demand_coordinate_evidence(
document=document,
layout=layout,
page_nos=set(),
)
assert restored['tables'] == layout['tables']
assert 'tables' not in restored['coordinate_evidence']
def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch):
"""同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。"""
with app.app_context():
document = _document()
layout = {
**_snapshot(),
'tables': [
{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 10, 'x1': 100, 'y1': 40}},
{'table_id': 'table-2', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 100, 'y1': 90}},
],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
page = SimpleNamespace(
page_no=1, width=100, height=200, image=None,
characters=[SimpleNamespace(model_dump=lambda mode='json': {'text': 'X'})],
)
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._native_characters_in_table',
lambda *, characters, table_bbox: [{'text': str(table_bbox['y0'])}],
)
restored = ensure_on_demand_coordinate_evidence(
document=document,
layout=layout,
page_nos={1},
# 兼容旧调用方即使只传入同页最后一张表,也不能覆盖 layout 中的第一张表。
table_by_page={1: layout['tables'][1]},
)
# 关键断言:同页表格不能被 page_no 字典覆盖,正式抽取可按真实 table_id 逐表重建。
assert restored['coordinate_evidence']['tables'] == {
'table-1': [{'text': '10'}],
'table-2': [{'text': '50'}],
}
def test_layout_document_budget_creates_unsupported_audit_versions(app):
"""超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 1
with app.app_context():
first = _document()
second = ShippingNoticeDocument(
second = ShippingOrderDocument(
intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment',
attachment_key='second.pdf', filename='second.pdf', content_hash='b' * 64,
classification='order_notice', parse_status='parsed',
)
text = ShippingNoticeDocument(
text = ShippingOrderDocument(
intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment',
attachment_key='notes.txt', filename='notes.txt', content_hash='c' * 64,
classification='order_notice', parse_status='parsed',
@@ -250,5 +437,5 @@ def test_deleting_document_cascades_layout_versions(app):
db.session.delete(document)
db.session.commit()
assert db.session.get(ShippingNoticeDocument, document_id) is None
assert db.session.get(ShippingOrderDocument, document_id) is None
assert db.session.get(ShippingDocumentLayoutVersion, version_id) is None
@@ -76,6 +76,68 @@ def _page(text: str) -> NativePdfPage:
)
def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
"""PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。"""
class FakeTextPage:
"""提供包含零 bbox 空格的最小 PDFium 文本页。"""
text = 'ZT Group'
def count_chars(self):
"""返回原始文本流字符数,包含空格。"""
return len(self.text)
def get_text_range(self, index, _count):
"""按 PDFium 单字符接口返回原始字符。"""
return self.text[index]
def get_charbox(self, index, loose=True):
"""可见字符返回有效坐标;空格不会进入该调用。"""
assert loose is True
return (10 + index * 4, 80, 13 + index * 4, 88)
class FakePage:
"""模拟无需渲染的单页 PDF。"""
def get_size(self):
"""返回固定页面尺寸。"""
return 200, 100
def get_textpage(self):
"""返回带逻辑空格的文本页。"""
return FakeTextPage()
def get_rotation(self):
"""样本不旋转。"""
return 0
class FakeDocument:
"""模拟 PDFium 文档的页数和索引访问。"""
def __init__(self, _content):
"""接受原始 bytes 但不解析。"""
def __len__(self):
"""测试文档仅一页。"""
return 1
def __getitem__(self, _index):
"""返回唯一页面。"""
return FakePage()
with patch(
'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument',
FakeDocument,
):
page = extract_native_pdf_pages(b'%PDF', render_images=False)[0]
# 关键断言:不创建伪空格 glyph,但 G 保留原始 index=3 和明确的前置空格证据。
assert ''.join(item.text for item in page.characters) == 'ZTGroup'
assert [item.source_index for item in page.characters] == [0, 1, 3, 4, 5, 6, 7]
assert page.characters[2].boundary_before == 'space'
assert all(item.bbox.x1 > item.bbox.x0 for item in page.characters)
def _fallback_page() -> NativePdfPage:
"""构造无框多行明细表;MinerU 未给 table 时只允许稳定表头触发原生 PDF 兜底。"""
characters = []
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_document_layout_runtime.py
用途:验证 Intake 阶段 MinerU 紧凑快照、PDFium 页面复用、降级行为和容量门禁。
用途:验证 MinerU 优先的紧凑快照、PDFium 页面复用、受控降级行为和容量门禁。
依赖:document_layout.runtime/mineru 构造候选、Flask 测试配置。
逻辑:Mock 客户端避免真实网络;只允许受预算文本块、表格 HTML 和能力摘要进入快照,原响应不得持久化。
逻辑:Mock 客户端避免真实网络;MinerU 有表格时不得被 PDFium 替换,只有空表或失败才允许严格回退。
"""
from __future__ import annotations
@@ -152,8 +152,56 @@ def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app
assert 'shipping_document_business_table_not_detected' in snapshot['issues']
def test_runtime_native_pdf_fast_path_skips_mineru_when_strict_table_evidence_exists(app):
"""文字型 PDF 可证明订单表格时应立即完成,不得继续等待 MinerU。"""
def test_runtime_empty_mineru_tables_use_pdfium_provider_fallback(app):
"""MinerU 真正返回空表时,严格原生表须成为显式 PDFium 降级快照。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
)
empty_candidate = _candidate().model_copy(update={'pages': [
_candidate().pages[0].model_copy(update={'tables': []}),
]})
page = type('Page', (), {'page_no': 1, 'width': 100, 'height': 200})()
table = {
'table_id': 'native-1', 'page_no': 1,
'bbox': {'x0': 0, 'y0': 20, 'x1': 100, 'y1': 100},
'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .5},
'html': '<table><tr><th>Item</th><th>Qty</th></tr><tr><td>10</td><td>1</td></tr></table>',
'row_count': 2, 'cell_count': 4, 'has_rowspan': False, 'has_colspan': False,
}
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[page],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks',
return_value=[table],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate',
) as build_layout, patch(
'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence',
return_value={'version': 'test'},
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
return_value={'status': 'completed'},
), patch(
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
return_value=empty_candidate,
):
build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'}
snapshot = build_mineru_table_snapshot(
filename='order.pdf', content=b'%PDF', document_id=1, content_hash='d' * 64,
)
assert snapshot['provider'] == 'pdfium'
assert snapshot['backend'] == 'native_pdf'
assert snapshot['tables'][0]['table_id'] == 'native-1'
assert snapshot['layout_candidate']['schema_version'] == 'shipping_document_layout.v1'
assert 'mineru_provider_fallback_used' in snapshot['issues']
assert 'mineru_table_structure_missing' in snapshot['issues']
def test_runtime_mineru_table_remains_primary_when_native_table_evidence_exists(app):
"""本地文字可恢复表格时仍须先调用 MinerU,且不得替换 Provider 已返回的表格。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
@@ -172,14 +220,18 @@ def test_runtime_native_pdf_fast_path_skips_mineru_when_strict_table_evidence_ex
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks',
return_value=[table],
), patch(
) as fallback, patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate',
) as build_layout, patch(
'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence',
return_value={'version': 'shipping_order_coordinate_evidence.v1'},
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
) as mineru:
return_value={'status': 'completed'},
) as mineru, patch(
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
return_value=_candidate(),
):
build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'}
timings: dict[str, int] = {}
snapshot = build_mineru_table_snapshot(
@@ -188,14 +240,15 @@ def test_runtime_native_pdf_fast_path_skips_mineru_when_strict_table_evidence_ex
)
assert snapshot['status'] == 'ready'
assert snapshot['provider'] == 'pdfium'
assert snapshot['tables'][0]['table_id'] == 'native-1'
assert timings['layout_fast_path'] == 1
mineru.assert_not_called()
assert snapshot['provider'] == 'mineru'
assert snapshot['tables'][0]['table_id'] == 'table-1'
assert 'layout_fast_path' not in timings
mineru.assert_called_once()
fallback.assert_not_called()
def test_runtime_native_fast_path_defers_page_rendering(app):
"""本地文字证据命中时只提取字符,不能预先渲染高分辨率页面图。"""
def test_runtime_provider_failure_uses_strict_native_fallback_without_page_rendering(app):
"""MinerU 失败后才允许原生文字降级,且复用前置字符预读而不渲染页面图。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
@@ -219,13 +272,21 @@ def test_runtime_native_fast_path_defers_page_rendering(app):
) as build_layout, patch(
'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence',
return_value={'version': 'test'},
):
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
side_effect=ServiceUnavailableError(
'failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
),
) as mineru:
build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'}
snapshot = build_mineru_table_snapshot(
filename='order.pdf', content=b'%PDF', document_id=1, content_hash='b' * 64,
)
assert snapshot['provider'] == 'pdfium'
assert 'mineru_provider_fallback_used' in snapshot['issues']
assert 'SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE' in snapshot['issues']
mineru.assert_called_once()
extract_pages.assert_called_once_with(b'%PDF', render_images=False)
@@ -248,6 +309,36 @@ def test_runtime_provider_failure_is_safe_fallback(app):
}
def test_runtime_native_fallback_failure_preserves_mineru_error(app):
"""严格 PDFium 降级自身异常时不得覆盖 MinerU 原始失败结果。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
)
page = type('Page', (), {'page_no': 1, 'width': 100, 'height': 200})()
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
return_value=[page],
), patch(
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks',
side_effect=ValueError('invalid native table evidence'),
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
side_effect=ServiceUnavailableError(
'failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
),
):
snapshot = build_mineru_table_snapshot(
filename='order.pdf', content=b'%PDF', document_id=1, content_hash='c' * 64,
)
assert snapshot == {
'snapshot_version': 'shipping_document_table_snapshot.v1',
'provider': 'mineru', 'backend': 'pipeline', 'status': 'failed',
'tables': [], 'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'],
}
def test_runtime_attachment_budget_preserves_order_and_marks_overflow(app):
"""EML 多附件只并发处理预算内文档,超量附件显式降级且原顺序不变。"""
app.config.update(
@@ -8,7 +8,8 @@ backend/tests/test_shipping_document_profile_quality.py
from __future__ import annotations
from datetime import datetime
from datetime import date, datetime
from decimal import Decimal
from types import SimpleNamespace
import pytest
@@ -16,8 +17,8 @@ import pytest
from app import db
from app.models import (
FileAsset,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingCustomer,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
@@ -28,9 +29,27 @@ from app.models import (
ShippingOrderDocumentProfileSample,
)
from app.services.shipping_notice import document_profile_quality_service as quality
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint
@pytest.mark.parametrize(
('actual', 'expected', 'config'),
[
('2026-06-09', date(2026, 6, 9), {'value_type': 'date'}),
('898.72000', Decimal('898.72000'), {'value_type': 'decimal'}),
(' Quanta Computer Inc. ', 'Quanta Computer Inc.', {'value_type': 'string', 'normalizer_key': 'trim'}),
],
)
def test_blind_test_order_field_comparison_normalizes_both_values(actual, expected, config):
"""关键断言:API 序列化后的字符串与冻结类型值按同一 Schema 比较,不产生伪 mismatch。"""
assert quality._order_field_values_match(actual=actual, expected=expected, config=config)
def test_blind_test_order_field_comparison_rejects_different_values():
"""关键断言:双向规范化只消除类型差异,真实日期差异仍必须失败。"""
assert not quality._order_field_values_match(
actual='2026-06-09', expected='2026-06-10', config={'value_type': 'date'},
)
def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source():
@@ -50,7 +69,7 @@ def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_sourc
) == [{'text': 'PAGE'}]
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingNoticeDocument]]:
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]:
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
# 产品模型只允许唯一的 SHIPPING_ORDER Schema,测试仅创建其隔离版本。
@@ -80,20 +99,39 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
db.session.add(version)
db.session.flush()
html = '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr></table>'
fingerprint = order_profile_structure_fingerprint(parse_html_grid(html, table_id='table-1'), header_row_index=0)
definition = {
'document_match': {
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0,
},
'table_regions': [{
'region_id': 'lines', 'page_scope': 'first_page',
'line_start_field_code': 'qty',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'new_line_anchor': None,
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .6, 'y1': 1},
'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate']},
],
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'],
'allowed_empty_fields': [],
}],
}],
'order_field_layouts': [], 'draft_unbound_order_field_layouts': [],
}
profile = ShippingOrderDocumentProfile(
profile_code='QUALITY_TEMPLATE', display_name='Quality template', version=1, status='published',
schema_version_id=version.id, structure_fingerprint=fingerprint, checksum='b' * 64,
published_at=datetime.utcnow(), definition_json={
'contract_version': 'shipping_order_document_profile.v1', 'structure_fingerprint': fingerprint,
'header_row_index': 0, 'data_start_row_index': 1, 'row_structure': 'preserved',
'drop_zero_qty': True, 'column_rules': [
{'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['part_number'],
'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}]},
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['qty'],
'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}]},
],
},
schema_version_id=version.id, structure_fingerprint='a' * 64, checksum='b' * 64,
published_at=datetime.utcnow(), definition_json=definition,
)
db.session.add(profile)
db.session.flush()
@@ -107,23 +145,36 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f'SNI-QUALITY-{index}', asset_id=asset.id, user_id=user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key=asset.storage_key,
filename=asset.original_filename, content_hash=asset.content_hash, classification='order_notice',
parse_status='parsed', extracted_text='PN-1 3',
)
db.session.add(document)
db.session.flush()
glyphs = []
for text, x0 in [('PN-1', 30), ('3', 150)]:
for char_index, char in enumerate(text):
glyphs.append({'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20, 'x1': x0 + char_index * 5 + 4, 'y1': 30,
}})
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru',
'backend': 'test', 'status': 'ready', 'issues': [],
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}],
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html,
'bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}}],
'coordinate_evidence': {
'tables': {'table-1': glyphs},
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': glyphs},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
documents.append(document)
db.session.commit()
@@ -138,7 +189,6 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
profile.checksum = None
profile.published_at = None
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': 'FACTORY A'}]},
'table_regions': [{
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
@@ -148,9 +198,9 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
],
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
}],
@@ -177,10 +227,10 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a
quality.add_sample(
suite_id=suite['id'], document_id=documents[0].id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
)
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed'
assert executed['latest_run']['status'] == 'passed', executed['latest_run']
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert approved['status'] == 'approved'
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
@@ -203,7 +253,7 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
profile, user, documents = _published_profile_with_samples()
# 仅专用模板样本可供日常盲测选择;训练文档必须始终被排除。
for document in documents:
db.session.get(ShippingNoticeIntake, document.intake_id).purpose = 'order_document_profile_sample'
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
db.session.add(ShippingOrderDocumentProfileSample(
profile_id=profile.id, document_id=documents[0].id, table_id='table-1',
sample_role='training', created_by_id=user.id,
@@ -221,22 +271,201 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
candidate = quality.preview_independent_sample(
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', actor_id=user.id,
)
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': 3}]
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}]
with pytest.raises(Exception) as incomplete:
quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1',
row_reviews=[{'correct': None, 'values': candidate['rows'][0]}],
order_field_reviews={}, actor_id=user.id,
order_field_reviews={}, layout_version_id=candidate['layout_version_id'],
layout_payload_checksum=candidate['layout_payload_checksum'], actor_id=user.id,
)
assert getattr(incomplete.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
confirmed = quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1',
row_reviews=[{'correct': True, 'values': {}}], order_field_reviews={}, actor_id=user.id,
row_reviews=[{'correct': True, 'values': {}}], order_field_reviews={},
layout_version_id=candidate['layout_version_id'],
layout_payload_checksum=candidate['layout_payload_checksum'], actor_id=user.id,
)
assert confirmed['sample_count'] == 1
sample = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0]
assert sample.expected_rows_json == candidate['rows']
assert sample.layout_version_id == candidate['layout_version_id']
assert sample.layout_payload_checksum == candidate['layout_payload_checksum']
# 当前指针变化不得改变已确认样本的回放输入;盲测必须继续读取冻结版本。
current_version = documents[1].current_layout_version
replacement = dict(current_version.payload_json or {})
replacement['tables'] = []
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
record_inline_layout_snapshot(documents[1], replacement, parser_key='changed-parser-key')
db.session.commit()
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed'
def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
"""关键断言:失败 Layout 可从原 PDF 诊断,但不能确认成盲测真值。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
document = documents[1]
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
current_version = document.current_layout_version
current_version.status = 'failed'
current_version.payload_json = {
'snapshot_version': 'shipping_document_table_snapshot.v1',
'status': 'failed', 'tables': [],
'issues': ['mineru_cell_coordinates_missing'],
}
current_version.issues_json = ['mineru_cell_coordinates_missing']
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""模拟从原始 PDF 恢复整页字符,验证盲测不依赖 MinerU table_id。"""
assert page_nos is None
recovered = dict(layout)
recovered['coordinate_evidence'] = {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
}
return recovered
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
candidate_option = next(item for item in available if item['document_id'] == document.id)
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
assert candidate_option['review_mode'] == 'diagnostic'
assert candidate_option['confirmable'] is False
assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing']
candidate = quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}]
with pytest.raises(Exception) as bypassed_review:
quality.add_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID,
expected_rows=candidate['rows'], actor_id=user.id,
)
assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
assert candidate['confirmable'] is False
with pytest.raises(Exception) as diagnostic_confirmation:
quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID,
row_reviews=[{'correct': True}], order_field_reviews={},
layout_version_id=current_version.id,
layout_payload_checksum=current_version.payload_checksum, actor_id=user.id,
)
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE'
def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
"""关键断言:后台 Layout 尚在运行时只显示准备状态,不启动临时 PDF 复核。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
document = documents[1]
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
current_version = document.current_layout_version
current_version.status = 'running'
current_version.payload_json = None
current_version.issues_json = []
document.current_layout_version_id = None
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""模拟正在预热时直接从原 PDF 恢复整页坐标,空布局不得阻断复核。"""
assert layout == {'status': 'pending', 'tables': [], 'issues': []}
assert page_nos is None
return {
**layout,
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
},
}
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
candidate_option = next(item for item in available if item['document_id'] == document.id)
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
assert candidate_option['review_mode'] == 'preparing'
assert candidate_option['confirmable'] is False
with pytest.raises(Exception) as preparing_preview:
quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert getattr(preparing_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
def test_document_candidate_identity_expires_after_background_layout_completion(app, monkeypatch):
"""关键断言:后台产生真实 table_id 后,旧文档候选必须刷新并重新正式预览。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
document = documents[1]
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
# 当前列表已经转成真实表格候选,模拟页面仍持有上传完成时的文档级身份。
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
assert any(item['document_id'] == document.id and item['table_id'] == 'table-1' for item in available)
assert not any(
item['document_id'] == document.id and item['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
for item in available
)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""文档级复核使用整页证据,不依赖后台刚生成的表格身份。"""
assert page_nos is None
recovered = dict(layout)
recovered['coordinate_evidence'] = {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
}
return recovered
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
with pytest.raises(Exception) as stale_preview:
quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert getattr(stale_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
def test_independent_samples_include_historical_blind_documents(app):
@@ -246,7 +475,7 @@ def test_independent_samples_include_historical_blind_documents(app):
historical_suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
quality.add_sample(
suite_id=historical_suite['id'], document_id=documents[0].id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
)
draft = ShippingOrderDocumentProfile(
profile_code=profile.profile_code, display_name=profile.display_name, version=2, status='draft',
@@ -292,7 +521,7 @@ def test_independent_samples_deduplicate_reuploaded_content(app):
with app.app_context():
profile, user, documents = _published_profile_with_samples()
for document in documents[:2]:
db.session.get(ShippingNoticeIntake, document.intake_id).purpose = 'order_document_profile_sample'
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
documents[1].content_hash = documents[0].content_hash
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
@@ -309,13 +538,13 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
'document_match': {'required_anchors': []},
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .15, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', 'region': {'x0': 0, 'y0': 0, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': .15, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
],
}]}],
}
@@ -343,11 +572,11 @@ def test_coordinate_blind_candidate_list_does_not_prepare_missing_evidence(app,
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
'document_match': {'required_anchors': []},
'table_regions': [], 'order_field_layouts': [],
}
for document in documents:
db.session.get(ShippingNoticeIntake, document.intake_id).purpose = 'order_document_profile_sample'
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
db.session.add(ShippingOrderDocumentProfileSample(
profile_id=profile.id, document_id=documents[0].id, table_id='table-1',
sample_role='training', created_by_id=user.id,
@@ -369,17 +598,17 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
'document_match': {'required_anchors': []},
'table_regions': [
{'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no',
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number',
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate']},
],
@@ -415,7 +644,7 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
for document in documents:
quality.add_sample(
suite_id=suite['id'], document_id=document.id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
)
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
@@ -518,7 +747,7 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
quality.add_sample(
suite_id=suite['id'], document_id=documents[0].id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
)
sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
serialized = quality.serialize_suite(db.session.get(ShippingDocumentProfileTestSuite, suite['id']))
@@ -539,7 +768,7 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
for document in documents:
quality.add_sample(
suite_id=suite['id'], document_id=document.id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
)
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
@@ -566,8 +795,8 @@ def test_draft_publish_requires_current_approved_blind_test(app):
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
def test_draft_publish_requires_static_document_anchor(app):
"""关键断言:零必填锚点的模板不能发布,避免成为匹配所有 PDF 的通配模板。"""
def test_draft_publish_does_not_force_static_document_anchor(app):
"""关键断言:是否配置必需锚点由用户决定,发布门禁不再强制添加。"""
from app.services.shipping_notice import document_profile_quality_service as quality
with app.app_context():
@@ -578,7 +807,7 @@ def test_draft_publish_requires_static_document_anchor(app):
with pytest.raises(Exception) as caught:
quality.assert_profile_publishable(profile)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR'
assert getattr(caught.value, 'code', None) != 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR'
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
@@ -591,7 +820,6 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
profile.checksum = None
profile.published_at = None
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT TYPE:', 'value': 'PURCHASE ORDER', 'value_position': 'right'}]},
'table_regions': [{
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
@@ -601,9 +829,9 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .16, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .16, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .15, 'y0': .16, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', 'region': {'x0': 0, 'y0': .16, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': .15, 'y0': .16, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
],
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
}],
@@ -615,7 +843,7 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
)
profile.structure_fingerprint = profiles._definition_hash(profile.definition_json)
def set_coordinate_rows(document: ShippingNoticeDocument, rows: list[tuple[str, str]]) -> None:
def set_coordinate_rows(document: ShippingOrderDocument, rows: list[tuple[str, str]]) -> None:
"""冻结每个样本的字符坐标,让 v2 盲测不依赖 HTML 网格。"""
glyphs = []
for row_index, (part, qty) in enumerate(rows):
@@ -628,12 +856,18 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}}},
# 发布冻结要求 page_glyphs + sources,避免测试误走 MinIO 按需补证据。
'coordinate_evidence': {
'tables': {'table-1': glyphs},
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': glyphs},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
for document in documents:
set_coordinate_rows(document, [('PN-1', '3')])
extra = ShippingNoticeDocument(
extra = ShippingOrderDocument(
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
attachment_key='quality-v2-extra.pdf', filename='quality-v2-extra.pdf', content_hash='f' * 64,
classification='order_notice', parse_status='parsed', extracted_text='PN-3 5',
@@ -0,0 +1,196 @@
"""
tests/test_shipping_document_profile_quality_xfa_phase4.py
用途:阶段 4 XFA 盲测真值隔离、文档级候选列表与 accuracy 门禁 focused 验收。
依赖:quality_service、blind_test expected.json、ShippingXfaStructureAnalysis。
逻辑:serialize_suite 不回显真值;XFA 列表返回 confirmable 文档级候选;fixture 要求 100% 准确率。
"""
from __future__ import annotations
import json
from datetime import datetime
from app.extensions import db
from app.models import (
FileAsset,
ShippingDocumentProfileTestSuite,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileSample,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingXfaStructureAnalysis,
User,
)
from app.services.shipping_notice import document_profile_quality_service as quality
from app.services.shipping_notice.document_profile_quality_service import (
MINIMUM_BLIND_SAMPLES,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_DOCUMENT_TABLE_ID,
XFA_PARSER_IDENTITY,
)
from tests.test_shipping_xfa_helpers import FIXTURE_ROOT
def test_xfa_blind_fixture_requires_independent_identity_and_full_accuracy():
"""关键断言:盲测 fixture 与 annotation 身份独立,且要求 100% 准确率门禁。"""
annotation = json.loads((FIXTURE_ROOT / 'annotation' / 'expected.json').read_text(encoding='utf-8'))
blind = json.loads((FIXTURE_ROOT / 'blind_test' / 'expected.json').read_text(encoding='utf-8'))
assert blind['content_identity']['content_hash'] != annotation.get('content_identity', {}).get('content_hash')
assert blind['content_identity']['logical_document_id'] != annotation.get('content_identity', {}).get('logical_document_id')
assert blind['required_accuracy']['required_fields'] == 1.0
assert blind['required_accuracy']['line_count'] == 1.0
assert blind['required_accuracy']['quantity_amount_date_normalization'] == 1.0
assert MINIMUM_BLIND_SAMPLES >= 1
assert XFA_DOCUMENT_TABLE_ID == 'xfa-authoritative-lines'
def test_serialize_suite_does_not_leak_blind_truths():
"""关键断言:普通盲测 DTO 不含 expected_rows / expected_order_fields 真值。"""
payload = {
'id': 1,
'profile_id': 9,
'profile_checksum': 'c' * 64,
'status': 'approved',
'sample_count': 1,
'samples': [{
'id': 3,
'document_id': 88,
'table_id': XFA_DOCUMENT_TABLE_ID,
'filename': '',
'page_no': 1,
}],
'approved_at': None,
'latest_run': {
'status': 'passed',
'sample_count': 1,
'passed_sample_count': 1,
'failure_codes': [],
},
}
encoded = json.dumps(payload)
assert 'SECRET-MAT' not in encoded
assert 'SECRET-PO' not in encoded
assert 'expected_rows' not in encoded
assert 'expected_order_fields' not in encoded
def _make_sample_document(*, user: User, suffix: str) -> ShippingOrderDocument:
"""创建一份目的为模板样本池的独立 PDF 文档。"""
content_hash = (suffix.encode().hex() + '0' * 64)[:64]
asset = FileAsset(
asset_no=f'FA-XFA-P4-{suffix}',
owner_user_id=user.id,
original_filename=f'xfa-{suffix}.pdf',
storage_provider='test',
storage_bucket='test',
storage_key=f'xfa-p4/{suffix}.pdf',
content_hash=content_hash,
file_size=1,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f'SNI-XFA-P4-{suffix.upper()}',
asset_id=asset.id,
user_id=user.id,
purpose='order_document_profile_sample',
parse_status='parsed',
parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key=asset.storage_key,
filename=asset.original_filename,
content_hash=content_hash,
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
return document
def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app):
"""关键断言:XFA 草稿列出文档级结构分析候选,confirmable=True 且不走坐标表。"""
with app.app_context():
user = User(username='xfa-p4-quality', email='xfa-p4-quality@example.com', role='admin')
schema = ShippingOrderSchema(schema_code='XFA_P4Q', display_name='XFA P4Q')
db.session.add_all([user, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', checksum='e' * 64,
published_at=datetime.utcnow(), definition_json={'fields': []},
)
db.session.add(version)
db.session.flush()
annotation_doc = _make_sample_document(user=user, suffix='ann')
blind_doc = _make_sample_document(user=user, suffix='blind')
profile = ShippingOrderDocumentProfile(
profile_code='XFA_P4Q', display_name='XFA P4Q', version=1, status='draft',
schema_version_id=version.id, structure_fingerprint='f' * 64,
template_mode='xfa_dataset',
definition_json={
'template_mode': 'xfa_dataset',
'source_contract': {
'template_packet_checksum': 'sha256:tpl',
'dataset_structure_fingerprint': 'sha256:fp',
'dataset_root_path': '/data',
'authoritative_line_collection_path': '/data/ITEMS/DATA',
'mirror_collection_paths': [],
},
'header_mappings': [],
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
'cross_checks': {
'acroform_enabled': False, 'mirror_collection_policy': 'ignore',
'line_amount_formula': 'disabled', 'total_amount_policy': 'disabled',
},
},
)
db.session.add(profile)
db.session.flush()
db.session.add(ShippingOrderDocumentProfileSample(
profile_id=profile.id, document_id=annotation_doc.id,
table_id=XFA_DOCUMENT_TABLE_ID, sample_role='annotation', created_by_id=user.id,
))
db.session.add(ShippingXfaStructureAnalysis(
document_id=blind_doc.id,
source_content_hash=str(blind_doc.content_hash),
document_kind='xfa_hybrid',
analysis_status='ready',
template_packet_checksum='sha256:tpl',
datasets_packet_checksum='sha256:ds',
dataset_structure_fingerprint='sha256:fp',
packet_checksums_json={},
stats_json={'line_row_count': 1},
security_summary_json={},
tree_summary_json={},
parser_identity=XFA_PARSER_IDENTITY,
contract_version='xfa-structure-analysis.v1',
))
suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=profile.structure_fingerprint, created_by_id=user.id,
)
db.session.add(suite)
db.session.commit()
listed = quality.list_independent_samples(suite_id=suite.id, actor_id=user.id)
samples = listed['samples']
assert samples, 'XFA blind candidate list must not be empty'
assert all(item['table_id'] == XFA_DOCUMENT_TABLE_ID for item in samples)
match = next(item for item in samples if int(item['document_id']) == int(blind_doc.id))
assert match['confirmable'] is True
assert match['review_mode'] == 'formal_review'
assert match['layout_version_id']
assert match['layout_payload_checksum'] == 'sha256:ds'
assert annotation_doc.id not in {int(item['document_id']) for item in samples}
@@ -20,7 +20,7 @@ from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingTask,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
)
from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
@@ -43,7 +43,7 @@ def _inventory_field_id(field_code: str) -> str:
def _freeze_export_snapshot(
task: ShippingTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
) -> None:
"""为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
@@ -122,7 +122,7 @@ def test_filename_pattern_supports_business_number_and_split_business_variables(
case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC',
business_date=date(2026, 6, 2), sequence_value=1,
)
task = ShippingTask(task_no='TASK-FILENAME', inventory_source_code='DBS')
task = ShippingNotice(task_no='TASK-FILENAME', inventory_source_code='DBS')
task.shipping_case = shipping_case
template = ShippingExcelTemplate(
template_code='FILENAME', display_name='Filename',
@@ -136,7 +136,7 @@ def test_filename_pattern_falls_back_to_controlled_environment_configuration(app
"""模板未提供规则时可使用受控环境变量,调用方仍不能提交任意文件名。"""
with app.app_context():
app.config['SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN'] = 'default_{task_no}.xlsx'
task = ShippingTask(task_no='TASK-FILENAME-DEFAULT')
task = ShippingNotice(task_no='TASK-FILENAME-DEFAULT')
template = ShippingExcelTemplate(template_code='DEFAULT', display_name='Default', definition_json={})
assert _filename(task, template) == 'default_TASK-FILENAME-DEFAULT.xlsx'
@@ -230,7 +230,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id),
ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id),
])
task = ShippingTask(
task = ShippingNotice(
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
inventory_warehouse_id='DUB', inventory_lines_json=[{
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
@@ -295,7 +295,7 @@ def test_header_mapping_rejects_line_order_field(app):
def test_export_date_system_fact_uses_business_timezone(app):
"""导出日期必须返回上海业务时区的日期对象,供模板统一格式化。"""
with app.app_context():
value = _system_fact(ShippingTask(task_no='TASK-DATE'), 'export_date')
value = _system_fact(ShippingNotice(task_no='TASK-DATE'), 'export_date')
assert isinstance(value, date)
@@ -411,7 +411,7 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
value_text=value, decision_id=decision.id,
))
task = ShippingTask(
task = ShippingNotice(
task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED',
inventory_warehouse_id='DUB', inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'},
@@ -584,7 +584,7 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
value_text='PN-A', decision_id=decision.id,
))
task = ShippingTask(
task = ShippingNotice(
task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id,
inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'},
@@ -1,151 +0,0 @@
"""
用途:验证发货 Excel 批次 ZIP 的权限、全部有效 Artifact、重名、校验和与 manifest 契约。
依赖:export_archive、ShippingBatch/Task/ExportArtifact、zipfile。
逻辑:构造同批次有效、缺失及损坏产物,断言 ZIP 仅包含可信文件并完整列出排除原因。
"""
from __future__ import annotations
import hashlib
import json
from zipfile import ZipFile
import pytest
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingBatch, ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingTask, User,
)
from app.services.shipping_notice.export_archive import build_export_archive
from app.core.auth.jwt import issue_local_access_token
def _seed_artifact_dependencies():
"""创建 Artifact 外键所需的最小发布版本。"""
template = ShippingExcelTemplate(
template_code='ZIP', display_name='ZIP', version=1, status='published',
storage_provider='minio', storage_bucket='test', storage_key='test/zip-template.xlsx',
original_filename='template.xlsx', file_checksum='t' * 64, definition_json={}, definition_checksum='d' * 64,
)
parsing = ShippingInventoryParsingProfile(
profile_code='ZIP', display_name='ZIP', version=1, status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add_all([template, parsing, schema]); db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
return template, parsing, version, extraction
def _artifact(task, path, dependencies, *, no: str, checksum: str | None = None):
"""为任务新增 ready Artifact,checksum 默认按文件内容计算。"""
template, parsing, version, extraction = dependencies
content = path.read_bytes() if path.is_file() else b''
item = ShippingExportArtifact(
artifact_no=no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=parsing.id, input_checksum='x' * 64,
file_path=str(path), file_name='shipment.xlsx', file_checksum=checksum or hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
db.session.add(item)
task.export_file_path = str(path)
task.export_file_name = 'shipment.xlsx'
return item
def test_batch_archive_manifest_and_duplicate_names(app, tmp_path):
"""同一任务多轮有效 Excel 都进入 ZIP,缺失/损坏 Artifact 保留明确审计状态。"""
with app.app_context():
user = User(username='zip-owner', email='zip@example.com', role='user', status='approved')
batch = ShippingBatch(batch_no='SB-ZIP', user_id=None, file_count=4)
db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id
tasks = [ShippingTask(task_no=f'TASK-{index}', user_id=user.id, batch_id=batch.id, batch_index=index, batch_total=4) for index in range(1, 5)]
db.session.add_all(tasks); db.session.flush()
first = tmp_path / 'first.xlsx'; first.write_bytes(b'first')
first_second_round = tmp_path / 'first-second-round.xlsx'; first_second_round.write_bytes(b'first-second-round')
second = tmp_path / 'second.xlsx'; second.write_bytes(b'second')
corrupt = tmp_path / 'corrupt.xlsx'; corrupt.write_bytes(b'changed')
dependencies = _seed_artifact_dependencies()
_artifact(tasks[0], first, dependencies, no='EXP-1')
_artifact(tasks[0], first_second_round, dependencies, no='EXP-1-SECOND')
_artifact(tasks[1], second, dependencies, no='EXP-2')
_artifact(tasks[2], tmp_path / 'missing.xlsx', dependencies, no='EXP-3')
_artifact(tasks[3], corrupt, dependencies, no='EXP-4', checksum='0' * 64)
db.session.commit()
stream, filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no)
with ZipFile(stream) as archive:
names = archive.namelist()
assert 'shipment.xlsx' in names
assert 'shipment_TASK-2.xlsx' in names # 同名按任务号消歧,避免覆盖。
assert 'shipment_TASK-1.xlsx' in names # 同一任务第二轮滚动 Artifact 不得遗漏。
archived_manifest = json.loads(archive.read('manifest.json'))
assert filename.startswith('shipping_exports_SB-ZIP_')
assert archived_manifest['included_count'] == 3
assert [entry['status'] for entry in manifest['entries']] == [
'included', 'included', 'included', 'missing_file', 'checksum_mismatch',
]
def test_archive_rejects_foreign_task_and_invalid_selection(app):
"""任一越权任务整体拒绝,且 batch_no/task_nos 不能同时或同时不传。"""
with app.app_context():
owner = User(username='archive-owner', email='archive-owner@example.com', role='user', status='approved')
other = User(username='archive-other', email='archive-other@example.com', role='user', status='approved')
task = ShippingTask(task_no='FOREIGN-TASK', user_id=owner.id)
db.session.add_all([owner, other]); db.session.flush(); task.user_id = owner.id; db.session.add(task); db.session.commit()
with pytest.raises(NotFoundError):
build_export_archive(user_id=other.id, task_nos=[task.task_no])
with pytest.raises(ValidationError):
build_export_archive(user_id=owner.id)
with pytest.raises(ValidationError):
build_export_archive(user_id=owner.id, batch_no='SB', task_nos=[task.task_no])
def test_archive_excludes_superseded_artifact_after_task_export_is_invalidated(app, tmp_path):
"""任务纠错必须显式作废旧 Artifact;仅清空旧 Task 指针不能影响滚动履约历史。"""
with app.app_context():
user = User(username='archive-reset', email='archive-reset@example.com', role='user', status='approved')
batch = ShippingBatch(batch_no='SB-RESET', user_id=None, file_count=1)
db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id
task = ShippingTask(task_no='TASK-RESET', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1)
db.session.add(task); db.session.flush()
path = tmp_path / 'old.xlsx'; path.write_bytes(b'old')
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-OLD')
artifact = ShippingExportArtifact.query.filter_by(artifact_no='EXP-OLD').one()
artifact.status = 'superseded'
task.export_file_path = None
task.export_file_name = None
db.session.commit()
_stream, _filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no)
assert manifest['included_count'] == 0
assert manifest['entries'][0]['status'] == 'missing_artifact'
def test_workspace_archive_api_returns_zip(app, client, tmp_path):
"""Workspace API 必须以当前用户权限生成 attachment ZIP,而不是暴露服务器文件路径。"""
with app.app_context():
user = User(username='archive-api', email='archive-api@example.com', role='user', status='approved')
db.session.add(user); db.session.flush()
batch = ShippingBatch(batch_no='SB-API-ZIP', user_id=user.id, file_count=1)
db.session.add(batch); db.session.flush()
task = ShippingTask(task_no='TASK-API-ZIP', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1)
db.session.add(task); db.session.flush()
path = tmp_path / 'api.xlsx'; path.write_bytes(b'api-content')
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-API')
db.session.commit()
token = issue_local_access_token(user)
response = client.post(
'/api/workspace/shipping-exports/archive', json={'batch_no': 'SB-API-ZIP'},
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200
assert response.mimetype == 'application/zip'
assert 'attachment' in response.headers['Content-Disposition']
@@ -0,0 +1,106 @@
"""
backend/tests/test_shipping_formal_task_edit_audit.py
用途:验收正式任务编辑成功/拒绝与 change_effect 失效写入 ShippingAuditEvent。
依赖:task_workflow、ShippingAuditEvent、test_shipping_review_formal_task_edit 种子助手。
逻辑:editable 拒绝写 formal_task_edit_rejected;inventory 失效写
formal_task_field_edited + inventory_match_invalidated + excel_export_invalidated。
"""
from __future__ import annotations
from app import db
from app.models import ShippingAuditEvent
from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
from app.services.shipping_notice.task_workflow import update_notice_line
from tests.test_shipping_review_formal_task_edit import (
_attach_extraction,
_link_order_task,
_review_payload,
_task,
)
def test_formal_task_edit_audit_event_types_frozen():
"""契约冻结:正式编辑四类事件码齐全。"""
assert FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES == frozenset({
'formal_task_field_edited',
'formal_task_edit_rejected',
'inventory_match_invalidated',
'excel_export_invalidated',
})
def test_formal_edit_rejection_writes_audit_event(app):
"""Schema 禁止编辑时仍落 formal_task_edit_rejected,可被审计中心检索。"""
with app.app_context():
task = _task(task_no='SN-FORMAL-AUDIT-REJ-001')
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
field_policies={'reservation_id': {'editable': False}},
)
db.session.commit()
response = update_notice_line({
'task_no': task.task_no,
'line_index': 0,
'patch': {'reservation_id': '3000092917'},
**_review_payload(),
})
assert response['status'] == 'failed'
assert response['data']['error_code'] == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
events = (
ShippingAuditEvent.query
.filter_by(task_no=task.task_no, event_type='formal_task_edit_rejected')
.all()
)
assert len(events) == 1
assert events[0].result == 'rejected'
assert events[0].error_code == 'SHIPPING.ORDER_FIELD_EDIT_FORBIDDEN'
def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
"""rerun_inventory_matching 同事务写入字段编辑 + 库存失效 + Excel 失效三类审计。"""
with app.app_context():
task = _task(task_no='SN-FORMAL-AUDIT-INV-001')
_attach_extraction(
task,
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
field_policies={
'reservation_id': {
'editable': True,
'change_effect': 'rerun_inventory_matching',
},
},
)
_link_order_task(task, stage='excel_generating')
db.session.commit()
response = update_notice_line({
'task_no': task.task_no,
'line_index': 0,
'patch': {'reservation_id': '3000092917'},
**_review_payload(version=1),
})
assert response['status'] == 'ok'
types = {
row.event_type
for row in ShippingAuditEvent.query.filter_by(task_no=task.task_no).all()
}
assert 'formal_task_field_edited' in types
assert 'inventory_match_invalidated' in types
assert 'excel_export_invalidated' in types
edited = (
ShippingAuditEvent.query
.filter_by(task_no=task.task_no, event_type='formal_task_field_edited')
.one()
)
assert edited.result == 'success'
assert edited.before_snapshot_json.get('match_status') == 'matched'
assert edited.after_snapshot_json.get('match_status') is None
meta = edited.metadata_json or {}
assert 'rerun_inventory_matching' in (meta.get('applied_effects') or [])
@@ -5,7 +5,7 @@ from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.models import ShippingTask
from app.models import ShippingNotice
from app.services.shipping_notice.export import generate_shipment_excel
from app.services.shipping_notice.upload_attempt_service import record_manual_upload
@@ -13,7 +13,7 @@ from app.services.shipping_notice.upload_attempt_service import record_manual_up
def test_export_rejects_voided_task_before_reading_template(app):
"""关键断言:被替代/作废任务即使持有旧字段也不能从底层导出。"""
with app.app_context():
task = ShippingTask(task_no='SN-ENTRY-VOID', source_type='test', lifecycle_status='voided')
task = ShippingNotice(task_no='SN-ENTRY-VOID', source_type='test', lifecycle_status='voided')
from app import db
db.session.add(task); db.session.commit()
with pytest.raises(ValueError, match='作废'):
@@ -23,7 +23,7 @@ def test_export_rejects_voided_task_before_reading_template(app):
def test_manual_upload_requires_receipt_number_and_evidence(app):
"""关键断言:截图/附件和货代回执号缺一不可,不能仅凭客户端声明完成上传。"""
with app.app_context():
task = ShippingTask(task_no='SN-ENTRY-UPLOAD', source_type='test')
task = ShippingNotice(task_no='SN-ENTRY-UPLOAD', source_type='test')
from app import db
db.session.add(task); db.session.commit()
with pytest.raises(ValidationError) as error:
+250 -15
View File
@@ -14,7 +14,9 @@ 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,
_coordinate_profile_rows,
_profile_table_candidates,
_route_reason_for_issue,
_should_attempt_generic_extraction,
route_deterministic_unit,
)
@@ -228,6 +230,94 @@ def test_should_attempt_generic_extraction_rejects_layout_drift():
) is False
def test_should_attempt_generic_extraction_allows_no_match_after_xfa_fallback():
"""XFA 失败回退后 match_status 来自坐标路径;no_match 允许进入通用/Dify。"""
assert _should_attempt_generic_extraction(
match_status='no_match',
profile_result={'issues': ['xfa_mirror_collection_mismatch'], 'match': {'status': 'no_match'}},
) is True
# 坐标路径自身的 structure_identity_changed 仍 fail-closed。
assert _should_attempt_generic_extraction(
match_status='structure_identity_changed',
profile_result={'issues': ['structure_identity_changed'], 'match': {'status': 'structure_identity_changed'}},
) is False
def test_route_deterministic_unit_xfa_failure_falls_back_to_generic(monkeypatch):
"""关键断言:XFA capability 文档失败后回退 generic_deterministic。"""
document = {
'document_id': 90,
'layout_snapshot': {
'status': 'ready',
'provider': 'xfa',
'xfa_capability': {
'structure_analysis_ready': True,
'template_packet_checksum': 'sha256:' + ('a' * 64),
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
},
'tables': [],
},
}
run = SimpleNamespace(
schema_version_id=1,
input_snapshot_json={
'schema': {
'checksum': 's' * 64,
'extraction_contract': {'schema_version_id': 1, 'checksum': 's' * 64},
'definition': {'fields': []},
},
'order_document_profiles': [],
'intakes': [{'intake_id': 1, 'intake_no': 'SNI-XFA', 'documents': [document]}],
'policy_versions': {'xfa_parser_identity': 'shipping-xfa-hardened-parser.v1'},
},
)
unit = SimpleNamespace(document_id=90, intake_id=1)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
lambda *_args, **_kwargs: ({'intake_no': 'SNI-XFA'}, document),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.xfa_enabled',
lambda: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._load_unit_pdf_bytes',
lambda *_args, **_kwargs: None,
)
generic_called = {'value': False}
def _fake_generic(**kwargs):
generic_called['value'] = True
decision = kwargs.get('decision') if isinstance(kwargs.get('decision'), dict) else {}
from app.services.shipping_notice.order_extraction_workflow import DeterministicRouteResult
return DeterministicRouteResult(
execution_mode='review_required',
decision={
**decision,
'route_type': 'generic_deterministic',
'route_decision': 'needs_review',
},
orders=[],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
_fake_generic,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled',
lambda: True,
)
route = route_deterministic_unit(run, unit=unit)
assert generic_called['value'] is True
assert route.decision.get('capability_kind') == 'xfa_fallback_coordinate'
assert 'xfa_dataset_missing' in (
route.decision.get('fallback_reason_codes')
or route.decision.get('xfa_fallback_reason_codes')
or []
)
def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
"""无异型特征时允许尝试通用解析。"""
assert _should_attempt_generic_extraction(
@@ -245,7 +335,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
'checksum': 'b' * 64,
'schema_version_id': 31,
'auto_create_approved': False,
'definition': {'contract_version': 'order_coordinate_profile.v2'},
'definition': {'table_regions': []},
}
document = {
'document_id': 66,
@@ -256,7 +346,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': []},
},
'tables': [],
'tables': [{'table_id': 'native-text-table-p1-1', 'page_no': 1}],
},
}
run = SimpleNamespace(
@@ -297,12 +387,13 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
seen_table_ids = []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._coordinate_v2_profile_rows',
lambda **_kwargs: [{
'app.services.shipping_notice.order_extraction_workflow._coordinate_profile_rows',
lambda **kwargs: (seen_table_ids.append(kwargs['raw_table']['table_id']) or [{
'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)
@@ -313,6 +404,146 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
assert len(result['tables'][0]['rows']) == 1
assert result['match']['status'] == 'unique_match'
assert result['match']['profile_code'] == 'ODP-PRODUCTION'
# 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。
assert seen_table_ids == ['native-text-table-p1-1']
def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
"""检测器未产出物理表格的续页应读取整页坐标;空续页不得被误判为证据不可用。"""
region = SimpleNamespace(
page_scope='all_pages', page_no=None, line_layouts=[SimpleNamespace(model_dump=lambda: {})],
region=SimpleNamespace(model_dump=lambda: {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}),
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
seen = {}
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows',
lambda **kwargs: (seen.update(characters=kwargs['characters']) or []),
)
rows = _coordinate_profile_rows(
raw_profile={}, raw_table={'table_id': 'page-2', 'page_no': 2},
layout={
'coordinate_evidence': {
'pages': {'2': {'width': 200, 'height': 100}},
'page_glyphs': {'2': [{'text': 'Terms', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'tables': {},
},
},
contract=SimpleNamespace(fields_by_code={}), schema_fields={},
)
assert rows == []
assert seen['characters'][0]['text'] == 'Terms'
def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch):
"""固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。"""
region = SimpleNamespace(
page_scope='all_pages', page_no=None,
line_layouts=[SimpleNamespace(model_dump=lambda: {})],
region=SimpleNamespace(
x0=0.1, y0=0.4, x1=0.9, y1=0.6,
model_dump=lambda: {'x0': 0.1, 'y0': 0.4, 'x1': 0.9, 'y1': 0.6},
),
termination_rules=[], exclusion_regions=[],
continuation_rule=SimpleNamespace(allow_cross_page=False),
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
seen: list[list[dict]] = []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows',
lambda **kwargs: (seen.append(kwargs['characters']) or []),
)
layout = {
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': [
{'text': 'header', 'bbox': {'x0': 20, 'y0': 30, 'x1': 30, 'y1': 35}},
{'text': 'main', 'bbox': {'x0': 20, 'y0': 44, 'x1': 30, 'y1': 48}},
# continuation 位于 MinerU y1=50 之外,但仍在模板 y=40..60 内。
{'text': 'continuation', 'bbox': {'x0': 20, 'y0': 53, 'x1': 35, 'y1': 57}},
]},
'tables': {'order-table': [{'text': 'main'}]},
},
}
rows = _coordinate_profile_rows(
raw_profile={},
raw_table={'table_id': 'order-table', 'page_no': 1, 'bbox': {'x0': 10, 'y0': 40, 'x1': 90, 'y1': 50}},
layout=layout,
contract=SimpleNamespace(fields_by_code={}), schema_fields={},
)
unrelated = _coordinate_profile_rows(
raw_profile={},
raw_table={'table_id': 'summary-table', 'page_no': 1, 'bbox': {'x0': 10, 'y0': 70, 'x1': 90, 'y1': 90}},
layout=layout,
contract=SimpleNamespace(fields_by_code={}), schema_fields={},
)
# 关键断言:模板区排除页头、保留框外续行;不相交的汇总表不得重复触发订单解析。
assert rows == []
assert unrelated == []
assert [[item['text'] for item in call] for call in seen] == [['main', 'continuation']]
def test_fixed_subrows_keep_repeated_records_below_template_sample(monkeypatch):
"""模板纵向框只描述样例版式;真实表格内后续重复记录不得被样例下边界截断。"""
region = SimpleNamespace(
page_scope='all_pages', page_no=None,
line_layouts=[SimpleNamespace(model_dump=lambda: {})],
region=SimpleNamespace(
x0=0.1, y0=0.4, x1=0.9, y1=0.5,
model_dump=lambda: {'x0': 0.1, 'y0': 0.4, 'x1': 0.9, 'y1': 0.5},
),
termination_rules=[], exclusion_regions=[],
continuation_rule=SimpleNamespace(allow_cross_page=False),
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
seen: list[list[dict]] = []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows',
lambda **kwargs: (seen.append(kwargs['characters']) or []),
)
layout = {'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': [
{'text': 'sample', 'bbox': {'x0': 20, 'y0': 44, 'x1': 30, 'y1': 48}},
{'text': 'next-record', 'bbox': {'x0': 20, 'y0': 64, 'x1': 35, 'y1': 68}},
{'text': 'summary', 'bbox': {'x0': 20, 'y0': 80, 'x1': 35, 'y1': 84}},
]},
'tables': {},
}}
rows = _coordinate_profile_rows(
raw_profile={},
raw_table={'table_id': 'order-table', 'page_no': 1, 'bbox': {'x0': 10, 'y0': 40, 'x1': 90, 'y1': 70}},
layout=layout,
contract=SimpleNamespace(fields_by_code={}), schema_fields={},
)
assert rows == []
assert [[item['text'] for item in call] for call in seen] == [['sample', 'next-record']]
def test_coordinate_reconstruction_reason_is_not_reported_as_profile_drift():
"""坐标证据暂不可用必须使用准确原因码,禁止错误展示为模板漂移。"""
assert _route_reason_for_issue(
'order_profile_coordinate_reconstruction_unavailable',
) == 'coordinate_evidence_unavailable'
def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch):
@@ -366,7 +597,7 @@ def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch):
def test_template_parse_failure_falls_back_to_generic(monkeypatch):
"""模板候选存在但模板解析失败时,仍按既定优先级降级到通用解析。"""
"""模板 no_match(非漂移)且开关开启时,可降级到通用解析。"""
candidate = _good_candidate()
run = SimpleNamespace(
schema_version_id=1,
@@ -395,9 +626,9 @@ def test_template_parse_failure_falls_back_to_generic(monkeypatch):
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': []},
'matched': False, 'blocking': False, 'tables': [],
'issues': [],
'match': {'status': 'no_match', 'candidates': []},
},
)
monkeypatch.setattr(
@@ -415,13 +646,13 @@ def test_template_parse_failure_falls_back_to_generic(monkeypatch):
assert route.orders
def test_route_deterministic_unit_attempts_generic_after_layout_drift(monkeypatch):
"""模板漂移不再终止路由;应先尝试通用门禁,失败才进入复核/LLM。"""
def test_route_deterministic_unit_layout_drift_does_not_fallback_to_generic(monkeypatch):
"""关键断言:layout_drift 禁止降级通用解析,直接 needs_review(与契约 GENERIC_ELIGIBLE 一致)。"""
run = SimpleNamespace(
schema_version_id=1,
input_snapshot_json={
'schema': {'extraction_contract': {}, 'definition': {'fields': []}},
'order_document_profiles': [{'schema_version_id': 1, 'definition': {'contract_version': 'order_coordinate_profile.v2'}}],
'order_document_profiles': [{'schema_version_id': 1, 'definition': {}}],
'intakes': [{'intake_no': 'SNI-001', 'documents': [{'document_id': 1, 'layout_snapshot': {'status': 'ready'}}]}],
},
)
@@ -442,13 +673,17 @@ def test_route_deterministic_unit_attempts_generic_after_layout_drift(monkeypatc
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
lambda *_args, **_kwargs: ({'intake_no': 'SNI-001'}, {'document_id': 1, 'layout_schema_candidates': []}),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
lambda **_kwargs: (_ for _ in ()).throw(AssertionError('layout_drift must not enter generic')),
)
route = route_deterministic_unit(run, unit=unit)
assert route.execution_mode == 'review_required'
assert isinstance(route.decision.get('generic_completeness'), dict)
assert route.decision['route_type'] == 'llm_assisted_review'
assert route.decision['fallback_reason_codes']
assert route.decision.get('generic_completeness') is None
assert route.decision['route_decision'] == 'needs_review'
assert route.decision['fallback_reason_codes'] or route.decision['reason_codes']
def test_legacy_five_auto_build_gates_do_not_parallel_user_block():
@@ -15,7 +15,7 @@ from app.extensions import db
from app.models import (
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingTask,
ShippingOrderSnapshotLine, ShippingNotice,
)
from app.services.shipping_notice.inventory_routing_engine import (
evaluate_inventory_source_rules,
@@ -75,9 +75,9 @@ def _published_line_fields() -> dict[str, str]:
def _task_with_line_values(
fields: dict[str, str], values: dict[str, tuple[str, str]],
) -> tuple[ShippingTask, dict[str, int]]:
) -> tuple[ShippingNotice, dict[str, int]]:
"""创建冻结快照供 Snapshot 路由路径读取。"""
task = ShippingTask(task_no='SN-CANDIDATE-ROUTE', user_id=None, source_type='manual')
task = ShippingNotice(task_no='SN-CANDIDATE-ROUTE', user_id=None, source_type='manual')
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(
@@ -19,7 +19,7 @@ from app.models import (
ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingTask,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
)
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
@@ -257,7 +257,7 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
value_text='R-1', decision_id=reservation_decision.id,
),
])
task = ShippingTask(
task = ShippingNotice(
task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE',
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
current_order_extraction_id=extraction.id,
@@ -311,7 +311,7 @@ def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_
source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match')
db.session.add(source)
db.session.commit()
task = ShippingTask(
task = ShippingNotice(
task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG',
inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
@@ -12,7 +12,7 @@ from app.extensions import db
from app.models import (
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingTask,
ShippingOrderSnapshotLine, ShippingNotice,
)
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.order_schema import service as order_schema_service
@@ -69,9 +69,9 @@ def _published_line_fields() -> dict[str, str]:
def _task_with_line_values(
fields: dict[str, str], values: dict[str, tuple[str, str]],
) -> tuple[ShippingTask, dict[str, int]]:
) -> tuple[ShippingNotice, dict[str, int]]:
"""创建冻结快照;路由测试只允许从该不可变事实读取字段。"""
task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
task = ShippingNotice(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual')
db.session.add(task)
db.session.flush()
extraction = ShippingOrderExtraction(
File diff suppressed because it is too large. Load diff
@@ -2,7 +2,7 @@
backend/tests/test_shipping_notice_business_case.py
用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。
依赖:app fixture、ShippingTask/ShippingCase、business_case_service。
依赖:app fixture、ShippingNotice/ShippingCase、business_case_service。
逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。
"""
@@ -10,14 +10,14 @@ import pytest
from app import db
from app.core.errors import ConflictError
from app.models import ShippingCase, ShippingCustomer, ShippingTask
from app.models import ShippingCase, ShippingCustomer, ShippingNotice
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
def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingTask:
def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingNotice:
"""构造最小货代任务,供业务单关系断言使用。"""
return ShippingTask(
return ShippingNotice(
task_no=task_no,
shipping_case_id=case_id,
supersedes_task_id=supersedes_task_id,
@@ -111,7 +111,7 @@ def test_create_task_assigns_case_and_serializes_it(app):
'raw_content': 'customer notice',
'customer_id': customer.id,
})
task = ShippingTask.query.filter_by(task_no=result['task_id']).one()
task = ShippingNotice.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
@@ -127,6 +127,7 @@ def test_create_task_rejects_without_customer(app):
assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK'
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_batch_revision_inherits_parent_case(app):
"""真实批量建单路径中的 revision 必须继承父任务业务单。"""
with app.app_context():
@@ -150,13 +151,14 @@ def test_batch_revision_inherits_parent_case(app):
}],
'defer_parse': True,
})
task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
task = ShippingNotice.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
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_batch_force_create_uses_new_case(app):
"""真实批量建单路径中的 force_create 必须创建独立业务单。"""
with app.app_context():
@@ -176,7 +178,7 @@ def test_batch_force_create_uses_new_case(app):
}],
'defer_parse': True,
})
task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
task = ShippingNotice.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'
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_notice_business_dedup.py
用途:第三阶段业务指纹、重复检测与决策门闩核心用例。
依赖:pytest、business_fingerprint、duplicate_detection、batch_from_intakes。
逻辑:覆盖指纹稳定性、阻断门闩、open_existing / create_revision 分流。
用途:业务指纹与 Intake/Candidate 重复检测核心用例(co8 已移除建批门闩用例)。
依赖:pytest、business_fingerprint、duplicate_detection、intake_service。
逻辑:覆盖指纹稳定性、候选阻断与 refresh。
"""
from __future__ import annotations
@@ -17,14 +17,12 @@ from app import db
from app.core.errors import ConflictError
from app.models import (
FileAsset,
ShippingBatch,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingNotice,
User,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
from app.services.shipping_notice.business_fingerprint import (
build_business_fingerprint,
build_content_fingerprint,
@@ -70,7 +68,7 @@ def _seed_parsed_intake(
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=intake_no,
asset_id=asset.id,
user_id=user_id,
@@ -144,237 +142,7 @@ def test_fingerprint_changes_with_qty():
assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint']
def test_blocking_create_requires_resolution(app, dedup_user):
with app.app_context():
summary = {
'customer_code': 'C1',
'po_number': 'PO-9',
'reservation_ids': ['1000140351'],
'lines': [],
}
fp = build_business_fingerprint(summary)
asset, intake = _seed_parsed_intake(
dedup_user.id,
intake_no='SNI-DEDUP-BLOCK',
hash_value='hash-block-1',
business_summary=summary,
fingerprint=fp,
)
batch = ShippingBatch(batch_no='SB-DEDUP-OLD', user_id=dedup_user.id, file_count=1)
db.session.add(batch)
db.session.flush()
existing = ShippingTask(
task_no='SN-DEDUP-OLD',
batch_id=batch.id,
user_id=dedup_user.id,
source_type='manual',
process_status='waiting_inventory',
business_fingerprint=fp['fingerprint'],
fingerprint_version=fp['version'],
document_version=1,
)
db.session.add(existing)
db.session.commit()
result = detect_duplicates_for_intake(intake=intake, asset=asset, business_summary=summary, fingerprint_result=fp)
assert result['blocking'] is True
assert result['status'] == 'same_active_task'
with pytest.raises(ConflictError) as excinfo:
create_shipping_batch_from_intakes(
user_id=dedup_user.id,
conversation_id='conv-dedup',
intake_nos=[intake.intake_no],
create_idempotency_key='idem-block',
)
assert excinfo.value.code == 'SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED'
def test_open_existing_does_not_create_batch(app, dedup_user):
with app.app_context():
summary = {
'customer_code': 'C1',
'po_number': 'PO-OPEN',
'reservation_ids': ['1000140352'],
'lines': [],
}
fp = build_business_fingerprint(summary)
asset, intake = _seed_parsed_intake(
dedup_user.id,
intake_no='SNI-DEDUP-OPEN',
hash_value='hash-open-1',
business_summary=summary,
fingerprint=fp,
)
batch = ShippingBatch(batch_no='SB-OPEN-OLD', user_id=dedup_user.id, file_count=1)
db.session.add(batch)
db.session.flush()
existing = ShippingTask(
task_no='SN-OPEN-OLD',
batch_id=batch.id,
user_id=dedup_user.id,
source_type='manual',
process_status='waiting_inventory',
business_fingerprint=fp['fingerprint'],
fingerprint_version=fp['version'],
document_version=1,
)
db.session.add(existing)
db.session.commit()
# 模拟前端已决策:写入 resolution,避免 resolve 内 refresh 对 SQLite 时间敏感
intake.duplicate_status = 'same_active_task'
intake.duplicate_matches_json = [
{
'task_no': existing.task_no,
'process_status': existing.process_status,
'document_version': 1,
'match_type': 'business_fingerprint',
'matched_fields': ['customer_code', 'po_number'],
'lifecycle': 'active',
}
]
intake.duplicate_resolution = 'open_existing'
intake.duplicate_target_task_no = existing.task_no
intake.duplicate_resolved_by_id = dedup_user.id
intake.duplicate_resolved_at = datetime.utcnow()
db.session.commit()
with patch(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items'
) as create_mock:
result = create_shipping_batch_from_intakes(
user_id=dedup_user.id,
conversation_id='conv-open',
intake_nos=[intake.intake_no],
create_idempotency_key='idem-open',
)
create_mock.assert_not_called()
assert result.get('batch_no') in (None, '')
refreshed = db.session.get(ShippingNoticeIntake, intake.id)
assert refreshed.parse_status == 'consumed'
assert refreshed.consumed_task_id == existing.id
def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatch):
"""create_revision 应写入 supersedes_task_id 与 document_version+1。"""
with app.app_context():
summary = {
'customer_code': 'C1',
'po_number': 'PO-REV-1',
'reservation_ids': ['12345678'],
'lines': [{'part_number': 'A', 'qty': 1, 'reservation_id': '12345678'}],
}
fp = build_business_fingerprint(summary)
asset, intake = _seed_parsed_intake(
dedup_user.id,
intake_no='SNI-REV-1',
hash_value='hash-rev-1',
business_summary=summary,
fingerprint=fp,
)
existing = ShippingTask(
task_no='SN-REV-BASE',
user_id=dedup_user.id,
source_type='manual',
process_status='uploaded',
business_fingerprint=fp.get('fingerprint'),
fingerprint_version=fp.get('version'),
document_version=1,
)
db.session.add(existing)
db.session.commit()
intake.duplicate_status = 'same_completed_task'
intake.duplicate_matches_json = [
{
'task_no': existing.task_no,
'process_status': 'uploaded',
'document_version': 1,
'match_type': 'business_fingerprint',
'matched_fields': ['customer_code', 'po_number'],
}
]
intake.duplicate_resolution = 'create_revision'
intake.duplicate_target_task_no = existing.task_no
intake.duplicate_resolved_by_id = dedup_user.id
intake.duplicate_resolved_at = datetime.utcnow()
db.session.commit()
def _fake_create(**kwargs):
notice_items = kwargs['notice_items']
item = notice_items[0]
batch = ShippingBatch(
batch_no='SB-REV-1',
user_id=dedup_user.id,
file_count=1,
create_idempotency_key=kwargs.get('create_idempotency_key'),
)
db.session.add(batch)
db.session.flush()
task = ShippingTask(
task_no='SN-REV-NEW',
batch_id=batch.id,
user_id=dedup_user.id,
source_type='manual',
source_content_hash=item.get('source_content_hash'),
source_asset_id=item.get('source_asset_id'),
source_intake_id=item.get('source_intake_id'),
business_fingerprint=item.get('business_fingerprint'),
fingerprint_version=item.get('fingerprint_version'),
document_version=int(item.get('document_version') or 1),
supersedes_task_id=item.get('supersedes_task_id'),
duplicate_resolution_type=item.get('duplicate_resolution_type'),
raw_content=item.get('raw_text'),
process_status='created',
)
db.session.add(task)
db.session.commit()
return {
'status': 'ok',
'batch_no': batch.batch_no,
'data': {
'batch': {'batch_no': batch.batch_no, 'id': batch.id},
'tasks': [{'task_id': task.task_no}],
'focus_task': {
'task_no': task.task_no,
'document_version': task.document_version,
'duplicate_resolution_type': task.duplicate_resolution_type,
'supersedes_task_no': existing.task_no,
},
},
}
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_notice_items',
_fake_create,
)
# 确保 detect 仍命中
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_intake',
lambda **kwargs: {
'status': 'same_completed_task',
'blocking': True,
'fingerprint': fp.get('fingerprint'),
'fingerprint_version': fp.get('version'),
'fingerprint_strength': fp.get('strength'),
'matches': intake.duplicate_matches_json,
'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
},
)
result = create_shipping_batch_from_intakes(
user_id=dedup_user.id,
conversation_id='conv-rev',
intake_nos=[intake.intake_no],
create_idempotency_key='idem-rev',
)
assert result['batch_no'] == 'SB-REV-1'
created = db.session.query(ShippingTask).filter_by(task_no='SN-REV-NEW').one()
assert created.supersedes_task_id == existing.id
assert int(created.document_version) == 2
assert created.duplicate_resolution_type == 'revision'
def test_fingerprint_strong_with_customer_name_po_reservation():
@@ -417,7 +185,7 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
business_summary=summary,
fingerprint=fp,
)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-PENDING-1',
user_id=dedup_user.id,
source_type='manual',
@@ -439,53 +207,6 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
assert result['blocking'] is True
def test_assert_no_exact_duplicate_allows_revision_and_force(app, dedup_user):
"""revision/force_create 可越过同 content_hash 的旧门闩;无决议仍阻断。"""
from app.services.shipping_notice.batch_create_idempotency import assert_no_exact_duplicate_notices
with app.app_context():
existing = ShippingTask(
task_no='SN-HASH-GATE',
user_id=dedup_user.id,
source_type='manual',
source_content_hash='samehashabc',
process_status='pending_review',
)
db.session.add(existing)
db.session.commit()
assert_no_exact_duplicate_notices(
dedup_user.id,
[
{
'source_content_hash': 'samehashabc',
'source_file_name': 'same.xlsx',
'duplicate_resolution_type': 'revision',
}
],
)
assert_no_exact_duplicate_notices(
dedup_user.id,
[
{
'source_content_hash': 'samehashabc',
'source_file_name': 'same.xlsx',
'duplicate_resolution_type': 'force_create',
}
],
)
with pytest.raises(ConflictError) as excinfo:
assert_no_exact_duplicate_notices(
dedup_user.id,
[
{
'source_content_hash': 'samehashabc',
'source_file_name': 'same.xlsx',
}
],
)
assert excinfo.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
"""API 投影:possible_duplicate 必须 blocking,供前端弹窗确认。"""
@@ -517,46 +238,6 @@ def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
assert 'force_create' in payload['duplicate']['allowed_actions']
def test_task_summary_includes_version_chain(app, dedup_user):
"""query_service SUMMARY 须暴露版本链与 duplicate 决策字段。"""
from app.services.shipping_notice.query_service import TaskProjection, serialize_task
with app.app_context():
base = ShippingTask(
task_no='SN-VER-BASE',
user_id=dedup_user.id,
source_type='manual',
process_status='uploaded',
document_version=1,
)
db.session.add(base)
db.session.flush()
rev = ShippingTask(
task_no='SN-VER-REV',
user_id=dedup_user.id,
source_type='manual',
process_status='pending_review',
document_version=2,
supersedes_task_id=base.id,
duplicate_resolution_type='revision',
duplicate_source_task_id=base.id,
duplicate_override_reason=None,
business_fingerprint='fp-x',
fingerprint_version='shipping-v1',
)
db.session.add(rev)
db.session.commit()
data = serialize_task(rev, TaskProjection.SUMMARY)
assert data['document_version'] == 2
assert data['supersedes_task_no'] == 'SN-VER-BASE'
assert data['duplicate_source_task_no'] == 'SN-VER-BASE'
assert data['duplicate_resolution_type'] == 'revision'
assert data['business_fingerprint'] == 'fp-x'
base_data = serialize_task(base, TaskProjection.SUMMARY)
assert base_data['superseded_by_task_no'] == 'SN-VER-REV'
def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
"""
@@ -571,7 +252,7 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
'lines': [],
}
)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-EXISTING-PO-A',
user_id=dedup_user.id,
source_type='manual',
@@ -598,7 +279,7 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
)
db.session.add(parent)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-STAGE2-DEDUP',
asset_id=parent.id,
user_id=dedup_user.id,
@@ -613,7 +294,7 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
docs = []
for idx, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1):
doc = ShippingNoticeDocument(
doc = ShippingOrderDocument(
intake_id=intake.id,
attachment_key=f'att-00{idx}',
document_type='attachment',
@@ -644,7 +325,7 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
business_summary=summary,
fingerprint_result=fp,
)
cand = ShippingNoticeCandidate(
cand = ShippingOrderCandidate(
candidate_no=f'SNC-{po}',
intake_id=intake.id,
primary_document_id=doc.id,
@@ -671,9 +352,9 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
assert results[2]['status'] == 'none'
refreshed = (
db.session.query(ShippingNoticeCandidate)
db.session.query(ShippingOrderCandidate)
.filter_by(intake_id=intake.id)
.order_by(ShippingNoticeCandidate.id.asc())
.order_by(ShippingOrderCandidate.id.asc())
.all()
)
assert refreshed[0].duplicate_status != 'none'
@@ -694,7 +375,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
'lines': [],
}
)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-REFRESH-EXISTING',
user_id=dedup_user.id,
source_type='manual',
@@ -721,7 +402,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
)
db.session.add(parent)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-REFRESH-DEDUP',
asset_id=parent.id,
user_id=dedup_user.id,
@@ -742,7 +423,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
'lines': [],
}
fp = build_business_fingerprint(summary)
doc = ShippingNoticeDocument(
doc = ShippingOrderDocument(
intake_id=intake.id,
attachment_key='att-001',
document_type='attachment',
@@ -754,7 +435,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
)
db.session.add(doc)
db.session.flush()
cand = ShippingNoticeCandidate(
cand = ShippingOrderCandidate(
candidate_no='SNC-REFRESH-1',
intake_id=intake.id,
primary_document_id=doc.id,
@@ -779,7 +460,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
)
assert payload['duplicate']['blocking'] is True
db.session.expire_all()
cand2 = db.session.query(ShippingNoticeCandidate).filter_by(candidate_no='SNC-REFRESH-1').one()
cand2 = db.session.query(ShippingOrderCandidate).filter_by(candidate_no='SNC-REFRESH-1').one()
assert cand2.duplicate_status != 'none'
assert list(cand2.duplicate_matches_json or [])
@@ -802,7 +483,7 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
}
identity = build_business_fingerprint(base)
content = build_content_fingerprint(base)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-CONTENT-EXISTING',
user_id=dedup_user.id,
source_type='manual',
@@ -820,7 +501,7 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
business_summary=base,
fingerprint=identity,
)
doc = ShippingNoticeDocument(
doc = ShippingOrderDocument(
intake_id=intake.id,
attachment_key='att-content',
document_type='attachment',
@@ -849,7 +530,7 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
)
assert same['status'] == 'same_business_content'
assert revision['status'] == 'possible_revision'
candidate = ShippingNoticeCandidate(
candidate = ShippingOrderCandidate(
candidate_no='SNC-CONTENT-WRITEBACK',
intake_id=intake.id,
primary_document_id=doc.id,
@@ -2,7 +2,7 @@
tests/test_shipping_notice_field_adjudication.py
用途:锁定后端规则解析与 Dify LLM Observation 的字段级交叉裁决规则。
依赖:field_adjudication、ShippingNoticeDocument 测试替身。
依赖:field_adjudication、ShippingOrderDocument 测试替身。
逻辑:覆盖单侧采用、共识、可信冲突、分差决策及不可变 Observation 审计。
"""
@@ -0,0 +1,115 @@
"""
tests/test_shipping_notice_intake_helpers.py
用途:ShippingOrderIntake 测试共用 fixture / 种子 / PDF 合成工具。
依赖:pytest、FileStorage、FileAsset、ShippingOrderIntake、upload_file_asset。
逻辑:供 intakes_lifecycle / parse / jobs 三个拆分模块 import;不包含断言用例。
"""
from __future__ import annotations
import threading
import time
from datetime import datetime
from unittest.mock import patch
import pytest
from werkzeug.datastructures import FileStorage
from io import BytesIO
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.models import (
FileAsset,
ShippingDocumentLayoutVersion,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingNotice,
User,
)
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
from app.services.shipping_notice.business_fingerprint import (
build_business_fingerprint,
build_content_fingerprint,
)
@pytest.fixture
def shipping_user(app):
with app.app_context():
user = User(username='intake-user', email='intake@example.com', password_hash='x')
db.session.add(user)
db.session.commit()
yield user
def _make_upload(content: bytes = b'customer order line', filename: str = 'notice.txt') -> FileStorage:
return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain')
def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_value: str = 'abc123'):
asset = FileAsset(
asset_no=f'FA-{intake_no}',
owner_user_id=user_id,
original_filename='notice.txt',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user_id}/test/{intake_no}.txt',
content_hash=hash_value,
file_size=12,
mime_type='text/plain',
upload_status='ready',
lifecycle_status='temporary',
reference_count=0,
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=intake_no,
asset_id=asset.id,
user_id=user_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v1',
extracted_text='SKU001 qty 10',
)
db.session.add(intake)
db.session.commit()
return asset, intake
def _minimal_pdf_bytes(marker: str) -> bytes:
"""构造含可见文本的最小 PDF(与 extract 测试口径一致)。"""
safe = str(marker).replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
stream = f'BT /F1 24 Tf 72 720 Td ({safe}) Tj ET'.encode('latin-1')
objects = [
b'1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n',
b'2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n',
(
b'3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] '
b'/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n'
),
f'4 0 obj<< /Length {len(stream)} >>stream\n'.encode('latin-1')
+ stream
+ b'\nendstream\nendobj\n',
b'5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n',
]
out = bytearray(b'%PDF-1.4\n')
offsets = [0]
for obj in objects:
offsets.append(len(out))
out.extend(obj)
xref_pos = len(out)
out.extend(f'xref\n0 {len(offsets)}\n'.encode('latin-1'))
out.extend(b'0000000000 65535 f \n')
for off in offsets[1:]:
out.extend(f'{off:010d} 00000 n \n'.encode('latin-1'))
out.extend(
f'trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n'.encode(
'latin-1'
)
)
return bytes(out)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -14,7 +14,7 @@ from app import db
from app.models import (
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink,
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
@@ -24,7 +24,7 @@ def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为库存/RPA 测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
@@ -77,7 +77,7 @@ def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_i
db.session.flush()
def _confirm_direct_rpa_task_customer(task: ShippingTask) -> None:
def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
"""为直接构造的 RPA 回调任务补齐已确认客户。
核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户,
@@ -180,7 +180,7 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
'report_group': 'Inventory', 'report_name': 'On Hand',
},
)
task = ShippingTask(
task = ShippingNotice(
task_no='SN-SNAPSHOT-SOURCE-UNIQUE', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000123456', 'qty': 1}],
)
@@ -237,7 +237,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
)
@@ -288,7 +288,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
stream.seek(0)
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
)
@@ -456,7 +456,7 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-CONFIRM-SOURCE-RPA",
source_type="pdf",
process_status="pending_review",
@@ -507,7 +507,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-BATCH-RUNNO",
source_type="manual",
process_status="waiting_inventory",
@@ -549,7 +549,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-BATCH-FAIL-TASK",
source_type="manual",
process_status="waiting_inventory",
@@ -593,7 +593,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-FAIL-NO-IDENT",
source_type="manual",
process_status="waiting_inventory",
@@ -674,7 +674,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-BATCH-NO-IDENT",
source_type="manual",
process_status="waiting_inventory",
@@ -742,7 +742,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
assert storage_path.is_file()
snap_id = snap.id
task = ShippingTask(
task = ShippingNotice(
task_no="SN-REUSE-INGEST-FAIL",
source_type="manual",
process_status="waiting_inventory",
@@ -857,14 +857,14 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
)
with app.app_context():
task_a = ShippingTask(
task_a = ShippingNotice(
task_no="SN-BATCH-OK",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
task_b = ShippingTask(
task_b = ShippingNotice(
task_no="SN-BATCH-FAIL",
source_type="manual",
process_status="waiting_inventory",
@@ -922,14 +922,14 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
run_no = "RUN-SHARED-LINK"
with app.app_context():
task_ok = ShippingTask(
task_ok = ShippingNotice(
task_no="SN-SHARED-OK",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
task_fail = ShippingTask(
task_fail = ShippingNotice(
task_no="SN-SHARED-FAIL",
source_type="manual",
process_status="waiting_inventory",
@@ -1011,7 +1011,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
)
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-POST-COMMIT-FAIL",
source_type="manual",
process_status="waiting_inventory",
@@ -1056,7 +1056,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
)
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-PROMOTE-FAIL-REBUILD",
source_type="manual",
process_status="waiting_inventory",
@@ -1094,7 +1094,7 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
snap_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-REPAIR-ATTACH",
source_type="manual",
process_status="inventory_ready",
@@ -1252,7 +1252,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
other_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-REPAIR-REJECT",
source_type="manual",
process_status="inventory_ready",
@@ -34,7 +34,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
assert "inventory_connector_type" in status_description
assert "inventory_source_type" not in status_description
assert set(paths) == {"/tools/get_task_status", "/tools/get_batch_status"}
assert set(paths) == {"/tools/get_task_status"}
def test_dynamic_openapi_uses_connector_contract(app, client) -> None:
@@ -21,11 +21,15 @@ from app.models import (
ChatLog,
ChatSession,
FileAsset,
ShippingBatch,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingNotice,
ShippingOrderProcessingPlan,
ShippingOrderProcessingRun,
ShippingOrderProcessingUnit,
ShippingOrderReviewCase,
ShippingOrderTask,
ShippingTaskEvent,
ShippingOrderExtraction,
ShippingOrderField,
@@ -121,6 +125,21 @@ def test_candidate_validation_projects_customer_po_number_to_legacy_candidate_fi
assert assessment['normalized_summary']['po_number'] == '4518838152'
def test_candidate_validation_reports_only_qty_when_part_number_exists():
"""数量缺失不得把已识别的内部料号一并误报为未解析。"""
assessment = assess_candidate_business_summary({
'lines': [{'part_number': 'B3-AR1000270A1', 'qty': None}],
})
assert assessment['can_create_task'] is False
assert assessment['missing_required_fields'] == ['qty']
assert assessment['invalid_lines'] == [{
'line_index': 0,
'reason': 'missing_part_number_or_positive_qty',
'fields': ['qty'],
}]
def test_merge_unit_orders_uses_atomic_customer_po_number_only():
"""同一原子客户 PO 可补全 Reservation;多 PO 邮件文本绝不能误合并。"""
schema = {'fields': [
@@ -181,7 +200,7 @@ def test_candidate_validation_accepts_frozen_temp_composite_rule():
assert assessment['normalized_summary']['lines'][0]['customer_part_number'] == 'TEMP-S000218929'
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingOrderIntake, ShippingOrderDocument, str]:
"""
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
@@ -219,7 +238,7 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
)
db.session.add_all([session, asset])
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-ORDER-EXTRACTION-001',
asset_id=int(asset.id),
user_id=int(user.id),
@@ -231,7 +250,7 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=int(intake.id),
asset_id=int(asset.id),
document_type='attachment',
@@ -260,15 +279,15 @@ def _build_test_extraction_context(payload: dict) -> dict:
"""
del payload
session = ChatSession.query.filter_by(session_id='shipping-order-extraction-session').one()
intakes = ShippingNoticeIntake.query.filter_by(user_id=int(session.user_id)).order_by(
ShippingNoticeIntake.id.asc()
intakes = ShippingOrderIntake.query.filter_by(user_id=int(session.user_id)).order_by(
ShippingOrderIntake.id.asc()
).all()
for intake in intakes:
if intake.conversation_id is None:
intake.conversation_id = session.session_id
documents = ShippingNoticeDocument.query.filter(
ShippingNoticeDocument.intake_id.in_([int(item.id) for item in intakes])
).order_by(ShippingNoticeDocument.id.asc()).all()
documents = ShippingOrderDocument.query.filter(
ShippingOrderDocument.intake_id.in_([int(item.id) for item in intakes])
).order_by(ShippingOrderDocument.id.asc()).all()
snapshot = f'test-{intakes[0].id}-{documents[0].id}'
db.session.commit()
return {
@@ -289,12 +308,12 @@ def _persist_test_orders(payload: dict) -> dict:
Candidate、Task 和待处理订单的安全摘要。
"""
session = ChatSession.query.filter_by(session_id='shipping-order-extraction-session').one()
intakes = ShippingNoticeIntake.query.filter_by(user_id=int(session.user_id)).order_by(
ShippingNoticeIntake.id.asc()
intakes = ShippingOrderIntake.query.filter_by(user_id=int(session.user_id)).order_by(
ShippingOrderIntake.id.asc()
).all()
documents = ShippingNoticeDocument.query.filter(
ShippingNoticeDocument.intake_id.in_([int(item.id) for item in intakes])
).order_by(ShippingNoticeDocument.id.asc()).all()
documents = ShippingOrderDocument.query.filter(
ShippingOrderDocument.intake_id.in_([int(item.id) for item in intakes])
).order_by(ShippingOrderDocument.id.asc()).all()
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
return persist_order_extraction_result(
session=session,
@@ -314,12 +333,12 @@ def _persist_test_orders(payload: dict) -> dict:
def _persist_shadow_orders(payload: dict) -> dict:
"""以默认关闭的自动建单门禁执行影子提交。"""
session = ChatSession.query.filter_by(session_id='shipping-order-extraction-session').one()
intakes = ShippingNoticeIntake.query.filter_by(user_id=int(session.user_id)).order_by(
ShippingNoticeIntake.id.asc()
intakes = ShippingOrderIntake.query.filter_by(user_id=int(session.user_id)).order_by(
ShippingOrderIntake.id.asc()
).all()
documents = ShippingNoticeDocument.query.filter(
ShippingNoticeDocument.intake_id.in_([int(item.id) for item in intakes])
).order_by(ShippingNoticeDocument.id.asc()).all()
documents = ShippingOrderDocument.query.filter(
ShippingOrderDocument.intake_id.in_([int(item.id) for item in intakes])
).order_by(ShippingOrderDocument.id.asc()).all()
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
return persist_order_extraction_result(
session=session, intakes=intakes, documents=documents,
@@ -330,6 +349,109 @@ def _persist_shadow_orders(payload: dict) -> dict:
)
def test_recompute_supersedes_referenced_stale_candidate_without_deleting_history(app):
"""同 Run 重算的旧 Candidate 已被 ReviewCase/OT 引用时必须保留。
核心逻辑:先持久化旧候选并建立两类外键引用,再以新 candidate_key
重算;断言旧版本只失效、引用不变,新版本成为当前候选。
"""
with app.app_context():
user, session, intake, document, _runtime_context = _seed_extraction_input()
first_order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
part_number='SKU-A',
qty=10,
include_process_fields=False,
)
_persist_test_orders({
'input_snapshot_hash': f'test-{intake.id}-{document.id}',
'orders': [first_order],
})
stale_candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
agent = Agent.query.filter_by(agent_code='shipping_notice').one()
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
run = ShippingOrderProcessingRun(
run_no='SNER-REFERENCED-CANDIDATE',
user_id=int(user.id),
owner_agent_id=int(agent.id),
conversation_id=session.session_id,
schema_version_id=int(schema.id),
input_snapshot_hash='referenced-candidate-snapshot',
input_snapshot_json={},
idempotency_key='referenced-candidate-run',
)
plan = ShippingOrderProcessingPlan(
run=run,
plan_version='test.v1',
input_snapshot_hash=run.input_snapshot_hash,
unit_count=1,
)
unit = ShippingOrderProcessingUnit(
plan=plan,
intake_id=int(intake.id),
document_id=int(document.id),
position=0,
unit_type='document_extraction',
document_type='attachment',
)
review_case = ShippingOrderReviewCase(
case_no='SORC-REFERENCED-CANDIDATE',
run=run,
unit=unit,
document_id=int(document.id),
candidate_id=int(stale_candidate.id),
owner_user_id=int(user.id),
status='draft',
)
order_task = ShippingOrderTask(
task_no='OT-REFERENCED-CANDIDATE',
user_id=int(user.id),
candidate_id=int(stale_candidate.id),
status='processing',
)
db.session.add_all([run, plan, unit, review_case, order_task])
db.session.commit()
second_order = _order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000002',
part_number='SKU-B',
qty=20,
include_process_fields=False,
)
persist_order_extraction_result(
session=session,
intakes=[intake],
documents=[document],
current_snapshot=f'test-{intake.id}-{document.id}',
request_id='test-order-extraction-recompute',
orders=[second_order],
run_id=None,
schema_version_id=int(schema.id),
extraction_source='test_workflow',
auto_create_enabled=True,
)
db.session.commit()
db.session.refresh(stale_candidate)
current_candidate = ShippingOrderCandidate.query.filter_by(
intake_id=int(intake.id),
is_current_version=True,
).one()
# 关键断言:不再触发 FK 删除失败,旧事实失效但 Case/OT 引用保持。
assert stale_candidate.candidate_status == 'expired'
assert stale_candidate.is_current_version is False
assert stale_candidate.selected is False
assert stale_candidate.candidate_status_before_superseded == 'provisional'
assert current_candidate.id != stale_candidate.id
assert review_case.candidate_id == stale_candidate.id
assert order_task.candidate_id == stale_candidate.id
def test_plain_text_table_issue_reaches_candidate_as_machine_readable_conflict(app):
"""无 cell 证据的纯文本表格必须在 Candidate 保留原因码,供现有任务 UI 解释。"""
with app.app_context():
@@ -352,7 +474,7 @@ def test_plain_text_table_issue_reaches_candidate_as_machine_readable_conflict(a
_persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=intake.id).one()
assert candidate.validation_status == 'needs_review'
assert any(
item.get('reason') == 'plain_text_table_has_no_cell_evidence'
@@ -371,8 +493,15 @@ def _order(
) -> dict:
"""构造符合动态订单 Schema 契约的单个订单结果。"""
fields = _ensure_order_schema()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
document = db.session.get(ShippingNoticeDocument, document_id)
# 同库可能并存多个 published 版本;取最早一条以贴近多数测试“先建后冻”的习惯。
version = (
ShippingOrderSchemaVersion.query
.filter_by(status='published')
.order_by(ShippingOrderSchemaVersion.id.asc())
.first()
)
assert version is not None
document = db.session.get(ShippingOrderDocument, document_id)
po_quote = f'PO {po_number}'
line_fields = [
{'field_id': fields['part_number'], 'observations': [
@@ -431,7 +560,7 @@ def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None:
field['observations'][0]['quote'] = 'NOT-IN-SOURCE'
def _attach_existing_task_dynamic_order(task: ShippingTask) -> None:
def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None:
"""为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。"""
fields = _ensure_order_schema()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
@@ -500,7 +629,7 @@ def test_order_field_display_uses_current_catalog_sequence(app):
ShippingOrderField.field_code.in_(sequence_by_code),
).all():
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
task = ShippingTask(
task = ShippingNotice(
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
)
@@ -522,7 +651,7 @@ def _add_extraction_intake(
user: User,
session: ChatSession,
suffix: str,
) -> tuple[ShippingNoticeIntake, ShippingNoticeDocument]:
) -> tuple[ShippingOrderIntake, ShippingOrderDocument]:
"""为隔离测试补充指定用户和会话下的已预处理 Intake/Document。"""
normalized = suffix.upper()
asset = FileAsset(
@@ -540,7 +669,7 @@ def _add_extraction_intake(
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f'SNI-ORDER-EXTRACTION-{normalized}',
asset_id=int(asset.id),
user_id=int(user.id),
@@ -552,7 +681,7 @@ def _add_extraction_intake(
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=int(intake.id),
asset_id=int(asset.id),
document_type='attachment',
@@ -612,12 +741,12 @@ def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_r
assert result['non_shipping_count'] == 0
assert result['created_with_missing_fields_count'] == 0
assert result['batch_no'] is None
candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all()
candidates = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).all()
assert len(candidates) == 2
assert len({item.candidate_key for item in candidates}) == 2
assert {item.candidate_status for item in candidates} == {'provisional'}
assert all(item.selected is False for item in candidates)
tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all()
tasks = ShippingNotice.query.filter_by(user_id=int(user.id)).all()
assert tasks == []
db.session.refresh(intake)
assert intake.parse_status == 'parsed'
@@ -631,8 +760,8 @@ def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_r
assert replay['created_count'] == 0
assert replay['opened_existing_count'] == 0
assert replay['pending_count'] == 2
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2
assert session.user_id == user.id
@@ -655,14 +784,14 @@ def test_shadow_mode_persists_ready_candidate_without_creating_task(app):
result = _persist_shadow_orders(payload)
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert result['created_count'] == 0
assert result['pending_count'] == 1
assert result['pending_orders'][0]['reasons'] == ['auto_create_disabled']
assert candidate.validation_status == 'ready'
assert candidate.candidate_status == 'provisional'
assert candidate.selected is False
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(app):
@@ -678,7 +807,7 @@ def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(a
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=intake.id).one()
assert candidate.candidate_status == 'accepted'
assert candidate.acceptance_mode == 'automatic'
assert candidate.extraction_source == 'approved_deterministic_profile'
@@ -699,7 +828,7 @@ def test_approved_generic_deterministic_marker_auto_accepts_candidate(app):
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=intake.id).one()
# 断言:通用标记自动接受且来源/策略版本与模板路径区分。
assert candidate.candidate_status == 'accepted'
assert candidate.acceptance_mode == 'automatic'
@@ -722,7 +851,7 @@ def test_unknown_acceptance_marker_stays_provisional(app):
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=intake.id).one()
assert candidate.candidate_status == 'provisional'
assert candidate.selected is False
assert candidate.acceptance_mode is None
@@ -762,7 +891,7 @@ def test_persist_order_extraction_result_consumes_empty_and_confident_non_shippi
'primary_document_id': int(document.id),
'classification_confidence': 0.99,
}]
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0
assert ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0
db.session.refresh(intake)
db.session.refresh(document)
assert intake.parse_status == 'consumed'
@@ -775,17 +904,8 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
"""订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
batch = ShippingBatch(
batch_no='SB-ORDER-EXISTING-001',
user_id=int(user.id),
conversation_id=session.session_id,
file_count=1,
)
db.session.add(batch)
db.session.flush()
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-ORDER-EXISTING-001',
batch_id=int(batch.id),
user_id=int(user.id),
source_type='manual',
process_status='waiting_inventory',
@@ -840,9 +960,9 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
assert result['pending_count'] == 0
assert result['message'] == '已打开 1 个已有任务。'
assert result['opened_existing'][0]['task_no'] == existing.task_no
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.consumed_task_id == existing.id
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1
def test_persist_order_extraction_result_empty_orders_reports_no_task_created(app):
@@ -920,15 +1040,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
"""同文件最新 Candidate 按 PO/SKU/qty 唯一命中时,只补旧任务空 Reservation 并保留人工复核。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
batch = ShippingBatch(
batch_no='SB-ORDER-RSV-BACKFILL-001',
user_id=int(user.id),
conversation_id=session.session_id,
file_count=1,
)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-ORDER-RSV-BACKFILL-001',
batch=batch,
user_id=int(user.id),
source_type='manual',
source_content_hash=document.content_hash,
@@ -977,8 +1090,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
assert result['created_count'] == 0
assert not result['pending_orders'], result['pending_orders']
assert result['opened_existing_count'] == 1, result
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1
candidate = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
assert candidate_line['inventory_source_hint'] == 'DBS DUB'
# 通用字段对账只写当前 Extraction 的 FieldValue;固定订单行投影不得变化。
@@ -1021,7 +1134,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
assert result['created_count'] == 0
assert result['pending_count'] == 1
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
def test_order_extraction_backend_blocks_reservation_source_conflict(app):
@@ -1071,7 +1184,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
assert result['created_count'] == 0
assert result['pending_count'] == 1
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert any(item['reason'] == 'cross_source_conflict' for item in candidate.conflicts_json)
adjudication = candidate.structured_result_json['extraction']['field_adjudication']
reservation_observations = [
@@ -1079,7 +1192,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
if item['field_id'] == _ensure_order_schema()['reservation_id']
]
assert {item['source_type'] for item in reservation_observations} == {'attachment_table', 'attachment_text'}
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
@pytest.mark.parametrize(
@@ -1104,8 +1217,8 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
}
task_values.update(task_overrides)
task = ShippingTask(**task_values)
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-NEG')
task = ShippingNotice(**task_values)
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-NEG')
db.session.add(task)
db.session.flush()
_attach_existing_task_dynamic_order(task)
@@ -1139,7 +1252,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
"""既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。"""
with app.app_context():
tasks = [
ShippingTask(
ShippingNotice(
task_no='SN-RSV-BACKFILL-CONFLICT',
po_number='4510038672',
source_type='manual',
@@ -1148,7 +1261,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
),
ShippingTask(
ShippingNotice(
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
po_number='4510038672',
source_type='manual',
@@ -1160,7 +1273,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
{'part_number': 'P123456', 'qty': 24},
],
),
ShippingTask(
ShippingNotice(
task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET',
po_number='4510038672',
source_type='manual',
@@ -1174,7 +1287,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
db.session.flush()
for task in tasks:
_attach_existing_task_dynamic_order(task)
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
summary = {
'po_number': '4510038672',
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
@@ -1210,7 +1323,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app):
"""目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE',
po_number='4510038672',
source_type='manual',
@@ -1219,7 +1332,7 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
)
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
db.session.add(task)
db.session.flush()
_attach_existing_task_dynamic_order(task)
@@ -1250,15 +1363,8 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
"""已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
batch = ShippingBatch(
batch_no='SB-ORDER-RSV-UNSAFE-OPEN-001',
user_id=int(user.id),
conversation_id=session.session_id,
file_count=1,
)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-ORDER-RSV-UNSAFE-OPEN-001',
batch=batch,
user_id=int(user.id),
source_type='manual',
source_content_hash=document.content_hash,
@@ -1289,7 +1395,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
})
db.session.refresh(existing)
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert result['opened_existing_count'] == 1
assert result['pending_count'] == 0
assert candidate.consumed_task_id == int(existing.id)
@@ -1323,24 +1429,17 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app)
assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.selected is False
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app):
"""exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
batch = ShippingBatch(
batch_no='SB-ORDER-RSV-UNVERIFIED-001',
user_id=int(user.id),
conversation_id=session.session_id,
file_count=1,
)
existing = ShippingTask(
existing = ShippingNotice(
task_no='SN-ORDER-RSV-UNVERIFIED-001',
batch=batch,
user_id=int(user.id),
source_type='manual',
source_content_hash=document.content_hash,
@@ -1377,7 +1476,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
'orders': [order],
})
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.duplicate_resolution == 'open_existing'
assert candidate.selected is False
assert candidate.validation_status == 'needs_review'
@@ -1,20 +1,23 @@
"""shipping_notice query_service 读路径单测。"""
"""
backend/tests/test_shipping_notice_query_service.py
用途:shipping_notice query_service 读路径单测(任务/待办;co8 已移除批次排序用例)。
依赖:pytest、ShippingNotice、query_service。
逻辑:覆盖 task_no 解析、分页、投影与 my_todos UNION。
"""
import pytest
from app.models import ShippingNotice
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.query_service import (
BatchProjection,
TaskProjection,
compute_batch_process_summary,
extract_task_no_from_text,
get_task_by_ref,
get_task_in_batch,
list_tasks_for_user,
list_tasks_page_for_user,
list_batch_task_summaries,
resolve_task_from_payload,
serialize_batch,
serialize_task,
sort_batch_tasks,
task_export_error_message,
task_sort_key,
)
@@ -24,7 +27,7 @@ from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
"""task_no 与数字主键均应能解析到同一任务。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-TEST-QUERY-001",
process_status="created",
source_type="manual",
@@ -41,45 +44,6 @@ def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
assert by_no.id == by_id.id
def test_sort_batch_tasks_orders_by_batch_index_then_created_at(app):
"""批次内排序应与 batch_index、created_at 规则一致。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-TEST-SORT", file_count=2)
second = ShippingTask(task_no="SN-SORT-2", batch_index=2, process_status="created", source_type="manual")
first = ShippingTask(task_no="SN-SORT-1", batch_index=1, process_status="created", source_type="manual")
from app import db
db.session.add(batch)
db.session.flush()
second.batch_id = batch.id
first.batch_id = batch.id
db.session.add_all([first, second])
db.session.commit()
ordered = sort_batch_tasks([second, first])
assert [item.task_no for item in ordered] == ["SN-SORT-1", "SN-SORT-2"]
assert task_sort_key(first) < task_sort_key(second)
summaries = list_batch_task_summaries(batch)
assert [row["task_no"] for row in summaries] == ["SN-SORT-1", "SN-SORT-2"]
def test_get_task_in_batch_rejects_foreign_task(app):
"""不属于目标批次的任务应返回 None。"""
with app.app_context():
batch_a = ShippingBatch(batch_no="SB-A", file_count=1)
batch_b = ShippingBatch(batch_no="SB-B", file_count=1)
task = ShippingTask(task_no="SN-FOREIGN", process_status="created", source_type="manual")
from app import db
db.session.add_all([batch_a, batch_b])
db.session.flush()
task.batch_id = batch_a.id
db.session.add(task)
db.session.commit()
assert get_task_in_batch("SB-A", "SN-FOREIGN") is not None
assert get_task_in_batch("SB-B", "SN-FOREIGN") is None
def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
@@ -87,14 +51,14 @@ def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
with app.app_context():
from app import db
shortage = ShippingTask(
shortage = ShippingNotice(
task_no="SN-FILTER-SHORTAGE",
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
)
ordinary = ShippingTask(
ordinary = ShippingNotice(
task_no="SN-FILTER-PARSE",
process_status="pending_review",
review_status="parse_review",
@@ -115,7 +79,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
from app import db
db.session.add_all([
ShippingTask(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", process_status="created", source_type="manual")
for index in range(1, 6)
])
db.session.commit()
@@ -141,9 +105,9 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
from app import db
db.session.add_all([
ShippingTask(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
ShippingTask(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
ShippingTask(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-1", process_status="created", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-2", process_status="created", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-3", process_status="uploaded", source_type="manual"),
])
db.session.commit()
@@ -159,10 +123,10 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
def test_task_export_error_message_distinct_for_missing_path(app):
"""无导出路径与磁盘缺失应返回不同错误文案。"""
with app.app_context():
empty = ShippingTask(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
empty = ShippingNotice(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
assert task_export_error_message(empty) == "export file not found"
missing = ShippingTask(
missing = ShippingNotice(
task_no="SN-MISSING-FILE",
process_status="matched",
source_type="manual",
@@ -174,7 +138,7 @@ def test_task_export_error_message_distinct_for_missing_path(app):
def test_task_projection_tool_strips_internal_fields(app):
"""TOOL 投影应剔除 Agent 不应复述的内部状态字段。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-PROJ-TOOL",
process_status="waiting_inventory",
review_status="align_review",
@@ -195,7 +159,7 @@ def test_task_projection_tool_strips_internal_fields(app):
def test_task_projection_internal_keeps_status_fields(app):
"""TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-PROJ-INT",
process_status="parsed",
review_status="parse_review",
@@ -206,39 +170,11 @@ def test_task_projection_internal_keeps_status_fields(app):
assert data["review_status"] == "parse_review"
def test_batch_process_summary_shared_formula(app):
"""批次汇总公式在 serialize_batch 与 compute_batch_process_summary 间应一致。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-SUMMARY", file_count=2)
done = ShippingTask(task_no="SN-DONE", process_status="uploaded", source_type="manual", batch_index=1)
running = ShippingTask(task_no="SN-RUN", process_status="matched", source_type="manual", batch_index=2)
from app import db
db.session.add(batch)
db.session.flush()
done.batch_id = batch.id
running.batch_id = batch.id
db.session.add_all([done, running])
db.session.commit()
tasks = [done, running]
summary = compute_batch_process_summary(tasks)
assert summary["total"] == 2
assert summary["completed"] == 1
assert summary["failed"] == 0
assert summary["running"] == 1
assert summary["pending"] == 2
assert summary["current_task_no"] == "SN-RUN"
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
assert tool_batch["process_summary"]["completed"] == 1
assert tool_batch["batch_no"] == "SB-SUMMARY"
assert "id" not in tool_batch
def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
"""conversation_id 仅在同会话只有一票可操作任务时允许回退。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-CONV-1",
conversation_id="conv-abc",
process_status="parsed",
@@ -263,13 +199,13 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
db.session.add_all(
[
ShippingTask(
ShippingNotice(
task_no="SN-CONV-MULTI-1",
conversation_id="conv-multi",
process_status="parsed",
source_type="manual",
),
ShippingTask(
ShippingNotice(
task_no="SN-CONV-MULTI-2",
conversation_id="conv-multi",
process_status="pending_review",
@@ -294,13 +230,13 @@ def test_task_can_handle_only_creator(app):
from app import db
from app.services.shipping_notice.query_service import task_can_handle
owned = ShippingTask(
owned = ShippingNotice(
task_no="SN-HANDLE-OWN",
process_status="created",
source_type="manual",
user_id=42,
)
orphan = ShippingTask(
orphan = ShippingNotice(
task_no="SN-HANDLE-ORPHAN",
process_status="created",
source_type="manual",
@@ -325,13 +261,13 @@ def test_get_task_for_user_rejects_null_owner(app):
get_task_visible_to_user,
)
orphan = ShippingTask(
orphan = ShippingNotice(
task_no="SN-NULL-OWNER",
process_status="created",
source_type="manual",
user_id=None,
)
owned = ShippingTask(
owned = ShippingNotice(
task_no="SN-OWNED",
process_status="created",
source_type="manual",
@@ -353,7 +289,7 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
from app import db
from app.services.shipping_notice.query_service import serialize_task_summary
task = ShippingTask(
task = ShippingNotice(
task_no="SN-ENRICH-1",
process_status="pending_review",
review_status="parse_review",
@@ -384,7 +320,7 @@ def test_list_my_todos_and_count_buckets(app):
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
owner = 55
review = ShippingTask(
review = ShippingNotice(
task_no="SN-TODO-REVIEW",
process_status="pending_review",
review_status="parse_review",
@@ -392,7 +328,7 @@ def test_list_my_todos_and_count_buckets(app):
source_type="manual",
user_id=owner,
)
upload = ShippingTask(
upload = ShippingNotice(
task_no="SN-TODO-UPLOAD",
process_status="matched",
source_type="manual",
@@ -400,13 +336,13 @@ def test_list_my_todos_and_count_buckets(app):
export_file_path="/tmp/u.xlsx",
export_file_name="u.xlsx",
)
done = ShippingTask(
done = ShippingNotice(
task_no="SN-TODO-DONE",
process_status="uploaded",
source_type="manual",
user_id=owner,
)
other = ShippingTask(
other = ShippingNotice(
task_no="SN-TODO-OTHER",
process_status="pending_review",
review_status="parse_review",
@@ -482,6 +418,70 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
assert counts['total_pending_badge'] == counts['pending']
def test_list_my_todos_includes_orphan_parse_failed_intake(app):
"""
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
断言:item_kind=order_intake;todo_category=intake_parse;count.pending 计入。
"""
with app.app_context():
from app import db
from app.models import FileAsset, ShippingOrderIntake, User
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
user = User(username='todo-orphan-intake', email='todo-orphan@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no=f'FA-ORPHAN-{user.id}',
owner_user_id=user.id,
original_filename='orphan-fail.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/orphan-fail.pdf',
content_hash='b' * 64,
file_size=12,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f'SNI-ORPHAN-{user.id}',
asset_id=int(asset.id),
user_id=int(user.id),
conversation_id='c' * 32,
upload_batch_id='batch-orphan-1',
source_type='direct_pdf',
purpose='shipping_notice',
parse_status='parse_failed',
parser_version='test-v1',
error_code='SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
error_message='parse boom',
)
db.session.add(intake)
db.session.commit()
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
intake_items = [item for item in pending['items'] if item.get('item_kind') == 'order_intake']
assert intake_items, 'pending 应包含未建 OT 的失败 Intake'
hit = next(item for item in intake_items if item.get('intake_no') == intake.intake_no)
assert hit['todo_category'] == 'intake_parse'
assert hit['conversation_id'] == 'c' * 32
assert hit['source_file_name'] == 'orphan-fail.pdf'
assert hit['can_handle'] is True
assert hit['ui_state']['summary']['entry_surface'] == 'conversation_processing'
filtered = list_my_todos(
user.id, bucket='pending', page=1, page_size=50, todo_category='intake_parse',
)
assert any(item.get('intake_no') == intake.intake_no for item in filtered['items'])
counts = count_my_todos(user.id)
assert counts['pending'] >= 1
def test_list_my_todos_filters_review_case_by_customer_filename(app):
"""Review Case 客户过滤按来源文件名/Case 号匹配,不能只筛 Task。"""
with app.app_context():
@@ -525,7 +525,7 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
# 520 > 旧 limit(500),用于证明截断不再作为 total 来源。
total_tasks = 520
tasks = [
ShippingTask(
ShippingNotice(
task_no=f"SN-TODO-PAGE-{index:04d}",
process_status="pending_review",
review_status="parse_review",
@@ -576,7 +576,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
owner = 88
fixtures = [
ShippingTask(
ShippingNotice(
task_no="SN-LW-REVIEW",
process_status="pending_review",
review_status="parse_review",
@@ -584,7 +584,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
source_type="manual",
user_id=owner,
),
ShippingTask(
ShippingNotice(
task_no="SN-LW-UPLOAD",
process_status="matched",
source_type="manual",
@@ -592,7 +592,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
export_file_path="/tmp/lw.xlsx",
export_file_name="lw.xlsx",
),
ShippingTask(
ShippingNotice(
task_no="SN-LW-SHORTAGE",
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
process_status="parsed",
@@ -601,13 +601,13 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
source_type="manual",
user_id=owner,
),
ShippingTask(
ShippingNotice(
task_no="SN-LW-DONE",
process_status="uploaded",
source_type="manual",
user_id=owner,
),
ShippingTask(
ShippingNotice(
task_no="SN-LW-PROGRESS",
process_status="parsed",
source_type="manual",
@@ -637,7 +637,7 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
# SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。
sql_category = (
db.session.query(category_expr)
.filter(ShippingTask.id == task.id)
.filter(ShippingNotice.id == task.id)
.scalar()
)
assert sql_category == expected
@@ -1,475 +0,0 @@
"""
backend/tests/test_shipping_notice_reference_context.py
用途:验证发货通知 reference_context 的 focus/动作/失败候选摘要构建。
依赖:models.ShippingBatch/ShippingTask/ShippingTaskEvent、shipping_notice.reference_context。
逻辑:直接构造批次、任务与少量事件,确保 Dify 只拿到短期指代线索,不会收到整批任务明细。
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta
from app import db
from app.models import ShippingBatch, ShippingTask, ShippingTaskEvent
from app.services.agent_runtime_context.policy import MAX_RECENT_ACTIVITY_SUMMARY_CHARS
from app.services.shipping_notice.reference_context import build_shipping_reference_context
def _make_task(
*,
task_no: str,
batch: ShippingBatch,
updated_at: datetime,
process_status: str = "created",
current_step: str | None = None,
pending_human_reason: str | None = None,
review_status: str | None = None,
match_status: str | None = None,
upload_status: str | None = None,
shortage_json: dict | None = None,
error_message: str | None = None,
) -> ShippingTask:
"""构造测试任务,减少样板字段噪音。"""
return ShippingTask(
task_no=task_no,
batch=batch,
conversation_id=batch.conversation_id,
source_type="manual",
process_status=process_status,
current_step=current_step,
pending_human_reason=pending_human_reason,
review_status=review_status,
match_status=match_status,
upload_status=upload_status,
shortage_json=shortage_json,
error_message=error_message,
updated_at=updated_at,
created_at=updated_at - timedelta(minutes=5),
)
def test_build_shipping_reference_context_includes_focus_and_last_action(app):
"""当前 focus task 与最近确认动作应进入 reference_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-001",
conversation_id="conv-ref-001",
current_focus_task_no="SN-REF-FOCUS-001",
file_count=2,
)
action_task = _make_task(
task_no="SN-REF-ACTION-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 9, 0, 0),
process_status="parsed",
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 9, 5, 0),
process_status="pending_review",
current_step="step2_parse_confirm",
)
db.session.add_all([batch, action_task, focus_task])
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=action_task.id,
event_type="parse_confirmed",
detail_json={"comment": "ok"},
created_at=datetime(2026, 7, 2, 9, 6, 0),
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-FOCUS-001"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-ACTION-001",
"action": "confirm_parse",
}
assert "当前 focus 为 SN-REF-FOCUS-001" in context["recent_activity_summary"]
assert "用户已确认 SN-REF-ACTION-001 解析" in context["recent_activity_summary"]
def test_build_shipping_reference_context_includes_last_failed_target(app):
"""最近失败任务应收敛为 last_failed_target,而不是要求 Dify 自己遍历整批任务。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-FAIL",
conversation_id="conv-ref-fail",
current_focus_task_no="SN-REF-FOCUS-002",
file_count=2,
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 10, 0, 0),
process_status="inventory_ready",
)
failed_task = _make_task(
task_no="SN-REF-FAIL-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 10, 10, 0),
process_status="pending_review",
match_status="shortage",
pending_human_reason="shortage",
shortage_json={"A001": 10},
)
db.session.add_all([batch, focus_task, failed_task])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
assert context["last_failed_target"] == {
"type": "task",
"id": "SN-REF-FAIL-002",
"reason": "shortage",
"label": "异常:库存不足",
}
assert "SN-REF-FAIL-002 库存匹配失败" in context["recent_activity_summary"]
def test_build_shipping_reference_context_limits_candidates_to_failure_tasks(app):
"""candidates 只应暴露少量失败/异常任务,不应把正常任务或整批明细塞进 context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-CAND",
conversation_id="conv-ref-cand",
current_focus_task_no="SN-REF-FOCUS-003",
file_count=5,
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 0, 0),
process_status="parsed",
)
shortage_task = _make_task(
task_no="SN-REF-SHORT-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 1, 0),
process_status="pending_review",
match_status="shortage",
pending_human_reason="shortage",
shortage_json={"A001": 1},
)
rejected_task = _make_task(
task_no="SN-REF-REJECT-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 2, 0),
process_status="rejected",
review_status="rejected",
)
upload_failed_task = _make_task(
task_no="SN-REF-UPFAIL-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 3, 0),
process_status="upload_failed",
upload_status="failed",
pending_human_reason="upload_rpa_failed",
)
normal_task = _make_task(
task_no="SN-REF-NORMAL-003",
batch=batch,
updated_at=datetime(2026, 7, 2, 11, 4, 0),
process_status="matched",
)
db.session.add_all([batch, focus_task, shortage_task, rejected_task, upload_failed_task, normal_task])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
candidates = {item["id"]: item["label"] for item in context["candidates"]}
assert candidates == {
"SN-REF-UPFAIL-003": "异常:上传失败",
"SN-REF-REJECT-003": "已驳回",
"SN-REF-SHORT-003": "异常:库存不足",
}
assert "SN-REF-NORMAL-003" not in json.dumps(context, ensure_ascii=False)
def test_build_shipping_reference_context_controls_summary_length_and_avoids_full_batch_dump(app):
"""多任务批次应只输出短摘要,不能把所有 task_no 都拼进 recent_activity_summary。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-SUMMARY",
conversation_id="conv-ref-summary",
current_focus_task_no="SN-REF-FOCUS-004",
file_count=10,
)
focus_task = _make_task(
task_no="SN-REF-FOCUS-004",
batch=batch,
updated_at=datetime(2026, 7, 2, 12, 0, 0),
process_status="parsed",
)
db.session.add_all([batch, focus_task])
for index in range(10):
db.session.add(
_make_task(
task_no=f"SN-REF-NOISE-{index:03d}",
batch=batch,
updated_at=datetime(2026, 7, 2, 12, 1, 0) + timedelta(minutes=index),
process_status="pending_review" if index % 2 == 0 else "matched",
match_status="shortage" if index == 0 else None,
pending_human_reason="shortage" if index == 0 else None,
shortage_json={"SKU": index} if index == 0 else None,
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
summary = context["recent_activity_summary"]
assert len(summary) <= MAX_RECENT_ACTIVITY_SUMMARY_CHARS
assert "SN-REF-FOCUS-004" in summary
assert "SN-REF-NOISE-000" in summary
assert "SN-REF-NOISE-009" not in summary
def test_build_shipping_reference_context_maps_real_decision_event_names(app):
"""真实决策事件名应能映射到标准 action,避免 reference builder 只认理想化别名。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-ACTION-MAP",
conversation_id="conv-ref-action-map",
current_focus_task_no="SN-REF-ACTION-MAP-001",
file_count=2,
)
reject_task = _make_task(
task_no="SN-REF-REJECT-REAL",
batch=batch,
updated_at=datetime(2026, 7, 2, 13, 0, 0),
process_status="rejected",
review_status="rejected",
)
focus_task = _make_task(
task_no="SN-REF-ACTION-MAP-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 13, 1, 0),
process_status="parsed",
)
db.session.add_all([batch, reject_task, focus_task])
db.session.flush()
db.session.add_all([
ShippingTaskEvent(
task_id=reject_task.id,
event_type="decision_rejected",
detail_json={"action": "reject", "target_id": reject_task.task_no},
created_at=datetime(2026, 7, 2, 13, 2, 0),
),
ShippingTaskEvent(
task_id=focus_task.id,
event_type="decision_rematch",
detail_json={"action": "rematch", "target_id": focus_task.task_no},
created_at=datetime(2026, 7, 2, 13, 3, 0),
),
])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=focus_task)
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-ACTION-MAP-001",
"action": "rematch",
}
assert context["last_failed_target"]["id"] == "SN-REF-REJECT-REAL"
assert context["last_failed_target"]["reason"] == "rejected"
def test_build_shipping_reference_context_recognizes_focus_switch_event(app):
"""focus_switched 应能进入 last_action_target,供 Dify 理解“刚才切过去那个”。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-SWITCH",
conversation_id="conv-ref-switch",
current_focus_task_no="SN-REF-SWITCH-002",
file_count=2,
)
old_focus = _make_task(
task_no="SN-REF-SWITCH-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 14, 0, 0),
process_status="parsed",
)
new_focus = _make_task(
task_no="SN-REF-SWITCH-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 14, 5, 0),
process_status="pending_review",
)
db.session.add_all([batch, old_focus, new_focus])
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=new_focus.id,
event_type="focus_switched",
detail_json={
"action": "switch_focus",
"target_id": new_focus.task_no,
"previous_focus_task_no": old_focus.task_no,
"next_focus_task_no": new_focus.task_no,
},
created_at=datetime(2026, 7, 2, 14, 6, 0),
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=new_focus)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-SWITCH-002"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-SWITCH-002",
"action": "switch_focus",
}
assert "用户已切换 focus 到 SN-REF-SWITCH-002" in context["recent_activity_summary"]
def test_build_shipping_reference_context_distinguishes_confirm_parse_and_confirm_matched(app):
"""parse_confirmed 与 decision_confirmed 应映射到不同 action,避免“确认解析”和“确认匹配结果”混淆。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-CONFIRM-TYPES",
conversation_id="conv-ref-confirm-types",
current_focus_task_no="SN-REF-CONFIRM-TYPES-002",
file_count=2,
)
parse_task = _make_task(
task_no="SN-REF-CONFIRM-TYPES-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 15, 0, 0),
process_status="parsed",
)
matched_task = _make_task(
task_no="SN-REF-CONFIRM-TYPES-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 15, 1, 0),
process_status="matched",
)
db.session.add_all([batch, parse_task, matched_task])
db.session.flush()
db.session.add_all([
ShippingTaskEvent(
task_id=parse_task.id,
event_type="parse_confirmed",
detail_json={"source": "workspace_api", "target_id": parse_task.task_no},
created_at=datetime(2026, 7, 2, 15, 2, 0),
),
ShippingTaskEvent(
task_id=matched_task.id,
event_type="decision_confirmed",
detail_json={"source": "workspace_api", "target_id": matched_task.task_no},
created_at=datetime(2026, 7, 2, 15, 3, 0),
),
])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=matched_task)
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-CONFIRM-TYPES-002",
"action": "confirm_matched",
}
assert "用户已确认 SN-REF-CONFIRM-TYPES-002 当前结果" in context["recent_activity_summary"]
def test_build_shipping_reference_context_prefers_user_focus_switch_over_auto_switch(app):
"""用户切票与系统自动切票并存时,应优先保留用户动作,避免“刚才那个”被后台动作覆盖。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-SWITCH-PRIORITY",
conversation_id="conv-ref-switch-priority",
current_focus_task_no="SN-REF-SWITCH-PRIORITY-002",
file_count=2,
)
user_focus = _make_task(
task_no="SN-REF-SWITCH-PRIORITY-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 16, 0, 0),
process_status="parsed",
)
auto_focus = _make_task(
task_no="SN-REF-SWITCH-PRIORITY-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 16, 1, 0),
process_status="pending_review",
)
db.session.add_all([batch, user_focus, auto_focus])
db.session.flush()
db.session.add_all([
ShippingTaskEvent(
task_id=user_focus.id,
event_type="focus_switched",
detail_json={"source": "workspace_api", "target_id": user_focus.task_no},
created_at=datetime(2026, 7, 2, 16, 2, 0),
),
ShippingTaskEvent(
task_id=auto_focus.id,
event_type="focus_auto_switched",
detail_json={"source": "backend_orchestrator", "target_id": auto_focus.task_no},
created_at=datetime(2026, 7, 2, 16, 3, 0),
),
])
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=auto_focus)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-SWITCH-PRIORITY-002"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-SWITCH-PRIORITY-001",
"action": "switch_focus",
}
assert "用户已切换 focus 到 SN-REF-SWITCH-PRIORITY-001" in context["recent_activity_summary"]
def test_build_shipping_reference_context_uses_auto_focus_when_only_auto_switch_exists(app):
"""只有系统自动切票时,应显式暴露 auto_focus,避免与用户手动切票混淆。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-REF-AUTO-FOCUS",
conversation_id="conv-ref-auto-focus",
current_focus_task_no="SN-REF-AUTO-FOCUS-002",
file_count=2,
)
old_focus = _make_task(
task_no="SN-REF-AUTO-FOCUS-001",
batch=batch,
updated_at=datetime(2026, 7, 2, 17, 0, 0),
process_status="parsed",
)
auto_focus = _make_task(
task_no="SN-REF-AUTO-FOCUS-002",
batch=batch,
updated_at=datetime(2026, 7, 2, 17, 1, 0),
process_status="pending_review",
)
db.session.add_all([batch, old_focus, auto_focus])
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=auto_focus.id,
event_type="focus_auto_switched",
detail_json={"source": "backend_orchestrator", "target_id": auto_focus.task_no},
created_at=datetime(2026, 7, 2, 17, 2, 0),
)
)
db.session.commit()
context = build_shipping_reference_context(batch=batch, focus_task=auto_focus)
assert context["focus_object"] == {"type": "task", "id": "SN-REF-AUTO-FOCUS-002"}
assert context["last_action_target"] == {
"type": "task",
"id": "SN-REF-AUTO-FOCUS-002",
"action": "auto_focus",
}
assert "系统自动聚焦到 SN-REF-AUTO-FOCUS-002" in context["recent_activity_summary"]
@@ -2,13 +2,13 @@
tests/test_shipping_notice_state_machine.py
用途:校验发货通知状态机注册表完整性与 STP checkpoint_kind 映射。
依赖:pytest、state_machine、constants、ShippingTask。
依赖:pytest、state_machine、constants、ShippingNotice。
逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。
"""
from types import SimpleNamespace
from app.models import ShippingTask
from app.models import ShippingNotice
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_PARSE_REVIEW,
@@ -39,7 +39,7 @@ def test_checkpoint_kinds_for_stp_stop_points() -> None:
def test_resolve_task_ui_state_parse_review(app) -> None:
"""pending_review + parse_review 应映射为 must_human / parse_review。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-SM-PARSE",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
@@ -54,7 +54,7 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
def test_resolve_task_ui_state_export_ready(app) -> None:
"""matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-SM-EXPORT",
process_status="matched",
source_type="manual",
@@ -70,7 +70,7 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
"""process_status=uploaded 应为 complete。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-SM-UPLOADED",
process_status="uploaded",
source_type="manual",
@@ -10,7 +10,7 @@ from __future__ import annotations
import pytest
from app.models import ShippingTask, User
from app.models import ShippingNotice, User
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_PARSE_REVIEW,
@@ -36,7 +36,7 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
from app import db
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-WAIT-UPLOAD",
process_status="matched",
source_type="manual",
@@ -60,7 +60,7 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
from app import db
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-MUST-HUMAN",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
@@ -83,7 +83,7 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch)
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-RPA-ON",
process_status="matched",
match_status="fulfillable",
@@ -125,7 +125,7 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch)
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = True
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-NO-RPA",
process_status="matched",
match_status="fulfillable",
@@ -164,7 +164,7 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
from app import db
from types import SimpleNamespace
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-MANUAL-CFM",
process_status="waiting_upload",
source_type="manual",
@@ -233,7 +233,7 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
from app import db
from types import SimpleNamespace
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-CLOSE-FAIL",
process_status="waiting_upload",
source_type="manual",
@@ -299,7 +299,7 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
"""场景:Excel 待人工上传登记待办深链入口为任务处理工作台。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-STP-ENTRY",
process_status="matched",
source_type="manual",
@@ -336,7 +336,7 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
db.session.add_all([owner, admin])
db.session.flush()
mine = ShippingTask(
mine = ShippingNotice(
task_no="SN-STP-OWN",
user_id=owner.id,
process_status="pending_review",
@@ -344,7 +344,7 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
waiting_upload = ShippingTask(
waiting_upload = ShippingNotice(
task_no="SN-STP-UPLOAD",
user_id=owner.id,
process_status="matched",
@@ -352,7 +352,7 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
export_file_path="/tmp/own.xlsx",
export_file_name="own.xlsx",
)
other = ShippingTask(
other = ShippingNotice(
task_no="SN-STP-OTHER",
user_id=admin.id,
process_status="pending_review",
+21 -21
View File
@@ -2,7 +2,7 @@
backend/tests/test_shipping_notice_tools.py
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
依赖:Flask 测试客户端、ShippingTask/Customer、货代 workflow 测试辅助。
依赖:Flask 测试客户端、ShippingNotice/Customer、货代 workflow 测试辅助。
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
"""
@@ -14,7 +14,7 @@ import pytest
from app import db
from app.models import (
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule,
ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingTask,
ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
@@ -34,7 +34,7 @@ def _tool_headers(app):
}
def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。"""
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
fields = {
@@ -258,7 +258,7 @@ def test_openapi_spec_public(app, client):
assert "/tools/generate_shipment_excel" not in spec["paths"]
assert "/tools/upload_to_freight" not in spec["paths"]
assert "/tools/switch_focus_task" not in spec["paths"]
assert set(spec["paths"]) == {"/tools/get_task_status", "/tools/get_batch_status"}
assert set(spec["paths"]) == {"/tools/get_task_status"}
spec_text = str(spec)
assert "只读解释" in spec_text
assert "submit_decision" not in spec_text
@@ -268,7 +268,7 @@ def test_confirm_inventory_source_route_returns_json(app, client):
"""confirm_inventory_source HTTP 路由必须存在且可调用。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-HTTP-CONFIRM-SRC",
source_type="manual",
process_status="pending_review",
@@ -306,7 +306,7 @@ def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory")
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory")
db.session.add(task)
db.session.commit()
@@ -327,7 +327,7 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
"""重新上传库存只重置正式库存结果,不进入任务级字段映射。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-REUPLOAD-INVENTORY",
source_type="manual",
process_status="matched",
@@ -367,7 +367,7 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
assert body["checkpoint"] == "upload_req"
assert body["human_options"] == ["upload_inventory_file", "retry_rpa"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
assert link.is_active is False
assert task.process_status == "waiting_inventory"
@@ -483,7 +483,7 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "inventory_ready"
@@ -520,7 +520,7 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"}
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
@@ -565,7 +565,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "waiting_inventory"
@@ -592,7 +592,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
with app.app_context():
result = _run_single_task(task_id)
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["status"] == "needs_human"
assert task.process_status == "waiting_inventory"
@@ -629,7 +629,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "waiting_inventory"
@@ -665,7 +665,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
@@ -713,7 +713,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
task_id = task_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.process_status = "waiting_inventory"
@@ -740,7 +740,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
with app.app_context():
result = retry_batch_pending_tasks(batch_no)
task = ShippingTask.query.filter_by(task_no=task_id).first()
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["started"] == 1
assert result["skipped"] == 0
@@ -755,7 +755,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
headers = _tool_headers(app)
first = ShippingTask(
first = ShippingNotice(
task_no="SN-MULTI-CONV-001",
conversation_id="conv-test-multi",
process_status="pending_review",
@@ -764,7 +764,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
source_type="manual",
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
)
second = ShippingTask(
second = ShippingNotice(
task_no="SN-MULTI-CONV-002",
conversation_id="conv-test-multi",
process_status="pending_review",
@@ -798,8 +798,8 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
with app.app_context():
rows = {
task.task_no: task
for task in ShippingTask.query.filter(ShippingTask.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
.order_by(ShippingTask.task_no)
for task in ShippingNotice.query.filter(ShippingNotice.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
.order_by(ShippingNotice.task_no)
.all()
}
assert rows["SN-MULTI-CONV-001"].process_status == "pending_review"
@@ -860,7 +860,7 @@ def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-20260101-TEST0001",
source_type="manual",
process_status="rejected",
@@ -2,11 +2,11 @@
tests/test_shipping_notice_ui_state.py
用途:校验发货通知 UI State 摘要字段与 entry_surface 映射。
依赖:pytest、ShippingTask、ui_state、state_machine constants。
依赖:pytest、ShippingNotice、ui_state、state_machine constants。
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
"""
from app.models import ShippingTask
from app.models import ShippingNotice
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_PARSE_REVIEW,
@@ -34,7 +34,7 @@ _REQUIRED_SUMMARY_KEYS = {
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
"""summary 必须包含 STP 可解释字段全集。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-UI-SUMMARY",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
@@ -51,7 +51,7 @@ def test_build_task_ui_state_summary_has_required_keys(app) -> None:
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
"""解析复核应进入人工复核工作台。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-UI-REVIEW",
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
@@ -65,7 +65,7 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None:
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
"""Excel 待人工上传登记应进入任务处理工作台(下载 + 登记)。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-UI-EXPORT",
process_status="matched",
source_type="manual",
@@ -86,7 +86,7 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
def test_stp_facts_candidates_frozen_projected(app) -> None:
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-UI-STP-FROZEN",
process_status="waiting_inventory",
source_type="manual",
@@ -109,7 +109,7 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
def test_stp_facts_projects_line_resolutions(app) -> None:
"""stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。"""
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-UI-STP-LINES",
process_status="matched",
source_type="manual",
@@ -148,7 +148,7 @@ def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW
with app.app_context():
task = ShippingTask(
task = ShippingNotice(
task_no="SN-UI-STP-MULTI",
process_status="matched",
review_status=RS_SHORTAGE_REVIEW,
@@ -2,11 +2,11 @@
tests/test_shipping_notice_user_facing_status.py
用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。
依赖:pytest、ShippingTask 模型、user_facing_status。
逻辑:构造最小 ShippingTask 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。
依赖:pytest、ShippingNotice 模型、user_facing_status。
逻辑:构造最小 ShippingNotice 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。
"""
from app.models import ShippingTask
from app.models import ShippingNotice
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
@@ -17,7 +17,7 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
核心逻辑:构造 waiting_inventory + rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。
"""
task = ShippingTask(
task = ShippingNotice(
task_no="SN-TEST-RPA-PENDING",
process_status="waiting_inventory",
pending_human_reason=PH_RPA_PENDING,
@@ -1,60 +0,0 @@
"""
backend/tests/test_shipping_notice_workflow_migration.py
用途:验收 Workflow 四表 ORM 可查询,并确认旧 ShippingSessionPdfWorkItem 已从 models 移除。
依赖:app fixture(db.create_all)、ShippingNoticeWorkflow* ORM、迁移 9d2f4a6b8c0e。
逻辑:create_all 后四表可空查;禁止从 app.models 导入旧会话工作项;
迁移脚本须创建 Workflow 表并 drop 旧表,且不做历史数据迁移/回填。
"""
from __future__ import annotations
from pathlib import Path
import pytest
from app.models import (
ShippingNoticeWorkflow,
ShippingNoticeWorkflowEvent,
ShippingNoticeWorkflowItem,
ShippingNoticeWorkflowItemVersion,
)
def test_workflow_orm_tables_are_queryable_after_create_all(app):
"""app fixture create_all 后 Workflow / Item / Version / Event 均可经 ORM 查询。"""
with app.app_context():
# 关键断言:四表已建且可空结果查询,证明 ORM 与内存库表结构对齐。
assert ShippingNoticeWorkflow.query.count() == 0
assert ShippingNoticeWorkflowItem.query.count() == 0
assert ShippingNoticeWorkflowItemVersion.query.count() == 0
assert ShippingNoticeWorkflowEvent.query.count() == 0
def test_shipping_session_pdf_work_item_is_not_importable_from_app_models():
"""旧 ShippingSessionPdfWorkItem 不得再从 app.models 导出。"""
import app.models as models
# 关键断言:迁移后旧会话工作项模型已删除,属性访问或显式 import 必须失败。
assert not hasattr(models, 'ShippingSessionPdfWorkItem')
with pytest.raises((ImportError, AttributeError)):
from app.models import ShippingSessionPdfWorkItem # noqa: F401
def test_migration_9d2f4a6b8c0e_drops_session_work_items_without_history_migration():
"""迁移 9d2f4a6b8c0e 须建 Workflow 表并 drop 旧表,且不迁移/回填历史会话工作项。"""
revision = (
Path(__file__).resolve().parents[1]
/ 'migrations'
/ 'versions'
/ '9d2f4a6b8c0e_replace_session_work_items_with_workflows.py'
)
# 关键断言:替换会话工作项的迁移文件存在,且明确不做历史迁移。
assert revision.is_file()
text = revision.read_text(encoding='utf-8')
assert "revision = '9d2f4a6b8c0e'" in text
assert "drop_table('shipping_session_pdf_work_items')" in text
assert 'shipping_notice_workflows' in text
assert '_migrate_session_work_items_to_workflows' not in text
assert '_restore_session_work_items_from_workflows' not in text
assert '不迁' in text or '不做历史' in text or '不迁移' in text
@@ -18,7 +18,7 @@ def test_freeze_created_tasks_requires_eligible_candidate_nos():
"""空 eligible 集合必须直接返回,禁止扩大冻结范围。"""
run = SimpleNamespace(id=1)
with patch(
'app.services.shipping_notice.order_auto_freeze_execution.ShippingNoticeCandidate'
'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate'
) as candidate_model:
frozen, blocked = _freeze_created_tasks(run=run, policy={'enabled': True}, candidate_nos=[])
assert frozen == []
@@ -36,7 +36,7 @@ def test_freeze_created_tasks_filters_accepted_selected_and_eligible_nos():
query.all.return_value = []
with patch(
'app.services.shipping_notice.order_auto_freeze_execution.ShippingNoticeCandidate'
'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate'
) as candidate_model:
candidate_model.query = query
frozen, blocked = _freeze_created_tasks(
@@ -26,7 +26,7 @@ from app.models import (
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRouteDecision,
ShippingOrderRouteDecision,
)
from app.services.shipping_notice.order_auto_freeze_policy import evaluate_run_auto_freeze_policy
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
@@ -43,7 +43,7 @@ def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrde
schema_version_id=schema_version_id,
structure_fingerprint='fp-' + checksum[:16],
checksum=checksum,
definition_json={'contract_version': 'order_coordinate_profile.v2', 'table_regions': []},
definition_json={'table_regions': []},
published_at=datetime.utcnow(),
)
db.session.add(profile)
@@ -121,7 +121,7 @@ def test_evaluate_run_auto_freeze_policy_keeps_fail_closed_with_run_blockers(app
run.status = 'review_required'
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -198,7 +198,7 @@ def test_evaluate_run_auto_freeze_policy_blocks_suspended_profile(app):
)
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -265,7 +265,7 @@ def test_evaluate_run_auto_freeze_policy_matches_customer_and_business_scope(app
)
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -346,7 +346,7 @@ def test_evaluate_run_auto_freeze_policy_ignores_placeholder_pending_orders(app)
)
db.session.add_all([
qualification,
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -401,7 +401,7 @@ def test_generic_straight_through_can_enable_auto_freeze_when_flag_on(app, monke
job = db.session.get(Job, run.current_job_id)
run.status = 'completed'
db.session.add(
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -451,7 +451,7 @@ def test_generic_deterministic_needs_review_cannot_auto_freeze(app, monkeypatch)
job = db.session.get(Job, run.current_job_id)
run.status = 'completed'
db.session.add(
ShippingOrderExtractionRouteDecision(
ShippingOrderRouteDecision(
run_id=run.id,
unit_id=unit.id,
job_id=job.id,
@@ -1,279 +0,0 @@
"""
backend/tests/test_shipping_order_document_profile.py
用途:验证订单模板 Profile 精确结构匹配、列语义覆盖、复合 cell 和零数量门禁。
依赖:document_layout.order_profile/html_table、冻结订单 Schema 表头契约。
逻辑:使用合成模板证明特例不污染全局 Schema;结构不匹配或行关系丢失时显式阻断。
"""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.order_profile import (
OrderCoordinateProfileV2,
OrderDocumentProfile,
OrderProfileColumnRule,
diagnose_order_profile_header,
order_profile_structure_fingerprint,
parse_html_table_with_order_profile,
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
def _field(code: str, *, value_type: str = 'string', required: bool = False) -> dict:
"""构造模板 Profile 执行所需的最小冻结字段配置。"""
return {
'field_id': f'id-{code}', 'field_code': code, 'scope': 'line',
'value_type': value_type, 'enabled': True, 'required': required,
'display_name': code, 'aliases': [], 'normalizer_key': 'trim',
'validator_keys': ['positive_decimal'] if code == 'qty' else [],
'collection_mode': 'llm_extraction',
}
def _contract():
"""创建覆盖客户 PO 行号、三料号和数量的冻结 Schema 契约。"""
return compile_table_header_contract({'fields': [
_field('customer_po_line_no'), _field('customer_part_number'),
_field('part_number', required=True), _field('aws_part_number'),
_field('qty', value_type='decimal', required=True),
]})
def _profile(html: str, rules: list[OrderProfileColumnRule]) -> OrderDocumentProfile:
"""从合成样本表头生成只用于测试的精确结构 Profile。"""
grid = parse_html_grid(html, table_id='sample')
return OrderDocumentProfile(
profile_code='ORDER_TEMPLATE_A',
version=1,
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
header_row_index=0,
data_start_row_index=1,
column_rules=rules,
)
def test_template_profile_overrides_global_part_number_semantics_without_collision():
"""特定模板可把 Part Number 与 Vendor Item 映射到客户/内部料号,不修改全局别名。"""
html = (
'<table><tr><th>LN</th><th>Part Number</th><th>Vendor Item#</th><th>Qty</th></tr>'
'<tr><td>1</td><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr></table>'
)
profile = _profile(html, [
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['customer_part_number']),
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['part_number']),
OrderProfileColumnRule(column_index=3, extractor_key='direct', target_field_codes=['qty']),
])
result = parse_html_table_with_order_profile(
html, table_id='runtime', profile=profile, contract=_contract(),
)
assert result.matched is True
assert result.rows[0].status == 'parsed'
assert result.rows[0].fields == {
'customer_po_line_no': '1', 'customer_part_number': 'CUSTOMER-1',
'part_number': 'INTERNAL-1', 'qty': 3.0,
}
def test_template_profile_extracts_registered_temp_and_internal_parts_from_composite_cell():
"""已注册复合解析器可从单 cell 提取客户 TEMP 与内部 D4,描述文本不进入料号值。"""
html = (
'<table><tr><th>Line</th><th>Parts & Description</th><th>QTY</th></tr>'
'<tr><td>10</td><td>AMTEMP-S000001 supplier D4-A08AR12000001 enclosure</td><td>2</td></tr></table>'
)
profile = _profile(html, [
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
OrderProfileColumnRule(
column_index=1,
extractor_key='temp_internal_parts',
target_field_codes=['customer_part_number', 'part_number'],
),
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
])
row = parse_html_table_with_order_profile(
html, table_id='runtime', profile=profile, contract=_contract(),
).rows[0]
assert row.status == 'parsed'
assert row.fields['customer_part_number'] == 'AMTEMP-S000001'
assert row.fields['part_number'] == 'D4-A08AR12000001'
def test_template_profile_drops_explicit_zero_qty_row():
"""管理员确认的零数量业务规则必须在模板解析入口删除整行。"""
html = (
'<table><tr><th>Vendor PN</th><th>Qty</th></tr>'
'<tr><td>INTERNAL-ZERO</td><td>0 EA</td></tr></table>'
)
profile = _profile(html, [
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['part_number']),
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['qty']),
])
row = parse_html_table_with_order_profile(
html, table_id='runtime', profile=profile, contract=_contract(),
).rows[0]
assert row.status == 'deleted'
assert row.fields == {}
def test_template_profile_requires_exact_structure_fingerprint():
"""列数或表头变化时不得采用最相似模板或按旧位置解析。"""
sample = '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>A</td><td>1</td></tr></table>'
runtime = '<table><tr><th>Part</th><th>Description</th><th>Qty</th></tr><tr><td>A</td><td>X</td><td>1</td></tr></table>'
profile = _profile(sample, [
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['part_number']),
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['qty']),
])
result = parse_html_table_with_order_profile(
runtime, table_id='runtime', profile=profile, contract=_contract(),
)
assert result.matched is False
assert result.rows == []
assert result.issues == ['order_profile_structure_mismatch']
def test_template_profile_routes_lost_row_structure_without_column_mapping():
"""MinerU 已丢失订单行关系的模板只能识别并阻断,不能配置固定列伪装修复。"""
html = '<table><tr><th>Item</th><th>Material</th></tr><tr><td>fragment</td><td>fragment</td></tr></table>'
grid = parse_html_grid(html, table_id='lost')
profile = OrderDocumentProfile(
profile_code='LOST_ROW_TEMPLATE',
version=1,
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
header_row_index=0,
data_start_row_index=1,
row_structure='unsupported_row_structure',
)
result = parse_html_table_with_order_profile(
html, table_id='runtime', profile=profile, contract=_contract(),
)
assert result.matched is True
assert result.rows == []
assert result.issues == ['order_profile_row_structure_unsupported']
def test_profile_header_diagnosis_blocks_merged_item_number_data():
"""合并到表头的 `ITEM NO 00010` 必须在映射前被识别为明细污染。"""
html = (
'<table><tr><th>ITEM NO 00010</th><th>Part Number</th><th>Qty</th></tr>'
'<tr><td>00020</td><td>PART-2</td><td>36</td></tr></table>'
)
assert diagnose_order_profile_header(parse_html_grid(html, table_id='contaminated'), header_row_index=0) == [
'order_profile_header_contaminated_by_data',
]
def test_template_profile_rejects_freeform_or_invalid_extractor_targets():
"""Profile 只能引用注册 parser key 和固定输出字段,禁止自由代码/正则。"""
with pytest.raises(ValidationError):
OrderProfileColumnRule(
column_index=0,
extractor_key='custom_regex',
target_field_codes=['part_number'],
)
with pytest.raises(ValidationError, match='targets are fixed'):
OrderProfileColumnRule(
column_index=0,
extractor_key='temp_internal_parts',
target_field_codes=['part_number'],
)
def test_coordinate_profile_v2_accepts_independent_header_and_multi_physical_line_layouts():
"""坐标模板必须能表达多条表头、两条不同布局的物理行和独立字段区域。"""
definition = {
'profile_code': 'COORDINATE_A', 'version': 1,
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT:', 'value': 'PURCHASE ORDER'}]},
'table_regions': [{
'region_id': 'main_lines', 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .8},
'header_layouts': [
{'layout_id': 'header_one', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}, 'field_regions': []},
{'layout_id': 'header_two', 'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .2}, 'field_regions': []},
],
'line_layouts': [
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .4},
'field_regions': [{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'region': {'x0': 0, 'y0': .4, 'x1': 1, 'y1': .6},
'field_regions': [{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .5, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
], 'continuation_rule': {'allow_cross_page': False}, 'termination_rules': [], 'exclusion_regions': [],
}],
}
profile = OrderCoordinateProfileV2.model_validate(definition)
assert profile.contract_version == 'order_coordinate_profile.v2'
assert len(profile.table_regions[0].header_layouts) == 2
assert [item.row_offset for item in profile.table_regions[0].line_layouts] == [0, 1]
@pytest.mark.parametrize('mutation', [
lambda value: value['table_regions'][0]['line_layouts'][1].update({'row_offset': 2}),
lambda value: value['table_regions'][0]['line_layouts'][1].update({'role': 'main'}),
lambda value: value['table_regions'][0]['line_layouts'][1]['field_regions'][0].update({'field_code': 'line_no'}),
lambda value: value['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region'].update({'x1': 1.1}),
lambda value: value['table_regions'][0]['line_layouts'][1]['region'].update({'y0': .4}),
])
def test_coordinate_profile_v2_rejects_ambiguous_or_invalid_regions(mutation):
"""关键断言:错序物理行、重复字段和越界区域均不得进入可发布定义。"""
value = {
'profile_code': 'COORDINATE_B', 'version': 1, 'document_match': {},
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .5}, 'field_regions': [{'field_id': 'line', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}, 'field_regions': [{'field_id': 'qty', 'field_code': 'qty', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
]}],
}
mutation(value)
with pytest.raises(ValidationError):
OrderCoordinateProfileV2.model_validate(value)
def test_coordinate_profile_v2_requires_declared_document_anchor_for_cross_page_continuation():
"""跨页只能绑定已有静态文档锚点,不能以相邻页面或列数相近作为合并理由。"""
profile = {
'profile_code': 'CROSS_PAGE', 'version': 1,
'document_match': {'required_anchors': [{'anchor_id': 'continued', 'label': 'PAGE:', 'value': 'CONTINUED'}]},
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'continuation_rule': {'allow_cross_page': True, 'required_anchor_ids': ['continued']},
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'field_regions': [
{'field_id': 'line', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
]}],
}],
}
assert OrderCoordinateProfileV2.model_validate(profile).table_regions[0].continuation_rule.allow_cross_page is True
profile['table_regions'][0]['continuation_rule']['required_anchor_ids'] = []
with pytest.raises(ValidationError, match='cross-page continuation requires anchor evidence'):
OrderCoordinateProfileV2.model_validate(profile)
def test_coordinate_profile_v2_allows_internal_line_no_binding():
"""关键断言:坐标模板可绑定内部项次 line_no 作为明细字段与起行锚点。"""
definition = {
'profile_code': 'COORDINATE_INTERNAL_LINE', 'version': 1, 'document_match': {},
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'line_start_field_code': 'line_no',
'line_layouts': [
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [{'field_id': 'line', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
]}],
}
profile = OrderCoordinateProfileV2.model_validate(definition)
assert profile.table_regions[0].line_layouts[0].field_regions[0].field_code == 'line_no'
assert profile.table_regions[0].line_start_field_code == 'line_no'
@@ -22,8 +22,8 @@ from app.models import (
ShippingOrderDocumentProfileDraftRevision,
ShippingOrderDocumentProfileSample,
ShippingDocumentLayoutVersion,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
FileAsset,
@@ -94,7 +94,6 @@ def _data(schema_id: int, *, fingerprint: str = 'b' * 64) -> dict:
def _coordinate_definition() -> dict:
"""构造最小 v2 坐标模板,供来源授权和服务端 field_id 冻结断言使用。"""
return {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT TYPE:', 'value': 'PURCHASE ORDER', 'value_position': 'right'}]},
'table_regions': [{
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
@@ -156,7 +155,7 @@ def _bind_ready_profile_sample(
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no=f'SNI-PROFILE-SAMPLE-{suffix}',
asset_id=asset.id,
user_id=user.id,
@@ -166,7 +165,7 @@ def _bind_ready_profile_sample(
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
@@ -188,6 +187,16 @@ def _bind_ready_profile_sample(
'rows': [{'cells': [{'text': 'ok'}]}],
'html': '<table><tr><td>ok</td></tr></table>',
}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': [{
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
}]},
'tables': {table_id: [{
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
}]},
'sources': {'pages': {'1': 'pdf_coordinate'}, 'tables': {table_id: 'pdf'}},
},
})
db.session.commit()
service.add_profile_sample(
@@ -202,8 +211,8 @@ def _bind_ready_profile_sample(
).one()
def test_template_sample_status_requires_ready_coordinate_layout(app):
"""Intake 已解析但坐标布局失败时,向导必须停止轮询并显示模板不可用。"""
def test_template_sample_status_accepts_materialized_document_with_failed_layout(app):
"""Intake 已物化文档后不等待坐标布局;失败 Layout 留给复核阶段处理。"""
with app.app_context():
user = User(username='layout-status-admin', email='layout-status-admin@example.com', role='admin')
db.session.add(user)
@@ -216,13 +225,13 @@ def test_template_sample_status_requires_ready_coordinate_layout(app):
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-STATUS', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='layout.pdf',
filename='layout.pdf', content_hash='l' * 64, classification='supporting', parse_status='parsed',
)
@@ -236,14 +245,15 @@ def test_template_sample_status_requires_ready_coordinate_layout(app):
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
# 上传成功只取决于样本文档已物化;失败 Layout 留到预览复核阶段按需恢复或报错。
assert status == {
'intake_no': 'SNI-LAYOUT-STATUS', 'parse_status': 'failed', 'document_count': 1,
'error_code': 'mineru_cell_coordinates_missing',
'intake_no': 'SNI-LAYOUT-STATUS', 'parse_status': 'parsed', 'document_count': 1,
'document_ids': [document.id], 'error_code': None,
}
def test_template_sample_status_rejects_ready_layout_without_modeling_table(app):
"""文本布局完成但没有表格时不得误报样本已就绪,避免向导无限等待列表同步。"""
def test_template_sample_status_accepts_materialized_document_without_modeling_table(app):
"""样本文档物化后立即可选;后台预解析没有表格时由复核阶段按需恢复。"""
with app.app_context():
user = User(username='empty-table-status-admin', email='empty-table-status@example.com', role='admin')
asset = FileAsset(
@@ -254,12 +264,12 @@ def test_template_sample_status_rejects_ready_layout_without_modeling_table(app)
)
db.session.add_all([user, asset]); db.session.flush()
asset.owner_user_id = user.id
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-EMPTY-TABLE-STATUS', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
)
db.session.add(intake); db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='empty-layout.pdf',
filename='layout.pdf', content_hash='e' * 64, classification='supporting', parse_status='parsed',
)
@@ -272,9 +282,38 @@ def test_template_sample_status_rejects_ready_layout_without_modeling_table(app)
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
# Layout 预热结果不是上传门禁,不能把可读 PDF 误报为上传失败。
assert status == {
'intake_no': 'SNI-EMPTY-TABLE-STATUS', 'parse_status': 'failed', 'document_count': 1,
'error_code': 'mineru_table_structure_missing',
'intake_no': 'SNI-EMPTY-TABLE-STATUS', 'parse_status': 'parsed', 'document_count': 1,
'document_ids': [document.id], 'error_code': None,
}
def test_template_sample_status_keeps_file_materialization_failure_fail_closed(app):
"""Intake 自身解析失败仍须阻断上传;只有后台 Layout 失败可与上传解耦。"""
with app.app_context():
user = User(username='materialization-failed-admin', email='materialization-failed@example.com', role='admin')
asset = FileAsset(
asset_no='FA-MATERIALIZATION-FAILED', owner_user_id=1, original_filename='broken.eml',
storage_provider='test', storage_bucket='test', storage_key='broken.eml',
content_hash='f' * 64, file_size=1, mime_type='message/rfc822',
upload_status='ready', lifecycle_status='temporary',
)
db.session.add_all([user, asset]); db.session.flush()
asset.owner_user_id = user.id
intake = ShippingOrderIntake(
intake_no='SNI-MATERIALIZATION-FAILED', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parse_failed',
error_code='SHIPPING_NOTICE_INTAKE_PARSE_FAILED', parser_version='test',
)
db.session.add(intake); db.session.commit()
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
# 文件本身未能物化时必须保持失败,不能借上传/Layout 解耦绕过。
assert status == {
'intake_no': 'SNI-MATERIALIZATION-FAILED', 'parse_status': 'failed', 'document_count': 0,
'document_ids': [], 'error_code': 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED',
}
@@ -319,7 +358,7 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
field_region = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
assert field_region['field_id'] == 'part-field'
assert saved['definition']['contract_version'] == 'order_coordinate_profile.v2'
assert 'contract_version' not in saved['definition']
def test_order_field_layout_is_independent_from_line_layout_and_freezes_header_field(app):
@@ -622,13 +661,13 @@ def test_profile_samples_are_governed_and_audited(app, monkeypatch):
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-GOVERNANCE-SAMPLE', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='sample.pdf',
filename='sample.pdf', content_hash='s' * 64, classification='supporting', parse_status='parsed',
)
@@ -777,7 +816,7 @@ def test_profile_publish_rolls_back_when_sample_layout_hash_drifts(app, monkeypa
draft = service.clone_draft(published['id'], actor_id=None)
sample = _bind_ready_profile_sample(draft['id'], content_hash='d' * 64, filename='drift.pdf')
document = db.session.get(ShippingNoticeDocument, sample.document_id)
document = db.session.get(ShippingOrderDocument, sample.document_id)
document.content_hash = 'e' * 64
db.session.commit()
@@ -804,7 +843,7 @@ def test_profile_publish_rejects_corrupted_layout_checksum(app, monkeypatch):
layout_version = db.session.get(
ShippingDocumentLayoutVersion,
db.session.get(ShippingOrderDocumentProfileSample, sample.id).layout_version_id or
db.session.get(ShippingNoticeDocument, sample.document_id).current_layout_version_id,
db.session.get(ShippingOrderDocument, sample.document_id).current_layout_version_id,
)
assert layout_version is not None
payload = dict(layout_version.payload_json or {})
@@ -833,7 +872,7 @@ def test_profile_frozen_sample_survives_new_layout_version(app, monkeypatch):
published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
frozen_before = db.session.get(ShippingOrderDocumentProfileSample, sample.id)
document = db.session.get(ShippingNoticeDocument, frozen_before.document_id)
document = db.session.get(ShippingOrderDocument, frozen_before.document_id)
old_layout_version_id = frozen_before.layout_version_id
old_checksum = frozen_before.layout_payload_checksum
record_inline_layout_snapshot(document, {
@@ -883,7 +922,7 @@ def test_immutable_profile_without_frozen_sample_is_marked_missing(app):
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-LEGACY-PROFILE',
asset_id=asset.id,
user_id=user.id,
@@ -893,7 +932,7 @@ def test_immutable_profile_without_frozen_sample_is_marked_missing(app):
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
@@ -939,8 +978,8 @@ def test_published_profile_sample_intake_cannot_be_deleted(app, monkeypatch):
sample = _bind_ready_profile_sample(draft['id'])
service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
document = db.session.get(ShippingNoticeDocument, sample.document_id)
intake = db.session.get(ShippingNoticeIntake, document.intake_id)
document = db.session.get(ShippingOrderDocument, sample.document_id)
intake = db.session.get(ShippingOrderIntake, document.intake_id)
with pytest.raises(Exception) as caught:
service.delete_sample_intake(intake.intake_no, actor_id=int(intake.user_id or 0))
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED'
@@ -1207,7 +1246,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-PROFILE-SAMPLE', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v7',
)
@@ -1217,7 +1256,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
'<table><tr><th>Part Number</th><th>Vendor Item#</th><th>Qty</th></tr>'
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr></table>'
)
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='sample.pdf', filename='sample.pdf', content_hash='c' * 64,
classification='order_notice', parse_status='parsed', extracted_text='sample',
@@ -1253,13 +1292,13 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
assert samples[0]['purpose'] == 'order_document_profile_sample'
with app.app_context():
duplicate_intake = ShippingNoticeIntake(
duplicate_intake = ShippingOrderIntake(
intake_no='SNI-PROFILE-SAMPLE-DUPLICATE', asset_id=asset_id, user_id=user_id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(duplicate_intake)
db.session.flush()
duplicate = ShippingNoticeDocument(
duplicate = ShippingOrderDocument(
intake_id=duplicate_intake.id, asset_id=asset_id, document_type='attachment',
attachment_key='duplicate.pdf', filename='duplicate.pdf', content_hash='c' * 64,
classification='order_notice', parse_status='parsed', current_layout_version_id=layout_version_id,
@@ -1296,7 +1335,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
)
assert created.status_code == 201
draft = parse_api_data(created.get_json())
assert draft['definition']['contract_version'] == 'order_coordinate_profile.v2'
assert 'contract_version' not in draft['definition']
assert len(draft['structure_fingerprint']) == 64
stale = client.put(
@@ -1351,13 +1390,13 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-PREVIEW-SAMPLE', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='preview.pdf',
filename='preview.pdf', content_hash='p' * 64, classification='supporting', parse_status='parsed',
)
@@ -1481,9 +1520,6 @@ def test_preview_page_region_text_reads_only_the_admin_selected_glyphs(app, monk
def test_profile_region_preview_requires_a_bound_document(app, monkeypatch):
"""局部预览只能作用于当前模板样本,避免管理员接口被 document_id 枚举越权。"""
with app.app_context():
monkeypatch.setattr(service, 'preview_coordinate_reconstruction', lambda _data, actor_id: {
'row_count': 1, 'status': 'needs_review', 'rows': [], 'row_roles': [], 'source_row_indices': [],
})
with pytest.raises(Exception) as caught:
service.preview_profile_region(999, data={'document_id': 999}, actor_id=1)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND'
@@ -1708,7 +1744,7 @@ def test_ocr_coordinate_evidence_preserves_page_dimensions_for_auto_suggestion(a
recorded: dict[str, object] = {}
page = SimpleNamespace(page_no=1, image=object(), width=100, height=100)
line = SimpleNamespace(text='00010', bbox=SimpleNamespace(x0=10, y0=10, x1=30, y1=20))
monkeypatch.setattr(db.session, 'get', lambda model, identity: document if model is ShippingNoticeDocument else asset)
monkeypatch.setattr(db.session, 'get', lambda model, identity: document if model is ShippingOrderDocument else asset)
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'pdf')
monkeypatch.setattr('app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', lambda _content: [page])
@@ -1737,7 +1773,7 @@ def test_coordinate_evidence_recovery_prefers_native_text_and_repairs_missing_pa
model_dump=lambda **_kwargs: {'text': '1', 'source_index': 0, 'bbox': {'x0': 10, 'y0': 10, 'x1': 15, 'y1': 20}},
)
page = SimpleNamespace(page_no=1, image=object(), width=100, height=100, characters=[character])
monkeypatch.setattr(db.session, 'get', lambda model, identity: document if model is ShippingNoticeDocument else asset)
monkeypatch.setattr(db.session, 'get', lambda model, identity: document if model is ShippingOrderDocument else asset)
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'pdf')
monkeypatch.setattr('app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', lambda _content: [page])
@@ -1768,13 +1804,13 @@ def test_profile_sample_api_reports_header_contamination_but_v2_can_use_independ
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-PROFILE-CONTAMINATED', asset_id=asset.id, user_id=user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='bad.pdf', filename='bad.pdf', content_hash='d' * 64,
classification='order_notice', parse_status='parsed', extracted_text='sample',
@@ -1833,7 +1869,7 @@ def test_profile_sample_intake_is_isolated_from_shipping_business_flow(app):
db.session.commit()
created = create_order_document_profile_sample_intake(user_id=user.id, asset_no=pdf.asset_no)
intake = ShippingNoticeIntake.query.filter_by(intake_no=created['intake_no']).one()
intake = ShippingOrderIntake.query.filter_by(intake_no=created['intake_no']).one()
assert intake.purpose == 'order_document_profile_sample'
assert intake.conversation_id is None
assert intake.order_extraction_status == 'not_started'
@@ -1858,13 +1894,13 @@ def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, m
asset.owner_user_id = user.id
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake = ShippingOrderIntake(
intake_no='SNI-PROFILE-DELETE', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
document = ShippingOrderDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='delete.pdf', filename='delete.pdf', content_hash='1' * 64,
classification='supporting', parse_status='parsed',
@@ -1878,19 +1914,19 @@ def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, m
lambda *, asset_no, user_id: deleted_assets.append(asset_no),
)
service.delete_sample_intake(intake.intake_no, actor_id=user.id)
assert ShippingNoticeIntake.query.filter_by(intake_no=intake.intake_no).first() is None
assert ShippingOrderIntake.query.filter_by(intake_no=intake.intake_no).first() is None
assert deleted_assets == ['FA-PROFILE-DELETE']
asset.reference_count = 1
asset.lifecycle_status = 'referenced'
protected_intake = ShippingNoticeIntake(
protected_intake = ShippingOrderIntake(
intake_no='SNI-PROFILE-BLIND', asset_id=asset.id, user_id=user.id,
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v7',
)
db.session.add(protected_intake)
db.session.flush()
protected_document = ShippingNoticeDocument(
protected_document = ShippingOrderDocument(
intake_id=protected_intake.id, asset_id=asset.id, document_type='attachment',
attachment_key='blind.pdf', filename='blind.pdf', content_hash='2' * 64,
classification='supporting', parse_status='parsed',
@@ -1973,7 +2009,6 @@ def test_workbench_minimum_v2_definition_can_be_saved(app):
saved = service.save_draft({
'profile_code': 'WORKBENCH_V2', 'display_name': 'Workbench v2', 'schema_version_id': schema.id,
'definition': {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': [], 'optional_anchors': [], 'minimum_score': .9, 'minimum_margin': .15},
'table_regions': [{
'region_id': 'main_lines', 'page_scope': 'all_pages',
@@ -2006,7 +2041,6 @@ def test_workbench_draft_can_save_without_bound_fields(app):
saved = service.save_draft({
'profile_code': 'UNBOUND_DRAFT', 'display_name': 'Unbound draft', 'schema_version_id': schema.id,
'definition': {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': [], 'optional_anchors': [], 'minimum_score': .9, 'minimum_margin': .15},
'table_regions': [{
'region_id': 'main_lines', 'page_scope': 'all_pages',
@@ -2030,7 +2064,6 @@ def test_workbench_auto_suggested_unbound_regions_do_not_block_publish(app, monk
saved = service.save_draft({
'profile_code': 'UNBOUND_PERSIST', 'display_name': 'Unbound persist', 'schema_version_id': schema.id,
'definition': {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': [], 'optional_anchors': [], 'minimum_score': .9, 'minimum_margin': .15},
'table_regions': [{
'region_id': 'main_lines', 'page_scope': 'all_pages',
@@ -2078,33 +2111,7 @@ def test_schema_migration_unbound_regions_still_block_publish(app, monkeypatch):
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
def test_historical_v1_profile_is_read_only_runtime_compatible(app):
"""历史冻结 v1 仅允许质量回放读取,任何新草稿仍必须通过 v2 保存契约。"""
with app.app_context():
schema = _schema_version()
historical = ShippingOrderDocumentProfile(
profile_code='HISTORICAL_V1', display_name='Historical v1', version=1, status='published',
schema_version_id=schema.id, structure_fingerprint='a' * 64, checksum='a' * 64,
definition_json={
'contract_version': 'shipping_order_document_profile.v1',
'structure_fingerprint': 'a' * 64, 'header_row_index': 0, 'data_start_row_index': 1,
'row_structure': 'preserved', 'drop_zero_qty': True, 'column_rules': [{
'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['part_number'],
}],
}, published_at=datetime.utcnow(),
)
db.session.add(historical)
db.session.commit()
assert service._definition_contract(historical).contract_version == 'shipping_order_document_profile.v1'
with pytest.raises(Exception) as caught:
service.save_draft({
'profile_code': 'NEW_V1_REJECT', 'display_name': 'New v1 reject', 'schema_version_id': schema.id,
'definition': dict(historical.definition_json),
}, actor_id=None)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
def test_coordinate_preview_reports_four_source_rows(app, monkeypatch):
def test_coordinate_preview_reports_four_source_rows_removed(app, monkeypatch):
"""四行物理版式在管理端预览中必须合并为一条逻辑明细并保留全部来源行。"""
def characters(*rows: list[tuple[str, float]]) -> list[dict]:
"""构造四条相互分离的坐标文本行,模拟持久化原生 PDF 字符证据。"""
@@ -2142,27 +2149,6 @@ def test_coordinate_preview_reports_four_source_rows(app, monkeypatch):
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 101 else None)
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
with app.app_context():
preview = service.preview_coordinate_reconstruction({
'document_id': 101,
'table_id': 'four-row',
'coordinate_reconstruction': {'subrow_layouts': [
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
'column_field_codes': [None, 'customer_part_number']},
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
'column_field_codes': [None, 'required_date']},
{'role': 'continuation', 'row_offset': 3, 'column_boundaries': [0, 0.5, 1],
'column_field_codes': [None, 'part_number']},
]},
}, actor_id=None)
assert preview['row_count'] == 2
assert preview['row_roles'] == ['header', 'data']
assert preview['source_row_indices'] == [[], [0, 1, 2, 3]]
def test_coordinate_suggestion_returns_reviewable_dynamic_rows(app, monkeypatch):
"""建议接口只返回相对边界和示例,并自动标出首行 customer_po_line_no。"""
characters = []
@@ -17,10 +17,10 @@ from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingAuditEvent,
ShippingNoticeDocument,
ShippingOrderExtractionPlan,
ShippingOrderDocument,
ShippingOrderProcessingPlan,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionUnit,
ShippingOrderProcessingUnit,
User,
)
from app.services.shipping_notice.order_extraction_cancel_service import (
@@ -33,9 +33,9 @@ from app.services.shipping_notice.order_extraction_workspace_projection import s
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _attach_units(run, *, statuses: list[str], document_ids: list[int] | None = None) -> list[ShippingOrderExtractionUnit]:
def _attach_units(run, *, statuses: list[str], document_ids: list[int] | None = None) -> list[ShippingOrderProcessingUnit]:
"""为测试 Run 物化计划与给定状态的 Unit。"""
plan = ShippingOrderExtractionPlan(
plan = ShippingOrderProcessingPlan(
run_id=run.id,
plan_version='shipping_order_extraction.plan.v1',
input_snapshot_hash=run.input_snapshot_hash,
@@ -44,11 +44,11 @@ def _attach_units(run, *, statuses: list[str], document_ids: list[int] | None =
)
db.session.add(plan)
db.session.flush()
units: list[ShippingOrderExtractionUnit] = []
units: list[ShippingOrderProcessingUnit] = []
intake_id = int(run.intakes[0].intake_id)
for index, status in enumerate(statuses):
document_id = int(document_ids[index]) if document_ids and index < len(document_ids) else index + 1
unit = ShippingOrderExtractionUnit(
unit = ShippingOrderProcessingUnit(
plan_id=plan.id,
intake_id=intake_id,
document_id=document_id,
@@ -97,7 +97,7 @@ def test_cancel_inflight_unit_requests_then_worker_checkpoint_completes(app):
"""执行中取消先进入正在取消,Worker 检查点后才生效并保留已完成 PDF。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-INFLIGHT')
second = ShippingNoticeDocument(
second = ShippingOrderDocument(
intake_id=intake.id,
asset_id=document.asset_id,
document_type='attachment',
@@ -108,7 +108,7 @@ def test_cancel_inflight_unit_requests_then_worker_checkpoint_completes(app):
parse_status='parsed',
extracted_text='PO 2 QTY 1',
)
third = ShippingNoticeDocument(
third = ShippingOrderDocument(
intake_id=intake.id,
asset_id=document.asset_id,
document_type='attachment',
@@ -167,12 +167,12 @@ def test_admin_cancel_other_user_run_requires_reason(app):
admin = User(username='cancel-admin', email='cancel-admin@example.com', password_hash='x', role='admin')
db.session.add(admin)
db.session.flush()
from app.models import ShippingOrderExtractionRun, ShippingOrderExtractionRunIntake
from app.models import ShippingOrderProcessingRun, ShippingOrderProcessingRunIntake
from app.models import ShippingOrderSchemaVersion
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
assert schema_version is not None
run = ShippingOrderExtractionRun(
run = ShippingOrderProcessingRun(
run_no=f'SNER-CANCEL-ADMIN-{user.id}',
user_id=user.id,
owner_agent_id=agent.id,
@@ -186,7 +186,7 @@ def test_admin_cancel_other_user_run_requires_reason(app):
)
db.session.add(run)
db.session.flush()
db.session.add(ShippingOrderExtractionRunIntake(run_id=run.id, intake_id=intake.id, position=0))
db.session.add(ShippingOrderProcessingRunIntake(run_id=run.id, intake_id=intake.id, position=0))
_attach_units(run, statuses=['pending'], document_ids=[document.id])
db.session.commit()
@@ -195,7 +195,7 @@ def test_admin_cancel_other_user_run_requires_reason(app):
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED'
db.session.rollback()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
admin = db.session.get(User, admin.id)
cancel_order_extraction_run(actor=admin, run_no=run.run_no, reason='积压清理')
db.session.commit()
@@ -0,0 +1,95 @@
"""
backend/tests/test_shipping_order_extraction_concurrency.py
用途:验收同会话连续多 Intake 提交各自独立 Run(P0-02 裁决边界)。
依赖:Flask/SQLite、submit_order_extraction。
逻辑:不同 Intake 不得并入同一 Run;连续提交应产生多活跃 Run。
"""
from __future__ import annotations
from app import db
from app.models import ShippingOrderProcessingRun, ShippingOrderProcessingRunIntake
from app.services.shipping_notice.order_extraction_run_service import (
create_order_extraction_run,
submit_order_extraction,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
def test_sequential_submits_create_independent_runs_per_intake(app):
"""
两次不同 Intake 提交各自新建 Run,不得跨 Intake 追加到同一 OT。
断言:decision=created;会话内共 3 个 Run;每个 Run 仅绑定 1 个 Intake。
"""
with app.app_context():
user, agent, session, intake, _ = _seed_run_input(suffix='CONC-A')
first, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
composer_context_id='CMP-CONC',
)
db.session.commit()
_, _, _, intake_b, _ = _seed_run_input(
suffix='CONC-B',
agent_code='shipping_notice_conc_b',
)
intake_b.user_id = user.id
intake_b.conversation_id = session.session_id
intake_b.upload_batch_id = intake.upload_batch_id
_, _, _, intake_c, _ = _seed_run_input(
suffix='CONC-C',
agent_code='shipping_notice_conc_c',
)
intake_c.user_id = user.id
intake_c.conversation_id = session.session_id
intake_c.upload_batch_id = intake.upload_batch_id
db.session.commit()
payload_b = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_b.intake_no],
submission_id='SUB-CONC-B',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-CONC',
)
db.session.commit()
payload_c = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_c.intake_no],
submission_id='SUB-CONC-C',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-CONC',
)
db.session.commit()
assert payload_b['decision'] == 'created'
assert payload_c['decision'] == 'created'
assert payload_b['reason_code'] == 'adjudication_unit_boundary'
assert payload_c['reason_code'] == 'adjudication_unit_boundary'
assert payload_b['run_no'] != first.run_no
assert payload_c['run_no'] != first.run_no
assert payload_b['run_no'] != payload_c['run_no']
assert ShippingOrderProcessingRun.query.filter_by(
conversation_id=session.session_id,
).count() == 3
for run_no in (first.run_no, payload_b['run_no'], payload_c['run_no']):
bound = {
int(row.intake_id)
for row in ShippingOrderProcessingRunIntake.query.join(
ShippingOrderProcessingRun
).filter(
ShippingOrderProcessingRun.run_no == run_no,
ShippingOrderProcessingRunIntake.released_at.is_(None),
).all()
}
assert len(bound) == 1
@@ -239,7 +239,9 @@ def test_guide_keeps_review_and_chat_capabilities_isolated():
assert '`agent_code=shipping_notice` 唯一 Chatflow' in source
assert 'ROUTE_DETECT_MODE.mode == "review"' in source
assert '复核分支不使用 Conversation History、Memory、Knowledge、Tool、HTTP、Agent' in source
assert '`get_task_status` 和 `get_batch_status`' in source
assert '`get_task_status`' in source
# OpenAPI 已下线 get_batch_status;手册 checklist 须标明只读 Tool 仅剩 get_task_status。
assert '只能看到 `get_task_status`' in source
assert 'Dify 不输出 `orders`' in source
assert '不自动冻结' in source
@@ -5,7 +5,7 @@ from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import ShippingOrderExtractionProgressEvent, ShippingOrderExtractionRun, User
from app.models import ShippingOrderExtractionProgressEvent, ShippingOrderProcessingRun, User
from app.services.shipping_notice.order_extraction_progress import MAPPING_VERSION, record_order_extraction_progress_event
from app.services.shipping_notice.order_extraction_run_service import (
cleanup_expired_order_extraction_progress_events,
@@ -17,9 +17,9 @@ from app.services.shipping_notice.order_extraction_progress_cleanup_schedule imp
)
def _run() -> ShippingOrderExtractionRun:
def _run() -> ShippingOrderProcessingRun:
"""创建不依赖订单输入的最小Run,专门验证进度投影。"""
row = ShippingOrderExtractionRun(
row = ShippingOrderProcessingRun(
run_no='SNER-PROGRESS', user_id=1, owner_agent_id=1, conversation_id='progress-conv',
schema_version_id=1, input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
status='processing', phase='deterministic_parsing',
@@ -50,7 +50,7 @@ def test_progress_events_dedupe_sequence_and_protect_terminal_run(app):
event={'event_code': 'profile_matched', 'unit_id': 7, 'document_id': 11, 'summary': {'profile_code': 'vendor_a'}},
) is False
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
assert run.current_stage_code == 'profile_matched'
assert list(run.active_stage_codes_json or []) == ['profile_matched']
@@ -59,7 +59,7 @@ def test_progress_events_dedupe_sequence_and_protect_terminal_run(app):
event={'event_code': 'candidate_ready', 'unit_id': 7, 'document_id': 11},
) is True
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
assert run.current_stage_code == 'candidate_ready'
run.status = 'completed'
@@ -70,7 +70,7 @@ def test_progress_events_dedupe_sequence_and_protect_terminal_run(app):
event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12},
) is False
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
assert run.current_stage_code == 'candidate_ready'
assert ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).count() == 4
@@ -84,7 +84,7 @@ def test_progress_mapping_version_fits_persisted_column(app):
event={'event_code': 'document_queued', 'document_id': 11},
) is True
db.session.expire_all()
persisted = db.session.get(ShippingOrderExtractionRun, run.id)
persisted = db.session.get(ShippingOrderProcessingRun, run.id)
assert len(MAPPING_VERSION) <= 32
assert persisted.progress_mapping_version == MAPPING_VERSION
@@ -103,7 +103,7 @@ def test_progress_event_accepts_email_supplement_merge_summary(app):
},
) is True
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one()
assert run.current_stage_code == 'email_supplement_merged'
assert list(run.active_stage_codes_json or []) == ['email_supplement_merged']
@@ -144,7 +144,7 @@ def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app):
},
) is True
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).order_by(
ShippingOrderExtractionProgressEvent.sequence_no.asc(),
).all()
@@ -195,7 +195,7 @@ def test_terminal_run_rejects_late_workspace_event_without_mutating_projection(a
event={'event_code': 'profile_matching', 'unit_id': 8, 'document_id': 12},
) is False
db.session.expire_all()
run = db.session.get(ShippingOrderExtractionRun, run.id)
run = db.session.get(ShippingOrderProcessingRun, run.id)
assert run.status == 'completed'
assert run.current_stage_code == 'candidate_ready'
assert run.progress_version == 9
@@ -218,7 +218,7 @@ def test_progress_cleanup_deletes_only_expired_events_and_keeps_run(app):
db.session.commit()
assert cleanup_expired_order_extraction_progress_events(now=now) == {'deleted_count': 1}
assert db.session.get(ShippingOrderExtractionRun, run.id) is not None
assert db.session.get(ShippingOrderProcessingRun, run.id) is not None
assert ShippingOrderExtractionProgressEvent.query.filter_by(id=retained.id).one() is not None
@@ -228,7 +228,7 @@ def test_user_slow_threshold_uses_p95_after_minimum_samples_and_is_capped(app):
assert get_order_extraction_user_slow_threshold_seconds() == 180
base = datetime.utcnow() - timedelta(minutes=10)
for index in range(20):
run = ShippingOrderExtractionRun(
run = ShippingOrderProcessingRun(
run_no=f'SNER-SLOW-{index}', user_id=1, owner_agent_id=1, conversation_id=f'slow-{index}',
schema_version_id=1, input_snapshot_hash=f'{index:064x}', input_snapshot_json={}, idempotency_key=f'{index + 100:064x}',
status='completed', phase='completed', created_at=base, finished_at=base + timedelta(seconds=400 if index >= 18 else 90),
@@ -1,7 +1,7 @@
"""Verify order extraction quality batches without runtime bindings."""
from app import db
from app.models import ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityLabel, ShippingOrderExtractionRun, User
from app.models import ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityLabel, ShippingOrderProcessingRun, User
from app.services.shipping_notice.order_extraction_quality_service import quality_metrics, save_quality_label
from tests.test_shipping_order_extraction_runs import _seed_run_input
@@ -17,7 +17,7 @@ def test_quality_metrics_require_two_matching_reviews(app):
batch_no='SOQ-QUALITY-METRICS', owner_agent_id=owner.id, schema_version_id=1,
threshold_version='l7.v1', status='collecting', created_by_id=user.id,
)
run = ShippingOrderExtractionRun(
run = ShippingOrderProcessingRun(
run_no='SNER-QUALITY-METRICS', user_id=user.id, owner_agent_id=owner.id,
conversation_id=session.session_id, schema_version_id=1,
input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
@@ -45,7 +45,7 @@ def test_quality_label_rejects_auto_creation_run(app):
batch_no='SOQ-QUALITY-INVALID', owner_agent_id=owner.id, schema_version_id=1,
threshold_version='l7.v1', status='collecting', created_by_id=user.id,
)
run = ShippingOrderExtractionRun(
run = ShippingOrderProcessingRun(
run_no='SNER-QUALITY-INVALID', user_id=user.id, owner_agent_id=owner.id,
conversation_id=session.session_id, schema_version_id=1,
input_snapshot_hash='c' * 64, input_snapshot_json={}, idempotency_key='d' * 64,
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,861 @@
"""
backend/tests/test_shipping_order_extraction_submission.py
用途:验证会话多任务统一提交:queued 可追加、冻结后新建、submission_id 幂等、processing 投影。
依赖:Flask/SQLite 夹具、create_order_extraction_run / submit_order_extraction、evaluate_can_append。
逻辑:复用 test_shipping_order_extraction_runs 的 _seed_run_input;覆盖阶段 1 追加裁决契约。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import ShippingOrderProcessingRun
from app.services.shipping_notice.order_extraction_run_service import (
create_order_extraction_run,
evaluate_can_append,
submit_order_extraction,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
def test_evaluate_can_append_only_when_queued_and_open(app):
"""仅 queued + input_lifecycle=open 且未冻结时可追加。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='APPEND-EVAL')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
ok, reason = evaluate_can_append(run)
assert ok is True
assert reason is None
run.input_lifecycle = 'frozen'
run.input_frozen_at = datetime.utcnow()
db.session.commit()
ok, reason = evaluate_can_append(run)
assert ok is False
assert reason == 'input_already_frozen'
def test_submit_appends_to_open_queued_run(app):
"""同会话第二次提交不同 Intake 时,因裁决边界须新建 Run(不再跨 Intake 追加)。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-APP')
first, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
assert first.user_task_no is None
assert evaluate_can_append(first)[0] is True
_, _, _, second_intake, _ = _seed_run_input(
suffix='SUB-APP-2',
agent_code='shipping_notice_sub_app_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
second_intake.upload_batch_id = intake.upload_batch_id
db.session.commit()
from app.services.shipping_notice.order_extraction_run_service import _effective_user_task_no
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-TEST-APPEND-1',
upload_batch_id=intake.upload_batch_id,
focused_user_task_no=_effective_user_task_no(first),
)
db.session.commit()
# 断言:不同 Intake 不得并入同一 Run;须新建 Run(Candidate 前无右侧 OT 卡)。
assert payload['decision'] == 'created'
assert payload['created_new'] is True
assert payload['run_no'] != first.run_no
assert payload['reason_code'] == 'adjudication_unit_boundary'
assert ShippingOrderProcessingRun.query.count() == 2
assert payload['user_task_no'] is None
assert payload['processing']['summary']['total_tasks'] == 0
def test_submit_creates_when_input_frozen(app):
"""输入已冻结时新建用户可见任务,允许同会话并行活跃 Run。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-NEW')
first, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
first.input_lifecycle = 'frozen'
first.input_frozen_at = datetime.utcnow()
db.session.commit()
_, _, _, second_intake, _ = _seed_run_input(
suffix='SUB-NEW-2',
agent_code='shipping_notice_sub_new_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-TEST-CREATE-1',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['created_new'] is True
assert payload['run_no'] != first.run_no
assert ShippingOrderProcessingRun.query.count() == 2
# Candidate 前会话右侧不展示伪 OT。
assert payload['user_task_no'] is None
assert payload['processing']['summary']['total_tasks'] == 0
def test_submit_idempotent_by_submission_id(app):
"""相同 submission_id 重放返回同一决策,不新增 Run。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-IDEM')
payload1 = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-TEST-IDEM-1',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
payload2 = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-TEST-IDEM-1',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
assert payload2['reused'] is True
assert payload2['reason_code'] == 'submission_idempotent_replay'
assert payload2['run_no'] == payload1['run_no']
assert payload2['user_task_no'] == payload1['user_task_no']
assert ShippingOrderProcessingRun.query.count() == 1
def test_legacy_create_can_still_block_parallel_when_flag_false(app):
"""兼容路径 allow_parallel_conversation_runs=False 仍抛 CONVERSATION_ACTIVE。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='LEGACY-PAR')
_, _, _, second_intake, _ = _seed_run_input(
suffix='LEGACY-PAR-2',
agent_code='shipping_notice_legacy_par_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
db.session.commit()
create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
allow_parallel_conversation_runs=False,
)
db.session.commit()
from app.core.errors import ConflictError
with pytest.raises(ConflictError) as caught:
create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
allow_parallel_conversation_runs=False,
)
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_ACTIVE'
def test_old_submission_id_survives_later_append(app):
"""BE-F01:追加后重放更早的 submission_id 仍命中原决策,不被覆盖。"""
with app.app_context():
from app.models import ShippingOrderExtractionSubmission
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-REPLAY')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-REPLAY-A',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-REPLAY',
)
db.session.commit()
_, _, _, second_intake, _ = _seed_run_input(
suffix='SUB-REPLAY-2',
agent_code='shipping_notice_sub_replay_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
second_intake.upload_batch_id = intake.upload_batch_id
db.session.commit()
second = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-REPLAY-B',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-REPLAY',
)
db.session.commit()
assert second['decision'] == 'created'
assert second['run_no'] != first['run_no']
replay = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-REPLAY-A',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
assert replay['reason_code'] == 'submission_idempotent_replay'
assert replay['decision'] == 'created'
assert replay['user_task_no'] == first['user_task_no']
assert ShippingOrderExtractionSubmission.query.filter_by(
user_id=user.id,
submission_id='SUB-REPLAY-A',
).count() == 1
assert replay['run_no'] == first['run_no']
assert ShippingOrderExtractionSubmission.query.filter_by(
user_id=user.id,
).count() == 2
assert ShippingOrderProcessingRun.query.count() == 2
def test_submit_without_context_creates_new_task(app):
"""BE-F04:缺少 composer/焦点且附件指纹不同时,不得退化追加到会话最近 open Run。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-NOCTX')
first, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
_, _, _, second_intake, _ = _seed_run_input(
suffix='SUB-NOCTX-2',
agent_code='shipping_notice_sub_noctx_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-NOCTX-NEW',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['run_no'] != first.run_no
assert ShippingOrderProcessingRun.query.count() == 2
def test_failed_same_attachment_reupload_inherits_user_task(app):
"""BE-02:失败后普通入口重传相同 PDF,继承原 OT 并新建当前有效 Run。"""
with app.app_context():
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
from datetime import timedelta
user, agent, session, intake, document = _seed_run_input(suffix='SUB-FAIL-REUSE')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-FAIL-REUSE-A',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
run = ShippingOrderProcessingRun.query.filter_by(run_no=first['run_no']).one()
run.status = 'failed'
run.phase = 'failed'
run.input_lifecycle = 'frozen'
run.input_frozen_at = datetime.utcnow()
db.session.commit()
second_asset = FileAsset(
asset_no='FA-SUB-FAIL-REUSE-2', owner_user_id=user.id,
original_filename=str(document.filename or 'fail-reuse.pdf'),
storage_provider='minio', storage_bucket='test',
storage_key=f'temporary/{user.id}/fail-reuse-2.pdf',
content_hash=db.session.get(FileAsset, intake.asset_id).content_hash,
file_size=100, mime_type='application/pdf', upload_status='ready', lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingOrderIntake(
intake_no='SNI-SUB-FAIL-REUSE-2', asset_id=second_asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='fail-reuse-batch-2',
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
extracted_text='same failed attachment', expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=second_intake.id, asset_id=second_asset.id, document_type='attachment',
attachment_key=str(document.attachment_key or 'fail-reuse.pdf'),
filename=str(document.filename or 'fail-reuse.pdf'),
content_hash=document.content_hash, classification='order_notice',
parse_status='parsed', extracted_text=document.extracted_text,
))
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-FAIL-REUSE-B',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
assert payload['decision'] == 'created'
# Candidate 前两侧均为 NULL;有真实 OT 后才继承同一 user_task_no。
assert payload['user_task_no'] is None
assert first['user_task_no'] is None
assert payload['run_no'] != first['run_no']
assert ShippingOrderProcessingRun.query.count() == 2
old_run = ShippingOrderProcessingRun.query.filter_by(run_no=first['run_no']).one()
new_run = ShippingOrderProcessingRun.query.filter_by(run_no=payload['run_no']).one()
# [BE-01] 普通重传必须建立正式版本谱系,不能只靠 UI 时间排序隐藏旧卡。
assert new_run.reparse_of_run_id == old_run.id
assert old_run.superseded_by_run_id == new_run.id
assert old_run.superseded_at is not None
assert payload['processing']['summary']['total_tasks'] == 0
def test_appended_projection_does_not_mark_recently_created(app):
"""跨 Intake 新建 Run 时 Candidate 前无右侧 OT 卡;仅断言裁决与 Run 边界。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='SUB-BADGE')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-BADGE-A',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-BADGE',
)
db.session.commit()
_, _, _, second_intake, _ = _seed_run_input(
suffix='SUB-BADGE-2',
agent_code='shipping_notice_sub_badge_2',
)
second_intake.user_id = user.id
second_intake.conversation_id = session.session_id
second_intake.upload_batch_id = intake.upload_batch_id
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-BADGE-B',
upload_batch_id=intake.upload_batch_id,
composer_context_id='CMP-BADGE',
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['run_no'] != first['run_no']
assert payload['user_task_no'] is None
assert first['user_task_no'] is None
assert payload['processing']['summary']['total_tasks'] == 0
assert ShippingOrderProcessingRun.query.count() == 2
def test_prior_user_task_ignores_schema_version(app):
"""BE-01:身份查找不按 schema_version_id 切断同一 PDF。"""
with app.app_context():
from app.services.shipping_notice.order_extraction_run_service import (
_prior_user_task_for_business_attachments,
)
user, agent, session, intake, _ = _seed_run_input(suffix='SUB-SCHEMA')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
snapshot = (
run.request_snapshot_json
if isinstance(run.request_snapshot_json, dict)
else run.input_snapshot_json
)
prior = _prior_user_task_for_business_attachments(
user_id=user.id,
owner_agent_id=agent.id,
conversation_id=session.session_id,
schema_version_id=-1,
snapshot=snapshot if isinstance(snapshot, dict) else {},
)
assert prior is not None
assert prior.user_task_no == run.user_task_no
assert prior.id == run.id
def test_ordinary_resubmit_freezes_prior_candidates_and_restores_on_failure(app):
"""BE-02:普通重传冻结旧 Candidate;新版失败后恢复旧当前版本资格。"""
with app.app_context():
from datetime import timedelta
from app.models import FileAsset, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake
from app.services.shipping_notice.order_extraction_run_service import (
transition_order_extraction_run,
)
user, agent, session, intake, document = _seed_run_input(suffix='SUB-CAND-FREEZE')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-CAND-FREEZE-A',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
old_run = ShippingOrderProcessingRun.query.filter_by(run_no=first['run_no']).one()
old_run.status = 'failed'
old_run.phase = 'failed'
old_run.input_lifecycle = 'frozen'
old_run.input_frozen_at = datetime.utcnow()
candidate = ShippingOrderCandidate(
candidate_no='SNC-SUB-CAND-FREEZE',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='ordinary-resubmit-freeze',
order_extraction_run_id=old_run.id,
selected=True,
candidate_status='accepted',
is_current_version=True,
validation_status='ready',
)
db.session.add(candidate)
db.session.commit()
second_asset = FileAsset(
asset_no='FA-SUB-CAND-FREEZE-2', owner_user_id=user.id,
original_filename=str(document.filename or 'cand-freeze.pdf'),
storage_provider='minio', storage_bucket='test',
storage_key=f'temporary/{user.id}/cand-freeze-2.pdf',
content_hash=db.session.get(FileAsset, intake.asset_id).content_hash,
file_size=100, mime_type='application/pdf', upload_status='ready', lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingOrderIntake(
intake_no='SNI-SUB-CAND-FREEZE-2', asset_id=second_asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='cand-freeze-batch-2',
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
extracted_text='same attachment for candidate freeze', expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=second_intake.id, asset_id=second_asset.id, document_type='attachment',
attachment_key=str(document.attachment_key or 'cand-freeze.pdf'),
filename=str(document.filename or 'cand-freeze.pdf'),
content_hash=document.content_hash, classification='order_notice',
parse_status='parsed', extracted_text=document.extracted_text,
))
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-CAND-FREEZE-B',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
new_run = ShippingOrderProcessingRun.query.filter_by(run_no=payload['run_no']).one()
db.session.refresh(candidate)
db.session.refresh(old_run)
assert candidate.is_current_version is False
assert candidate.selected is False
assert candidate.candidate_status == 'expired'
assert old_run.superseded_by_run_id == new_run.id
transition_order_extraction_run(new_run, target_status='processing')
transition_order_extraction_run(new_run, target_status='failed', error_message='provider unavailable')
db.session.flush()
db.session.refresh(candidate)
db.session.refresh(old_run)
assert candidate.is_current_version is True
assert candidate.selected is True
assert candidate.candidate_status == 'accepted'
assert old_run.superseded_by_run_id is None
def test_ordinary_resubmit_cancel_restores_prior_candidates(app):
"""BE-01:新版取消后必须恢复旧 Run/Candidate,不得让任务失去当前结果。"""
with app.app_context():
from datetime import timedelta
from app.models import (
FileAsset,
ShippingAuditEvent,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
)
from app.services.shipping_notice.order_extraction_run_service import (
transition_order_extraction_run,
)
user, agent, session, intake, document = _seed_run_input(suffix='SUB-CAND-CANCEL')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-CAND-CANCEL-A',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
old_run = ShippingOrderProcessingRun.query.filter_by(run_no=first['run_no']).one()
old_run.status = 'failed'
old_run.phase = 'failed'
old_run.input_lifecycle = 'frozen'
old_run.input_frozen_at = datetime.utcnow()
candidate = ShippingOrderCandidate(
candidate_no='SNC-SUB-CAND-CANCEL',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='ordinary-resubmit-cancel',
order_extraction_run_id=old_run.id,
selected=True,
candidate_status='accepted',
is_current_version=True,
validation_status='ready',
)
db.session.add(candidate)
db.session.commit()
second_asset = FileAsset(
asset_no='FA-SUB-CAND-CANCEL-2', owner_user_id=user.id,
original_filename=str(document.filename or 'cand-cancel.pdf'),
storage_provider='minio', storage_bucket='test',
storage_key=f'temporary/{user.id}/cand-cancel-2.pdf',
content_hash=db.session.get(FileAsset, intake.asset_id).content_hash,
file_size=100, mime_type='application/pdf', upload_status='ready', lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingOrderIntake(
intake_no='SNI-SUB-CAND-CANCEL-2', asset_id=second_asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='cand-cancel-batch-2',
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
extracted_text='same attachment for cancel restore', expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=second_intake.id, asset_id=second_asset.id, document_type='attachment',
attachment_key=str(document.attachment_key or 'cand-cancel.pdf'),
filename=str(document.filename or 'cand-cancel.pdf'),
content_hash=document.content_hash, classification='order_notice',
parse_status='parsed', extracted_text=document.extracted_text,
))
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-CAND-CANCEL-B',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
assert payload['decision'] == 'created'
assert payload['run_no'] != first['run_no']
new_run = ShippingOrderProcessingRun.query.filter_by(run_no=payload['run_no']).one()
db.session.refresh(old_run)
# [BE-02] 版本替代审计必须可回放 source/replacement 与 Candidate 快照。
replaced = (
ShippingAuditEvent.query.filter_by(
event_type='conversation_processing_task_version_replaced',
run_no=new_run.run_no,
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert replaced is not None
before = (
replaced.before_snapshot_json
if isinstance(replaced.before_snapshot_json, dict)
else {}
)
after = (
replaced.after_snapshot_json
if isinstance(replaced.after_snapshot_json, dict)
else {}
)
meta = replaced.metadata_json if isinstance(replaced.metadata_json, dict) else {}
assert before.get('source_run_no') == old_run.run_no
assert old_run.run_no in (before.get('source_run_nos') or [])
assert isinstance(before.get('candidate_snapshots'), list)
assert any(
int(row.get('candidate_id') or 0) == int(candidate.id)
for row in (before.get('candidate_snapshots') or [])
if isinstance(row, dict)
)
assert after.get('replacement_run_no') == new_run.run_no
assert meta.get('replacement_reason') == 'same_attachment_resubmit'
assert meta.get('source_run_no') == old_run.run_no
assert meta.get('replacement_run_no') == new_run.run_no
assert str(replaced.reason_code or '') == 'same_attachment_resubmit'
assert str(replaced.actor_id or '') == str(user.id)
assert replaced.operation_id
assert replaced.before_hash
assert replaced.after_hash
db.session.refresh(candidate)
assert candidate.is_current_version is False
assert old_run.superseded_by_run_id == new_run.id
transition_order_extraction_run(new_run, target_status='processing')
transition_order_extraction_run(new_run, target_status='cancelled')
db.session.flush()
db.session.refresh(candidate)
db.session.refresh(old_run)
assert candidate.is_current_version is True
assert candidate.selected is True
assert candidate.candidate_status == 'accepted'
assert old_run.superseded_by_run_id is None
# [BE-01] 版本恢复必须有独立审计,可回放旧 Run/Candidate 前后快照。
restored = (
ShippingAuditEvent.query.filter_by(
event_type='conversation_processing_task_version_restored',
run_no=new_run.run_no,
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert restored is not None
restore_before = (
restored.before_snapshot_json
if isinstance(restored.before_snapshot_json, dict)
else {}
)
restore_after = (
restored.after_snapshot_json
if isinstance(restored.after_snapshot_json, dict)
else {}
)
restore_meta = restored.metadata_json if isinstance(restored.metadata_json, dict) else {}
assert restore_before.get('successor_run_no') == new_run.run_no
assert old_run.run_no in (restore_before.get('source_run_nos') or [])
assert any(
int(row.get('candidate_id') or 0) == int(candidate.id)
and row.get('is_current_version') is False
for row in (restore_before.get('candidate_snapshots') or [])
if isinstance(row, dict)
)
assert restore_after.get('restored_run_no') == old_run.run_no
assert any(
int(row.get('candidate_id') or 0) == int(candidate.id)
and row.get('is_current_version') is True
for row in (restore_after.get('candidate_snapshots') or [])
if isinstance(row, dict)
)
assert str(restored.reason_code or '') == 'successor_cancelled'
assert restore_meta.get('replacement_reason') == 'successor_cancelled'
# [BE-01] 执行恢复的是 system/worker,属主与触发方分字段,禁止 actor_id=user_id。
assert restored.actor_type in {'system', 'worker'}
assert str(restored.actor_id or '') != str(user.id)
assert int(restored.owner_user_id or 0) == int(user.id)
assert restore_meta.get('initiated_by_actor_type') in {'user', 'admin', 'system', 'worker'}
# 直接 transition 取消未写 cancellation_actor_* 时,不得回填业务属主为发起人。
assert str(restore_meta.get('initiated_by_actor_id') or '') != str(user.id)
assert int(restore_meta.get('owner_user_id') or 0) == int(user.id)
# [BE-02] Run 谱系前后快照须含 superseded_by_run_id(恢复前非空 → 恢复后 null)。
before_run_snaps = restore_before.get('source_run_snapshots') or []
after_run_snaps = restore_after.get('source_run_snapshots') or []
assert any(
row.get('source_run_no') == old_run.run_no
and int(row.get('superseded_by_run_id') or 0) == int(new_run.id)
for row in before_run_snaps
if isinstance(row, dict)
)
assert any(
row.get('source_run_no') == old_run.run_no
and row.get('superseded_by_run_id') is None
for row in after_run_snaps
if isinstance(row, dict)
)
assert restored.operation_id
assert restored.before_hash
assert restored.after_hash
def test_admin_cancel_restore_audit_uses_cancellation_actor(app):
"""BE-01:管理员代取消时,恢复审计发起人必须是 admin,不得回填业务属主。"""
with app.app_context():
from datetime import timedelta
from app.models import (
FileAsset,
ShippingAuditEvent,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
User,
)
from app.services.shipping_notice.order_extraction_run_service import (
transition_order_extraction_run,
)
user, agent, session, intake, document = _seed_run_input(suffix='SUB-ADMIN-CANCEL')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-ADMIN-CANCEL-A',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
old_run = ShippingOrderProcessingRun.query.filter_by(run_no=first['run_no']).one()
old_run.status = 'failed'
old_run.phase = 'failed'
old_run.input_lifecycle = 'frozen'
old_run.input_frozen_at = datetime.utcnow()
candidate = ShippingOrderCandidate(
candidate_no='SNC-SUB-ADMIN-CANCEL',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='ordinary-resubmit-admin-cancel',
order_extraction_run_id=old_run.id,
selected=True,
candidate_status='accepted',
is_current_version=True,
validation_status='ready',
)
db.session.add(candidate)
db.session.commit()
second_asset = FileAsset(
asset_no='FA-SUB-ADMIN-CANCEL-2', owner_user_id=user.id,
original_filename=str(document.filename or 'admin-cancel.pdf'),
storage_provider='minio', storage_bucket='test',
storage_key=f'temporary/{user.id}/admin-cancel-2.pdf',
content_hash=db.session.get(FileAsset, intake.asset_id).content_hash,
file_size=100, mime_type='application/pdf', upload_status='ready', lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingOrderIntake(
intake_no='SNI-SUB-ADMIN-CANCEL-2', asset_id=second_asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='admin-cancel-batch-2',
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
extracted_text='same attachment for admin cancel restore',
expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=second_intake.id, asset_id=second_asset.id, document_type='attachment',
attachment_key=str(document.attachment_key or 'admin-cancel.pdf'),
filename=str(document.filename or 'admin-cancel.pdf'),
content_hash=document.content_hash, classification='order_notice',
parse_status='parsed', extracted_text=document.extracted_text,
))
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[second_intake.intake_no],
submission_id='SUB-ADMIN-CANCEL-B',
upload_batch_id=second_intake.upload_batch_id,
)
db.session.commit()
new_run = ShippingOrderProcessingRun.query.filter_by(run_no=payload['run_no']).one()
admin = User(
username='restore-audit-admin',
email='restore-audit-admin@example.com',
password_hash='x',
role='admin',
)
db.session.add(admin)
db.session.flush()
admin_id = str(admin.id)
transition_order_extraction_run(new_run, target_status='processing')
new_run.cancellation_actor_type = 'admin'
new_run.cancellation_actor_id = admin_id
transition_order_extraction_run(new_run, target_status='cancelled')
db.session.flush()
restored = (
ShippingAuditEvent.query.filter_by(
event_type='conversation_processing_task_version_restored',
run_no=new_run.run_no,
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert restored is not None
restore_meta = restored.metadata_json if isinstance(restored.metadata_json, dict) else {}
assert int(restored.owner_user_id or 0) == int(user.id)
assert restore_meta.get('initiated_by_actor_type') == 'admin'
assert str(restore_meta.get('initiated_by_actor_id') or '') == admin_id
assert str(restore_meta.get('initiated_by_actor_id') or '') != str(user.id)
@@ -29,7 +29,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
monkeypatch.setattr(
handler,
'ShippingOrderExtractionRun',
'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
@@ -38,7 +38,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
)
monkeypatch.setattr(
handler,
'ShippingOrderExtractionUnit',
'ShippingOrderProcessingUnit',
SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
@@ -56,7 +56,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
def __eq__(self, _other):
return True
monkeypatch.setattr(handler, 'ShippingOrderExtractionPlan', SimpleNamespace(run_id=_Eq()))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=_Eq()))
monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing'))
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **_kwargs: events.append('failed'))
def fake_materialize(_run, *, finalize_plan=True):
@@ -97,7 +97,7 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
job = SimpleNamespace(id=2, attempts=1, business_ref=run.run_no, max_attempts=3)
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
monkeypatch.setattr(
handler, 'ShippingOrderExtractionRun',
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
@@ -147,13 +147,13 @@ def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
monkeypatch.setattr(
handler, 'ShippingOrderExtractionRun',
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(
handler, 'ShippingOrderExtractionUnit',
handler, 'ShippingOrderProcessingUnit',
SimpleNamespace(
status=_Expr(),
query=SimpleNamespace(join=lambda *_a, **_k: SimpleNamespace(
@@ -161,7 +161,7 @@ def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
)),
),
)
monkeypatch.setattr(handler, 'ShippingOrderExtractionPlan', SimpleNamespace(run_id=_Expr()))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=_Expr()))
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: events.append('materialize'),
@@ -197,6 +197,9 @@ def _patch_unit_transitions(monkeypatch):
unit.retry_status = 'retrying' if int(unit.attempt_count or 0) > 1 else 'running'
elif target_status == 'pending':
unit.retry_status = 'pending_retry'
unit.technical_failure_reason_code = None
unit.error_code = None
unit.error_message = None
elif target_status == 'failed':
unit.retry_status = 'failed'
unit.technical_failure_reason_code = error_code
@@ -328,6 +331,46 @@ def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch):
assert route_attempts == [1, 2]
def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatch):
"""Job 自动重跑遇到遗留 merging_supplement 时必须先回 pending,不能直接跳 routing。"""
event_log: list[tuple[str, str | None]] = []
_patch_unit_transitions(monkeypatch)
_patch_worker_io(monkeypatch, event_log=event_log)
run = SimpleNamespace(id=1, run_no='SNER-WORKER-RECOVER-MERGING')
unit = SimpleNamespace(
id=11, intake_id=15, document_id=105, status='merging_supplement', attempt_count=1,
retry_status='running', technical_failure_reason_code=None,
result_json=None, summary_json={'orders': [{'stale': True}]},
)
job = SimpleNamespace(id=9)
orders = [{'source_intake_no': 'SNI-RECOVER', 'primary_document_id': 105, 'header_fields': [], 'lines': []}]
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction.route_deterministic_unit',
lambda _run, *, unit: SimpleNamespace(
execution_mode='deterministic',
orders=orders,
decision={'selected_profile_code': 'vendor_a', 'selected_profile_version': 1},
),
)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction.validate_unit_orders',
lambda _run, *, unit, orders: orders,
)
monkeypatch.setattr(
'app.jobs.handlers.shipping_order_extraction._reload_run_and_unit',
lambda *, run_id, unit_id: (run, unit),
)
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
assert result == orders
assert unit.status == 'merging_supplement'
assert unit.attempt_count == 2
assert unit.technical_failure_reason_code is None
def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch):
"""自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。"""
event_log: list[tuple[str, str | None]] = []
@@ -10,8 +10,12 @@ from __future__ import annotations
from pydantic import ValidationError as PydanticValidationError
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
from app.services.shipping_notice.document_layout.order_field_extraction import (
_render_visual_row,
extract_order_fields,
)
from app.services.shipping_notice.document_layout.coordinate_region_text import visual_text_lines
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.runtime import _ocr_page_characters
from app.services.shipping_notice.document_profile_quality_service import _order_field_quality_failures
from app.core.errors import ValidationError
@@ -33,9 +37,9 @@ def _glyphs(*lines: tuple[str, float, float]) -> list[dict]:
return result
def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfileV2:
def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfile:
"""构造包含一个独立 header 字段的最小合法 v2 Profile。"""
return OrderCoordinateProfileV2.model_validate({
return OrderCoordinateProfile.model_validate({
'profile_code': 'ORDER-FIELD-TEST', 'version': 1,
'document_match': {'required_anchors': []},
'table_regions': [{'region_id': 'lines', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .9}, 'line_layouts': [], 'header_layouts': [{'layout_id': 'headers', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .7}}]}],
@@ -65,6 +69,61 @@ def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -
}
def test_visual_row_prefers_explicit_pdf_space_boundary_over_geometry_threshold():
"""真实词间距低于旧阈值时,PDF 文本流的明确空格仍应恢复,不能输出粘连地址。"""
row = [
(index, {
'text': character,
'source_index': source_index,
'boundary_before': 'space' if character == 'G' else 'none',
'bbox': {'x0': x0, 'y0': 10, 'x1': x0 + 6, 'y1': 18},
})
for index, (character, source_index, x0) in enumerate([
('Z', 0, 10), ('T', 1, 16), ('G', 3, 24.8), ('r', 4, 30.8), ('o', 5, 36.8),
('u', 6, 42.8), ('p', 7, 48.8),
])
]
# gap=2.8 小于旧平均字宽阈值 4.5;只能由可靠文本流边界恢复空格。
assert _render_visual_row(row) == 'ZT Group'
def test_visual_row_does_not_split_identifier_without_explicit_boundary():
"""料号、金额和 PO 未携带原始空白边界时,不得因修复公司名而被主动拆分。"""
for value in ('BU-00014-001B', 'D4-AR1200163A1', '563.79', '1000050815'):
row = [
(index, {
'text': character,
'source_index': index,
'boundary_before': 'none',
'bbox': {'x0': 10 + index * 6, 'y0': 10, 'x1': 16 + index * 6, 'y1': 18},
})
for index, character in enumerate(value)
]
# 关键断言:新边界机制不会通过降低全局阈值改变结构化标识符。
assert _render_visual_row(row) == value
def test_coordinate_region_reader_uses_same_explicit_space_boundary():
"""模板查看、模板匹配和区域诊断必须与订单字段共享同一原始空格语义。"""
glyphs = [
{
'text': character,
'source_index': source_index,
'boundary_before': 'space' if character == 'G' else 'none',
'bbox': {'x0': x0, 'y0': 10, 'x1': x0 + 6, 'y1': 18},
}
for character, source_index, x0 in [
('Z', 0, 10), ('T', 1, 16), ('G', 3, 24.8), ('r', 4, 30.8),
('o', 5, 36.8), ('u', 6, 42.8), ('p', 7, 48.8),
]
]
# 关键断言:区域阅读器不能继续输出历史粘连值 ZTGroup。
assert visual_text_lines(glyphs) == ['ZT Group']
def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
"""唯一 PO 标签右侧的原生字符经规范化后可确认为独立订单字段。"""
profile = _profile(layout={
@@ -11,7 +11,7 @@ from __future__ import annotations
from app import db
from app.models import (
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingTask,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingNotice,
)
from app.services.shipping_notice.order_schema import service
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
@@ -31,14 +31,14 @@ def _config(field_id: str) -> dict:
}
def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingTask:
def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingNotice:
"""创建冻结快照,策略绑定决定履约阶段如何定位预约单号。"""
service.initialize_schema({'display_name': '用途测试'}, actor_id=None)
field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
saved = service.save_draft(draft['id'], {'fields': [_config(field['id'])], 'expected_lock_version': draft['lock_version']}, actor_id=None)
published = service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
task = ShippingTask(
task = ShippingNotice(
task_no='SN-PURPOSE-1', source_type='manual', lines_json=[{'reservation_id': 'WRONG'}],
)
db.session.add(task)
@@ -1,10 +1,14 @@
"""验证订单坐标模板的唯一匹配只使用静态锚点和冻结结构证据。"""
"""验证订单坐标模板匹配:版面签名、七维评分与解析校验门禁。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
from app.services.shipping_notice.document_layout.order_profile_signature import (
MATCHER_POLICY_ID,
build_layout_signature,
)
def _field_region(*, field_id: str = 'line-id', field_code: str = 'customer_po_line_no', region: dict | None = None) -> dict:
"""构造符合 v2 scope 契约的字段区域。"""
"""构造符合统一 scope 契约的字段区域。"""
box = region or {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}
return {
'field_id': field_id,
@@ -16,17 +20,19 @@ def _field_region(*, field_id: str = 'line-id', field_code: str = 'customer_po_l
}
def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None = None, score: float = .9, margin: float = .12) -> dict:
"""构造最小冻结 Profile;工厂值必须与 PLANT NAME 标签形成关系才可命中。"""
return {'profile_code': code, 'version': 1, 'checksum': f'{code.lower():0<64}'[:64], 'definition': {
'contract_version': 'order_coordinate_profile.v2',
'profile_code': code,
'version': 1,
'document_match': {
'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': value, 'value_position': 'right'}],
'optional_anchors': [{'anchor_id': f'optional_{index}', 'label': 'TYPE:', 'value': item, 'value_position': 'right'} for index, item in enumerate(optional or [])],
'minimum_score': score, 'minimum_margin': margin,
'scoring_thresholds': {
'auto_select_minimum_score': 0.90,
'auto_select_minimum_margin': 0.15,
'auto_select_minimum_margin': 0.12,
'evidence_coverage_minimum': 0.70,
'critical_structure_minimum': 0.90,
},
},
@@ -37,43 +43,81 @@ def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None
}}
def _layout(text: str = 'PLANT NAME: FACTORY A') -> dict:
"""构造最小页面坐标证据,业务文本仅用于证明它没有参与匹配逻辑。"""
return {'tables': [{'table_id': 'table-1', 'page_no': 1}], 'coordinate_evidence': {
'tables': {'table-1': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate(text)
]}, 'pages': {'1': {'width': 200, 'height': 200}},
def _layout(text: str = 'PLANT NAME: FACTORY A', *, bbox: dict | None = None) -> dict:
"""构造页眉锨点与表内表头分离的最小坐标证据。"""
table = {
'table_id': 'table-1',
'page_no': 1,
'bbox': bbox or {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
}
anchor_glyphs = [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate(text)
]
header_text = 'ITEM NO QTY'
header_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 8, 'y0': 76, 'x1': 15 + index * 8, 'y1': 88},
'boundary_before': 'space' if index and header_text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(header_text)
if char != ' '
]
glyphs = [*anchor_glyphs, *header_glyphs]
return {'tables': [table], 'coordinate_evidence': {
'tables': {'table-1': header_glyphs},
'pages': {'1': {'width': 200, 'height': 280}},
'page_glyphs': {'1': glyphs},
}}
def _with_signature(profile: dict, layout: dict) -> dict:
"""为 Profile 附加 matching_signature 快照。"""
enriched = dict(profile)
signature_pack = build_layout_signature(
definition=enriched['definition'],
sample_layouts=[layout],
)
enriched['matching_signature'] = signature_pack
enriched['matching_signature_checksum'] = signature_pack['signature_checksum']
enriched['matching_signature_run_id'] = 1
enriched['matching_signature_version'] = 'order-profile-layout-signature'
return enriched
def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values():
"""工厂标签和值关系不受订单号、料号、数量变化影响。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'])], layout=_layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X'))
layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X')
profile = _with_signature(_profile('PO_A', optional=['UM17']), layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
assert result.profile_code == 'PO_A'
assert result.scoring_policy_version == MATCHER_POLICY_ID
def test_profile_matcher_ignores_pdf_whitespace_when_matching_label_value_anchor():
"""PDF 坐标字符逐字拼接时空白会丢失,标签和值关系仍必须可命中。"""
result = match_frozen_coordinate_profiles(
profiles=[_profile('PO_A', value='IEC Technologies, S. de R.L. de C.V')],
layout=_layout('PLANT NAME: IEC Technologies, S. de R.L. de C.V'),
)
layout = _layout('PLANT NAME: IEC Technologies, S. de R.L. de C.V')
profile = _with_signature(_profile('PO_A', value='IEC Technologies, S. de R.L. de C.V'), layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
def test_profile_matcher_rejects_similar_profiles_when_margin_is_insufficient():
"""相同静态锚点的两个 Profile 必须返回 ambiguous,禁止按版本或顺序选择。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A'), _profile('PO_B')], layout=_layout())
"""相同静态锚点的两个 Profile 必须返回 ambiguous。"""
layout = _layout()
profiles = [_with_signature(_profile('PO_A'), layout), _with_signature(_profile('PO_B'), layout)]
result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
assert result.status == 'ambiguous'
def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
"""缺静态锚点为 layout_drift;没有坐标页证据则为 evidence_insufficient。"""
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('REMARK: FACTORY A')).status == 'layout_drift'
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout={'tables': []}).status == 'evidence_insufficient'
layout_drift = _layout('REMARK: FACTORY A')
profile = _with_signature(_profile('PO_A'), _layout())
assert match_frozen_coordinate_profiles(profiles=[profile], layout=layout_drift).status == 'layout_drift'
assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient'
def test_profile_matcher_reports_only_missing_anchor_identifiers():
@@ -82,188 +126,225 @@ def test_profile_matcher_reports_only_missing_anchor_identifiers():
profile['definition']['document_match']['required_anchors'].append({
'anchor_id': 'customer_logo', 'label': 'CUSTOMER:', 'value': 'ACME LOGO', 'value_position': 'right',
})
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_layout('PLANT NAME: FACTORY A PO-12345'))
# 关键断言:管理员能定位配置缺项,而诊断不泄露订单业务值。
layout = _layout('PLANT NAME: FACTORY A PO-12345')
profile = _with_signature(profile, layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'layout_drift'
candidate = result.candidates[0]
assert candidate.reason_codes == ['required_anchor_missing']
assert 'required_anchor_missing' in candidate.reason_codes
assert candidate.missing_required_anchor_ids == ['customer_logo']
assert 'PO-12345' not in candidate.model_dump_json()
def test_profile_matcher_requires_optional_score_threshold():
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'], score=.95)], layout=_layout())
assert result.status == 'no_match'
def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
"""模板静态锚点可位于表格外,必须从页级冻结证据匹配而非只读表内字符。"""
layout = _layout('LINE ITEMS')
layout['coordinate_evidence']['page_glyphs'] = {'1': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate('PLANT NAME: FACTORY A')
]}
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
# 关键断言:订单字段模板不再要求业务锚点错误地落在明细表格中。
assert result.status == 'unique_match'
def test_profile_matcher_restores_region_text_by_visual_line_before_matching_anchor():
"""
区域锚点须按视觉行内横坐标恢复固定值,不能因 PDF 字符基线抖动打乱阅读顺序。
关键断言:值字符的 y0 顺序故意为 C、A、B;匹配器仍应按 x0 得到 ABC,
与标注工作台保存固定值时的视觉行重建规则一致。
"""
profile = _profile('PO_A', value='ABC')
anchor = profile['definition']['document_match']['required_anchors'][0]
anchor.update({
'page_no': 1,
'label_region': {'x0': 0.05, 'y0': 0.05, 'x1': 0.4, 'y1': 0.25},
'value_region': {'x0': 0.45, 'y0': 0.05, 'x1': 0.8, 'y1': 0.25},
})
layout = _layout('')
layout['coordinate_evidence']['page_glyphs'] = {'1': [
{'text': char, 'bbox': {'x0': 10 + index * 5, 'y0': 10, 'x1': 14 + index * 5, 'y1': 20}}
for index, char in enumerate('PLANT NAME:')
] + [
{'text': 'A', 'bbox': {'x0': 100, 'y0': 12, 'x1': 108, 'y1': 22}},
{'text': 'B', 'bbox': {'x0': 115, 'y0': 14, 'x1': 123, 'y1': 24}},
{'text': 'C', 'bbox': {'x0': 130, 'y0': 10, 'x1': 138, 'y1': 20}},
]}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence():
"""缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。"""
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match'
def test_profile_matcher_allows_multiple_template_regions_on_one_detected_table():
"""续页未被检测器拆表时,页级坐标证据仍可匹配多区域模板。"""
profile = _profile('PO_A')
profile['definition']['table_regions'][0]['region']['y1'] = .5
profile['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = .5
profile['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = .5
profile['definition']['table_regions'].append({
'region_id': 'lines_page_2', 'page_scope': 'exact_page', 'page_no': 2,
'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1},
'header_layouts': [{'layout_id': 'header_page_2', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}}],
})
def test_profile_matcher_no_optional_anchors_leaves_optional_static_text_unavailable():
"""无 optional 锚点时 optional_static_text 为 unavailable,不得因缺省锚点得满分。"""
layout = _layout()
layout['coordinate_evidence']['page_glyphs'] = {'1': layout['coordinate_evidence']['tables']['table-1']}
profile = _with_signature(_profile('PO_A', score=.99), layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
assert result.candidates[0].dimension_states['optional_static_text'] == 'unavailable'
assert result.candidates[0].evidence_coverage < 1.0
def test_profile_matcher_rejects_invalid_scope_contract_as_no_candidate():
"""缺少 scope/target_fields 的非法 Profile 不得参与评分(静默跳过 → no_match)。"""
broken = _profile('PO_BROKEN')
broken['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] = [{
'field_id': 'line-id',
'field_code': 'customer_po_line_no',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
}]
assert match_frozen_coordinate_profiles(profiles=[broken], layout=_layout()).status == 'no_match'
def test_profile_matcher_no_customer_hint_leaves_trusted_business_context_unavailable():
"""无 customer_hint 时 trusted_business_context 不得满分。"""
layout = _layout()
profile = _with_signature(_profile('PO_A'), layout)
profile['customer_ids'] = [100, 200]
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout, customer_hint_id=None)
assert result.candidates[0].dimension_states['trusted_business_context'] == 'unavailable'
def test_profile_matcher_customer_hint_can_match_trusted_business_context():
"""提供 customer_hint 且命中模板客户范围时该维度 matched。"""
layout = _layout()
profile = _with_signature(_profile('PO_A'), layout)
profile['customer_ids'] = [42]
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout, customer_hint_id=42)
assert result.candidates[0].dimension_states['trusted_business_context'] == 'matched'
def test_profile_matcher_missing_signature_hard_fails():
"""无 matching_signature 的 Profile 不得 hard_match。"""
layout = _layout()
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
assert result.candidates[0].hard_match is False
assert 'profile_signature_missing' in result.candidates[0].reason_codes
def test_profile_matcher_different_column_structures_produce_score_differences():
"""不同实际表头签名应产生可区分分数。"""
layout = _layout('PLANT NAME: FACTORY A ITEM QTY PRICE')
narrow = _with_signature(_profile('PO_NARROW'), layout)
wide = _profile('PO_WIDE')
wide_layout = _layout('PLANT NAME: FACTORY A ITEM QTY PRICE')
wide_header = 'LINE PART DESCRIPTION UNIT PRICE AMOUNT DUE DATE'
wide_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 4, 'y0': 76, 'x1': 13 + index * 4, 'y1': 88},
'boundary_before': 'space' if index and wide_header[index - 1] == ' ' else 'none',
}
for index, char in enumerate(wide_header)
if char != ' '
]
wide_layout['coordinate_evidence']['tables']['table-1'] = wide_glyphs
wide_layout['coordinate_evidence']['page_glyphs']['1'] = [
*[item for item in wide_layout['coordinate_evidence']['page_glyphs']['1'] if item['bbox']['y0'] < 70],
*wide_glyphs,
]
wide_sig = build_layout_signature(definition=wide['definition'], sample_layouts=[wide_layout])
wide['matching_signature'] = wide_sig
wide['matching_signature_checksum'] = wide_sig['signature_checksum']
result = match_frozen_coordinate_profiles(profiles=[narrow, wide], layout=layout)
scores = {item.profile_code: item.score for item in result.candidates}
assert scores['PO_NARROW'] != scores['PO_WIDE']
def test_profile_matcher_tie_scores_remain_ambiguous_not_order_dependent():
"""同分候选必须 ambiguous,且对输入顺序不敏感。"""
left_first = match_frozen_coordinate_profiles(profiles=[_profile('PO_A'), _profile('PO_B')], layout=_layout())
right_first = match_frozen_coordinate_profiles(profiles=[_profile('PO_B'), _profile('PO_A')], layout=_layout())
layout = _layout()
left = [_with_signature(_profile('PO_A'), layout), _with_signature(_profile('PO_B'), layout)]
right = [_with_signature(_profile('PO_B'), layout), _with_signature(_profile('PO_A'), layout)]
left_first = match_frozen_coordinate_profiles(profiles=left, layout=layout)
right_first = match_frozen_coordinate_profiles(profiles=right, layout=layout)
assert left_first.status == 'ambiguous'
assert right_first.status == 'ambiguous'
assert [item.profile_code for item in left_first.candidates] == [item.profile_code for item in right_first.candidates]
def test_profile_matcher_reports_dimension_scores_and_margin_on_candidates():
"""分项得分与 Top1/Top2/Margin 必须出现在候选与结果摘要中。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'])], layout=_layout('PLANT NAME: FACTORY A TYPE: UM17'))
def test_profile_matcher_low_evidence_coverage_blocks_auto_select():
"""evidence_coverage 不足时不得 unique_match。"""
layout = _layout()
profile = _with_signature(_profile('PO_A'), layout)
profile['definition']['document_match']['scoring_thresholds']['evidence_coverage_minimum'] = 0.95
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout, customer_hint_id=None)
assert result.status == 'no_match'
assert result.candidates[0].evidence_coverage < 0.95
assert 'profile_evidence_coverage_insufficient' in result.candidates[0].reason_codes
def test_profile_matcher_negative_anchor_hard_fails():
"""排除锚点命中时 hard_match 必须为 False。"""
layout = _layout('PLANT NAME: FACTORY A REJECT: BAD')
profile = _profile('PO_A')
profile['definition']['document_match']['negative_anchors'] = [{
'anchor_id': 'reject_marker', 'label': 'REJECT:', 'value': 'BAD', 'value_position': 'right',
}]
profile = _with_signature(profile, layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.candidates[0].hard_match is False
assert 'profile_negative_anchor_matched' in result.candidates[0].reason_codes
def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
"""模板静态锚点可位于表格外,必须从页级冻结证据匹配。"""
layout = _layout('LINE ITEMS')
table_glyphs = list(layout['coordinate_evidence']['tables']['table-1'])
layout['coordinate_evidence']['page_glyphs'] = {'1': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate('PLANT NAME: FACTORY A')
] + table_glyphs}
profile = _with_signature(_profile('PO_A'), layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
assert result.top1_score is not None
assert result.margin is not None
candidate = result.candidates[0]
assert candidate.dimension_scores is not None
assert candidate.dimension_scores.anchor_geometry == 1.0
assert 0.0 <= candidate.score <= 1.0
def test_profile_matcher_returns_no_special_profile_feature_without_template_evidence():
"""文档不含任何模板锚点/值证据时,必须明确无异型特征而非 layout_drift。"""
result = match_frozen_coordinate_profiles(
profiles=[_profile('PO_A')],
layout=_layout('GENERIC INVOICE NUMBER 12345 TOTAL DUE'),
)
"""文档不含任何模板锚点/值证据时,必须明确无异型特征。"""
layout = _layout('GENERIC INVOICE NUMBER 12345 TOTAL DUE')
signature_layout = _layout('PLANT NAME: FACTORY A')
signature_header = 'PART DESCRIPTION UNIT PRICE AMOUNT'
signature_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 5, 'y0': 76, 'x1': 14 + index * 5, 'y1': 88},
'boundary_before': 'space' if index and signature_header[index - 1] == ' ' else 'none',
}
for index, char in enumerate(signature_header)
if char != ' '
]
signature_layout['coordinate_evidence']['tables']['table-1'] = signature_glyphs
signature_layout['coordinate_evidence']['page_glyphs']['1'] = [
*[item for item in signature_layout['coordinate_evidence']['page_glyphs']['1'] if item['bbox']['y0'] < 70],
*signature_glyphs,
]
profile = _with_signature(_profile('PO_A'), signature_layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'no_special_profile_feature'
assert result.status != 'layout_drift'
def test_profile_matcher_auto_selects_by_score_when_margin_and_thresholds_met():
"""多候选 hard_match 且满足自动决胜阈值时返回 selected_by_score。"""
stronger = _profile('PO_A', optional=['UM17'])
weaker = _profile('PO_B', optional=['MISSING_TAG'])
layout = _layout('PLANT NAME: FACTORY A TYPE: UM17')
stronger = _with_signature(_profile('PO_A', optional=['UM17']), layout)
weaker = _with_signature(_profile('PO_B', optional=['MISSING_TAG']), layout)
weaker['definition']['table_regions'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'][0]['line_layouts'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['y1'] = 0.5
weaker['definition']['table_regions'].append({
'region_id': 'extra_lines',
'page_scope': 'exact_page',
'page_no': 1,
'region': {'x0': 0, 'y0': 0.5, 'x1': 1, 'y1': 1},
'line_layouts': [{
'layout_id': 'extra_main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0.5, 'x1': 1, 'y1': 1},
'field_regions': [_field_region(field_id='line-id-2', region={'x0': 0, 'y0': 0.5, 'x1': 1, 'y1': 1})],
}],
})
for item in (stronger, weaker):
item['definition']['document_match']['minimum_margin'] = 0.05
item['definition']['document_match']['scoring_thresholds'] = {
'auto_select_minimum_score': 0.90,
'auto_select_minimum_margin': 0.15,
'critical_structure_minimum': 0.80,
'auto_select_minimum_score': 0.80,
'auto_select_minimum_margin': 0.05,
'evidence_coverage_minimum': 0.60,
'critical_structure_minimum': 0.70,
}
result = match_frozen_coordinate_profiles(
profiles=[stronger, weaker],
layout=_layout('PLANT NAME: FACTORY A TYPE: UM17'),
)
weaker_sig = build_layout_signature(definition=weaker['definition'], sample_layouts=[layout])
weaker['matching_signature'] = weaker_sig
weaker['matching_signature_checksum'] = weaker_sig['signature_checksum']
result = match_frozen_coordinate_profiles(profiles=[stronger, weaker], layout=layout)
assert result.status == 'selected_by_score'
assert result.profile_code == 'PO_A'
assert result.margin is not None
assert result.margin >= 0.15
assert result.margin >= 0.05
def test_profile_matcher_uses_page_geometry_when_mineru_detects_no_table():
"""v2 坐标模板有完整页证据时,MinerU 零表不得把拓扑分清零并拒绝既有模板。"""
def test_profile_matcher_page_existence_alone_is_not_page_structure_match():
"""仅有 pages 但宽高比/表数不符时 page_structure 不得视为完全匹配。"""
layout = _layout('PLANT NAME: FACTORY A')
layout['coordinate_evidence']['page_glyphs'] = {
'1': list(layout['coordinate_evidence']['tables']['table-1']),
}
layout['tables'] = []
layout['coordinate_evidence']['pages'] = {'1': {'width': 50, 'height': 500}}
profile = _with_signature(_profile('PO_A'), _layout())
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
candidate = result.candidates[0]
assert candidate.dimension_states.get('page_structure') in {'mismatched', 'unavailable'}
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
def test_profile_matcher_compares_header_inside_table_not_page_header():
"""运行时表头评分必须忽略页面抬头,仅消费主表 bbox 顶部的字符。"""
layout = _layout('PLANT NAME: FACTORY A PURCHASE ORDER VENDOR DATE')
page_glyphs = layout['coordinate_evidence']['page_glyphs']['1']
header_text = 'ITEM NO MATERIAL NO REV MATERIAL DESCRIPTION UNIT PRICE ORDER QUANTITY ORDER AMOUNT'
page_glyphs.extend([
{
'text': char,
'bbox': {'x0': 10 + index * 4, 'y0': 76, 'x1': 13 + index * 4, 'y1': 88},
'boundary_before': 'space' if index and header_text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(header_text)
if char != ' '
])
layout['coordinate_evidence']['tables']['table-1'] = list(page_glyphs)
profile = _with_signature(_profile('PO_A'), layout)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
candidate = result.candidates[0]
assert candidate.hard_match is True
assert candidate.dimension_scores is not None
assert candidate.dimension_scores.header_semantic_position >= 0.75
def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness():
"""硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。"""
layout = _layout('PLANT NAME: FACTORY A')
qualified = _with_signature(_profile('PO_QUALIFIED'), layout)
ineligible = _with_signature(_profile('PO_INELIGIBLE', score=0.99), layout)
ineligible['definition']['document_match']['scoring_thresholds']['evidence_coverage_minimum'] = 0.95
result = match_frozen_coordinate_profiles(
profiles=[qualified, ineligible], layout=layout,
)
assert result.status == 'unique_match'
assert result.candidates[0].dimension_scores is not None
assert result.candidates[0].dimension_scores.table_topology == 1.0
def test_profile_matcher_drift_is_not_no_special_profile_feature():
"""部分锚点证据缺失但页内仍出现模板值时,必须判定 layout_drift。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('REMARK: FACTORY A'))
assert result.status == 'layout_drift'
assert result.status != 'no_special_profile_feature'
assert result.profile_code == 'PO_QUALIFIED'
@@ -0,0 +1,166 @@
"""验证 Profile 解析候选只读校验的基础行为。"""
from app.services.shipping_notice.document_layout.order_profile_parse_validation import (
validate_profile_parse_candidate,
)
from app.services.shipping_notice.document_layout.order_profile_signature import build_layout_signature
def _minimal_profile_snapshot(*, line_regions: list[dict] | None = None) -> dict:
"""构造带 line 字段区的最小 Profile 快照。"""
field_regions = line_regions or [{
'field_id': 'line-id',
'field_code': 'customer_po_line_no',
'scope': 'line',
'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.3, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id'}],
}]
definition = {
'profile_code': 'PO_TEST',
'version': 1,
'document_match': {'required_anchors': [], 'optional_anchors': []},
'table_regions': [{
'region_id': 'lines',
'region': {'x0': 0, 'y0': 0.3, 'x1': 1, 'y1': 1},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0.3, 'x1': 1, 'y1': 1},
'field_regions': field_regions,
}],
}],
}
return {'profile_code': 'PO_TEST', 'version': 1, 'definition': definition}
def _layout_with_line_text(text: str = '001 PART-A 10') -> dict:
"""构造含明细区文字的 layout。"""
glyphs = [
{'text': char, 'bbox': {'x0': 20 + index * 5, 'y0': 120 + (index % 3), 'x1': 24 + index * 5, 'y1': 132 + (index % 3)}}
for index, char in enumerate(text)
]
return {
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 280}},
'page_glyphs': {'1': glyphs},
'tables': {'table-1': glyphs},
},
}
def test_parse_validation_passes_with_sufficient_line_coverage():
"""line 字段区有文字且行数合理时应通过。"""
layout = _layout_with_line_text()
profile = _minimal_profile_snapshot()
definition = {'fields': [{'field_code': 'customer_po_line_no', 'enabled': True, 'value_type': 'string'}]}
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout=layout,
definition=definition,
)
assert result['passed'] is True
assert result['reason_codes'] == []
assert result['metrics']['line_coverage_ratio'] > 0
def test_parse_validation_fails_without_coordinate_evidence():
"""缺少坐标证据时必须失败且 reason 稳定。"""
profile = _minimal_profile_snapshot()
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout={'tables': []},
definition={'fields': []},
)
assert result['passed'] is False
assert 'profile_parse_evidence_missing' in result['reason_codes']
def test_parse_validation_fails_when_line_regions_empty():
"""line 字段区大面积无文字时应触发 unknown_columns。"""
layout = _layout_with_line_text(' ')
profile = _minimal_profile_snapshot()
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout=layout,
definition={'fields': []},
)
assert result['passed'] is False
assert 'profile_parse_unknown_columns' in result['reason_codes']
def test_parse_validation_is_idempotent():
"""相同输入多次调用应得到相同结果。"""
layout = _layout_with_line_text()
profile = _minimal_profile_snapshot()
definition = {'fields': []}
first = validate_profile_parse_candidate(profile_snapshot=profile, layout=layout, definition=definition)
second = validate_profile_parse_candidate(profile_snapshot=profile, layout=layout, definition=definition)
assert first == second
def test_parse_validation_invalid_definition():
"""无法解析的 Profile 定义应返回 definition_invalid。"""
result = validate_profile_parse_candidate(
profile_snapshot={'profile_code': 'X', 'version': 1, 'definition': {'table_regions': []}},
layout=_layout_with_line_text(),
definition={'fields': []},
)
assert result['passed'] is False
assert 'profile_parse_definition_invalid' in result['reason_codes']
def test_parse_validation_supports_order_field_layout_absolute_regions():
"""订单头 OrderFieldLayout 必须按 absolute_value_region 验证,不得访问不存在的 region 属性。"""
profile = _minimal_profile_snapshot()
profile['definition']['order_field_layouts'] = [{
'layout_id': 'purchase_order_no', 'field_id': 'po-id', 'field_code': 'customer_po_no',
'scope': 'header', 'anchor': {'anchor_id': 'po_anchor', 'text': 'PO NO'},
'absolute_value_region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.3, 'y1': 0.5},
'required': True,
}]
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout=_layout_with_line_text(),
definition={'fields': [
{'field_code': 'customer_po_no', 'enabled': True, 'value_type': 'string'},
{'field_code': 'customer_po_line_no', 'enabled': True, 'value_type': 'string'},
]},
)
assert result['passed'] is True
assert result['metrics']['header_coverage_ratio'] == 1.0
def test_parse_validation_accepts_month_day_year_date_format():
"""轻量类型检查应接受采购订单常见 MM/DD/YYYY,正式标准化由后续 normalizer 完成。"""
profile = _minimal_profile_snapshot(line_regions=[
{
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.09, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{
'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id',
}],
},
{
'field_id': 'date-id', 'field_code': 'requested_receipt_date', 'scope': 'line',
'region': {'x0': 0.10, 'y0': 0.4, 'x1': 0.6, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{
'scope': 'line', 'field_code': 'requested_receipt_date', 'field_id': 'date-id',
}],
},
])
result = validate_profile_parse_candidate(
profile_snapshot=profile,
layout=_layout_with_line_text('06/22/2026'),
definition={'fields': [{
'field_code': 'requested_receipt_date', 'enabled': True, 'value_type': 'date',
}]},
)
assert result['passed'] is True
assert result['metrics']['type_issue_count'] == 0
@@ -0,0 +1,159 @@
"""验证 Phase 1 版面签名生成与审计安全边界。"""
from app.services.shipping_notice.document_layout.order_profile_signature import (
LAYOUT_SIGNATURE_ID,
build_layout_signature,
signature_checksum,
signature_is_safe_for_audit,
)
def _minimal_definition(*, profile_code: str = 'PO_SIG', header_token: str = 'ITEM') -> dict:
"""构造可生成签名的最小 Profile 定义。"""
return {
'profile_code': profile_code,
'version': 1,
'document_match': {'required_anchors': [], 'optional_anchors': []},
'table_regions': [{
'region_id': 'lines',
'region': {'x0': 0, 'y0': 0.2, 'x1': 1, 'y1': 1},
'header_layouts': [{
'layout_id': 'header', 'region': {'x0': 0, 'y0': 0.2, 'x1': 1, 'y1': 0.35},
'field_regions': [{
'field_id': 'hdr-item',
'field_code': 'item_no',
'scope': 'header',
'region': {'x0': 0.05, 'y0': 0.22, 'x1': 0.2, 'y1': 0.32},
'allowed_sources': ['pdf_coordinate'],
}],
}],
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0.35, 'x1': 1, 'y1': 1},
'field_regions': [{
'field_id': 'line-id',
'field_code': 'customer_po_line_no',
'scope': 'line',
'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.25, 'y1': 0.5},
'allowed_sources': ['pdf_coordinate'],
'target_fields': [{'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id'}],
}],
}],
}],
'_header_token_hint': header_token,
}
def _sample_layout(*, header_text: str = 'ITEM NO QTY') -> dict:
"""构造含表头文字的样本 layout。"""
glyphs = [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 60, 'x1': 13 + index * 4, 'y1': 72}}
for index, char in enumerate(header_text)
] + [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 110, 'x1': 13 + index * 4, 'y1': 122}}
for index, char in enumerate('001 PART-A')
]
return {
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 280}},
'page_glyphs': {'1': glyphs},
'tables': {'table-1': glyphs},
},
}
def test_same_input_produces_same_checksum():
"""相同 definition + sample_layouts 必须得到相同 checksum。"""
definition = _minimal_definition()
layout = _sample_layout()
first = build_layout_signature(definition=definition, sample_layouts=[layout])
second = build_layout_signature(definition=definition, sample_layouts=[layout])
assert first['signature_checksum'] == second['signature_checksum']
assert signature_checksum(first['signature']) == first['signature_checksum']
def test_different_samples_produce_different_checksum():
"""不同表头样本应产生不同 checksum。"""
definition = _minimal_definition()
layout_a = _sample_layout(header_text='ITEM NO QTY')
layout_b = _sample_layout(header_text='LINE PART AMT')
checksum_a = build_layout_signature(definition=definition, sample_layouts=[layout_a])['signature_checksum']
checksum_b = build_layout_signature(definition=definition, sample_layouts=[layout_b])['signature_checksum']
assert checksum_a != checksum_b
def test_signature_is_safe_for_audit_rejects_http_urls():
"""签名快照含 http URL 时必须被审计安全边界拒绝。"""
unsafe = {
'signature': {'signature_version': LAYOUT_SIGNATURE_ID, 'table_patterns': []},
'source_sample_refs': [{'id': 1, 'url': 'https://minio.example/bucket/file.pdf'}],
}
assert signature_is_safe_for_audit(unsafe) is False
def test_signature_is_safe_for_audit_accepts_clean_snapshot():
"""正常签名快照应通过审计安全边界。"""
definition = _minimal_definition()
layout = _sample_layout()
snapshot = build_layout_signature(
definition=definition,
sample_layouts=[layout],
source_sample_refs=[{'id': 1, 'role': 'primary', 'content_hash': 'abc123'}],
)
assert signature_is_safe_for_audit(snapshot) is True
def test_dynamic_tokens_filtered_from_header_signature():
"""PO 号/日期等动态 token 不得进入稳定 header_tokens。"""
definition = _minimal_definition()
layout = _sample_layout(header_text='ITEM PO-12345678 2026-08-04')
snapshot = build_layout_signature(definition=definition, sample_layouts=[layout])
tokens = snapshot['signature']['table_patterns'][0]['header_tokens']
joined = ' '.join(tokens).upper()
assert 'PO-12345678' not in joined
assert '2026-08-04' not in joined
def test_header_signature_preserves_visual_line_order_and_token_positions():
"""表头字符即使源顺序交错,也必须按视觉行和行内坐标生成签名。"""
definition = _minimal_definition()
layout = _sample_layout(header_text='ITEM NO QTY')
glyphs = layout['coordinate_evidence']['page_glyphs']['1']
header = [item for item in glyphs if item['bbox']['y0'] == 60]
body = [item for item in glyphs if item['bbox']['y0'] == 110]
layout['coordinate_evidence']['page_glyphs']['1'] = [
*body[::2], *header[1::2], *body[1::2], *header[::2],
]
layout['coordinate_evidence']['tables']['table-1'] = list(
layout['coordinate_evidence']['page_glyphs']['1'],
)
pattern = build_layout_signature(
definition=definition, sample_layouts=[layout],
)['signature']['table_patterns'][0]
assert pattern['header_tokens'] == ['ITEM', 'NO', 'QTY']
assert len(pattern['column_centers']) == 3
assert pattern['column_centers'] == sorted(pattern['column_centers'])
def test_signature_relation_graph_uses_anchor_text_contract():
"""订单头字段关系图必须读取 AnchorRule.text,生成签名不得访问不存在的 label 属性。"""
definition = _minimal_definition()
definition['order_field_layouts'] = [
{
'layout_id': 'purchase_order_no', 'field_id': 'po-id', 'field_code': 'customer_po_no',
'scope': 'header', 'anchor': {'anchor_id': 'po_anchor', 'text': 'PO NO'},
'absolute_value_region': {'x0': 0.2, 'y0': 0.05, 'x1': 0.4, 'y1': 0.1},
},
{
'layout_id': 'currency', 'field_id': 'currency-id', 'field_code': 'currency',
'scope': 'header', 'anchor': {'anchor_id': 'currency_anchor', 'text': 'CURRENCY'},
'absolute_value_region': {'x0': 0.6, 'y0': 0.05, 'x1': 0.8, 'y1': 0.1},
},
]
snapshot = build_layout_signature(definition=definition, sample_layouts=[_sample_layout()])
assert isinstance(snapshot['signature']['field_relation_graph'], list)
@@ -0,0 +1,67 @@
"""
tests/test_shipping_order_profile_signature_audit.py
用途:验收草稿变化清空签名引用时写入 matching_signature_invalidated 审计。
依赖:Profile 服务、租约服务、验证服务、Audit ORM。
逻辑:先生成签名引用,再改草稿定义,断言引用清空且审计事件存在。
"""
from __future__ import annotations
from app.extensions import db
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice.order_document_profile_service import clear_matching_signature_refs
from tests.test_shipping_order_document_profile_service import _data, _schema_version
def test_clear_matching_signature_refs_writes_audit(app):
"""关键断言:清空签名引用会写 matching_signature_invalidated,且字段变为空。"""
with app.app_context():
schema = _schema_version()
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='sig-audit-create')
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
profile.matching_signature_run_id = None
profile.matching_signature_checksum = 'c' * 64
profile.matching_signature_version = 'order-profile-layout-signature'
db.session.flush()
cleared = clear_matching_signature_refs(
profile, actor_id=None, operation_id='sig-audit-clear', reason='definition_changed',
)
db.session.commit()
assert cleared is True
assert profile.matching_signature_checksum is None
assert profile.matching_signature_version is None
events = ShippingOrderDocumentProfileAudit.query.filter_by(
profile_id=profile.id, event_type='matching_signature_invalidated',
).all()
assert len(events) == 1
assert events[0].detail_json.get('reason') == 'definition_changed'
def test_save_draft_definition_change_clears_signature(app):
"""关键断言:有效定义变化后 Profile 签名引用立即失效。"""
with app.app_context():
schema = _schema_version()
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='sig-stale-create')
lease = lease_service.acquire_lease(
draft['id'], actor_id=None, browser_session_id='sig-audit-tab', operation_id='sig-lease',
)
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
profile.matching_signature_checksum = 'd' * 64
profile.matching_signature_version = 'order-profile-layout-signature'
db.session.commit()
changed = _data(schema.id)
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.15
changed['expected_lock_version'] = draft['lock_version']
profile_service.save_draft(
changed, actor_id=None, profile_id=draft['id'], browser_session_id='sig-audit-tab',
lease_token=lease['lease_token'], operation_id='sig-stale-change', enforce_lease=True,
)
reloaded = db.session.get(ShippingOrderDocumentProfile, draft['id'])
assert reloaded.matching_signature_checksum is None
assert reloaded.matching_signature_version is None
@@ -0,0 +1,73 @@
"""
tests/test_shipping_order_profile_signature_migration.py
用途:验收版面签名引用迁移后的模型字段与 run_type 约束可写入。
依赖:Flask app fixture、ShippingOrderDocumentProfile / ValidationRun ORM。
逻辑:在测试库创建带 matching_signature_* 的 Profile 与 layout_signature 运行,确认约束放行。
"""
from __future__ import annotations
from datetime import datetime
from app.extensions import db
from app.models import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileValidationRun,
)
from tests.test_shipping_order_document_profile_service import _schema_version
def test_layout_signature_run_type_and_profile_refs_persist(app):
"""关键断言:layout_signature run_type 可写入,Profile 可保存签名轻量引用。"""
with app.app_context():
schema = _schema_version()
profile = ShippingOrderDocumentProfile(
profile_code='SIG_MIG',
display_name='Signature migration',
version=1,
status='draft',
schema_version_id=schema.id,
structure_fingerprint='a' * 64,
definition_json={
'document_match': {'required_anchors': [], 'optional_anchors': []},
'table_regions': [{
'region_id': 'lines',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [],
}],
}],
},
)
db.session.add(profile)
db.session.flush()
run = ShippingOrderDocumentProfileValidationRun(
profile_id=profile.id,
revision_no=1,
definition_checksum=profile.structure_fingerprint,
schema_version_id=schema.id,
run_type='layout_signature',
status='passed',
summary_json={'signature_checksum': 'b' * 64},
result_snapshot_json={'signature_checksum': 'b' * 64, 'signature': {}},
operation_id='sig-mig-op',
completed_at=datetime.utcnow(),
)
db.session.add(run)
db.session.flush()
profile.matching_signature_run_id = run.id
profile.matching_signature_checksum = 'b' * 64
profile.matching_signature_version = 'order-profile-layout-signature'
db.session.commit()
reloaded = db.session.get(ShippingOrderDocumentProfile, profile.id)
assert reloaded.matching_signature_run_id == run.id
assert reloaded.matching_signature_checksum == 'b' * 64
assert reloaded.matching_signature_version == 'order-profile-layout-signature'
assert db.session.get(ShippingOrderDocumentProfileValidationRun, run.id).run_type == 'layout_signature'
@@ -35,12 +35,14 @@ def test_project_review_case_field_conflicts_builds_stable_keys():
'field': 'qty',
'value': '10',
'source': 'table',
'source_type': 'attachment_text',
},
{
'observation_id': 'obs-b',
'field': 'qty',
'value': '12',
'source': 'header',
'source_type': 'email_body_text',
},
],
},
@@ -76,6 +78,10 @@ def test_project_review_case_field_conflicts_builds_stable_keys():
assert item['reason'] == 'cross_source_conflict'
assert [opt['display_value'] for opt in item['options']] == ['10', '12']
assert item['options'][0]['sources'] == ['table']
# 关键断言:主 PDF / 邮件正文分别标注 evidence_role,供冲突面板徽章。
assert item['options'][0]['evidence_role'] == 'primary_pdf'
assert item['options'][0]['source_type'] == 'attachment_text'
assert item['options'][1]['evidence_role'] == 'context'
def test_project_review_case_field_conflicts_empty_without_candidate():
@@ -17,7 +17,7 @@ from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingAuditEvent,
ShippingNoticeCandidate,
ShippingOrderCandidate,
ShippingOrderExtractionProgressEvent,
ShippingOrderReviewSuggestion,
)
@@ -46,7 +46,7 @@ def _seed_review_case(*, suffix: str):
'conflicts': [],
}],
}
db.session.add(ShippingNoticeCandidate(
db.session.add(ShippingOrderCandidate(
candidate_no=f'CAND-LLM-{suffix}',
intake_id=int(intake.id),
primary_document_id=int(document.id),
@@ -15,7 +15,7 @@ from sqlalchemy.exc import OperationalError
from app import db
from app.models import (
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionUnit,
ShippingOrderProcessingUnit,
)
from app.services.shipping_notice.order_extraction_progress import record_run_progress
from app.services.shipping_notice.order_review_progress_bridge import record_review_progress_event
@@ -63,7 +63,7 @@ def test_bridge_falls_back_to_run_progress_without_unit(app):
_user, case, _field_id = _seed_review_case(suffix='BRIDGE-RUN')
case.run.status = 'review_required'
plan_id = int(case.run.extraction_plan.id)
ShippingOrderExtractionUnit.query.filter_by(plan_id=plan_id).delete(
ShippingOrderProcessingUnit.query.filter_by(plan_id=plan_id).delete(
synchronize_session=False,
)
db.session.commit()
@@ -0,0 +1,103 @@
"""
tests/test_shipping_order_review_resume_service.py
用途:验收统一恢复协调器的资格三层分离与 blocked / waiting_manual_confirm 分支。
依赖:order_review_resume_service、types.SimpleNamespace、monkeypatch。
逻辑:不落库;断言 can_build=false → blocked,can_build 且非 auto_gate → waiting_manual_confirm。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.shipping_notice import order_review_resume_service as svc
def _case(*, status='draft', can_build=False, can_auto_create=False, validation_status='needs_review'):
draft = SimpleNamespace(
draft_version=3,
validation_result_json={
'status': validation_status,
'can_build': can_build,
'can_auto_create': can_auto_create,
'failed_gates': [] if can_build else ['customer_confirmed'],
'issues': [],
},
)
return SimpleNamespace(
case_no='CASE-RESUME-1',
status=status,
confirmed_task_id=None,
candidate_id=None,
owner_user_id=7,
document_id=9,
id=1,
current_draft=draft,
run=SimpleNamespace(id=1),
)
def test_resume_blocked_when_not_can_build(monkeypatch):
"""资格未通过时 outcome=blocked,不尝试建单。"""
case = _case(can_build=False, can_auto_create=False)
monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case)
monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None)
monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: [])
monkeypatch.setattr(
'app.services.shipping_notice.order_review_draft_service.validate_draft',
lambda **_kw: {'case_no': case.case_no},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **_kw: None,
)
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
monkeypatch.setattr(svc.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_projection.serialize_review_case',
lambda _c: {'case_no': case.case_no},
)
result = svc.resume_after_review_change(
user_id=7,
case_no=case.case_no,
trigger='customer_confirmed',
skip_validate=True,
)
assert result['outcome'] == 'blocked'
assert result['task_created'] is False
assert result['auto_gate_allowed'] is False
assert result['gate_recalculated'] is True
def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch):
"""可建单但不允许 auto_gate → waiting_manual_confirm。"""
case = _case(can_build=True, can_auto_create=False, validation_status='ready')
monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case)
monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None)
monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: [])
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **_kw: None,
)
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
monkeypatch.setattr(svc.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_projection.serialize_review_case',
lambda _c: {'case_no': case.case_no, 'status': case.status},
)
result = svc.resume_after_review_change(
user_id=7,
case_no=case.case_no,
trigger='customer_confirmed',
skip_validate=True,
allow_auto_create=True,
)
assert result['outcome'] == 'waiting_manual_confirm'
assert result['can_build'] is True
assert result['auto_gate_allowed'] is False
assert result['task_created'] is False
assert case.status == 'ready'
@@ -17,11 +17,12 @@ from app.core.errors import NotFoundError
from app.models import (
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingNoticeCandidate,
ShippingOrderCandidate,
ShippingOrderReviewCase,
ShippingOrderReviewCaseEvent,
ShippingOrderReviewConfirmedRevision,
ShippingTask,
ShippingOrderReviewWaveLine,
ShippingNotice,
User,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case, serialize_review_run
@@ -35,6 +36,7 @@ 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,
build_confirmable_draft_summary,
delete_line,
keep_manual_inventory_routing,
patch_header_field,
@@ -99,7 +101,7 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
'conflicts': [],
}],
}
candidate = ShippingNoticeCandidate(
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-ONE', intake_id=intake.id, primary_document_id=document.id,
candidate_key='review-one', order_extraction_run_id=run.id, structured_result_json={'machine': 'unchanged'},
)
@@ -117,7 +119,7 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
assert case.candidate_id == candidate.id
assert case.current_draft is not None
assert case.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-1'
assert db.session.get(ShippingNoticeCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
assert db.session.get(ShippingOrderCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
def test_review_case_backfills_final_run_order_for_an_empty_legacy_draft(app):
@@ -167,7 +169,7 @@ def test_review_case_without_or_with_multiple_candidates_never_picks_a_machine_s
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-MULTI')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
for index in (1, 2):
db.session.add(ShippingNoticeCandidate(
db.session.add(ShippingOrderCandidate(
candidate_no=f'CAND-REVIEW-MULTI-{index}', intake_id=intake.id, primary_document_id=document.id,
candidate_key=f'review-multi-{index}', order_extraction_run_id=run.id,
))
@@ -312,7 +314,7 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap
]}],
}]}
# 建单资格 fail-closed:客户未确认时 validate 只能 needs_review,与坐标高亮无关。
db.session.add(ShippingNoticeCandidate(
db.session.add(ShippingOrderCandidate(
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'}},
@@ -563,6 +565,45 @@ def test_review_evidence_resolves_nested_layout_evidence_cell_ids(app):
assert item['machine_value'] == '20'
def test_review_evidence_never_maps_duplicate_value_to_another_field(app):
"""单价与金额相同值时,缺少字段身份坐标不得按文本反查到相邻字段。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-DUPLICATE-VALUE')
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-lines', 'rows': [{'cells': [
{'cell_id': 'unit-price', 'text': '941.76', 'bbox': {'x0': 100, 'y0': 200, 'x1': 200, 'y1': 250}},
{'cell_id': 'order-amount', 'text': '941.76', 'bbox': {'x0': 700, 'y0': 200, 'x1': 800, 'y1': 250}},
]}]}],
}],
},
}
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': 'order-amount', 'observations': [{
'value': '941.76', 'quote': '941.76', 'page_no': 1,
}],
}]}]}]}
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]
# 关键断言:相同文本无法证明字段归属,不能把金额误标到单价位置。
assert item['machine_value'] == '941.76'
assert item['highlight_bbox'] is None
assert item['coordinate_status'] == 'unavailable'
def test_review_evidence_highlight_verified_and_unavailable_states(app):
"""证据 API 须覆盖 verified / unavailable;缺失坐标不影响 machine_value。"""
with app.app_context():
@@ -668,7 +709,11 @@ def test_document_reparse_uses_one_document_and_restores_old_draft_when_new_run_
assert reused is False
assert case.status == 'reparse_pending'
marker = replacement.input_snapshot_json['review_reparse']
assert marker == {'document_id': document.id, 'source_case_no': case.case_no}
assert marker['document_id'] == document.id
assert marker['source_case_no'] == case.case_no
assert marker['source_candidate_id'] is None
assert marker['source_order_task_no'] is None
assert replacement.user_task_no is None
documents = [
item for intake_snapshot in replacement.input_snapshot_json['intakes']
for item in intake_snapshot['documents'] if item['document_type'] != 'email_body'
@@ -738,7 +783,7 @@ def test_replacement_run_requires_new_pdf_and_preserves_old_case_until_success(a
transition_order_extraction_run(run, target_status='review_required', result={})
db.session.commit()
from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
asset = FileAsset(
@@ -749,14 +794,14 @@ def test_replacement_run_requires_new_pdf_and_preserves_old_case_until_success(a
)
db.session.add(asset)
db.session.flush()
replacement_intake = ShippingNoticeIntake(
replacement_intake = ShippingOrderIntake(
intake_no='SNI-REVIEW-REPLACEMENT', asset_id=asset.id, user_id=user.id,
conversation_id=session.session_id, upload_batch_id='review-replacement-test', purpose='shipping_notice',
parse_status='parsed', parser_version=intake.parser_version,
)
db.session.add(replacement_intake)
db.session.flush()
replacement_document = ShippingNoticeDocument(
replacement_document = ShippingOrderDocument(
intake_id=replacement_intake.id, asset_id=asset.id, attachment_key='file', document_type='attachment',
filename='replacement.pdf', content_hash='replacement-hash', parse_status='parsed', extracted_text='replacement order',
)
@@ -770,9 +815,12 @@ def test_replacement_run_requires_new_pdf_and_preserves_old_case_until_success(a
)
assert reused is False
assert case.status == 'reparse_pending'
assert replacement.input_snapshot_json['review_reparse'] == {
'document_id': replacement_document.id, 'source_case_no': case.case_no,
}
marker = replacement.input_snapshot_json['review_reparse']
assert marker['document_id'] == replacement_document.id
assert marker['source_case_no'] == case.case_no
assert marker['source_candidate_id'] is None
assert marker['source_order_task_no'] is None
assert replacement.user_task_no is None
finalize_document_reparse(run=replacement, succeeded=False)
assert case.status == 'unreviewed'
@@ -800,7 +848,7 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092917'}]},
]}]}]}
machine = ShippingNoticeCandidate(
machine = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-CONFIRM', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-confirm', order_extraction_run_id=run.id,
# 客户已确认是建单前置条件;机器 Candidate 只读快照不得被确认覆盖。
@@ -812,6 +860,14 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
db.session.add(machine)
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
# 确认建单要求 Candidate 已绑定 OT(BE-01);测试显式物化。
from app.services.shipping_notice.order_task_service import upsert_order_task_from_run
upsert_order_task_from_run(
run,
intake_id=int(intake.id),
candidate_id=int(machine.id),
stage='waiting_review',
)
validated = patch_header_field(
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-CONFIRMED', expected_draft_version=1,
)
@@ -824,19 +880,25 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
)
db.session.commit()
task = ShippingTask.query.filter_by(task_no=result['task_no']).one()
task = ShippingNotice.query.filter_by(task_no=result['task_no']).one()
review_candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
revision = ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).one()
# 关键断言:确认只生成当前 PDF 的一张 Task,无 Batch,并冻结草稿而不覆盖机器 Candidate。
assert task.batch_id is None
# 关键断言:确认只生成当前 PDF 的一张 Notice,并冻结草稿而不覆盖机器 Candidate。
assert result.get('order_task_no')
assert getattr(task, 'order_task_id', None) is not None
assert task.source_candidate_id is not None
assert task.current_order_extraction_id is not None
# 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。
assert task.process_status == 'parsed'
assert task.review_status is None
assert task.pending_human_reason is None
# 关键断言:人工 Candidate 必须保留受控字段证据,建单后资格不能反向变成 evidence_missing。
assert review_candidate is not None
assert review_candidate.evidence_json
assert all(item.get('field') for item in review_candidate.evidence_json)
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 == {
assert db.session.get(ShippingOrderCandidate, machine.id).structured_result_json == {
'machine': 'unchanged',
'customer': {'resolution_status': 'confirmed'},
}
@@ -865,7 +927,7 @@ 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(
db.session.add(ShippingOrderCandidate(
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'}},
@@ -887,7 +949,7 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati
# 关键断言:重复点击不创建第二 Task,终态 Case 也不能再修改或标记。
assert replay['idempotent_replay'] is True
assert replay['task_no'] == first['task_no']
assert ShippingTask.query.filter_by(source_type='review_confirmation').count() == 1
assert ShippingNotice.query.filter_by(source_type='review_confirmation').count() == 1
try:
patch_line_field(user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='4', expected_draft_version=1)
except Exception as exc:
@@ -918,7 +980,7 @@ def test_confirm_review_case_rejects_when_customer_unresolved(app):
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092999'}]},
]}]}]}
db.session.add(ShippingNoticeCandidate(
db.session.add(ShippingOrderCandidate(
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'}},
@@ -940,7 +1002,78 @@ def test_confirm_review_case_rejects_when_customer_unresolved(app):
}
else:
raise AssertionError('confirm without customer must be rejected')
assert ShippingTask.query.filter_by(source_type='review_confirmation').count() == 0
assert ShippingNotice.query.filter_by(source_type='review_confirmation').count() == 0
def test_confirm_review_case_rejects_when_inventory_source_unresolved(app):
"""
库存源未唯一确定时不得创建正式订单(阶段 1 硬门禁)。
断言:拒绝码为 REVIEW_INVENTORY_SOURCE_UNRESOLVED;不落 Notice;OT stage 回写为
inventory_source_resolving(若 OT 已存在)。
"""
with app.app_context():
from app.models import ShippingOrderTask
from app.services.shipping_notice.order_task_service import upsert_order_task_from_run
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-CONFIRM-NOINV')
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': 'A010'}]},
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092998'}]},
]}]}]}
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-NOINV', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-no-inventory', order_extraction_run_id=run.id,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
)
db.session.add(candidate)
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
# 故意不注入 catch-all 库存规则 → inventory_source_routing 阻断。
order_task = upsert_order_task_from_run(
run,
intake_id=int(intake.id),
candidate_id=int(candidate.id),
stage='waiting_review',
)
db.session.commit()
assert order_task is not None
before_version = int(order_task.progress_version or 1)
try:
confirm_review_case(
user_id=user.id,
case_no=case.case_no,
expected_draft_version=1,
idempotency_key='review-no-inventory-1',
)
except Exception as exc:
# 关键断言:库存源硬门禁专用错误码(非泛化 VALIDATION_FAILED)。
assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED'
else:
raise AssertionError('confirm without inventory source must be rejected')
assert ShippingNotice.query.filter_by(source_type='review_confirmation').count() == 0
db.session.refresh(order_task)
assert str(order_task.stage or '') == 'inventory_source_resolving'
assert str(order_task.status or '') == 'blocked'
assert int(order_task.progress_version or 1) > before_version
assert ShippingOrderTask.query.filter_by(task_no=order_task.task_no).count() == 1
def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app):
"""重路由读取最新规则与启停状态;人工决定不被静默覆盖;同幂等键只生效一次。"""
@@ -1118,3 +1251,183 @@ def test_inventory_routing_keep_manual_clears_pending_suggestion(app):
assert proj['selection_mode'] == 'manual'
assert proj['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
assert proj.get('suggestion_pending') is False
def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app):
"""
充足完整行可先行建单;同 PDF 第二波次不被精确重复检查阻断;同行不可重复入波次。
"""
from app.core.errors import ConflictError
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-MULTI-WAVE')
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]
# 行 A 完整;行 B 缺 qty → 整单 needs_review,但 A 应可先行。
unit.result_json = {'orders': [{'header_fields': [], 'lines': [
{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'WA001'}]},
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092901'}]},
]},
{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'WB002'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092902'}]},
]},
]}]}
db.session.add(ShippingOrderCandidate(
candidate_no='CAND-REVIEW-MULTI-WAVE', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-multi-wave', 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()
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)]
assert len(lines) == 2
key_a = str(lines[0].get('line_key') or '').strip()
key_b = str(lines[1].get('line_key') or '').strip()
assert key_a and key_b
whole = validate_draft(
user_id=user.id,
case_no=case.case_no,
expected_draft_version=int(case.current_draft.draft_version),
)
assert whole['draft']['build_eligibility']['status'] == 'needs_review'
_summary, wave_validation = build_confirmable_draft_summary(case, line_keys=[key_a])
# 关键断言:按选中行重算后,充足完整行可建单,不被兄弟行拖垮。
assert wave_validation.get('status') == 'ready'
assert wave_validation.get('can_build') is True
assert len(wave_validation.get('line_projections') or []) == 1
first = confirm_review_case(
user_id=user.id,
case_no=case.case_no,
expected_draft_version=int(case.current_draft.draft_version),
idempotency_key='review-wave-1',
line_keys=[key_a],
warning_acknowledgements=[{'code': 'manual_checked'}],
)
db.session.commit()
db.session.refresh(case)
task1 = ShippingNotice.query.filter_by(task_no=first['task_no']).one()
assert case.status == 'ready'
assert ShippingOrderReviewWaveLine.query.filter_by(
review_case_id=case.id, line_key=key_a, task_id=task1.id,
).count() == 1
with pytest.raises(ConflictError) as dup_exc:
confirm_review_case(
user_id=user.id,
case_no=case.case_no,
expected_draft_version=int(case.current_draft.draft_version),
idempotency_key='review-wave-dup-line',
line_keys=[key_a],
warning_acknowledgements=[{'code': 'manual_checked'}],
)
# 关键断言:同一明细行不可进入第二个 Task(数据库唯一约束)。
assert dup_exc.value.code == 'SHIPPING.REVIEW_LINE_ALREADY_IN_TASK'
db.session.rollback()
db.session.refresh(case)
# 补齐行 B 后发起第二波次(同 PDF content_hash)。
patched = patch_line_field(
user_id=user.id,
case_no=case.case_no,
line_key=key_b,
field_id='qty-id',
value='3',
expected_draft_version=int(case.current_draft.draft_version),
)
second = confirm_review_case(
user_id=user.id,
case_no=case.case_no,
expected_draft_version=patched['draft']['draft_version'],
idempotency_key='review-wave-2',
line_keys=[key_b],
warning_acknowledgements=[{'code': 'manual_checked'}],
)
db.session.commit()
db.session.refresh(case)
task2 = ShippingNotice.query.filter_by(task_no=second['task_no']).one()
# 关键断言:第二波次成功且 Task 不同;同文件哈希不阻断同 Case 波次。
assert task2.id != task1.id
assert task1.source_content_hash == task2.source_content_hash == document.content_hash
assert ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).count() == 2
assert ShippingOrderReviewWaveLine.query.filter_by(review_case_id=case.id).count() == 2
assert case.status == 'confirmed'
def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app):
"""精确重复检查可豁免同 Case 既有波次 Task,仍阻断无关进行中任务。"""
from app.services.shipping_notice.batch_create_idempotency import assert_no_exact_duplicate_notices
from app.core.errors import ConflictError
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-DEDUP-WAVE')
content_hash = str(document.content_hash or '').strip().lower()
assert content_hash
own = ShippingNotice(
task_no='SN-WAVE-OWN',
user_id=user.id,
source_type='review_confirmation',
source_content_hash=content_hash,
process_status='parsed',
)
other = ShippingNotice(
task_no='SN-WAVE-OTHER',
user_id=user.id,
source_type='manual',
source_content_hash=content_hash,
process_status='parsed',
)
db.session.add_all([own, other])
db.session.commit()
assert_no_exact_duplicate_notices(
int(user.id),
[{
'source_content_hash': content_hash,
'source_file_name': document.filename,
'duplicate_resolution_type': 'normal',
}],
exclude_task_ids={int(own.id), int(other.id)},
)
with pytest.raises(ConflictError) as exc:
assert_no_exact_duplicate_notices(
int(user.id),
[{
'source_content_hash': content_hash,
'source_file_name': document.filename,
'duplicate_resolution_type': 'normal',
}],
exclude_task_ids={int(own.id)},
)
assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
del agent, session, intake
+1 -1
View File
@@ -476,7 +476,7 @@ def test_order_field_retire_is_blocked_by_v2_coordinate_profile(app):
db.session.add(ShippingOrderDocumentProfile(
profile_code='V2_REFERENCE', display_name='V2 reference', version=1, status='draft',
schema_version_id=version['id'], structure_fingerprint='a' * 64,
definition_json={'contract_version': 'order_coordinate_profile.v2', 'table_regions': [{
definition_json={'table_regions': [{
'header_layouts': [], 'line_layouts': [{'field_regions': [{'field_id': field['id']}]}],
}]}, lock_version=1,
))
Loaded 100 of 571 files, more files were not shown because too many files have changed in this diff. Show more