Files
syops/backend/tests/test_shipping_xfa_profile_extraction.py
hugo 4ec436d44c feat(shipping-notice): 完善 XFA 模板映射与订单审核流程
- 统一 XFA 数据集、字段拆分、校验及运行时解析
- 完善订单模板管理、发布检查与迁移状态
- 优化订单审核草稿、预约回退及 STP 投影缓存
- 更新前端模板编辑器、映射组件与多语言错误文案
- 补充后端与前端测试,并更新本地集成启动配置
2026-09-12 22:41:21 +08:00

729 lines
32 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
tests/test_shipping_xfa_profile_extraction.py
用途:阶段 3 XFA Header/Line 提取与类型标准化 golden 验收。
依赖:xfa_profile_extraction、xfa_dataset、annotation expected.json、pytest。
逻辑:用脱敏 datasets fixture + 冻结映射提取,断言验收字段与 A/B 预期一致;
权威集合缺失时 fail-closed。
"""
from __future__ import annotations
import json
from decimal import Decimal
from types import SimpleNamespace
import pytest
from app.core.errors import ValidationError
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XfaSplitMatcher,
XfaSplitRule,
XfaSplitRuleSet,
XfaSplitSegment,
new_segment_id,
)
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
_is_formal_header_leaf,
normalize_definition,
)
from tests.test_shipping_xfa_helpers import FIXTURE_ROOT, load_datasets_fixture
pytestmark = pytest.mark.pure_unit
def _expected() -> dict:
"""加载 annotation expected.json。"""
return json.loads((FIXTURE_ROOT / 'annotation' / 'expected.json').read_text(encoding='utf-8'))
def _schema_definition() -> dict:
"""构造覆盖 golden 字段的 Schema definition。"""
fields = [
{'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
{'field_id': 'f-total', 'field_code': 'total_amount', 'scope': 'header', 'value_type': 'decimal',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'f-mat', 'field_code': 'material_no', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line', 'value_type': 'decimal',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'f-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'f-pu', 'field_code': 'price_unit', 'scope': 'line', 'value_type': 'integer',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
{'field_id': 'f-amt', 'field_code': 'amount', 'scope': 'line', 'value_type': 'decimal',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
{'field_id': 'f-date', 'field_code': 'delivery_date', 'scope': 'line', 'value_type': 'date',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['iso_date']},
]
return {'fields': fields}
def _xfa_binding(
*,
binding_id: str,
field_id: str,
field_code: str,
scope: str,
path_id: str,
data_path: str,
) -> dict:
"""构造最小合法统一 binding(正式提取 bindings-only)。"""
return {
'binding_id': binding_id,
'field_id': field_id,
'field_code': field_code,
'scope': scope,
'value_binding': {
'type': 'xfa_dataset',
'path_id': path_id,
'data_path': data_path,
},
'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,
},
}
def _raw_profile(*, authoritative: str = '/data/ITEMS/DATA') -> dict:
"""构造冻结 XFA Profile(bindings-only,无 legacy mappings)。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
summary = build_signature_summary(
template_bytes=b'<template><subform name="form"/></template>',
dataset_nodes=analysis.nodes,
)
bindings = [
_xfa_binding(
binding_id='bind-m-po', field_id='f-po', field_code='customer_po_no',
scope='header', path_id='path-po', data_path='/data/HEADER/EBELN',
),
_xfa_binding(
binding_id='bind-m-total', field_id='f-total', field_code='total_amount',
scope='header', path_id='path-total', data_path='/data/HEADER/TOTAL_AMOUNT',
),
_xfa_binding(
binding_id='bind-m-mat', field_id='f-mat', field_code='material_no',
scope='line', path_id='path-mat', data_path=f'{authoritative}/MATNR',
),
_xfa_binding(
binding_id='bind-m-qty', field_id='f-qty', field_code='quantity',
scope='line', path_id='path-qty', data_path=f'{authoritative}/MENGE',
),
_xfa_binding(
binding_id='bind-m-price', field_id='f-price', field_code='unit_price',
scope='line', path_id='path-price', data_path=f'{authoritative}/NETPR',
),
_xfa_binding(
binding_id='bind-m-pu', field_id='f-pu', field_code='price_unit',
scope='line', path_id='path-pu', data_path=f'{authoritative}/PEINH',
),
_xfa_binding(
binding_id='bind-m-amt', field_id='f-amt', field_code='amount',
scope='line', path_id='path-amt', data_path=f'{authoritative}/AMOUNT',
),
_xfa_binding(
binding_id='bind-m-date', field_id='f-date', field_code='delivery_date',
scope='line', path_id='path-date', data_path=f'{authoritative}/EINDT',
),
]
return {
'profile_id': 7,
'profile_code': 'XFA_GOLDEN',
'version': 1,
'checksum': 'c' * 64,
'status': 'published',
'template_mode': 'xfa_dataset',
'definition': {
'template_mode': 'xfa_dataset',
'source_contract': {
'template_packet_checksum': summary['template_packet_checksum'],
'dataset_structure_fingerprint': summary['dataset_structure_fingerprint'],
'dataset_root_path': '/data',
'authoritative_line_collection_path': authoritative,
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
},
'header_mappings': [],
'line_mapping': {
'row_path': authoritative,
'fields': [],
},
'bindings': bindings,
# NETPR 是复合展示值;正式 unit_price 必须通过管理员确认的声明式规则取得。
'split_rules': [XfaSplitRuleSet(
rule_set_id='netpr-unit-price-v1',
rule_version=1,
source_path_id='path-price',
source_scope='line',
source_field_code='NETPR',
rules=[
XfaSplitRule(
rule_id='netpr-unit-price',
matcher=XfaSplitMatcher(
type='regex', pattern=r'^(.+) / ([0-9]+)$', capture_group=1,
),
segment=XfaSplitSegment(
segment_id=new_segment_id(),
segment_code='unit_price',
display_name='单价',
handling='mapped',
target_field_id='f-price',
target_field_code='unit_price',
),
),
],
unmatched_line_policy='needs_review',
source='user',
status='confirmed',
requires_confirmation=False,
).model_dump(mode='json')],
'cross_checks': {
'acroform_enabled': True,
'mirror_collection_policy': 'must_match_when_present',
'line_amount_formula': 'quantity_times_unit_price',
'total_amount_policy': 'must_equal_line_sum',
},
},
}
def _field_values(rows: list[dict]) -> dict[str, object]:
"""从首行提取 field_code → value。"""
assert rows
return {
str(item.get('field_code')): item.get('value')
for item in rows[0].get('fields') or []
if isinstance(item, dict)
}
def test_golden_header_and_line_extraction():
"""关键断言:正式提取与 annotation golden A/B 字段一致。"""
expected = _expected()
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=_schema_definition(),
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
)
assert result.status == 'parsed'
assert result.reason_codes == []
values = _field_values(result.rows)
assert str(values['customer_po_no']) == expected['header']['customer_po_no']
assert str(values['material_no']) == expected['lines'][0]['material_no']
assert str(values['quantity']) == expected['lines'][0]['quantity']
assert Decimal(str(values['unit_price'])) == Decimal(expected['lines'][0]['unit_price'])
assert str(values['price_unit']) == expected['lines'][0]['price_unit']
assert Decimal(str(values['amount'])) == Decimal(expected['lines'][0]['amount'])
assert str(values['delivery_date']) == expected['lines'][0]['delivery_date']
# Evidence refs 不得含完整 XML / 明文路径。
summary = result.evidence_summary
blob = json.dumps(summary, ensure_ascii=False)
assert '<data>' not in blob
assert '/data/HEADER/EBELN' not in blob
for ref in summary.get('field_evidence_refs') or []:
assert 'data_path' not in ref
assert 'raw_value' not in ref
assert ref.get('source') == 'xfa_dataset'
assert 'data_path_hash' in ref
def test_line_reservation_can_inherit_a_formal_header_dataset_value():
"""关键断言:全单 Header Reservation 可审计地投影到每个业务明细行。"""
xml = load_datasets_fixture().replace(
b'<TOTAL_AMOUNT>26961.60</TOTAL_AMOUNT>',
b'<TOTAL_AMOUNT>26961.60</TOTAL_AMOUNT><SHIPMENT_TEXT>1000144510</SHIPMENT_TEXT>',
)
analysis = parse_xfa_datasets(xml)
schema = _schema_definition()
schema['fields'].append({
'field_id': 'f-reservation', 'field_code': 'reservation_id', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [],
})
raw_profile = _raw_profile()
raw_profile['definition']['bindings'].append(_xfa_binding(
binding_id='bind-m-reservation', field_id='f-reservation', field_code='reservation_id',
scope='line', path_id='path-shipment-text', data_path='/data/HEADER/SHIPMENT_TEXT',
))
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=schema,
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
)
assert result.status == 'parsed'
reservation = next(item for item in result.rows[0]['fields'] if item['field_code'] == 'reservation_id')
assert reservation['value'] == '1000144510'
assert reservation['inherited_from_header'] is True
assert reservation['evidence_ref']['source'] == 'xfa_dataset'
def test_confirmed_matnr_split_keeps_match_audit_out_of_review_reasons():
"""确定的 MATNR 拆分可保留命中审计,但不得被误判为需要复核。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
schema = _schema_definition()
schema['fields'].extend([
{'field_id': 'f-customer-part', 'field_code': 'customer_part_number', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
{'field_id': 'f-part', 'field_code': 'part_number', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
])
raw_profile['definition']['bindings'].extend([
_xfa_binding(
binding_id='bind-customer-part', field_id='f-customer-part',
field_code='customer_part_number', scope='line', path_id='path-mat',
data_path='/data/ITEMS/DATA/MATNR',
),
_xfa_binding(
binding_id='bind-part', field_id='f-part', field_code='part_number',
scope='line', path_id='path-mat', data_path='/data/ITEMS/DATA/MATNR',
),
])
raw_profile['definition']['split_rules'].append(XfaSplitRuleSet(
rule_set_id='matnr-split-audit-v1',
rule_version=1,
source_path_id='path-mat',
source_scope='line',
source_field_code='MATNR',
rules=[
XfaSplitRule(
rule_id='customer-part',
matcher=XfaSplitMatcher(type='position', line_index=1),
segment=XfaSplitSegment(
segment_id=new_segment_id(), segment_code='customer_part',
display_name='客户料号', handling='mapped',
target_field_id='f-customer-part', target_field_code='customer_part_number',
),
),
XfaSplitRule(
rule_id='part-number',
matcher=XfaSplitMatcher(
type='prefix', value='MPN', separators=[':'], case_sensitive=False,
),
segment=XfaSplitSegment(
segment_id=new_segment_id(), segment_code='part_number',
display_name='内部料号', handling='mapped',
target_field_id='f-part', target_field_code='part_number',
),
),
],
unmatched_line_policy='evidence_only',
source='user',
status='confirmed',
requires_confirmation=False,
).model_dump(mode='json'))
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=schema,
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
)
assert result.status == 'parsed'
assert 'xfa_split:line_match_candidates' not in result.rows[0]['issues']
def _normalization_path_context(analysis):
"""构造保存期路径上下文,模拟冻结分析只暴露受控 path_id。"""
path_map = {}
header_leaf_path_ids = set()
def walk(node):
path_map[node.path_id] = node.data_path
if node.is_leaf and node.is_header_candidate:
header_leaf_path_ids.add(node.path_id)
for child in node.children:
walk(child)
for root in analysis.nodes:
walk(root)
return {
'path_map': path_map,
'known_path_ids': set(path_map),
'header_leaf_path_ids': header_leaf_path_ids,
'dataset_root_path': analysis.dataset_root_path,
'template_packet_checksum': 'sha256:' + ('a' * 64),
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
}
def _normalization_raw_profile(analysis):
"""将提取 golden 的占位 path_id 替换为当前分析的真实受控路径。"""
raw = _raw_profile()['definition']
# 保存期规范化关注 binding / 视觉框契约,不依赖黄金测试的演示拆分规则。
raw.pop('split_rules', None)
context = _normalization_path_context(analysis)
path_id_by_path = {data_path: path_id for path_id, data_path in context['path_map'].items()}
for binding in raw['bindings']:
value = binding['value_binding']
value['path_id'] = path_id_by_path[value['data_path']]
binding['field_layout_id'] = f"layout-{binding['scope']}-{binding['field_code']}"
raw['order_field_layouts'] = [
{
'layout_id': binding['field_layout_id'],
'field_id': binding['field_id'],
'field_code': binding['field_code'],
'scope': binding['scope'],
}
for binding in raw['bindings']
]
context['template_packet_checksum'] = raw['source_contract']['template_packet_checksum']
context['dataset_structure_fingerprint'] = raw['source_contract']['dataset_structure_fingerprint']
return raw, context, path_id_by_path
def test_normalize_definition_allows_line_binding_to_known_header_leaf():
"""保存期断言:行字段可显式继承分析器确认的 Header 叶子。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
schema = _schema_definition()
schema['fields'].append({
'field_id': 'f-reservation', 'field_code': 'reservation_id', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [],
})
raw, context, path_id_by_path = _normalization_raw_profile(analysis)
raw['bindings'].append(_xfa_binding(
binding_id='bind-reservation-header', field_id='f-reservation',
field_code='reservation_id', scope='line', path_id=path_id_by_path['/data/HEADER/EBELN'],
data_path='/data/HEADER/EBELN',
))
raw['bindings'][-1]['field_layout_id'] = 'layout-line-reservation_id'
raw['order_field_layouts'].append({
'layout_id': 'layout-line-reservation_id',
'field_id': 'f-reservation',
'field_code': 'reservation_id',
'scope': 'line',
})
normalized = normalize_definition(
raw,
schema_version=SimpleNamespace(definition_json=schema),
path_context=context,
)
reservation = next(item for item in normalized['bindings'] if item['field_code'] == 'reservation_id')
assert reservation['scope'] == 'line'
assert reservation['value_binding']['path_id'] == path_id_by_path['/data/HEADER/EBELN']
def test_normalize_definition_freezes_schema_identity_for_visual_header_line_field():
"""视觉表头 ITEM/QTY 可映射为 Line 字段,保存时仍必须冻结 field_id。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
raw['table_regions'] = [{
'region_id': 'table_one', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .8},
'header_layouts': [{
'layout_id': 'header_one', 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .25},
'field_regions': [{
'field_id': '', 'field_code': 'quantity', 'scope': 'line',
'region': {'x0': .4, 'y0': .2, 'x1': .5, 'y1': .25},
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
'minimum_evidence_level': 'coordinate',
}],
}],
'line_layouts': [], 'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
'termination_rules': [], 'exclusion_regions': [], 'draft_unbound_field_regions': [],
}]
normalized = normalize_definition(
raw, schema_version=SimpleNamespace(definition_json=_schema_definition()), path_context=context,
)
field = normalized['table_regions'][0]['header_layouts'][0]['field_regions'][0]
assert field['field_id'] == 'f-qty'
assert field['scope'] == 'line'
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())
schema = _schema_definition()
schema['fields'].extend([
{
'field_id': 'f-reservation-header', 'field_code': 'reservation_id', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'required': False,
'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'f-reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [],
},
])
raw, context, path_id_by_path = _normalization_raw_profile(analysis)
raw['order_field_layouts'].append({
'layout_id': 'layout-header-reservation_id',
'field_id': 'f-reservation-header',
'field_code': 'reservation_id',
'scope': 'header',
})
raw['bindings'].append({
**_xfa_binding(
binding_id='bind-reservation-header-layout', field_id='f-reservation-line',
field_code='reservation_id', scope='line', path_id=path_id_by_path['/data/HEADER/EBELN'],
data_path='/data/HEADER/EBELN',
),
'field_layout_id': 'layout-header-reservation_id',
})
normalized = normalize_definition(
raw,
schema_version=SimpleNamespace(definition_json=schema),
path_context=context,
)
reservation = next(item for item in normalized['bindings'] if item['field_code'] == 'reservation_id')
assert reservation['scope'] == 'line'
assert reservation['field_layout_id'] == 'layout-header-reservation_id'
def test_normalize_definition_allows_split_target_to_reuse_its_single_source_visual_layout():
"""拆分目标复用 MATNR 源框,禁止为同一物理值框伪造重叠字段框。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
schema = _schema_definition()
schema['fields'].append({
'field_id': 'f-customer-part', 'field_code': 'customer_part_number', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [],
})
raw, context, path_id_by_path = _normalization_raw_profile(analysis)
matnr_path_id = path_id_by_path['/data/ITEMS/DATA/MATNR']
raw['split_rules'] = [XfaSplitRuleSet(
rule_set_id='matnr-split-target-v1', rule_version=1,
source_path_id=matnr_path_id, source_scope='line', source_field_code='MATNR',
source='user', status='confirmed', requires_confirmation=False,
rules=[
XfaSplitRule(
rule_id='internal-part',
matcher=XfaSplitMatcher(type='position', line_index=1),
segment=XfaSplitSegment(
segment_id=new_segment_id(), segment_code='customer_part',
display_name='客户料号', handling='mapped',
target_field_id='f-customer-part', target_field_code='customer_part_number',
),
),
],
).model_dump(mode='json')]
raw['bindings'].append({
**_xfa_binding(
binding_id='bind-split-customer-part', field_id='f-customer-part',
field_code='customer_part_number', scope='line', path_id=matnr_path_id,
data_path='/data/ITEMS/DATA/MATNR',
),
'field_layout_id': 'layout-line-material_no',
'split_rule_ref': {
'rule_set_id': 'matnr-split-target-v1',
'segment_id': raw['split_rules'][0]['rules'][0]['segment']['segment_id'],
},
})
normalized = normalize_definition(
raw,
schema_version=SimpleNamespace(definition_json=schema),
path_context=context,
)
target = next(item for item in normalized['bindings'] if item['field_code'] == 'customer_part_number')
assert target['field_layout_id'] == 'layout-line-material_no'
def test_normalize_definition_rejects_line_binding_to_non_leaf_header_node():
"""保存期断言:行字段不得借 Header 继承读取集合、根或描述节点。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
raw['bindings'][2]['value_binding'] = {
'type': 'xfa_dataset',
'path_id': next(node.path_id for node in analysis.nodes[0].children if node.local_name == 'HEADER'),
'data_path': '/data/HEADER',
}
with pytest.raises(ValidationError) as exc_info:
normalize_definition(
raw,
schema_version=SimpleNamespace(definition_json=_schema_definition()),
path_context=context,
)
assert exc_info.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
assert exc_info.value.details['reason'] == 'line_header_inheritance_source_invalid'
def test_normalize_definition_rejects_line_binding_to_header_description_leaf():
"""保存期断言:dataDescription 的 Header 叶子不是可继承的正式数据值。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
description_path = '/datasets/dataDescription/data/HEADER/EBELN'
description_path_id = 'path-description-header-ebeln'
# 模拟真实 XFA 同时携带 data/data 与 dataDescription/data 两棵树的分析结果。
context['path_map'][description_path_id] = description_path
context['known_path_ids'].add(description_path_id)
assert _is_formal_header_leaf(SimpleNamespace(
data_path=description_path,
is_leaf=True,
is_header_candidate=True,
)) is False
raw['bindings'][2]['value_binding'] = {
'type': 'xfa_dataset',
'path_id': description_path_id,
'data_path': description_path,
}
with pytest.raises(ValidationError) as exc_info:
normalize_definition(
raw,
schema_version=SimpleNamespace(definition_json=_schema_definition()),
path_context=context,
)
assert exc_info.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
assert exc_info.value.details['reason'] == 'line_header_inheritance_source_invalid'
def test_authoritative_collection_missing_fails_closed():
"""关键断言:权威集合缺失 → needs_review reason。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile(authoritative='/data/ITEMS/MISSING')
raw_profile['definition']['source_contract']['authoritative_line_collection_path'] = '/data/ITEMS/MISSING'
raw_profile['definition']['line_mapping']['row_path'] = '/data/ITEMS/MISSING'
for item in raw_profile['definition']['bindings']:
if item.get('scope') == 'line':
item['value_binding']['data_path'] = str(item['value_binding']['data_path']).replace(
'/data/ITEMS/DATA', '/data/ITEMS/MISSING',
)
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=_schema_definition(),
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
)
assert result.status == 'failed'
assert 'xfa_authoritative_collection_missing' in result.reason_codes
def test_netpr_composite_requires_an_explicit_split_rule():
"""关键断言:NETPR 复合文本未配置拆分规则时不得隐式生成任何正式字段。"""
from app.services.shipping_notice.document_layout.order_profile_extractors import (
extract_profile_field_value,
registered_extractor_output_codes,
)
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
# 坐标解析器不再注册 NETPR 的隐式多字段拆分;必须由两个视觉框或 XFA 显式规则提供字段值。
assert extract_profile_field_value(
extractor_key='unit_price_price_unit', field_code='unit_price', raw='898.72 / 1',
) == {}
assert registered_extractor_output_codes(
extractor_key='unit_price_price_unit', field_code='unit_price',
) == set()
# Schema 标准化不得按字段名猜测拆分;只有显式拆分规则产出的单值才可转换 decimal。
with pytest.raises(ValidationError) as exc_info:
normalize_order_field_value(
'898.72 / 1',
{'field_code': 'unit_price', 'value_type': 'decimal', 'normalizer_key': 'trim'},
)
assert exc_info.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
# 正式提取:没有拆分规则时,复合 NETPR 仅保留问题证据,不能伪造 unit_price/price_unit。
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
raw_profile['definition'].pop('split_rules', None)
raw_profile['definition']['bindings'] = [
item for item in raw_profile['definition']['bindings']
if item.get('field_code') != 'price_unit'
]
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=_schema_definition(),
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
)
assert result.status == 'needs_review'
values = _field_values(result.rows)
assert 'unit_price' not in values
assert 'price_unit' not in values
assert 'order_profile_field_invalid:unit_price' in result.rows[0]['issues']
assert 'xfa_source_mapping_incomplete' in result.reason_codes
def test_missing_bindings_fails_closed():
"""关键断言:无末端映射 → xfa_mapping_required。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
raw_profile['definition']['bindings'] = []
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=_schema_definition(),
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
)
assert result.status == 'failed'
assert 'xfa_mapping_required' in result.reason_codes
def test_dual_binding_source_fails_closed():
"""关键断言:bindings 与 legacy mappings 共存 → xfa_dual_binding_source。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
raw_profile['definition']['header_mappings'] = [{
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
'value_type': 'string', 'normalizer_key': 'trim',
}]
result = extract_xfa_profile(
raw_profile=raw_profile,
dataset_analysis=analysis,
schema_definition=_schema_definition(),
document_id=85,
packet_checksum='sha256:' + ('a' * 64),
)
assert result.status == 'failed'
assert 'xfa_dual_binding_source' in result.reason_codes