feat(shipping-notice): 落地 XFA 统一视觉拆分确认门禁与处理投影收敛
闭合拆分预览令牌单次消费、样本 checksum 绑定与确认审计;正式提取改为 bindings-only。 同步统一标注工作台交互,并补齐进度投影/任务中心与迁移文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d2b3d74def
commit
84a881b554
195 files changed
+20269
-3463
No files matched your search
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
backend/tests/performance/test_shipping_xfa_visual_mapping_load.py
|
||||
|
||||
用途:阶段 8 统一视觉映射建议/转换负载冒烟(合成数据,软阈值,非 flaky)。
|
||||
依赖:order_profile_unified_migration、time。
|
||||
逻辑:批量转换合成 XFA definition;断言在本地冒烟预算内完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
convert_xfa_definition_to_unified_bindings,
|
||||
)
|
||||
|
||||
|
||||
def _synthetic_xfa_definition(*, field_count: int = 40) -> dict:
|
||||
"""生成含多 Header/Line 映射的合成 XFA definition。"""
|
||||
headers = []
|
||||
lines = []
|
||||
for index in range(field_count // 2):
|
||||
headers.append({
|
||||
'mapping_id': f'map-h-{index}',
|
||||
'field_id': f'fld-h-{index}',
|
||||
'field_code': f'header_field_{index}',
|
||||
'data_path': f'/data/HEADER/F{index}',
|
||||
'path_id': f'path-h-{index}',
|
||||
'value_type': 'string',
|
||||
})
|
||||
lines.append({
|
||||
'mapping_id': f'map-l-{index}',
|
||||
'field_id': f'fld-l-{index}',
|
||||
'field_code': f'line_field_{index}',
|
||||
'data_path': f'/data/ITEMS/DATA/C{index}',
|
||||
'path_id': f'path-l-{index}',
|
||||
'value_type': 'string',
|
||||
})
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': headers,
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': lines},
|
||||
'bindings': [],
|
||||
'split_rules': [],
|
||||
}
|
||||
|
||||
|
||||
def test_visual_mapping_conversion_under_soft_latency_budget():
|
||||
"""40 字段统一转换应在软阈值(2s)内完成;失败才视为回归。"""
|
||||
definition = _synthetic_xfa_definition(field_count=40)
|
||||
started = time.perf_counter()
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(definition, widgets=[])
|
||||
elapsed = time.perf_counter() - started
|
||||
assert stats['binding_count'] == 40
|
||||
assert len(after['bindings']) == 40
|
||||
# 软阈值:本地合成转换远快于 2s;避免偶发 GC 抖动用宽松上限。
|
||||
assert elapsed < 2.0
|
||||
@@ -120,8 +120,8 @@ def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> t
|
||||
return saved, paths, lease['lease_token']
|
||||
|
||||
|
||||
def test_xfa_current_sample_summary_rejects_auto_create_missing():
|
||||
"""关键断言:auto_create_key 缺值时当前样本摘要必须失败。"""
|
||||
def test_current_sample_summary_still_supports_coordinate_schema_gate():
|
||||
"""通用摘要保留坐标模板的 Schema 门禁;XFA 调用方固定传零。"""
|
||||
status, summary, _ = validation_service._current_sample_summary(
|
||||
line_field_count=2, line_value_count=2, header_field_count=1, header_value_count=1,
|
||||
header_required_missing_count=0, auto_create_key_missing_count=1,
|
||||
|
||||
@@ -43,8 +43,8 @@ def test_xfa_definition_scale_and_identity_summary():
|
||||
assert 'blind' not in str(identity).lower()
|
||||
|
||||
|
||||
def test_xfa_readonly_mapping_evidence_has_no_pdf_preview():
|
||||
"""关键断言:只读映射 DTO 明确禁用 PDF 预览且不含盲测真值键。"""
|
||||
def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
"""关键断言:只读映射 DTO 声明 PDF 预览可用(阶段 2)。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
id=1,
|
||||
profile_code='XFA_RO',
|
||||
@@ -80,7 +80,7 @@ def test_xfa_readonly_mapping_evidence_has_no_pdf_preview():
|
||||
},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is False
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
assert evidence['template_mode'] == 'xfa_dataset'
|
||||
assert 'expected_rows' not in evidence
|
||||
assert 'expected_order_fields' not in evidence
|
||||
|
||||
@@ -123,3 +123,28 @@ def test_hash_verify_detects_tampered_chain(app):
|
||||
# 关键断言:篡改链被日检检出。
|
||||
assert int(result['hash_verify']['failed_chains']) >= 1
|
||||
assert result['hash_verify']['failures_sample']
|
||||
|
||||
|
||||
def test_retention_job_includes_xfa_snapshot_purge_key(app):
|
||||
"""shipping-audit-retention 必须覆盖 XFA 快照清理(阶段 8)。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = False
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=10, dry_run=True, hash_sample_limit=10, xfa_snapshot_limit=50),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:结果含 xfa_snapshots 清理统计,证明 Job 仍覆盖 XFA 快照。
|
||||
assert 'xfa_snapshots' in result
|
||||
assert 'scanned' in result['xfa_snapshots']
|
||||
assert 'deleted' in result['xfa_snapshots']
|
||||
retention = get_platform_job('shipping-audit-retention')
|
||||
assert retention is not None
|
||||
schema_keys = {field['key'] for field in retention.params_schema}
|
||||
assert 'xfa_snapshot_limit' in schema_keys or 'limit' in schema_keys
|
||||
|
||||
|
||||
def test_retention_days_default_is_1095(app):
|
||||
"""审计保留期默认 1095 天(3 年),阶段 8 运营验收。"""
|
||||
with app.app_context():
|
||||
days = int(app.config.get('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS') or 0)
|
||||
assert days == 1095
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_lifecycle.py
|
||||
|
||||
用途:验证 L1 版面快照 checksum、版本幂等、容量门禁和当前成功版本保护。
|
||||
依赖:ShippingOrderDocument/LayoutVersion、document_layout.lifecycle、Flask 测试库。
|
||||
逻辑:相同快照复用;新失败/超限版本保留审计但不覆盖旧成功引用。
|
||||
用途:验证 L1 版面快照 checksum、版本幂等、XFA 证据本地化、容量门禁和当前成功版本保护。
|
||||
依赖:ShippingOrderDocument/LayoutVersion/XfaStructureAnalysis、document_layout.lifecycle、Flask 测试库。
|
||||
逻辑:相同快照复用;XFA 复用同步克隆 document-scoped 分析;失败版本不覆盖旧成功引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,7 +11,15 @@ from __future__ import annotations
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import Job, ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake, FileAsset, User
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
Job,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingXfaStructureAnalysis,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
canonical_layout_payload,
|
||||
claim_layout_version,
|
||||
@@ -190,6 +198,123 @@ def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
|
||||
assert scheduled.id != incomplete.id
|
||||
|
||||
|
||||
def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app):
|
||||
"""相同 XFA 文件复用时,目标 Document 必须获得独立 Analysis 并重写快照身份。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
source_analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=original.id,
|
||||
layout_version_id=None,
|
||||
source_content_hash=original.content_hash,
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
template_packet_checksum='sha256:template',
|
||||
datasets_packet_checksum='sha256:datasets',
|
||||
dataset_structure_fingerprint='sha256:structure',
|
||||
packet_checksums_json={'datasets': 'sha256:datasets'},
|
||||
stats_json={'leaf_count': 8},
|
||||
security_summary_json={'scripts_executed': False},
|
||||
tree_summary_json={'known_path_ids': ['path-1']},
|
||||
parser_identity='xfa-parser.v1',
|
||||
contract_version='xfa-contract.v1',
|
||||
)
|
||||
db.session.add(source_analysis)
|
||||
db.session.flush()
|
||||
source_layout = record_inline_layout_snapshot(original, {
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'provider_version': 'xfa-parser.v1',
|
||||
'backend': 'pypdf',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
'template_packet_checksum': source_analysis.template_packet_checksum,
|
||||
'dataset_structure_fingerprint': source_analysis.dataset_structure_fingerprint,
|
||||
},
|
||||
'capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
},
|
||||
})
|
||||
source_analysis.layout_version_id = source_layout.id
|
||||
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-XFA-DUPLICATE', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(duplicate_intake)
|
||||
db.session.flush()
|
||||
duplicate = ShippingOrderDocument(
|
||||
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
|
||||
attachment_key='duplicate-xfa.pdf', filename='duplicate-xfa.pdf',
|
||||
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.flush()
|
||||
|
||||
localized = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
target_analysis = ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).one()
|
||||
target_capability = localized.payload_json['xfa_capability']
|
||||
assert localized.document_id == duplicate.id
|
||||
assert localized.id != source_layout.id
|
||||
assert target_analysis.id != source_analysis.id
|
||||
assert target_analysis.layout_version_id == localized.id
|
||||
assert target_analysis.source_content_hash == duplicate.content_hash
|
||||
assert target_analysis.dataset_structure_fingerprint == source_analysis.dataset_structure_fingerprint
|
||||
assert target_capability['structure_analysis_id'] == target_analysis.id
|
||||
assert localized.payload_json['capability']['structure_analysis_id'] == target_analysis.id
|
||||
|
||||
|
||||
def test_xfa_layout_without_source_analysis_is_not_reused(app):
|
||||
"""XFA 快照声明 ready 但源 Analysis 缺失时必须重新排队,禁止复制伪 ready 状态。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
source_layout = record_inline_layout_snapshot(original, {
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'provider_version': 'xfa-parser.v1',
|
||||
'backend': 'pypdf',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': 999999,
|
||||
'template_packet_checksum': 'sha256:template',
|
||||
'dataset_structure_fingerprint': 'sha256:structure',
|
||||
},
|
||||
})
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-XFA-MISSING-ANALYSIS', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(duplicate_intake)
|
||||
db.session.flush()
|
||||
duplicate = ShippingOrderDocument(
|
||||
intake_id=duplicate_intake.id, asset_id=original.asset_id, document_type='attachment',
|
||||
attachment_key='duplicate-xfa-missing.pdf', filename='duplicate-xfa-missing.pdf',
|
||||
content_hash=original.content_hash, classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.flush()
|
||||
|
||||
scheduled = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
assert source_layout.status == 'ready'
|
||||
assert scheduled.document_id == duplicate.id
|
||||
assert scheduled.status == 'queued'
|
||||
assert duplicate.current_layout_version_id is None
|
||||
assert ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).count() == 0
|
||||
|
||||
|
||||
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
|
||||
"""布局实现指纹变化后自动创建新版本,不依赖人工修改环境变量。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
|
||||
@@ -304,6 +304,34 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
|
||||
assert executed['latest_run']['status'] == 'passed'
|
||||
|
||||
|
||||
def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
|
||||
"""关键断言:HTML 表格存在但坐标证据缺失时,不得进入会必然失败的正式复核。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
for document in documents:
|
||||
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=documents[0].id, table_id='table-1',
|
||||
sample_role='training', created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
layout_version = documents[1].current_layout_version
|
||||
payload = dict(layout_version.payload_json)
|
||||
payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}}
|
||||
layout_version.payload_json = payload
|
||||
db.session.commit()
|
||||
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
candidate = next(
|
||||
item for item in quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
if item['document_id'] == documents[1].id
|
||||
)
|
||||
assert candidate['review_mode'] == 'preparing'
|
||||
assert candidate['confirmable'] is False
|
||||
assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing']
|
||||
|
||||
|
||||
def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
||||
"""关键断言:失败 Layout 可从原 PDF 诊断,但不能确认成盲测真值。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -104,3 +104,9 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
|
||||
assert edited.after_snapshot_json.get('match_status') is None
|
||||
meta = edited.metadata_json or {}
|
||||
assert 'rerun_inventory_matching' in (meta.get('applied_effects') or [])
|
||||
field_changes = meta.get('field_changes') or []
|
||||
assert field_changes
|
||||
assert 'previous_value' in field_changes[0]
|
||||
assert 'new_value' in field_changes[0]
|
||||
assert field_changes[0]['previous_value'] == '3000000001'
|
||||
assert field_changes[0]['new_value'] == '3000092917'
|
||||
@@ -86,10 +86,11 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
|
||||
|
||||
def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch):
|
||||
"""物化后新出现的 PDF 必须先排布局 Job;布局运行中禁止进入模板路由。"""
|
||||
"""物化后新出现的 PDF 必须转交布局 Job,并明确当前 Job 只是成功完成交接。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=2, user_id=9, run_no='SNER-WORKER-WAIT-LAYOUT', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
@@ -112,7 +113,11 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'})
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting'))
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
def fake_finish_job(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish_job)
|
||||
monkeypatch.setattr(handler, 'route_deterministic_unit', lambda *_args, **_kwargs: events.append('routed'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
|
||||
@@ -120,6 +125,12 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
|
||||
assert events == ['materialize', 'schedule', 'waiting', 'finished']
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert finished['result'] == {
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
}
|
||||
assert finished['message'] == '已转交附件版面解析,完成后自动创建后继订单识别任务'
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
|
||||
@@ -15,6 +15,7 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingOrderCandidate,
|
||||
@@ -28,6 +29,7 @@ from app.models import (
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case, serialize_review_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
ensure_review_case_for_unit,
|
||||
ensure_run_review_cases,
|
||||
get_review_case_visible_to_user,
|
||||
get_review_run_visible_to_user,
|
||||
@@ -61,11 +63,13 @@ from app.services.shipping_notice.order_extraction_plan import ensure_order_extr
|
||||
|
||||
|
||||
def _materialized_run(*, user, agent, session, intake):
|
||||
"""测试中显式物化延迟创建的 Plan/Unit,保持与 Worker 的生产时序一致。"""
|
||||
"""测试中显式物化 Plan,并把 Review 测试默认 Unit 推进到可建 Case 的就绪态。"""
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
for unit in run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
@@ -122,24 +126,110 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
|
||||
assert db.session.get(ShippingOrderCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
|
||||
|
||||
|
||||
def test_review_cases_follow_each_ready_unit_for_any_pdf_count_and_completion_order(app):
|
||||
"""任意数量 PDF 乱序完成时,只能为当前已就绪 Unit 建 Case,兄弟 PDF 不得被提前初始化。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first_document = _seed_run_input(suffix='REVIEW-N-PDF')
|
||||
documents = [first_document]
|
||||
for index in range(2, 6):
|
||||
document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=first_document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'orders-review-n-pdf-{index}.pdf',
|
||||
filename=f'orders-review-n-pdf-{index}.pdf',
|
||||
content_hash=(str(index) * 64)[:64],
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'PO-N-{index}',
|
||||
)
|
||||
db.session.add(document)
|
||||
documents.append(document)
|
||||
db.session.commit()
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
units_by_document = {
|
||||
int(unit.document_id): unit for unit in run.extraction_plan.units
|
||||
}
|
||||
assert len(units_by_document) == 5
|
||||
for unit in units_by_document.values():
|
||||
unit.status = 'pending'
|
||||
unit.result_json = None
|
||||
db.session.commit()
|
||||
|
||||
completion_order = [3, 0, 4, 1, 2]
|
||||
completed_document_ids: set[int] = set()
|
||||
for step, document_index in enumerate(completion_order, start=1):
|
||||
document = documents[document_index]
|
||||
unit = units_by_document[int(document.id)]
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {'orders': [{
|
||||
'primary_document_id': int(document.id),
|
||||
'header_fields': [{
|
||||
'field_id': 'po',
|
||||
'observations': [{'value': f'PO-N-{document_index + 1}'}],
|
||||
}],
|
||||
'lines': [],
|
||||
}]}
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-REVIEW-N-{document_index + 1}',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=int(document.id),
|
||||
candidate_key=f'review-n-{document_index + 1}',
|
||||
order_extraction_run_id=run.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
db.session.commit()
|
||||
completed_document_ids.add(int(document.id))
|
||||
|
||||
# 关键断言:每一步仅增长一个 Case,未完成的任意兄弟 PDF 始终没有空 Case。
|
||||
assert case is not None
|
||||
assert case.candidate_id == candidate.id
|
||||
assert ShippingOrderReviewCase.query.filter_by(run_id=run.id).count() == step
|
||||
actual_document_ids = {
|
||||
int(row.document_id)
|
||||
for row in ShippingOrderReviewCase.query.filter_by(run_id=run.id).all()
|
||||
}
|
||||
assert actual_document_ids == completed_document_ids
|
||||
|
||||
reconciled = ensure_run_review_cases(run=run)
|
||||
db.session.commit()
|
||||
assert len(reconciled) == 5
|
||||
assert ShippingOrderReviewCase.query.filter_by(run_id=run.id).count() == 5
|
||||
|
||||
|
||||
def test_review_case_backfills_final_run_order_for_an_empty_legacy_draft(app):
|
||||
"""最终合并订单可回填旧空草稿,复核页不得把成功 PDF 显示为机器订单不可用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-FINAL-ORDER')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
# 先模拟 Worker 在最终合并结果写入前创建的空白旧 Case。
|
||||
# 先模拟历史 Worker 在最终结果与 Candidate 写入前创建的空白旧 Case。
|
||||
unit.status = 'review_required'
|
||||
legacy_case = ensure_run_review_cases(run=run)[0]
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-REVIEW-FINAL-ORDER', intake_id=intake.id,
|
||||
primary_document_id=unit.document_id, candidate_key='review-final-order',
|
||||
order_extraction_run_id=run.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
run.execution_result_json = {'orders': [{
|
||||
'primary_document_id': unit.document_id,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-FINAL'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A001'}]}]}],
|
||||
}]}
|
||||
unit.status = 'candidate_ready'
|
||||
# 后续校验可能已替换 machine_order_unavailable,修复不能依赖单一问题码。
|
||||
legacy_case.current_draft.issue_summary_json = [{'code': 'customer_unresolved', 'severity': 'blocking'}]
|
||||
|
||||
refreshed = ensure_run_review_cases(run=run)[0]
|
||||
refreshed = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:按当前 PDF 的 primary_document_id 回填,不依赖旧 Unit 中间结果。
|
||||
# 关键断言:补回唯一 Candidate 和机器 Draft,不依赖已被校验替换的问题码。
|
||||
assert refreshed.id == legacy_case.id
|
||||
assert refreshed.candidate_id == candidate.id
|
||||
assert refreshed.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-FINAL'
|
||||
assert refreshed.current_draft.lines_json[0]['machine_fields'][0]['observations'][0]['value'] == 'A001'
|
||||
assert not any(item['code'] == 'machine_order_unavailable' for item in refreshed.current_draft.issue_summary_json)
|
||||
|
||||
@@ -365,10 +365,11 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app):
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 仅给 document_b 对应 Unit 写入可确认机器结果。
|
||||
# 仅给 document_b 对应 Unit 写入可确认机器结果,并标记为复核就绪。
|
||||
for unit in run.extraction_plan.units:
|
||||
if int(unit.document_id) != int(document_b.id):
|
||||
continue
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'primary_document_id': int(document_b.id),
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_task_progress_audit.py
|
||||
|
||||
用途:验收 OT 统一进度中央写入口强制写入 order_task_progress_changed 审计。
|
||||
依赖:order_task_service.sync_order_task_processing_state、ShippingAuditEvent、pytest。
|
||||
逻辑:stage/status 变更必须落审计前后值与 reason_code;无变更不写事件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingOrderTask, User
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES,
|
||||
)
|
||||
|
||||
|
||||
def test_order_task_progress_audit_event_types_frozen():
|
||||
"""契约冻结:OT 进度三类事件码齐全。"""
|
||||
assert ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES == frozenset({
|
||||
'order_task_created',
|
||||
'order_task_updated',
|
||||
'order_task_progress_changed',
|
||||
})
|
||||
|
||||
|
||||
def _seed_user_and_task(task_no: str = 'OT-PROGRESS-AUDIT-1') -> ShippingOrderTask:
|
||||
"""最小 OT 行,供中央进度写入口测试。"""
|
||||
user = User(
|
||||
username=f'ot-progress-{task_no[-4:]}',
|
||||
email=f'{task_no.lower()}@example.com',
|
||||
password_hash='x',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
now = datetime.utcnow()
|
||||
ot = ShippingOrderTask(
|
||||
task_no=task_no,
|
||||
user_id=int(user.id),
|
||||
status='processing',
|
||||
stage='candidate_creating',
|
||||
progress_version=1,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.commit()
|
||||
return ot
|
||||
|
||||
|
||||
def test_sync_order_task_processing_state_writes_progress_audit(app):
|
||||
"""BE-06:stage 变更强制写 order_task_progress_changed,含前后值。"""
|
||||
with app.app_context():
|
||||
ot = _seed_user_and_task()
|
||||
sync_order_task_processing_state(
|
||||
ot,
|
||||
stage='waiting_review',
|
||||
status='waiting_review',
|
||||
reason_code='candidate_pre_confirm_sync',
|
||||
source='test',
|
||||
request_id='req-progress-1',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
events = (
|
||||
ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.all()
|
||||
)
|
||||
assert len(events) >= 1
|
||||
event = events[0]
|
||||
assert event.reason_code == 'candidate_pre_confirm_sync'
|
||||
assert event.request_id == 'req-progress-1'
|
||||
assert event.action == 'sync_order_task_processing_state'
|
||||
before = event.before_snapshot_json if isinstance(event.before_snapshot_json, dict) else {}
|
||||
after = event.after_snapshot_json if isinstance(event.after_snapshot_json, dict) else {}
|
||||
# 白名单快照须保留 stage/status/progress_version,禁止静默丢字段。
|
||||
assert before.get('stage') == 'candidate_creating'
|
||||
assert before.get('status') == 'processing'
|
||||
assert before.get('progress_version') == 1
|
||||
assert after.get('stage') == 'waiting_review'
|
||||
assert after.get('status') == 'waiting_review'
|
||||
assert after.get('progress_version') == 2
|
||||
assert int(ot.progress_version or 1) == 2
|
||||
|
||||
|
||||
def test_sync_order_task_processing_state_noop_skips_audit(app):
|
||||
"""值未变化时不得刷审计与 progress_version。"""
|
||||
with app.app_context():
|
||||
ot = _seed_user_and_task('OT-PROGRESS-AUDIT-2')
|
||||
version = int(ot.progress_version or 1)
|
||||
before_count = ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
).count()
|
||||
sync_order_task_processing_state(
|
||||
ot,
|
||||
stage='candidate_creating',
|
||||
status='processing',
|
||||
reason_code='noop',
|
||||
)
|
||||
db.session.commit()
|
||||
after_count = ShippingAuditEvent.query.filter_by(
|
||||
event_type='order_task_progress_changed',
|
||||
aggregate_id=ot.task_no,
|
||||
).count()
|
||||
assert after_count == before_count
|
||||
assert int(ot.progress_version or 1) == version
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_task_stage_machine.py
|
||||
|
||||
用途:验收确认前 OT stage 与 Candidate 前 Run 早期 stage 由写路径推进。
|
||||
依赖:order_task_stage_machine、shipping_processing_projection、pytest。
|
||||
逻辑:客户未确认 → customer_resolving;查重未清 → duplicate_checking;
|
||||
否则 waiting_review;进度事件写入 processing_stage 后投影优先读事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
resolve_pre_confirm_stage,
|
||||
resolve_processing_stage_for_progress_event,
|
||||
write_run_unified_processing_stage,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
map_run_to_processing_stage,
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_pre_confirm_stage_customer_blocking():
|
||||
"""客户未确认时 stage=customer_resolving。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': ['customer_unresolved'],
|
||||
},
|
||||
)
|
||||
assert stage == 'customer_resolving'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_resolve_pre_confirm_stage_duplicate_blocking():
|
||||
"""查重未清时 stage=duplicate_checking。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': True, 'duplicate_resolved': False},
|
||||
'blocking_reason_codes': ['duplicate_unresolved'],
|
||||
},
|
||||
)
|
||||
assert stage == 'duplicate_checking'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_resolve_pre_confirm_stage_waiting_review_default():
|
||||
"""资格无阻断时落到 waiting_review。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': True, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': [],
|
||||
'can_auto_create': False,
|
||||
},
|
||||
)
|
||||
assert stage == 'waiting_review'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_prefer_waiting_review_still_respects_customer_blocker():
|
||||
"""BE-02:prefer_waiting_review 不得覆盖客户未确认阻断。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': False, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': ['customer_unresolved'],
|
||||
},
|
||||
prefer_waiting_review=True,
|
||||
)
|
||||
assert stage == 'customer_resolving'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_prefer_waiting_review_when_gates_clear():
|
||||
"""无阻断时 prefer_waiting_review 落到 waiting_review。"""
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
evaluation={
|
||||
'gates': {'customer_confirmed': True, 'duplicate_resolved': True},
|
||||
'blocking_reason_codes': [],
|
||||
},
|
||||
prefer_waiting_review=True,
|
||||
)
|
||||
assert stage == 'waiting_review'
|
||||
assert status == 'waiting_review'
|
||||
|
||||
|
||||
def test_progress_event_maps_early_stages_for_eml():
|
||||
"""EML:plan_created→email_parsing;layout→document_parsing;merge→email_adjudicating。"""
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'plan_created', source_type='eml',
|
||||
) == 'email_parsing'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'layout_parsing_started', source_type='eml',
|
||||
) == 'document_parsing'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'email_supplement_merged', source_type='eml',
|
||||
) == 'email_adjudicating'
|
||||
|
||||
|
||||
def test_progress_event_direct_pdf_never_email_stages():
|
||||
"""direct_pdf:禁止 email_*;merge 折叠为 candidate_creating。"""
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'plan_created', source_type='direct_pdf',
|
||||
) == 'upload_received'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'email_supplement_merged', source_type='direct_pdf',
|
||||
) == 'candidate_creating'
|
||||
assert resolve_processing_stage_for_progress_event(
|
||||
'layout_parsing_started', source_type='direct_pdf',
|
||||
) == 'document_parsing'
|
||||
|
||||
|
||||
def test_map_run_prefers_written_processing_stage():
|
||||
"""投影优先读 Run.progress_summary_json.processing_stage 写路径事实。"""
|
||||
run = SimpleNamespace(
|
||||
status='processing',
|
||||
phase='extracting',
|
||||
current_stage_code='profile_matching',
|
||||
progress_summary_json=None,
|
||||
extraction_plan=None,
|
||||
)
|
||||
write_run_unified_processing_stage(run, 'document_parsing', source_type='eml')
|
||||
assert map_run_to_processing_stage(run, source_type='eml') == 'document_parsing'
|
||||
|
||||
write_run_unified_processing_stage(run, 'email_adjudicating', source_type='eml')
|
||||
assert map_run_to_processing_stage(run, source_type='eml') == 'email_adjudicating'
|
||||
|
||||
# direct_pdf 即便误写入 email_* 也须 clamp。
|
||||
write_run_unified_processing_stage(run, 'email_adjudicating', source_type='direct_pdf')
|
||||
assert map_run_to_processing_stage(run, source_type='direct_pdf') == 'document_parsing'
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
backend/tests/test_shipping_processing_projection_invariants.py
|
||||
|
||||
用途:验收统一投影 status/stage/gate/action 不变量与 15 阶节点事实。
|
||||
依赖:processing_projection_invariants、pytest。
|
||||
逻辑:不连库;断言 Gate 复核强制 waiting_review、Run completed 非全流程完成、
|
||||
动作契约映射与 stage_nodes 权威输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
build_stage_nodes,
|
||||
derivation_status_for_extraction_run,
|
||||
normalize_action_code,
|
||||
reconcile_processing_projection_facts,
|
||||
)
|
||||
|
||||
|
||||
def test_run_completed_is_not_workflow_completed_before_review():
|
||||
"""识别 Run completed + candidate_creating 不得映射为全流程 completed。"""
|
||||
assert derivation_status_for_extraction_run('completed', stage='candidate_creating') == 'processing'
|
||||
assert derivation_status_for_extraction_run('completed', stage='waiting_review') == 'waiting_review'
|
||||
assert derivation_status_for_extraction_run('completed', stage='completed') == 'completed'
|
||||
|
||||
|
||||
def test_open_order_review_gate_forces_waiting_review_stage():
|
||||
"""Gate 要求进入复核时,stage/status 必须对齐 waiting_review。"""
|
||||
payload = reconcile_processing_projection_facts({
|
||||
'status': 'processing',
|
||||
'stage': 'candidate_creating',
|
||||
'source_type': 'direct_pdf',
|
||||
'current_gate': {
|
||||
'gate_code': 'order_freeze_readiness',
|
||||
'status': 'blocked',
|
||||
'next_action_code': 'open_order_review',
|
||||
'blocking_reason_code': 'waiting_review',
|
||||
'attempt_no': 0,
|
||||
},
|
||||
'available_actions': ['view_details', 'open_order_review'],
|
||||
})
|
||||
assert payload['status'] == 'waiting_review'
|
||||
assert payload['stage'] == 'waiting_review'
|
||||
assert payload['available_actions'][0] == 'open_order_review'
|
||||
current = next(n for n in payload['stage_nodes'] if n['stage'] == 'waiting_review')
|
||||
assert current['status'] == 'blocked'
|
||||
assert next(n for n in payload['stage_nodes'] if n['stage'] == 'email_parsing')['status'] == 'skipped'
|
||||
|
||||
|
||||
def test_completed_clears_write_actions_and_gate():
|
||||
"""status=completed 时 stage 必须 completed,且不得残留写操作。"""
|
||||
payload = reconcile_processing_projection_facts({
|
||||
'status': 'completed',
|
||||
'stage': 'excel_generating',
|
||||
'source_type': 'eml',
|
||||
'current_gate': {
|
||||
'gate_code': 'x',
|
||||
'status': 'blocked',
|
||||
'next_action_code': 'open_order_review',
|
||||
},
|
||||
'available_actions': ['open_order_review', 'retry'],
|
||||
})
|
||||
assert payload['stage'] == 'completed'
|
||||
assert payload['current_gate'] is None
|
||||
assert 'open_order_review' not in payload['available_actions']
|
||||
assert payload['available_actions'] == ['view_result']
|
||||
|
||||
|
||||
def test_normalize_unknown_action_codes():
|
||||
"""未知 / 别名动作码映射到契约或丢弃。"""
|
||||
assert normalize_action_code('retry_failed_documents') == 'retry'
|
||||
assert normalize_action_code('open_fulfillment') == 'view_result'
|
||||
assert normalize_action_code('not_a_real_action') is None
|
||||
|
||||
|
||||
def test_stage_nodes_length_is_fifteen():
|
||||
"""stage_nodes 恒为 15 阶权威事实。"""
|
||||
nodes = build_stage_nodes(
|
||||
stage='inventory_matching',
|
||||
status='automating',
|
||||
source_type='eml',
|
||||
)
|
||||
assert len(nodes) == 15
|
||||
assert nodes[11]['stage'] == 'inventory_matching'
|
||||
assert nodes[11]['status'] == 'running'
|
||||
assert nodes[10]['status'] == 'passed'
|
||||
assert nodes[12]['status'] == 'pending'
|
||||
|
||||
|
||||
def test_invalidated_from_stage_marks_nodes_pending():
|
||||
"""BE-01:改单失效起点及之后(当前游标之前)不得再标 passed。"""
|
||||
nodes = build_stage_nodes(
|
||||
stage='inventory_matching',
|
||||
status='processing',
|
||||
source_type='eml',
|
||||
invalidated_from_stage='inventory_source_resolving',
|
||||
)
|
||||
# inventory_source_resolving 在当前游标之前且位于失效起点,应标 pending。
|
||||
inv_node = next(n for n in nodes if n['stage'] == 'inventory_source_resolving')
|
||||
assert inv_node['status'] == 'pending'
|
||||
waiting = next(n for n in nodes if n['stage'] == 'waiting_review')
|
||||
assert waiting['status'] == 'pending'
|
||||
# 失效起点之前仍可为 passed。
|
||||
dup_node = next(n for n in nodes if n['stage'] == 'duplicate_checking')
|
||||
assert dup_node['status'] == 'passed'
|
||||
current = next(n for n in nodes if n['stage'] == 'inventory_matching')
|
||||
assert current['status'] == 'running'
|
||||
|
||||
|
||||
def test_download_excel_requires_excel_ready_fact():
|
||||
"""BE-04:仅 stage=excel_generating 不得推出 download_excel。"""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derive_available_actions,
|
||||
)
|
||||
|
||||
without_ready = derive_available_actions(
|
||||
status='blocked',
|
||||
stage='excel_generating',
|
||||
gate=None,
|
||||
excel_ready=False,
|
||||
)
|
||||
assert 'download_excel' not in without_ready
|
||||
assert 'regenerate_excel' in without_ready
|
||||
|
||||
with_ready = derive_available_actions(
|
||||
status='blocked',
|
||||
stage='freight_uploading',
|
||||
gate={'next_action_code': 'wait_manual_upload'},
|
||||
excel_ready=True,
|
||||
)
|
||||
assert 'download_excel' in with_ready
|
||||
assert 'open_manual_upload' in with_ready
|
||||
assert 'regenerate_excel' not in with_ready
|
||||
|
||||
|
||||
def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
"""BE-05:Notice 履约态映射属领域层,写/读共用。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
uploaded = SimpleNamespace(
|
||||
process_status='uploaded', current_step='', upload_status='', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
process_status='waiting_upload', current_step='', upload_status='', export_file_path='/x.xlsx',
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading')
|
||||
|
||||
matching = SimpleNamespace(
|
||||
process_status='matching', current_step='step5_match', upload_status='', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching')
|
||||
|
||||
|
||||
def test_map_notice_unknown_status_fail_closed():
|
||||
"""BE-03: unknown Notice status must fail-closed, not order_creating."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
unknown = SimpleNamespace(
|
||||
process_status='totally_unknown_xyz',
|
||||
current_step='',
|
||||
upload_status='',
|
||||
export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(unknown) == ('blocked', 'waiting_review')
|
||||
|
||||
|
||||
def test_derive_available_actions_blocked_without_retry_gate():
|
||||
"""BE-04: business blocked without retry Gate must not append retry."""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derive_available_actions,
|
||||
)
|
||||
|
||||
actions = derive_available_actions(
|
||||
status='blocked',
|
||||
stage='inventory_source_resolving',
|
||||
gate={
|
||||
'gate_code': 'inventory_source',
|
||||
'status': 'blocked',
|
||||
'next_action_code': 'confirm_inventory_source',
|
||||
},
|
||||
excel_ready=False,
|
||||
)
|
||||
assert 'retry' not in actions
|
||||
assert 'open_inventory_source_review' in actions
|
||||
|
||||
|
||||
def test_derive_available_actions_failed_adds_retry():
|
||||
"""BE-04: technical failed should allow retry by default."""
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
derive_available_actions,
|
||||
)
|
||||
|
||||
actions = derive_available_actions(
|
||||
status='failed',
|
||||
stage='document_parsing',
|
||||
gate=None,
|
||||
excel_ready=False,
|
||||
)
|
||||
assert 'retry' in actions
|
||||
@@ -64,14 +64,15 @@ def _upload_ready_asset(user_id: int, *, filename: str, content: bytes) -> str:
|
||||
|
||||
|
||||
def test_map_run_status_to_processing_status() -> None:
|
||||
"""Run.status 折叠到统一 ShippingProcessingStatus。"""
|
||||
"""Run.status 折叠到统一 ShippingProcessingStatus;识别完成 ≠ 全流程 completed。"""
|
||||
assert map_run_status_to_processing_status('queued') == 'processing'
|
||||
assert map_run_status_to_processing_status('processing') == 'processing'
|
||||
assert map_run_status_to_processing_status('review_required') == 'waiting_review'
|
||||
assert map_run_status_to_processing_status('failed') == 'failed'
|
||||
assert map_run_status_to_processing_status('cancelled') == 'cancelled'
|
||||
assert map_run_status_to_processing_status('completed') == 'completed'
|
||||
assert map_run_status_to_processing_status('partially_completed') == 'completed'
|
||||
# [BE-03] 无 stage 上下文时 completed/partially_completed → processing。
|
||||
assert map_run_status_to_processing_status('completed') == 'processing'
|
||||
assert map_run_status_to_processing_status('partially_completed') == 'processing'
|
||||
assert map_run_status_to_processing_status('unknown') == 'processing'
|
||||
|
||||
|
||||
@@ -186,7 +187,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi
|
||||
"""
|
||||
解析失败 Intake 必须投影 blocked Gate、失败原因码与 retry_parse。
|
||||
|
||||
断言:current_gate.status=blocked;failure_reason_code;available_actions 含 retry_parse。
|
||||
断言:current_gate.status=blocked;failure_reason_code;available_actions 含 retry(契约码)。
|
||||
"""
|
||||
with app.app_context():
|
||||
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=9409):
|
||||
@@ -228,7 +229,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi
|
||||
assert item['current_gate']['attempt_no'] == 2
|
||||
assert item['source_summary']['failure_reason_code'] == 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
assert item['source_summary']['parse_attempt_count'] == 2
|
||||
assert 'retry_parse' in item['available_actions']
|
||||
assert 'retry' in item['available_actions']
|
||||
|
||||
|
||||
def test_project_conversation_processing_items_includes_work_items(app, shipping_user):
|
||||
@@ -351,17 +352,25 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
|
||||
assert item['source_summary']['candidate_count'] >= 1
|
||||
assert item['source_summary']['po_number'] == 'PO-OT-1'
|
||||
assert item['source_summary']['customer_name'] == 'ACME Co'
|
||||
# 每个 OT 只统计自身主 PDF,禁止把整个 Run 的文档数复制到兄弟 OT。
|
||||
assert item['source_summary']['document_id'] == int(document.id)
|
||||
assert item['source_summary']['document_count'] == 1
|
||||
assert item['source_summary']['filename'] == document.filename
|
||||
|
||||
|
||||
def test_project_order_task_prefers_notice_fulfillment_stage(app, shipping_user):
|
||||
def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user):
|
||||
"""
|
||||
OT 已挂 Notice 时,投影 stage/status 须跟随 Notice.process_status,而非过期 OT.stage。
|
||||
BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。
|
||||
|
||||
断言:waiting_upload → automating + freight_uploading。
|
||||
断言:Notice 已是 waiting_upload,但 OT 仍为 candidate_creating 时投影不得偷偷改成 freight_uploading;
|
||||
经 sync_order_task_stage_for_notice 回写后投影才反映履约态。
|
||||
"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
@@ -391,7 +400,13 @@ def test_project_order_task_prefers_notice_fulfillment_stage(app, shipping_user)
|
||||
run.user_task_no = order_task.task_no
|
||||
db.session.commit()
|
||||
|
||||
item = _project_order_task_work_item(run)
|
||||
assert item['status'] == 'automating'
|
||||
assert item['stage'] == 'freight_uploading'
|
||||
assert item['shipping_notice_no'] == notice.task_no
|
||||
stale = _project_order_task_work_item(run)
|
||||
assert stale['stage'] == 'candidate_creating'
|
||||
assert stale['status'] == 'processing'
|
||||
assert stale['shipping_notice_no'] == notice.task_no
|
||||
|
||||
sync_order_task_stage_for_notice(notice, order_task=order_task)
|
||||
db.session.commit()
|
||||
synced = _project_order_task_work_item(run)
|
||||
assert synced['status'] == 'automating'
|
||||
assert synced['stage'] == 'freight_uploading'
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
@@ -157,8 +158,8 @@ def _task(**kwargs) -> ShippingNotice:
|
||||
po_number=kwargs.pop('po_number', 'PO-FORMAL-001'),
|
||||
match_status=kwargs.pop('match_status', 'matched'),
|
||||
line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]),
|
||||
export_file_path=kwargs.pop('export_file_path', '/tmp/formal.xlsx'),
|
||||
export_file_name=kwargs.pop('export_file_name', 'formal.xlsx'),
|
||||
export_file_path=kwargs.pop('export_file_path', None),
|
||||
export_file_name=kwargs.pop('export_file_name', None),
|
||||
order_data_version=kwargs.pop('order_data_version', 1),
|
||||
order_lines_migration_status='pending',
|
||||
**kwargs,
|
||||
@@ -184,6 +185,73 @@ def _link_order_task(task: ShippingNotice, *, stage: str = 'inventory_matching')
|
||||
return order_task
|
||||
|
||||
|
||||
def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None) -> ShippingExportArtifact:
|
||||
"""为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09)。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
|
||||
file_path = str(path or task.export_file_path or '/tmp/formal.xlsx')
|
||||
template = ShippingExcelTemplate(
|
||||
template_code=f'TPL-{task.task_no}',
|
||||
display_name='Formal Edit',
|
||||
version=1,
|
||||
status='published',
|
||||
storage_bucket='test',
|
||||
storage_key='test/template.xlsx',
|
||||
original_filename='template.xlsx',
|
||||
file_checksum='a' * 64,
|
||||
definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code=f'PRF-{task.task_no}',
|
||||
display_name='Formal Edit',
|
||||
version=1,
|
||||
status='published',
|
||||
file_format='xlsx',
|
||||
definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code=f'SCH-{task.task_no}', display_name='Formal')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction_id = getattr(task, 'current_order_extraction_id', None)
|
||||
if extraction_id is None:
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash='e' * 64,
|
||||
status='accepted',
|
||||
task_id=int(task.id),
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
extraction_id = extraction.id
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=f'ART-{task.task_no}',
|
||||
task_id=int(task.id),
|
||||
template_id=int(template.id),
|
||||
order_schema_version_id=int(version.id),
|
||||
order_extraction_id=int(extraction_id),
|
||||
inventory_parsing_profile_id=int(profile.id),
|
||||
input_checksum='b' * 64,
|
||||
file_path=file_path,
|
||||
file_name=str(task.export_file_name or 'formal.xlsx'),
|
||||
file_checksum='c' * 64,
|
||||
file_size=10,
|
||||
status='ready',
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
return artifact
|
||||
|
||||
|
||||
def test_formal_edit_rejects_default_readonly_field(app):
|
||||
"""Schema 显式 editable=false 时拒绝,即使字段在 legacy 白名单内。"""
|
||||
with app.app_context():
|
||||
@@ -210,7 +278,7 @@ def test_formal_edit_rejects_default_readonly_field(app):
|
||||
def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
"""Schema editable=True 时允许写入并递增 order_data_version。"""
|
||||
with app.app_context():
|
||||
task = _task()
|
||||
task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -221,6 +289,22 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
},
|
||||
},
|
||||
)
|
||||
_seed_ready_export_artifact(task)
|
||||
db.session.commit()
|
||||
|
||||
# Excel ready(ready Artifact)时即使 Schema editable 也必须冻结。
|
||||
frozen = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert frozen['status'] == 'failed'
|
||||
assert frozen['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN'
|
||||
|
||||
# 清除导出后允许 Schema 放行字段写入。
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
@@ -232,15 +316,14 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app):
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
# change_effect=none 时不应清空已有匹配/导出派生结果。
|
||||
# change_effect=none 时不应清空已有匹配结果。
|
||||
assert refreshed.match_status == 'matched'
|
||||
assert refreshed.export_file_path == '/tmp/formal.xlsx'
|
||||
|
||||
|
||||
def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(app):
|
||||
"""rerun_inventory_matching 清空匹配并同步 OT inventory_matching stage。"""
|
||||
with app.app_context():
|
||||
task = _task()
|
||||
task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx')
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
@@ -252,13 +335,16 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a
|
||||
},
|
||||
)
|
||||
order_task = _link_order_task(task, stage='excel_generating')
|
||||
# 测试编辑路径:先去掉 Excel 冻结。
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(),
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
@@ -285,6 +371,13 @@ def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
},
|
||||
)
|
||||
order_task = _link_order_task(task, stage='inventory_matching')
|
||||
# 版本不匹配的导出视为 stale,不触发 Excel 冻结,便于测 regenerate_excel。
|
||||
task.export_file_path = '/tmp/stale.xlsx'
|
||||
task.export_file_name = 'stale.xlsx'
|
||||
task.step_payload_json = {
|
||||
**dict(task.step_payload_json or {}),
|
||||
'export_meta': {'order_data_version': 999},
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_fields({
|
||||
@@ -300,3 +393,31 @@ def test_change_effect_regenerate_excel_only_clears_export(app):
|
||||
ot = db.session.get(ShippingOrderTask, order_task.id)
|
||||
assert ot.stage == 'excel_generating'
|
||||
assert int(ot.progress_version) == 2
|
||||
|
||||
|
||||
def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app):
|
||||
"""有 order_snapshot_id 但 Excel 未 ready 时,Schema editable 字段仍可写。"""
|
||||
with app.app_context():
|
||||
task = _task(order_snapshot_id=12345)
|
||||
_attach_extraction(
|
||||
task,
|
||||
[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
|
||||
field_policies={
|
||||
'reservation_id': {
|
||||
'editable': True,
|
||||
'change_effect': 'none',
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
response = update_notice_line({
|
||||
'task_no': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000092917'},
|
||||
**_review_payload(version=1),
|
||||
})
|
||||
assert response['status'] == 'ok'
|
||||
refreshed = db.session.get(ShippingNotice, task.id)
|
||||
assert int(refreshed.order_data_version) == 2
|
||||
assert int(refreshed.order_snapshot_id) == 12345
|
||||
@@ -1,18 +1,20 @@
|
||||
"""
|
||||
backend/tests/test_shipping_schema_edit_policy.py
|
||||
|
||||
用途:验收正式任务 Schema 编辑策略默认只读与显式放行。
|
||||
用途:验收正式任务 Schema 编辑策略默认只读与显式放行(无 legacy 绕过)。
|
||||
依赖:schema_edit_policy、pytest。
|
||||
逻辑:无 task_edit_policy → 不可编辑;显式 editable=True → 可编辑;
|
||||
excel_ready 截止后关闭。
|
||||
excel_ready 后全局关闭。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.schema_edit_policy import (
|
||||
DEFAULT_EDITABLE_AFTER_TASK_CREATION,
|
||||
is_excel_ready_for_task,
|
||||
is_field_editable_for_formal_task,
|
||||
list_editable_formal_field_ids,
|
||||
sanitize_audit_field_value,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,7 +28,7 @@ def test_default_formal_fields_are_readonly() -> None:
|
||||
|
||||
|
||||
def test_schema_explicit_editable_is_honored_until_excel_ready() -> None:
|
||||
"""Schema 显式放行字段在 Excel 就绪前可编辑。"""
|
||||
"""Schema 显式放行字段在 Excel 就绪前可编辑;就绪后全局关闭。"""
|
||||
field = {
|
||||
'field_id': 'reservation-id',
|
||||
'task_edit_policy': {
|
||||
@@ -38,3 +40,84 @@ def test_schema_explicit_editable_is_honored_until_excel_ready() -> None:
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=False) is True
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=True) is False
|
||||
assert list_editable_formal_field_ids([field], excel_ready=False) == ['reservation-id']
|
||||
assert list_editable_formal_field_ids([field], excel_ready=True) == []
|
||||
|
||||
|
||||
def test_excel_ready_freezes_even_without_editable_until() -> None:
|
||||
"""Excel ready 时即使未声明 editable_until 也全局禁写。"""
|
||||
field = {
|
||||
'field_id': 'po-id',
|
||||
'task_edit_policy': {'editable': True, 'change_effect': 'none'},
|
||||
}
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=False) is True
|
||||
assert is_field_editable_for_formal_task(field, excel_ready=True) is False
|
||||
|
||||
|
||||
def test_sanitize_audit_field_value_truncates_long_text() -> None:
|
||||
"""审计前后值过长时截断。"""
|
||||
long_text = 'x' * 400
|
||||
sanitized = sanitize_audit_field_value(long_text)
|
||||
assert isinstance(sanitized, str)
|
||||
assert len(sanitized) < 400
|
||||
assert sanitized.endswith('…')
|
||||
|
||||
|
||||
def test_excel_ready_requires_ready_artifact(app) -> None:
|
||||
"""仅有 export_file_path、无 ready Artifact 时不得冻结(BE-09)。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingNotice,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-EXCEL-READY-BE09',
|
||||
source_type='manual',
|
||||
process_status='matched',
|
||||
export_file_path='/tmp/be09.xlsx',
|
||||
export_file_name='be09.xlsx',
|
||||
order_data_version=1,
|
||||
order_lines_migration_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
assert is_excel_ready_for_task(task) is False
|
||||
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='BE09', display_name='BE09', version=1, status='published',
|
||||
storage_bucket='test', storage_key='t.xlsx', original_filename='t.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='BE09', display_name='BE09', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='BE09', display_name='BE09')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id,
|
||||
input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingExportArtifact(
|
||||
artifact_no='ART-BE09', task_id=task.id, template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path='/tmp/be09.xlsx', file_name='be09.xlsx',
|
||||
file_checksum='d' * 64, file_size=1, status='ready',
|
||||
))
|
||||
db.session.commit()
|
||||
assert is_excel_ready_for_task(task) is True
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
backend/tests/test_shipping_task_center_review_run_deep_link.py
|
||||
|
||||
用途:验收任务中心 Notice 摘要注入 review_run_no,供 UI-04 深链订单处理工作台。
|
||||
依赖:query_service._inject_unified_processing_fields、ShippingOrderTask、pytest。
|
||||
逻辑:OT 挂 extraction_run 时 SUMMARY 必含 review_run_no / owner_agent_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.query_service import serialize_task_summary
|
||||
|
||||
|
||||
def test_serialize_task_summary_injects_review_run_no_for_order_processing_deeplink(app):
|
||||
"""UI-04:建单后任务摘要须带 review_run_no,任务中心才能深链 order-review。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TC-DEEPLINK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-TC-DEEPLINK-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type='manual',
|
||||
process_status='waiting_upload',
|
||||
current_step='step7_upload_freight',
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
order_task = ShippingOrderTask(
|
||||
task_no='OT-TC-DEEPLINK-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
extraction_run_id=int(run.id),
|
||||
shipping_notice_id=int(notice.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
status='automating',
|
||||
stage='freight_uploading',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(order_task)
|
||||
db.session.flush()
|
||||
notice.order_task_id = int(order_task.id)
|
||||
run.user_task_no = order_task.task_no
|
||||
# 深链 Agent:优先 Run.owner_agent_id(注入逻辑读 Run)。
|
||||
run.owner_agent_id = int(agent.id)
|
||||
db.session.commit()
|
||||
|
||||
data = serialize_task_summary(notice, viewer_user_id=user.id)
|
||||
assert data['order_task_no'] == 'OT-TC-DEEPLINK-1'
|
||||
assert data['review_run_no'] == run.run_no
|
||||
assert int(data.get('owner_agent_id') or 0) == int(agent.id)
|
||||
@@ -60,8 +60,72 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
FIXTURE_ROOT = Path(__file__).resolve().parent / 'fixtures' / 'shipping_xfa'
|
||||
|
||||
|
||||
def _confirmed_visual_binding() -> dict[str, object]:
|
||||
"""最小已确认 visual_binding。"""
|
||||
return {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.15},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
}
|
||||
|
||||
|
||||
def _sample_xfa_definition(**overrides):
|
||||
"""构造合法 xfa_dataset definition 基线。"""
|
||||
"""构造合法 xfa_dataset definition 基线(bindings-only 正式路径)。"""
|
||||
payload = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [],
|
||||
},
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-header-po',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-header-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': _confirmed_visual_binding(),
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-line-mat',
|
||||
'field_id': 'f-mat',
|
||||
'field_code': 'material_no',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-line-matnr',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': _confirmed_visual_binding(),
|
||||
},
|
||||
],
|
||||
'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',
|
||||
},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def _legacy_only_xfa_definition(**overrides):
|
||||
"""构造仅含 legacy mappings 的迁移输入(不可经正式 validate)。"""
|
||||
payload = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
@@ -96,6 +160,7 @@ def _sample_xfa_definition(**overrides):
|
||||
},
|
||||
],
|
||||
},
|
||||
'bindings': [],
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -131,6 +196,12 @@ def test_xfa_definition_rejects_coordinate_region_keys():
|
||||
assert model.source_contract.authoritative_line_collection_path == '/data/ITEMS/DATA'
|
||||
|
||||
|
||||
def test_xfa_definition_rejects_legacy_only_without_bindings():
|
||||
"""关键断言:仅 legacy mappings 无 bindings 时正式 validate fail-closed。"""
|
||||
with pytest.raises(ValidationError, match='xfa_legacy_mappings_forbidden'):
|
||||
validate_xfa_dataset_definition(_legacy_only_xfa_definition())
|
||||
|
||||
|
||||
def test_controlled_data_path_rejects_wildcard_function_parent_escape_and_script():
|
||||
"""数据路径语法拒绝通配符、函数、父级逃逸、脚本。"""
|
||||
assert validate_controlled_data_path('/data/HEADER/EBELN') == '/data/HEADER/EBELN'
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_evidence_retention.py
|
||||
|
||||
用途:阶段 5 evidence_only 保留率——MATNR 第 2/4/5 行 100%。
|
||||
依赖:xfa_validation.compute_evidence_retention_rate、formal_multiline helpers。
|
||||
逻辑:正式提取后断言期望行号全部保留;人为缺行时保留率 < 1.0。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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_validation import (
|
||||
compute_evidence_retention_rate,
|
||||
)
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_raw_profile,
|
||||
_schema_definition,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
EXPECTED_EVIDENCE_LINES = {2, 4, 5}
|
||||
|
||||
|
||||
def test_matnr_lines_2_4_5_evidence_retention_100_percent():
|
||||
"""关键断言:第 2/4/5 行 evidence_only 保留率 100%。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_matnr_rule_set()]),
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-evidence-retain',
|
||||
)
|
||||
rate = compute_evidence_retention_rate(
|
||||
extraction=result,
|
||||
expected_line_nos=EXPECTED_EVIDENCE_LINES,
|
||||
)
|
||||
assert rate == 1.0
|
||||
|
||||
|
||||
def test_missing_evidence_line_lowers_retention_rate():
|
||||
"""关键断言:缺少期望证据行时保留率低于 100%。"""
|
||||
rate = compute_evidence_retention_rate(
|
||||
evidence_segments=[
|
||||
{'line_no': 2, 'normalized_text': 'CAB'},
|
||||
{'line_no': 4, 'normalized_text': 'Cust'},
|
||||
# 故意缺少第 5 行
|
||||
],
|
||||
expected_line_nos=EXPECTED_EVIDENCE_LINES,
|
||||
)
|
||||
assert rate < 1.0
|
||||
assert abs(rate - (2 / 3)) < 1e-6
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_multiline_extraction.py
|
||||
|
||||
用途:正式提取——多行 MATNR 经已确认 stages 流水线产出 customer_part_number 与 part_number。
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number。
|
||||
依赖:xfa_profile_extraction、xfa_split_rule_contract、xfa_dataset、pytest。
|
||||
逻辑:合成多行 datasets XML + 已确认规则集;断言 mapped 字段、evidence_only 与 needs_review 边界。
|
||||
"""
|
||||
@@ -14,12 +14,11 @@ from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_d
|
||||
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,
|
||||
XfaSplitStage,
|
||||
new_segment_id,
|
||||
new_stage_id,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
@@ -35,13 +34,6 @@ MATNR_RAW = (
|
||||
AUTH_PATH = '/data/ITEMS/DATA'
|
||||
|
||||
|
||||
def _stage(**kwargs) -> XfaSplitStage:
|
||||
"""构造 stage。"""
|
||||
payload = {'stage_id': new_stage_id()}
|
||||
payload.update(kwargs)
|
||||
return XfaSplitStage.model_validate(payload)
|
||||
|
||||
|
||||
def _multiline_datasets_xml() -> bytes:
|
||||
"""构造含多行 MATNR 的最小 datasets XML。"""
|
||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -91,17 +83,17 @@ def _schema_definition() -> dict:
|
||||
|
||||
|
||||
def _confirmed_matnr_rule_set() -> dict:
|
||||
"""构造已确认、可正式提取的用户配置 MATNR 流水线。"""
|
||||
"""构造已确认、可正式提取的用户配置 MATNR matcher 规则集。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-multiline-v1',
|
||||
rule_set_id='matnr-multiline-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
strategy='pipeline',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='cpn',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_material_candidate',
|
||||
@@ -110,22 +102,12 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='desc',
|
||||
order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='material_description',
|
||||
display_name='品名规格',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=2)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='mpn',
|
||||
order=3,
|
||||
matcher=XfaSplitMatcher(
|
||||
type='prefix', value='MPN', separators=[':', ':'], case_sensitive=False,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_candidate',
|
||||
@@ -134,26 +116,6 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=3),
|
||||
_stage(type='extract_prefix', value='MPN', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='cust',
|
||||
order=4,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_number_evidence',
|
||||
display_name='客户编号',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=4),
|
||||
_stage(type='extract_prefix', value='Cust nr', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
@@ -161,44 +123,65 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
return rule_set.model_dump(mode='json')
|
||||
return rule_set.model_dump(mode='json', by_alias=True)
|
||||
|
||||
|
||||
def _confirmed_header_rule_set() -> dict:
|
||||
"""构造 Header 多行账款信息拆分规则。"""
|
||||
"""构造 Header 拆分规则:第 1 行 mapped,其余行 evidence_only。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_id='invoiced-to-v1',
|
||||
rule_set_id='invoiced-to-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-invoiced-to',
|
||||
source_scope='header',
|
||||
source_field_code='INVOICED_TO',
|
||||
source_data_path='/data/HEADER/INVOICED_TO',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='bill-customer', order=1,
|
||||
rule_id='bill-customer',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='bill_customer', display_name='账款客户',
|
||||
handling='mapped', target_field_id='f-bill-customer', target_field_code='bill_to_customer',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='bill-address', order=2,
|
||||
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',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line_range', line_start=2, line_end=4, join_with='newline'),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
).model_dump(mode='json')
|
||||
).model_dump(mode='json', by_alias=True)
|
||||
|
||||
|
||||
def _xfa_binding(
|
||||
*,
|
||||
binding_id: str,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
) -> dict:
|
||||
"""构造最小合法统一 binding。"""
|
||||
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(*, split_rules: list[dict] | None = None) -> dict:
|
||||
"""构造含 split_rules 的冻结 XFA Profile。"""
|
||||
"""构造含 split_rules 的冻结 XFA Profile(bindings-only)。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
summary = build_signature_summary(
|
||||
template_bytes=b'<template><subform name="form"/></template>',
|
||||
@@ -215,26 +198,25 @@ def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
'authoritative_line_collection_path': AUTH_PATH,
|
||||
'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',
|
||||
}],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {
|
||||
'row_path': AUTH_PATH,
|
||||
'fields': [
|
||||
{
|
||||
'mapping_id': 'm-matnr', 'field_id': 'f-matnr', 'field_code': 'material_no',
|
||||
'data_path': f'{AUTH_PATH}/MATNR', 'path_id': 'path-matnr',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'data_path': f'{AUTH_PATH}/MENGE', 'path_id': 'path-qty',
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
],
|
||||
'fields': [],
|
||||
},
|
||||
'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-matnr', field_id='f-matnr', field_code='material_no',
|
||||
scope='line', path_id='path-matnr', data_path=f'{AUTH_PATH}/MATNR',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-m-qty', field_id='f-qty', field_code='quantity',
|
||||
scope='line', path_id='path-qty', data_path=f'{AUTH_PATH}/MENGE',
|
||||
),
|
||||
],
|
||||
'cross_checks': {
|
||||
'acroform_enabled': False,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -247,7 +229,7 @@ def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
|
||||
|
||||
def test_confirmed_split_rules_extract_mapped_fields():
|
||||
"""已确认流水线正式提取产出客户料号与料号。"""
|
||||
"""已确认 matcher 规则正式提取产出客户料号与料号。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_matnr_rule_set()]),
|
||||
@@ -296,8 +278,8 @@ def test_draft_split_rules_fail_closed_needs_review():
|
||||
assert 'part_number' not in field_codes
|
||||
|
||||
|
||||
def test_confirmed_header_split_rules_extract_once_into_header_fields():
|
||||
"""Header 源规则执行一次并产出客户与连续多行地址。"""
|
||||
def test_confirmed_header_split_rules_extract_customer_line():
|
||||
"""Header 源规则执行一次并产出第 1 行客户名;其余行保留为 evidence。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_header_rule_set()]),
|
||||
@@ -308,6 +290,4 @@ def test_confirmed_header_split_rules_extract_once_into_header_fields():
|
||||
)
|
||||
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 result.evidence_summary['header_split_evidence'] == []
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_split_extraction.py
|
||||
|
||||
用途:阶段 5 正式拆分提取黄金用例——customer_part_number / part_number。
|
||||
依赖:复用 test_shipping_xfa_formal_multiline_extraction 助手、xfa_profile_extraction。
|
||||
逻辑:断言 TEMP-S000218922 与 D4-A08AR12000001;evidence_only 行保留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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 tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_raw_profile,
|
||||
_schema_definition,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_golden_matnr_split_produces_customer_part_and_mpn():
|
||||
"""关键断言:正式拆分产出 TEMP-S000218922 与 D4-A08AR12000001。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_matnr_rule_set()]),
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-checksum-formal-split-01234567',
|
||||
)
|
||||
assert result.rows
|
||||
values = {
|
||||
str(item.get('field_code') or ''): item.get('value')
|
||||
for item in (result.rows[0].get('fields') or [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
assert values.get('customer_part_number') == 'TEMP-S000218922'
|
||||
assert values.get('part_number') == 'D4-A08AR12000001'
|
||||
evidence = result.rows[0].get('split_evidence') or []
|
||||
line_nos = {int(item['line_no']) for item in evidence if isinstance(item, dict) and item.get('line_no') is not None}
|
||||
# 第 2/4/5 行须保留为 evidence_only。
|
||||
assert {2, 4, 5}.issubset(line_nos)
|
||||
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_mapping_concurrency.py
|
||||
|
||||
用途:验收 bindings/split_rules 保存的 operation_id 幂等与 lock_version 409。
|
||||
依赖:Flask test client、phase2/multiline XFA 夹具、profile_service。
|
||||
逻辑:重复 operation_id 返回同一 revision;旧 lock_version 稳定 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileDraftRevision, User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from tests.conftest import parse_api_error
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import _schema_definition
|
||||
from tests.test_shipping_xfa_unified_mapping_api import _multiline_sample, _schema_version_id
|
||||
|
||||
|
||||
def _admin_headers(app, username: str) -> dict[str, str]:
|
||||
"""生成 admin JWT。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(username=username, email=f'{username}@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
|
||||
def _draft_with_binding(app, monkeypatch):
|
||||
"""创建含 bindings-only(无 line_mapping.fields)与租约的 XFA 草稿。"""
|
||||
with app.app_context():
|
||||
user = User(username='conc-user', email='conc-user@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Concurrency',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'conc-tab',
|
||||
'operation_id': 'conc-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
definition = dict(profile.definition_json)
|
||||
definition['line_mapping'] = {
|
||||
'row_path': definition['source_contract']['authoritative_line_collection_path'],
|
||||
}
|
||||
definition['split_rules'] = []
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-conc-001',
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['MENGE'],
|
||||
'data_path': '/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.6, 'x1': 0.4, 'y1': 0.75},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
return int(user.id), schema_id, document_id, created, profile_id, definition, paths
|
||||
|
||||
|
||||
def test_duplicate_operation_id_is_idempotent(app, monkeypatch):
|
||||
"""相同 operation_id + 已落库 snapshot 须幂等,不产生冲突 revision。"""
|
||||
user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
first = 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='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-idempotent',
|
||||
enforce_lease=True,
|
||||
)
|
||||
rev = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='conc-op-idempotent',
|
||||
).one()
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
# 重放必须携带已规范化 snapshot,与 Revision 冻结内容一致。
|
||||
second = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': dict(rev.definition_snapshot_json or {}),
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-idempotent',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert first['draft_revision']['revision_no'] == second['draft_revision']['revision_no']
|
||||
assert first['draft_revision']['operation_id'] == 'conc-op-idempotent'
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='conc-op-idempotent',
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_stale_lock_version_returns_409_via_api(app, monkeypatch):
|
||||
"""旧 expected_lock_version 经 PUT API 须返回稳定 409。"""
|
||||
_user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
stale_lock = max(profile.lock_version - 1, 0)
|
||||
profile_code = profile.profile_code
|
||||
display_name = profile.display_name
|
||||
|
||||
client = app.test_client()
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}',
|
||||
json={
|
||||
'profile_code': profile_code,
|
||||
'display_name': display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': definition,
|
||||
'expected_lock_version': stale_lock,
|
||||
'sample_document_id': document_id,
|
||||
'browser_session_id': 'conc-tab',
|
||||
'lease_token': created['edit_lease']['lease_token'],
|
||||
'operation_id': 'conc-stale-lock',
|
||||
},
|
||||
headers=_admin_headers(app, 'conc-user'),
|
||||
)
|
||||
assert response.status_code == 409
|
||||
error = parse_api_error(response.get_json())
|
||||
assert error['code'] in {
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
|
||||
}
|
||||
|
||||
|
||||
def test_operation_id_conflict_on_different_definition(app, monkeypatch):
|
||||
"""相同 operation_id 但 definition 不同须 409。"""
|
||||
user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
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='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-conflict',
|
||||
enforce_lease=True,
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
mutated = dict(definition)
|
||||
mutated['bindings'] = []
|
||||
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': mutated,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-op-conflict',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_mirror_split_consistency.py
|
||||
|
||||
用途:阶段 5 镜像集合在拆分规则下正式字段一致率验收。
|
||||
依赖:xfa_validation、formal_multiline helpers、pytest。
|
||||
逻辑:权威/镜像同 MATNR 多行拆分后 mapped 值一致 → mirror_consistency_rate=1.0;
|
||||
篡改镜像 → mismatched / 0.0。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
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_validation import (
|
||||
compute_mirror_consistency_rate,
|
||||
validate_xfa_extraction,
|
||||
)
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_raw_profile,
|
||||
_schema_definition,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_mirror_split_mapped_fields_consistent():
|
||||
"""关键断言:拆分后镜像正式字段一致 → mirror_consistency_rate=1.0。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
raw_profile = _raw_profile(split_rules=[_confirmed_matnr_rule_set()])
|
||||
extraction = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-mirror-split-ok',
|
||||
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=None,
|
||||
)
|
||||
assert result.passed is True
|
||||
assert result.cross_check_summary['mirror_status'] == 'matched'
|
||||
assert compute_mirror_consistency_rate(result.cross_check_summary) == 1.0
|
||||
|
||||
|
||||
def test_mirror_split_mismatch_rate_zero(monkeypatch):
|
||||
"""关键断言:镜像拆分后 mapped 值不同 → mismatched / rate=0。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
raw_profile = _raw_profile(split_rules=[_confirmed_matnr_rule_set()])
|
||||
extraction = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-mirror-split-bad',
|
||||
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import read_collection_rows as real_read
|
||||
|
||||
def _fake_rows(dataset_analysis, collection_path):
|
||||
rows = real_read(dataset_analysis, collection_path)
|
||||
if str(collection_path).endswith('ITEMS1/DATA') and rows:
|
||||
mutated = deepcopy(rows)
|
||||
key = '/data/ITEMS1/DATA/MATNR'
|
||||
mutated[0][key] = 'TEMP-OTHER\nCAB\nMPN:OTHER-PN\nCust\nS-ENC'
|
||||
return mutated
|
||||
return rows
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_collection_rows',
|
||||
_fake_rows,
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=None,
|
||||
)
|
||||
assert result.passed is False
|
||||
assert 'xfa_mirror_collection_mismatch' in result.reason_codes
|
||||
assert compute_mirror_consistency_rate(result.cross_check_summary) == 0.0
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_page_preview.py
|
||||
|
||||
用途:验收阶段 2 XFA PDF 页面预览不再被禁令阻断,且令牌绑定 actor/profile/页。
|
||||
依赖:preview_service、pytest app fixture、XFA phase2 helpers。
|
||||
逻辑:mock PDFium 渲染;断言 authorize 不抛 XFA 禁令;令牌跨 actor/样本隔离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from tests.test_order_document_profile_preview_service import _PreviewStore
|
||||
|
||||
|
||||
def test_xfa_profile_frozen_preview_no_longer_raises_blank_pdf_ban(app, monkeypatch):
|
||||
"""关键断言:XFA Profile 签发冻结样本预览时不得再抛 blank PDF 禁令。"""
|
||||
profile = SimpleNamespace(id=1, template_mode='xfa_dataset', definition_json={'template_mode': 'xfa_dataset'})
|
||||
sample = SimpleNamespace(id=2, page_count_snapshot=None)
|
||||
document = SimpleNamespace(id=3)
|
||||
asset = SimpleNamespace()
|
||||
layout = SimpleNamespace()
|
||||
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_frozen_sample_context',
|
||||
lambda **_kwargs: (profile, sample, document, layout, asset),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_render_pdf_pages',
|
||||
lambda _asset: [
|
||||
SimpleNamespace(page_no=1, image=np.zeros((8, 8, 3), dtype=np.uint8)),
|
||||
SimpleNamespace(page_no=2, image=np.zeros((8, 8, 3), dtype=np.uint8)),
|
||||
SimpleNamespace(page_no=3, image=np.zeros((8, 8, 3), dtype=np.uint8)),
|
||||
],
|
||||
)
|
||||
store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: store)
|
||||
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_service.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
preview_service.db.session,
|
||||
'get',
|
||||
lambda model, pk: profile if pk == 1 else None,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
payload = preview_service.authorize_frozen_sample_preview_pages(
|
||||
1, sample_binding_id=2, actor_id=99,
|
||||
)
|
||||
|
||||
assert payload['page_count'] == 3
|
||||
assert len(payload['pages']) == 3
|
||||
assert all(item.get('preview_token') for item in payload['pages'])
|
||||
|
||||
|
||||
def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
"""只读映射 DTO 应声明 PDF 预览可用(阶段 2)。"""
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice.order_document_profile_preview_service import (
|
||||
build_xfa_readonly_mapping_evidence,
|
||||
)
|
||||
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
id=1,
|
||||
profile_code='XFA',
|
||||
display_name='XFA',
|
||||
version=1,
|
||||
status='published',
|
||||
schema_version_id=1,
|
||||
structure_fingerprint='c' * 64,
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'source_contract': {}, 'header_mappings': [], 'line_mapping': {'fields': []}},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
|
||||
|
||||
def test_preview_token_binds_actor_profile_page(app, monkeypatch):
|
||||
"""render 消费 token 时必须匹配 actor_id、profile_id、sample_binding_id、page_no。"""
|
||||
store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: store)
|
||||
store.setex(
|
||||
'shipping:order-profile-frozen-preview:tok-1',
|
||||
120,
|
||||
'{"profile_id":1,"sample_binding_id":2,"actor_id":5,"page_no":1}',
|
||||
)
|
||||
profile = SimpleNamespace(id=1)
|
||||
sample = SimpleNamespace(id=2)
|
||||
document = SimpleNamespace(id=3)
|
||||
layout = SimpleNamespace()
|
||||
asset = SimpleNamespace()
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_frozen_sample_context',
|
||||
lambda **_kwargs: (profile, sample, document, layout, asset),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
preview_service,
|
||||
'_render_pdf_pages',
|
||||
lambda _asset: [SimpleNamespace(page_no=1, image=np.zeros((4, 4, 3), dtype=np.uint8))],
|
||||
)
|
||||
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_service.db.session, 'commit', lambda: None)
|
||||
|
||||
with app.app_context():
|
||||
png = preview_service.render_frozen_sample_preview_page(
|
||||
profile_id=1,
|
||||
sample_binding_id=2,
|
||||
token='tok-1',
|
||||
page_no=1,
|
||||
actor_id=5,
|
||||
)
|
||||
assert isinstance(png, bytes) and len(png) > 0
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
preview_service.render_frozen_sample_preview_page(
|
||||
profile_id=1,
|
||||
sample_binding_id=2,
|
||||
token='tok-1',
|
||||
page_no=1,
|
||||
actor_id=6,
|
||||
)
|
||||
@@ -50,13 +50,77 @@ def _schema_definition() -> dict:
|
||||
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。"""
|
||||
"""构造冻结 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',
|
||||
@@ -73,53 +137,12 @@ def _raw_profile(*, authoritative: str = '/data/ITEMS/DATA') -> dict:
|
||||
'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',
|
||||
},
|
||||
],
|
||||
'header_mappings': [],
|
||||
'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',
|
||||
},
|
||||
],
|
||||
'fields': [],
|
||||
},
|
||||
'bindings': bindings,
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -179,11 +202,13 @@ 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')
|
||||
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,
|
||||
@@ -216,12 +241,11 @@ def test_netpr_composite_splits_unit_price_and_price_unit():
|
||||
)
|
||||
assert typed == Decimal('898.72')
|
||||
|
||||
# 正式提取:去掉 PEINH 映射后仍应由 NETPR 复合值补齐 price_unit。
|
||||
# 正式提取:去掉 price_unit binding 后仍应由 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']
|
||||
raw_profile['definition']['bindings'] = [
|
||||
item for item in raw_profile['definition']['bindings']
|
||||
if item.get('field_code') != 'price_unit'
|
||||
]
|
||||
result = extract_xfa_profile(
|
||||
@@ -241,3 +265,39 @@ def test_netpr_composite_splits_unit_price_and_price_unit():
|
||||
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
|
||||
@@ -200,11 +200,26 @@ def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_
|
||||
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['header_mappings'] = []
|
||||
definition['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-po-001',
|
||||
'field_id': 'ignored',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['EBELN'],
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.4, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
@@ -225,7 +240,7 @@ def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_
|
||||
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'
|
||||
assert saved['definition']['bindings'][0]['field_id'] == 'f-po'
|
||||
# 关键断言:Schema 必填明细字段可由 EML 等其他来源补充,不得成为 XFA 模板映射问题。
|
||||
assert 'mapping_issues' not in saved
|
||||
assert ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
@@ -252,9 +267,25 @@ def test_xfa_unknown_path_id_blocked(app, _patch_xfa_io):
|
||||
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',
|
||||
bad['header_mappings'] = []
|
||||
bad['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
bad['bindings'] = [{
|
||||
'binding_id': 'bind-bad-001',
|
||||
'field_id': 'x',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-unknown-xxx',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.2, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
with pytest.raises(Exception) as caught:
|
||||
profile_service.save_draft(
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_publish_separation_of_duties.py
|
||||
|
||||
用途:阶段 6 发布职责分离契约——编辑人不得批准自己的 Revision。
|
||||
依赖:publish_check_service 已有 consume 阻断键;本文件固化原因码与审计事件集合。
|
||||
逻辑:纯单元断言职责分离键与编辑审计事件白名单稳定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_editor_self_approval_reason_key_is_stable():
|
||||
"""关键断言:职责分离失败键稳定为 editor_cannot_approve_own_version。"""
|
||||
source = inspect.getsource(checks.consume_report)
|
||||
assert 'editor_cannot_approve_own_version' in source
|
||||
assert '_find_last_profile_editor_id' in source
|
||||
|
||||
|
||||
def test_editor_audit_events_cover_mapping_and_split():
|
||||
"""关键断言:查找最近编辑者覆盖映射、拆分与视觉绑定编辑审计事件。"""
|
||||
source = inspect.getsource(checks._find_last_profile_editor_id)
|
||||
for event in (
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
):
|
||||
assert event in source
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_safe_regex.py
|
||||
|
||||
用途:锁定 XFA 安全正则模块——RE2 优先、restricted_re 子进程 fallback、禁止灾难回溯模式。
|
||||
依赖:xfa_safe_regex。
|
||||
逻辑:纯单测;不读 PDF;超时用例通过 monkeypatch 慢 worker,避免无限挂死。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.shipping_notice.document_layout import xfa_safe_regex as safe_regex_mod
|
||||
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
|
||||
SafeRegexError,
|
||||
compile_safe_regex,
|
||||
has_re2_engine,
|
||||
search_safe,
|
||||
validate_restricted_regex_pattern,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def force_restricted_re(monkeypatch: pytest.MonkeyPatch):
|
||||
"""强制走 restricted_re 引擎,便于覆盖子进程匹配路径。"""
|
||||
monkeypatch.setattr(safe_regex_mod, '_HAS_RE2', False)
|
||||
|
||||
|
||||
def test_validate_rejects_forbidden_and_catastrophic_patterns():
|
||||
"""命名捕获与嵌套量词必须拒绝。"""
|
||||
with pytest.raises(SafeRegexError, match='forbidden'):
|
||||
validate_restricted_regex_pattern(r'(?P<name>x)', max_length=128, max_groups=5)
|
||||
with pytest.raises(SafeRegexError, match='catastrophic'):
|
||||
validate_restricted_regex_pattern(r'(a+)+$', max_length=128, max_groups=5)
|
||||
|
||||
|
||||
def test_compile_and_search_basic_capture():
|
||||
"""可编译并捕获分组。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
matched = search_safe(compiled, 'MPN:ABC123', timeout_ms=50)
|
||||
assert matched is not None
|
||||
assert matched.group(1) == 'ABC123'
|
||||
assert has_re2_engine() in (True, False)
|
||||
|
||||
|
||||
def test_search_returns_none_when_no_match():
|
||||
"""无匹配时返回 None。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
assert search_safe(compiled, 'NOPE', timeout_ms=50) is None
|
||||
|
||||
|
||||
def test_case_insensitive_search():
|
||||
"""不区分大小写时可命中。"""
|
||||
compiled = compile_safe_regex(r'^mpn:(.+)$', case_sensitive=False, max_length=128, max_groups=5)
|
||||
matched = search_safe(compiled, 'MPN:XYZ', timeout_ms=50)
|
||||
assert matched is not None
|
||||
assert matched.group(1) == 'XYZ'
|
||||
|
||||
|
||||
def test_restricted_re_subprocess_basic_match(force_restricted_re):
|
||||
"""restricted_re 子进程路径:基本捕获仍可用。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
assert compiled.engine == 'restricted_re'
|
||||
matched = search_safe(compiled, 'MPN:ABC123', timeout_ms=500)
|
||||
assert matched is not None
|
||||
assert matched.group(1) == 'ABC123'
|
||||
|
||||
|
||||
def test_restricted_re_subprocess_no_match(force_restricted_re):
|
||||
"""restricted_re 子进程路径:无匹配时返回 None。"""
|
||||
compiled = compile_safe_regex(r'^MPN:(.+)$', case_sensitive=True, max_length=128, max_groups=5)
|
||||
assert search_safe(compiled, 'NOPE', timeout_ms=500) is None
|
||||
|
||||
|
||||
def test_restricted_re_subprocess_timeout_kills_worker(force_restricted_re):
|
||||
"""restricted_re 灾难回溯场景:超时抛 TimeoutError,且不等待完整回溯结束。"""
|
||||
compiled = compile_safe_regex(r'(a|a)*X', case_sensitive=True, max_length=128, max_groups=5)
|
||||
haystack = 'a' * 32 + 'Y'
|
||||
started = time.monotonic()
|
||||
with pytest.raises(TimeoutError, match='timed out'):
|
||||
search_safe(compiled, haystack, timeout_ms=100)
|
||||
elapsed = time.monotonic() - started
|
||||
assert elapsed < 2.0
|
||||
safe_regex_mod._destroy_restricted_pool()
|
||||
@@ -19,6 +19,7 @@ REQUIRED_SPLIT_AUDIT_EVENTS = (
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_rule_confirmed',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
@@ -39,20 +40,16 @@ def test_split_audit_events_registered_in_contracts():
|
||||
|
||||
|
||||
def _rule_set(*, segment_id: str, handling: str = 'mapped', target: str | None = 'customer_part_number') -> dict:
|
||||
"""构造最小可 diff 的拆分规则集(stages 流水线)。"""
|
||||
"""构造最小可 diff 的拆分规则集(matcher 模型)。"""
|
||||
return {
|
||||
'rule_id': 'rs-1',
|
||||
'rule_set_id': 'rs-1',
|
||||
'rule_version': 1,
|
||||
'source_path_id': 'path-matnr',
|
||||
'source_scope': 'line',
|
||||
'source_field_code': 'MATNR',
|
||||
'strategy': 'pipeline',
|
||||
'rules': [{
|
||||
'rule_id': 'r-1',
|
||||
'order': 1,
|
||||
'stages': [
|
||||
{'stage_id': 'st-split', 'type': 'split_lines', 'line_breaks': ['\n']},
|
||||
{'stage_id': 'st-sel', 'type': 'select_line', 'line_index': 1},
|
||||
],
|
||||
'matcher': {'type': 'position', 'line_index': 1},
|
||||
'segment': {
|
||||
'segment_id': segment_id,
|
||||
'segment_code': 'cpn' if segment_id == 'seg-a' else segment_id.replace('-', '_'),
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_confirmation_gate.py
|
||||
|
||||
用途:反向锁定 BE-1/BE-2/BE-3/BE-4——拆分确认令牌消费、样本绑定、显式拒绝与审计。
|
||||
依赖:xfa_split_preview_token、_enforce_split_rule_confirmation_integrity。
|
||||
逻辑:纯单测 + Flask app 上下文签发令牌;禁止客户端无令牌声明 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.xfa_split_preview_token import (
|
||||
issue_split_preview_token,
|
||||
split_rule_preview_fingerprint,
|
||||
verify_and_consume_split_preview_token,
|
||||
verify_split_preview_token,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
_enforce_split_rule_confirmation_integrity,
|
||||
split_rules_definition_changed,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
SAMPLE_CHECKSUM = hashlib.sha256(b'test-split-sample').hexdigest()[:32]
|
||||
FAKE_PATH_CONTEXT = {
|
||||
'path_map': {'path-a': '/data/ITEMS/DATA/MATNR'},
|
||||
'dataset_analysis': object(),
|
||||
'analysis': None,
|
||||
'template_packet_checksum': 'sha256:tpl-test',
|
||||
'dataset_structure_fingerprint': 'sha256:fp-test',
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _stable_sample_checksum(monkeypatch):
|
||||
"""单测固定 sample_checksum,避免依赖完整 XFA dataset 树。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._compute_split_source_sample_checksum',
|
||||
lambda **_kw: SAMPLE_CHECKSUM,
|
||||
)
|
||||
|
||||
|
||||
def _rule_set(*, status: str = 'draft', path_id: str = 'path-a') -> dict:
|
||||
return {
|
||||
'rule_set_id': 'rs1',
|
||||
'rule_id': 'rs1',
|
||||
'rule_version': 1,
|
||||
'source_path_id': path_id,
|
||||
'source_field_code': 'MATNR',
|
||||
'strategy': 'matcher',
|
||||
'normalization': {'trim': True, 'remove_empty_lines': True, 'line_breaks': ['\n']},
|
||||
'rules': [{
|
||||
'rule_id': 'r1',
|
||||
'order': 1,
|
||||
'matcher': {'type': 'position', 'line_index': 1},
|
||||
'segment': {
|
||||
'segment_id': 's1',
|
||||
'segment_code': 'customer_part',
|
||||
'display_name': 'CPN',
|
||||
'handling': 'mapped',
|
||||
'target_field_code': 'customer_part_number',
|
||||
},
|
||||
}],
|
||||
'unmatched_line_policy': 'evidence_only',
|
||||
'duplicate_match_policy': 'needs_review',
|
||||
'same_field_multiple_segment_policy': 'needs_review',
|
||||
'source': 'user',
|
||||
'status': status,
|
||||
'requires_confirmation': status != 'confirmed',
|
||||
}
|
||||
|
||||
|
||||
def _issue_token(app, rule: dict, *, actor_id: int = 7, sample_checksum: str = SAMPLE_CHECKSUM) -> str:
|
||||
with app.app_context():
|
||||
return issue_split_preview_token(
|
||||
actor_id=actor_id,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=sample_checksum,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
|
||||
|
||||
def test_client_cannot_confirm_split_rules_without_token(app):
|
||||
"""关键断言:无 preview token 时客户端声明 confirmed 须显式抛错,不得静默降级 draft。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [_rule_set(status='confirmed')]},
|
||||
confirmation_tokens=None,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_REJECTED'
|
||||
assert caught.value.details.get('reason') == 'token_missing'
|
||||
|
||||
|
||||
def test_valid_preview_token_allows_confirmed(app, monkeypatch):
|
||||
"""关键断言:服务端签发令牌可把规则确认为 confirmed(一次消费)。"""
|
||||
audit_calls: list[str] = []
|
||||
platform_calls: list[str] = []
|
||||
|
||||
def _capture_audit(**kwargs):
|
||||
audit_calls.append(str(kwargs.get('event_type')))
|
||||
|
||||
def _capture_platform(**kwargs):
|
||||
platform_calls.append(str(kwargs.get('event_type')))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._audit',
|
||||
_capture_audit,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
_capture_platform,
|
||||
)
|
||||
with app.app_context():
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule)
|
||||
out = _enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert out['split_rules'][0]['status'] == 'confirmed'
|
||||
assert out['split_rules'][0]['requires_confirmation'] is False
|
||||
assert 'xfa_split_rule_confirmed' in audit_calls
|
||||
assert 'xfa_split_rule_confirmed' in platform_calls
|
||||
|
||||
|
||||
def test_preview_token_rejects_replay(app):
|
||||
"""关键断言:同一令牌二次消费须失败(token_replay)。"""
|
||||
with app.app_context():
|
||||
rule = _rule_set()
|
||||
token = _issue_token(app, rule)
|
||||
verify_and_consume_split_preview_token(
|
||||
token,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
verify_and_consume_split_preview_token(
|
||||
token,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
assert caught.value.details.get('reason') == 'token_replay'
|
||||
|
||||
|
||||
def test_preview_token_rejects_sample_checksum_mismatch(app):
|
||||
"""关键断言:样本 checksum 不匹配时确认须被拒绝。"""
|
||||
with app.app_context():
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule, sample_checksum='deadbeef' * 2)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_REJECTED'
|
||||
assert caught.value.details.get('reason') == 'sample_checksum_mismatch'
|
||||
|
||||
|
||||
def test_preview_token_rejects_actor_mismatch(app):
|
||||
"""关键断言:令牌绑定 actor,他人不可复用。"""
|
||||
with app.app_context():
|
||||
rule = _rule_set()
|
||||
token = _issue_token(app, rule)
|
||||
with pytest.raises(ValidationError):
|
||||
verify_split_preview_token(
|
||||
token,
|
||||
actor_id=8,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
)
|
||||
|
||||
|
||||
def test_split_rules_definition_changed_detects_content_drift():
|
||||
"""关键断言:内容变更检测供 xfa_split_rule_edit 门禁使用。"""
|
||||
prev = {'split_rules': [_rule_set(status='confirmed')]}
|
||||
nxt = {'split_rules': [_rule_set(status='confirmed')]}
|
||||
nxt['split_rules'][0]['rules'][0]['matcher'] = {'type': 'position', 'line_index': 2}
|
||||
assert split_rules_definition_changed(prev, nxt) is True
|
||||
assert split_rules_definition_changed(prev, prev) is False
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_preview_api.py
|
||||
|
||||
用途:验收拆分规则 preview API 零写库,并保留 rule_checksum/preview_token。
|
||||
依赖:Flask test client、多行 MATNR 夹具、SQLAlchemy session 监听。
|
||||
逻辑:preview 前后业务表/审计表写入计数为 0;响应含 checksum 与 token。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import event
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingAuditEvent, ShippingOrderDocumentProfileAudit, User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import _confirmed_matnr_rule_set, _multiline_datasets_xml
|
||||
from tests.test_shipping_xfa_unified_mapping_api import _admin_headers, _multiline_sample, _schema_version_id
|
||||
|
||||
|
||||
def _count_pending_writes(session) -> int:
|
||||
"""统计 session 中待 flush 的新对象数。"""
|
||||
return len(session.new) + len(session.dirty) + len(session.deleted)
|
||||
|
||||
|
||||
def test_split_preview_api_zero_db_writes(app, monkeypatch):
|
||||
"""preview API 不得 commit 任何业务或审计写入。"""
|
||||
with app.app_context():
|
||||
user = User(username='preview-zero', email='preview-zero@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Preview Zero',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'preview-tab',
|
||||
'operation_id': 'preview-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
rule_set['requires_confirmation'] = True
|
||||
|
||||
audit_before = ShippingOrderDocumentProfileAudit.query.count()
|
||||
shipping_audit_before = ShippingAuditEvent.query.count()
|
||||
|
||||
write_events: list[int] = []
|
||||
|
||||
def _before_flush(session, _flush_context, _instances):
|
||||
write_events.append(_count_pending_writes(session))
|
||||
|
||||
event.listen(db.session, 'before_flush', _before_flush)
|
||||
try:
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/xfa/split-rules/preview',
|
||||
json={
|
||||
'path_id': paths['MATNR'],
|
||||
'rule_set': rule_set,
|
||||
'profile_id': profile_id,
|
||||
},
|
||||
headers=_admin_headers(app, 'preview-zero'),
|
||||
)
|
||||
finally:
|
||||
event.remove(db.session, 'before_flush', _before_flush)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
assert data['rule_checksum']
|
||||
assert data['preview_token']
|
||||
assert data['sample_checksum']
|
||||
assert write_events == []
|
||||
assert ShippingOrderDocumentProfileAudit.query.count() == audit_before
|
||||
assert ShippingAuditEvent.query.count() == shipping_audit_before
|
||||
|
||||
|
||||
def test_split_preview_service_returns_mapped_values(app, monkeypatch):
|
||||
"""preview 须对多行 MATNR 样本产出映射预览。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='preview-values', email='preview-values@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Preview Values',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'pv-tab',
|
||||
'operation_id': 'pv-wizard',
|
||||
}, actor_id=user.id)
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
payload = profile_service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
path_id=paths['MATNR'],
|
||||
rule_set=rule_set,
|
||||
actor_id=user.id,
|
||||
profile_id=created['id'],
|
||||
include_full_values=True,
|
||||
write_audit=False,
|
||||
)
|
||||
mapped = payload['preview']['mapped_fields']
|
||||
assert mapped['customer_part_number'] == 'TEMP-S000218922'
|
||||
assert mapped['part_number'] == 'D4-A08AR12000001'
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_rule_contract.py
|
||||
|
||||
用途:锁定 XFA 字段拆分规则契约——segment/stages 白名单、Schema 映射边界、
|
||||
用途:锁定 XFA 字段拆分规则契约——matcher 模型、Schema 映射边界、
|
||||
evidence_only 约束与正则资源上限。
|
||||
依赖:xfa_split_rule_contract。
|
||||
逻辑:纯契约单测;不读 PDF;不执行引擎。
|
||||
@@ -13,13 +13,14 @@ import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XFA_SPLIT_MATCHER_PRIORITY,
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
XfaSplitStage,
|
||||
new_segment_id,
|
||||
new_stage_id,
|
||||
parse_split_rule_sets,
|
||||
split_rule_content_fingerprint,
|
||||
validate_split_rules_against_schema,
|
||||
)
|
||||
|
||||
@@ -38,12 +39,19 @@ def _mapped_segment(**overrides):
|
||||
return XfaSplitSegment.model_validate(payload)
|
||||
|
||||
|
||||
def _select_line_pipeline(*, line_index: int = 1) -> list[XfaSplitStage]:
|
||||
"""构造最小流水线:换行 → 选行。"""
|
||||
return [
|
||||
XfaSplitStage(stage_id=new_stage_id('split'), type='split_lines'),
|
||||
XfaSplitStage(stage_id=new_stage_id('sel'), type='select_line', line_index=line_index),
|
||||
]
|
||||
def _position_rule(*, line_index: int = 1, **segment_overrides) -> XfaSplitRule:
|
||||
"""构造 position 规则。"""
|
||||
return XfaSplitRule(
|
||||
rule_id='r-position',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=line_index),
|
||||
segment=_mapped_segment(**segment_overrides),
|
||||
)
|
||||
|
||||
|
||||
def test_matcher_priority_constants():
|
||||
"""冻结优先级 prefix > regex > position。"""
|
||||
assert XFA_SPLIT_MATCHER_PRIORITY['prefix'] < XFA_SPLIT_MATCHER_PRIORITY['regex']
|
||||
assert XFA_SPLIT_MATCHER_PRIORITY['regex'] < XFA_SPLIT_MATCHER_PRIORITY['position']
|
||||
|
||||
|
||||
def test_mapped_requires_target_fields():
|
||||
@@ -70,43 +78,50 @@ def test_evidence_only_forbids_target_fields():
|
||||
)
|
||||
|
||||
|
||||
def test_stage_whitelist_and_regex_limits():
|
||||
"""仅允许声明式 stage;过长/命名捕获/嵌套量词正则拒绝。"""
|
||||
assert XfaSplitStage(stage_id='s1', type='select_line', line_index=1).type == 'select_line'
|
||||
line_range = XfaSplitStage(
|
||||
stage_id='range-1', type='select_line_range',
|
||||
line_start=2, line_end=4, join_with='newline',
|
||||
def test_matcher_whitelist_and_regex_limits():
|
||||
"""matcher 白名单;过长/命名捕获/嵌套量词正则拒绝。"""
|
||||
assert XfaSplitMatcher(type='position', line_index=1).type == 'position'
|
||||
assert XfaSplitMatcher(type='prefix', value='MPN').value == 'MPN'
|
||||
assert XfaSplitMatcher(
|
||||
type='regex', pattern=r'^MPN[::](.+)$', capture_group=1,
|
||||
).type == 'regex'
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='position')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='prefix', value='')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='regex', pattern='a' * 200)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='regex', pattern=r'(?P<name>x)')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitMatcher(type='regex', pattern=r'(a+)+$')
|
||||
|
||||
|
||||
def test_rule_set_accepts_rule_id_alias():
|
||||
"""历史 rule_id 字段可解析为 rule_set_id。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
rules=[_position_rule()],
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
assert line_range.line_end == 4
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='range-2', type='select_line_range', line_start=4, line_end=2)
|
||||
assert XfaSplitStage(stage_id='s2', type='extract_prefix', value='MPN').value == 'MPN'
|
||||
assert XfaSplitStage(
|
||||
stage_id='s3', type='regex_capture', pattern=r'^MPN[::](.+)$', capture_group=1,
|
||||
).type == 'regex_capture'
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='s4', type='regex_capture', pattern='a' * 200)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='s5', type='regex_capture', pattern=r'(?P<name>x)')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitStage(stage_id='s6', type='regex_capture', pattern=r'(a+)+$')
|
||||
assert rule_set.rule_set_id == 'matnr-v1'
|
||||
assert rule_set.rule_id == 'matnr-v1'
|
||||
|
||||
|
||||
def test_system_suggestion_must_be_draft():
|
||||
"""系统推荐必须 draft + requires_confirmation。"""
|
||||
rule = XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
segment=_mapped_segment(),
|
||||
stages=_select_line_pipeline(),
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
rules=[rule],
|
||||
source_scope='line',
|
||||
rules=[_position_rule()],
|
||||
source='system_suggestion',
|
||||
status='confirmed',
|
||||
requires_confirmation=True,
|
||||
@@ -129,20 +144,19 @@ def test_validate_against_schema_requires_source_target_scope_match(
|
||||
):
|
||||
"""拆分结果只能映射与源节点相同作用域的 Schema 字段。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope=source_scope, # type: ignore[arg-type]
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=_mapped_segment(
|
||||
target_field_id='f-target',
|
||||
target_field_code='target_field',
|
||||
segment_code='scope_target',
|
||||
),
|
||||
stages=_select_line_pipeline(),
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
@@ -171,18 +185,11 @@ def test_validate_against_schema_requires_source_target_scope_match(
|
||||
def test_validate_against_schema_rejects_unknown_field():
|
||||
"""目标 Schema 不存在时拒绝。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
segment=_mapped_segment(),
|
||||
stages=_select_line_pipeline(),
|
||||
),
|
||||
],
|
||||
source_scope='line',
|
||||
rules=[_position_rule()],
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
@@ -201,28 +208,50 @@ def test_parse_split_rule_sets_empty():
|
||||
assert parse_split_rule_sets([]) == []
|
||||
|
||||
|
||||
def test_duplicate_order_rejected():
|
||||
"""同一规则集内 order 必须唯一。"""
|
||||
def test_duplicate_rule_id_rejected():
|
||||
"""同一规则集内 rule_id 必须唯一。"""
|
||||
segment = _mapped_segment(segment_code='code_a')
|
||||
with pytest.raises(ValidationError):
|
||||
XfaSplitRuleSet(
|
||||
rule_id='matnr-v1',
|
||||
rule_set_id='matnr-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1', order=1, segment=_mapped_segment(segment_code='a'),
|
||||
stages=_select_line_pipeline(line_index=1),
|
||||
rule_id='dup', matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=segment,
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='r2', order=1,
|
||||
rule_id='dup', matcher=XfaSplitMatcher(type='position', line_index=2),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='b',
|
||||
display_name='B',
|
||||
handling='evidence_only',
|
||||
segment_id=new_segment_id(), segment_code='b',
|
||||
display_name='B', handling='evidence_only',
|
||||
),
|
||||
stages=_select_line_pipeline(line_index=2),
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_mapping_target_does_not_change_confirmed_rule_fingerprint():
|
||||
"""Schema 映射与 matcher 分离,绑定目标字段不得改变内容指纹。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id='header-v1', rule_version=1,
|
||||
source_path_id='path-header', source_scope='header',
|
||||
rules=[XfaSplitRule(
|
||||
rule_id='r1',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id='segment-1', segment_code='bill_customer', display_name='账款客户',
|
||||
handling='evidence_only',
|
||||
),
|
||||
)],
|
||||
status='confirmed', requires_confirmation=False,
|
||||
)
|
||||
mapped = rule_set.model_dump(mode='json', by_alias=True)
|
||||
mapped['rules'][0]['segment'].update({
|
||||
'handling': 'mapped',
|
||||
'target_field_id': 'f-bill',
|
||||
'target_field_code': 'bill_to_customer',
|
||||
})
|
||||
assert split_rule_content_fingerprint(rule_set) == split_rule_content_fingerprint(mapped)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_split_rule_engine.py
|
||||
|
||||
用途:锁定 XFA 多阶段拆分引擎——流水线解析、同行冲突、脱敏投影、order 执行。
|
||||
用途:锁定 XFA 优先级拆分引擎——prefix > regex > position、冲突语义与 MATNR 五行样本。
|
||||
依赖:xfa_split_rule_engine、xfa_split_rule_contract。
|
||||
逻辑:纯引擎单测;不读真实 PDF。
|
||||
"""
|
||||
@@ -13,12 +13,11 @@ from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
|
||||
project_split_result_safe,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
XfaSplitStage,
|
||||
new_segment_id,
|
||||
new_stage_id,
|
||||
)
|
||||
|
||||
MATNR_RAW = (
|
||||
@@ -30,25 +29,18 @@ MATNR_RAW = (
|
||||
)
|
||||
|
||||
|
||||
def _stage(**kwargs) -> XfaSplitStage:
|
||||
"""构造 stage,自动补 stage_id。"""
|
||||
payload = {'stage_id': new_stage_id()}
|
||||
payload.update(kwargs)
|
||||
return XfaSplitStage.model_validate(payload)
|
||||
|
||||
|
||||
def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation: bool = False) -> XfaSplitRuleSet:
|
||||
"""用户配置的 MATNR 多阶段规则集。"""
|
||||
def _matnr_rule_set(*, status: str = 'confirmed', requires_confirmation: bool = False) -> XfaSplitRuleSet:
|
||||
"""MATNR 五行样本:position1 + prefix MPN,其余 unmatched evidence_only。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_id='matnr-multiline-v1',
|
||||
rule_set_id='matnr-multiline-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
strategy='pipeline',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='cpn',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_material_candidate',
|
||||
@@ -57,28 +49,12 @@ def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=1),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='desc',
|
||||
order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='material_description',
|
||||
display_name='品名规格',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=2),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='mpn',
|
||||
order=3,
|
||||
matcher=XfaSplitMatcher(
|
||||
type='prefix', value='MPN', separators=[':', ':'], case_sensitive=False,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_candidate',
|
||||
@@ -87,26 +63,6 @@ def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=3),
|
||||
_stage(type='extract_prefix', value='MPN', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='cust',
|
||||
order=4,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='customer_number_evidence',
|
||||
display_name='客户编号',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=4),
|
||||
_stage(type='extract_prefix', value='Cust nr', separators=[':', ':'], case_sensitive=False),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
@@ -118,7 +74,7 @@ def _matnr_pipeline_rule_set(*, status: str = 'confirmed', requires_confirmation
|
||||
|
||||
def test_project_split_result_masks_by_default():
|
||||
"""默认投影必须脱敏,不得泄露完整 raw_text。"""
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=_matnr_pipeline_rule_set())
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=_matnr_rule_set())
|
||||
masked = project_split_result_safe(result, include_full_values=False)
|
||||
assert masked['full_values_revealed'] is False
|
||||
assert 'TEMP-S000218922' not in str(masked['mapped_fields'])
|
||||
@@ -128,30 +84,74 @@ def test_project_split_result_masks_by_default():
|
||||
assert full['evidence_only_segments'] == []
|
||||
|
||||
|
||||
def test_multiline_pipeline_parses_matnr_sample():
|
||||
"""多阶段流水线:正式字段两项 + 证据保留。"""
|
||||
rule_set = _matnr_pipeline_rule_set()
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=rule_set)
|
||||
def test_matnr_five_line_sample():
|
||||
"""五行 MATNR:position1→customer_part_number,prefix MPN→part_number,其余 evidence_only。"""
|
||||
result = execute_split_rule_set(raw_value=MATNR_RAW, rule_set=_matnr_rule_set())
|
||||
assert result.status == 'parsed'
|
||||
assert result.mapped_fields['customer_part_number'] == 'TEMP-S000218922'
|
||||
assert result.mapped_fields['part_number'] == 'D4-A08AR12000001'
|
||||
evidence = {item.normalized_text for item in result.evidence_only_segments}
|
||||
assert 'CAB 42.5U AR1.2 FRAME' in evidence
|
||||
assert '504-006043-001' in evidence
|
||||
assert 'Cust nr:504-006043-001' in evidence
|
||||
assert 'S-ENC-FOBU260702-286' in evidence
|
||||
mapped_lines = {item.line_no for item in result.segments if item.handling == 'mapped'}
|
||||
assert mapped_lines == {1, 3}
|
||||
|
||||
|
||||
def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
"""两条流水线认领同一行 → duplicate_line_match。"""
|
||||
def test_prefix_beats_position_on_same_line():
|
||||
"""同行 prefix 优先级高于 position。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='dup-v1',
|
||||
rule_set_id='prio-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='pos',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='line1_full',
|
||||
display_name='整行',
|
||||
handling='mapped',
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='pref',
|
||||
matcher=XfaSplitMatcher(type='prefix', value='MPN', separators=[':']),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_only',
|
||||
display_name='MPN',
|
||||
handling='mapped',
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(raw_value='MPN:HELLO', rule_set=rule_set)
|
||||
assert result.mapped_fields['part_number'] == 'HELLO'
|
||||
assert 'customer_part_number' not in result.mapped_fields
|
||||
|
||||
|
||||
def test_same_priority_mapped_conflict_needs_review():
|
||||
"""同优先级两个 mapped 命中同一行 → duplicate_line_match。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id='dup-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='a',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='a_part',
|
||||
@@ -160,11 +160,10 @@ def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
target_field_id='f-cpn',
|
||||
target_field_code='customer_part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='b',
|
||||
order=2,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='b_part',
|
||||
@@ -173,7 +172,6 @@ def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
@@ -185,91 +183,17 @@ def test_same_line_claimed_by_two_pipelines_needs_review():
|
||||
assert any(d.code == 'duplicate_line_match' for d in result.diagnostics)
|
||||
|
||||
|
||||
def test_consecutive_line_range_preserves_newlines_and_claims_full_range():
|
||||
"""连续多行提取保留换行,并确保范围内行不再生成 unmatched 证据。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='address-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-address',
|
||||
source_field_code='DELIVER_TO',
|
||||
rules=[XfaSplitRule(
|
||||
rule_id='address',
|
||||
order=1,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='delivery_address',
|
||||
display_name='收货地址',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(
|
||||
type='select_line_range', line_start=2, line_end=4,
|
||||
join_with='newline',
|
||||
),
|
||||
],
|
||||
)],
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(
|
||||
raw_value='Cloud Network Technology Kft.\nBánki Donát u. 1,\n2900 Komárom,\nHungary\nFooter',
|
||||
rule_set=rule_set,
|
||||
)
|
||||
address = next(item for item in result.segments if item.rule_id == 'address')
|
||||
assert address.normalized_text == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
assert (address.line_no, address.line_end_no) == (2, 4)
|
||||
unmatched_lines = {item.line_no for item in result.evidence_only_segments if item.rule_id == 'unmatched'}
|
||||
assert unmatched_lines == {1, 5}
|
||||
|
||||
|
||||
def test_overlapping_line_range_needs_review():
|
||||
"""连续行范围与单行规则重叠时必须进入复核。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='overlap-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-address',
|
||||
source_field_code='DELIVER_TO',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='range', order=1,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='address',
|
||||
display_name='地址', handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line_range', line_start=2, line_end=4, join_with='space'),
|
||||
],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='single', order=2,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='country',
|
||||
display_name='国家', handling='evidence_only',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=4)],
|
||||
),
|
||||
],
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(raw_value='Company\nStreet\nCity\nCountry', rule_set=rule_set)
|
||||
assert result.status == 'needs_review'
|
||||
assert any(d.code == 'duplicate_line_match' and d.line_no == 4 for d in result.diagnostics)
|
||||
|
||||
|
||||
def test_same_field_multiple_segment_needs_review():
|
||||
"""同一正式字段被多段命中 → needs_review。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='conflict-v1',
|
||||
rule_set_id='conflict-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
source_scope='line',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='a_part',
|
||||
@@ -278,11 +202,10 @@ def test_same_field_multiple_segment_needs_review():
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=1)],
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='r2',
|
||||
order=2,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=2),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='b_part',
|
||||
@@ -291,7 +214,6 @@ def test_same_field_multiple_segment_needs_review():
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[_stage(type='split_lines'), _stage(type='select_line', line_index=2)],
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
@@ -303,63 +225,24 @@ def test_same_field_multiple_segment_needs_review():
|
||||
assert any(d.code == 'same_field_multiple_segment' for d in result.diagnostics)
|
||||
|
||||
|
||||
def test_prefix_after_select_line():
|
||||
"""选行后再按前缀提取。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='prio-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-matnr',
|
||||
source_field_code='MATNR',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='pref',
|
||||
order=1,
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='mpn_only',
|
||||
display_name='MPN',
|
||||
handling='mapped',
|
||||
target_field_id='f-pn',
|
||||
target_field_code='part_number',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines'),
|
||||
_stage(type='select_line', line_index=1),
|
||||
_stage(type='extract_prefix', value='MPN', separators=[':']),
|
||||
],
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
)
|
||||
result = execute_split_rule_set(raw_value='MPN:HELLO', rule_set=rule_set)
|
||||
assert result.mapped_fields['part_number'] == 'HELLO'
|
||||
|
||||
|
||||
def test_line_breaks_config_is_honored():
|
||||
"""normalization.line_breaks 参与未匹配行盘点切分。"""
|
||||
"""normalization.line_breaks 参与拆行与未匹配行盘点。"""
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_id='breaks-v1',
|
||||
rule_set_id='breaks-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-x',
|
||||
source_field_code='X',
|
||||
source_scope='line',
|
||||
normalization={'trim': True, 'remove_empty_lines': True, 'line_breaks': ['|']},
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='r1',
|
||||
order=1,
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='first',
|
||||
display_name='First',
|
||||
handling='evidence_only',
|
||||
),
|
||||
stages=[
|
||||
_stage(type='split_lines', line_breaks=['|'], trim=True, remove_empty_lines=True),
|
||||
_stage(type='select_line', line_index=1),
|
||||
],
|
||||
),
|
||||
],
|
||||
source='user',
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_audit.py
|
||||
|
||||
用途:验收统一视觉/拆分审计事件已注册,并在确认视觉绑定与保存草稿路径被触发;
|
||||
confirm 路径双写平台审计含加密快照引用。
|
||||
依赖:xfa_contract、progress_audit_contract、visual_binding_service、order_document_profile_service、
|
||||
audit_service、ShippingAuditEvent、ShippingXfaAuditSnapshot。
|
||||
逻辑:契约白名单断言 + mock 审计写入 + confirm 路径 snapshot refs 集成断言。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_svc
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS,
|
||||
build_profile_audit_context,
|
||||
record_visual_binding_audit,
|
||||
)
|
||||
|
||||
|
||||
REQUIRED_UNIFIED_AUDIT_EVENTS = (
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_profile_draft_saved',
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
)
|
||||
|
||||
|
||||
def _ensure_secret_key(app) -> None:
|
||||
"""确保 SECRET_KEY 可用于派生 XFA 审计快照 Fernet。"""
|
||||
if not str(app.config.get('SECRET_KEY') or '').strip():
|
||||
app.config['SECRET_KEY'] = 'test-shipping-xfa-visual-audit-secret'
|
||||
|
||||
|
||||
def test_unified_visual_and_split_audit_events_registered():
|
||||
"""关键审计事件必须同时出现在 XFA 契约与进度事件白名单。"""
|
||||
for event in REQUIRED_UNIFIED_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES, event
|
||||
assert event in XFA_PROGRESS_EVENT_CODES, event
|
||||
for event in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES
|
||||
|
||||
|
||||
def test_confirm_visual_binding_fires_confirmed_audit():
|
||||
"""确认视觉绑定路径必须写入 xfa_visual_binding_confirmed(Profile _audit)。"""
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
with patch(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
) as platform_mock:
|
||||
record_visual_binding_audit(
|
||||
profile_id=11,
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=3,
|
||||
before={'status': 'suggested', 'field_code': 'part_number'},
|
||||
after={'status': 'confirmed', 'field_code': 'part_number'},
|
||||
detail={'binding_id': 'bind-1', 'action': 'confirm'},
|
||||
operation_id='op-confirm-1',
|
||||
profile_context={
|
||||
'profile_code': 'PO-XFA',
|
||||
'profile_version': 1,
|
||||
'definition_checksum': 'sha256:abc',
|
||||
'revision_no': 2,
|
||||
'template_mode': 'xfa_dataset',
|
||||
},
|
||||
)
|
||||
assert audit_mock.call_count == 1
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
assert kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert kwargs['detail']['before_visual_binding']['status'] == 'suggested'
|
||||
assert kwargs['detail']['after_visual_binding']['status'] == 'confirmed'
|
||||
assert platform_mock.call_count == 1
|
||||
platform_kwargs = platform_mock.call_args.kwargs
|
||||
assert platform_kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert platform_kwargs['aggregate_type'] == 'shipping_order_document_profile'
|
||||
assert platform_kwargs['aggregate_id'] == '11'
|
||||
assert platform_kwargs['sensitivity_level'] == 'sensitive'
|
||||
assert platform_kwargs['context_refs']['binding_id'] == 'bind-1'
|
||||
assert platform_kwargs['context_refs']['action'] == 'confirm'
|
||||
|
||||
|
||||
def test_confirm_visual_binding_platform_audit_has_snapshot_refs(app):
|
||||
"""confirm 路径双写平台事件含加密 full 快照引用。"""
|
||||
with app.app_context():
|
||||
_ensure_secret_key(app)
|
||||
record_visual_binding_audit(
|
||||
profile_id=77,
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=3,
|
||||
before={'status': 'suggested', 'field_code': 'part_number', 'binding_id': 'bind-77'},
|
||||
after={'status': 'confirmed', 'field_code': 'part_number', 'binding_id': 'bind-77'},
|
||||
detail={'binding_id': 'bind-77', 'action': 'confirm'},
|
||||
operation_id='op-confirm-snap',
|
||||
request_id='req-confirm-snap',
|
||||
raw_binding_before={'binding_id': 'bind-77', 'field_code': 'part_number', 'visual_binding': {'status': 'suggested'}},
|
||||
raw_binding_after={'binding_id': 'bind-77', 'field_code': 'part_number', 'visual_binding': {'status': 'confirmed'}},
|
||||
profile_context={
|
||||
'profile_code': 'PO-XFA-77',
|
||||
'profile_version': 3,
|
||||
'definition_checksum': 'sha256:before-cs',
|
||||
'revision_no': 4,
|
||||
'template_mode': 'xfa_dataset',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
event = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(
|
||||
aggregate_type='shipping_order_document_profile',
|
||||
aggregate_id='77',
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert event is not None
|
||||
assert event.operation_id == 'op-confirm-snap'
|
||||
assert event.request_id == 'req-confirm-snap'
|
||||
ctx = event.context_refs_json or {}
|
||||
assert ctx.get('snapshot_before_ref', '').startswith('xfa-snap-')
|
||||
assert ctx.get('snapshot_after_ref', '').startswith('xfa-snap-')
|
||||
assert ctx.get('binding_id') == 'bind-77'
|
||||
assert ctx.get('action') == 'confirm'
|
||||
assert event.before_hash
|
||||
assert event.after_hash
|
||||
assert ShippingXfaAuditSnapshot.query.filter_by(object_id='77').count() >= 2
|
||||
assert event.metadata_json.get('binding_id') == 'bind-77'
|
||||
|
||||
|
||||
def test_save_draft_path_emits_draft_saved_audit_hook():
|
||||
"""保存草稿路径上的 binding/split diff 审计钩子可被调用(mock)。"""
|
||||
before = {'bindings': [], 'split_rules': []}
|
||||
after = {
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-0001-aaaa',
|
||||
'field_id': 'fld-1',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-1',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}],
|
||||
'split_rules': [],
|
||||
}
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
profiles._audit_xfa_binding_changes(
|
||||
profile_id=21,
|
||||
actor_id=5,
|
||||
operation_id='op-save-1',
|
||||
browser_session_id='tab-1',
|
||||
previous_definition=before,
|
||||
next_definition=after,
|
||||
)
|
||||
profiles._audit(
|
||||
profile_id=21,
|
||||
event_type='xfa_profile_draft_saved',
|
||||
actor_id=5,
|
||||
operation_id='op-save-1',
|
||||
detail={'definition_checksum': 'sha256:test'},
|
||||
)
|
||||
events = [call.kwargs['event_type'] for call in audit_mock.call_args_list]
|
||||
assert 'xfa_profile_draft_saved' in events
|
||||
# binding 变更至少产出一条审计(created/updated 族)
|
||||
assert any(
|
||||
event.startswith('xfa_visual_binding_') or event == 'xfa_mapping_saved' or 'binding' in event
|
||||
for event in events
|
||||
) or audit_mock.call_count >= 2
|
||||
|
||||
|
||||
def test_confirm_service_calls_record_audit_when_definition_ready():
|
||||
"""confirm_xfa_visual_binding 在成功路径委托 record_visual_binding_audit(mock 编排)。"""
|
||||
profile = MagicMock()
|
||||
profile.id = 9
|
||||
profile.status = 'draft'
|
||||
profile.template_mode = 'xfa_dataset'
|
||||
profile.definition_json = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-0001-aaaa',
|
||||
'field_id': 'fld-1',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-1',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.5,
|
||||
},
|
||||
}],
|
||||
'split_rules': [],
|
||||
}
|
||||
with (
|
||||
patch.object(visual_svc, '_profile', return_value=profile),
|
||||
patch.object(visual_svc.lease_service, 'require_active_lease'),
|
||||
patch.object(visual_svc, 'record_visual_binding_audit') as audit_mock,
|
||||
patch.object(visual_svc.db.session, 'flush'),
|
||||
patch.object(visual_svc.db.session, 'commit'),
|
||||
):
|
||||
result = visual_svc.confirm_xfa_visual_binding(
|
||||
9,
|
||||
'bind-0001-aaaa',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=7,
|
||||
browser_session_id='sess',
|
||||
lease_token='lease',
|
||||
operation_id='op-1',
|
||||
)
|
||||
assert result['status'] == 'confirmed'
|
||||
assert audit_mock.call_count == 1
|
||||
assert audit_mock.call_args.kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_auto_create.py
|
||||
|
||||
用途:阶段 6 统一自动建单——Profile checksum / 视觉可发布性再验 + CQ 指标消费。
|
||||
依赖:order_stp_auto_create_service、candidate_qualification_service、phase6 helpers。
|
||||
逻辑:适配 phase6 正例;断言低视觉率 / checksum 漂移阻断;STP 再验失败 needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
evaluate_candidate_qualification,
|
||||
)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
_revalidate_published_xfa_profile,
|
||||
_xfa_stp_precheck,
|
||||
)
|
||||
from tests.test_shipping_xfa_auto_create_phase6 import (
|
||||
_eligible_xfa_candidate,
|
||||
_patch_xfa_policy,
|
||||
_xfa_unit,
|
||||
)
|
||||
|
||||
|
||||
def test_unified_auto_create_passes_phase6_baseline(monkeypatch):
|
||||
"""关键断言:既有 phase6 正例在统一门禁下仍可自动建单。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_parser_trace_visual_rate_blocks_auto_create(monkeypatch):
|
||||
"""关键断言:parser_trace.visual_coverage_rate < 1.0 → 阻断。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(xfa_unified_metrics={
|
||||
'visual_coverage_rate': 0.5,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert result['gates'].get('xfa_unified_profile_snapshot') is False
|
||||
assert 'xfa_visual_coverage_insufficient' in result['blocking_reason_codes']
|
||||
|
||||
|
||||
def test_stp_revalidate_checksum_mismatch(monkeypatch):
|
||||
"""关键断言:已发布 Profile checksum 漂移 → xfa_profile_checksum_mismatch。"""
|
||||
profile = SimpleNamespace(
|
||||
status='published',
|
||||
checksum='sha256:other',
|
||||
structure_fingerprint='sha256:other',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'bindings': []},
|
||||
schema_version=SimpleNamespace(definition_json={'fields': []}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.db.session.get',
|
||||
lambda model, pk: profile,
|
||||
)
|
||||
ok, reason = _revalidate_published_xfa_profile(
|
||||
validation={
|
||||
'qualification': {
|
||||
'parser_trace': {
|
||||
'profile_id': 88,
|
||||
'profile_checksum': 'sha256:deadbeef',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert ok is False
|
||||
assert reason == 'xfa_profile_checksum_mismatch'
|
||||
|
||||
|
||||
def test_stp_precheck_blocks_when_unified_gate_failed(monkeypatch):
|
||||
"""关键断言:CQ 快照 xfa_unified_profile_snapshot=false 时 STP 阻断。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.extraction_emergency_stop_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.xfa_shadow_mode_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._revalidate_published_xfa_profile',
|
||||
lambda **kwargs: (True, None),
|
||||
)
|
||||
allowed, reason = _xfa_stp_precheck(
|
||||
validation={
|
||||
'can_auto_create': True,
|
||||
'qualification': {
|
||||
'gates': {
|
||||
'xfa_auto_create_policy': True,
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': True,
|
||||
'xfa_evidence_integrity': True,
|
||||
'xfa_unified_profile_snapshot': False,
|
||||
},
|
||||
'blocking_reason_codes': ['xfa_visual_coverage_insufficient'],
|
||||
},
|
||||
},
|
||||
)
|
||||
assert allowed is False
|
||||
assert reason == 'xfa_visual_coverage_insufficient'
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_binding_contract.py
|
||||
|
||||
用途:验收统一字段 binding 契约(value_binding + visual_binding + split_rule_ref)。
|
||||
依赖:xfa_contract、pytest。
|
||||
逻辑:覆盖合法绑定、非法值类型、视觉框面积、发布可发布性、checksum 稳定性;
|
||||
断言 XFA Profile 不得混入 coordinate 表区键,但允许 visual 归一化框。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
XfaLineMapping,
|
||||
XfaNormalizedBBox,
|
||||
XfaSourceContract,
|
||||
XfaUnifiedFieldBinding,
|
||||
XfaValueBinding,
|
||||
XfaVisualBinding,
|
||||
canonical_unified_bindings_payload,
|
||||
is_formal_binding_publishable,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import (
|
||||
compute_definition_business_checksum,
|
||||
compute_unified_bindings_checksum,
|
||||
)
|
||||
|
||||
|
||||
def _source() -> XfaSourceContract:
|
||||
"""构造最小合法 source_contract。"""
|
||||
return XfaSourceContract(
|
||||
template_packet_checksum='sha256:' + ('a' * 64),
|
||||
dataset_structure_fingerprint='sha256:' + ('b' * 64),
|
||||
dataset_root_path='/data',
|
||||
authoritative_line_collection_path='/data/ITEMS/DATA',
|
||||
mirror_collection_paths=['/data/ITEMS1/DATA'],
|
||||
)
|
||||
|
||||
|
||||
def _confirmed_binding(**overrides: object) -> dict[str, object]:
|
||||
"""构造已确认的统一绑定字典。"""
|
||||
payload: dict[str, object] = {
|
||||
'binding_id': 'bind-0001-aaaa-bbbb',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-matnr',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'acroform_widget',
|
||||
'status': 'confirmed',
|
||||
'confidence': 0.98,
|
||||
},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def test_unified_binding_accepts_visual_bbox_without_coordinate_keys() -> None:
|
||||
"""允许 visual_binding;拒绝 table_regions 等 coordinate 键。"""
|
||||
profile = OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
assert len(profile.bindings) == 1
|
||||
assert profile.bindings[0].visual_binding.status == 'confirmed'
|
||||
|
||||
with pytest.raises(ValidationError, match='coordinate keys'):
|
||||
OrderXfaDatasetProfile.model_validate(
|
||||
{
|
||||
'source_contract': _source().model_dump(mode='json'),
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'table_regions': [],
|
||||
'bindings': [_confirmed_binding()],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_dual_binding_source() -> None:
|
||||
"""bindings 与 legacy mappings 不得共存。"""
|
||||
with pytest.raises(ValidationError, match='xfa_dual_binding_source'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(
|
||||
row_path='/data/ITEMS/DATA',
|
||||
fields=[{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_legacy_only_without_bindings() -> None:
|
||||
"""仅 legacy mappings 无 bindings 时正式契约 fail-closed。"""
|
||||
with pytest.raises(ValidationError, match='xfa_legacy_mappings_forbidden'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(
|
||||
row_path='/data/ITEMS/DATA',
|
||||
fields=[{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
),
|
||||
bindings=[],
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_non_dataset_value_binding() -> None:
|
||||
"""XFA Profile 内正式绑定不得使用 pdf_coordinate。"""
|
||||
bad = _confirmed_binding(
|
||||
value_binding={'type': 'pdf_coordinate', 'region_id': 'region-1'},
|
||||
)
|
||||
with pytest.raises(ValidationError, match='xfa_dataset'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(bad)],
|
||||
)
|
||||
|
||||
|
||||
def test_visual_bbox_requires_positive_area() -> None:
|
||||
"""归一化框必须正面积。"""
|
||||
with pytest.raises(ValidationError, match='positive area'):
|
||||
XfaNormalizedBBox(x0=0.5, y0=0.5, x1=0.4, y1=0.6)
|
||||
|
||||
|
||||
def test_publishable_requires_confirmed_visual() -> None:
|
||||
"""正式字段发布门禁:视觉状态须 confirmed。"""
|
||||
confirmed = XfaUnifiedFieldBinding.model_validate(_confirmed_binding())
|
||||
assert is_formal_binding_publishable(confirmed) is True
|
||||
|
||||
suggested = XfaUnifiedFieldBinding.model_validate(
|
||||
_confirmed_binding(
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.5,
|
||||
},
|
||||
),
|
||||
)
|
||||
assert is_formal_binding_publishable(suggested) is False
|
||||
|
||||
|
||||
def test_bindings_checksum_covers_visual_and_split_ref() -> None:
|
||||
"""checksum 随 visual 或 split_rule_ref 变化而变化。"""
|
||||
base = [_confirmed_binding()]
|
||||
with_split = [
|
||||
_confirmed_binding(
|
||||
split_rule_ref={'rule_set_id': 'ruleset-0001-aaaa', 'segment_id': 'seg-0001-bbbb'},
|
||||
),
|
||||
]
|
||||
moved = [
|
||||
_confirmed_binding(
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
),
|
||||
]
|
||||
c1 = compute_unified_bindings_checksum(base)
|
||||
c2 = compute_unified_bindings_checksum(with_split)
|
||||
c3 = compute_unified_bindings_checksum(moved)
|
||||
assert c1 != c2
|
||||
assert c1 != c3
|
||||
assert c1.startswith('sha256:')
|
||||
|
||||
# canonical 排序稳定
|
||||
assert canonical_unified_bindings_payload(base)[0]['binding_id'] == 'bind-0001-aaaa-bbbb'
|
||||
|
||||
|
||||
def test_definition_business_checksum_includes_split_rules() -> None:
|
||||
"""definition 业务 checksum 覆盖 split_rules。"""
|
||||
definition_a = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [_confirmed_binding()],
|
||||
'split_rules': [],
|
||||
}
|
||||
definition_b = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [_confirmed_binding()],
|
||||
'split_rules': [{'rule_set_id': 'x', 'rules': []}],
|
||||
}
|
||||
assert compute_definition_business_checksum(definition_a) != compute_definition_business_checksum(
|
||||
definition_b,
|
||||
)
|
||||
|
||||
|
||||
def test_value_binding_type_constraints() -> None:
|
||||
"""xfa_dataset 必须 path;坐标类型必须 region_id。"""
|
||||
with pytest.raises(ValidationError):
|
||||
XfaValueBinding(type='xfa_dataset', path_id=None, data_path=None)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaValueBinding(type='pdf_coordinate')
|
||||
ok = XfaValueBinding(type='pdf_coordinate', region_id='r1')
|
||||
assert ok.region_id == 'r1'
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_blind_test.py
|
||||
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;哨兵 metrics 可序列化。
|
||||
依赖:document_profile_quality_service serialize / metrics 前缀。
|
||||
逻辑:纯单元验证 metrics 哨兵编解码与阈值语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
_XFA_BLIND_METRICS_PREFIX,
|
||||
serialize_suite,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_serialize_suite_strips_metrics_sentinel():
|
||||
"""关键断言:failure_codes 中的指标哨兵剥离为 latest_run.metrics。"""
|
||||
metrics = {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
}
|
||||
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=[
|
||||
f"{_XFA_BLIND_METRICS_PREFIX}{json.dumps(metrics, sort_keys=True, separators=(',', ':'))}",
|
||||
'sample:1:order_field:po:mismatch',
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
payload = serialize_suite(suite)
|
||||
assert payload['latest_run']['metrics'] == metrics
|
||||
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())
|
||||
@@ -0,0 +1,280 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_mapping_api.py
|
||||
|
||||
用途:验收 XFA 统一映射 suggest API(视觉 + 拆分规则)与保存 bindings/split_rules。
|
||||
依赖:Flask test client、phase2 XFA 夹具、suggestion_service、profile_service。
|
||||
逻辑:统一 suggest 返回 suggested/draft 状态;保存后 definition 含 bindings 与 split_rules。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileDraftRevision, User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import new_segment_id
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
_confirmed_matnr_rule_set,
|
||||
_multiline_datasets_xml,
|
||||
_schema_definition,
|
||||
)
|
||||
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf
|
||||
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io, _seed_xfa_sample
|
||||
|
||||
|
||||
def _schema_version_id(app) -> int:
|
||||
"""发布含拆分目标字段的 Schema,返回 version id。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ShippingOrderSchema, ShippingOrderSchemaVersion
|
||||
|
||||
with app.app_context():
|
||||
schema = ShippingOrderSchema(schema_code='XFA_UNIFIED', display_name='XFA Unified')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='d' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json=_schema_definition(),
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
return int(version.id)
|
||||
|
||||
|
||||
def _admin_headers(app, username: str = 'xfa-unified-admin') -> dict[str, str]:
|
||||
"""生成 admin JWT headers。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(username=username, email=f'{username}@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
|
||||
def _multiline_sample(app, monkeypatch, *, user: User):
|
||||
"""写入多行 MATNR XFA 样本。"""
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
|
||||
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
|
||||
|
||||
pdf_bytes = build_synthetic_xfa_hybrid_pdf(_multiline_datasets_xml())
|
||||
content_hash = sha256(pdf_bytes).hexdigest()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-ML-{content_hash[:10]}',
|
||||
owner_user_id=user.id,
|
||||
original_filename='xfa-multiline.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-ML-{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-multiline.pdf',
|
||||
content_hash=content_hash,
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
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'),
|
||||
'MATNR': _path_id_for('/data/ITEMS/DATA/MATNR'),
|
||||
'MENGE': _path_id_for('/data/ITEMS/DATA/MENGE'),
|
||||
}
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _a: pdf_bytes)
|
||||
return int(document.id), paths
|
||||
|
||||
|
||||
def test_unified_suggest_api_returns_visual_and_split(app, monkeypatch, _patch_xfa_io):
|
||||
"""统一 suggest API 须返回视觉候选与 draft 拆分建议。"""
|
||||
with app.app_context():
|
||||
user = User(username='unified-suggest', email='unified-suggest@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Unified Suggest',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'unified-tab',
|
||||
'operation_id': 'unified-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/unified-mapping/suggest',
|
||||
json={
|
||||
'document_id': document_id,
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
'path_id': paths['MATNR'],
|
||||
},
|
||||
headers=_admin_headers(app, 'unified-suggest'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
assert data['suggestion_status'] == 'suggested'
|
||||
assert data['visual_suggestion']['diagnostics']['auto_confirm_blocked'] is True
|
||||
rule_set = data['split_rule_suggestion']['rule_set']
|
||||
assert rule_set['status'] == 'draft'
|
||||
assert rule_set['status'] != 'confirmed'
|
||||
assert rule_set['requires_confirmation'] is True
|
||||
matchers = [rule['matcher']['type'] for rule in rule_set['rules']]
|
||||
assert 'position' in matchers
|
||||
assert 'prefix' in matchers
|
||||
|
||||
|
||||
def test_save_bindings_and_split_rules_creates_revision(app, monkeypatch, _patch_xfa_io):
|
||||
"""保存 bindings + split_rules 须规范化写入 definition 并产生 Revision。"""
|
||||
with app.app_context():
|
||||
user = User(username='unified-save', email='unified-save@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Unified Save',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'save-tab',
|
||||
'operation_id': 'save-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile_id = created['id']
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
definition = dict(profile.definition_json)
|
||||
definition['header_mappings'] = []
|
||||
definition['line_mapping'] = {
|
||||
'row_path': definition['source_contract']['authoritative_line_collection_path'],
|
||||
'fields': [],
|
||||
}
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
rule_set['requires_confirmation'] = True
|
||||
segment_id = new_segment_id()
|
||||
definition['split_rules'] = [rule_set]
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-save-test-001',
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['MENGE'],
|
||||
'data_path': '/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
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='save-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='save-bindings-op-1',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert saved['definition']['bindings'][0]['field_code'] == 'quantity'
|
||||
assert saved['definition']['split_rules'][0]['status'] == 'draft'
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='save-bindings-op-1',
|
||||
).count() == 1
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile_id, operation_id='save-bindings-op-1',
|
||||
).one()
|
||||
snap = revision.definition_snapshot_json or {}
|
||||
assert 'bindings' in snap
|
||||
assert 'split_rules' in snap
|
||||
|
||||
|
||||
def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_io):
|
||||
"""拆分建议 service 层 status 必须为 draft/suggested。"""
|
||||
with app.app_context():
|
||||
user = User(username='split-svc', email='split-svc@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Split Svc',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'svc-tab',
|
||||
'operation_id': 'svc-wizard',
|
||||
}, actor_id=user.id)
|
||||
payload = suggestion_service.suggest_xfa_split_rules(
|
||||
created['id'],
|
||||
document_id=document_id,
|
||||
path_id=paths['MATNR'],
|
||||
actor_id=user.id,
|
||||
write_audit=False,
|
||||
)
|
||||
assert payload['suggestion_status'] == 'suggested'
|
||||
assert payload['rule_set']['status'] == 'draft'
|
||||
assert 'confirmed' != payload['rule_set']['status']
|
||||
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_migration.py
|
||||
|
||||
用途:验收统一 binding 一次性迁移(坐标 + XFA Dry Run;路径保留 100%;正式字段差异 0)。
|
||||
依赖:order_profile_unified_migration、pytest。
|
||||
逻辑:使用合成 definition,不接真实 PDF;断言报告指标与 convert 稳定性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
_clear_xfa_legacy_mappings,
|
||||
build_migration_report,
|
||||
convert_coordinate_definition_to_unified_bindings,
|
||||
convert_xfa_definition_to_unified_bindings,
|
||||
)
|
||||
|
||||
|
||||
def _coordinate_definition() -> dict:
|
||||
"""构造最小合法坐标 definition(含 order_field_layouts)。"""
|
||||
return {
|
||||
'template_mode': 'coordinate',
|
||||
'document_match': {
|
||||
'required_anchors': [],
|
||||
'optional_anchors': [],
|
||||
'negative_anchors': [],
|
||||
},
|
||||
'table_regions': [{
|
||||
'region_id': 'table_main',
|
||||
'page_scope': 'first_page',
|
||||
'region': {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.8},
|
||||
'header_layouts': [],
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'region_id': 'line_part',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.2, 'y0': 0.3, 'x1': 0.4, 'y1': 0.35},
|
||||
'allowed_sources': ['pdf_text'],
|
||||
'extractor_key': 'direct',
|
||||
}],
|
||||
}],
|
||||
'continuation_rule': {'required_anchor_ids': []},
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'hdr_po',
|
||||
'field_id': 'fld-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'absolute_value_region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.14},
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
|
||||
def _xfa_definition() -> dict:
|
||||
"""构造最小合法 XFA definition(header + line mapping)。"""
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'map-po',
|
||||
'field_id': 'fld-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
'path_id': 'path-ebeln',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
'line_mapping': {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
},
|
||||
'bindings': [],
|
||||
'split_rules': [],
|
||||
}
|
||||
|
||||
|
||||
def test_coordinate_dry_run_path_preserve_and_zero_field_diff():
|
||||
"""坐标迁移:正式字段差异 0;bindings 覆盖 order + line 字段。"""
|
||||
before = _coordinate_definition()
|
||||
after, stats = convert_coordinate_definition_to_unified_bindings(before)
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
assert report['field_diff_count'] == 0
|
||||
assert report['path_preserve_rate'] == 100.0
|
||||
assert report['binding_count'] >= 2
|
||||
assert report['pending_visual_count'] == 0
|
||||
assert all(
|
||||
item['value_binding']['type'] in {'pdf_coordinate', 'ocr_coordinate'}
|
||||
for item in after['bindings']
|
||||
)
|
||||
assert all(item['visual_binding']['status'] == 'confirmed' for item in after['bindings'])
|
||||
# 原 coordinate 键保留
|
||||
assert after['order_field_layouts']
|
||||
assert after['table_regions']
|
||||
|
||||
|
||||
def test_xfa_dry_run_path_preserve_100_and_zero_field_diff():
|
||||
"""XFA 迁移:path_id 保留率 100%;正式字段差异 0;视觉框为 suggested。"""
|
||||
before = _xfa_definition()
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
assert report['path_preserve_rate'] == 100.0
|
||||
assert report['field_diff_count'] == 0
|
||||
assert report['binding_count'] == 2
|
||||
assert report['pending_visual_count'] == 2
|
||||
assert report['legacy_will_be_cleared'] is True
|
||||
assert report['legacy_mapping_counts'] == {'header': 1, 'line': 1}
|
||||
assert after['header_mappings'] == before['header_mappings']
|
||||
assert after['line_mapping'] == before['line_mapping']
|
||||
assert after['source_contract'] == before['source_contract']
|
||||
assert all(item['value_binding']['type'] == 'xfa_dataset' for item in after['bindings'])
|
||||
assert {item['value_binding']['path_id'] for item in after['bindings']} == {
|
||||
'path-ebeln', 'path-matnr',
|
||||
}
|
||||
assert all(item['visual_binding']['status'] == 'suggested' for item in after['bindings'])
|
||||
|
||||
|
||||
def test_xfa_execute_clears_legacy_mappings():
|
||||
"""Execute 后须清除 header_mappings / line_mapping.fields,仅保留 bindings。"""
|
||||
before = _xfa_definition()
|
||||
after, _stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
cleared = _clear_xfa_legacy_mappings(after)
|
||||
assert cleared['bindings']
|
||||
assert cleared['header_mappings'] == []
|
||||
assert cleared['line_mapping']['fields'] == []
|
||||
assert cleared['line_mapping']['row_path'] == before['source_contract']['authoritative_line_collection_path']
|
||||
|
||||
|
||||
def test_xfa_migrated_pending_visual_blocks_publish_gate():
|
||||
"""关键断言:迁移 Execute 清除 legacy 后 suggested 视觉框仍阻断发布。"""
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
|
||||
before = _xfa_definition()
|
||||
after, _stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
migrated = _clear_xfa_legacy_mappings(after)
|
||||
schema_field_ids = {'fld-po', 'fld-part'}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=migrated,
|
||||
schema_field_ids=schema_field_ids,
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_scan_unified_migration_profiles_synthetic():
|
||||
"""scan 返回逐族状态;无 DB 时用 summarize 逻辑(纯函数部分)。"""
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
scan_unified_migration_profiles,
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
coord = summarize_unified_migration_status(_coordinate_definition(), template_mode='coordinate')
|
||||
assert coord['unified_binding_status'] == 'needs_migration'
|
||||
assert coord['field_diff_count'] == 0
|
||||
|
||||
xfa = summarize_unified_migration_status(_xfa_definition(), template_mode='xfa_dataset')
|
||||
assert xfa['unified_binding_status'] == 'needs_migration'
|
||||
assert xfa['pending_visual_count'] == 2
|
||||
assert xfa['path_preserve_rate'] == 100.0
|
||||
|
||||
# scan 需 DB;此处只验证函数可导入且 summarize 与 convert 一致
|
||||
assert callable(scan_unified_migration_profiles)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_binding.py
|
||||
|
||||
用途:验收 XFA 视觉绑定候选评分、歧义诊断与审计 before/after。
|
||||
依赖:xfa_visual_binding、xfa_acroform、order_document_profile_visual_binding_service。
|
||||
逻辑:纯函数 + mock Widget/datasets;不接真实 PDFium/google-re2。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import XfaAcroformWidget
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
visual_binding_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
|
||||
|
||||
def _dataset_analysis() -> XfaDatasetAnalysis:
|
||||
"""构造最小 datasets 分析(双 MATNR 歧义路径)。"""
|
||||
return XfaDatasetAnalysis(
|
||||
nodes=[],
|
||||
dataset_root_path='/data',
|
||||
leaf_values_by_path={
|
||||
'/data/HEADER/EBELN': '4510039227',
|
||||
'/data/ITEMS/DATA/MATNR': 'TEMP-S000218922',
|
||||
'/data/ITEMS1/DATA/MATNR': 'TEMP-S000218922',
|
||||
},
|
||||
header_candidates=['/data/HEADER'],
|
||||
collection_candidates=[],
|
||||
known_path_ids=set(),
|
||||
stats={},
|
||||
)
|
||||
|
||||
|
||||
def _widget(
|
||||
*,
|
||||
short_name: str,
|
||||
value: str,
|
||||
page_no: int = 1,
|
||||
bbox: dict[str, float] | None = None,
|
||||
) -> XfaAcroformWidget:
|
||||
"""合成单个 Widget。"""
|
||||
region = bbox or {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55}
|
||||
qname = f'form[0].{short_name}[0]'
|
||||
return XfaAcroformWidget(
|
||||
widget_id=f'wgt-{short_name}',
|
||||
qualified_name=qname,
|
||||
short_name=short_name,
|
||||
page_no=page_no,
|
||||
normalized_bbox=region,
|
||||
value=value,
|
||||
value_masked=value[:4] + '***' if value else '',
|
||||
)
|
||||
|
||||
|
||||
def test_visual_binding_candidates_never_auto_confirm():
|
||||
"""所有候选 status 必须为 suggested,diagnostics 阻断自动确认。"""
|
||||
widgets = [
|
||||
_widget(short_name='EBELN', value='4510039227', bbox={'x0': 0.1, 'y0': 0.1, 'x1': 0.4, 'y1': 0.2}),
|
||||
_widget(short_name='MATNR', value='TEMP-S000218922', bbox={'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55}),
|
||||
]
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=1,
|
||||
normalized_bbox={'x0': 0.1, 'y0': 0.38, 'x1': 0.52, 'y1': 0.58},
|
||||
dataset_analysis=_dataset_analysis(),
|
||||
widgets=widgets,
|
||||
)
|
||||
assert result['candidates']
|
||||
assert all(item['status'] == 'suggested' for item in result['candidates'])
|
||||
assert result['diagnostics']['auto_confirm_blocked'] is True
|
||||
assert 'confirmed' not in str(result).lower() or all(
|
||||
item['status'] != 'confirmed' for item in result['candidates']
|
||||
)
|
||||
|
||||
|
||||
def test_ambiguous_path_candidates_flagged():
|
||||
"""同短名多 datasets 路径时必须标记 ambiguous。"""
|
||||
widgets = [_widget(short_name='MATNR', value='TEMP-S000218922')]
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=1,
|
||||
normalized_bbox={'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
dataset_analysis=_dataset_analysis(),
|
||||
widgets=widgets,
|
||||
)
|
||||
top = result['candidates'][0]
|
||||
assert len(top['path_candidates']) >= 2
|
||||
assert result['diagnostics']['ambiguous'] is True
|
||||
|
||||
|
||||
def test_visual_binding_audit_events_registered():
|
||||
"""视觉绑定审计事件须注册于契约白名单。"""
|
||||
for event in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES, event
|
||||
assert event in XFA_PROGRESS_EVENT_CODES, event
|
||||
|
||||
|
||||
def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
"""确认视觉绑定必须写入 before/after 审计摘要。"""
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as svc
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-test-001',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.9,
|
||||
},
|
||||
}],
|
||||
}
|
||||
before_snap = visual_binding_audit_snapshot(definition['bindings'][0])
|
||||
assert before_snap['status'] == 'suggested'
|
||||
|
||||
with patch.object(lease_service, 'require_active_lease', return_value=object()):
|
||||
with patch.object(svc, '_profile') as profile_mock:
|
||||
profile = type('P', (), {'id': 1, 'status': 'draft', 'template_mode': 'xfa_dataset', 'definition_json': definition})()
|
||||
profile_mock.return_value = profile
|
||||
with patch.object(svc.db.session, 'flush', lambda: None):
|
||||
with patch.object(svc.db.session, 'commit', lambda: None):
|
||||
with patch.object(svc, 'record_visual_binding_audit') as audit_mock:
|
||||
svc.confirm_xfa_visual_binding(
|
||||
1,
|
||||
'bind-test-001',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.11, 'x1': 0.31, 'y1': 0.21},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
)
|
||||
audit_mock.assert_called_once()
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
assert kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert kwargs['before']['status'] == 'suggested'
|
||||
assert kwargs['after']['status'] == 'confirmed'
|
||||
assert kwargs['before']['normalized_bbox']['x0'] == 0.1
|
||||
assert kwargs['after']['normalized_bbox']['x0'] == 0.11
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_binding_permissions.py
|
||||
|
||||
用途:验收 XFA 视觉绑定 API 的管理员鉴权与租约门禁。
|
||||
依赖:Flask test client、JWT、XFA phase2 样本夹具。
|
||||
逻辑:非 admin 403;suggest 可读;confirm/reject 无租约 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import 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_visual_binding_service as vb_service
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io, _schema_with_required, _seed_xfa_sample
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers_factory(app):
|
||||
"""生成 admin Bearer JWT。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_headers_factory(app):
|
||||
"""生成普通用户 Bearer JWT。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
def _xfa_draft_profile(app, monkeypatch):
|
||||
"""创建含 binding 占位的最小 XFA 草稿 Profile。"""
|
||||
with app.app_context():
|
||||
admin = User(username='xfa-vb-admin', email='xfa-vb-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
schema = _schema_with_required()
|
||||
document, paths, _pdf = _seed_xfa_sample(user=admin)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA Visual Binding',
|
||||
'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': 'vb-tab',
|
||||
'operation_id': 'vb-wizard-op',
|
||||
}, actor_id=admin.id)
|
||||
profile_id = int(created['id'])
|
||||
binding = vb_service.ensure_binding_stub(
|
||||
profile_id,
|
||||
field_id='f-po',
|
||||
field_code='customer_po_no',
|
||||
scope='header',
|
||||
path_id=paths['EBELN'],
|
||||
data_path='/data/HEADER/EBELN',
|
||||
actor_id=admin.id,
|
||||
browser_session_id='vb-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
)
|
||||
return profile_id, document.id, binding['binding_id'], created['edit_lease']['lease_token']
|
||||
|
||||
|
||||
def test_visual_binding_suggest_requires_admin(app, monkeypatch, admin_headers_factory, user_headers_factory, _patch_xfa_io):
|
||||
"""非 admin 不得调用视觉建议 API。"""
|
||||
profile_id, document_id, _, _ = _xfa_draft_profile(app, monkeypatch)
|
||||
client = app.test_client()
|
||||
payload = {
|
||||
'document_id': document_id,
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
}
|
||||
forbidden = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/suggest',
|
||||
json=payload,
|
||||
headers=user_headers_factory('vb-user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
ok = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/suggest',
|
||||
json=payload,
|
||||
headers=admin_headers_factory('vb-admin2'),
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
data = parse_api_data(ok.get_json())
|
||||
assert data['diagnostics']['auto_confirm_blocked'] is True
|
||||
|
||||
|
||||
def test_visual_binding_confirm_requires_lease(app, monkeypatch, admin_headers_factory, _patch_xfa_io):
|
||||
"""确认视觉绑定必须持有有效租约。"""
|
||||
profile_id, _document_id, binding_id, _lease_token = _xfa_draft_profile(app, monkeypatch)
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/{binding_id}/confirm',
|
||||
json={
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
},
|
||||
headers=admin_headers_factory('vb-admin3'),
|
||||
)
|
||||
assert response.status_code == 409
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_publish_gate.py
|
||||
|
||||
用途:阶段 5 视觉绑定发布门禁——缺 bindings / 双源 / 未确认框阻断发布。
|
||||
依赖:publish_check_service 内部 _blocking_xfa_visual_bindings、xfa_contract。
|
||||
逻辑:纯单元构造 definition;断言 xfa_visual_bindings_required / dual source / incomplete。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_validation_metrics,
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _source_contract() -> dict:
|
||||
"""最小 XFA source_contract。"""
|
||||
return {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
}
|
||||
|
||||
|
||||
def _confirmed_binding(*, field_id: str, field_code: str, status: str = 'confirmed') -> dict:
|
||||
"""构造最小统一绑定。"""
|
||||
return {
|
||||
'binding_id': f'bind-{field_id}-aaaa-bbbb',
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': 'header' if field_id.startswith('f-h') else 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': f'path-{field_id}',
|
||||
'data_path': f'/data/HEADER/{field_code.upper()}' if field_id.startswith('f-h') else f'/data/ITEMS/DATA/{field_code.upper()}',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'manual_draw',
|
||||
'status': status,
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_missing_bindings_blocks_xfa_profile():
|
||||
"""关键断言:XFA 无 bindings → xfa_visual_bindings_required。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_bindings_required' for item in blocking)
|
||||
|
||||
|
||||
def test_dual_binding_source_blocks_publish():
|
||||
"""关键断言:bindings 与 legacy mappings 共存 → xfa_dual_binding_source。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-h-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
}],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_dual_binding_source' for item in blocking)
|
||||
|
||||
|
||||
def test_unconfirmed_visual_binding_blocks_publish():
|
||||
"""关键断言:正式字段视觉状态非 confirmed → xfa_visual_binding_incomplete。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_confirmed_bindings_pass_visual_gate():
|
||||
"""关键断言:全部正式字段 confirmed → 无视觉阻断。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
|
||||
|
||||
def test_validation_metrics_threshold_blocks_below_100_percent():
|
||||
"""关键断言:摘要指标 < 1.0 时发布门禁阻断。"""
|
||||
blocking = _blocking_xfa_validation_metrics({
|
||||
'visual_coverage_rate': 0.5,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
})
|
||||
assert any(item.get('key') == 'xfa_visual_coverage_insufficient' for item in blocking)
|
||||
Reference in new issue
Block a user