feat(shipping-notice): 完善 XFA 模板映射与订单审核流程
- 统一 XFA 数据集、字段拆分、校验及运行时解析 - 完善订单模板管理、发布检查与迁移状态 - 优化订单审核草稿、预约回退及 STP 投影缓存 - 更新前端模板编辑器、映射组件与多语言错误文案 - 补充后端与前端测试,并更新本地集成启动配置
This commit is contained in:
1 parent
43a30a7489
commit
4ec436d44c
67 files changed
+5411
-528
No files matched your search
@@ -74,8 +74,11 @@ def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
assert 'xfa_required_path_coverage_incomplete' in keys
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
"""关键断言:同名 header/line 字段缺路径时,发布诊断必须保留真实字段身份。"""
|
||||
def test_xfa_path_coverage_header_reservation_covers_line_key():
|
||||
"""
|
||||
关键断言:header.reservation_id 已绑 datasets path 时,line.reservation_id
|
||||
建单键不再因缺行级 path 阻断发布(与 runtime 头→行回退一致)。
|
||||
"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_DIAGNOSTIC', display_name='XFA Scope', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='c' * 64, template_mode='xfa_dataset',
|
||||
@@ -91,6 +94,36 @@ def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
'field_code': 'reservation_id', 'scope': 'header', 'field_layout_id': 'header-reservation',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-path', 'data_path': '/data/HEADER/RESERVATION'},
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'page_no': 1, 'region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.2, 'y1': 0.2},
|
||||
}],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
)
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', 'enabled': True, 'required': False},
|
||||
{'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'required': True, 'auto_create_key_field': True},
|
||||
]}})()
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
assert 'xfa_required_path_coverage_incomplete' not in {item['key'] for item in blocking}
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_line_reservation_when_header_unmapped():
|
||||
"""关键断言:头/行 reservation 均未映射时,诊断须标明缺失的是 line.reservation_id。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_MISSING', display_name='XFA Scope Missing', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='d' * 64, template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:template', 'dataset_structure_fingerprint': 'sha256:structure',
|
||||
'dataset_root_path': '/data', 'authoritative_line_collection_path': '/data/ITEMS',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'bindings': [],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
@@ -102,8 +135,6 @@ def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
coverage = next(item for item in blocking if item['key'] == 'xfa_required_path_coverage_incomplete')
|
||||
|
||||
# 同名显示码只是辅助信息;管理员必须能识别真正缺失的是 line 的 reservation_id。
|
||||
assert coverage['field_codes'] == ['reservation_id']
|
||||
assert coverage['missing_fields'] == [{
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/tests/test_shipping_document_profile_quality.py
|
||||
用途:验证订单文档模板的独立盲测候选、批准资格和冻结 checksum 门禁。
|
||||
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
|
||||
逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
|
||||
XFA 确认真值允许候选含 bindings 以外的视觉表头(如 bill_to)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,6 +43,47 @@ def _memory_file_asset_storage(monkeypatch):
|
||||
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
|
||||
|
||||
|
||||
def test_expected_order_fields_allows_extra_visual_header_keys_for_xfa_bindings():
|
||||
"""XFA 确认:bindings 表头齐全即可;候选额外含 bill_to 等视觉框不得拒绝。"""
|
||||
binding = SimpleNamespace(
|
||||
scope='header',
|
||||
field_code='customer_po_number',
|
||||
value_binding=SimpleNamespace(path_id='po-path'),
|
||||
)
|
||||
parser = SimpleNamespace(bindings=[binding], header_mappings=[], order_field_layouts=[])
|
||||
raw = {
|
||||
'header:customer_po_number': '4510039229',
|
||||
'header:bill_to_customer': 'Cloud Network Technology Kft.',
|
||||
'header:bill_to_address': 'Bánki Donát u. 1',
|
||||
}
|
||||
|
||||
result = quality._expected_order_fields(raw, parser=parser)
|
||||
|
||||
# 关键断言:正式绑定键保留,额外视觉表头一并写入盲测真值。
|
||||
assert result == raw
|
||||
|
||||
|
||||
def test_expected_order_fields_still_requires_every_bound_header_for_xfa():
|
||||
"""XFA 确认:缺少 bindings 表头仍须拒绝,避免静默漏掉正式 path 字段。"""
|
||||
parser = SimpleNamespace(
|
||||
bindings=[
|
||||
SimpleNamespace(scope='header', field_code='customer_po_number'),
|
||||
SimpleNamespace(scope='header', field_code='currency'),
|
||||
],
|
||||
header_mappings=[],
|
||||
order_field_layouts=[],
|
||||
)
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality._expected_order_fields(
|
||||
{'header:customer_po_number': '4510039229', 'header:bill_to_customer': 'X'},
|
||||
parser=parser,
|
||||
)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
||||
assert 'header:currency' in (getattr(caught.value, 'details', {}) or {}).get('missing_keys', [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('actual', 'expected', 'config'),
|
||||
[
|
||||
|
||||
@@ -134,9 +134,57 @@ def test_position_matcher_line_index_1based():
|
||||
parsed_seg = [s for s in result.segments if s.rule_id == 'pos1'][0]
|
||||
assert parsed_seg.normalized_text == 'Vendor Comments:'
|
||||
assert parsed_seg.line_no == 1
|
||||
assert parsed_seg.line_end_no == 1
|
||||
assert parsed_seg.handling == 'evidence_only'
|
||||
|
||||
|
||||
def test_position_matcher_joins_consecutive_lines():
|
||||
"""连续多行 position:line_end + join_with 合并文本并认领范围内行。"""
|
||||
seg = BaseSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='bill_to_address',
|
||||
display_name='账款地址',
|
||||
handling='mapped',
|
||||
target_field_id='f-addr',
|
||||
target_field_code='bill_to_address',
|
||||
)
|
||||
rule_set = _base_rule_set([
|
||||
BaseSplitRule(
|
||||
rule_id='addr-range',
|
||||
matcher=BaseSplitMatcher(
|
||||
type='position',
|
||||
line_index=2,
|
||||
line_end=4,
|
||||
join_with='newline',
|
||||
),
|
||||
segment=seg,
|
||||
),
|
||||
])
|
||||
raw = (
|
||||
'Cloud Network Technology Kft.\n'
|
||||
'Bánki Donát u. 1.\n'
|
||||
'2900 Komárom\n'
|
||||
'Hungary'
|
||||
)
|
||||
result = execute_base_split_rule_set(raw_value=raw, rule_set=rule_set)
|
||||
assert result.status == 'parsed'
|
||||
assert result.mapped_fields['bill_to_address'] == (
|
||||
'Bánki Donát u. 1.\n2900 Komárom\nHungary'
|
||||
)
|
||||
parsed_seg = [s for s in result.segments if s.rule_id == 'addr-range'][0]
|
||||
assert parsed_seg.line_no == 2
|
||||
assert parsed_seg.line_end_no == 4
|
||||
unmatched = [s for s in result.segments if s.matcher_type == 'unmatched']
|
||||
assert len(unmatched) == 1
|
||||
assert unmatched[0].line_no == 1
|
||||
|
||||
|
||||
def test_position_matcher_rejects_inverted_line_range():
|
||||
"""line_end < line_index 时契约拒绝。"""
|
||||
with pytest.raises(Exception):
|
||||
BaseSplitMatcher(type='position', line_index=3, line_end=1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [TEST 2] 优先级仲裁——prefix > regex > position > unmatched
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -183,6 +183,51 @@ def test_reference_page_frames_read_annotation_coordinate_evidence():
|
||||
}
|
||||
|
||||
|
||||
def test_definition_contract_hydrates_empty_order_field_id_from_schema():
|
||||
"""盲测候选预览:已保存空 field_id 必须从 Schema 回填,禁止 Pydantic 500。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_9',
|
||||
'field_id': '',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'anchor': None,
|
||||
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .4, 'y1': .15},
|
||||
'value_mode': 'single_line',
|
||||
'stop_anchors': [],
|
||||
'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
profile = SimpleNamespace(
|
||||
profile_code='FOX_HUNGARY',
|
||||
version=1,
|
||||
definition_json=definition,
|
||||
schema_version=schema,
|
||||
)
|
||||
|
||||
contract = service._definition_contract(profile)
|
||||
|
||||
# 关键断言:空串 field_id 已按 Schema 回填,坐标契约可构造。
|
||||
assert contract.order_field_layouts[0].field_id == 'po-field'
|
||||
assert contract.order_field_layouts[0].layout_id == 'order_field_1_9'
|
||||
|
||||
|
||||
def test_reservation_region_rejects_schema_without_header_scope():
|
||||
"""无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
@@ -603,6 +648,54 @@ def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_soft_dedupes_duplicate_order_field_codes(app, monkeypatch):
|
||||
"""进入编辑页时草稿若已重复绑定同一 Header 字段,预览须去重后继续返回样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': f'customer_po_{index}', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
} for index in (1, 2)],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:预览只保留首个重复字段布局,不因 order_field_duplicate 拒绝进入编辑页。
|
||||
assert len(result['fields']) == 1
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_order_field_before_table_region_is_drawn(app, monkeypatch):
|
||||
"""共同视觉预览在明细表尚未标注时,仍可读取已标注的订单级 PO 字段。"""
|
||||
glyphs = [
|
||||
|
||||
@@ -873,3 +873,44 @@ def test_provider_omission_is_merged_but_override_of_confirmed_order_field_is_re
|
||||
assert error.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
else:
|
||||
raise AssertionError('confirmed order field override must be rejected')
|
||||
|
||||
|
||||
def test_merge_confirmed_fields_skips_lock_when_orders_use_xfa_dataset():
|
||||
"""
|
||||
XFA:datasets 为正式值;坐标 confirmed 锁(含标签 OCR 垃圾值)不得否决或覆盖。
|
||||
关键断言:bill_to 保留 datasets 客户名,且不抛 ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE。
|
||||
"""
|
||||
from unittest.mock import patch
|
||||
|
||||
unit = type('Unit', (), {'document_id': 247})()
|
||||
xfa_orders = [{
|
||||
'header_fields': [{
|
||||
'field_id': '9a81b044-b49f-4ed3-8c09-2aec85fb1470',
|
||||
'value_source': 'xfa_dataset',
|
||||
'observations': [{
|
||||
'value': 'Cloud Network Technology Kft.',
|
||||
'source': 'xfa_dataset',
|
||||
'document_id': 247,
|
||||
'layout_evidence': {
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': {'source': 'xfa_dataset'},
|
||||
},
|
||||
}],
|
||||
}],
|
||||
'lines': [],
|
||||
}]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow._confirmed_profile_order_fields',
|
||||
lambda _run, unit: [{
|
||||
'field_id': '9a81b044-b49f-4ed3-8c09-2aec85fb1470',
|
||||
'value': 'b) Issue invoice to:',
|
||||
'status': 'confirmed',
|
||||
'source': 'pdf_coordinate',
|
||||
}],
|
||||
):
|
||||
merged = _merge_confirmed_profile_order_fields(object(), unit=unit, orders=xfa_orders)
|
||||
|
||||
obs = merged[0]['header_fields'][0]['observations'][0]
|
||||
assert obs['value'] == 'Cloud Network Technology Kft.'
|
||||
assert obs['source'] == 'xfa_dataset'
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
tests/test_shipping_order_profile_unified_migration_status.py
|
||||
|
||||
用途:锁定 summarize_unified_migration_status 的 pending_visual 计数规则。
|
||||
依赖:order_profile_unified_migration.summarize_unified_migration_status。
|
||||
逻辑:纯摘要单测;不读 PDF / 不写库。现代 XFA 绑定靠 field_layout_id,不得因缺少
|
||||
visual_binding 被计为「待补框」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
|
||||
def test_summarize_skips_pending_when_field_layout_id_present():
|
||||
"""
|
||||
有 field_layout_id 的 XFA binding 即使无 visual_binding,也不计 pending_visual。
|
||||
"""
|
||||
summary = summarize_unified_migration_status(
|
||||
{
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'field_layout_id': 'header_po_box',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-po'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-mat',
|
||||
'field_code': 'material_number',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line_1:material_number',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'matnr-path'},
|
||||
# visual_binding 缺失或非 confirmed 都不应计入 pending。
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
},
|
||||
],
|
||||
},
|
||||
template_mode='xfa_dataset',
|
||||
)
|
||||
|
||||
# 关键断言:库列表「待补框」不得把已挂共享布局的 XFA 绑定算进去。
|
||||
assert summary['already_unified'] is True
|
||||
assert summary['needs_migration'] is False
|
||||
assert summary['binding_count'] == 2
|
||||
assert summary['pending_visual_count'] == 0
|
||||
assert summary['unified_binding_status'] == 'ready'
|
||||
|
||||
|
||||
def test_summarize_counts_pending_without_field_layout_or_confirmed_visual():
|
||||
"""
|
||||
无 field_layout_id 且 visual 未 confirmed 的 binding 仍计为 pending_visual。
|
||||
"""
|
||||
summary = summarize_unified_migration_status(
|
||||
{
|
||||
'template_mode': 'coordinate',
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-ready',
|
||||
'field_code': 'order_date',
|
||||
'scope': 'header',
|
||||
'field_layout_id': '',
|
||||
'visual_binding': {'status': 'confirmed'},
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-pending',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-missing-visual',
|
||||
'field_code': 'ship_to',
|
||||
'scope': 'header',
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
],
|
||||
},
|
||||
template_mode='coordinate',
|
||||
)
|
||||
|
||||
# 关键断言:仅无布局且未确认视觉的两条计入 pending。
|
||||
assert summary['binding_count'] == 3
|
||||
assert summary['pending_visual_count'] == 2
|
||||
assert summary['unified_binding_status'] == 'pending_visual'
|
||||
@@ -0,0 +1,281 @@
|
||||
"""
|
||||
tests/test_shipping_order_review_draft_reservation_fallback.py
|
||||
|
||||
用途:回归「表头已有预约单号、明细行格空」时草稿校验与确认摘要同一回退规则。
|
||||
依赖:order_review_draft_service._validation / build_confirmable_draft_summary、
|
||||
field_rules.compute_effective_reservation_id。
|
||||
逻辑:资格服务已算 effective_reservation_id,但确认物化/冻结只认行级 reservation_id;
|
||||
本测试锁定校验不误拦,且确认摘要必须把表头值写回行字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
_validation,
|
||||
build_confirmable_draft_summary,
|
||||
)
|
||||
|
||||
|
||||
def _string_field(field_id: str, field_code: str, *, scope: str, required: bool) -> dict:
|
||||
"""构造草稿校验用的最小 Schema 字段配置。"""
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_type': 'string',
|
||||
'required': required,
|
||||
'normalizer_key': 'reservation_id' if field_code == 'reservation_id' else 'trim',
|
||||
'validator_keys': ['reservation_id'] if field_code == 'reservation_id' else [],
|
||||
'display_name': field_code,
|
||||
}
|
||||
|
||||
|
||||
def test_draft_validation_accepts_required_line_reservation_from_header():
|
||||
"""
|
||||
表头预约单号有效、行格空时:不得再发 required_field_missing;
|
||||
投影行应带上表头有效值供资格服务使用。
|
||||
"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={
|
||||
'machine_fields': [
|
||||
{'field_id': 'h-res', 'observations': [{'value': '2000485916'}]},
|
||||
],
|
||||
'values': {},
|
||||
},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
# 行预约单号故意缺失:应回退表头。
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=1,
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
current_draft=draft,
|
||||
candidate_id=None,
|
||||
unit=None,
|
||||
unit_id=None,
|
||||
run=None,
|
||||
run_id=None,
|
||||
case_no='CASE-RES-FALLBACK',
|
||||
document_id=1,
|
||||
)
|
||||
captured_lines: list[dict] = []
|
||||
|
||||
def _fake_eligibility(*, lines, **_kwargs):
|
||||
captured_lines.extend(lines)
|
||||
return {
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
'shadow_would_auto_create': False,
|
||||
'gates': {'required_fields_complete': True},
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'line_projections': [{
|
||||
'draft_line_id': 'machine-1',
|
||||
'effective_reservation_id': '2000485916',
|
||||
}],
|
||||
'qualification': {},
|
||||
'assessment': {
|
||||
'can_create_task': True,
|
||||
'missing_required_fields': [],
|
||||
'invalid_lines': [],
|
||||
},
|
||||
'enabled_inventory_source_codes': [],
|
||||
}
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.assess_order_build_eligibility',
|
||||
side_effect=_fake_eligibility,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.candidate_qualification_service.resolve_review_case_customer_resolved',
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = _validation(case)
|
||||
|
||||
# 关键断言:表头回退后不再把行预约单号标成 Schema 必填缺失。
|
||||
assert not any(
|
||||
str(item.get('code') or '') == 'required_field_missing'
|
||||
and str(item.get('field_id') or '') == 'l-res'
|
||||
for item in (result.get('issues') or [])
|
||||
)
|
||||
assert captured_lines and captured_lines[0].get('reservation_id') == '2000485916'
|
||||
assert result['can_build'] is True
|
||||
|
||||
|
||||
def test_draft_validation_still_blocks_when_header_and_line_reservation_missing():
|
||||
"""表头与行均无有效预约单号时,行必填仍应阻断。"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={'machine_fields': [], 'values': {}},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=1,
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
current_draft=draft,
|
||||
candidate_id=None,
|
||||
unit=None,
|
||||
unit_id=None,
|
||||
run=None,
|
||||
run_id=None,
|
||||
case_no='CASE-RES-MISSING',
|
||||
document_id=1,
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.assess_order_build_eligibility',
|
||||
return_value={
|
||||
'can_build': True,
|
||||
'can_auto_create': False,
|
||||
'shadow_would_auto_create': False,
|
||||
'gates': {},
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'line_projections': [],
|
||||
'qualification': {},
|
||||
'assessment': {
|
||||
'can_create_task': True,
|
||||
'missing_required_fields': [],
|
||||
'invalid_lines': [],
|
||||
},
|
||||
'enabled_inventory_source_codes': [],
|
||||
},
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.candidate_qualification_service.resolve_review_case_customer_resolved',
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = _validation(case)
|
||||
|
||||
# 关键断言:双端皆空时仍报行级预约单号缺失。
|
||||
assert any(
|
||||
str(item.get('code') or '') == 'required_field_missing'
|
||||
and str(item.get('field_id') or '') == 'l-res'
|
||||
for item in (result.get('issues') or [])
|
||||
)
|
||||
assert result['can_build'] is False
|
||||
|
||||
|
||||
def test_build_confirmable_draft_summary_fills_line_reservation_from_header():
|
||||
"""
|
||||
确认建单摘要必须把表头有效预约单号写进行级 reservation_id,
|
||||
否则物化 Extraction 无行 FieldValue,冻结门禁会 ORDER_FREEZE_BLOCKED。
|
||||
"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={
|
||||
'machine_fields': [
|
||||
{'field_id': 'h-res', 'observations': [{'value': '2000485916'}]},
|
||||
],
|
||||
'values': {},
|
||||
},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=3,
|
||||
schema_version_id=1,
|
||||
)
|
||||
case = SimpleNamespace(current_draft=draft)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._validation',
|
||||
return_value={'status': 'ready', 'can_build': True, 'issues': []},
|
||||
),
|
||||
):
|
||||
summary, _validation_result = build_confirmable_draft_summary(case)
|
||||
|
||||
# 关键断言:确认摘要行上须带有效预约单号,供物化/冻结消费。
|
||||
assert summary.get('reservation_id') == '2000485916'
|
||||
assert summary['lines'][0].get('reservation_id') == '2000485916'
|
||||
assert summary['lines'][0].get('draft_line_id') == 'machine-1'
|
||||
@@ -681,7 +681,7 @@ def test_runtime_preserves_customer_po_line_number_without_system_line_projectio
|
||||
|
||||
|
||||
def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
"""行级 Reservation 优先,缺失时回退订单头,二者均可选不构成阶段 0 门禁。"""
|
||||
"""行级 Reservation 优先;缺失时回退订单头,且不得再因行缺值误拦完整性门禁。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
header_reservation = service.save_field(
|
||||
@@ -691,9 +691,11 @@ def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
line_cfg = _config(line_reservation['id'], '行预约单号', value_type='string')
|
||||
line_cfg.update({'auto_create_key_field': True, 'minimum_confidence': 0.95})
|
||||
published = _save_and_publish(draft, [
|
||||
_config(header_reservation['id'], '订单预约单号', value_type='string'),
|
||||
_config(line_reservation['id'], '行预约单号', value_type='string'),
|
||||
line_cfg,
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
@@ -715,7 +717,13 @@ def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == ['3000000001', '3000000002']
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == [
|
||||
'3000000001', '3000000002',
|
||||
]
|
||||
# 关键断言:行投影已回填表头值;完整性不得因「行格空」阻断预约单号。
|
||||
assert result['lines'][0].get('reservation_id') == '3000000001'
|
||||
assert result['lines'][1].get('reservation_id') == '3000000002'
|
||||
assert 'reservation_id' not in (result.get('blocked_fields') or [])
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
tests/test_shipping_stp_projection_cache_shell.py
|
||||
|
||||
用途:空壳投影缓存不得把已失败的 STP Job 误判为「未入队」;
|
||||
ORDER_FREEZE_BLOCKED 在 can_auto+can_build 时须投影为可技术重试。
|
||||
依赖:order_stp_auto_create_service.find_latest_stp_job、
|
||||
reconciliation_projector.project_case_automation_status。
|
||||
逻辑:Gate 投影会写入无 stp_jobs_* 的 session 缓存;若按「缺键=空列表」处理,
|
||||
UI 会错误展示重试自动推进,而 API 又因真实 failed Job 抛 RETRY_STP_BLOCKED_MANUAL。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import find_latest_stp_job
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_automation_status,
|
||||
)
|
||||
|
||||
|
||||
def test_find_latest_stp_job_falls_back_when_cache_shell_has_no_ref(app):
|
||||
"""空壳缓存有 dict 但无该 business_ref 时,必须查库而非返回 None。"""
|
||||
with app.app_context():
|
||||
db.session.info['shipping_conversation_projection_read_cache'] = {
|
||||
'gates_by_execution_id': {},
|
||||
'stp_jobs_by_ref': {},
|
||||
}
|
||||
sentinel = SimpleNamespace(id=1904, status='failed', business_ref='stp-auto:r:doc-1:v3')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.Job'
|
||||
) as job_model:
|
||||
query = job_model.query.filter.return_value.order_by.return_value
|
||||
query.first.return_value = sentinel
|
||||
found = find_latest_stp_job(business_ref='stp-auto:r:doc-1:v3')
|
||||
assert found is sentinel
|
||||
|
||||
|
||||
def test_order_freeze_blocked_projects_retryable_when_can_auto(app):
|
||||
"""
|
||||
历史 Job 以 ORDER_FREEZE_BLOCKED + retryable=false 落库时,
|
||||
若当前仍可建单,投影必须允许技术重试(与 assert_case_not_blocked_manual 放行一致)。
|
||||
"""
|
||||
with app.app_context():
|
||||
draft = SimpleNamespace(draft_version=3)
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-TEST-FREEZE',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=246,
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='SNER-TEST'),
|
||||
candidate_id=None,
|
||||
)
|
||||
failed_job = SimpleNamespace(
|
||||
id=1904,
|
||||
status='failed',
|
||||
result_json={
|
||||
'retryable': False,
|
||||
'blocking_reason': 'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
'error_code': 'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
},
|
||||
)
|
||||
validation = {'status': 'ready', 'can_auto_create': True, 'can_build': True}
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.build_stp_idempotency_key',
|
||||
return_value='stp-auto:SNER-TEST:doc-246:v3',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_latest_stp_job',
|
||||
return_value=failed_job,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
return_value={'has_formal_ot': False, 'task_missing': False},
|
||||
):
|
||||
auto = project_case_automation_status(
|
||||
case, validation=validation, post_confirm=None,
|
||||
)
|
||||
|
||||
assert auto['status'] == 'failed'
|
||||
assert auto['retryable'] is True
|
||||
assert auto['job_id'] == 1904
|
||||
assert auto['blocking_reason'] == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
@@ -80,6 +80,34 @@ def test_tree_nodes_have_path_id_and_no_raw_paths_in_serialized_dto():
|
||||
assert payload['data_path_hash'].startswith('sha256:')
|
||||
assert 'data_path' not in payload
|
||||
assert '4510039227' not in json.dumps(payload)
|
||||
assert 'raw_value' not in json.dumps(payload)
|
||||
|
||||
|
||||
def test_tree_nodes_can_reveal_full_sample_display_without_raw_value_key():
|
||||
"""断言意图:reveal 路径可把完整样本写入 display,但仍禁止 raw_value 键。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
root = analysis.nodes[0]
|
||||
payload = serialize_tree_node(root, include_values=True, include_full_values=True)
|
||||
dumped = json.dumps(payload)
|
||||
assert 'raw_value' not in dumped
|
||||
assert '4510039227' in dumped
|
||||
assert 'data_path' not in payload
|
||||
|
||||
def find_leaf(node: dict):
|
||||
if node.get('is_leaf'):
|
||||
return node
|
||||
for child in node.get('children') or []:
|
||||
found = find_leaf(child)
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
leaf = find_leaf(payload)
|
||||
assert leaf is not None
|
||||
assert leaf.get('full_value_revealed') is True
|
||||
assert leaf.get('display_policy') == 'full'
|
||||
assert '•' not in str(leaf.get('sample_value_display') or '')
|
||||
assert '…' not in str(leaf.get('sample_value_display') or '')
|
||||
|
||||
|
||||
def test_mask_value_for_dto():
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_extraction_route.py
|
||||
|
||||
用途:阶段 3 正式 Worker 路由端到端——精确命中 published XFA Profile 后产出 golden 字段。
|
||||
用途:阶段 3 正式 Worker 路由端到端——精确命中 published XFA Profile 后产出 golden 字段;
|
||||
另锁定盲测 rows 剔除表头、空视觉 reservation 不冲掉 datasets。
|
||||
依赖:order_extraction_workflow、xfa helpers、pytest。
|
||||
逻辑:合成 hybrid PDF + 冻结 Profile 快照 → route_deterministic_unit;
|
||||
断言 A/B 字段、needs_review 失败关闭、无通用回退、snapshot 冻结 parser identity。
|
||||
@@ -36,11 +37,16 @@ def test_datasets_adapter_uses_ocr_only_as_cross_check_evidence():
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 1
|
||||
assert result['mismatch_count'] == 1
|
||||
assert result['mismatches'] == [{'row_index': 0, 'field_id': 'material'}]
|
||||
assert result['mismatches'] == [{
|
||||
'row_index': 0,
|
||||
'field_id': 'material',
|
||||
'ocr_value': 'OCR-M1',
|
||||
'datasets_value': 'DATA-M1',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:验证/盲测阶段也必须拒绝 OCR 与 datasets 的字段冲突。"""
|
||||
"""关键断言:验证/盲测对照须标出 OCR 与 datasets 冲突字段及两侧截断值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_validation_evidence_cross_check,
|
||||
)
|
||||
@@ -58,11 +64,17 @@ def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
assert result['mismatches'] == [{
|
||||
'scope': 'header',
|
||||
'row_index': None,
|
||||
'field_code': 'customer_po_no',
|
||||
'ocr_value': 'OCR-PO',
|
||||
'datasets_value': 'DATA-PO',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值。"""
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值;对照带两侧值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
)
|
||||
@@ -80,7 +92,13 @@ def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
assert result['mismatches'] == [{
|
||||
'scope': 'header',
|
||||
'row_index': None,
|
||||
'field_code': 'customer_po_no',
|
||||
'ocr_value': 'OCR-PO',
|
||||
'datasets_value': 'DATA-PO',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_conflict(monkeypatch):
|
||||
@@ -186,6 +204,226 @@ def test_datasets_overlap_parse_result_uses_formal_datasets_extraction(monkeypat
|
||||
assert result == {'passed': True, 'reason_codes': []}
|
||||
|
||||
|
||||
def test_blind_rows_exclude_header_fields_copied_onto_line_rows():
|
||||
"""
|
||||
正式提取会把单头挂到每行;盲测明细 JSON 必须剔除这些 header field_code。
|
||||
关键断言:currency/reservation_id 等只应出现在 order_fields,不得留在 rows。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_rows_excluding_header_fields,
|
||||
)
|
||||
|
||||
extraction = SimpleNamespace(
|
||||
header_fields=[
|
||||
SimpleNamespace(field_code='currency'),
|
||||
SimpleNamespace(field_code='reservation_id'),
|
||||
SimpleNamespace(field_code='bill_to_customer'),
|
||||
],
|
||||
rows=[{
|
||||
'fields': [
|
||||
{'field_code': 'currency', 'value': 'USD'},
|
||||
{'field_code': 'reservation_id', 'value': '1000144510'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Cloud Network'},
|
||||
{'field_code': 'part_number', 'value': 'D4-A08'},
|
||||
{'field_code': 'qty', 'value': 1},
|
||||
],
|
||||
}],
|
||||
)
|
||||
rows = _blind_rows_excluding_header_fields(
|
||||
extraction=extraction, json_value=lambda value: value,
|
||||
)
|
||||
assert rows == [{'part_number': 'D4-A08', 'qty': 1}]
|
||||
|
||||
|
||||
def test_empty_visual_reservation_does_not_wipe_datasets_header():
|
||||
"""空视觉 reservation 不得冲掉 datasets 已抽取的单头值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_merge_visual_reservation_into_blind_candidate,
|
||||
)
|
||||
|
||||
datasets_candidate = {
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': '1000144510',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate,
|
||||
visual_candidate={
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': None,
|
||||
'scope': 'header', 'status': 'unavailable', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{}],
|
||||
},
|
||||
)
|
||||
reservation = next(
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
assert reservation['value'] == '1000144510'
|
||||
|
||||
|
||||
def test_non_empty_visual_reservation_overrides_datasets_header():
|
||||
"""非空视觉 Reservation 专区结果应覆盖 datasets 单头。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_merge_visual_reservation_into_blind_candidate,
|
||||
)
|
||||
|
||||
datasets_candidate = {
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': 'OLD',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate,
|
||||
visual_candidate={
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': '1000144510',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'reservation_id': 'LINE-1'}],
|
||||
},
|
||||
)
|
||||
reservation = next(
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
assert reservation['value'] == '1000144510'
|
||||
assert datasets_candidate['rows'][0]['reservation_id'] == 'LINE-1'
|
||||
|
||||
|
||||
def test_datasets_success_drops_ocr_parse_strategy_fallback_codes():
|
||||
"""
|
||||
datasets 正式通过后,OCR 行重建 PARSE_STRATEGY 不得留作阻断码。
|
||||
关键断言:PARSE_STRATEGY_* / 无表/坐标证据不可用被剔除;其它码保留。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_fallback_codes_after_datasets_success,
|
||||
)
|
||||
|
||||
kept = _fallback_codes_after_datasets_success([
|
||||
'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',
|
||||
'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',
|
||||
'business_table_not_found',
|
||||
'coordinate_evidence_unavailable',
|
||||
'reservation_region_needs_review',
|
||||
])
|
||||
assert kept == ['reservation_region_needs_review']
|
||||
|
||||
|
||||
def test_blind_gate_does_not_fail_on_ocr_or_visual_metrics():
|
||||
"""
|
||||
XFA:OCR↔datasets 与 visual/mirror/evidence 指标均不得硬拦盲测(datasets 为正式值)。
|
||||
关键断言:指标 < 1.0 且对照 mismatched 时 failures 为空;抽取失败仍硬拦。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
blind_gate_failures,
|
||||
)
|
||||
|
||||
visual = {
|
||||
'order_fields': [
|
||||
{'field_code': 'currency', 'value': 'usd', 'scope': 'header'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Full Block', 'scope': 'header'},
|
||||
],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
datasets = {
|
||||
'order_fields': [
|
||||
{'field_code': 'currency', 'value': 'USD', 'scope': 'header'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Cloud Network', 'scope': 'header'},
|
||||
],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
comparison = _blind_candidate_cross_check(
|
||||
visual_candidate=visual, datasets_candidate=datasets,
|
||||
)
|
||||
assert comparison['status'] == 'mismatched'
|
||||
assert {item['field_code'] for item in comparison['mismatches']} == {
|
||||
'currency', 'bill_to_customer',
|
||||
}
|
||||
failures, metrics = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'parsed',
|
||||
'reason_codes': [],
|
||||
'visual_coverage_rate': 0.857,
|
||||
'mirror_consistency_rate': 0.5,
|
||||
'evidence_retention_rate': 0.9,
|
||||
'ocr_datasets_cross_check': comparison,
|
||||
},
|
||||
sample_id=44,
|
||||
)
|
||||
assert failures == []
|
||||
assert metrics['visual_coverage_rate'] == 0.857
|
||||
assert 'ocr_datasets_mismatch' not in failures
|
||||
|
||||
extract_failures, _ = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'failed',
|
||||
'reason_codes': ['xfa_dataset_missing'],
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
},
|
||||
sample_id=45,
|
||||
)
|
||||
assert extract_failures == ['sample:45:extraction:xfa_dataset_missing']
|
||||
|
||||
|
||||
def test_serialize_suite_exposes_soft_diagnostics_without_payload_values():
|
||||
"""执行摘要应带 soft_diagnostics 字段码,且不含对照正文值。"""
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
|
||||
suite = SimpleNamespace(
|
||||
id=1,
|
||||
profile_id=9,
|
||||
profile_checksum='abc',
|
||||
status='draft',
|
||||
samples=[],
|
||||
approved_at=None,
|
||||
runs=[
|
||||
SimpleNamespace(
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[],
|
||||
evidence_json={
|
||||
'metrics': {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
},
|
||||
'soft_diagnostics': [{
|
||||
'sample_id': 44,
|
||||
'code': 'ocr_datasets_mismatch',
|
||||
'mismatch_count': 1,
|
||||
'fields': [{
|
||||
'scope': 'header',
|
||||
'field_code': 'bill_to_customer',
|
||||
'row_index': None,
|
||||
'ocr_value': 'Cloud Network Technology Kft. Full Block',
|
||||
'datasets_value': 'Cloud Network Technology Kft.',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
payload = serialize_suite(suite)
|
||||
assert payload['latest_run']['status'] == 'passed'
|
||||
field = payload['latest_run']['soft_diagnostics'][0]['fields'][0]
|
||||
assert field['field_code'] == 'bill_to_customer'
|
||||
assert field['ocr_value'].startswith('Cloud Network')
|
||||
assert field['datasets_value'] == 'Cloud Network Technology Kft.'
|
||||
dumped = json.dumps(payload['latest_run']['soft_diagnostics'])
|
||||
assert 'normalized_value' not in dumped
|
||||
|
||||
|
||||
def test_xfa_unified_bindings_require_header_blind_truths():
|
||||
"""bindings-only XFA Profile 的 Header 真值不得因 legacy 映射为空而被静默丢弃。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_multiline_extraction.py
|
||||
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number。
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number;
|
||||
Header INVOICED_TO 拆分不得因带 split_rule_ref 的目标 binding 重复读源全文。
|
||||
依赖:xfa_profile_extraction、xfa_split_rule_contract、xfa_dataset、pytest。
|
||||
逻辑:合成多行 datasets XML + 已确认规则集;断言 mapped 字段、evidence_only 与 needs_review 边界。
|
||||
"""
|
||||
@@ -127,7 +128,7 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
|
||||
|
||||
def _confirmed_header_rule_set() -> dict:
|
||||
"""构造 Header 拆分规则:第 1 行 mapped,其余行 evidence_only。"""
|
||||
"""构造 Header 拆分规则:第 1 行客户,第 2–末行地址。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_set_id='invoiced-to-v1',
|
||||
rule_version=1,
|
||||
@@ -144,6 +145,14 @@ def _confirmed_header_rule_set() -> dict:
|
||||
handling='mapped', target_field_id='f-bill-customer', target_field_code='bill_to_customer',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='bill-address',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=2, line_end=4),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='bill_address', display_name='账款地址',
|
||||
handling='mapped', target_field_id='f-bill-address', target_field_code='bill_to_address',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
@@ -158,9 +167,10 @@ def _xfa_binding(
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
split_rule_ref: dict | None = None,
|
||||
) -> dict:
|
||||
"""构造最小合法统一 binding。"""
|
||||
return {
|
||||
payload = {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
@@ -178,6 +188,9 @@ def _xfa_binding(
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
if split_rule_ref is not None:
|
||||
payload['split_rule_ref'] = split_rule_ref
|
||||
return payload
|
||||
|
||||
|
||||
def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
@@ -279,7 +292,7 @@ def test_draft_split_rules_fail_closed_needs_review():
|
||||
|
||||
|
||||
def test_confirmed_header_split_rules_extract_customer_line():
|
||||
"""Header 源规则执行一次并产出第 1 行客户名;其余行保留为 evidence。"""
|
||||
"""Header 源规则执行一次并产出客户/地址;不得再附带源全文重复项。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_header_rule_set()]),
|
||||
@@ -290,4 +303,54 @@ def test_confirmed_header_split_rules_extract_customer_line():
|
||||
)
|
||||
header_values = {item.field_code: item.normalized_value for item in result.header_fields}
|
||||
assert header_values['bill_to_customer'] == 'Cloud Network Technology Kft.'
|
||||
assert header_values['bill_to_address'] == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
assert sum(item.field_code == 'bill_to_customer' for item in result.header_fields) == 1
|
||||
assert sum(item.field_code == 'bill_to_address' for item in result.header_fields) == 1
|
||||
|
||||
|
||||
def test_header_split_target_bindings_do_not_duplicate_raw_source():
|
||||
"""
|
||||
编辑器形态:账款客户/地址 binding 共享源 path 且带 split_rule_ref。
|
||||
关键断言:表头只保留拆分段,禁止 STEP1 再读源全文导致重复与错误值。
|
||||
"""
|
||||
rule_set = _confirmed_header_rule_set()
|
||||
customer_seg = rule_set['rules'][0]['segment']['segment_id']
|
||||
address_seg = rule_set['rules'][1]['segment']['segment_id']
|
||||
raw = _raw_profile(split_rules=[rule_set])
|
||||
raw['definition']['bindings'].extend([
|
||||
_xfa_binding(
|
||||
binding_id='bind-bill-customer',
|
||||
field_id='f-bill-customer',
|
||||
field_code='bill_to_customer',
|
||||
scope='header',
|
||||
path_id='path-invoiced-to',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
split_rule_ref={'rule_set_id': 'invoiced-to-v1', 'segment_id': customer_seg},
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-bill-address',
|
||||
field_id='f-bill-address',
|
||||
field_code='bill_to_address',
|
||||
scope='header',
|
||||
path_id='path-invoiced-to',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
split_rule_ref={'rule_set_id': 'invoiced-to-v1', 'segment_id': address_seg},
|
||||
),
|
||||
])
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-checksum-0123456789abcdef',
|
||||
)
|
||||
customers = [item for item in result.header_fields if item.field_code == 'bill_to_customer']
|
||||
addresses = [item for item in result.header_fields if item.field_code == 'bill_to_address']
|
||||
assert len(customers) == 1
|
||||
assert len(addresses) == 1
|
||||
assert customers[0].normalized_value == 'Cloud Network Technology Kft.'
|
||||
assert addresses[0].normalized_value == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
# 禁止 STEP1 把源全文挂到目标 field_code。
|
||||
assert 'Cloud Network Technology Kft.\nBánki' not in (customers[0].normalized_value or '')
|
||||
assert customers[0].normalized_value != addresses[0].normalized_value
|
||||
@@ -454,6 +454,30 @@ def test_normalize_definition_freezes_schema_identity_for_visual_header_line_fie
|
||||
assert field['target_fields'] == [{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line'}]
|
||||
|
||||
|
||||
def test_normalize_definition_freezes_schema_identity_for_order_field_layouts():
|
||||
"""订单头视觉框画布常提交空 field_id,XFA 保存必须按 Schema 冻结,禁止盲测读到空串。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
|
||||
assert raw['order_field_layouts'], 'fixture must already contain an order field layout'
|
||||
for layout in raw['order_field_layouts']:
|
||||
layout['field_id'] = ''
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw, schema_version=SimpleNamespace(definition_json=_schema_definition()), path_context=context,
|
||||
)
|
||||
|
||||
# 关键断言:空 field_id 已写成 Schema 主键,持久化定义可直接构造坐标契约。
|
||||
assert all(str(item.get('field_id') or '').strip() for item in normalized['order_field_layouts'])
|
||||
assert all(
|
||||
item['field_id'] == next(
|
||||
field['field_id']
|
||||
for field in _schema_definition()['fields']
|
||||
if field['field_code'] == item['field_code'] and field['scope'] == item['scope']
|
||||
)
|
||||
for item in normalized['order_field_layouts']
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_definition_allows_line_header_inheritance_to_reuse_header_visual_layout():
|
||||
"""行级正式继承可复用同名 Header 视觉框,避免伪造不存在的表格内预约号框。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
|
||||
@@ -107,6 +107,21 @@ def test_position_matcher_accepts_restricted_prefix_post_processor():
|
||||
|
||||
assert matcher.post_processors[0].type == 'prefix'
|
||||
assert matcher.post_processors[0].value == 'MPN'
|
||||
assert matcher.line_end is None
|
||||
assert matcher.join_with is None
|
||||
|
||||
|
||||
def test_position_matcher_accepts_consecutive_line_range():
|
||||
"""连续多行 position:允许 line_end + join_with。"""
|
||||
matcher = XfaSplitMatcher(
|
||||
type='position',
|
||||
line_index=2,
|
||||
line_end=4,
|
||||
join_with='newline',
|
||||
)
|
||||
assert matcher.line_index == 2
|
||||
assert matcher.line_end == 4
|
||||
assert matcher.join_with == 'newline'
|
||||
|
||||
|
||||
def test_rule_set_accepts_rule_id_alias():
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_blind_test.py
|
||||
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;所有 adapter 共用 evidence DTO。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json。
|
||||
逻辑:纯单元验证公共 evidence DTO 与阈值语义。
|
||||
用途:阶段 6 独立盲测指标——公共 evidence DTO 序列化;XFA 视觉指标不硬拦通过。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json;
|
||||
xfa_dataset.blind_gate_failures。
|
||||
逻辑:纯单元验证公共 evidence DTO 与 XFA 盲测硬门禁语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +14,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
blind_gate_failures,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -47,11 +51,17 @@ def test_serialize_suite_reads_shared_adapter_evidence():
|
||||
assert payload['latest_run']['failure_codes'] == ['sample:1:order_field:po:mismatch']
|
||||
|
||||
|
||||
def test_blind_metrics_threshold_requires_full_coverage():
|
||||
"""关键断言:任一统一指标 < 1.0 即视为盲测不合格(契约语义)。"""
|
||||
rates = {
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}
|
||||
assert any(float(v) < 1.0 for v in rates.values())
|
||||
def test_xfa_blind_gate_keeps_visual_metrics_as_display_only():
|
||||
"""关键断言:XFA 视觉/镜像/留痕 < 1.0 不产生硬失败码,仅回传指标。"""
|
||||
failures, metrics = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'parsed',
|
||||
'reason_codes': [],
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
},
|
||||
sample_id=7,
|
||||
)
|
||||
assert failures == []
|
||||
assert metrics['visual_coverage_rate'] == 0.99
|
||||
@@ -296,6 +296,46 @@ def test_xfa_publish_gate_accepts_a_line_binding_with_its_shared_line_visual_lay
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_xfa_publish_gate_prefers_field_region_id_over_legacy_layout_key():
|
||||
"""有 region_id 时,binding.field_layout_id 必须按 region_id 校验,而不是强制 legacy 键。"""
|
||||
definition = {
|
||||
'order_field_layouts': [],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'line-binding-region',
|
||||
'field_id': 'field-quantity',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'field_qty_box',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-quantity',
|
||||
'data_path': '/datasets/data/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
}],
|
||||
'table_regions': [{
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'region_id': 'field_qty_box',
|
||||
'region': {'x0': .2, 'y0': .3, 'x1': .4, 'y1': .4},
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
blocking = _blocking_shared_field_labels(
|
||||
definition=definition,
|
||||
schema_field_ids={'field-quantity'},
|
||||
)
|
||||
|
||||
# 关键断言:region_id 作为 shared layout 主键时,发布门禁应放行。
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_io):
|
||||
"""拆分建议 service 层 status 必须为 draft/suggested。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -248,6 +248,75 @@ def test_acroform_composite_value_requires_an_explicit_split_binding(monkeypatch
|
||||
assert 'xfa_acroform_mismatch' in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_skips_header_bindings_with_split_rule_ref(monkeypatch):
|
||||
"""
|
||||
表头拆分目标不得拿源 Widget 全文对账(与明细 split_rule_ref 跳过对齐)。
|
||||
关键断言:即使 datasets 侧与 AcroForm 源全文因换行不同,也不应报 bill_to_* mismatched。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import XfaExtractedField
|
||||
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
raw_profile['definition']['bindings'].append({
|
||||
'binding_id': 'bind-bill-customer',
|
||||
'field_id': 'f-bill-customer',
|
||||
'field_code': 'bill_to_customer',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-invoiced-to',
|
||||
'data_path': '/data/HEADER/INVOICED_TO',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.02, 'y1': 0.02},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
'split_rule_ref': {
|
||||
'rule_set_id': 'invoiced-to-v1',
|
||||
'segment_id': 'seg-bill-customer',
|
||||
},
|
||||
})
|
||||
# 模拟 STEP1 误写的源全文(修复前会按 binding_id 参与 AcroForm 对账)。
|
||||
sample_evidence = extraction.header_fields[0].evidence if extraction.header_fields else {}
|
||||
extraction.header_fields = list(extraction.header_fields) + [
|
||||
XfaExtractedField(
|
||||
mapping_id='bind-bill-customer',
|
||||
field_id='f-bill-customer',
|
||||
field_code='bill_to_customer',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
raw_value='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
normalized_value='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
quote='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
normalizer_key='trim',
|
||||
evidence=sample_evidence,
|
||||
issues=[],
|
||||
),
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_acroform_fields',
|
||||
lambda _pdf: [
|
||||
XfaAcroformField(
|
||||
'INVOICED_TO',
|
||||
'INVOICED_TO',
|
||||
'Cloud Network Technology Kft.\r\nBánki Donát u.1.',
|
||||
'Cloud***u.1.',
|
||||
),
|
||||
],
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=b'%PDF-fake',
|
||||
)
|
||||
mismatches = result.cross_check_summary.get('acroform_mismatches') or []
|
||||
assert not any(item.get('field_code') == 'bill_to_customer' for item in mismatches)
|
||||
assert 'xfa_acroform_mismatch' not in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_english_month_date_matches_normalized_dataset_date(monkeypatch):
|
||||
"""AcroForm 的英文月名日期与 datasets ISO 日期一致时不得误判为冲突。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
|
||||
Reference in new issue
Block a user