feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力

This commit is contained in:
hugo committed 2026-07-27 09:11:25 +08:00
1 parent d62f5107b2
commit 93777fd6df
63 files changed
+9707 -1491

No files matched your search

@@ -58,7 +58,13 @@ def _parsing_profile() -> dict:
state = order_schema_service.get_state()
if state['schema'] is None:
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
fields = {item['field_code']: item for item in order_schema_service.get_state()['fields']}
# 解析 Profile 仅需要这两个订单行匹配键;不能把当前目录的所有字段
# 带进最小 Schema,以免其类型专用 normalizer 影响本服务测试。
fields = {
item['field_code']: item
for item in order_schema_service.get_state()['fields']
if item['field_code'] in {'part_number', 'reservation_id'}
}
for code in ('part_number', 'reservation_id'):
if code not in fields:
fields[code] = order_schema_service.save_field(
@@ -68,7 +74,8 @@ def _parsing_profile() -> dict:
schema_draft = order_schema_service.create_draft({}, actor_id=None)
saved_schema = order_schema_service.save_draft(schema_draft['id'], {'fields': [{
'field_id': field['id'], 'display_name': code, 'required': True, 'aliases': [],
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
'normalizer_key': 'decimal' if field['value_type'] == 'decimal' else 'trim',
'validator_keys': [], 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_table'],
'conflict_policy': 'block', 'allow_single_source': True,
@@ -491,8 +498,8 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED'
def test_publish_rule_rejects_missing_or_disabled_source(app):
"""发布规则只能引用启用库存源,避免运行期落入无法确认的伪候选。"""
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
@@ -502,15 +509,21 @@ def test_publish_rule_rejects_missing_or_disabled_source(app):
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
reservation_field_id = _published_route_field_id()
for index, code in enumerate(('MISSING_SOURCE', 'DISABLED_ROUTE_SOURCE'), start=1):
rule = shipping_inventory_service.save_rule({
'rule_code': f'INVALID_SOURCE_{index}', 'rule_name': 'Invalid source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [code]},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': str(index)}],
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
missing_rule = shipping_inventory_service.save_rule({
'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
disabled_rule = shipping_inventory_service.save_rule({
'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}],
}, actor_id=None)
assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
valid_rule = shipping_inventory_service.save_rule({
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
+180 -1
View File
@@ -39,7 +39,7 @@ from app.services.admin.agent_service import update_agent_permissions
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.admin.agent_service import list_agents
from app.services.shipping_notice.order_extraction_workflow import (
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
_cross_page_anchor_matches, build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
parse_order_extraction_workflow_result, validate_unit_orders,
)
from app.services.shipping_notice.order_extraction_run_service import (
@@ -51,6 +51,31 @@ from app.services.shipping_notice.order_extraction_run_service import (
from tests.test_shipping_order_extraction_runs import _seed_run_input
def test_cross_page_coordinate_continuation_requires_frozen_relation_anchor_and_region():
"""续页锚点须在声明区域命中;整页出现相同文本不足以授权跨页合并。"""
profile = {'definition': {'document_match': {'required_anchors': [{
'anchor_id': 'continued', 'text': 'CONTINUED', 'match_mode': 'exact',
'region': {'x0': 0, 'y0': 0, 'x1': .5, 'y1': .5},
}]}}}
layout = {'coordinate_evidence': {
'tables': {'page-two': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate('CONTINUED')
]},
'pages': {'2': {'width': 200, 'height': 200}},
}}
assert _cross_page_anchor_matches(
raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout,
anchor_ids=['continued'],
) is True
profile['definition']['document_match']['required_anchors'][0]['region'] = {'x0': .5, 'y0': .5, 'x1': 1, 'y1': 1}
assert _cross_page_anchor_matches(
raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout,
anchor_ids=['continued'],
) is False
def test_binding_rejects_non_internal_or_non_workflow_provider(app):
"""订单抽取 Provider 必须是启用的 internal Dify Workflow,不能绑定普通 Chatflow。"""
with app.app_context():
@@ -757,6 +782,160 @@ def test_approved_profile_builds_order_from_its_own_parsed_rows(app):
assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30
def test_coordinate_v2_profile_builds_from_frozen_coordinates_without_html(app):
"""v2 运行只消费冻结 bbox/字符证据;MinerU HTML 缺失也不得回退为固定列解析。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-V2')
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
version.definition_json = {'fields': [
{
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal',
'enabled': True, 'required': True, 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
},
{
'field_id': 'uom-id', 'field_code': 'uom', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
]}
def glyphs() -> list[dict]:
values = []
for text, x0 in [('00010', 10), ('PART-A', 90), ('3 EA', 210)]:
for offset, char in enumerate(text):
values.append({'text': char, 'bbox': {
'x0': x0 + offset * 4, 'y0': 20, 'x1': x0 + offset * 4 + 3, 'y1': 30,
}})
return values
definition = {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'main_lines', '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',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .3, 'y0': 0, 'x1': .7, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'extractor_key': 'quantity_uom', 'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}, {'field_id': 'uom-id', 'field_code': 'uom'}], 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number', 'qty', 'uom'], 'allowed_empty_fields': [],
}],
}],
}
profile = ShippingOrderDocumentProfile(
profile_code='COORDINATE_V2', display_name='Coordinate v2', version=1, status='published',
schema_version_id=version.id, structure_fingerprint='c' * 64, checksum='d' * 64,
definition_json=definition, published_at=datetime.utcnow(),
)
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'coordinate-only', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 300, 'y1': 60}}],
'coordinate_evidence': {
'tables': {'coordinate-only': glyphs()},
'pages': {'1': {'width': 300, 'height': 60}},
},
})
db.session.add(profile)
db.session.commit()
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
unit = run.extraction_plan.units[0]
run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True
from app.services.shipping_notice.order_extraction_workflow import (
_build_approved_profile_order,
_profile_table_candidates,
build_deterministic_unit_orders,
)
candidates = _profile_table_candidates(run, unit=unit)
assert candidates['blocking'] is False, candidates
assert candidates['tables'] and candidates['tables'][0]['auto_create_approved'] is True, candidates
direct = _build_approved_profile_order(
unit=unit, intake=run.input_snapshot_json['intakes'][0],
schema=run.input_snapshot_json['schema']['extraction_contract'],
definition=run.input_snapshot_json['schema']['definition'], table=candidates['tables'][0],
)
assert direct is not None, candidates
orders = build_deterministic_unit_orders(run, unit=unit)
assert orders is not None
fields = {field['field_id']: field['observations'][0]['value'] for field in orders[0]['lines'][0]['fields']}
assert fields == {'line-id': '00010', 'part-id': 'PART-A', 'qty-id': 3, 'uom-id': 'EA'}
def test_coordinate_v2_profile_uses_page_relative_regions_not_table_bbox(app):
"""画布保存整页相对区域;运行时不得再按 MinerU 表格 bbox 二次缩放。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-PAGE-SPACE')
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
version.definition_json = {'fields': [
{
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': False, 'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
]}
profile = ShippingOrderDocumentProfile(
profile_code='COORDINATE_PAGE_SPACE', display_name='Coordinate page space', version=1, status='published',
schema_version_id=version.id, structure_fingerprint='e' * 64, checksum='f' * 64,
definition_json={
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'main_lines', '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',
# This real canvas region is page-relative (x=20..80 on a 200pt page),
# while MinerU's table bbox begins at x=50 and must not offset it again.
'region': {'x0': .1, 'y0': .4, 'x1': .4, 'y1': .6},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': .1, 'y0': .4, 'x1': .2, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .2, 'y0': .4, 'x1': .4, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']},
], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number'], 'allowed_empty_fields': [],
}],
}],
}, published_at=datetime.utcnow(),
)
glyphs = []
for text, x0 in [('00010', 22), ('PART-PAGE', 45)]:
for offset, char in enumerate(text):
glyphs.append({'text': char, 'bbox': {'x0': x0 + offset * 4, 'y0': 90, 'x1': x0 + offset * 4 + 3, 'y1': 100}})
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'offset-table', 'page_no': 1, 'bbox': {'x0': 50, 'y0': 70, 'x1': 160, 'y1': 140}}],
'coordinate_evidence': {'tables': {'offset-table': glyphs}, 'pages': {'1': {'width': 200, 'height': 200}}},
})
db.session.add(profile)
db.session.commit()
run, _ = create_order_extraction_run(user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no])
unit = run.extraction_plan.units[0]
run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
orders = build_deterministic_unit_orders(run, unit=unit)
assert orders is not None
values = {
field['field_id']: field['observations'][0]['value']
for field in orders[0]['lines'][0]['fields']
}
assert values['part-id'] == 'PART-PAGE'
def test_plain_text_complete_table_still_uses_provider(app):
"""纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。"""
with app.app_context():
+257
View File
@@ -582,6 +582,263 @@ def test_summarize_inventory_batch_results_empty():
}
def test_real_upload_requires_explicit_enablement(monkeypatch, tmp_path):
"""未显式开启上传浏览器自动化时,不得打开货代页面或提交文件。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false")
with pytest.raises(RuntimeError, match="upload RPA is disabled"):
worker._upload_shipment_with_browser(workbook)
def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch, tmp_path):
"""真实上传只能在页面成功标识可见后回传可选货代回执。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL", "https://freight.example/upload")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR", "#file")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR", "#submit")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR", "#success")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR", "#receipt")
events: list[tuple[str, object]] = []
class _Locator:
def __init__(self, selector: str):
self.selector = selector
self.first = self
def set_input_files(self, value: str, **_kwargs) -> None:
events.append(("file", value))
def click(self, **_kwargs) -> None:
events.append(("submit", self.selector))
def wait_for(self, **_kwargs) -> None:
events.append(("success", self.selector))
def text_content(self, **_kwargs) -> str:
return "FREIGHT-REF-001"
class _Page:
def goto(self, url: str, **_kwargs) -> None:
events.append(("goto", url))
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
class _Context:
def close(self) -> None:
events.append(("context_close", None))
class _Playwright:
def stop(self) -> None:
events.append(("playwright_stop", None))
runtime_profile = tmp_path / "profile"
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"
assert events[:4] == [
("goto", "https://freight.example/upload"),
("file", str(workbook)),
("submit", "#submit"),
("success", "#success"),
]
def test_dsv_upload_navigates_from_my_applications_before_setting_file(monkeypatch, tmp_path):
"""DSV 上传必须复用登录态,并优先使用截图确认的 My Applications 入口。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
events: list[tuple[str, object]] = []
class _Locator:
def __init__(self, selector: str):
self.selector = selector
self.first = self
def wait_for(self, **_kwargs) -> None:
events.append(("wait", self.selector))
def click(self, **_kwargs) -> None:
events.append(("click", self.selector))
def set_input_files(self, _value: str, **_kwargs) -> None:
events.append(("file", self.selector))
class _Page:
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
def get_by_text(self, text: str, **_kwargs) -> _Locator:
return _Locator(text)
class _Context:
def close(self) -> None:
events.append(("context_close", None))
class _Playwright:
def stop(self) -> None:
events.append(("playwright_stop", None))
runtime_profile = tmp_path / "profile"
runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}")
assert worker._upload_shipment_with_browser(
workbook, connector_type="dbs", dsv_entry_url="https://dsv.example/portal"
) == "REF-shipment.xlsx"
assert events[0] == ("session", "https://dsv.example/portal")
assert any(event == ("click", ":has-text(\"My Applications\") a:has-text('Upload Tool')") for event in events)
assert ("file", "#file2") in events
assert ("click", 'button.upload-button:has-text("Process File")') in events
def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
"""DSV History 缺绿色状态或 Reference # 时,不得把文件提交误报为上传成功。"""
worker = _load_freight_rpa_worker()
class _Locator:
first = None
def __init__(self):
self.first = self
def click(self, **_kwargs) -> None:
return None
class _Page:
def get_by_text(self, _text: str, **_kwargs) -> _Locator:
return _Locator()
def evaluate(self, _script: str, _arg: dict) -> dict:
return {"found": True, "succeeded": False, "reference": "556833"}
monkeypatch.setattr(worker.time, "sleep", lambda _seconds: None)
clock = {"value": 0.0}
def monotonic() -> float:
clock["value"] += 2.0
return clock["value"]
monkeypatch.setattr(worker.time, "monotonic", monotonic)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
with pytest.raises(RuntimeError, match="did not confirm a green success status"):
worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx")
def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeypatch):
"""History 的绿色同名行与非空 Reference # 必须原样作为 DSV 上传回执返回。"""
worker = _load_freight_rpa_worker()
class _Locator:
first = None
def __init__(self):
self.first = self
def click(self, **_kwargs) -> None:
return None
class _Page:
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 test_dsv_upload_falls_back_to_apps_menu(monkeypatch):
"""首页入口缺失时,DSV 仅可退回已确认的 Apps > Upload Tool 路径。"""
worker = _load_freight_rpa_worker()
events: list[str] = []
class _Locator:
def __init__(self, selector: str):
self.selector = selector
self.first = self
def wait_for(self, **_kwargs) -> None:
if "My Applications" in self.selector:
raise RuntimeError("homepage tile missing")
def click(self, **_kwargs) -> None:
events.append(self.selector)
class _Page:
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
def get_by_text(self, _text: str, **_kwargs) -> _Locator:
return _Locator("WMS Upload Tool")
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda *_args: events.append("session"))
worker._navigate_dsv_to_upload_tool(_Page(), "https://dsv.example/portal")
assert events[0] == "session"
assert "nav a:has-text('Apps')" in events
assert "a:has-text('Upload Tool')" in events
def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
"""浏览器上传未获成功证据时必须失败回调,不能遗留无限等待的 trigger。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "upload_triggers"
trigger_dir.mkdir()
trigger_path = trigger_dir / "upload_SN-UPLOAD-FAIL.json"
queue_file = tmp_path / "shipment.xlsx"
queue_file.write_bytes(b"test")
trigger_path.write_text(json.dumps({
"task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8",
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda _path: (_ for _ in ()).throw(RuntimeError("success marker missing")))
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
assert callbacks == [("/api/shipping-notice/rpa/upload-complete", {
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8", "success": False,
"error_message": "success marker missing",
})]
assert (trigger_dir / "processed" / trigger_path.name).is_file()
def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
"""空上传路径必须直接失败回调,禁止把当前目录传给浏览器文件控件。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "upload_triggers"
trigger_dir.mkdir()
trigger_path = trigger_dir / "upload_SN-UPLOAD-EMPTY.json"
trigger_path.write_text(json.dumps({
"task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9",
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
assert callbacks[0][1]["success"] is False
assert callbacks[0][1]["error_message"] == "queue file missing: <empty>"
def test_summarize_inventory_batch_results_skipped_and_failed():
"""仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
worker = _load_freight_rpa_worker()
@@ -9,7 +9,10 @@ from __future__ import annotations
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
reconstruct_coordinate_profile_rows,
reconstruct_table_from_positioned_text,
suggest_header_layouts,
suggest_header_regions,
suggest_multi_subrow_layouts,
)
from app.services.shipping_notice.document_layout.order_profile import (
@@ -22,6 +25,11 @@ from app.services.shipping_notice.document_layout.order_profile import (
)
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.order_extraction_workflow import (
_build_approved_profile_order,
_validate_table_header_outputs,
)
from types import SimpleNamespace
def _glyphs(*rows: list[tuple[str, float]]) -> list[dict]:
@@ -50,6 +58,615 @@ def _reconstruct(characters: list[dict]):
)
def test_header_suggestions_only_return_unique_schema_aliases():
"""表头建议只能使用当前 Schema 的唯一精确别名,位置相近或歧义均保持未映射。"""
suggestions = suggest_header_layouts(
characters=_glyphs([('Quantity', 20), ('Part No.', 120)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
header_layouts=[{'layout_id': 'header_one', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .2}, 'field_regions': [
{'region': {'x0': 0, 'y0': 0, 'x1': .45, 'y1': 1}},
{'region': {'x0': .45, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
schema_fields=[
{'field_code': 'qty', 'display_name': 'Quantity', 'aliases': ['Qty']},
{'field_code': 'part_number', 'display_name': 'Part No.', 'aliases': []},
{'field_code': 'customer_part_number', 'display_name': 'Part No.', 'aliases': []},
],
)
# Quantity 唯一命中;Part No. 同时属于两个 Schema 字段,因此不得猜测归属。
assert suggestions[0].fields[0].model_dump() == {'field_code': 'qty', 'text': 'Quantity', 'confidence': 'exact_alias'}
assert suggestions[0].fields[1].model_dump()['field_code'] is None
def test_unbound_header_region_can_suggest_a_schema_field():
"""未绑定表头框必须直接读取自身区域,并仅返回唯一 Schema 别名供管理员确认。"""
suggestions = suggest_header_layouts(
characters=_glyphs([('DELI. DATE', 120)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
header_layouts=[{
'layout_id': 'delivery_header',
'region': {'x0': .55, 'y0': 0, 'x1': 1, 'y1': .4},
'field_regions': [],
}],
schema_fields=[{
'field_code': 'requested_receipt_date',
'display_name': 'Delivery Date',
'aliases': ['DELI. DATE'],
}],
)
# 断言无需预先创建表头子字段框,也能形成待确认的精确别名建议。
assert suggestions[0].fields[0].text == 'DELI. DATE'
assert suggestions[0].fields[0].field_code == 'requested_receipt_date'
assert suggestions[0].fields[0].confidence == 'exact_alias'
def test_auto_header_regions_stop_before_first_detail_row():
"""自动标记只框选首条明细前的独立表头,不能把业务数据当成表头。"""
suggestions = suggest_header_regions(
characters=_glyphs(
[('Item', 10), ('Material', 65), ('Quantity', 150)],
[('Description', 10), ('Delivery Date', 120)],
[('00010', 10), ('PART-A', 65), ('3', 160)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
)
assert [item.text for item in suggestions] == [
'Item Material Quantity', 'Description Delivery Date',
]
assert suggestions[0].region.y1 < suggestions[1].region.y0
def test_auto_header_regions_recognize_compact_pdf_header_words():
"""PDF 丢失表头词间空格时,仍应识别独立表头行。"""
suggestions = suggest_header_regions(
characters=_glyphs(
[('ITEMNO', 10), ('MATERIALNO', 65), ('UNITPRICE', 140)],
[('00010', 10), ('PART-A', 65), ('3.00', 150)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
)
assert len(suggestions) == 1
assert suggestions[0].text == 'ITEMNO MATERIALNO UNITPRICE'
def test_subrow_suggestion_uses_one_record_for_vertical_samples():
"""多条明细只能增强列边界,不能把样例子行纵向范围拉伸到后续记录。"""
suggestions = suggest_multi_subrow_layouts(
characters=_glyphs(
[('00010', 10), ('PART-A', 65)],
[('2026-08-01', 120)],
[('00020', 10), ('PART-B', 65)],
[('2026-08-02', 120)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
)
assert len(suggestions) == 2
assert suggestions[0].y1 < suggestions[1].y0
def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
"""v2 主行必须有行号,续行按 row_offset 合并,合计或额外文本不得混入明细。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-A', 65), ('5', 160)],
[('Delivery', 65), ('2026-08-01', 150)],
[('TOTAL AMOUNT', 65)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'continuation', 'row_offset': 1, 'field_regions': [
{'field_code': 'required_date', 'region': {'x0': .65, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
],
)
assert len(rows) == 1
assert rows[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
def test_coordinate_profile_row_layout_repeats_across_the_table():
"""物理行框是可重复版式样例;同一字段横向边界必须读取后续明细而非只命中标注时的绝对 Y。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-A', 65)],
[('00020', 10), ('PART-B', 65)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
table_region={'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .25, 'y1': .35}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': .15, 'x1': .75, 'y1': .35}},
]}],
)
# 断言样例框的 X 版式重复应用到第二条明细,Y 只用于表达该物理子行的相对顺序。
assert [row.fields for row in rows] == [
{'line_no': '00010', 'part_number': 'PART-A'},
{'line_no': '00020', 'part_number': 'PART-B'},
]
def test_coordinate_profile_rows_apply_registered_composite_extractors_atomically():
"""qty/uom、金额/币种和单价/币种必须成对拆分;格式无效时不写入任何半截字段。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('00010', 10), ('3 EA', 65), ('USD 10.50', 115), ('12.00 USD', 165)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 60},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'extractor_key': 'direct', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}},
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .2, 'y0': 0, 'x1': .5, 'y1': 1}},
{'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency', 'region': {'x0': .5, 'y0': 0, 'x1': .75, 'y1': 1}},
{'field_code': 'unit_price', 'extractor_key': 'price_currency', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
)
assert rows[0].fields == {
'line_no': '00010', 'qty': '3', 'uom': 'EA', 'line_amount_before_tax': '10.50',
'currency': 'USD', 'unit_price': '12.00',
}
invalid = reconstruct_coordinate_profile_rows(
characters=_glyphs([('00010', 10), ('not-a-quantity', 65)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
)
assert invalid[0].fields == {'line_no': '00010'}
def test_coordinate_profile_rows_marks_conflicting_composite_values_for_review():
"""同一逻辑明细中的复合字段冲突必须留痕,不能以后到值静默覆盖前值。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('00010', 10), ('3 EA', 65)], [('4 PCS', 65)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 80},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'continuation', 'row_offset': 1, 'field_regions': [
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
],
)
assert rows[0].fields['qty'] == '3'
assert 'coordinate_profile_composite_conflict:qty' in rows[0].issues
def test_coordinate_profile_rows_treat_vertical_regions_as_repeatable_layout_samples():
"""物理行纵向框表达子行顺序而非绝对页坐标,模板才能重复读取后续明细。"""
base_layouts = [
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'continuation', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
{'field_code': 'required_date', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
]
characters = _glyphs([('00010', 10), ('PART-A', 65)], [('2026-08-01', 100)])
matched = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=base_layouts,
)
assert matched[0].fields['required_date'] == '2026-08-01'
base_layouts[1]['region']['y0'] = .6
base_layouts[1]['region']['y1'] = .8
repeated = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=base_layouts,
)
# 断言只要 row_offset 顺序有效,示例框移动不会把模板退化为只能识别一条绝对 Y 行。
assert repeated[0].fields['required_date'] == '2026-08-01'
def test_coordinate_profile_rows_reject_swapped_physical_region_order():
"""字段绑定不变但物理行区域错序时必须阻断,不能仅因 y 顺序相邻而合并。"""
characters = _glyphs(
[('00010', 10), ('PART-A', 65)],
[('2026-08-01', 100)],
[('By Truck', 100)],
)
layouts = [
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'delivery', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
{'field_code': 'required_date', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'shipping', 'row_offset': 2, 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': .75}, 'field_regions': [
{'field_code': 'shipway', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
]
correct = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=layouts,
)
assert correct[0].fields['shipway'] == 'By Truck'
# Retain each layout's fields but assign the delivery layout to the shipping band.
layouts[1]['region'], layouts[2]['region'] = layouts[2]['region'], layouts[1]['region']
rejected = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=layouts,
)
assert rejected[0].fields == {'line_no': '00010', 'part_number': 'PART-A'}
assert rejected[0].issues == ['coordinate_profile_layout_region_mismatch']
def test_coordinate_profile_rows_restore_pdf_visual_spaces():
"""原生 PDF 未持久化空格时按字符间距恢复字段原文,供受控解析器与证据复核使用。"""
characters = _glyphs([('00010', 10), ('By', 65), ('Truck', 81)])
rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'shipway', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
)
assert rows[0].fields['shipway'] == 'By Truck'
def test_coordinate_profile_rows_discard_the_prior_record_for_explicit_deleted_marker():
"""`** Item deleted **` 只能废弃前一条已启动明细,不能作为下一条或独立明细。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-DELETED', 65)],
[('** Item deleted **', 65)],
[('00020', 10), ('PART-KEEP', 65)],
[('TOTAL AMOUNT', 65)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
)
assert [row.fields for row in rows] == [{'line_no': '00020', 'part_number': 'PART-KEEP'}]
def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schema_fields():
"""脱敏回放 F9A1:四条物理行只合并为一条,并只读取已绑定的标准字段。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('541-000175-007', 50), ('B3-A08AR10000018-A7', 190)],
[('AWS', 45), ('48.5U', 65), ('RACK', 92), ('175-007', 118), ('WELLTRUST', 150),
('3.000', 195), ('PCS', 220), ('2026/05/05', 245)],
[('EXW', 45), ('SGSIN', 62), ('DBS', 86), ('1,645.11000', 200), ('4,935.33', 250)],
[('R2_SA;HF_SA;EF_SA', 45), ('ASG_S-ENCWIW260412386643', 120), ('@', 240), ('3000092530', 250)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 100},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .3}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .12, 'y1': 1}},
{'field_code': 'customer_part_number', 'region': {'x0': .12, 'y0': 0, 'x1': .58, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .58, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'quantity_delivery', 'row_offset': 1, 'region': {'x0': 0, 'y0': .3, 'x1': 1, 'y1': .44}, 'field_regions': [
{'field_code': 'qty', 'region': {'x0': .62, 'y0': 0, 'x1': .71, 'y1': 1}},
{'field_code': 'uom', 'region': {'x0': .71, 'y0': 0, 'x1': .78, 'y1': 1}},
{'field_code': 'required_date', 'region': {'x0': .78, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'terms_pricing', 'row_offset': 2, 'region': {'x0': 0, 'y0': .44, 'x1': 1, 'y1': .58}, 'field_regions': [
{'field_code': 'incoterm', 'region': {'x0': .12, 'y0': 0, 'x1': .45, 'y1': 1}},
{'field_code': 'unit_price', 'region': {'x0': .62, 'y0': 0, 'x1': .82, 'y1': 1}},
{'field_code': 'line_amount_before_tax', 'region': {'x0': .82, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'reservation', 'row_offset': 3, 'region': {'x0': 0, 'y0': .58, 'x1': 1, 'y1': .75}, 'field_regions': [
{'field_code': 'reservation_id', 'region': {'x0': .76, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
],
)
assert len(rows) == 1
assert rows[0].source_row_indices == [0, 1, 2, 3]
assert rows[0].fields == {
'line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
'qty': '3.000', 'uom': 'PCS', 'required_date': '2026/05/05', 'incoterm': 'EXW SGSIN DBS',
'unit_price': '1,645.11000', 'line_amount_before_tax': '4,935.33', 'reservation_id': '@ 3000092530',
}
def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line():
"""一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('B3-A08AR10000018-A7', 120)],
[('3.000', 124), ('PCS', 158), ('2026/05/05', 190)],
[('1,645.11000', 124), ('4,935.33', 220)],
[('20', 10), ('B3-A08AR10000027-A9', 120)],
[('8.000', 124), ('EA', 158), ('2026/06/01', 190)],
[('2,100.00000', 124), ('16,800.00', 220)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 120},
line_layouts=[{
'layout_id': 'detail',
'row_offset': 0,
'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .48},
'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .12, 'y1': .25}},
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .15, 'x1': 1, 'y1': .25}},
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .26, 'x1': .52, 'y1': .36}},
{'field_code': 'uom', 'region': {'x0': .52, 'y0': .26, 'x1': .63, 'y1': .36}},
{'field_code': 'requested_receipt_date', 'region': {'x0': .63, 'y0': .26, 'x1': 1, 'y1': .36}},
{'field_code': 'unit_price', 'region': {'x0': .38, 'y0': .37, 'x1': .72, 'y1': .48}},
{'field_code': 'line_amount_before_tax', 'region': {'x0': .72, 'y0': .37, 'x1': 1, 'y1': .48}},
],
}],
)
# 数量与单位不得从同一横向范围内、但位于首视觉行的内部料号尾数读取。
assert [row.fields for row in rows] == [
{
'line_no': '10', 'part_number': 'B3-A08AR10000018-A7', 'qty': '3.000', 'uom': 'PCS',
'requested_receipt_date': '2026/05/05', 'unit_price': '1,645.11000',
'line_amount_before_tax': '4,935.33',
},
{
'line_no': '20', 'part_number': 'B3-A08AR10000027-A9', 'qty': '8.000', 'uom': 'EA',
'requested_receipt_date': '2026/06/01', 'unit_price': '2,100.00000',
'line_amount_before_tax': '16,800.00',
},
]
deleted = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('B3-A08AR10000018-A7', 120)],
[('3.000', 124), ('PCS', 158)],
[('** Item deleted **', 30)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 80},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0,
'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .65},
'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .12, 'y1': .35}},
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .2, 'x1': 1, 'y1': .35}},
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .36, 'x1': .52, 'y1': .5}},
],
}],
)
assert deleted == []
def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_parent_whitespace():
"""父物理行含底部留白时应复用样例视觉子行偏移,不能按高度缩放把字段投到行间。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('6Y70B2501901', 55), ('0', 205), ('EA', 225)],
[('D4-A08AR12000002', 55), ('06/22/2026', 170)],
[('RoHS2', 20), ('EXW AWS HUB', 105)],
[], [], [],
[('00020', 10), ('6Y70B2501901', 55), ('30', 205), ('EA', 225)],
[('D4-A08AR12000002', 55), ('06/29/2026', 170)],
[('RoHS2', 20), ('EXW AWS HUB', 105)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 160},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0,
# 样例父框包含第三子行后的留白;线性压缩会让第二子行字段落入空白。
'region': {'x0': 0, 'y0': .05, 'x1': 1, 'y1': .53},
'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .12, 'x1': .2, 'y1': .19}},
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .12, 'x1': .64, 'y1': .19}},
{'field_code': 'qty', 'region': {'x0': .76, 'y0': .12, 'x1': .86, 'y1': .19}},
{'field_code': 'uom', 'region': {'x0': .86, 'y0': .12, 'x1': 1, 'y1': .19}},
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .21, 'x1': .64, 'y1': .28}},
{'field_code': 'requested_receipt_date', 'region': {'x0': .64, 'y0': .21, 'x1': 1, 'y1': .28}},
],
}],
)
assert [row.fields for row in rows] == [
{
'line_no': '00010', 'customer_part_number': '6Y70B2501901', 'qty': '0', 'uom': 'EA',
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/22/2026',
},
{
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/29/2026',
},
]
def test_coordinate_profile_rows_calibrate_unbound_visual_bands_from_sample_evidence():
"""字段之间存在未标注描述行时,必须按样例字符证据校准真实 band,不能压缩字段序号。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('CUSTOMER-A', 55)],
[('UNBOUND DESCRIPTION', 55)],
[('PART-A', 55)],
[('00020', 10), ('CUSTOMER-B', 55)],
[('UNBOUND DESCRIPTION', 55)],
[('PART-B', 55)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 120},
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .2, 'y1': .25}},
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .15, 'x1': .6, 'y1': .25}},
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .38, 'x1': .6, 'y1': .48}},
]}],
)
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_band():
"""某条明细多出未标注换行时,应以格式和顺序重新对齐,不能把描述静默写入料号。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('CUSTOMER-A', 55)],
[('PART-A', 55)],
[('00020', 10), ('CUSTOMER-B', 55)],
[('WRAPPED DESCRIPTION', 55)],
[('PART-B', 55)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
]}],
)
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
"""额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('CUSTOMER-A', 55)],
[('PART-A', 55)],
[('00020', 10), ('CUSTOMER-B', 55)],
[('ALT-1', 55)],
[('ALT-2', 55)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
]}],
)
assert rows[1].fields.get('part_number') is None
assert 'coordinate_profile_field_band_ambiguous:part_number' in rows[1].issues
def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary():
"""脱敏回放 4518838152:删除标记废弃 00010,合计后的记录不允许泄漏。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('6Y70B2501901', 62), ('0', 210), ('EA', 225)],
[('D4-A08AR12000002', 62), ('06/22/2026', 210)],
[('EXW', 62), ('AWS', 80), ('HUB', 98), ('Ship by sea', 180)],
[('** Item deleted **', 62)],
[('00020', 10), ('6Y70B2501901', 62), ('30', 210), ('EA', 225)],
[('D4-A08AR12000002', 62), ('06/29/2026', 210)],
[('EXW', 62), ('AWS', 80), ('HUB', 98), ('Ship by land', 180)],
[('TOTAL AMOUNT', 62), ('28,252.80', 210)],
[('00030', 10), ('MUST-NOT-LEAK', 62)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 160},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .18, 'y1': 1}},
{'field_code': 'customer_part_number', 'region': {'x0': .18, 'y0': 0, 'x1': .7, 'y1': 1}},
{'field_code': 'qty', 'region': {'x0': .7, 'y0': 0, 'x1': .85, 'y1': 1}},
{'field_code': 'uom', 'region': {'x0': .85, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'delivery', 'row_offset': 1, 'field_regions': [
{'field_code': 'part_number', 'region': {'x0': .18, 'y0': 0, 'x1': .7, 'y1': 1}},
{'field_code': 'required_date', 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'terms', 'row_offset': 2, 'field_regions': [
{'field_code': 'incoterm', 'region': {'x0': .18, 'y0': 0, 'x1': .62, 'y1': 1}},
]},
],
)
assert len(rows) == 1
assert rows[0].source_row_indices == [4, 5, 6]
assert rows[0].fields == {
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
'part_number': 'D4-A08AR12000002', 'required_date': '06/29/2026', 'incoterm': 'EXW AWS HUB',
}
def test_coordinate_profile_rows_honor_configured_table_exclusion_and_termination_regions():
"""第 6 阶段:只有配置表区可读;排除区和显式终止锚点均不能流入订单。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('OUTSIDE', 10)],
[('00010', 10), ('PART-A', 65)],
[('SIGNATURE', 65)],
[('STOP HERE', 65)],
[('00020', 10), ('MUST-NOT-LEAK', 65)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
table_region={'x0': 0, 'y0': .3, 'x1': 1, 'y1': .9},
exclusion_regions=[{'x0': 0, 'y0': .45, 'x1': 1, 'y1': .6}],
termination_rules=[{'rule_id': 'stop', 'anchor': {
'anchor_id': 'stop_here', 'text': 'STOP HERE', 'match_mode': 'exact',
'region': {'x0': 0, 'y0': .6, 'x1': 1, 'y1': .75},
}}],
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
)
assert [row.fields for row in rows] == [{'line_no': '00010', 'part_number': 'PART-A'}]
def test_coordinate_profile_rows_can_continue_only_explicit_carry_state_on_next_page():
"""跨页续行由调用方传入已验证的 carry;当前页自身没有主行锚点时不会擅自建行。"""
layouts = [
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
{'layout_id': 'delivery', 'row_offset': 1, 'field_regions': [
{'field_code': 'required_date', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]},
]
page_two = _glyphs([('2026-08-01', 80)])
assert reconstruct_coordinate_profile_rows(
characters=page_two, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, line_layouts=layouts,
) == []
continued = reconstruct_coordinate_profile_rows(
characters=page_two, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, line_layouts=layouts,
initial_fields={'line_no': '00010', 'part_number': 'PART-A'}, initial_next_offset=1,
)
assert continued[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'required_date': '2026-08-01'}
def test_currency_composite_output_becomes_header_only_when_all_rows_agree():
"""行区域产生的币种遵循 Schema Header scope;币种冲突必须拒绝自动建单。"""
definition = {'fields': [
{'field_id': 'line-id', 'field_code': 'part_number', 'scope': 'line', 'enabled': True,
'collection_mode': 'llm_extraction', 'required': True},
{'field_id': 'currency-id', 'field_code': 'currency', 'scope': 'header', 'enabled': True,
'collection_mode': 'llm_extraction', 'required': True},
]}
schema_fields = {item['field_code']: item for item in definition['fields']}
table = {'rows': [
{'status': 'parsed', 'issues': [], 'fields': [
{'field_id': 'line-id', 'field_code': 'part_number', 'value': 'A', 'quote': 'A USD'},
{'field_id': 'currency-id', 'field_code': 'currency', 'value': 'USD', 'quote': 'A USD'},
]},
{'status': 'parsed', 'issues': [], 'fields': [
{'field_id': 'line-id', 'field_code': 'part_number', 'value': 'B', 'quote': 'B USD'},
{'field_id': 'currency-id', 'field_code': 'currency', 'value': 'USD', 'quote': 'B USD'},
]},
]}
assert _validate_table_header_outputs(table['rows'], schema_fields=schema_fields)
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,
)
assert order is not None
assert order['header_fields'][0]['field_id'] == 'currency-id'
assert all('currency-id' not in {field['field_id'] for field in line['fields']} for line in order['lines'])
table['rows'][1]['fields'][1]['value'] = 'EUR'
assert not _validate_table_header_outputs(table['rows'], schema_fields=schema_fields)
assert _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,
) is None
def test_coordinate_reconstruction_uses_x_y_and_continuation_rules():
"""行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。"""
result = _reconstruct(_glyphs(
@@ -210,7 +827,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
'column_field_codes': ['line_no', 'part_number', 'qty']},
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
'column_field_codes': [None, 'required_date', 'remark']},
'column_field_codes': [None, 'required_date', 'line_remark']},
])
html = reconstruct_order_profile_html(
characters=_glyphs(
@@ -221,7 +838,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
reconstruction=settings,
)
grid = parse_html_grid(html, table_id='multi-subrow')
headers = ['line_no', 'part_number', 'qty', 'required_date', 'remark']
headers = ['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),
@@ -237,7 +854,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
{'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': 'remark', 'enabled': True},
{'field_code': 'line_remark', 'enabled': True},
]})
parsed = parse_html_table_with_order_profile(html, table_id='multi-subrow', profile=profile, contract=contract)
@@ -247,7 +864,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
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['remark'] == 'Ship by land'
assert parsed.rows[0].fields['line_remark'] == 'Ship by land'
def test_multi_subrow_profile_supports_four_or_more_physical_rows():
@@ -18,9 +18,12 @@ from app.models import (
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingDocumentProfileTestSuite,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
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
@@ -38,15 +41,20 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', checksum='a' * 64,
published_at=datetime.utcnow(), definition_json={'fields': [
{
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [],
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
'value_type': 'decimal', 'enabled': True, 'required': True,
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], 'allowed_sources': ['pdf_coordinate'],
},
]},
)
@@ -136,6 +144,40 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a
assert getattr(immutable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app):
"""v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2', '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': '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']},
],
}]}],
}
for document in documents:
glyphs = []
for text, x0 in [('00010', 5), ('PN-1', 30), ('3', 150)]:
for index, char in enumerate(text):
glyphs.append({'text': char, 'bbox': {'x0': x0 + index * 4, 'y0': 20, 'x1': x0 + index * 4 + 3, 'y1': 30}})
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': 60}}},
})
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
for document in documents:
quality.add_sample(suite_id=suite['id'], document_id=document.id, table_id='table-1',
expected_rows=[{'line_no': '00010', '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', executed['latest_run']['failure_codes']
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
with app.app_context():
@@ -151,3 +193,165 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
profile.checksum = 'c' * 64
db.session.commit()
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(app):
"""盲测草稿可受控删除样本并留痕,批准后的真值不得再被篡改。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
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,
)
sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
removed = quality.remove_sample(suite_id=suite['id'], sample_id=sample_id, actor_id=user.id)
assert removed['sample_count'] == 0
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
ShippingOrderDocumentProfileAudit.id.desc(),
).first()
assert audit.event_type == 'blind_test_sample_removed'
assert audit.detail_json == {'suite_id': suite['id']}
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,
)
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
immutable_sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
with pytest.raises(Exception) as caught:
quality.remove_sample(suite_id=suite['id'], sample_id=immutable_sample_id, actor_id=user.id)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
def test_draft_publish_requires_independent_training_and_multiline_blind_gate(app):
"""关键断言:发布前必须已有训练样本、独立多明细盲测与审批,不能发布后补门禁。"""
from app.services.shipping_notice import order_document_profile_service as profiles
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.status = 'draft'
profile.checksum = None
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,
))
db.session.commit()
with pytest.raises(Exception) as missing_suite:
profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
assert getattr(missing_suite.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
# Use different documents than the training sample. One sample is real multi-line evidence.
record_inline_layout_snapshot(documents[1], {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr><tr><td>PN-2</td><td>4</td></tr></table>'}],
})
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
{'part_number': 'PN-1', 'qty': 3}, {'part_number': 'PN-2', 'qty': 4},
], actor_id=user.id)
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id)
assert quality.execute_suite(suite_id=suite['id'], actor_id=user.id)['latest_run']['status'] == 'failed'
# A third independent document is necessary even when one sample is multi-line.
extra = ShippingNoticeDocument(
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
attachment_key='quality-extra.pdf', filename='quality-extra.pdf', content_hash='e' * 64,
classification='order_notice', parse_status='parsed', extracted_text='PN-1 3',
)
db.session.add(extra)
db.session.flush()
record_inline_layout_snapshot(extra, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr></table>'}],
})
db.session.commit()
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', 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', executed['latest_run']['failure_codes']
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
# This legacy fixture cannot be republished under the v2-only write contract,
# but its current approved credential proves the draft gate accepts independent evidence.
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.structure_fingerprint)
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
"""关键断言:v2 草稿在训练、独立多明细盲测通过后可发布,并冻结正式 checksum 凭证。"""
from app.services.shipping_notice import order_document_profile_service as profiles
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.status = 'draft'
profile.checksum = None
profile.published_at = None
profile.definition_json = {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .15}, 'field_regions': []}], 'termination_rules': [], 'exclusion_regions': [],
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
'line_layouts': [{
'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': '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']},
],
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
}],
}],
}
def set_coordinate_rows(document: ShippingNoticeDocument, rows: list[tuple[str, str]]) -> None:
"""冻结每个样本的字符坐标,让 v2 盲测不依赖 HTML 网格。"""
glyphs = []
for row_index, (part, qty) in enumerate(rows):
for text, x0 in ((f'{(row_index + 1) * 10:05d}', 5), (part, 30), (qty, 150)):
for index, char in enumerate(text):
glyphs.append({'text': char, 'bbox': {
'x0': x0 + index * 4, 'y0': 20 + row_index * 20,
'x1': x0 + index * 4 + 3, 'y1': 30 + row_index * 20,
}})
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}}},
})
for document in documents:
set_coordinate_rows(document, [('PN-1', '3')])
set_coordinate_rows(documents[1], [('PN-1', '3'), ('PN-2', '4')])
extra = ShippingNoticeDocument(
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',
)
db.session.add(extra)
db.session.flush()
set_coordinate_rows(extra, [('PN-3', '5')])
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,
))
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
# Training document is rejected immediately, not only later at publication time.
with pytest.raises(Exception) as reused:
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)
assert getattr(reused.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}, {'line_no': '00020', 'part_number': 'PN-2', 'qty': '4'},
], actor_id=user.id)
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
assert published['status'] == 'published'
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=published['checksum'])
@@ -0,0 +1,56 @@
"""
backend/tests/test_shipping_order_coordinate_profile_governance_migration.py
用途:验证订单坐标 Profile 治理迁移可以在 SQLite 最小前置结构上升级和降级。
依赖:Alembic Operations、SQLite 内存数据库、028e9f0a1b2c 迁移。
逻辑:先构造 Profile 与外键目标,再检查新增列、样本/审计表和索引会被完整回滚。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def _migration():
"""以文件路径加载数字开头的 Alembic 迁移模块。"""
path = Path(__file__).parents[1] / 'migrations' / 'versions' / '028e9f0a1b2c_add_order_coordinate_profile_governance.py'
spec = importlib.util.spec_from_file_location('order_coordinate_profile_governance_migration', path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_order_coordinate_profile_governance_migration_round_trip():
"""治理摘要、样本绑定和审计表必须可迁移并完全逆序回滚。"""
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
for name in ('users', 'shipping_notice_documents', 'shipping_order_schema_versions'):
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_order_document_profiles', metadata,
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('status', sa.String(16), nullable=False),
)
metadata.create_all(engine)
with engine.begin() as connection:
migration = _migration()
migration.op = Operations(MigrationContext.configure(connection))
migration.upgrade()
inspector = sa.inspect(connection)
assert {'shipping_order_document_profile_samples', 'shipping_order_document_profile_audits'} <= set(inspector.get_table_names())
assert {'template_mode', 'training_sample_count', 'match_strategy_summary_json'} <= {
column['name'] for column in inspector.get_columns('shipping_order_document_profiles')
}
migration.downgrade()
inspector = sa.inspect(connection)
assert 'shipping_order_document_profile_samples' not in inspector.get_table_names()
assert 'shipping_order_document_profile_audits' not in inspector.get_table_names()
assert not {'template_mode', 'training_sample_count', 'match_strategy_summary_json'} & {
column['name'] for column in inspector.get_columns('shipping_order_document_profiles')
}
@@ -13,6 +13,7 @@ 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,
@@ -190,3 +191,72 @@ def test_template_profile_rejects_freeform_or_invalid_extractor_targets():
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', 'text': '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': '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': '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', 'text': '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': '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)
File diff suppressed because it is too large. Load diff
@@ -288,7 +288,7 @@ def test_create_run_freezes_published_order_document_profile_definition(app):
assert reused is False
frozen = run.input_snapshot_json['order_document_profiles']
assert frozen == [{
assert [{key: value for key, value in item.items() if key != 'auto_create_approved'} for item in frozen] == [{
'profile_id': profile.id,
'profile_code': 'PO_312207',
'version': 1,
@@ -297,6 +297,8 @@ def test_create_run_freezes_published_order_document_profile_definition(app):
'structure_fingerprint': 'b' * 64,
'definition': profile.definition_json,
}]
# 质量门禁也必须成为冻结快照的一部分,不能在 Worker 中回读当前测试集状态。
assert frozen[0]['auto_create_approved'] is False
profile.definition_json = {**profile.definition_json, 'drop_zero_qty': False}
db.session.commit()
assert run.input_snapshot_json['order_document_profiles'][0]['definition']['drop_zero_qty'] is True
@@ -0,0 +1,54 @@
"""验证订单坐标模板的唯一匹配只使用静态锚点和冻结结构证据。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
def _profile(code: str, *, required: str = 'PURCHASE ORDER', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
"""构造不包含订单号、料号、数量或金额的最小冻结 Profile。"""
return {'profile_code': code, 'version': 1, 'checksum': f'{code.lower():0<64}'[:64], 'definition': {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {
'required_anchors': [{'anchor_id': 'title', 'text': required}],
'optional_anchors': [{'anchor_id': f'optional_{index}', 'text': value} for index, value in enumerate(optional or [])],
'minimum_score': score, 'minimum_margin': margin,
},
'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': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
}]}],
}}
def _layout(text: str = 'PURCHASE ORDER') -> 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 test_profile_matcher_uniquely_matches_static_anchors_not_dynamic_order_values():
"""同一静态版式在订单号、料号、数量变化后仍稳定命中同一 Profile。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'])], layout=_layout('PURCHASE ORDER SUPPLIER A PO-999 QTY 999 PART-X'))
assert result.status == 'unique_match'
assert result.profile_code == 'PO_A'
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())
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('DELIVERY NOTE')).status == 'layout_drift'
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout={'tables': []}).status == 'evidence_insufficient'
def test_profile_matcher_requires_optional_score_threshold():
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
assert result.status == 'no_match'
@@ -24,6 +24,7 @@ from app.models import (
ShippingOrderFieldValue,
ShippingOrderSchemaAuditEvent,
ShippingOrderSchemaVersion,
ShippingOrderDocumentProfile,
User,
)
from app.services.shipping_notice.order_schema import service
@@ -468,6 +469,27 @@ def test_order_field_retire_is_blocked_by_active_cross_domain_config(app):
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
def test_order_field_retire_is_blocked_by_v2_coordinate_profile(app):
"""关键断言:v2 表头或明细字段区域引用的 field_id 也必须阻止字段退役。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({'field_code': 'coordinate_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
schema = service.get_state()['schema']
version = service.create_draft({}, actor_id=None)
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': [{
'header_layouts': [], 'line_layouts': [{'field_regions': [{'field_id': field['id']}]}],
}]}, lock_version=1,
))
db.session.commit()
with pytest.raises(Exception) as exc_info:
service.retire_field(field['id'])
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
"""新 Schema 版本移除下游仍在使用的字段时,发布必须在运行前阻断。"""
with app.app_context():
@@ -0,0 +1,148 @@
"""
backend/tests/test_shipping_order_schema_compatibility.py
用途:验证订单文档模板按稳定 field_id 自动兼容 Schema 小版本变化。
依赖:纯兼容性判定和模板定义重映射函数。
逻辑:覆盖字段改名、可选字段新增和破坏性类型变化。
"""
from app.services.shipping_notice.order_schema.compatibility import (
compare_profile_schema,
remap_profile_field_codes,
)
def test_profile_impact_service_is_exposed_by_compatibility_contract():
"""纯函数契约保留字段级 breaking reason,供影响接口直接展示。"""
result = compare_profile_schema(
_profile(),
_schema(_field('f1', 'old_code')),
_schema(_field('f1', 'old_code', scope='header')),
)
assert result['status'] == 'breaking'
assert result['breaking_changes'][0]['reason'] == 'scope_changed'
def _schema(*fields):
return {'fields': list(fields)}
def _field(field_id, code, *, value_type='string', scope='line', enabled=True):
return {
'field_id': field_id,
'field_code': code,
'value_type': value_type,
'scope': scope,
'enabled': enabled,
}
def _profile():
return {
'table_regions': [{
'line_layouts': [{
'field_regions': [{
'field_id': 'f1', 'field_code': 'old_code',
'target_fields': [{'field_id': 'f1', 'field_code': 'old_code'}],
}],
}],
}],
}
def test_field_rename_and_optional_addition_are_automatically_compatible():
result = compare_profile_schema(
_profile(),
_schema(_field('f1', 'old_code')),
_schema(_field('f1', 'new_code'), _field('f2', 'optional_code')),
)
assert result['status'] == 'compatible'
assert result['auto_upgradable'] is True
assert result['renamed_fields'] == [{'field_id': 'f1', 'from': 'old_code', 'to': 'new_code'}]
def test_type_change_is_breaking_for_referenced_field():
result = compare_profile_schema(
_profile(),
_schema(_field('f1', 'old_code')),
_schema(_field('f1', 'old_code', value_type='decimal')),
)
assert result['status'] == 'breaking'
assert result['breaking_changes'][0]['reason'] == 'value_type_changed'
def test_profile_field_codes_are_remapped_by_stable_identity():
result = remap_profile_field_codes(
_profile(),
_schema(_field('f1', 'new_code')),
)
field = result['table_regions'][0]['line_layouts'][0]['field_regions'][0]
assert field['field_id'] == 'f1'
assert field['field_code'] == 'new_code'
assert field['target_fields'][0]['field_code'] == 'new_code'
def test_migration_resolution_contract_requires_each_breaking_field():
"""破坏性字段必须逐项处理,避免迁移草稿静默丢失绑定。"""
result = compare_profile_schema(
_profile(),
_schema(_field('f1', 'old_code')),
_schema(_field('f1', 'old_code', value_type='decimal')),
)
assert [item['field_id'] for item in result['breaking_changes']] == ['f1']
def test_semantic_rule_change_requires_review_without_forcing_coordinate_migration():
before = _field('f1', 'code') | {'validator_keys': []}
after = _field('f1', 'code') | {'validator_keys': ['non_empty']}
result = compare_profile_schema(_profile(), _schema(before), _schema(after))
assert result['status'] == 'review_required'
assert result['auto_upgradable'] is True
assert result['review_changes'][0]['reason'] == 'validator_keys_changed'
def test_source_schema_missing_referenced_identity_is_breaking():
result = compare_profile_schema(_profile(), _schema(), _schema(_field('f1', 'code')))
assert result['status'] == 'breaking'
assert result['breaking_changes'][0]['reason'] == 'source_field_missing'
def test_replacement_candidates_exclude_changed_field_and_require_source_coverage():
"""替代候选不能用原字段自我消解,且必须覆盖原字段全部坐标来源。"""
before = _field('f1', 'old_code') | {
'required': False,
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'],
}
target = _schema(
_field('f1', 'old_code') | {
'required': True,
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'],
},
_field('f2', 'partial') | {'allowed_sources': ['pdf_coordinate']},
_field('f3', 'replacement') | {
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'],
},
)
result = compare_profile_schema(_profile(), _schema(before), target)
assert result['status'] == 'breaking'
assert result['breaking_changes'][0]['replacement_candidates'] == [{
'field_id': 'f3', 'field_code': 'replacement', 'display_name': None,
}]
def test_removed_field_still_offers_contract_compatible_replacement():
"""删除字段时仍应提供安全候选,避免管理员只能解除绑定。"""
before = _field('f1', 'old_code') | {'allowed_sources': ['pdf_coordinate']}
replacement = _field('f2', 'replacement') | {'allowed_sources': ['pdf_coordinate']}
result = compare_profile_schema(_profile(), _schema(before), _schema(replacement))
assert result['breaking_changes'][0]['reason'] == 'removed_or_disabled'
assert result['breaking_changes'][0]['replacement_candidates'] == [{
'field_id': 'f2', 'field_code': 'replacement', 'display_name': None,
}]
@@ -17,6 +17,7 @@ from app.models import (
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingReservation, ShippingTask,
ShippingUploadAttempt,
)
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
from app.services.shipping_notice.upload_attempt_service import complete_attempt, start_rpa_attempt, void_rejected_artifact
@@ -76,6 +77,20 @@ def test_failed_attempt_does_not_complete_reservation(app):
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app):
"""共享目录投递失败要落为失败 Attempt,不能遗留 uploading Artifact 阻断下一轮。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
complete_attempt(
attempt, success=False, callback_id=f'trigger_failed:{attempt.id}',
error_message='RPA upload trigger could not be written',
)
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
assert start_rpa_attempt(task, artifact_id=artifact.id).attempt_no == 2
def test_only_explicit_rejection_can_void_and_release_artifact(app):
"""网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。"""
with app.app_context():
@@ -87,3 +102,15 @@ def test_only_explicit_rejection_can_void_and_release_artifact(app):
void_rejected_artifact(task, artifact_id=artifact.id, operator_id=1, reason='货代明确拒绝')
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'superseded'
assert db.session.get(ShippingReservation, reservation.id).status == 'pending'
def test_upload_callback_success_parsing_does_not_treat_false_text_as_success():
"""Worker 回调的字符串 false/0 必须严格映射失败,非法值不得默认成功。"""
assert _rpa_callback_success(True) is True
assert _rpa_callback_success('true') is True
assert _rpa_callback_success(False) is False
assert _rpa_callback_success('false') is False
assert _rpa_callback_success('0') is False
with pytest.raises(ValidationError) as exc_info:
_rpa_callback_success('yes')
assert exc_info.value.code == 'SHIPPING.UPLOAD_CALLBACK_INVALID'