feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

@@ -0,0 +1,382 @@
"""
tests/test_shipping_xfa_profile_phase2.py
用途:阶段 2 XFA Profile 创建/映射保存/Revision/Lease 409 focused 验收。
依赖:creation_service、profile_service、lease_service、xfa helpers、pytest app fixture。
逻辑:合成 XFA hybrid PDF → 落库结构分析 → 向导创建 → 保存映射 → 校验 checksum/Revision;
覆盖未知 path_id、租约冲突与旧 lock_version。
"""
from __future__ import annotations
from datetime import datetime
from hashlib import sha256
import pytest
from app.extensions import db
from app.models import (
FileAsset,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileDraftRevision,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf, persist_xfa_structure_analysis
from app.services.shipping_notice.document_layout.xfa_dataset import _path_id_for
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
def _schema_with_required() -> ShippingOrderSchemaVersion:
"""发布含必填 Header/Line 字段的 Schema。"""
schema = ShippingOrderSchema(schema_code='XFA_ORDER', display_name='XFA Order')
db.session.add(schema)
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id,
version=1,
status='published',
checksum='c' * 64,
published_at=datetime.utcnow(),
definition_json={'fields': [
{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['xfa_dataset', 'pdf_coordinate'],
},
{
'field_id': 'f-mat', 'field_code': 'material_no', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['xfa_dataset', 'pdf_coordinate'],
},
]},
)
db.session.add(version)
db.session.commit()
return version
def _seed_xfa_sample(*, user: User) -> tuple[ShippingOrderDocument, dict[str, str], bytes]:
"""写入合成 XFA 样本与 ready 分析。"""
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
content_hash = sha256(pdf_bytes).hexdigest()
asset = FileAsset(
asset_no=f'FA-XFA-{content_hash[:10]}',
owner_user_id=user.id,
original_filename='xfa-sample.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'xfa/{content_hash}.pdf',
content_hash=content_hash,
file_size=len(pdf_bytes),
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='referenced',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f'SNI-XFA-{content_hash[:8].upper()}',
asset_id=asset.id,
user_id=user.id,
purpose='order_document_profile_sample',
parse_status='parsed',
parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key=f'xfa/{content_hash}.pdf',
filename='xfa-sample.pdf',
content_hash=content_hash,
classification='supporting',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
outcome = analyze_xfa_pdf(pdf_bytes)
assert outcome.dataset_analysis is not None
layout = dict(outcome.snapshot)
layout['status'] = 'ready'
layout['provider'] = 'xfa'
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
layout_version = record_inline_layout_snapshot(document, layout)
persist_xfa_structure_analysis(
document_id=document.id,
layout_version_id=layout_version.id,
source_content_hash=content_hash,
outcome=outcome,
)
db.session.commit()
paths = {
'ITEMS_DATA': _path_id_for('/data/ITEMS/DATA'),
'ITEMS1_DATA': _path_id_for('/data/ITEMS1/DATA'),
'EBELN': _path_id_for('/data/HEADER/EBELN'),
'MATNR': _path_id_for('/data/ITEMS/DATA/MATNR'),
}
return document, paths, pdf_bytes
@pytest.fixture
def _patch_xfa_io(monkeypatch):
"""让 XFA path 解析与 layout 读取使用内存合成 PDF。"""
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
def _fake_read(_asset):
return pdf_bytes
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', _fake_read)
def _fake_layout(document):
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
return current_layout_snapshot(document) or {}
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._document_layout',
_fake_layout,
)
def test_xfa_wizard_creates_draft_without_table_id(app, _patch_xfa_io):
"""关键断言:XFA 向导不要求 table_id,落库 template_mode=xfa_dataset。"""
with app.app_context():
user = User(username='xfa-admin', email='xfa-admin@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
schema = _schema_with_required()
document, paths, _ = _seed_xfa_sample(user=user)
created = creation_service.complete_wizard({
'display_name': 'XFA Wizard',
'schema_version_id': schema.id,
'document_id': document.id,
'authoritative_collection_path_id': paths['ITEMS_DATA'],
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
'browser_session_id': 'xfa-tab-1',
'operation_id': 'xfa-wizard-op-1',
}, actor_id=user.id)
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
assert profile.template_mode == 'xfa_dataset'
assert profile.definition_json['source_contract']['authoritative_line_collection_path'] == '/data/ITEMS/DATA'
assert created['edit_lease']['lease_token']
assert ShippingOrderDocumentProfileAudit.query.filter_by(
profile_id=profile.id, event_type='xfa_draft_created',
).count() == 1
def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_io):
"""关键断言:修改映射产生新 Revision + checksum,并清空 matching signature。"""
with app.app_context():
user = User(username='xfa-mapper', email='xfa-mapper@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
schema = _schema_with_required()
document, paths, _ = _seed_xfa_sample(user=user)
created = creation_service.complete_wizard({
'display_name': 'XFA Map',
'schema_version_id': schema.id,
'document_id': document.id,
'authoritative_collection_path_id': paths['ITEMS_DATA'],
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
'browser_session_id': 'xfa-tab-2',
'operation_id': 'xfa-wizard-op-2',
}, actor_id=user.id)
profile_id = created['id']
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
profile.matching_signature_run_id = 99
profile.matching_signature_checksum = 'sigchecksum012345678901234567890123456789012345678901234567'
db.session.commit()
before_checksum = profile.structure_fingerprint
definition = dict(profile.definition_json)
definition['authoritative_collection_path_id'] = paths['ITEMS_DATA']
definition['header_mappings'] = [{
'mapping_id': 'm-po', 'field_id': 'ignored', 'field_code': 'customer_po_no',
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'], 'value_type': 'string',
}]
definition['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
saved = profile_service.save_draft(
{
'profile_code': profile.profile_code,
'display_name': profile.display_name,
'schema_version_id': schema.id,
'definition': definition,
'expected_lock_version': profile.lock_version,
'sample_document_id': document.id,
},
actor_id=user.id,
profile_id=profile_id,
browser_session_id='xfa-tab-2',
lease_token=created['edit_lease']['lease_token'],
operation_id='xfa-save-op-1',
enforce_lease=True,
)
refreshed = db.session.get(ShippingOrderDocumentProfile, profile_id)
assert refreshed.structure_fingerprint != before_checksum
assert refreshed.matching_signature_run_id is None
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id).count() >= 2
assert saved['definition']['header_mappings'][0]['field_id'] == 'f-po'
# 关键断言:Schema 必填明细字段可由 EML 等其他来源补充,不得成为 XFA 模板映射问题。
assert 'mapping_issues' not in saved
assert ShippingOrderDocumentProfileAudit.query.filter_by(
profile_id=profile_id, event_type='xfa_mapping_saved',
).count() >= 1
def test_xfa_unknown_path_id_blocked(app, _patch_xfa_io):
"""关键断言:未知 path_id 被服务端拒绝。"""
with app.app_context():
user = User(username='xfa-bad', email='xfa-bad@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
schema = _schema_with_required()
document, paths, _ = _seed_xfa_sample(user=user)
created = creation_service.complete_wizard({
'display_name': 'XFA Invalid',
'schema_version_id': schema.id,
'document_id': document.id,
'authoritative_collection_path_id': paths['ITEMS_DATA'],
'browser_session_id': 'xfa-tab-3',
'operation_id': 'xfa-wizard-op-3',
}, actor_id=user.id)
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
bad = dict(profile.definition_json)
bad['authoritative_collection_path_id'] = paths['ITEMS_DATA']
bad['header_mappings'] = [{
'mapping_id': 'm1', 'field_code': 'customer_po_no', 'path_id': 'path-unknown-xxx',
'data_path': '/data/HEADER/EBELN', 'value_type': 'string', 'field_id': 'x',
}]
with pytest.raises(Exception) as caught:
profile_service.save_draft(
{
'profile_code': profile.profile_code,
'display_name': profile.display_name,
'schema_version_id': schema.id,
'definition': bad,
'expected_lock_version': profile.lock_version,
'sample_document_id': document.id,
},
actor_id=user.id,
profile_id=profile.id,
browser_session_id='xfa-tab-3',
lease_token=created['edit_lease']['lease_token'],
operation_id='xfa-bad-path',
enforce_lease=True,
)
assert getattr(caught.value, 'code', '') in {
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
} or 'unknown' in str(caught.value).lower()
def test_xfa_collection_evidence_filters_empty_structures(app, _patch_xfa_io):
"""关键断言:集合 API 返回可读业务证据,空 dataDescription 只能进入不可选列表。"""
with app.app_context():
user = User(username='xfa-evidence', email='xfa-evidence@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
document, _paths, _ = _seed_xfa_sample(user=user)
payload = profile_service.get_xfa_collections(document.id, actor_id=user.id)
assert payload['collection_candidates']
assert all(item['selectable'] for item in payload['collection_candidates'])
authoritative = next(item for item in payload['collection_candidates'] if item['recommended_role'] == 'authoritative')
assert authoritative['path_label'] == 'data / ITEMS / DATA'
assert authoritative['recommendation_reasons'][0] == 'highest_business_coverage'
assert authoritative['non_empty_field_count'] > 0
assert any(item['field_name'] == 'MENGE' for item in authoritative['sample_fields'])
assert ShippingOrderDocumentProfileAudit.query.filter_by(
document_id=document.id,
event_type='xfa_collections_accessed',
).count() == 1
def test_xfa_value_preview_reveals_full_value_and_audits(app, _patch_xfa_io):
"""关键断言:受控完整值读取返回原值,并同时写 Profile 审计和统一敏感审计。"""
from app.models import ShippingAuditEvent
with app.app_context():
user = User(username='xfa-reveal', email='xfa-reveal@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
document, paths, _ = _seed_xfa_sample(user=user)
payload = profile_service.preview_xfa_sample_value(
document.id,
path_id=paths['EBELN'],
actor_id=user.id,
include_full_value=True,
)
db.session.commit()
assert payload['display_value'] == '4510039227'
assert payload['full_value_revealed'] is True
assert ShippingOrderDocumentProfileAudit.query.filter_by(
document_id=document.id,
event_type='xfa_sensitive_sample_value_read',
).count() == 1
assert ShippingAuditEvent.query.filter_by(
document_id=document.id,
event_type='xfa_sensitive_sample_value_read',
).count() == 1
def test_xfa_lease_conflict_and_stale_lock_version_return_409(app, _patch_xfa_io):
"""关键断言:租约冲突与旧 lock_version 写入返回稳定 409。"""
with app.app_context():
owner = User(username='xfa-owner', email='xfa-owner@example.com', role='admin', status='active')
other = User(username='xfa-other', email='xfa-other@example.com', role='admin', status='active')
db.session.add_all([owner, other])
db.session.flush()
schema = _schema_with_required()
document, paths, _ = _seed_xfa_sample(user=owner)
created = creation_service.complete_wizard({
'display_name': 'XFA Lease',
'schema_version_id': schema.id,
'document_id': document.id,
'authoritative_collection_path_id': paths['ITEMS_DATA'],
'browser_session_id': 'xfa-owner',
'operation_id': 'xfa-wizard-op-4',
}, actor_id=owner.id)
profile_id = created['id']
with pytest.raises(Exception) as lease_err:
lease_service.acquire_lease(
profile_id,
actor_id=other.id,
browser_session_id='xfa-intruder',
operation_id='lease-conflict',
confirm_takeover=False,
)
assert getattr(lease_err.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT'
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
definition = dict(profile.definition_json)
definition['authoritative_collection_path_id'] = paths['ITEMS_DATA']
with pytest.raises(Exception) as version_err:
profile_service.save_draft(
{
'profile_code': profile.profile_code,
'display_name': profile.display_name,
'schema_version_id': schema.id,
'definition': definition,
'expected_lock_version': max(profile.lock_version - 1, 0),
'sample_document_id': document.id,
},
actor_id=owner.id,
profile_id=profile_id,
browser_session_id='xfa-owner',
lease_token=created['edit_lease']['lease_token'],
operation_id='stale-lock',
enforce_lease=True,
)
assert getattr(version_err.value, 'code', None) in {
'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
'SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
}