Files
syops/backend/tests/test_shipping_pdf_automark.py
T
hugo 1e5aedb9ed feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
2026-08-26 02:47:07 +08:00

853 lines
43 KiB
Python

"""
tests/test_shipping_pdf_automark.py
用途:验证统一 PDF 自动标记 Job 对不同 PDF 能力输出同一候选契约。
依赖:order_document_profile_pdf_automark_service、pytest mock。
逻辑:普通 PDF 复用坐标重建与 OCR 回退;XFA 复用多源融合执行器,但调用方不传类型。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from app.core.errors import ValidationError
from app.services.shipping_notice.order_document_profile_pdf_automark_service import (
_acroform_widget_candidates,
_fuse_header_regions_with_column_geometry,
enqueue_pdf_automark,
execute_pdf_automark_job,
)
pytestmark = pytest.mark.pure_unit
def test_header_text_is_projected_onto_widget_column_geometry():
"""表头文字与 Widget 列框融合后,画布必须得到可确认的每列表头框。"""
geometry = {
'table_region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .8},
'subrow_layouts': [{'column_boundaries': [0, .2, .7, 1]}],
'header_regions': [],
}
text = {
'header_regions': [{
'text': 'ITEM PARTS & DESCRIPTION QTY',
'region': {'x0': .1, 'y0': .22, 'x1': .9, 'y1': .28},
'fields': [
{'text': 'ITEM', 'field_code': 'line_no', 'region': {'x0': .11, 'y0': .22, 'x1': .18, 'y1': .28}},
{'text': 'PARTS & DESCRIPTION', 'field_code': 'part_number', 'region': {'x0': .29, 'y0': .22, 'x1': .63, 'y1': .28}},
{'text': 'QTY', 'field_code': 'quantity', 'region': {'x0': .76, 'y0': .22, 'x1': .82, 'y1': .28}},
],
}],
}
fused = _fuse_header_regions_with_column_geometry(
geometry, geometry_source='acroform_widget_geometry',
text_reconstructions=[('pdf_coordinate', text)],
)
fields = fused['header_regions'][0]['fields']
assert [(item['text'], item['field_code'], item['region']) for item in fields] == [
('ITEM', 'line_no', {'x0': .1, 'y0': .22, 'x1': .26, 'y1': .28}),
('PARTS & DESCRIPTION', 'part_number', {'x0': .26, 'y0': .22, 'x1': .66, 'y1': .28}),
('QTY', 'quantity', {'x0': .66, 'y0': .22, 'x1': .9, 'y1': .28}),
]
assert all(item['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate'] for item in fields)
assert fields[0]['observations'] == [{
'source': 'pdf_coordinate', 'text': 'ITEM', 'field_code': 'line_no',
'region': {'x0': .11, 'y0': .22, 'x1': .18, 'y1': .28},
}]
def test_header_geometry_keeps_unmapped_text_unbound():
"""视觉文字没有唯一 Schema 映射时只补框,禁止按列位置猜字段编码。"""
geometry = {
'table_region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .8},
'subrow_layouts': [{'column_boundaries': [0, .5, 1]}],
'header_regions': [],
}
text = {'header_regions': [{
'region': {'x0': 0, 'y0': .22, 'x1': 1, 'y1': .28},
'fields': [{'text': 'UNRECOGNIZED', 'field_code': None, 'region': {'x0': .1, 'y0': .22, 'x1': .4, 'y1': .28}}],
}]}
fused = _fuse_header_regions_with_column_geometry(
geometry, geometry_source='opencv_geometry', text_reconstructions=[('ocr_coordinate', text)],
)
assert fused['header_regions'][0]['fields'][0]['field_code'] is None
def test_enqueue_automark_requires_frozen_annotation_layout(monkeypatch):
"""关键断言:自动标注不能在无冻结 Layout 的样本上生成可接受候选。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
monkeypatch.setattr(service.db.session, 'get', lambda model, ident: None)
monkeypatch.setattr(
service, 'ShippingOrderDocumentProfileSample',
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(first=lambda: None),
),
)),
)
with pytest.raises(Exception) as caught:
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND'
def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_changed(monkeypatch):
"""关键断言:Layout 版本未变但内容快照已替换时,不能继续生成旧候选 Job。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
annotation = SimpleNamespace(id=71, document_id=77, table_id='table-1')
document = SimpleNamespace(
id=77,
current_layout_version_id=88,
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
)
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
monkeypatch.setattr(
service, 'ShippingOrderDocumentProfileSample',
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(first=lambda: annotation),
),
)),
)
monkeypatch.setattr(
service.db.session,
'get',
lambda model, _ident: document if model is service.ShippingOrderDocument else None,
)
from app.services.shipping_notice import order_document_profile_service as profile_service
monkeypatch.setattr(
profile_service,
'require_profile_sample_automark_ready',
lambda **_kwargs: (_ for _ in ()).throw(ValidationError(
'Profile sample layout is stale',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE',
)),
)
monkeypatch.setattr(service, 'enqueue', lambda *_args, **_kwargs: 9001)
with pytest.raises(ValidationError) as caught:
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
# Layout 身份不一致必须使用可操作的 stale 错误码,不能退化为泛化配置错误。
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE'
def test_execute_automark_rejects_job_after_document_layout_reparse(monkeypatch):
"""关键断言:排队期间 Layout 重解析后,旧 Job 不得生成可被确认的视觉候选。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
current_document = SimpleNamespace(id=77, current_layout_version_id=99)
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
monkeypatch.setattr(
service.db.session,
'get',
lambda model, _ident: current_document if model is service.ShippingOrderDocument else None,
)
with pytest.raises(service.PdfAutomarkError) as caught:
execute_pdf_automark_job({
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
})
assert caught.value.error_code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE'
def test_execute_automark_rejects_job_with_layout_checksum_mismatch(monkeypatch):
"""关键断言:同一 Layout 版本但冻结快照 checksum 不一致时也必须失败关闭。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
current_document = SimpleNamespace(
id=77,
current_layout_version_id=88,
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
)
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
monkeypatch.setattr(
service.db.session,
'get',
lambda model, _ident: current_document if model is service.ShippingOrderDocument else None,
)
with pytest.raises(service.PdfAutomarkError) as caught:
execute_pdf_automark_job({
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
})
assert caught.value.error_code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE'
def test_automark_handler_persists_layout_stale_code_for_workbench_recovery(monkeypatch):
"""关键断言:Worker 必须原样持久化 Layout 失效码,供统一画布提示重新标记。"""
from app.jobs.handlers import shipping_pdf_automark as handler
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
job = SimpleNamespace(id=9001, attempts=1, payload_json={
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
})
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _job_id: job)
monkeypatch.setattr(
service,
'execute_pdf_automark_job',
lambda _payload: (_ for _ in ()).throw(service.PdfAutomarkError(
'layout changed',
error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE',
)),
)
failed: dict[str, object] = {}
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **kwargs: failed.update(kwargs))
handler.run_shipping_pdf_automark(SimpleNamespace(), {'job_id': 9001})
assert failed['retryable'] is False
assert failed['result'] == {
'status': 'failed',
'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE',
'details': {},
}
def test_opencv_reconstruction_projects_only_data_rows(monkeypatch):
"""关键断言:冻结 Layout 的 header/summary 只能作证据,不能伪造成明细行。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
layout = {
'layout_candidate': {
'quality': {'issues': [{'code': 'native_pdf_cells_from_opencv_candidate'}]},
'pages': [{
'page_no': 1,
'tables': [{
'table_id': 'table-1',
'normalized_bbox': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'rows': [
{'row_index': 0, 'role': 'header', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}}]},
{'row_index': 1, 'role': 'data', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .2}, 'text': 'A'}]},
{'row_index': 2, 'role': 'summary', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'text': 'TOTAL'}]},
],
}],
}],
},
}
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._document_layout',
lambda _document: layout,
)
monkeypatch.setattr(service.db.session, 'get', lambda model, ident: object())
result = service._layout_opencv_reconstruction(document_id=77, table_id='table-1')
assert result is not None
assert [item['row_offset'] for item in result['subrow_layouts']] == [0]
assert result['subrow_layouts'][0]['source_row_index'] == 1
def test_coordinate_pdf_automark_retries_with_ocr_and_returns_candidates():
"""关键断言:普通 PDF 在坐标不足时由统一 Job 触发 OCR 后仍返回 candidates[]。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
reconstruction = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
fields = {'order_field_candidates': [], 'page_no': 1}
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.side_effect = [
ValidationError('missing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
reconstruction,
]
coordinate.suggest_order_field_layouts.return_value = fields
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
), patch(
'app.services.shipping_notice.order_document_profile_service',
coordinate,
create=True,
):
# execute 函数内部延迟导入,直接替换模块缓存中的服务对象。
with patch.dict('sys.modules', {
'app.services.shipping_notice.order_document_profile_service': coordinate,
}):
result = execute_pdf_automark_job({
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'schema_version_id': 3, 'page_no': 1,
})
assert result['kind'] == 'field_binding_candidates'
assert [item['candidate_kind'] for item in result['candidates']] == ['table_reconstruction']
assert result['diagnostics']['coordinate_reconstruction'] == reconstruction
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
document_id=77, table_id='table-1', actor_id=None, force_ocr=True,
)
def test_xfa_pdf_automark_reuses_the_shared_visual_executor():
"""关键断言:XFA 只在确认后的正式值映射不同,自动标记仍走共享视觉执行器。"""
profile = SimpleNamespace(
template_mode='xfa_dataset',
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
status='draft',
)
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
coordinate.suggest_order_field_layouts.return_value = {
'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}],
}
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
coordinate.generate_ocr_coordinate_evidence,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table'})
assert result['kind'] == 'field_binding_candidates'
candidate = next(item for item in result['candidates'] if item['candidate_kind'] == 'field_binding')
assert candidate['candidate_kind'] == 'field_binding'
assert 'value_binding' not in candidate['binding']
assert result['diagnostics']['coordinate_reconstruction'] == {'subrow_layouts': []}
assert coordinate.suggest_coordinate_reconstruction.call_count == 2
def test_xfa_pdf_automark_keeps_header_candidates_when_visual_rows_need_review():
"""关键断言:视觉行重建为空不能丢弃已识别的抬头框,结果必须留在 needs_review。"""
profile = SimpleNamespace(
template_mode='xfa_dataset',
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
status='draft',
)
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.side_effect = [
ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID'),
ValidationError('OCR rows unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
]
coordinate.suggest_order_field_layouts.return_value = {
'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}],
}
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
coordinate.generate_ocr_coordinate_evidence,
):
result = execute_pdf_automark_job({
'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table', 'page_no': 1,
})
assert result['status'] == 'needs_review'
assert result['candidates'][0]['binding']['field_code'] == 'customer_po_no'
assert result['candidates'][0]['needs_review'] is True
assert result['diagnostics']['row_reconstruction']['error_code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'
def test_xfa_pdf_automark_retries_invalid_native_rows_with_forced_ocr():
"""关键断言:部分 native glyph 无法成行时,Job 必须强制 OCR 后再重建一次。"""
profile = SimpleNamespace(
template_mode='xfa_dataset',
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
status='draft',
)
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.side_effect = [
ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID'),
{'subrow_layouts': [{'row_offset': 0}], 'header_regions': []},
]
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'page_no': 1, 'source': 'ocr_coordinate',
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}]}
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
coordinate.generate_ocr_coordinate_evidence,
):
result = execute_pdf_automark_job({
'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table', 'page_no': 1,
})
# 自动标注只产生待确认的视觉候选;即使 OCR 已补全行框,也不能把 Job 结果标为可发布成功。
assert result['status'] == 'needs_review'
assert result['diagnostics']['coordinate_reconstruction']['subrow_layouts'] == [{'row_offset': 0}]
# OCR 重建后的候选不能声称已有 native 佐证;来源必须忠实反映本次实际证据。
assert result['candidates'][0]['evidence_sources'] == ['ocr_coordinate']
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
document_id=77, table_id='xfa-main-table', actor_id=None, force_ocr=True,
)
def test_xfa_pdf_automark_requires_the_frozen_visual_main_table():
"""关键断言:XFA 也不能绕过统一视觉主表契约执行自动标注。"""
profile = SimpleNamespace(
template_mode='xfa_dataset',
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
status='draft',
)
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
):
with pytest.raises(Exception) as caught:
execute_pdf_automark_job({'profile_id': 12, 'document_id': 77})
assert getattr(caught.value, 'error_code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
def test_coordinate_pdf_automark_returns_the_same_field_binding_candidate_contract():
"""关键断言:普通 PDF 也以 field_binding_candidates 返回,前端不按 PDF 类型分支保存。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
coordinate.suggest_order_field_layouts.return_value = {
'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}],
}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'page_no': 1})
assert result['kind'] == 'field_binding_candidates'
candidate = next(item for item in result['candidates'] if item['candidate_kind'] == 'field_binding')
assert candidate['candidate_kind'] == 'field_binding'
assert candidate['binding']['field_id'] == 'f-po'
# 自动标记只提出视觉框,最终值源由字段映射确认阶段选择。
assert 'value_binding' not in candidate['binding']
def test_automark_does_not_project_ambiguous_or_unavailable_fields_as_empty_boxes():
"""关键断言:未得到唯一值框的字段只能留在诊断,不能成为画布可确认候选。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
candidates = service._visual_binding_candidates({
'order_field_candidates': [
{'field_id': 'ambiguous', 'field_code': 'customer_po_no', 'status': 'ambiguous'},
{'field_id': 'unavailable', 'field_code': 'order_date', 'status': 'unavailable'},
{
'field_id': 'suggested', 'field_code': 'currency', 'status': 'suggested',
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
},
],
}, page_no=1)
assert [item['binding']['field_code'] for item in candidates] == ['currency']
assert candidates[0]['binding']['visual_binding']['normalized_bbox'] == {
'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4,
}
def test_automark_diagnostics_do_not_claim_unobserved_ocr_or_native_evidence():
"""关键断言:诊断只能列出实际候选来源,不能把可用的回退能力写成已取到的证据。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
coordinate.suggest_order_field_layouts.return_value = {
'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'source': 'pdf_coordinate',
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}],
}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
assert result['candidates'][0]['evidence_sources'] == ['pdf_coordinate']
assert result['diagnostics']['evidence_sources'] == ['pdf_coordinate']
def test_automark_keeps_native_and_ocr_table_reconstruction_candidates_in_parallel():
"""关键断言:原生行重建成功也必须保留同页 OCR 的独立候选,不以先成功者屏蔽另一证据。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
native = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
ocr = {'subrow_layouts': [{'row_offset': 0}, {'row_offset': 1}], 'header_regions': []}
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.side_effect = [native, ocr]
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
coordinate.generate_ocr_coordinate_evidence,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
table_candidates = [item for item in result['candidates'] if item['candidate_kind'] == 'table_reconstruction']
assert [item['evidence_sources'] for item in table_candidates] == [['pdf_coordinate'], ['ocr_coordinate']]
assert result['diagnostics']['coordinate_reconstruction'] == native
assert result['diagnostics']['conflicts'] == [{
'code': 'table_reconstruction_source_conflict',
'sources': ['pdf_coordinate', 'ocr_coordinate'],
}]
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
document_id=77, table_id='table-1', actor_id=None, force_ocr=True,
)
def test_automark_marks_consistent_multi_evidence_candidates_as_needing_review():
"""关键断言:多路视觉证据结构一致也只代表可复核候选,不能绕过人工确认。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
reconstruction = {'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}]}
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.side_effect = [reconstruction, reconstruction]
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no',
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}]}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
coordinate.generate_ocr_coordinate_evidence,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
assert result['status'] == 'needs_review'
assert result['diagnostics']['conflicts'] == []
assert all(item['needs_review'] is True for item in result['candidates'])
def test_automark_exposes_only_the_unified_pdf_job_type():
"""关键断言:XFA 不保留独立自动标记 Job 类型。"""
from app.jobs.types import JobType
assert JobType.SHIPPING_PDF_AUTOMARK.value == 'shipping_pdf_automark'
assert not hasattr(JobType, 'SHIPPING_XFA_OCR_AUTOMARK')
def test_automark_exposes_acroform_widget_as_independent_visual_candidate():
"""关键断言:Widget 只补充定位证据,不能替代 datasets 正式值绑定。"""
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header',
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}]}
widget = SimpleNamespace(widget_id='wgt-1', short_name='customer_po_number', page_no=1,
normalized_bbox={'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3})
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._acroform_widget_candidates',
return_value=[{
'candidate_id': 'widget-wgt-1', 'candidate_kind': 'field_binding',
'binding': {'field_code': 'customer_po_number', 'visual_binding': {'source': 'acroform_widget'}},
'evidence_sources': ['acroform_widget'], 'needs_review': True,
}],
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget'])
assert widget_candidate['needs_review'] is True
assert 'value_binding' not in widget_candidate['binding']
def test_automark_merges_same_field_same_geometry_sources():
"""关键断言:同字段同页同坐标的 PDF 与 Widget 候选只生成一个画布框。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
candidates = [
{
'candidate_id': 'pdf-1', 'candidate_kind': 'field_binding',
'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': {
'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}},
'evidence_sources': ['pdf_coordinate'], 'needs_review': True,
},
{
'candidate_id': 'widget-1', 'candidate_kind': 'field_binding',
'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': {
'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}},
'evidence_sources': ['acroform_widget'], 'needs_review': True,
},
]
merged = service._merge_duplicate_field_binding_candidates(candidates)
assert len(merged) == 1
assert merged[0]['evidence_sources'] == ['pdf_coordinate', 'acroform_widget']
def test_automark_keeps_unmatched_acroform_widget_as_unbound_visual_candidate(monkeypatch):
"""Widget 技术名未匹配 Schema 时仍可供人工框选,禁止自动猜业务字段。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
document = SimpleNamespace(asset_id=11)
asset = SimpleNamespace(id=11)
widget = SimpleNamespace(
widget_id='wgt-ebeln', short_name='EBELN', page_no=1,
normalized_bbox={'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3},
)
monkeypatch.setattr(service.db.session, 'get', lambda _model, ident: document if ident == 77 else asset)
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test')
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.xfa_acroform.read_acroform_widgets',
lambda _bytes: [widget],
)
candidates = _acroform_widget_candidates(
document_id=77,
fields={'order_field_candidates': []},
actor_id=1,
)
# 关键断言:只携带 Widget 几何和技术名,field_code 为空且不存在正式 value_binding。
assert candidates == [
{
'candidate_id': 'widget-unbound-wgt-ebeln',
'candidate_kind': 'field_binding',
'binding': {
'binding_id': 'widget-unbound-wgt-ebeln',
'field_id': '',
'field_code': '',
'display_name': 'EBELN',
'scope': 'header',
'visual_binding': {
'page_no': 1,
'normalized_bbox': {'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3},
'source': 'acroform_widget',
'status': 'suggested',
'confidence': 0.0,
'region_kind': 'field',
'widget_id': 'wgt-ebeln',
'widget_short_name': 'EBELN',
},
},
'evidence_sources': ['acroform_widget'],
'needs_review': True,
},
]
def test_automark_keeps_existing_opencv_layout_geometry_as_parallel_table_candidate():
"""关键断言:Layout 阶段已验收的 OpenCV 几何进入统一候选,但仍需人工确认。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
}
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
opencv = {'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .5, 1]}], 'header_regions': []}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._layout_opencv_reconstruction',
return_value=opencv,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
opencv_candidates = [item for item in result['candidates'] if item['evidence_sources'] == ['opencv_geometry']]
assert len(opencv_candidates) == 1
assert opencv_candidates[0]['needs_review'] is True
assert result['diagnostics']['evidence_sources'] == ['opencv_geometry', 'pdf_coordinate']
def test_automark_keeps_xfa_widget_geometry_as_parallel_table_candidate():
"""关键断言:动态 XFA 未绘制明细值时,Widget 几何可形成待确认行框但不能自动采值。"""
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
}
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
widget_geometry = {
'subrow_layouts': [{
'row_offset': 0, 'column_boundaries': [0, .2, .5, 1],
'column_samples': [],
}],
'header_regions': [], 'status': 'needs_review',
}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._xfa_widget_geometry_reconstruction',
return_value=widget_geometry,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget_geometry'])
assert widget_candidate['needs_review'] is True
assert widget_candidate['payload']['subrow_layouts'][0]['column_samples'] == []
def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
"""XFA 行框来自 Widget 时仍须把独立坐标表头补入同一候选,供画布生成 header_field。"""
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {
'subrow_layouts': [], 'header_regions': [],
}
coordinate.suggest_coordinate_header_reconstruction.return_value = {
'header_regions': [{
'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2},
'fields': [{'text': 'ITEM', 'field_code': 'line_no', 'region': {'x0': .11, 'y0': .15, 'x1': .18, 'y1': .2}}],
}],
}
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
widget_geometry = {
'table_region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .8},
# 动态 XFA 的表头控件有展示值时,Widget 聚类会把表头带误判为候选行。
'subrow_layouts': [{
'row_offset': 0, 'column_boundaries': [0, .25, 1],
'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2},
}],
'header_regions': [], 'status': 'needs_review',
}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_header_reconstruction',
coordinate.suggest_coordinate_header_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._xfa_widget_geometry_reconstruction',
return_value=widget_geometry,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget_geometry'])
field = widget_candidate['payload']['header_regions'][0]['fields'][0]
assert field['text'] == 'ITEM'
assert field['field_code'] == 'line_no'
assert field['region'] == {'x0': .1, 'y0': .15, 'x1': .3, 'y1': .2}
assert field['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate']
# 已确认的表头带不得同时作为可保存的 Widget 明细行。
assert widget_candidate['payload']['subrow_layouts'] == []
def test_automark_marks_opencv_and_native_structure_conflict_for_review():
"""关键断言:OpenCV 与 native 几何不一致时保留双方并记录冲突。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
}
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._layout_opencv_reconstruction',
return_value={'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .5, 1]}], 'header_regions': []},
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
assert result['status'] == 'needs_review'
assert result['diagnostics']['conflicts'] == [{
'code': 'table_reconstruction_source_conflict',
'sources': ['pdf_coordinate', 'opencv_geometry'],
}]
def test_automark_keeps_native_and_ocr_field_candidates_in_parallel():
"""关键断言:字段框与表格行一样保留 native/OCR 两路,不以 native 候选屏蔽 OCR。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': [], 'header_regions': []}
native_fields = {'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
'source': 'pdf_coordinate',
}]}
ocr_fields = {'order_field_candidates': [{
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
'absolute_value_region': {'x0': .12, 'y0': .2, 'x1': .32, 'y1': .4},
'source': 'ocr_coordinate',
}]}
coordinate.suggest_order_field_layouts.side_effect = [native_fields, ocr_fields]
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
coordinate.suggest_coordinate_reconstruction,
), patch(
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
coordinate.suggest_order_field_layouts,
), patch(
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
coordinate.generate_ocr_coordinate_evidence,
):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
fields = [item for item in result['candidates'] if item['candidate_kind'] == 'field_binding']
assert [item['evidence_sources'] for item in fields] == [['pdf_coordinate'], ['ocr_coordinate']]
assert result['diagnostics']['field_conflicts'] == [{
'code': 'field_binding_source_conflict',
'field_id': 'f-po',
'field_code': 'customer_po_no',
'scope': 'header',
'sources': ['pdf_coordinate', 'ocr_coordinate'],
}]