feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力

This commit is contained in:
hugo committed 2026-07-27 09:11:25 +08:00
1 parent d62f5107b2
commit 93777fd6df
63 files changed
+9707 -1491

No files matched your search

+180 -1
View File
@@ -39,7 +39,7 @@ from app.services.admin.agent_service import update_agent_permissions
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.admin.agent_service import list_agents
from app.services.shipping_notice.order_extraction_workflow import (
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
_cross_page_anchor_matches, build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
parse_order_extraction_workflow_result, validate_unit_orders,
)
from app.services.shipping_notice.order_extraction_run_service import (
@@ -51,6 +51,31 @@ from app.services.shipping_notice.order_extraction_run_service import (
from tests.test_shipping_order_extraction_runs import _seed_run_input
def test_cross_page_coordinate_continuation_requires_frozen_relation_anchor_and_region():
"""续页锚点须在声明区域命中;整页出现相同文本不足以授权跨页合并。"""
profile = {'definition': {'document_match': {'required_anchors': [{
'anchor_id': 'continued', 'text': 'CONTINUED', 'match_mode': 'exact',
'region': {'x0': 0, 'y0': 0, 'x1': .5, 'y1': .5},
}]}}}
layout = {'coordinate_evidence': {
'tables': {'page-two': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate('CONTINUED')
]},
'pages': {'2': {'width': 200, 'height': 200}},
}}
assert _cross_page_anchor_matches(
raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout,
anchor_ids=['continued'],
) is True
profile['definition']['document_match']['required_anchors'][0]['region'] = {'x0': .5, 'y0': .5, 'x1': 1, 'y1': 1}
assert _cross_page_anchor_matches(
raw_profile=profile, raw_table={'table_id': 'page-two', 'page_no': 2}, layout=layout,
anchor_ids=['continued'],
) is False
def test_binding_rejects_non_internal_or_non_workflow_provider(app):
"""订单抽取 Provider 必须是启用的 internal Dify Workflow,不能绑定普通 Chatflow。"""
with app.app_context():
@@ -757,6 +782,160 @@ def test_approved_profile_builds_order_from_its_own_parsed_rows(app):
assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30
def test_coordinate_v2_profile_builds_from_frozen_coordinates_without_html(app):
"""v2 运行只消费冻结 bbox/字符证据;MinerU HTML 缺失也不得回退为固定列解析。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-V2')
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
version.definition_json = {'fields': [
{
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal',
'enabled': True, 'required': True, 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
},
{
'field_id': 'uom-id', 'field_code': 'uom', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
]}
def glyphs() -> list[dict]:
values = []
for text, x0 in [('00010', 10), ('PART-A', 90), ('3 EA', 210)]:
for offset, char in enumerate(text):
values.append({'text': char, 'bbox': {
'x0': x0 + offset * 4, 'y0': 20, 'x1': x0 + offset * 4 + 3, 'y1': 30,
}})
return values
definition = {
'contract_version': 'order_coordinate_profile.v2',
'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .3, 'y0': 0, 'x1': .7, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'qty-id', 'field_code': 'qty', 'extractor_key': 'quantity_uom', 'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}, {'field_id': 'uom-id', 'field_code': 'uom'}], 'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number', 'qty', 'uom'], 'allowed_empty_fields': [],
}],
}],
}
profile = ShippingOrderDocumentProfile(
profile_code='COORDINATE_V2', display_name='Coordinate v2', version=1, status='published',
schema_version_id=version.id, structure_fingerprint='c' * 64, checksum='d' * 64,
definition_json=definition, published_at=datetime.utcnow(),
)
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'coordinate-only', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 300, 'y1': 60}}],
'coordinate_evidence': {
'tables': {'coordinate-only': glyphs()},
'pages': {'1': {'width': 300, 'height': 60}},
},
})
db.session.add(profile)
db.session.commit()
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
unit = run.extraction_plan.units[0]
run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True
from app.services.shipping_notice.order_extraction_workflow import (
_build_approved_profile_order,
_profile_table_candidates,
build_deterministic_unit_orders,
)
candidates = _profile_table_candidates(run, unit=unit)
assert candidates['blocking'] is False, candidates
assert candidates['tables'] and candidates['tables'][0]['auto_create_approved'] is True, candidates
direct = _build_approved_profile_order(
unit=unit, intake=run.input_snapshot_json['intakes'][0],
schema=run.input_snapshot_json['schema']['extraction_contract'],
definition=run.input_snapshot_json['schema']['definition'], table=candidates['tables'][0],
)
assert direct is not None, candidates
orders = build_deterministic_unit_orders(run, unit=unit)
assert orders is not None
fields = {field['field_id']: field['observations'][0]['value'] for field in orders[0]['lines'][0]['fields']}
assert fields == {'line-id': '00010', 'part-id': 'PART-A', 'qty-id': 3, 'uom-id': 'EA'}
def test_coordinate_v2_profile_uses_page_relative_regions_not_table_bbox(app):
"""画布保存整页相对区域;运行时不得再按 MinerU 表格 bbox 二次缩放。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='COORDINATE-PAGE-SPACE')
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
version.definition_json = {'fields': [
{
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': False, 'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': [],
},
]}
profile = ShippingOrderDocumentProfile(
profile_code='COORDINATE_PAGE_SPACE', display_name='Coordinate page space', version=1, status='published',
schema_version_id=version.id, structure_fingerprint='e' * 64, checksum='f' * 64,
definition_json={
'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
# This real canvas region is page-relative (x=20..80 on a 200pt page),
# while MinerU's table bbox begins at x=50 and must not offset it again.
'region': {'x0': .1, 'y0': .4, 'x1': .4, 'y1': .6},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'line_no', 'target_fields': [{'field_id': 'line-id', 'field_code': 'line_no'}], 'region': {'x0': .1, 'y0': .4, 'x1': .2, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}], 'region': {'x0': .2, 'y0': .4, 'x1': .4, 'y1': .6}, 'allowed_sources': ['pdf_coordinate']},
], 'continuation_conditions': [], 'required_fields': ['line_no', 'part_number'], 'allowed_empty_fields': [],
}],
}],
}, published_at=datetime.utcnow(),
)
glyphs = []
for text, x0 in [('00010', 22), ('PART-PAGE', 45)]:
for offset, char in enumerate(text):
glyphs.append({'text': char, 'bbox': {'x0': x0 + offset * 4, 'y0': 90, 'x1': x0 + offset * 4 + 3, 'y1': 100}})
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'offset-table', 'page_no': 1, 'bbox': {'x0': 50, 'y0': 70, 'x1': 160, 'y1': 140}}],
'coordinate_evidence': {'tables': {'offset-table': glyphs}, 'pages': {'1': {'width': 200, 'height': 200}}},
})
db.session.add(profile)
db.session.commit()
run, _ = create_order_extraction_run(user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no])
unit = run.extraction_plan.units[0]
run.input_snapshot_json['order_document_profiles'][0]['auto_create_approved'] = True
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
orders = build_deterministic_unit_orders(run, unit=unit)
assert orders is not None
values = {
field['field_id']: field['observations'][0]['value']
for field in orders[0]['lines'][0]['fields']
}
assert values['part-id'] == 'PART-PAGE'
def test_plain_text_complete_table_still_uses_provider(app):
"""纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。"""
with app.app_context():