"""
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
import pytest
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 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'',
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,
'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 '' 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_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_splits_unit_price_and_price_unit():
"""关键断言:NETPR ``898.72 / 1`` → unit_price=898.72、price_unit=1(无独立 PEINH 映射)。"""
from app.services.shipping_notice.document_layout.order_profile_extractors import (
parse_unit_price_with_price_unit,
)
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
# 解析器本身。
assert parse_unit_price_with_price_unit('898.72 / 1') == {
'unit_price': '898.72',
'price_unit': '1',
}
assert parse_unit_price_with_price_unit('898.72') is None
# Schema 标准化:复合值不得抛 Dynamic field value type is invalid。
typed = normalize_order_field_value(
'898.72 / 1',
{'field_code': 'unit_price', 'value_type': 'decimal', 'normalizer_key': 'trim'},
)
assert typed == Decimal('898.72')
# 正式提取:去掉 price_unit binding 后仍应由 NETPR 复合值补齐 price_unit。
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
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 == 'parsed'
values = _field_values(result.rows)
assert Decimal(str(values['unit_price'])) == Decimal('898.72')
assert str(values['price_unit']) == '1'
unit_item = next(
item for item in result.rows[0]['fields']
if item.get('field_code') == 'unit_price'
)
assert '898.72 / 1' in str(unit_item.get('quote') or '')
def test_missing_bindings_fails_closed():
"""关键断言:无 bindings → xfa_visual_bindings_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_visual_bindings_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