feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
hugo committed 2026-08-26 02:47:07 +08:00
1 parent 7cfd5d167e
commit 1e5aedb9ed
235 files changed
+11394 -9613

No files matched your search

@@ -30,6 +30,16 @@ from app.models import (
)
from app.services.shipping_notice import document_profile_quality_service as quality
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.file_assets import storage as file_asset_storage_module
@pytest.fixture(autouse=True)
def _memory_file_asset_storage(monkeypatch):
"""测试外置坐标证据使用内存对象,保持 FileAsset/MinIO 契约而不依赖服务。"""
objects: dict[str, bytes] = {}
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'upload_bytes', lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data)))
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'get_bytes', lambda storage_key: objects[storage_key])
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
@pytest.mark.parametrize(
@@ -52,8 +62,8 @@ def test_blind_test_order_field_comparison_rejects_different_values():
)
def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source():
"""盲测仅在模板显式启用自适应模式时改用整页字符,默认表格模式必须保持不变。"""
def test_quality_region_uses_page_glyphs_for_every_reconstruction_mode():
"""盲测与预览/正式解析必须从当前页同一字符事实开始重建。"""
evidence = {
'tables': {'table-1': [{'text': 'TABLE'}]},
'page_glyphs': {'1': [{'text': 'PAGE'}]},
@@ -62,13 +72,36 @@ def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_sourc
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
evidence=evidence, raw_table=raw_table, table_id='table-1',
) == [{'text': 'TABLE'}]
) == [{'text': 'PAGE'}]
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'),
evidence=evidence, raw_table=raw_table, table_id='table-1',
) == [{'text': 'PAGE'}]
def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages():
"""关键断言:第二页只有合同正文时,不能重复重建第一页的订单明细。"""
evidence = {
'tables': {'table-1': [{'text': 'TABLE'}]},
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'TERMS'}]},
}
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
raw_table = {'table_id': 'table-1', 'page_no': 1}
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}]
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
evidence = {
'tables': {'table-1': [{'text': 'PAGE-1'}]},
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'PAGE-2'}]},
}
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=True))
raw_table = {'table_id': 'table-1', 'page_no': 1}
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) == [{'text': 'PAGE-2'}]
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]:
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
@@ -244,10 +277,8 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a
)
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed', executed['latest_run']
with pytest.raises(Exception) as self_approval:
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert getattr(self_approval.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
approved = quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
# 业务规则:具备管理员权限即可批准,不再要求必须由其他管理员批准。
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert approved['status'] == 'approved'
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
qualification = quality.qualification_summary(profile)
@@ -334,6 +365,7 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
layout_version = documents[1].current_layout_version
payload = dict(layout_version.payload_json)
payload.pop('coordinate_evidence_ref', None)
payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}}
layout_version.payload_json = payload
db.session.commit()
@@ -344,7 +376,6 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
if item['document_id'] == documents[1].id
)
assert candidate['review_mode'] == 'preparing'
assert candidate['confirmable'] is False
assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing']
@@ -365,27 +396,6 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""模拟从原始 PDF 恢复整页字符,验证盲测不依赖 MinerU table_id。"""
assert page_nos is None
recovered = dict(layout)
recovered['coordinate_evidence'] = {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
}
return recovered
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
candidate_option = next(item for item in available if item['document_id'] == document.id)
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
@@ -393,11 +403,13 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
assert candidate_option['confirmable'] is False
assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing']
candidate = quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}]
with pytest.raises(Exception) as diagnostic_preview:
quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert getattr(diagnostic_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
candidate = {'rows': []}
with pytest.raises(Exception) as bypassed_review:
quality.add_sample(
suite_id=suite['id'], document_id=document.id,
@@ -405,7 +417,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
expected_rows=candidate['rows'], actor_id=user.id,
)
assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
assert candidate['confirmable'] is False
assert diagnostic_preview.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
with pytest.raises(Exception) as diagnostic_confirmation:
quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=document.id,
@@ -414,7 +426,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
layout_version_id=current_version.id,
layout_payload_checksum=current_version.payload_checksum, actor_id=user.id,
)
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE'
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
@@ -431,29 +443,6 @@ def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""模拟正在预热时直接从原 PDF 恢复整页坐标,空布局不得阻断复核。"""
assert layout == {'status': 'pending', 'tables': [], 'issues': []}
assert page_nos is None
return {
**layout,
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
},
}
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
candidate_option = next(item for item in available if item['document_id'] == document.id)
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
@@ -484,26 +473,6 @@ def test_document_candidate_identity_expires_after_background_layout_completion(
for item in available
)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""文档级复核使用整页证据,不依赖后台刚生成的表格身份。"""
assert page_nos is None
recovered = dict(layout)
recovered['coordinate_evidence'] = {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
}
return recovered
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
with pytest.raises(Exception) as stale_preview:
quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
@@ -600,8 +569,9 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
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}}},
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
})
db.session.flush()
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
for document in documents:
@@ -671,7 +641,7 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
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}}},
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
})
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
@@ -680,6 +650,56 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
assert candidate['rows'] == []
def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
"""盲测候选必须和编辑器预览一样排除表头视觉区域。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [{
'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25},
'field_regions': [],
}],
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
],
}],
}], 'order_field_layouts': [],
}
glyphs = [
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 10, 'x1': 23 + index * 4, 'y1': 20}}
for index, char in enumerate('Item')
] + [
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
for index, char in enumerate('20')
] + [
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
for index, char in enumerate('PART-A')
]
record_inline_layout_snapshot(documents[1], {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
db.session.commit()
candidate = quality._candidate_for_sample(
profile=profile, document_id=documents[1].id, table_id='table-1',
)
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
with app.app_context():