Files
syops/backend/tests/test_shipping_attachment_selection.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

709 lines
27 KiB
Python

"""
backend/tests/test_shipping_attachment_selection.py
用途:验证发送阶段附件选择计划只依赖快览事实,并能把计划摘要投影到 Run 响应。
依赖:pytest、纯函数 attachment_selection、订单抽取 Run 序列化服务。
逻辑:覆盖评分/排除/去重/首轮预算,以及 Run API 的 selection_plan 摘要输出。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot
from app.services.shipping_notice.order_extraction_plan import (
_snapshot_documents,
transition_order_extraction_unit,
)
from app.services.shipping_notice.order_extraction_runtime_snapshot import (
resolve_unit_runtime_snapshot,
)
from app.services.shipping_notice.order_extraction_snapshot_selection import (
has_attachment_catalog,
has_selected_attachments,
selected_attachment_keys_by_intake,
should_include_snapshot_document,
)
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
from app.services.shipping_notice.order_extraction_workspace_projection import (
serialize_workspace_run_documents,
)
def _preview_intake(intake_no: str, attachments: list[dict], *, subject: str = '', body_text: str = ''):
"""构造最小快览 Intake 假对象,避免测试选择计划时依赖数据库。"""
return SimpleNamespace(
intake_no=intake_no,
structured_result_json={
'email': {
'subject': subject,
'body_text': body_text,
'body_html_tables': [],
},
'attachments': attachments,
},
)
def test_attachment_selection_snapshot_materializes_all_budgeted_attachments_before_execution():
"""预算内业务附件均在首轮物化;执行并发 2 不得把第三份附件推入扩批。"""
snapshot = build_attachment_selection_snapshot(intakes=[
_preview_intake(
'SNI-A',
[
{
'attachment_key': 'po-1.pdf',
'filename': 'PO_451883815A.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'a' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'logo.png',
'filename': 'customer-logo.png',
'mime_type': 'image/png',
'size': 4096,
'content_hash': 'b' * 64,
'ready_for_extraction': False,
'is_inline_resource': True,
'catalog_reason': 'inline_resource',
},
{
'attachment_key': 'archive.zip',
'filename': 'orders.zip',
'mime_type': 'application/zip',
'size': 120000,
'content_hash': 'c' * 64,
'ready_for_extraction': False,
'catalog_reason': 'archive',
},
],
subject='PO 451883815A and booking details',
),
_preview_intake(
'SNI-B',
[
{
'attachment_key': 'po-1-duplicate.pdf',
'filename': 'PO_451883815A_copy.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'a' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'booking.xlsx',
'filename': 'booking_451883816.xlsx',
'mime_type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'size': 56000,
'content_hash': 'd' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'third.docx',
'filename': 'order_notes.docx',
'mime_type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'size': 42000,
'content_hash': 'e' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
],
body_text='Please process PO 451883816 first.',
),
])
assert snapshot['selection_version'] == 'shipping_notice_attachment_selection.v1'
# 内嵌签名资源不属于业务附件,不计入选择计划数量。
assert snapshot['total_attachment_count'] == 5
assert snapshot['eligible_attachment_count'] == 3
assert snapshot['selected_attachment_count'] == 3
assert snapshot['planned_attachment_count'] == 3
assert snapshot['pending_expansion_attachment_count'] == 0
assert snapshot['pending_expansion_batches'] == {}
selected = [item for item in snapshot['items'] if item['selected']]
assert [item['filename'] for item in selected] == [
'PO_451883815A.pdf',
'booking_451883816.xlsx',
'order_notes.docx',
]
by_name = {item['filename']: item for item in snapshot['items']}
assert by_name['PO_451883815A_copy.pdf']['skip_reason_codes'] == ['duplicate_content_hash']
assert 'customer-logo.png' not in by_name
assert by_name['orders.zip']['skip_reason_codes'] == ['catalog_reason:archive']
assert by_name['order_notes.docx']['skip_reason_codes'] == []
assert by_name['order_notes.docx']['selection_batch'] == 1
assert by_name['order_notes.docx']['planned_selection_batch'] is None
assert by_name['PO_451883815A.pdf']['group_key'] == '451883815A'
def test_attachment_selection_snapshot_stops_at_total_byte_budget():
"""累计深度解析字节超预算时,后续附件必须标记为预算停止而非静默扩批。"""
snapshot = build_attachment_selection_snapshot(
intakes=[_preview_intake('SNI-BYTE', [
{
'attachment_key': 'first.pdf', 'filename': 'first.pdf', 'mime_type': 'application/pdf',
'size': 20, 'content_hash': 'a' * 64, 'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'second.pdf', 'filename': 'second.pdf', 'mime_type': 'application/pdf',
'size': 20, 'content_hash': 'b' * 64, 'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
])],
max_total_bytes=30,
)
by_name = {item['filename']: item for item in snapshot['items']}
assert snapshot['planned_total_bytes'] == 20
assert by_name['first.pdf']['selected'] is True
assert by_name['second.pdf']['skip_reason_codes'] == ['budget_total_bytes']
def test_attachment_selection_snapshot_excludes_inline_resources_from_counts():
"""邮件签名图不属于用户业务附件,不能占用识别计划的附件数量或预算。"""
snapshot = build_attachment_selection_snapshot(intakes=[
_preview_intake(
'SNI-A',
[
{
'attachment_key': 'signature.gif',
'filename': 'signature.gif',
'mime_type': 'image/gif',
'size': 1024,
'content_hash': 'a' * 64,
'ready_for_extraction': False,
'is_inline_resource': True,
'catalog_reason': 'inline_resource',
},
{
'attachment_key': 'po-1.pdf',
'filename': 'PO_4518838152.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'b' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
{
'attachment_key': 'po-2.pdf',
'filename': 'PO_4518838154.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': 'c' * 64,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
},
],
),
])
assert snapshot['total_attachment_count'] == 2
assert snapshot['eligible_attachment_count'] == 2
assert snapshot['selected_attachment_count'] == 2
assert [item['filename'] for item in snapshot['items']] == [
'PO_4518838152.pdf', 'PO_4518838154.pdf',
]
def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypatch):
"""Run 用户态响应应暴露计划摘要计数,但不能泄露具体正文或打分细节。"""
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run',
lambda _run: {
'summary': {
'total_documents': 0,
'pending_documents': 0,
'processing_documents': 0,
'completed_documents': 0,
'review_required_documents': 0,
'failed_documents': 0,
'candidate_count': 0,
},
'current_activity': None,
'available_actions': ['view_details'],
},
)
run = SimpleNamespace(
run_no='SNER-SELECTION',
owner_agent_id=1,
conversation_id='conv-selection',
status='queued',
phase='queued',
schema_version_id=1,
attempt_count=0,
reparse_source=None,
superseding_run=None,
reparse_reason=None,
superseded_at=None,
result_json=None,
error_code=None,
created_at=None,
updated_at=None,
started_at=None,
finished_at=None,
extraction_plan=SimpleNamespace(units=[
SimpleNamespace(
selection_batch=1,
status='candidate_ready',
reason_code=None,
result_json={
'orders': [{
'lines': [{'fields': []}],
'conflicts': [{'reason': 'supplement_relation_ambiguous'}],
}],
},
retry_status='running',
technical_failure_reason_code=None,
),
SimpleNamespace(
selection_batch=1,
status='failed',
reason_code=None,
result_json=None,
retry_status='failed',
technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
),
SimpleNamespace(
selection_batch=2,
status='review_required',
reason_code='required_field_missing',
result_json={'orders': []},
retry_status='review_required',
technical_failure_reason_code=None,
),
]),
input_snapshot_json={
'schema': {
'version': 1,
'checksum': 'a' * 64,
'definition': {
'fields': [{'field_code': 'reservation_id', 'field_id': 'reservation-id'}],
},
},
'intakes': [{'intake_no': 'SNI-1'}],
'attachment_selection': {
'selection_version': 'shipping_notice_attachment_selection.v1',
'max_initial_attachments': 2,
'max_initial_concurrency': 2,
'expansion_batch_size': 2,
'max_total_attachments': 6,
'total_attachment_count': 5,
'eligible_attachment_count': 3,
'selected_attachment_count': 2,
'planned_attachment_count': 3,
'pending_expansion_attachment_count': 1,
'pending_expansion_batches': {'2': 1},
'group_count': 2,
'items': [
{'selected': True, 'selection_batch': 1, 'filename': 'must-not-leak.pdf', 'score': 999},
{'selected': True, 'selection_batch': 1},
{'selected': False, 'planned_selection_batch': 2, 'skip_reason_codes': []},
{'selected': False, 'skip_reason_codes': ['duplicate_content_hash']},
{'selected': False, 'skip_reason_codes': ['catalog_reason:inline_resource']},
],
},
},
)
payload = serialize_order_extraction_run(run)
assert payload['selection_plan'] == {
'selection_version': 'shipping_notice_attachment_selection.v1',
'max_initial_attachments': 2,
'max_initial_concurrency': 2,
'expansion_batch_size': 2,
'max_total_attachments': 6,
'max_total_bytes': 0,
'max_runtime_seconds': 0,
'input_total_bytes': 0,
'planned_total_bytes': 0,
'total_attachment_count': 5,
'eligible_attachment_count': 3,
'selected_attachment_count': 2,
'planned_attachment_count': 3,
'pending_expansion_attachment_count': 1,
'pending_expansion_batches': {'2': 1},
'skipped_attachment_count': 2,
'duplicate_attachment_count': 1,
'budget_limited_attachment_count': 0,
'group_count': 2,
}
assert payload['unit_summary'] == {
'total_units': 3,
'selected_units': 3,
'retrying_units': 1,
'pending_retry_units': 0,
'failed_units': 1,
'review_required_units': 1,
'succeeded_units': 0,
'selection_batches': {'1': 2, '2': 1},
'review_required_reason_codes': ['required_field_missing'],
'expansion_trigger_reason_codes': [
'missing_reservation_id',
'required_field_missing',
'supplement_relation_ambiguous',
],
'technical_failure_reason_codes': ['SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'],
}
assert 'must-not-leak' not in str(payload)
def test_snapshot_selection_helpers_keep_only_selected_attachment_documents():
"""Run snapshot 应只包含本次计划选中的附件,正文补充事实必须保留。"""
selection_snapshot = {
'total_attachment_count': 4,
'selected_attachment_count': 2,
'items': [
{'intake_no': 'SNI-A', 'attachment_key': 'po-1.pdf', 'selected': True},
{'intake_no': 'SNI-A', 'attachment_key': 'copy.pdf', 'selected': False},
{'intake_no': 'SNI-B', 'attachment_key': 'booking.xlsx', 'selected': True},
],
}
assert has_attachment_catalog(selection_snapshot) is True
assert has_selected_attachments(selection_snapshot) is True
assert selected_attachment_keys_by_intake(selection_snapshot) == {
'SNI-A': {'po-1.pdf'},
'SNI-B': {'booking.xlsx'},
}
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-A',
document_type='email_body',
attachment_key='body',
) is True
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-A',
document_type='attachment',
attachment_key='po-1.pdf',
) is True
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-A',
document_type='attachment',
attachment_key='copy.pdf',
) is False
def test_snapshot_selection_helpers_fall_back_to_all_documents_for_non_catalog_inputs():
"""普通单文件没有附件目录时,不应误把唯一文档过滤掉。"""
selection_snapshot = {'total_attachment_count': 0, 'selected_attachment_count': 0, 'items': []}
assert has_attachment_catalog(selection_snapshot) is False
assert has_selected_attachments(selection_snapshot) is False
assert should_include_snapshot_document(
selection_snapshot=selection_snapshot,
intake_no='SNI-FILE',
document_type='attachment',
attachment_key='file',
) is True
def test_snapshot_documents_include_selection_metadata():
"""计划编译应把选择批次、原因码、分组键和预算摘要映射到附件单元。"""
run = SimpleNamespace(
input_snapshot_json={
'attachment_selection': {
'max_initial_attachments': 2,
'max_initial_concurrency': 2,
'items': [
{
'intake_no': 'SNI-A',
'attachment_key': 'po-1.pdf',
'selected': True,
'selection_batch': 1,
'score_reasons': ['type_pdf', 'po_hint_detected'],
'group_key': '451883815A',
},
{
'intake_no': 'SNI-A',
'attachment_key': 'copy.pdf',
'selected': False,
'score_reasons': ['filename_copy_hint'],
'group_key': '451883815A',
},
],
},
'intakes': [{
'intake_id': 11,
'intake_no': 'SNI-A',
'documents': [
{
'document_id': 101,
'document_type': 'attachment',
'attachment_key': 'po-1.pdf',
'content_hash': 'a' * 64,
},
{
'document_id': 102,
'document_type': 'attachment',
'attachment_key': 'copy.pdf',
'content_hash': 'b' * 64,
},
],
}],
},
)
documents = _snapshot_documents(run)
assert documents[0]['selection_batch'] == 1
assert documents[0]['selection_reason_codes'] == ['type_pdf', 'po_hint_detected']
assert documents[0]['group_key'] == '451883815A'
assert documents[0]['budget_cost'] == {
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'expansion_batch_size': 0,
'max_total_attachments': 0,
'selected_in_batch': 1,
}
assert documents[1]['selection_batch'] is None
assert documents[1]['selection_reason_codes'] == ['filename_copy_hint']
def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(monkeypatch):
"""附件单元失败与重试时应更新 retry_status 和 technical_failure_reason_code。"""
audit_calls: list[dict] = []
monkeypatch.setattr(
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
lambda **kwargs: audit_calls.append(kwargs),
)
plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN'))
unit = SimpleNamespace(
id=1,
document_id=101,
status='pending',
attempt_count=0,
reason_code=None,
summary_json=None,
result_json=None,
error_code=None,
error_message=None,
last_activity_at=None,
started_at=None,
finished_at=None,
retry_status='not_started',
technical_failure_reason_code=None,
plan=plan,
)
plan.units = [unit]
transition_order_extraction_unit(unit, target_status='routing')
assert unit.retry_status == 'running'
assert unit.technical_failure_reason_code is None
transition_order_extraction_unit(
unit,
target_status='failed',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
error_message='timeout',
)
assert unit.retry_status == 'failed'
assert unit.technical_failure_reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
transition_order_extraction_unit(unit, target_status='pending')
assert unit.retry_status == 'pending_retry'
assert unit.technical_failure_reason_code is None
assert audit_calls
def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatch):
"""冻结快照已有 ready layout 时,Worker 不应回读当前 Document。"""
run = SimpleNamespace(
input_snapshot_json={
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'layout_snapshot': {
'status': 'ready',
'layout_candidate': {'pages': []},
'coordinate_evidence': {'pages': {}, 'page_glyphs': {}},
},
'layout_schema_candidates': [{'mapping_status': 'accepted'}],
}],
}],
},
)
unit = SimpleNamespace(intake_id=11, document_id=101)
monkeypatch.setattr('app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get', lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('should not query db')))
intake, document = resolve_unit_runtime_snapshot(run, unit)
assert intake['intake_id'] == 11
assert document['layout_snapshot']['status'] == 'ready'
assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted'}]
def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(monkeypatch):
"""Run 先创建后布局就绪时,Worker 应补读当前 ready layout 和 schema candidates。"""
run = SimpleNamespace(
input_snapshot_json={
'schema': {'definition': {'fields': []}},
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'layout_snapshot': {'status': 'queued'},
'layout_schema_candidates': [],
}],
}],
},
)
unit = SimpleNamespace(intake_id=11, document_id=101)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get',
lambda model, document_id: SimpleNamespace(
id=document_id,
asset_id=301,
filename='po-1.pdf',
current_layout_version=None,
),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot',
lambda document: {'status': 'ready', 'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]}},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.map_layout_document_to_schema',
lambda layout_candidate, contract: [{'mapping_status': 'accepted', 'issues': []}],
)
_intake, document = resolve_unit_runtime_snapshot(run, unit)
assert document['layout_snapshot']['status'] == 'ready'
assert document['layout_schema_candidates'] == [{'mapping_status': 'accepted', 'issues': []}]
def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch):
"""工作台文档详情应直接暴露单元选择、预算和失败事实。"""
run = SimpleNamespace(
id=1,
status='processing',
auto_freeze_policy_json=None,
input_snapshot_json={
'schema': {'definition': {'fields': []}},
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'document_type': 'attachment',
'filename': 'po-1.pdf',
}],
}],
},
extraction_plan=SimpleNamespace(units=[SimpleNamespace(
id=7,
document_id=101,
created_at=None,
status='failed',
reason_code=None,
selection_batch=1,
group_key='451883815A',
retry_status='failed',
technical_failure_reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
budget_cost_json={
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'selected_in_batch': 1,
},
result_json={},
cancellation_requested_at=None,
cancellation_completed_at=None,
)]),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_route_decisions',
lambda _run: {},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
lambda _run: ({}, None),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_layout_document_events',
lambda _run: {},
)
items = serialize_workspace_run_documents(run)
item = items[0]
assert item['unit_id'] == 7
assert item['document_id'] == 101
assert item['file_name'] == 'po-1.pdf'
assert item['status'] == 'failed'
assert item['selection_batch'] == 1
assert item['group_key'] == '451883815A'
assert item['retry_status'] == 'failed'
assert item['technical_failure_reason_code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
assert item['budget_cost'] == {
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'selected_in_batch': 1,
}
assert item['reason_code'] == 'technical_failure'
assert item['review_details'] == []
assert item['available_actions'] == ['view_details']
assert item['activity_event_code'] is None
assert item['started_at'] is None
assert item['last_activity_at'] is None
assert item['finished_at'] is None
def test_workspace_documents_show_selected_pdfs_while_layout_is_pending(monkeypatch):
"""等待版面解析时仍返回已选 PDF,避免处理详情误报“暂无结果”。"""
run = SimpleNamespace(
id=1,
status='processing',
error_code=None,
created_at=None,
finished_at=None,
last_activity_at=None,
phase='waiting_layout',
input_snapshot_json={
'attachment_selection': {
'items': [{
'selected': True,
'filename': 'po-pending.pdf',
'content_hash': 'pending-hash',
'selection_batch': 1,
'group_key': 'PO-PENDING',
}],
},
'intakes': [{
'intake_id': 11,
'documents': [{
'document_id': 101,
'document_type': 'attachment',
'filename': 'po-pending.pdf',
'content_hash': 'pending-hash',
}],
}],
},
extraction_plan=None,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
lambda _run: ({}, None),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection._latest_layout_document_events',
lambda _run: {},
)
items = serialize_workspace_run_documents(run)
# 关键断言:Unit 延后创建时,用户仍能看到正在等待版面解析的具体 PDF。
assert items[0]['file_name'] == 'po-pending.pdf'
assert items[0]['status'] == 'pending'
assert items[0]['document_id'] == 101
assert items[0]['activity_event_code'] is None