feat(shipping-order): 迭代货代订单提取与履约全流程功能
添加订单字段自动标注配置,默认仅关键字段参与自动框选 完善字段规范化逻辑,支持更多日期格式解析 添加订单候选人工采纳、驳回的完整流程,包含API、前端交互与状态管理 完善盲测功能,支持订单级字段真值校验,调整盲测集唯一性约束 加固库存校验逻辑,防止重复预约与数量不一致问题 优化坐标匹配逻辑,支持表格外的锚点定位 新增上传结果未知的状态处理,完善任务状态机 更新多语言文案与文档说明,补充功能细节 修复订单合并、重解析的边缘情况问题 补充相关测试用例,完善质量保障
This commit is contained in:
1 parent
11079910ec
commit
90f77634d6
76 files changed
+5056
-338
No files matched your search
@@ -3,7 +3,7 @@ backend/tests/test_shipping_document_profile_quality.py
|
||||
|
||||
用途:验证订单文档模板的独立盲测、批准资格和冻结 checksum 门禁。
|
||||
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
|
||||
逻辑:管理员固化三份独立样本真值;全部通过且批准后才可放行确定性自动建单。
|
||||
逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -111,17 +111,12 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
return profile, user, documents
|
||||
|
||||
|
||||
def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(app):
|
||||
"""关键断言:三样本全通过和管理员批准缺一不可,批准后样本不可篡改。"""
|
||||
def test_profile_auto_create_requires_one_passing_blind_sample_and_approval(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)
|
||||
for document in documents[:2]:
|
||||
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,
|
||||
)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'failed'
|
||||
with pytest.raises(Exception) as caught:
|
||||
@@ -129,10 +124,11 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
|
||||
|
||||
quality.add_sample(
|
||||
suite_id=suite['id'], document_id=documents[2].id, table_id='table-1',
|
||||
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,
|
||||
)
|
||||
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed'
|
||||
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)
|
||||
@@ -144,6 +140,43 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a
|
||||
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(ShippingNoticeIntake, 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}
|
||||
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={}, 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={}, 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']
|
||||
|
||||
|
||||
def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app):
|
||||
"""v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。"""
|
||||
with app.app_context():
|
||||
@@ -178,6 +211,44 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
|
||||
|
||||
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 = {
|
||||
'contract_version': 'order_coordinate_profile.v2', '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': 'part-id', 'field_code': 'part_number',
|
||||
'region': {'x0': 0, '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}}},
|
||||
})
|
||||
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_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
|
||||
with app.app_context():
|
||||
@@ -195,6 +266,21 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
|
||||
|
||||
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():
|
||||
@@ -205,8 +291,15 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
|
||||
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()
|
||||
@@ -244,7 +337,7 @@ def test_draft_publish_requires_independent_training_and_multiline_blind_gate(ap
|
||||
assert getattr(missing_suite.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
||||
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
# Use different documents than the training sample. One sample is real multi-line evidence.
|
||||
# One independent sample is enough, but it must still be genuine multi-line evidence.
|
||||
record_inline_layout_snapshot(documents[1], {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr><tr><td>PN-2</td><td>4</td></tr></table>'}],
|
||||
@@ -252,28 +345,9 @@ def test_draft_publish_requires_independent_training_and_multiline_blind_gate(ap
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
||||
{'part_number': 'PN-1', 'qty': 3}, {'part_number': 'PN-2', 'qty': 4},
|
||||
], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id)
|
||||
assert quality.execute_suite(suite_id=suite['id'], actor_id=user.id)['latest_run']['status'] == 'failed'
|
||||
|
||||
# A third independent document is necessary even when one sample is multi-line.
|
||||
extra = ShippingNoticeDocument(
|
||||
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
|
||||
attachment_key='quality-extra.pdf', filename='quality-extra.pdf', content_hash='e' * 64,
|
||||
classification='order_notice', parse_status='parsed', extracted_text='PN-1 3',
|
||||
)
|
||||
db.session.add(extra)
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(extra, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr></table>'}],
|
||||
})
|
||||
db.session.commit()
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.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']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
# This legacy fixture cannot be republished under the v2-only write contract,
|
||||
# but its current approved credential proves the draft gate accepts independent evidence.
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.structure_fingerprint)
|
||||
|
||||
|
||||
|
||||
@@ -78,6 +78,55 @@ def test_candidate_content_fingerprint_migration_upgrade_and_downgrade():
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_candidate_acceptance_lifecycle_migration_is_conservative_and_reversible():
|
||||
"""迁移只自动接受已消费记录,未消费 legacy selected 记录必须保持 provisional。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_notice_candidates', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('selected', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('is_current_version', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('consumed_task_id', sa.Integer(), nullable=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.029f0a1b2c3d_add_shipping_candidate_acceptance_lifecycle'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_notice_candidates (id, selected, is_current_version, consumed_task_id) "
|
||||
"VALUES (1, 1, 1, NULL), (2, 1, 1, 99)"
|
||||
))
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
original_op = migration.op
|
||||
migration.op = operations
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')}
|
||||
assert {
|
||||
'candidate_status', 'candidate_status_before_superseded', 'acceptance_mode',
|
||||
'accepted_at', 'accepted_by_id', 'acceptance_reason', 'acceptance_policy_version',
|
||||
} <= columns
|
||||
statuses = connection.execute(sa.text(
|
||||
'SELECT id, candidate_status, acceptance_mode FROM shipping_notice_candidates ORDER BY id'
|
||||
)).all()
|
||||
assert statuses == [(1, 'provisional', None), (2, 'accepted', 'legacy')]
|
||||
assert 'ix_shipping_notice_candidates_fulfillment_gate' in {
|
||||
index['name'] for index in inspector.get_indexes('shipping_notice_candidates')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_notice_candidates')}
|
||||
assert 'candidate_status' not in columns
|
||||
assert 'acceptance_mode' not in columns
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建 e0f1 迁移所需的 d9 版本最小表结构与旧唯一约束。"""
|
||||
metadata = sa.MetaData()
|
||||
|
||||
@@ -117,6 +117,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
},
|
||||
validation_status='needs_review',
|
||||
conflicts_json=[{'field': 'qty'}],
|
||||
extraction_source='dify_workflow',
|
||||
selected=True,
|
||||
duplicate_resolution='open_existing',
|
||||
duplicate_target_task_no=existing.task_no,
|
||||
@@ -143,10 +144,40 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
patched = patch_response.get_json()['data']
|
||||
assert patched['selected'] is False
|
||||
assert patched['validation_status'] == 'ready'
|
||||
|
||||
# 模拟重复任务在审核完成前被关闭,采纳必须重新通过实时重复门禁。
|
||||
with app.app_context():
|
||||
existing = ShippingTask.query.filter_by(task_no='SN-CANDIDATE-EXISTING-001').one()
|
||||
db.session.delete(existing)
|
||||
db.session.commit()
|
||||
|
||||
promote_response = client.post(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote',
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert promote_response.status_code == 200
|
||||
promoted = promote_response.get_json()['data']
|
||||
assert promoted['candidate_status'] == 'accepted'
|
||||
assert promoted['acceptance_mode'] == 'manual'
|
||||
assert promoted['selected'] is True
|
||||
|
||||
repeated = client.post(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote',
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert repeated.status_code == 200
|
||||
assert repeated.get_json()['data']['candidate_status'] == 'accepted'
|
||||
assert patched['conflicts'] == []
|
||||
assert patched['content_fingerprint']
|
||||
assert patched['duplicate_resolution'] is None
|
||||
|
||||
with app.app_context():
|
||||
db.session.add(ShippingTask(
|
||||
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
|
||||
source_content_hash='candidate-api-content-hash', process_status='created',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
forbidden = client.patch(
|
||||
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
|
||||
json={'selected': True},
|
||||
@@ -349,6 +380,7 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app
|
||||
validation_status='ready',
|
||||
conflicts_json=[],
|
||||
selected=True,
|
||||
candidate_status='accepted',
|
||||
duplicate_status='none',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
@@ -402,6 +434,25 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app
|
||||
assert none_selected.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED'
|
||||
|
||||
|
||||
def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user):
|
||||
"""provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。"""
|
||||
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
|
||||
|
||||
with app.app_context():
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate',
|
||||
intake_id=1, primary_document_id=1, selected=True,
|
||||
candidate_status='provisional', is_current_version=True,
|
||||
validation_status='ready', conflicts_json=[],
|
||||
)
|
||||
with pytest.raises(ConflictError) as provisional:
|
||||
ensure_candidate_fulfillment_ready(candidate)
|
||||
assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED'
|
||||
|
||||
candidate.candidate_status = 'accepted'
|
||||
ensure_candidate_fulfillment_ready(candidate)
|
||||
|
||||
|
||||
def test_candidate_era_intake_without_candidates_cannot_fallback_to_single_eml_task(app, shipping_user):
|
||||
"""v6 Intake 无 Candidate 时必须阻断,不得退回整封 EML 建一个旧式 Task。"""
|
||||
with app.app_context():
|
||||
@@ -551,6 +602,7 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping
|
||||
validation_status='ready',
|
||||
conflicts_json=[],
|
||||
selected=True,
|
||||
candidate_status='accepted',
|
||||
business_fingerprint=identity['fingerprint'],
|
||||
fingerprint_version=identity['version'],
|
||||
fingerprint_strength=identity['strength'],
|
||||
|
||||
@@ -28,6 +28,7 @@ from app.models import (
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
@@ -37,6 +38,7 @@ from app.models import (
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.order_extraction import persist_order_extraction_result
|
||||
from app.services.shipping_notice.order_extraction_workflow import parse_order_extraction_workflow_result
|
||||
from app.services.shipping_notice.open_existing_reservation_backfill import (
|
||||
backfill_exact_file_open_existing_reservations,
|
||||
)
|
||||
@@ -449,11 +451,9 @@ def test_order_field_display_uses_current_catalog_sequence(app):
|
||||
with app.app_context():
|
||||
_ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
fields = [dict(item) for item in (version.definition_json or {}).get('fields') or []]
|
||||
sequence_by_code = {'qty': 1, 'part_number': 2, 'reservation_id': 3, 'po_number': 4}
|
||||
for field in fields:
|
||||
field['sequence'] = sequence_by_code.get(str(field.get('field_code')), 99)
|
||||
version.definition_json = {**(version.definition_json or {}), 'fields': fields}
|
||||
sequence_by_code = {'part_number': 1, 'qty': 2, 'reservation_id': 3, 'po_number': 4}
|
||||
for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id).all():
|
||||
field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
|
||||
task = ShippingTask(
|
||||
task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual',
|
||||
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}],
|
||||
@@ -522,8 +522,8 @@ def _add_extraction_intake(
|
||||
return intake, document
|
||||
|
||||
|
||||
def test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay(app):
|
||||
"""一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。"""
|
||||
def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_replayable(app):
|
||||
"""Provider 结果无论置信度高低均先形成 provisional Candidate,重试只回放。"""
|
||||
with app.app_context():
|
||||
user, session, intake, document, runtime_context = _seed_extraction_input()
|
||||
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
|
||||
@@ -559,26 +559,20 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes
|
||||
}
|
||||
result = _persist_test_orders(payload)
|
||||
|
||||
# 断言一附件拆成两个 Candidate,仅高置信订单创建 Task,Intake 保留为部分完成。
|
||||
assert result['created_count'] == 1
|
||||
# Dify/Provider 结果不得直接建单;阶段二才允许受控确定性模板自动接受。
|
||||
assert result['created_count'] == 0
|
||||
assert result['opened_existing_count'] == 0
|
||||
assert result['pending_count'] == 1
|
||||
assert result['pending_count'] == 2
|
||||
assert result['non_shipping_count'] == 0
|
||||
assert result['created_with_missing_fields_count'] == 1
|
||||
assert result['message'] == (
|
||||
'已创建 1 个发货任务;另有 1 个订单需要补充信息或处理冲突。'
|
||||
'其中 1 个新建任务仍缺少 Reservation ID,可通过自然对话补充。'
|
||||
)
|
||||
assert result['batch_no']
|
||||
assert result['created_with_missing_fields_count'] == 0
|
||||
assert result['batch_no'] is None
|
||||
candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all()
|
||||
assert len(candidates) == 2
|
||||
assert len({item.candidate_key for item in candidates}) == 2
|
||||
assert {item.candidate_status for item in candidates} == {'provisional'}
|
||||
assert all(item.selected is False for item in candidates)
|
||||
tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all()
|
||||
assert len(tasks) == 1
|
||||
task = tasks[0]
|
||||
assert task.process_status == 'pending_review'
|
||||
assert task.pending_human_reason == 'rsv_req'
|
||||
assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == ['reservation_id']
|
||||
assert tasks == []
|
||||
db.session.refresh(intake)
|
||||
assert intake.parse_status == 'parsed'
|
||||
# 低置信订单仍未消费,因此 Intake 抽取终态必须保留为 partially_completed。
|
||||
@@ -586,35 +580,13 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes
|
||||
db.session.refresh(document)
|
||||
assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2
|
||||
|
||||
# 断言后台或自然语言“继续”无法绕过字段门禁进入库存流程。
|
||||
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
|
||||
progress = auto_progress({'task_id': task.task_no})
|
||||
assert progress['status'] == 'needs_human'
|
||||
assert progress['checkpoint'] == 'rsv_req'
|
||||
assert 'ensure_inventory' in progress['forbidden_next_tools']
|
||||
|
||||
replay = _persist_test_orders(payload)
|
||||
assert replay['idempotent_replay'] is True
|
||||
assert replay['created_count'] == 1
|
||||
assert replay['created_count'] == 0
|
||||
assert replay['opened_existing_count'] == 0
|
||||
assert replay['pending_count'] == 1
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
|
||||
assert replay['pending_count'] == 2
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2
|
||||
|
||||
edit_result = update_notice_line({
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {
|
||||
'reservation_id': '1000140351',
|
||||
},
|
||||
'comment': '用户通过自然对话补齐流程字段',
|
||||
})
|
||||
db.session.refresh(task)
|
||||
# 断言既有行更新 Tool 可完成自然对话补字段,并清除旧流程字段门禁。
|
||||
assert edit_result['status'] == 'ok'
|
||||
assert task.pending_human_reason == 'low_confidence'
|
||||
assert 'process_field_gate' not in (task.step_payload_json or {})
|
||||
assert task.current_order_extraction_id is not None
|
||||
assert session.user_id == user.id
|
||||
|
||||
|
||||
@@ -642,10 +614,38 @@ def test_shadow_mode_persists_ready_candidate_without_creating_task(app):
|
||||
assert result['pending_count'] == 1
|
||||
assert result['pending_orders'][0]['reasons'] == ['auto_create_disabled']
|
||||
assert candidate.validation_status == 'ready'
|
||||
assert candidate.candidate_status == 'provisional'
|
||||
assert candidate.selected is False
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(app):
|
||||
"""已批准固定模板的后端标记可自动接受;普通 Provider 结果仍须人工采纳。"""
|
||||
with app.app_context():
|
||||
_user, _session, intake, document, runtime_context = _seed_extraction_input()
|
||||
context = _build_test_extraction_context({'agent_runtime_context': runtime_context})
|
||||
order = _order(
|
||||
intake_no=intake.intake_no, document_id=int(document.id), po_number='4510000001',
|
||||
part_number='SKU-A', qty=10, include_process_fields=True,
|
||||
)
|
||||
order['_hxops_acceptance'] = 'approved_deterministic_profile_v1'
|
||||
|
||||
_persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]})
|
||||
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
|
||||
assert candidate.candidate_status == 'accepted'
|
||||
assert candidate.acceptance_mode == 'automatic'
|
||||
assert candidate.extraction_source == 'approved_deterministic_profile'
|
||||
assert candidate.selected is True
|
||||
|
||||
|
||||
def test_workflow_result_accepts_only_documented_data_orders_wrapper():
|
||||
"""Dify End 允许 data.orders 包装,但不把内部接受字段当作可信输入。"""
|
||||
assert parse_order_extraction_workflow_result({
|
||||
'status': 'succeeded', 'outputs': {'orders': {'data': {'orders': [{'id': 'one'}]}}},
|
||||
}) == [{'id': 'one'}]
|
||||
|
||||
|
||||
def test_persist_order_extraction_result_consumes_empty_and_confident_non_shipping_results(app):
|
||||
"""空 orders[] 与高置信非发货分类均不生成 Candidate,并返回明确的未建单事实。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -128,6 +128,195 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
|
||||
assert saved['definition']['contract_version'] == 'order_coordinate_profile.v2'
|
||||
|
||||
|
||||
def test_order_field_layout_is_independent_from_line_layout_and_freezes_header_field(app):
|
||||
"""订单级字段必须冻结 Header 身份,且不写入表头或物理行字段区域。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': 'forged', 'field_code': 'po_number',
|
||||
'page_scope': 'first_page',
|
||||
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO', 'aliases': ['PO NUMBER']},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': True,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'ORDER_FIELD', 'display_name': 'Order field',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
order_field = saved['definition']['order_field_layouts'][0]
|
||||
assert order_field['field_id'] == 'po-field'
|
||||
assert order_field['anchor']['aliases'] == ['PO NUMBER']
|
||||
assert all(
|
||||
item['field_code'] != 'po_number'
|
||||
for item in saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions']
|
||||
)
|
||||
|
||||
|
||||
def test_order_field_layout_duplicate_returns_bound_schema_code(app):
|
||||
"""同一 Header 字段重复绑定时必须返回具体字段编码,不能退化成泛化契约错误。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'ship-to-field', 'field_code': 'ship_to_customer', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': f'ship_to_{index}', 'field_id': '', 'field_code': 'ship_to_customer',
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': {'anchor_id': f'ship_to_label_{index}', 'text': f'SHIP TO {index}'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}
|
||||
for index in (1, 2)
|
||||
]
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft({
|
||||
'profile_code': 'ORDER_FIELD_DUPLICATE', 'display_name': 'Order field duplicate',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:前端可用 details 精确指出重复字段,而不是只能显示通用配置无效。
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
assert getattr(caught.value, 'details', {}).get('field_codes') == ['ship_to_customer']
|
||||
|
||||
|
||||
def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
|
||||
"""账款客户和地址同一行时可共享标签证据,但必须各自保存为独立字段布局。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].extend([
|
||||
{
|
||||
'field_id': 'bill-to-customer', 'field_code': 'bill_to_customer', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'bill-to-address', 'field_code': 'bill_to_address', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
])
|
||||
definition = _coordinate_definition()
|
||||
shared_anchor = {
|
||||
'anchor_id': 'invoice_bill_sold_to', 'text': 'INVOICE BILL/SOLD TO',
|
||||
'region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .25},
|
||||
}
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': 'bill_to_customer_layout', 'field_id': '', 'field_code': 'bill_to_customer',
|
||||
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 3, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
},
|
||||
{
|
||||
'layout_id': 'bill_to_address_layout', 'field_id': '', 'field_code': 'bill_to_address',
|
||||
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
|
||||
'value_region': {'x0': 3, 'y0': 0, 'x1': 10, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
},
|
||||
]
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'BILL_TO_SHARED_ANCHOR', 'display_name': 'Bill to shared anchor',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:共享标签没有重复绑定 Schema 字段,也不会复用 layout_id。
|
||||
assert [item['layout_id'] for item in saved['definition']['order_field_layouts']] == [
|
||||
'bill_to_customer_layout', 'bill_to_address_layout',
|
||||
]
|
||||
|
||||
|
||||
def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app):
|
||||
"""订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'invalid_line', 'field_id': '', 'field_code': 'part_number',
|
||||
'page_scope': 'all_pages', 'anchor': None,
|
||||
'value_region': None,
|
||||
'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft({
|
||||
'profile_code': 'INVALID_ORDER_FIELD', 'display_name': 'Invalid order field',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_order_field_layout_freezes_schema_normalizer_and_rejects_a_mismatch(app):
|
||||
"""订单字段不能让浏览器替换 Schema 的规范化策略,保存结果必须冻结 Schema key。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'uppercase_trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'ORDER_FIELD_NORMALIZER', 'display_name': 'Order field normalizer',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
assert saved['definition']['order_field_layouts'][0]['normalizer_key'] == 'uppercase_trim'
|
||||
|
||||
definition['order_field_layouts'][0]['normalizer_key'] = 'trim'
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft({
|
||||
'profile_code': 'ORDER_FIELD_BAD_NORMALIZER', 'display_name': 'Bad normalizer',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
|
||||
|
||||
def test_order_field_ocr_minimum_level_keeps_native_pdf_as_stronger_allowed_source(app):
|
||||
"""OCR 最低证据允许更强的原生 PDF 坐标,不能把 Schema 授权错误收窄为 OCR-only。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'page_scope': 'first_page', 'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
'stop_anchors': [], 'required': False, 'minimum_evidence_level': 'ocr_coordinate',
|
||||
}]
|
||||
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'ORDER_FIELD_OCR_MINIMUM', 'display_name': 'Order field OCR minimum',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
assert saved['definition']['order_field_layouts'][0]['minimum_evidence_level'] == 'ocr_coordinate'
|
||||
|
||||
|
||||
def test_composite_coordinate_binding_freezes_all_registered_output_fields(app):
|
||||
"""复合解析器的辅助输出也必须以 field_id 冻结;缺少任何输出字段时拒绝保存。"""
|
||||
with app.app_context():
|
||||
@@ -359,6 +548,58 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
assert field['field_id'] == 'replacement-field'
|
||||
assert field['field_code'] == 'supplier_part_number'
|
||||
|
||||
|
||||
def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publish(app, monkeypatch):
|
||||
"""删除订单字段时保留锚点/值区,并在管理员重新绑定前阻止新模板发布。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
source_schema = _schema_version()
|
||||
source_schema.definition_json = {
|
||||
**source_schema.definition_json,
|
||||
'fields': [*source_schema.definition_json['fields'], {
|
||||
'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'page_scope': 'first_page',
|
||||
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
draft = service.save_draft({
|
||||
'profile_code': 'ORDER_FIELD_MIGRATION', 'display_name': 'Order field migration',
|
||||
'schema_version_id': source_schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
source_schema.status = 'retired'
|
||||
target_schema = ShippingOrderSchemaVersion(
|
||||
schema_id=source_schema.schema_id, version=2, status='published', checksum='d' * 64,
|
||||
published_at=datetime.utcnow(), definition_json={'fields': [
|
||||
dict(item) for item in source_schema.definition_json['fields'] if item['field_id'] != 'po-field'
|
||||
]},
|
||||
)
|
||||
db.session.add(target_schema)
|
||||
db.session.commit()
|
||||
migrated = service.create_schema_migration_draft(
|
||||
published['id'], target_schema_version_id=target_schema.id,
|
||||
resolutions={'po-field': {'action': 'unbind'}}, actor_id=None,
|
||||
)
|
||||
assert migrated['definition']['order_field_layouts'] == []
|
||||
unbound = migrated['definition']['draft_unbound_order_field_layouts'][0]
|
||||
assert unbound['layout_id'] == 'po_number'
|
||||
assert unbound['anchor']['text'] == 'PO NO'
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(migrated['id'], actor_id=None, expected_lock_version=migrated['lock_version'])
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
|
||||
assert migrated['migration_status'] == 'needs_revalidation'
|
||||
|
||||
model = db.session.get(ShippingOrderDocumentProfile, migrated['id'])
|
||||
@@ -1106,6 +1347,36 @@ def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, m
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED'
|
||||
|
||||
|
||||
def test_delete_draft_cascades_blind_test_suite(app):
|
||||
"""关键断言:删除草稿 Profile 时一并清理盲测套件,避免外键约束导致 500。"""
|
||||
with app.app_context():
|
||||
user = User(username='draft-delete-admin', email='draft-delete@example.com', role='admin', status='active')
|
||||
schema = _schema_version()
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='DRAFT_DELETE_SUITE', display_name='Draft delete suite', version=1,
|
||||
status='draft', schema_version_id=schema.id,
|
||||
structure_fingerprint='3' * 64, definition_json={}, checksum='3' * 64,
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.checksum or profile.structure_fingerprint,
|
||||
created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.commit()
|
||||
suite_id = suite.id
|
||||
profile_id = profile.id
|
||||
|
||||
service.delete_draft(profile_id)
|
||||
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile_id) is None
|
||||
assert db.session.get(ShippingDocumentProfileTestSuite, suite_id) is None
|
||||
|
||||
|
||||
def test_profile_rejects_legacy_grid_definition(app):
|
||||
"""关键断言:新 Profile 不能再混入 HTML 网格、表头行号或固定列映射。"""
|
||||
with app.app_context():
|
||||
@@ -1169,8 +1440,8 @@ def test_workbench_draft_can_save_without_bound_fields(app):
|
||||
assert saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] == []
|
||||
|
||||
|
||||
def test_workbench_draft_preserves_unbound_regions_but_publish_rejects_them(app):
|
||||
"""未绑定框可随草稿恢复,但在完成 Schema 绑定前禁止发布。"""
|
||||
def test_workbench_auto_suggested_unbound_regions_do_not_block_publish(app, monkeypatch):
|
||||
"""自动标记的非关键候选可保留展示,不能阻断已经通过质量门禁的模板发布。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
saved = service.save_draft({
|
||||
@@ -1194,6 +1465,29 @@ def test_workbench_draft_preserves_unbound_regions_but_publish_rejects_them(app)
|
||||
},
|
||||
}, actor_id=None)
|
||||
assert saved['definition']['table_regions'][0]['draft_unbound_field_regions'][0]['label'] == '未绑定列 1'
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
assert service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])['status'] == 'published'
|
||||
|
||||
|
||||
def test_schema_migration_unbound_regions_still_block_publish(app, monkeypatch):
|
||||
"""只有 Schema breaking migration 明确遗留的待绑定区域才会阻止发布。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
payload = _coordinate_definition()
|
||||
payload['table_regions'][0]['draft_unbound_field_regions'] = [{
|
||||
'region_id': 'migration-main-part-field', 'parent_layout_id': 'main',
|
||||
'label': 'part_number', 'region': {'x0': .1, 'y0': .4, 'x1': .3, 'y1': .5},
|
||||
'requires_rebinding': True,
|
||||
}]
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'UNBOUND_MIGRATION', 'display_name': 'Unbound migration',
|
||||
'schema_version_id': schema.id, 'definition': payload,
|
||||
}, actor_id=None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
|
||||
@@ -1358,3 +1652,294 @@ def test_coordinate_suggestion_can_return_only_requested_physical_row(app, monke
|
||||
# 当前行识别只返回 row_offset=1,首行建议不会混入响应。
|
||||
assert [item['row_offset'] for item in result['subrow_layouts']] == [1]
|
||||
assert result['subrow_layouts'][0]['column_samples'] == [['VENDOR-20']]
|
||||
|
||||
|
||||
def test_coordinate_suggestion_binds_line_columns_from_enabled_field_rules(app, monkeypatch):
|
||||
"""明细表头仅在唯一别名且字段启用自动标记时绑定相应列。"""
|
||||
characters = []
|
||||
source_index = 0
|
||||
for row_index, row in enumerate([
|
||||
[('ITEMNO', 12), ('MATERIALNO', 100), ('QTY', 270)],
|
||||
[('00020', 12), ('PART-20', 100), ('36', 270)],
|
||||
]):
|
||||
for text, x0 in row:
|
||||
for character_index, character in enumerate(text):
|
||||
if character == ' ':
|
||||
continue
|
||||
characters.append({
|
||||
'text': character, 'source_index': source_index,
|
||||
'bbox': {
|
||||
'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20,
|
||||
'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20,
|
||||
},
|
||||
})
|
||||
source_index += 1
|
||||
layout = {
|
||||
'tables': [{'table_id': 'schema-suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70},
|
||||
'html': '<table><tr><td>broken</td></tr></table>'}],
|
||||
'coordinate_evidence': {'tables': {'schema-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}},
|
||||
}
|
||||
version = SimpleNamespace(definition_json={'fields': [
|
||||
{'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True,
|
||||
'display_name': 'Item number', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True,
|
||||
'display_name': 'Material number', 'aliases': ['MATERIAL NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'enabled': True,
|
||||
'display_name': 'Quantity', 'aliases': ['QTY'], 'allowed_sources': ['pdf_coordinate'],
|
||||
'auto_annotation_enabled': False},
|
||||
]})
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 106 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_coordinate_reconstruction(
|
||||
{'document_id': 106, 'table_id': 'schema-suggest', 'schema_version_id': 1}, actor_id=None,
|
||||
)
|
||||
|
||||
header_codes = [field['field_code'] for field in result['header_regions'][0]['fields']]
|
||||
assert header_codes == ['line_no', 'part_number', None]
|
||||
# The disabled automatic marker never produces a table-header or detail-column binding.
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'] == ['line_no', 'part_number', None]
|
||||
|
||||
|
||||
def test_coordinate_suggestion_binds_line_columns_from_normalized_field_codes(app, monkeypatch):
|
||||
"""没有维护别名时,稳定 field_code 仍可精确对应常见空格表头。"""
|
||||
characters = []
|
||||
for row_index, row in enumerate([
|
||||
[('ITEM NO', 12), ('UNIT PRICE', 90), ('ORDER QUANTITY', 210)],
|
||||
[('00020', 12), ('941.760000', 90), ('30', 210)],
|
||||
]):
|
||||
for text, x0 in row:
|
||||
for character_index, character in enumerate(text):
|
||||
if character != ' ':
|
||||
characters.append({'text': character, 'bbox': {
|
||||
'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20,
|
||||
'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20,
|
||||
}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'code-suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70}}],
|
||||
'coordinate_evidence': {'tables': {'code-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}},
|
||||
}
|
||||
version = SimpleNamespace(definition_json={'fields': [
|
||||
{'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True,
|
||||
'display_name': '项次', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line', 'enabled': True,
|
||||
'display_name': '单价', 'aliases': [], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'quantity', 'field_code': 'order_quantity', 'scope': 'line', 'enabled': True,
|
||||
'display_name': '数量', 'aliases': [], 'allowed_sources': ['pdf_coordinate']},
|
||||
]})
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 107 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_coordinate_reconstruction(
|
||||
{'document_id': 107, 'table_id': 'code-suggest', 'schema_version_id': 1}, actor_id=None,
|
||||
)
|
||||
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'] == [
|
||||
'line_no', 'unit_price', 'order_quantity',
|
||||
]
|
||||
|
||||
|
||||
def test_order_field_suggestions_use_page_glyphs_and_never_auto_confirm(app, monkeypatch):
|
||||
"""订单字段自动标记只从整页唯一标签生成 needs_review 的锚点和值区候选。"""
|
||||
glyphs = []
|
||||
for text, x0, y0 in [('PO NO: 45001', 20, 20), ('BILL TO: ACME', 20, 45), ('PO NO: duplicate', 20, 70)]:
|
||||
for index, character in enumerate(text):
|
||||
if character != ' ':
|
||||
glyphs.append({'text': character, 'bbox': {
|
||||
'x0': x0 + index * 5, 'y0': y0, 'x1': x0 + index * 5 + 4, 'y1': y0 + 8,
|
||||
}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 300, 'height': 200}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
version = type('Version', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'PO Number', 'scope': 'header',
|
||||
'aliases': ['PO NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'bill', 'field_code': 'bill_to', 'display_name': 'Bill To', 'scope': 'header',
|
||||
'aliases': ['BILL TO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
]}})()
|
||||
document = type('Document', (), {'id': 104})()
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 104 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts(
|
||||
{'document_id': 104, 'schema_version_id': 1, 'page_no': 1}, actor_id=None,
|
||||
)
|
||||
|
||||
by_code = {item['field_code']: item for item in result['order_field_candidates']}
|
||||
assert result['status'] == 'needs_review'
|
||||
assert by_code['bill_to']['status'] == 'suggested'
|
||||
assert by_code['bill_to']['value_mode'] == 'right_of_anchor'
|
||||
assert by_code['customer_po']['status'] == 'ambiguous'
|
||||
|
||||
|
||||
def test_order_field_suggestions_keep_unbound_visual_labels_for_manual_binding(app, monkeypatch):
|
||||
"""未维护别名的订单抬头标签仍要出现成对框选,管理员随后在工作台绑定 Schema。"""
|
||||
glyphs = []
|
||||
for index, character in enumerate('PURCHASE ORDER DATE: 06/20/2026'):
|
||||
if character != ' ':
|
||||
glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
}
|
||||
version = type('Version', (), {'definition_json': {'fields': []}})()
|
||||
document = type('Document', (), {'id': 105})()
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 105 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda document: layout)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts({'document_id': 105, 'schema_version_id': 1}, actor_id=None)
|
||||
|
||||
candidate = result['order_field_candidates'][0]
|
||||
assert candidate['binding_status'] == 'unbound'
|
||||
assert candidate['anchor_text'] == 'PURCHASE ORDER DATE'
|
||||
assert candidate['field_code'] == ''
|
||||
|
||||
|
||||
def test_order_field_suggestions_backfill_page_glyphs_for_legacy_table_only_snapshot(app, monkeypatch):
|
||||
"""历史样本仅有表内字符时,建议前必须补齐整页证据以识别表格外的订单抬头。"""
|
||||
document = type('Document', (), {'id': 106, 'asset_id': 3, 'filename': 'legacy.pdf'})()
|
||||
asset = object()
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'tables': {'lines': []}},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 106 else asset if object_id == 3 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: type('Version', (), {'definition_json': {'fields': []}})())
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **kwargs: {
|
||||
**layout, 'coordinate_evidence': {**layout['coordinate_evidence'],
|
||||
'page_glyphs': {'1': [{'text': 'P', 'bbox': {'x0': 20, 'y0': 20, 'x1': 24, 'y1': 28}}, {'text': 'O', 'bbox': {'x0': 25, 'y0': 20, 'x1': 29, 'y1': 28}}, {'text': ':', 'bbox': {'x0': 30, 'y0': 20, 'x1': 34, 'y1': 28}}]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
})
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts({'document_id': 106, 'schema_version_id': 1}, actor_id=None)
|
||||
|
||||
assert result['order_field_candidates'][0]['anchor_text'] == 'PO'
|
||||
|
||||
|
||||
def test_order_field_suggestions_split_inline_label_from_value_and_exclude_terms(app, monkeypatch):
|
||||
"""标签框只覆盖冒号前文本,值框只覆盖同一行值;表格前条款不应成为未绑定订单字段。"""
|
||||
glyphs = []
|
||||
for text, y0 in [('PURCHASE ORDER DATE: 06/20/2026', 20), ('QUALITY: IF ANY DISCREPANCY FOUND', 85)]:
|
||||
for index, character in enumerate(text):
|
||||
if character != ' ':
|
||||
glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': y0, 'x1': 24 + index * 5, 'y1': y0 + 8}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
}
|
||||
document = type('Document', (), {'id': 107})()
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 107 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: type('Version', (), {'definition_json': {'fields': []}})())
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts({'document_id': 107, 'schema_version_id': 1}, actor_id=None)
|
||||
|
||||
candidate = result['order_field_candidates'][0]
|
||||
assert candidate['anchor_region']['x1'] < candidate['value_region']['x0']
|
||||
assert candidate['value_region']['x1'] < .75
|
||||
assert all(item['anchor_text'] != 'QUALITY' for item in result['order_field_candidates'])
|
||||
|
||||
|
||||
def test_order_field_suggestions_keep_value_box_to_first_same_line_value_group(app, monkeypatch):
|
||||
"""同一视觉行含多个键值组时,首个订单字段值框不得吞掉下一个字段。"""
|
||||
glyphs = []
|
||||
for text, x0 in [('PO NO: 451883152', 20), ('VERSION: 2', 190)]:
|
||||
for index, character in enumerate(text):
|
||||
if character != ' ':
|
||||
glyphs.append({'text': character, 'bbox': {
|
||||
'x0': x0 + index * 5, 'y0': 20, 'x1': x0 + index * 5 + 4, 'y1': 28,
|
||||
}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
}
|
||||
version = type('Version', (), {'definition_json': {'fields': [{
|
||||
'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'Customer PO', 'aliases': ['PO NO'],
|
||||
'scope': 'header', 'allowed_sources': ['pdf_coordinate'], 'auto_annotation_enabled': True,
|
||||
}]}})()
|
||||
document = type('Document', (), {'id': 109})()
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 109 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts({'document_id': 109, 'schema_version_id': 1}, actor_id=None)
|
||||
|
||||
candidate = result['order_field_candidates'][0]
|
||||
# VERSION starts at 190/300. The PO value box must end before that next key/value group.
|
||||
assert candidate['value_region']['x1'] < .64
|
||||
|
||||
|
||||
def test_order_field_suggestions_stop_value_before_adjacent_same_line_label(app, monkeypatch):
|
||||
"""无明显字间距时,值框仍须在同一行下一个标签冒号前停止。"""
|
||||
glyphs = []
|
||||
text = 'PO NO: 451883152 VERSION: 2'
|
||||
for index, character in enumerate(text):
|
||||
if character != ' ':
|
||||
glyphs.append({'text': character, 'bbox': {
|
||||
'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28,
|
||||
}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
}
|
||||
version = type('Version', (), {'definition_json': {'fields': [{
|
||||
'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'Customer PO', 'aliases': ['PO NO'],
|
||||
'scope': 'header', 'allowed_sources': ['pdf_coordinate'], 'auto_annotation_enabled': True,
|
||||
}]}})()
|
||||
document = type('Document', (), {'id': 110})()
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 110 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts({'document_id': 110, 'schema_version_id': 1}, actor_id=None)
|
||||
|
||||
# VERSION begins at character 17, x=105; the PO value must stop before it.
|
||||
candidate = result['order_field_candidates'][0]
|
||||
assert candidate['value_region']['x1'] < .36
|
||||
assert candidate['suggested_value'] == '451883152'
|
||||
# An 8px text line on a 200px page gets at most 1px top/bottom padding.
|
||||
value_region = result['order_field_candidates'][0]['value_region']
|
||||
assert value_region['y1'] - value_region['y0'] <= .05
|
||||
|
||||
|
||||
def test_order_field_suggestions_do_not_duplicate_bound_schema_field_as_unbound_label(app, monkeypatch):
|
||||
"""同一视觉行已绑定 order_date 时,完整文档标签不得再生成第二个未绑定候选。"""
|
||||
glyphs = []
|
||||
for index, character in enumerate('PURCHASE ORDER DATE: 06/20/2026'):
|
||||
if character != ' ':
|
||||
glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
|
||||
}
|
||||
document = type('Document', (), {'id': 108})()
|
||||
version = type('Version', (), {'definition_json': {'fields': [{
|
||||
'field_id': 'date', 'field_code': 'order_date', 'display_name': 'Order Date', 'aliases': [],
|
||||
'scope': 'header', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]}})()
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 108 else None)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda item: layout)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda value: version)
|
||||
|
||||
with app.app_context():
|
||||
result = service.suggest_order_field_layouts({'document_id': 108, 'schema_version_id': 1}, actor_id=None)
|
||||
|
||||
assert [(item['field_code'], item.get('binding_status')) for item in result['order_field_candidates']] == [('order_date', 'bound')]
|
||||
@@ -21,6 +21,8 @@ from app.jobs.queue import claim_next_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
AgentRuntimeBinding,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderExtractionQualityBatch,
|
||||
ShippingOrderExtractionQualityLabel,
|
||||
ShippingOrderExtractionRun,
|
||||
@@ -253,6 +255,9 @@ def test_approved_batch_is_listed_and_frozen_on_run(app):
|
||||
provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id,
|
||||
config={'auto_create_enabled': True},
|
||||
)
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
|
||||
schema.auto_creation_policy_json = {'enabled': True}
|
||||
db.session.commit()
|
||||
|
||||
listed = list_approved_quality_batches(owner_agent_id=owner.id)
|
||||
run, reused = create_order_extraction_run(
|
||||
@@ -279,6 +284,30 @@ def test_approved_batch_is_listed_and_frozen_on_run(app):
|
||||
assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED'
|
||||
|
||||
|
||||
def test_disabled_schema_keeps_runtime_auto_create_binding_in_shadow_mode(app):
|
||||
"""质量批次已配置时,Schema 总开关关闭仍可创建影子 Run,且不得触发自动建单。"""
|
||||
with app.app_context():
|
||||
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-SHADOW')
|
||||
provider = Agent.query.filter_by(exposure_mode='internal').first()
|
||||
binding = AgentRuntimeBinding.query.filter_by(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
).one()
|
||||
binding.config_json = {'timeout_seconds': 900, 'max_attempts': 3, 'auto_create_enabled': True}
|
||||
binding.provider_agent_id = provider.id
|
||||
# The missing quality batch is intentional: schema-disabled execution is shadow-only.
|
||||
binding.quality_batch_id = None
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=owner.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
assert reused is False
|
||||
assert run.provider_config_json['auto_create_enabled'] is False
|
||||
assert run.input_snapshot_json['auto_creation_policy']['schema_enabled'] is False
|
||||
assert run.input_snapshot_json['auto_creation_policy']['runtime_binding_enabled'] is True
|
||||
|
||||
def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client):
|
||||
"""质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -206,6 +206,29 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert ShippingOrderExtractionUnit.query.count() == 1
|
||||
|
||||
|
||||
def test_schema_auto_create_switch_cannot_bypass_disabled_runtime_binding(app):
|
||||
"""Schema 总开关开启时,未显式启用 Runtime Binding 的 Run 仍必须保持影子模式。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-CREATE-GATE')
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
|
||||
schema.auto_creation_policy_json = {'enabled': True}
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
assert reused is False
|
||||
assert run.provider_config_json['auto_create_enabled'] is False
|
||||
policy = run.input_snapshot_json['auto_creation_policy']
|
||||
assert policy == {
|
||||
'enabled': False,
|
||||
'schema_enabled': True,
|
||||
'runtime_binding_enabled': False,
|
||||
}
|
||||
|
||||
|
||||
def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app):
|
||||
"""Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。"""
|
||||
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
|
||||
@@ -1383,7 +1406,7 @@ def test_failed_reparse_restores_source_candidate_version(app):
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='restore-version', order_extraction_run_id=source.id,
|
||||
selected=True, is_current_version=True, validation_status='ready',
|
||||
selected=True, candidate_status='accepted', is_current_version=True, validation_status='ready',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
@@ -1395,6 +1418,8 @@ def test_failed_reparse_restores_source_candidate_version(app):
|
||||
assert candidate.is_current_version is False
|
||||
assert candidate.selected is False
|
||||
assert candidate.selected_before_superseded is True
|
||||
assert candidate.candidate_status == 'expired'
|
||||
assert candidate.candidate_status_before_superseded == 'accepted'
|
||||
transition_order_extraction_run(replacement, target_status='running')
|
||||
transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable')
|
||||
db.session.flush()
|
||||
@@ -1402,6 +1427,8 @@ def test_failed_reparse_restores_source_candidate_version(app):
|
||||
assert candidate.is_current_version is True
|
||||
assert candidate.selected is True
|
||||
assert candidate.selected_before_superseded is None
|
||||
assert candidate.candidate_status == 'accepted'
|
||||
assert candidate.candidate_status_before_superseded is None
|
||||
assert source.superseded_by_run_id is None
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
"""
|
||||
tests/test_shipping_order_field_extraction.py
|
||||
|
||||
用途:验证订单级字段锚点/相对区域确定性读取的失败关闭边界。
|
||||
依赖:order_field_extraction、订单 Profile 与冻结 Schema 字段规则。
|
||||
逻辑:覆盖独立订单字段,不经过明细物理行或 Dify,防止两类区域重新耦合。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
|
||||
from app.services.shipping_notice.document_layout.runtime import _ocr_page_characters
|
||||
from app.services.shipping_notice.document_profile_quality_service import _order_field_quality_failures
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_build_approved_profile_order,
|
||||
_merge_confirmed_profile_order_fields,
|
||||
)
|
||||
|
||||
|
||||
def _glyphs(*lines: tuple[str, float, float]) -> list[dict]:
|
||||
"""将测试文字按字符展开为坐标 glyph,模拟 PDFium 不保留空白字符的输出。"""
|
||||
result = []
|
||||
for text, x, y in lines:
|
||||
offset = 0
|
||||
for character in text:
|
||||
if character != ' ':
|
||||
result.append({'text': character, 'bbox': {'x0': x + offset * 4, 'y0': y, 'x1': x + offset * 4 + 3, 'y1': y + 8}})
|
||||
offset += 1
|
||||
return result
|
||||
|
||||
|
||||
def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfileV2:
|
||||
"""构造包含一个独立 header 字段的最小合法 v2 Profile。"""
|
||||
return OrderCoordinateProfileV2.model_validate({
|
||||
'profile_code': 'ORDER-FIELD-TEST', 'version': 1,
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .9}, 'line_layouts': [], 'header_layouts': [{'layout_id': 'headers', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .7}}]}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'po_field', 'field_id': 'po-id', 'field_code': 'customer_po',
|
||||
'page_scope': page_scope, **layout,
|
||||
}],
|
||||
})
|
||||
|
||||
|
||||
def _schema(**overrides: object) -> dict[str, dict]:
|
||||
"""提供允许 PDF/OCR 坐标且默认 string 的冻结 Header Schema 字段。"""
|
||||
return {'po-id': {
|
||||
'field_id': 'po-id', 'field_code': 'customer_po', 'scope': 'header', 'enabled': True,
|
||||
'value_type': 'string', 'normalizer_key': 'trim', 'validator_keys': ['non_empty'],
|
||||
'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'], **overrides,
|
||||
}}
|
||||
|
||||
|
||||
def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict:
|
||||
"""构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。"""
|
||||
return {
|
||||
'pages': {page: {'width': 200, 'height': 200} for page in pages},
|
||||
'page_glyphs': pages,
|
||||
'sources': {'pages': {page: source for page in pages}},
|
||||
}
|
||||
|
||||
|
||||
def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
|
||||
"""唯一 PO 标签右侧的原生字符经规范化后可确认为独立订单字段。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('PO NO 45001', 20, 20))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:独立字段不依赖 table glyph,唯一锚点的 PDF 坐标才可提升 confirmed。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '45001'
|
||||
assert result.source == 'pdf_coordinate'
|
||||
|
||||
|
||||
def test_wide_address_value_region_is_valid_relative_to_short_anchor():
|
||||
"""地址值框可比短标签宽得多,自动标记后保存不得被相对区域上限拒绝。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 10.5, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor',
|
||||
})
|
||||
|
||||
# 关键断言:仍有有限上限,但自动建议的长地址几何属于合法模板定义。
|
||||
assert profile.order_field_layouts[0].value_region.x1 == 10.5
|
||||
|
||||
|
||||
def test_duplicate_anchor_requires_review_instead_of_selecting_one():
|
||||
"""同页两个 PO 标签存在歧义,绝不按先后顺序静默选择。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('PO NO 1', 20, 20), ('PO NO 2', 20, 50))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:多锚点只能进入人工复核。
|
||||
assert result.status == 'needs_review'
|
||||
assert result.issues == ['order_field_anchor_ambiguous']
|
||||
|
||||
|
||||
def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrences():
|
||||
"""锚点参考区与精确匹配共同排除页眉重复标签和更长单词中的局部文本。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO', 'match_mode': 'exact', 'region': {'x0': 0, 'y0': .1, 'x1': .8, 'y1': .3}},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('PONUMBER 999', 20, 8), ('PO 45001', 20, 30), ('PO 111', 20, 120))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:只允许参考区内独立 PO,避免选择页眉或 PONUMBER 的局部命中。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '45001'
|
||||
|
||||
|
||||
def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence():
|
||||
"""历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'ship_to', 'text': '订单字段标签 1',
|
||||
'region': {'x0': .08, 'y0': .1, 'x1': .35, 'y1': .2},
|
||||
},
|
||||
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('SHIP TO PARTY ACME', 20, 30))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:占位标签不会伪装成已确认,但原锚点框内的值仍可恢复展示。
|
||||
assert result.status == 'needs_review'
|
||||
assert result.value == 'ACME'
|
||||
assert result.issues == ['order_field_anchor_text_mismatch']
|
||||
|
||||
|
||||
def test_non_placeholder_anchor_text_with_reference_region_still_fails_closed():
|
||||
"""管理员自定义标签写错时不可退化为坐标猜值,避免历史兼容绕过锚点门禁。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'ship_to', 'text': 'WRONG LABEL',
|
||||
'region': {'x0': .08, 'y0': .1, 'x1': .35, 'y1': .2},
|
||||
},
|
||||
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('SHIP TO PARTY ACME', 20, 30))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:兼容范围仅限系统默认占位标签,普通错配仍不可用。
|
||||
assert result.status == 'unavailable'
|
||||
assert result.issues == ['order_field_anchor_missing']
|
||||
|
||||
|
||||
def test_all_pages_conflicting_repeated_value_requires_review():
|
||||
"""每页重复字段值不一致必须记录冲突,不能将首页值静默确认为正式结果。"""
|
||||
profile = _profile(page_scope='all_pages', layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('PO NO 45001', 20, 20)), '2': _glyphs(('PO NO 45002', 20, 20))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:多页冲突只能进入人工复核。
|
||||
assert result.status == 'needs_review'
|
||||
assert 'order_field_page_value_conflict' in result.issues
|
||||
|
||||
|
||||
def test_missing_page_evidence_and_anchor_fail_closed():
|
||||
"""没有整页坐标或找不到标签时均不可用,禁止退回表格/绝对坐标猜值。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
no_page = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence={'pages': {'1': {'width': 200, 'height': 200}}})[0]
|
||||
no_anchor = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('ORDER 1', 20, 20))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:两种证据缺口都没有可用值。
|
||||
assert no_page.status == 'unavailable'
|
||||
assert no_anchor.status == 'unavailable'
|
||||
|
||||
|
||||
def test_fallback_and_ocr_never_become_confirmed():
|
||||
"""无锚点固定区和 OCR 字符均只可生成待复核候选。"""
|
||||
fallback = _profile(layout={
|
||||
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2},
|
||||
})
|
||||
fallback_result = extract_order_fields(profile=fallback, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('45001', 30, 20))},
|
||||
))[0]
|
||||
anchored = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO', 'minimum_evidence_level': 'ocr_coordinate'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'minimum_evidence_level': 'ocr_coordinate',
|
||||
})
|
||||
ocr_result = extract_order_fields(profile=anchored, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('PO NO 45001', 20, 20))}, source='ocr_coordinate',
|
||||
))[0]
|
||||
|
||||
# 关键断言:低可靠度模式与 OCR 必须保留人工复核状态。
|
||||
assert fallback_result.status == 'needs_review'
|
||||
assert ocr_result.status == 'needs_review'
|
||||
|
||||
|
||||
def test_multiline_stops_at_next_label_and_type_failure_requires_review():
|
||||
"""地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。"""
|
||||
address = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
'value_region': {'x0': 0, 'y0': 1.1, 'x1': 5, 'y1': 5}, 'value_mode': 'multi_line',
|
||||
'stop_anchors': [{'anchor_id': 'ship_to', 'text': 'SHIP TO'}],
|
||||
})
|
||||
address_result = extract_order_fields(profile=address, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('BILL TO', 20, 20), ('ABC COMPANY', 20, 34), ('ROAD 1', 20, 46), ('SHIP TO NEXT', 20, 60))},
|
||||
))[0]
|
||||
date = _profile(layout={
|
||||
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
date_result = extract_order_fields(profile=date, schema_fields=_schema(value_type='date', validator_keys=['iso_date']), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('DATE invalid', 20, 20))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:地址不包含下一个区块,错误类型值不作为正式结果。
|
||||
assert address_result.value == 'ABC COMPANY\nROAD 1'
|
||||
assert date_result.status == 'needs_review'
|
||||
assert date_result.issues == ['order_field_normalization_failed']
|
||||
|
||||
|
||||
def test_common_purchase_order_slash_date_is_normalized():
|
||||
"""美式订单日期应进入受控日期类型,而不是被误判为格式异常。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='order_date', value_type='date', validator_keys=['iso_date'],
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/20/2026', 20, 20))}))[0]
|
||||
|
||||
# 关键断言:运行期值保持 date 对象,后续 JSON 序列化统一输出 ISO 日期。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value.isoformat() == '2026-06-20'
|
||||
|
||||
|
||||
def test_date_recovers_one_glyph_just_outside_value_frame():
|
||||
"""关键断言:日期值框少一个字符宽时仅补紧邻末尾数字,避免候选无故消失。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
|
||||
# The right edge falls just before the final ``6`` of 06/20/2026.
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.73, 'y1': 1},
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='order_date', value_type='date', validator_keys=['iso_date'],
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/20/2026', 20, 20))}))[0]
|
||||
|
||||
# 断言仅相邻一个字宽的末尾数字可恢复为完整的受控日期。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value.isoformat() == '2026-06-20'
|
||||
|
||||
|
||||
def test_right_of_anchor_recovers_a_customer_name_cut_off_by_value_frame():
|
||||
"""客户值框截在单词中间时,应跳过冒号并补全同一连续公司名称。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
# Right edge cuts ``Corporation`` before its last three characters.
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.5, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='bill_to_customer',
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs((
|
||||
'BILL TO: Inventec Corporation BILL ADDRESS: 66 Street', 20, 20,
|
||||
))}))[0]
|
||||
|
||||
# 关键断言:不能回传 ``: Inventec Corporati``,也不能吞入右侧地址字段。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'Inventec Corporation'
|
||||
|
||||
|
||||
def test_right_of_anchor_never_extends_from_customer_value_box_into_address():
|
||||
"""同一行客户和地址相邻时,客户值框不得扩展跨过词间隔。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
# This box already contains the full company name but ends before the address.
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 4.25, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(
|
||||
field_code='bill_to_customer',
|
||||
), coordinate_evidence=_evidence(pages={'1': _glyphs((
|
||||
'BILL TO: Inventec Corporation 66 Hou-Kang Street', 20, 20,
|
||||
))}))[0]
|
||||
|
||||
# 关键断言:框尾后的地址首字符必须因词间隔被拒绝,不能混入客户名称。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'Inventec Corporation'
|
||||
|
||||
|
||||
def test_multiline_stop_anchor_ignores_same_label_above_current_anchor():
|
||||
"""页眉或其他区块中位于当前锚点上方的停止标签,不能截断账款地址。"""
|
||||
address = _profile(layout={
|
||||
'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'},
|
||||
'value_region': {'x0': 0, 'y0': 1.1, 'x1': 5, 'y1': 5}, 'value_mode': 'multi_line',
|
||||
'stop_anchors': [{'anchor_id': 'ship_to', 'text': 'SHIP TO'}],
|
||||
})
|
||||
result = extract_order_fields(profile=address, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(
|
||||
('SHIP TO HEADER', 20, 8), ('BILL TO', 20, 30), ('ABC COMPANY', 20, 44),
|
||||
('ROAD 1', 20, 56), ('SHIP TO NEXT', 20, 72),
|
||||
)},
|
||||
))[0]
|
||||
|
||||
# 关键断言:只以当前 BILL TO 后的 SHIP TO 作为停止条件。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'ABC COMPANY\nROAD 1'
|
||||
|
||||
|
||||
def test_page_ocr_character_builder_preserves_page_coordinates_without_native_fallback():
|
||||
"""扫描页 OCR 仅在原生字符缺失时可生成页级证据,空白字符不应成为可选锚点。"""
|
||||
class _Box:
|
||||
x0, y0, x1, y1 = 10, 20, 30, 28
|
||||
|
||||
class _Line:
|
||||
text, bbox = 'PO 1', _Box()
|
||||
|
||||
glyphs = _ocr_page_characters([_Line()])
|
||||
|
||||
# 关键断言:OCR 字符保留原页 y 坐标且剔除空白,供后续明确标为 ocr_coordinate。
|
||||
assert [item['text'] for item in glyphs] == ['P', 'O', '1']
|
||||
assert glyphs[0]['bbox']['y0'] == 20
|
||||
|
||||
|
||||
def test_quality_gate_rejects_unavailable_or_low_reliability_order_field_candidates():
|
||||
"""盲测必须将订单字段的锚点缺失和固定坐标回退标为失败,而不是只核对明细行。"""
|
||||
anchored = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
missing = _order_field_quality_failures(
|
||||
parser=anchored, schema_fields=_schema(), sample_id=7,
|
||||
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('ORDER 1', 20, 20))})}, expected_values={'customer_po': '45001'},
|
||||
)
|
||||
fallback = _profile(layout={'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2}})
|
||||
low_reliability = _order_field_quality_failures(
|
||||
parser=fallback, schema_fields=_schema(), sample_id=8,
|
||||
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('45001', 30, 20))})}, expected_values={'customer_po': '45001'},
|
||||
)
|
||||
|
||||
# 关键断言:没有 confirmed 证据的订单字段阻断盲测凭证。
|
||||
assert missing == ['sample:7:order_field:customer_po:unavailable']
|
||||
assert low_reliability == ['sample:8:order_field:customer_po:needs_review']
|
||||
|
||||
|
||||
def test_quality_gate_compares_confirmed_order_field_value_with_human_truth():
|
||||
"""状态为 confirmed 仍必须逐字段等于人工真值,防止读到错误但格式合法的 PO。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
failures = _order_field_quality_failures(
|
||||
parser=profile, schema_fields=_schema(), sample_id=9,
|
||||
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('PO NO 45001', 20, 20))})},
|
||||
expected_values={'customer_po': '45002'},
|
||||
)
|
||||
|
||||
# 关键断言:格式合法但与人工真值不同的字段必须阻断盲测。
|
||||
assert failures == ['sample:9:order_field:customer_po:mismatch']
|
||||
|
||||
|
||||
def test_quality_gate_normalizes_order_field_truth_before_comparison():
|
||||
"""JSON 盲测真值的日期字符串须按冻结 Schema 规范化后再与提取值比较。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
})
|
||||
schema = _schema(field_code='order_date', value_type='date', validator_keys=['iso_date'])
|
||||
profile.order_field_layouts[0].field_code = 'order_date'
|
||||
failures = _order_field_quality_failures(
|
||||
parser=profile, schema_fields=schema, sample_id=10,
|
||||
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('DATE 2026-08-01', 20, 20))})},
|
||||
expected_values={'order_date': '2026-08-01'},
|
||||
)
|
||||
|
||||
# 关键断言:同一日期的 JSON 字符串与运行时 date 对象不应产生伪 mismatch。
|
||||
assert failures == []
|
||||
|
||||
|
||||
def test_deterministic_order_merges_confirmed_order_field_and_required_header_gate():
|
||||
"""确定性建单将独立 confirmed 字段合并为 Header,并用它满足必填订单字段。"""
|
||||
order = _build_approved_profile_order(
|
||||
unit=type('Unit', (), {'document_id': 42})(), intake={'intake_no': 'SNI-1'},
|
||||
schema={'schema_version_id': 1, 'checksum': 'a' * 64},
|
||||
definition={'fields': [
|
||||
{'field_id': 'po-id', 'field_code': 'customer_po', 'scope': 'header', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'},
|
||||
]},
|
||||
table={'rows': [{'status': 'parsed', 'issues': [], 'fields': [{'field_id': 'qty-id', 'value': 3, 'quote': '3'}]}]},
|
||||
confirmed_order_fields=[{
|
||||
'field_id': 'po-id', 'value': '45001', 'page_no': 1, 'source': 'pdf_coordinate',
|
||||
'anchor_bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
|
||||
'value_bbox': {'x0': 25, 'y0': 10, 'x1': 50, 'y1': 20}, 'glyph_indices': [4, 5, 6],
|
||||
}],
|
||||
)
|
||||
|
||||
# 关键断言:订单字段与明细字段严格分域后仍可在最终订单 Header 合并。
|
||||
assert order is not None
|
||||
assert {field['field_id'] for field in order['header_fields']} == {'po-id'}
|
||||
assert order['header_fields'][0]['observations'][0]['layout_evidence']['page_no'] == 1
|
||||
|
||||
|
||||
def test_provider_omission_is_merged_but_override_of_confirmed_order_field_is_rejected(monkeypatch):
|
||||
"""Dify 不接收 confirmed 字段可省略;若自行返回冲突值,HXOPS 必须拒绝。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._confirmed_profile_order_fields',
|
||||
lambda _run, unit: [{'field_id': 'po-id', 'value': '45001'}],
|
||||
)
|
||||
unit = type('Unit', (), {'document_id': 42})()
|
||||
omitted = [{'header_fields': []}]
|
||||
merged = _merge_confirmed_profile_order_fields(object(), unit=unit, orders=omitted)
|
||||
field = merged[0]['header_fields'][0]
|
||||
assert field['field_id'] == 'po-id'
|
||||
assert field['observations'][0]['value'] == '45001'
|
||||
assert field['_hxops_order_field_evidence'] is True
|
||||
assert merged[0]['_hxops_order_field_evidence'] is True
|
||||
invalid = [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'DIFF'}]}]}]
|
||||
|
||||
# 关键断言:模型不可覆盖模板已确认的订单字段。
|
||||
try:
|
||||
_merge_confirmed_profile_order_fields(object(), unit=unit, orders=invalid)
|
||||
except ValidationError as error:
|
||||
assert error.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
else:
|
||||
raise AssertionError('confirmed order field override must be rejected')
|
||||
@@ -52,3 +52,22 @@ def test_profile_matcher_requires_optional_score_threshold():
|
||||
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
|
||||
assert result.status == 'no_match'
|
||||
|
||||
|
||||
def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
|
||||
"""模板静态锚点可位于表格外,必须从页级冻结证据匹配而非只读表内字符。"""
|
||||
layout = _layout('LINE ITEMS')
|
||||
layout['coordinate_evidence']['page_glyphs'] = {'1': [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate('PURCHASE ORDER')
|
||||
]}
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
|
||||
|
||||
# 关键断言:订单字段模板不再要求业务锚点错误地落在明细表格中。
|
||||
assert result.status == 'unique_match'
|
||||
|
||||
|
||||
def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence():
|
||||
"""缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。"""
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match'
|
||||
@@ -340,6 +340,42 @@ def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]:
|
||||
return int(intake.id), [body, pdf], int(user.id)
|
||||
|
||||
|
||||
def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_marked_only(app):
|
||||
"""确认订单字段必须保留坐标元数据;未经过 Workflow 注入的标记不得提升 Provider 证据。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
po = service.save_field({'field_code': 'customer_po', 'scope': 'header', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(po['id'], '客户 PO', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
coordinate = {
|
||||
'page_no': 1, 'source': 'pdf_coordinate',
|
||||
'anchor_bbox': {'x0': 10, 'y0': 10, 'x1': 30, 'y1': 20},
|
||||
'value_bbox': {'x0': 35, 'y0': 10, 'x1': 70, 'y1': 20},
|
||||
'glyph_indices': [4, 5, 6, 7, 8],
|
||||
}
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [{'field_id': po['id'], '_hxops_order_field_evidence': True, 'observations': [{
|
||||
'value': 'PO-100', 'document_id': documents[1].id, 'quote': 'PO-100',
|
||||
'layout_evidence': coordinate,
|
||||
}]}],
|
||||
'lines': [],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='o' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
observation = ShippingOrderFieldObservation.query.filter_by(
|
||||
extraction_id=result['extraction'].id, field_id=po['id'],
|
||||
).one()
|
||||
# 关键断言:最终记录可追溯到页号、锚点/值框与字符索引,而非 Provider 自报置信度。
|
||||
assert observation.evidence_verified is True
|
||||
assert observation.extractor == 'order_profile_order_field'
|
||||
assert observation.evidence_metadata_json == {'kind': 'order_field_coordinate', **coordinate}
|
||||
assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1'
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
"""同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -48,6 +48,37 @@ def test_rolling_verification_keeps_shortage_pending_and_later_releases_it(app):
|
||||
assert second.result_json['available_count'] == 1
|
||||
|
||||
|
||||
def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app):
|
||||
"""关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='quantity-authority')
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
db.session.commit()
|
||||
line = snapshot.lines[0]
|
||||
frozen_quantity = str(line.qty)
|
||||
result = {
|
||||
'reservation_id': line.reservation_id,
|
||||
'part_number': line.part_number,
|
||||
'required_qty': '1',
|
||||
'available_qty': '1',
|
||||
'line_status': 'ok',
|
||||
}
|
||||
|
||||
with pytest.raises(ValidationError) as quantity_error:
|
||||
record_inventory_verification(
|
||||
task, inventory_snapshot_id=None, source_config_version='v1', line_results=[result],
|
||||
)
|
||||
assert quantity_error.value.code == 'SHIPPING.RESERVATION_MISMATCH'
|
||||
db.session.rollback()
|
||||
|
||||
result['required_qty'] = frozen_quantity
|
||||
with pytest.raises(ValidationError) as duplicate_error:
|
||||
record_inventory_verification(
|
||||
task, inventory_snapshot_id=None, source_config_version='v1', line_results=[result, result.copy()],
|
||||
)
|
||||
assert duplicate_error.value.code == 'SHIPPING.RESERVATION_MISMATCH'
|
||||
|
||||
|
||||
def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app):
|
||||
"""A/B 首轮占用后,C 补货只能进入第二轮;首轮 Artifact 不得被覆盖或重复占用。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -18,7 +18,8 @@ from app.models import (
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
|
||||
from app.services.shipping_notice.upload_attempt_service import complete_attempt, start_rpa_attempt, void_rejected_artifact
|
||||
from app.services.shipping_notice.upload_attempt_service import complete_attempt, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
|
||||
|
||||
def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingReservation]:
|
||||
@@ -91,6 +92,57 @@ def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app):
|
||||
assert start_rpa_attempt(task, artifact_id=artifact.id).attempt_no == 2
|
||||
|
||||
|
||||
def test_timed_out_upload_is_frozen_until_reconciled(app):
|
||||
"""关键断言:回调超时不是失败,禁止重传;迟到成功或货代明确拒绝才可收口。"""
|
||||
with app.app_context():
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
mark_attempt_result_unknown(attempt)
|
||||
|
||||
with pytest.raises(ConflictError) as retry_error:
|
||||
start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key=attempt.idempotency_key)
|
||||
assert retry_error.value.code == 'SHIPPING.UPLOAD_RESULT_UNKNOWN'
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
|
||||
complete_attempt(attempt, success=True, callback_id='late-success', freight_ref_no='F-LATE')
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
|
||||
|
||||
|
||||
def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app):
|
||||
"""关键断言:未知结果只允许核对或凭回执收口,UI 不得暴露重试上传动作。"""
|
||||
with app.app_context():
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
mark_attempt_result_unknown(attempt)
|
||||
task.pending_human_reason = 'upload_result_unknown'
|
||||
task.upload_status = 'unknown'
|
||||
|
||||
state = resolve_task_ui_state(task)
|
||||
assert state.checkpoint == 'upload_result_unknown'
|
||||
assert state.human_options == ['refresh', 'download_excel', 'mark_manual_uploaded']
|
||||
assert 'retry_upload' not in state.human_options
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
|
||||
|
||||
def test_timed_out_upload_requires_explicit_rejection_before_release(app):
|
||||
"""关键断言:未知结果中的普通失败不释放预约单,明确拒绝并授权作废才允许恢复。"""
|
||||
with app.app_context():
|
||||
task, artifact, reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
mark_attempt_result_unknown(attempt)
|
||||
|
||||
complete_attempt(attempt, success=False, callback_id='late-network-error', error_message='network timeout')
|
||||
assert attempt.status == 'timed_out'
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading'
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
|
||||
complete_attempt(attempt, success=False, callback_id='late-freight-rejection', error_message='freight_rejected: invalid document')
|
||||
void_rejected_artifact(task, artifact_id=artifact.id, operator_id=1, reason='货代明确拒绝')
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'pending'
|
||||
|
||||
|
||||
def test_only_explicit_rejection_can_void_and_release_artifact(app):
|
||||
"""网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。"""
|
||||
with app.app_context():
|
||||
|
||||
Reference in new issue
Block a user