Files
syops/backend/tests/test_shipping_xfa_profile_extraction.py
T

244 lines
11 KiB
Python

"""
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 _raw_profile(*, authoritative: str = '/data/ITEMS/DATA') -> dict:
"""构造冻结 XFA Profile。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
summary = build_signature_summary(
template_bytes=b'<template><subform name="form"/></template>',
dataset_nodes=analysis.nodes,
)
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': [
{
'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',
},
{
'mapping_id': 'm-total', 'field_id': 'f-total', 'field_code': 'total_amount',
'data_path': '/data/HEADER/TOTAL_AMOUNT', 'path_id': 'path-total',
'value_type': 'decimal', 'normalizer_key': 'trim',
},
],
'line_mapping': {
'row_path': authoritative,
'fields': [
{
'mapping_id': 'm-mat', 'field_id': 'f-mat', 'field_code': 'material_no',
'data_path': f'{authoritative}/MATNR', 'path_id': 'path-mat',
'value_type': 'string', 'normalizer_key': 'trim',
},
{
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
'data_path': f'{authoritative}/MENGE', 'path_id': 'path-qty',
'value_type': 'decimal', 'normalizer_key': 'trim',
},
{
'mapping_id': 'm-price', 'field_id': 'f-price', 'field_code': 'unit_price',
'data_path': f'{authoritative}/NETPR', 'path_id': 'path-price',
'value_type': 'decimal', 'normalizer_key': 'trim',
},
{
'mapping_id': 'm-pu', 'field_id': 'f-pu', 'field_code': 'price_unit',
'data_path': f'{authoritative}/PEINH', 'path_id': 'path-pu',
'value_type': 'integer', 'normalizer_key': 'trim',
},
{
'mapping_id': 'm-amt', 'field_id': 'f-amt', 'field_code': 'amount',
'data_path': f'{authoritative}/AMOUNT', 'path_id': 'path-amt',
'value_type': 'decimal', 'normalizer_key': 'trim',
},
{
'mapping_id': 'm-date', 'field_id': 'f-date', 'field_code': 'delivery_date',
'data_path': f'{authoritative}/EINDT', 'path_id': 'path-date',
'value_type': 'date', 'normalizer_key': 'trim',
},
],
},
'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_authoritative_collection_missing_fails_closed():
"""关键断言:权威集合缺失 → needs_review reason。"""
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile(authoritative='/data/ITEMS/MISSING')
# row_path 必须等于 authoritative;手工破坏集合路径以模拟缺失。
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']['line_mapping']['fields']:
item['data_path'] = item['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')
# 正式提取:去掉 PEINH 映射后仍应由 NETPR 复合值补齐 price_unit。
analysis = parse_xfa_datasets(load_datasets_fixture())
raw_profile = _raw_profile()
raw_profile['definition']['line_mapping']['fields'] = [
item
for item in raw_profile['definition']['line_mapping']['fields']
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 '')