- 统一 XFA 数据集、字段拆分、校验及运行时解析 - 完善订单模板管理、发布检查与迁移状态 - 优化订单审核草稿、预约回退及 STP 投影缓存 - 更新前端模板编辑器、映射组件与多语言错误文案 - 补充后端与前端测试,并更新本地集成启动配置
1164 lines
63 KiB
Python
1164 lines
63 KiB
Python
"""
|
|
backend/tests/test_shipping_document_profile_quality.py
|
|
|
|
用途:验证订单文档模板的独立盲测候选、批准资格和冻结 checksum 门禁。
|
|
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
|
|
逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
|
|
XFA 确认真值允许候选含 bindings 以外的视觉表头(如 bill_to)。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, datetime
|
|
from decimal import Decimal
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from app import db
|
|
from app.models import (
|
|
FileAsset,
|
|
ShippingOrderDocument,
|
|
ShippingOrderIntake,
|
|
ShippingCustomer,
|
|
ShippingOrderDocumentProfile,
|
|
ShippingOrderDocumentProfileAudit,
|
|
ShippingDocumentProfileTestSuite,
|
|
ShippingOrderSchema,
|
|
ShippingOrderSchemaVersion,
|
|
User,
|
|
ShippingOrderDocumentProfileSample,
|
|
)
|
|
from app.services.shipping_notice import document_profile_quality_service as quality
|
|
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
|
from app.services.file_assets import storage as file_asset_storage_module
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _memory_file_asset_storage(monkeypatch):
|
|
"""测试外置坐标证据使用内存对象,保持 FileAsset/MinIO 契约而不依赖服务。"""
|
|
objects: dict[str, bytes] = {}
|
|
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'upload_bytes', lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data)))
|
|
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'get_bytes', lambda storage_key: objects[storage_key])
|
|
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
|
|
|
|
|
|
def test_expected_order_fields_allows_extra_visual_header_keys_for_xfa_bindings():
|
|
"""XFA 确认:bindings 表头齐全即可;候选额外含 bill_to 等视觉框不得拒绝。"""
|
|
binding = SimpleNamespace(
|
|
scope='header',
|
|
field_code='customer_po_number',
|
|
value_binding=SimpleNamespace(path_id='po-path'),
|
|
)
|
|
parser = SimpleNamespace(bindings=[binding], header_mappings=[], order_field_layouts=[])
|
|
raw = {
|
|
'header:customer_po_number': '4510039229',
|
|
'header:bill_to_customer': 'Cloud Network Technology Kft.',
|
|
'header:bill_to_address': 'Bánki Donát u. 1',
|
|
}
|
|
|
|
result = quality._expected_order_fields(raw, parser=parser)
|
|
|
|
# 关键断言:正式绑定键保留,额外视觉表头一并写入盲测真值。
|
|
assert result == raw
|
|
|
|
|
|
def test_expected_order_fields_still_requires_every_bound_header_for_xfa():
|
|
"""XFA 确认:缺少 bindings 表头仍须拒绝,避免静默漏掉正式 path 字段。"""
|
|
parser = SimpleNamespace(
|
|
bindings=[
|
|
SimpleNamespace(scope='header', field_code='customer_po_number'),
|
|
SimpleNamespace(scope='header', field_code='currency'),
|
|
],
|
|
header_mappings=[],
|
|
order_field_layouts=[],
|
|
)
|
|
|
|
with pytest.raises(Exception) as caught:
|
|
quality._expected_order_fields(
|
|
{'header:customer_po_number': '4510039229', 'header:bill_to_customer': 'X'},
|
|
parser=parser,
|
|
)
|
|
|
|
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
|
assert 'header:currency' in (getattr(caught.value, 'details', {}) or {}).get('missing_keys', [])
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
('actual', 'expected', 'config'),
|
|
[
|
|
('2026-06-09', date(2026, 6, 9), {'value_type': 'date'}),
|
|
('898.72000', Decimal('898.72000'), {'value_type': 'decimal'}),
|
|
(' Quanta Computer Inc. ', 'Quanta Computer Inc.', {'value_type': 'string', 'normalizer_key': 'trim'}),
|
|
],
|
|
)
|
|
def test_blind_test_order_field_comparison_normalizes_both_values(actual, expected, config):
|
|
"""关键断言:API 序列化后的字符串与冻结类型值按同一 Schema 比较,不产生伪 mismatch。"""
|
|
assert quality._order_field_values_match(actual=actual, expected=expected, config=config)
|
|
|
|
|
|
def test_blind_test_order_field_comparison_rejects_different_values():
|
|
"""关键断言:双向规范化只消除类型差异,真实日期差异仍必须失败。"""
|
|
assert not quality._order_field_values_match(
|
|
actual='2026-06-09', expected='2026-06-10', config={'value_type': 'date'},
|
|
)
|
|
|
|
|
|
def test_quality_region_uses_page_glyphs_for_every_reconstruction_mode():
|
|
"""盲测与预览/正式解析必须从当前页同一字符事实开始重建。"""
|
|
evidence = {
|
|
'tables': {'table-1': [{'text': 'TABLE'}]},
|
|
'page_glyphs': {'1': [{'text': 'PAGE'}]},
|
|
}
|
|
raw_table = {'page_no': 1}
|
|
assert quality._region_characters_for_quality(
|
|
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
|
|
evidence=evidence, raw_table=raw_table, table_id='table-1',
|
|
) == [{'text': 'PAGE'}]
|
|
assert quality._region_characters_for_quality(
|
|
region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'),
|
|
evidence=evidence, raw_table=raw_table, table_id='table-1',
|
|
) == [{'text': 'PAGE'}]
|
|
|
|
|
|
def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages():
|
|
"""关键断言:第二页只有合同正文时,不能重复重建第一页的订单明细。"""
|
|
evidence = {
|
|
'tables': {'table-1': [{'text': 'TABLE'}]},
|
|
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'TERMS'}]},
|
|
}
|
|
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
|
|
raw_table = {'table_id': 'table-1', 'page_no': 1}
|
|
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'PAGE-1'}]
|
|
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
|
|
|
|
|
|
def test_quality_region_falls_back_to_table_glyphs_without_page_evidence():
|
|
"""页级坐标未冻结时,盲测仍可使用同页表格字符完成历史样本回放。"""
|
|
evidence = {'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {}}
|
|
|
|
assert quality._region_characters_for_quality(
|
|
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
|
|
evidence=evidence, raw_table={'page_no': 1}, table_id='table-1',
|
|
) == [{'text': 'TABLE'}]
|
|
|
|
|
|
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
|
|
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
|
|
evidence = {
|
|
'tables': {'table-1': [{'text': 'PAGE-1'}]},
|
|
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'PAGE-2'}]},
|
|
}
|
|
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=True))
|
|
raw_table = {'table_id': 'table-1', 'page_no': 1}
|
|
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) == [{'text': 'PAGE-2'}]
|
|
|
|
|
|
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]:
|
|
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
|
|
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
|
|
# 产品模型只允许唯一的 SHIPPING_ORDER Schema,测试仅创建其隔离版本。
|
|
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Quality order')
|
|
db.session.add_all([user, schema])
|
|
db.session.flush()
|
|
version = ShippingOrderSchemaVersion(
|
|
schema_id=schema.id, version=1, status='published', checksum='a' * 64,
|
|
published_at=datetime.utcnow(), definition_json={'fields': [
|
|
{
|
|
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
|
'value_type': 'string', 'enabled': True, 'required': True,
|
|
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
|
},
|
|
{
|
|
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
|
'value_type': 'string', 'enabled': True, 'required': True,
|
|
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
|
},
|
|
{
|
|
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
|
'value_type': 'decimal', 'enabled': True, 'required': True,
|
|
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], 'allowed_sources': ['pdf_coordinate'],
|
|
},
|
|
]},
|
|
)
|
|
db.session.add(version)
|
|
db.session.flush()
|
|
html = '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr></table>'
|
|
definition = {
|
|
'document_match': {
|
|
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
|
|
'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0,
|
|
},
|
|
'table_regions': [{
|
|
'region_id': 'lines', 'page_scope': 'first_page',
|
|
'line_start_field_code': 'qty',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
|
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
|
'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
|
'new_line_anchor': None,
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': .6, 'y1': 1},
|
|
'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
|
'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'],
|
|
'allowed_empty_fields': [],
|
|
}],
|
|
}],
|
|
'order_field_layouts': [], 'draft_unbound_order_field_layouts': [],
|
|
}
|
|
profile = ShippingOrderDocumentProfile(
|
|
profile_code='QUALITY_TEMPLATE', display_name='Quality template', version=1, status='published',
|
|
schema_version_id=version.id, structure_fingerprint='a' * 64, checksum='b' * 64,
|
|
published_at=datetime.utcnow(), definition_json=definition,
|
|
)
|
|
db.session.add(profile)
|
|
db.session.flush()
|
|
documents = []
|
|
for index in range(3):
|
|
asset = FileAsset(
|
|
asset_no=f'FA-QUALITY-{index}', owner_user_id=user.id, original_filename=f'q{index}.pdf',
|
|
storage_provider='test', storage_bucket='test', storage_key=f'q{index}.pdf',
|
|
content_hash=f'{index:x}' * 64, file_size=1, mime_type='application/pdf',
|
|
upload_status='ready', lifecycle_status='temporary',
|
|
)
|
|
db.session.add(asset)
|
|
db.session.flush()
|
|
intake = ShippingOrderIntake(
|
|
intake_no=f'SNI-QUALITY-{index}', asset_id=asset.id, user_id=user.id,
|
|
purpose='shipping_notice', 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=asset.storage_key,
|
|
filename=asset.original_filename, content_hash=asset.content_hash, classification='order_notice',
|
|
parse_status='parsed', extracted_text='PN-1 3',
|
|
)
|
|
db.session.add(document)
|
|
db.session.flush()
|
|
glyphs = []
|
|
for text, x0 in [('PN-1', 30), ('3', 150)]:
|
|
for char_index, char in enumerate(text):
|
|
glyphs.append({'text': char, 'bbox': {
|
|
'x0': x0 + char_index * 5, 'y0': 20, 'x1': x0 + char_index * 5 + 4, 'y1': 30,
|
|
}})
|
|
record_inline_layout_snapshot(document, {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru',
|
|
'backend': 'test', 'status': 'ready', 'issues': [],
|
|
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html,
|
|
'bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}}],
|
|
'coordinate_evidence': {
|
|
'tables': {'table-1': glyphs},
|
|
'pages': {'1': {'width': 200, 'height': 60}},
|
|
'page_glyphs': {'1': glyphs},
|
|
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
|
},
|
|
})
|
|
documents.append(document)
|
|
db.session.commit()
|
|
return profile, user, documents
|
|
|
|
|
|
def _independent_approver() -> User:
|
|
"""创建与盲测编辑者不同的审批人,验证双人复核门禁。"""
|
|
suffix = User.query.count() + 1
|
|
approver = User(
|
|
username=f'profile-quality-approver-{suffix}',
|
|
email=f'profile-quality-approver-{suffix}@example.com',
|
|
role='admin',
|
|
)
|
|
db.session.add(approver)
|
|
db.session.flush()
|
|
return approver
|
|
|
|
|
|
def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
|
"""将质量夹具改为最小 v2 草稿,使发布测试只覆盖阶段 4 边界。"""
|
|
from app.services.shipping_notice import order_document_profile_service as profiles
|
|
|
|
profile.status = 'draft'
|
|
profile.checksum = None
|
|
profile.published_at = None
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': 'FACTORY A'}]},
|
|
'table_regions': [{
|
|
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
|
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
|
'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
|
|
}],
|
|
}],
|
|
}
|
|
profile.definition_json = profiles._normalize_definition(
|
|
profile.definition_json,
|
|
schema_version=profile.schema_version,
|
|
)
|
|
profile.structure_fingerprint = profiles._definition_hash(profile.definition_json)
|
|
|
|
|
|
def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(app):
|
|
"""关键断言:盲测批准应升级当前模板版本资格,避免审批结果无法生效。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
|
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
assert executed['latest_run']['status'] == 'failed'
|
|
with pytest.raises(Exception) as caught:
|
|
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
|
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
|
|
|
|
quality.add_sample(
|
|
suite_id=suite['id'], document_id=documents[0].id, table_id='table-1',
|
|
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
|
)
|
|
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
assert executed['latest_run']['status'] == 'passed', executed['latest_run']
|
|
# 业务规则:具备管理员权限即可批准,不再要求必须由其他管理员批准。
|
|
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
|
assert approved['status'] == 'approved'
|
|
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
|
qualification = quality.qualification_summary(profile)
|
|
assert qualification['status'] == 'auto_freeze_approved'
|
|
assert qualification['quality_suite_id'] == suite['id']
|
|
# 盲测只批准解析质量,未配置范围时仍要求人工确认。
|
|
assert qualification['requires_customer_confirmation'] is True
|
|
with pytest.raises(Exception) as immutable:
|
|
quality.add_sample(
|
|
suite_id=suite['id'], document_id=documents[0].id, table_id='other',
|
|
expected_rows=[{'part_number': 'PN-1'}], actor_id=user.id,
|
|
)
|
|
assert getattr(immutable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
|
|
|
|
|
|
def test_independent_sample_review_reuses_existing_truth_and_excludes_training_input(app):
|
|
"""关键断言:只展示同类未建模样本,逐项确认后才将候选写为既有盲测真值。"""
|
|
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()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
assert {item['document_id'] for item in available} == {documents[1].id, documents[2].id}
|
|
# 候选下拉必须能区分同页多表,且不回传 HTML、坐标或内部布局内容。
|
|
assert available[0]['table_index'] == 1
|
|
assert available[0]['row_count'] > 0 and available[0]['column_count'] > 0
|
|
assert available[0]['header_preview']
|
|
assert 'html' not in available[0] and 'bbox' not in available[0]
|
|
candidate = quality.preview_independent_sample(
|
|
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', actor_id=user.id,
|
|
)
|
|
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}]
|
|
with pytest.raises(Exception) as incomplete:
|
|
quality.confirm_sample_reviews(
|
|
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1',
|
|
row_reviews=[{'correct': None, 'values': candidate['rows'][0]}],
|
|
order_field_reviews={}, layout_version_id=candidate['layout_version_id'],
|
|
layout_payload_checksum=candidate['layout_payload_checksum'], actor_id=user.id,
|
|
)
|
|
assert getattr(incomplete.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
|
|
|
confirmed = quality.confirm_sample_reviews(
|
|
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1',
|
|
row_reviews=[{'correct': True, 'values': {}}], order_field_reviews={},
|
|
layout_version_id=candidate['layout_version_id'],
|
|
layout_payload_checksum=candidate['layout_payload_checksum'], actor_id=user.id,
|
|
)
|
|
assert confirmed['sample_count'] == 1
|
|
sample = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0]
|
|
assert sample.expected_rows_json == candidate['rows']
|
|
assert sample.layout_version_id == candidate['layout_version_id']
|
|
assert sample.layout_payload_checksum == candidate['layout_payload_checksum']
|
|
|
|
# 当前指针变化不得改变已确认样本的回放输入;盲测必须继续读取冻结版本。
|
|
current_version = documents[1].current_layout_version
|
|
replacement = dict(current_version.payload_json or {})
|
|
replacement['tables'] = []
|
|
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
|
record_inline_layout_snapshot(documents[1], replacement, parser_key='changed-parser-key')
|
|
db.session.commit()
|
|
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
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.pop('coordinate_evidence_ref', None)
|
|
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['layout_issue_codes'] == ['coordinate_evidence_missing']
|
|
|
|
|
|
def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
|
|
"""关键断言:失败 Layout 可从原 PDF 诊断,但不能确认成盲测真值。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
document = documents[1]
|
|
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
|
current_version = document.current_layout_version
|
|
current_version.status = 'failed'
|
|
current_version.payload_json = {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
|
'status': 'failed', 'tables': [],
|
|
'issues': ['mineru_cell_coordinates_missing'],
|
|
}
|
|
current_version.issues_json = ['mineru_cell_coordinates_missing']
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
candidate_option = next(item for item in available if item['document_id'] == document.id)
|
|
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
|
|
assert candidate_option['review_mode'] == 'diagnostic'
|
|
assert candidate_option['confirmable'] is False
|
|
assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing']
|
|
|
|
with pytest.raises(Exception) as diagnostic_preview:
|
|
quality.preview_independent_sample(
|
|
suite_id=suite['id'], document_id=document.id,
|
|
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
|
|
)
|
|
assert getattr(diagnostic_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
|
candidate = {'rows': []}
|
|
with pytest.raises(Exception) as bypassed_review:
|
|
quality.add_sample(
|
|
suite_id=suite['id'], document_id=document.id,
|
|
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID,
|
|
expected_rows=candidate['rows'], actor_id=user.id,
|
|
)
|
|
assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
|
assert diagnostic_preview.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
|
with pytest.raises(Exception) as diagnostic_confirmation:
|
|
quality.confirm_sample_reviews(
|
|
suite_id=suite['id'], document_id=document.id,
|
|
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID,
|
|
row_reviews=[{'correct': True}], order_field_reviews={},
|
|
layout_version_id=current_version.id,
|
|
layout_payload_checksum=current_version.payload_checksum, actor_id=user.id,
|
|
)
|
|
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
|
|
|
|
|
def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
|
|
"""关键断言:后台 Layout 尚在运行时只显示准备状态,不启动临时 PDF 复核。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
document = documents[1]
|
|
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
|
current_version = document.current_layout_version
|
|
current_version.status = 'running'
|
|
current_version.payload_json = None
|
|
current_version.issues_json = []
|
|
document.current_layout_version_id = None
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
candidate_option = next(item for item in available if item['document_id'] == document.id)
|
|
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
|
|
assert candidate_option['review_mode'] == 'preparing'
|
|
assert candidate_option['confirmable'] is False
|
|
|
|
with pytest.raises(Exception) as preparing_preview:
|
|
quality.preview_independent_sample(
|
|
suite_id=suite['id'], document_id=document.id,
|
|
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
|
|
)
|
|
assert getattr(preparing_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
|
|
|
|
|
|
def test_document_candidate_identity_expires_after_background_layout_completion(app, monkeypatch):
|
|
"""关键断言:后台产生真实 table_id 后,旧文档候选必须刷新并重新正式预览。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
document = documents[1]
|
|
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
|
|
# 当前列表已经转成真实表格候选,模拟页面仍持有上传完成时的文档级身份。
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
assert any(item['document_id'] == document.id and item['table_id'] == 'table-1' for item in available)
|
|
assert not any(
|
|
item['document_id'] == document.id and item['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
|
|
for item in available
|
|
)
|
|
|
|
with pytest.raises(Exception) as stale_preview:
|
|
quality.preview_independent_sample(
|
|
suite_id=suite['id'], document_id=document.id,
|
|
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
|
|
)
|
|
assert getattr(stale_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
|
|
|
|
|
|
def test_independent_samples_include_historical_blind_documents(app):
|
|
"""关键断言:新版本可复用同一模板族的历史盲测文档,但必须重新确认本版本真值。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
historical_suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
quality.add_sample(
|
|
suite_id=historical_suite['id'], document_id=documents[0].id, table_id='table-1',
|
|
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
|
)
|
|
draft = ShippingOrderDocumentProfile(
|
|
profile_code=profile.profile_code, display_name=profile.display_name, version=2, status='draft',
|
|
schema_version_id=profile.schema_version_id, structure_fingerprint=profile.structure_fingerprint,
|
|
definition_json=profile.definition_json, source_profile_id=profile.id,
|
|
)
|
|
db.session.add(draft)
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=draft.id, actor_id=user.id)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
|
|
assert {(item['document_id'], item['table_id']) for item in available} == {(documents[0].id, 'table-1')}
|
|
|
|
|
|
def test_independent_samples_include_all_historical_profile_sample_roles(app):
|
|
"""关键断言:历史 annotation/training/旧 blind_test 绑定均可作为新版本待复核来源。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
roles = ('annotation', 'training', 'blind_test')
|
|
for document, role in zip(documents, roles, strict=True):
|
|
db.session.add(ShippingOrderDocumentProfileSample(
|
|
profile_id=profile.id, document_id=document.id, table_id='table-1',
|
|
sample_role=role, created_by_id=user.id,
|
|
))
|
|
draft = ShippingOrderDocumentProfile(
|
|
profile_code=profile.profile_code, display_name=profile.display_name, version=2, status='draft',
|
|
schema_version_id=profile.schema_version_id, structure_fingerprint=profile.structure_fingerprint,
|
|
definition_json=profile.definition_json, source_profile_id=profile.id,
|
|
)
|
|
db.session.add(draft)
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=draft.id, actor_id=user.id)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
|
|
# 三种历史角色只提供来源;加入当前套件前仍需走候选预览和人工确认。
|
|
assert {item['document_id'] for item in available} == {item.id for item in documents}
|
|
|
|
|
|
def test_independent_samples_deduplicate_reuploaded_content(app):
|
|
"""关键断言:相同文件内容重复上传不会用相同表格摘要占满独立样本选择器。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
for document in documents[:2]:
|
|
db.session.get(ShippingOrderIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
|
documents[1].content_hash = documents[0].content_hash
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
|
|
# 两个相同内容、相同页表结构的 Document 仅保留较新的候选。
|
|
matching = [item for item in available if item['document_id'] in {documents[0].id, documents[1].id}]
|
|
assert len(matching) == 1
|
|
|
|
|
|
def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app):
|
|
"""v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': []},
|
|
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', 'region': {'x0': 0, 'y0': 0, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': .15, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
}]}],
|
|
}
|
|
for document in documents:
|
|
glyphs = []
|
|
for text, x0 in [('00010', 5), ('PN-1', 30), ('3', 150)]:
|
|
for index, char in enumerate(text):
|
|
glyphs.append({'text': char, 'bbox': {'x0': x0 + index * 4, 'y0': 20, 'x1': x0 + index * 4 + 3, 'y1': 30}})
|
|
record_inline_layout_snapshot(document, {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
|
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
|
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
|
})
|
|
db.session.flush()
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
for document in documents:
|
|
quality.add_sample(suite_id=suite['id'], document_id=document.id, table_id='table-1',
|
|
expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
|
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
|
|
|
|
|
def test_coordinate_blind_candidate_list_does_not_prepare_missing_evidence(app, monkeypatch):
|
|
"""关键断言:打开盲测候选列表只能读取现有摘要,不能为历史文档触发 OCR 证据补齐。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': []},
|
|
'table_regions': [], 'order_field_layouts': [],
|
|
}
|
|
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()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
monkeypatch.setattr(
|
|
quality, '_ensure_order_field_evidence',
|
|
lambda **_kwargs: pytest.fail('candidate listing must not prepare coordinate evidence'),
|
|
)
|
|
|
|
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
|
|
|
assert {item['document_id'] for item in available} == {documents[1].id, documents[2].id}
|
|
|
|
|
|
def test_coordinate_blind_preview_skips_header_only_regions(app):
|
|
"""关键断言:仅含订单字段的页不重建物理行,候选预览不会因空布局报 500。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': []},
|
|
'table_regions': [
|
|
{'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
|
'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
|
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
}]},
|
|
{'region_id': 'header_only', 'page_scope': 'exact_page', 'page_no': 2,
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}, 'field_regions': []}],
|
|
'line_layouts': []},
|
|
],
|
|
}
|
|
for document in documents:
|
|
glyphs = [
|
|
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 20, 'x1': 23 + index * 4, 'y1': 30}}
|
|
for index, char in enumerate('PN-1')
|
|
]
|
|
record_inline_layout_snapshot(document, {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
|
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
|
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
|
})
|
|
db.session.commit()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
candidate = quality._candidate_for_sample(profile=profile, document_id=documents[0].id, table_id='table-1')
|
|
assert suite['id'] > 0
|
|
assert candidate['rows'] == []
|
|
|
|
|
|
def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
|
|
"""盲测候选必须和编辑器预览一样排除表头视觉区域。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': []},
|
|
'table_regions': [{
|
|
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'header_layouts': [{
|
|
'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25},
|
|
'field_regions': [],
|
|
}],
|
|
'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
|
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
|
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
}],
|
|
}], 'order_field_layouts': [],
|
|
}
|
|
glyphs = [
|
|
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 10, 'x1': 23 + index * 4, 'y1': 20}}
|
|
for index, char in enumerate('Item')
|
|
] + [
|
|
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
|
|
for index, char in enumerate('20')
|
|
] + [
|
|
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
|
|
for index, char in enumerate('PART-A')
|
|
]
|
|
record_inline_layout_snapshot(documents[1], {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
|
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
|
'coordinate_evidence': {
|
|
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
|
|
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
|
|
},
|
|
})
|
|
db.session.commit()
|
|
candidate = quality._candidate_for_sample(
|
|
profile=profile, document_id=documents[1].id, table_id='table-1',
|
|
)
|
|
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
|
|
|
|
|
def test_coordinate_blind_candidate_keeps_rows_when_strategy_needs_review(app, monkeypatch):
|
|
"""关键断言:策略需复核时盲测预览仍展示最佳努力明细,不能整表吞掉。"""
|
|
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
|
|
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': []},
|
|
'table_regions': [{
|
|
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
|
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
|
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
}],
|
|
}], 'order_field_layouts': [],
|
|
}
|
|
glyphs = [
|
|
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
|
|
for index, char in enumerate('20')
|
|
] + [
|
|
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
|
|
for index, char in enumerate('PART-A')
|
|
]
|
|
record_inline_layout_snapshot(documents[1], {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
|
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
|
'coordinate_evidence': {
|
|
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
|
|
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
|
|
},
|
|
})
|
|
db.session.commit()
|
|
|
|
def _force_review(**_kwargs):
|
|
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
|
|
|
|
monkeypatch.setattr(
|
|
'app.services.shipping_notice.document_layout.runtime_parse_strategy.resolve_runtime_parse_strategy',
|
|
_force_review,
|
|
)
|
|
candidate = quality._candidate_for_sample(
|
|
profile=profile, document_id=documents[1].id, table_id='table-1',
|
|
)
|
|
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
|
|
|
|
|
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
|
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
for document in documents:
|
|
quality.add_sample(
|
|
suite_id=suite['id'], document_id=document.id, table_id='table-1',
|
|
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
|
)
|
|
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
|
profile.checksum = 'c' * 64
|
|
db.session.commit()
|
|
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
|
|
|
|
|
def test_profile_auto_freeze_qualification_can_be_suspended_independently(app, monkeypatch):
|
|
"""关键断言:暂停资格不退役模板,且只影响当前版本。"""
|
|
from app.services.shipping_notice import order_document_profile_service as profiles
|
|
|
|
with app.app_context():
|
|
monkeypatch.setattr(
|
|
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
|
)
|
|
profile, user, _documents = _published_profile_with_samples()
|
|
_publishable_v2_draft(profile)
|
|
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()
|
|
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
|
qualification = quality.suspend_auto_freeze_qualification(
|
|
profile_id=profile.id, actor_id=user.id, reason='manual_review',
|
|
)
|
|
assert qualification.status == 'auto_freeze_suspended'
|
|
assert db.session.get(ShippingOrderDocumentProfile, profile.id).status == 'published'
|
|
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
|
|
|
|
|
def test_profile_auto_freeze_scope_can_be_configured_independently(app, monkeypatch):
|
|
"""关键断言:客户/业务场景授权范围可独立配置,并写入模板审计摘要。"""
|
|
from app.services.shipping_notice import order_document_profile_service as profiles
|
|
|
|
with app.app_context():
|
|
monkeypatch.setattr(
|
|
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
|
)
|
|
profile, user, _documents = _published_profile_with_samples()
|
|
_publishable_v2_draft(profile)
|
|
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()
|
|
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
|
customer = ShippingCustomer(standard_name='Scope Customer', short_code='SCOP')
|
|
db.session.add(customer)
|
|
db.session.commit()
|
|
|
|
qualification = quality.configure_auto_freeze_qualification_scope(
|
|
profile_id=profile.id,
|
|
actor_id=user.id,
|
|
customer_ids=[customer.id],
|
|
business_scenarios=['shipping_notice_order'],
|
|
requires_customer_confirmation=False,
|
|
)
|
|
|
|
assert qualification.customer_ids_json == [customer.id]
|
|
assert qualification.business_scenarios_json == ['shipping_notice_order']
|
|
assert qualification.requires_customer_confirmation is False
|
|
refreshed = profiles.payload(db.session.get(ShippingOrderDocumentProfile, profile.id))
|
|
assert refreshed['auto_freeze_qualification']['customer_scope_configured'] is True
|
|
assert refreshed['auto_freeze_qualification']['business_scenario_scope_configured'] is True
|
|
assert refreshed['auto_freeze_qualification']['requires_customer_confirmation'] is False
|
|
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
|
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
|
|
ShippingOrderDocumentProfileAudit.id.desc(),
|
|
).first()
|
|
assert audit.event_type == 'auto_freeze_scope_configured'
|
|
|
|
|
|
def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app):
|
|
"""保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。"""
|
|
with app.app_context():
|
|
profile, user, _documents = _published_profile_with_samples()
|
|
stale = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
profile.checksum = 'd' * 64
|
|
db.session.commit()
|
|
|
|
current = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
assert current['id'] != stale['id']
|
|
assert current['profile_checksum'] == 'd' * 64
|
|
stale_suite = db.session.get(ShippingDocumentProfileTestSuite, stale['id'])
|
|
assert stale_suite.status == 'superseded'
|
|
|
|
|
|
def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(app):
|
|
"""盲测草稿可受控删除样本并留痕,批准后的真值不得再被篡改。"""
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
quality.add_sample(
|
|
suite_id=suite['id'], document_id=documents[0].id, table_id='table-1',
|
|
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
|
)
|
|
sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
|
|
serialized = quality.serialize_suite(db.session.get(ShippingDocumentProfileTestSuite, suite['id']))
|
|
# 关键断言:工作台只得到移除定位信息,绝不返回人工确认的字段真值。
|
|
assert serialized['samples'] == [{
|
|
'id': sample_id, 'document_id': documents[0].id, 'table_id': 'table-1',
|
|
'filename': 'q0.pdf', 'page_no': 1,
|
|
}]
|
|
removed = quality.remove_sample(suite_id=suite['id'], sample_id=sample_id, actor_id=user.id)
|
|
assert removed['sample_count'] == 0
|
|
assert removed['samples'] == []
|
|
audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by(
|
|
ShippingOrderDocumentProfileAudit.id.desc(),
|
|
).first()
|
|
assert audit.event_type == 'blind_test_sample_removed'
|
|
assert audit.detail_json == {'suite_id': suite['id']}
|
|
|
|
for document in documents:
|
|
quality.add_sample(
|
|
suite_id=suite['id'], document_id=document.id, table_id='table-1',
|
|
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
|
)
|
|
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
|
immutable_sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
|
|
with pytest.raises(Exception) as caught:
|
|
quality.remove_sample(suite_id=suite['id'], sample_id=immutable_sample_id, actor_id=user.id)
|
|
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
|
|
|
|
|
|
def test_draft_publish_requires_current_approved_blind_test(app):
|
|
"""关键断言:阶段 7 起,缺少当前 approved blind test 的草稿不得发布。"""
|
|
from app.services.shipping_notice import order_document_profile_service as profiles
|
|
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
_publishable_v2_draft(profile)
|
|
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()
|
|
|
|
with pytest.raises(Exception) as caught:
|
|
profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
|
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
|
|
|
|
|
def test_draft_publish_does_not_force_static_document_anchor(app):
|
|
"""关键断言:是否配置必需锚点由用户决定,发布门禁不再强制添加。"""
|
|
from app.services.shipping_notice import document_profile_quality_service as quality
|
|
|
|
with app.app_context():
|
|
profile, _user, _documents = _published_profile_with_samples()
|
|
profile.status = 'draft'
|
|
profile.definition_json = {'document_match': {'required_anchors': []}}
|
|
|
|
with pytest.raises(Exception) as caught:
|
|
quality.assert_profile_publishable(profile)
|
|
|
|
assert getattr(caught.value, 'code', None) != 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR'
|
|
|
|
|
|
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
|
"""关键断言:v2 草稿在训练、独立多明细盲测通过后可发布,并冻结正式 checksum 凭证。"""
|
|
from app.services.shipping_notice import order_document_profile_service as profiles
|
|
|
|
with app.app_context():
|
|
profile, user, documents = _published_profile_with_samples()
|
|
profile.status = 'draft'
|
|
profile.checksum = None
|
|
profile.published_at = None
|
|
profile.definition_json = {
|
|
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT TYPE:', 'value': 'PURCHASE ORDER', 'value_position': 'right'}]},
|
|
'table_regions': [{
|
|
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
|
'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .15}, 'field_regions': []}], 'termination_rules': [], 'exclusion_regions': [],
|
|
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
|
'line_layouts': [{
|
|
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
|
'region': {'x0': 0, 'y0': .16, 'x1': 1, 'y1': 1},
|
|
'field_regions': [
|
|
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', 'region': {'x0': 0, 'y0': .16, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': .15, 'y0': .16, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
|
],
|
|
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
|
|
}],
|
|
}],
|
|
}
|
|
profile.definition_json = profiles._normalize_definition(
|
|
profile.definition_json,
|
|
schema_version=profile.schema_version,
|
|
)
|
|
profile.structure_fingerprint = profiles._definition_hash(profile.definition_json)
|
|
|
|
def set_coordinate_rows(document: ShippingOrderDocument, rows: list[tuple[str, str]]) -> None:
|
|
"""冻结每个样本的字符坐标,让 v2 盲测不依赖 HTML 网格。"""
|
|
glyphs = []
|
|
for row_index, (part, qty) in enumerate(rows):
|
|
for text, x0 in ((f'{(row_index + 1) * 10:05d}', 5), (part, 30), (qty, 150)):
|
|
for index, char in enumerate(text):
|
|
glyphs.append({'text': char, 'bbox': {
|
|
'x0': x0 + index * 4, 'y0': 20 + row_index * 20,
|
|
'x1': x0 + index * 4 + 3, 'y1': 30 + row_index * 20,
|
|
}})
|
|
record_inline_layout_snapshot(document, {
|
|
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
|
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
|
# 发布冻结要求 page_glyphs + sources,避免测试误走 MinIO 按需补证据。
|
|
'coordinate_evidence': {
|
|
'tables': {'table-1': glyphs},
|
|
'pages': {'1': {'width': 200, 'height': 100}},
|
|
'page_glyphs': {'1': glyphs},
|
|
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
|
},
|
|
})
|
|
|
|
for document in documents:
|
|
set_coordinate_rows(document, [('PN-1', '3')])
|
|
extra = ShippingOrderDocument(
|
|
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
|
|
attachment_key='quality-v2-extra.pdf', filename='quality-v2-extra.pdf', content_hash='f' * 64,
|
|
classification='order_notice', parse_status='parsed', extracted_text='PN-3 5',
|
|
)
|
|
db.session.add(extra)
|
|
db.session.flush()
|
|
set_coordinate_rows(extra, [('PN-3', '5')])
|
|
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()
|
|
|
|
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
|
# Training document is rejected immediately, not only later at publication time.
|
|
with pytest.raises(Exception) as reused:
|
|
quality.add_sample(suite_id=suite['id'], document_id=documents[0].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
|
assert getattr(reused.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
|
|
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
|
{'customer_po_line_no': '00010', 'part_number': 'PN-1', 'qty': '3'},
|
|
], actor_id=user.id)
|
|
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
|
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
|
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
|
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
|
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
|
|
|
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
|
assert published['status'] == 'published'
|
|
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
|
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=published['checksum'])
|
|
frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id'])
|
|
assert frozen_suite.profile_checksum == published['checksum']
|
|
assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs)
|
|
|
|
|
|
def test_republish_identical_content_reuses_historical_promoted_suite(app):
|
|
"""关键断言:同内容重复发布时复用历史发布凭证,新草稿集转为 superseded 而非撞唯一键。
|
|
|
|
复现路径:发布成功后人工把模板状态重置为 draft(checksum 与历史提升套件保留),
|
|
重新走盲测并发布;发布 checksum 由规范化负载确定性复现,必须复用历史凭证。
|
|
"""
|
|
from app.models import ShippingDocumentProfileTestRun
|
|
from app.services.shipping_notice import document_profile_quality_service as quality
|
|
|
|
with app.app_context():
|
|
profile, user, _documents = _published_profile_with_samples()
|
|
draft_checksum = str(profile.structure_fingerprint)
|
|
published_checksum = str(profile.checksum)
|
|
occupant = ShippingDocumentProfileTestSuite(
|
|
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
|
|
)
|
|
new_suite = ShippingDocumentProfileTestSuite(
|
|
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
|
|
)
|
|
db.session.add_all([occupant, new_suite])
|
|
db.session.flush()
|
|
db.session.add_all([
|
|
ShippingDocumentProfileTestRun(
|
|
suite_id=occupant.id, profile_checksum=published_checksum, status='passed',
|
|
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
|
|
),
|
|
ShippingDocumentProfileTestRun(
|
|
suite_id=new_suite.id, profile_checksum=draft_checksum, status='passed',
|
|
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
|
|
),
|
|
])
|
|
db.session.flush()
|
|
|
|
quality.promote_approved_suite_for_publish(
|
|
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
|
|
)
|
|
db.session.flush()
|
|
|
|
# 历史凭证保持原样,仍是发布 checksum 的唯一持有者。
|
|
assert occupant.status == 'approved'
|
|
assert occupant.profile_checksum == published_checksum
|
|
assert all(run.profile_checksum == published_checksum for run in occupant.runs)
|
|
# 新草稿集降级为 superseded,保留自身运行历史供审计,不重写 checksum。
|
|
assert new_suite.status == 'superseded'
|
|
assert new_suite.profile_checksum == draft_checksum
|
|
assert all(run.profile_checksum == draft_checksum for run in new_suite.runs)
|
|
reuse_audits = ShippingOrderDocumentProfileAudit.query.filter_by(
|
|
profile_id=profile.id, event_type='blind_test_suite_superseded',
|
|
).all()
|
|
assert any(
|
|
(audit.detail_json or {}).get('reason_code') == 'republish_identical_content'
|
|
and (audit.detail_json or {}).get('reused_suite_id') == occupant.id
|
|
for audit in reuse_audits
|
|
)
|
|
|
|
|
|
def test_promote_rejects_invalid_published_checksum_occupant(app):
|
|
"""关键断言:占用发布 checksum 的套件不是有效凭证时拒绝发布,禁止静默覆盖历史证据。"""
|
|
from app.core.errors import ConflictError
|
|
from app.models import ShippingDocumentProfileTestRun
|
|
from app.services.shipping_notice import document_profile_quality_service as quality
|
|
|
|
with app.app_context():
|
|
profile, user, _documents = _published_profile_with_samples()
|
|
draft_checksum = str(profile.structure_fingerprint)
|
|
published_checksum = str(profile.checksum)
|
|
invalid_occupant = ShippingDocumentProfileTestSuite(
|
|
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
|
|
)
|
|
new_suite = ShippingDocumentProfileTestSuite(
|
|
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
|
|
)
|
|
db.session.add_all([invalid_occupant, new_suite])
|
|
db.session.flush()
|
|
db.session.add(ShippingDocumentProfileTestRun(
|
|
suite_id=invalid_occupant.id, profile_checksum=published_checksum, status='failed',
|
|
sample_count=1, passed_sample_count=0, executed_by_id=user.id,
|
|
))
|
|
db.session.flush()
|
|
|
|
with pytest.raises(ConflictError) as caught:
|
|
quality.promote_approved_suite_for_publish(
|
|
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
|
|
)
|
|
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT'
|
|
# 冲突时两个套件都不得被改动,保持发布事务可整体回滚。
|
|
assert invalid_occupant.profile_checksum == published_checksum
|
|
assert new_suite.status == 'approved'
|
|
assert new_suite.profile_checksum == draft_checksum
|