feat(shipping-notice): 升级货代发货流程为五阶段,完善业务校验
将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段; 统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认"; 新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成; 新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式; 更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
This commit is contained in:
1 parent
1b6483a4ea
commit
935bf26fa6
86 files changed
+2743
-311
No files matched your search
@@ -206,6 +206,62 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
|
||||
ensure_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_unique_customer_candidate_can_be_confirmed_before_draft_validation(app):
|
||||
"""保存校验前,唯一 Shadow 候选必须先落为 Bill-to 已确认事实。"""
|
||||
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(case_no='SORC-UNIQUE-CUSTOMER', candidate_id=31)
|
||||
with patch.object(
|
||||
coord,
|
||||
'_customer_step_for_case',
|
||||
return_value=('auto_confirmed', {'customer_id': 5555}),
|
||||
) as step_mock:
|
||||
result = coord.auto_confirm_unique_customer_for_review_case(
|
||||
case=case,
|
||||
trigger='draft_validated',
|
||||
)
|
||||
|
||||
step_mock.assert_called_once_with(case=case, trigger='draft_validated')
|
||||
assert result == {'status': 'auto_confirmed', 'customer_id': 5555}
|
||||
|
||||
|
||||
def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(app):
|
||||
"""唯一客户自动确认只 flush,不能在 Draft 校验前单独提交事务。"""
|
||||
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31)
|
||||
candidate = SimpleNamespace(id=31)
|
||||
shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555)
|
||||
extraction = SimpleNamespace(id=101)
|
||||
shadow_model = SimpleNamespace(
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)),
|
||||
)
|
||||
match_model = SimpleNamespace(
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))),
|
||||
)
|
||||
with patch.object(coord.db.session, 'get', return_value=candidate), patch.object(
|
||||
coord,
|
||||
'ShippingCustomerShadowResolution',
|
||||
shadow_model,
|
||||
), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object(
|
||||
coord,
|
||||
'_resolve_extraction_for_case',
|
||||
return_value=extraction,
|
||||
), patch.object(
|
||||
coord,
|
||||
'ShippingOrderCustomerMatch',
|
||||
match_model,
|
||||
), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object(
|
||||
coord,
|
||||
'record_fulfillment_audit',
|
||||
):
|
||||
status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated')
|
||||
|
||||
assert status == 'auto_confirmed'
|
||||
assert metadata == {'customer_id': 5555, 'extraction_id': 101}
|
||||
assert confirm_mock.call_args.kwargs['commit'] is False
|
||||
|
||||
|
||||
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
|
||||
"""合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
@@ -277,6 +277,53 @@ def test_coordinate_profile_row_layout_repeats_across_the_table():
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_regions():
|
||||
"""锚点框架选中的平移必须同时投影主表、物理行和每个字段区。"""
|
||||
baseline_layout = {
|
||||
'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .35},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .25, 'x1': .25, 'y1': .35}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .25, 'x1': .55, 'y1': .35}},
|
||||
{'field_code': 'qty', 'region': {'x0': .55, 'y0': .25, 'x1': .75, 'y1': .35}},
|
||||
{'field_code': 'unit_price', 'region': {'x0': .75, 'y0': .25, 'x1': 1, 'y1': .35}},
|
||||
],
|
||||
}],
|
||||
}
|
||||
shifted = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('PART-A', 65), ('2', 135), ('10.50', 175)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
|
||||
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .20},
|
||||
**baseline_layout,
|
||||
)
|
||||
|
||||
# Without the selected transform these glyphs sit outside all baseline Y regions.
|
||||
assert shifted[0].fields == {
|
||||
'customer_po_line_no': '00010', 'customer_part_number': 'PART-A',
|
||||
'qty': '2', 'unit_price': '10.50',
|
||||
}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_reject_invalid_selected_anchor_frame_transform():
|
||||
"""非 matcher 认可的变换不得悄悄回退为绝对坐标取值。"""
|
||||
kwargs = {
|
||||
'characters': _glyphs([('00010', 10), ('PART-A', 65)]),
|
||||
'table_bbox': {'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
|
||||
'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40},
|
||||
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .20, 'x1': .25, 'y1': .40}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .20, 'x1': 1, 'y1': .40}},
|
||||
]}],
|
||||
}
|
||||
|
||||
assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={'status': 'pending'}) == []
|
||||
assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={
|
||||
'status': 'applied', 'translate_x': 0, 'translate_y': .9,
|
||||
}) == []
|
||||
|
||||
|
||||
def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review():
|
||||
"""仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。"""
|
||||
kwargs = {
|
||||
|
||||
@@ -504,6 +504,8 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab
|
||||
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in pending.payload_json['coordinate_evidence']
|
||||
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence']
|
||||
assert pending.payload_json['matching_features']['version'] == 'v1'
|
||||
assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2]
|
||||
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json
|
||||
@@ -569,6 +571,36 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map
|
||||
assert 'tables' not in restored['coordinate_evidence']
|
||||
|
||||
|
||||
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
|
||||
"""冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
current = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 200}},
|
||||
'page_glyphs': {'1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
|
||||
'tables': {'table-1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
})
|
||||
db.session.flush()
|
||||
document.current_layout_version = current
|
||||
frozen_layout = {
|
||||
**_snapshot(),
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
|
||||
}
|
||||
|
||||
restored = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=frozen_layout, page_nos={1},
|
||||
)
|
||||
|
||||
# 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。
|
||||
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
|
||||
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
|
||||
|
||||
|
||||
def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch):
|
||||
"""同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -442,6 +442,42 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
|
||||
assert seen['characters'][0]['text'] == 'Terms'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_forward_selected_match_transform_without_recomputing(monkeypatch):
|
||||
"""工作流只能转交共同 matcher 的已选变换,不能由表格或订单值重新推断。"""
|
||||
region = SimpleNamespace(
|
||||
page_scope='all_pages', page_no=None, line_layouts=[SimpleNamespace(model_dump=lambda: {})],
|
||||
region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}),
|
||||
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
|
||||
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
|
||||
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
|
||||
)
|
||||
seen = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows',
|
||||
lambda **kwargs: (seen.update(coordinate_transform=kwargs.get('coordinate_transform')) or []),
|
||||
)
|
||||
transform = {
|
||||
'status': 'applied', 'translate_x': 0.0, 'translate_y': .03,
|
||||
'anchor_ids': ['title'], 'reason_codes': [],
|
||||
}
|
||||
|
||||
rows = _coordinate_profile_rows(
|
||||
raw_profile={}, raw_table={'table_id': 'order-table', 'page_no': 1},
|
||||
layout={'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': [{'text': 'x', 'bbox': {'x0': 30, 'y0': 30, 'x1': 31, 'y1': 31}}]},
|
||||
'tables': {},
|
||||
}},
|
||||
contract=SimpleNamespace(fields_by_code={}), schema_fields={}, coordinate_transform=transform,
|
||||
)
|
||||
|
||||
assert rows == []
|
||||
assert seen['coordinate_transform'] == transform
|
||||
|
||||
|
||||
def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch):
|
||||
"""固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。"""
|
||||
region = SimpleNamespace(
|
||||
|
||||
@@ -77,18 +77,18 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback()
|
||||
"primary_action": {
|
||||
"code": "mark_manual_uploaded",
|
||||
"label": "登记人工上传",
|
||||
"target_surface": "upload_complete",
|
||||
"target_surface": "freight_upload",
|
||||
},
|
||||
"action_presentation": [{
|
||||
"code": "download_excel",
|
||||
"label": "下载发货 Excel",
|
||||
"target_surface": "upload_complete",
|
||||
"target_surface": "freight_upload",
|
||||
"target_anchor": "excel_artifact",
|
||||
}],
|
||||
},
|
||||
)
|
||||
assert state["primary"]["target_surface"] == "upload_complete"
|
||||
assert state["secondary"][0]["target_surface"] == "upload_complete"
|
||||
assert state["primary"]["target_surface"] == "freight_upload"
|
||||
assert state["secondary"][0]["target_surface"] == "freight_upload"
|
||||
assert state["secondary"][0]["target_anchor"] == "excel_artifact"
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
assert "stage_context" in detailed_state
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
|
||||
def test_build_task_ui_state_exposes_five_business_stages_and_unified_actions(app) -> None:
|
||||
"""没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
@@ -133,13 +133,13 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap
|
||||
state = build_task_ui_state(task)
|
||||
assert state["stage"]["code"] == "order_review"
|
||||
assert state["stage"]["index"] == 2
|
||||
assert state["stage"]["total"] == 4
|
||||
assert state["stage"]["total"] == 5
|
||||
assert state["actions"]["primary"] is None
|
||||
assert state["actions"]["secondary"] == []
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
|
||||
"""正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
|
||||
"""正式工作台的五个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-LIFECYCLE-ENTRIES",
|
||||
@@ -153,6 +153,7 @@ def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> Non
|
||||
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "freight_upload", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
|
||||
]
|
||||
|
||||
@@ -213,7 +214,7 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
|
||||
|
||||
|
||||
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
|
||||
"""正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。"""
|
||||
"""正式人工上传 Gate 必须停留货代上传,不受旧复核字段影响。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
@@ -235,16 +236,16 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
|
||||
|
||||
state = build_task_ui_state(task)
|
||||
|
||||
assert state['lifecycle_stage'] == 'upload_complete'
|
||||
assert state['lifecycle_stage'] == 'freight_upload'
|
||||
assert state['lifecycle_authority'] == 'process_gate'
|
||||
assert state['stage']['code'] == 'upload_complete'
|
||||
assert state['stage']['code'] == 'freight_upload'
|
||||
assert [entry['state'] for entry in state['lifecycle_entries']] == [
|
||||
'available', 'available', 'available', 'current',
|
||||
'available', 'available', 'available', 'current', 'unavailable',
|
||||
]
|
||||
|
||||
|
||||
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
|
||||
"""库存匹配/上传结果只映射四个业务阶段。"""
|
||||
"""库存匹配与无证据历史上传分别映射通知准备和货代上传。"""
|
||||
with app.app_context():
|
||||
fulfillment = ShippingNotice(
|
||||
task_no="SN-UI-FULFILLMENT",
|
||||
@@ -259,7 +260,7 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(
|
||||
)
|
||||
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
|
||||
upload_state = build_task_ui_state(upload, include_stage_context=True)
|
||||
assert upload_state["stage"]["code"] == "upload_complete"
|
||||
assert upload_state["stage"]["code"] == "freight_upload"
|
||||
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
|
||||
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
|
||||
|
||||
|
||||
@@ -64,6 +64,7 @@ from app.jobs.queue import fail_job
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
submit_order_extraction_run_result,
|
||||
submit_order_extraction_unit_result,
|
||||
reconcile_review_case_after_unit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_plan import (
|
||||
@@ -2925,6 +2926,23 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app):
|
||||
assert ShippingOrderCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0
|
||||
|
||||
|
||||
def test_unit_replay_reconciles_review_case_after_ensure(monkeypatch):
|
||||
"""Unit 幂等回放创建/恢复 Case 后必须进入统一自动校验协调器。"""
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_service.ensure_review_case_for_unit',
|
||||
lambda **kwargs: calls.append(('ensure', kwargs)) or object(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.maybe_stp_auto_create_for_run',
|
||||
lambda **kwargs: calls.append(('reconcile', kwargs)) or [{'validate_status': 'validated'}],
|
||||
)
|
||||
|
||||
reconcile_review_case_after_unit(run='run', unit='unit')
|
||||
|
||||
assert [item[0] for item in calls] == ['ensure', 'reconcile']
|
||||
|
||||
|
||||
def test_unit_submission_survives_deleted_chat_session(app):
|
||||
"""后台 Run 不得因 UI 会话历史已清理而回滚 Candidate/Review Case 持久化。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -140,6 +140,27 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
|
||||
assert result.source == 'pdf_coordinate'
|
||||
|
||||
|
||||
def test_anchor_frame_transform_moves_order_number_anchor_and_value_together():
|
||||
"""共同 matcher 的纵向平移必须同时投影订单号标签和值框。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'po', 'text': 'PO NO',
|
||||
'region': {'x0': .05, 'y0': .1, 'x1': .25, 'y1': .14},
|
||||
'position_locked': True,
|
||||
},
|
||||
'absolute_value_region': {'x0': .2, 'y0': .1, 'x1': .9, 'y1': .14},
|
||||
'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(
|
||||
profile=profile,
|
||||
schema_fields=_schema(),
|
||||
coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 20, 40))}),
|
||||
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .1},
|
||||
)[0]
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '45001'
|
||||
|
||||
|
||||
def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower():
|
||||
"""值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。"""
|
||||
profile = _profile(layout={
|
||||
|
||||
@@ -86,6 +86,124 @@ def _with_signature(profile: dict, layout: dict) -> dict:
|
||||
return enriched
|
||||
|
||||
|
||||
def _anchor_frame_profile(code: str = 'PO_ANCHOR_FRAME') -> dict:
|
||||
"""构造声明锚点坐标框架的最小 Profile,供平移门禁回归使用。"""
|
||||
profile = _profile(code)
|
||||
profile['definition']['coordinate_model'] = {
|
||||
'type': 'anchor_frame',
|
||||
'anchors': [{
|
||||
'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'match_mode': 'exact',
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
'region': {'x0': .185, 'y0': .05, 'x1': .26, 'y1': .0857142857},
|
||||
}],
|
||||
'max_translate_x': .02,
|
||||
'max_translate_y': .05,
|
||||
}
|
||||
return profile
|
||||
|
||||
|
||||
def _layout_with_frame_anchor(*, anchor_y: float = .05, table_y: float = .25) -> dict:
|
||||
"""构造标题与主表同步平移的坐标 Layout,模拟正文高度改变而非结构变更。"""
|
||||
layout = _layout(bbox={'x0': .05, 'y0': table_y, 'x1': .95, 'y1': .95})
|
||||
text = 'PURCHASE ORDER'
|
||||
anchor_glyphs = [
|
||||
{
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 5, 'y0': anchor_y * 280, 'x1': 14 + index * 5, 'y1': anchor_y * 280 + 10},
|
||||
'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none',
|
||||
}
|
||||
for index, char in enumerate(text)
|
||||
if char != ' '
|
||||
]
|
||||
header = layout['coordinate_evidence']['tables']['table-1']
|
||||
for glyph in header:
|
||||
glyph['bbox']['y0'] += (table_y - .25) * 280
|
||||
glyph['bbox']['y1'] += (table_y - .25) * 280
|
||||
plant_text = 'PLANT NAME: FACTORY A'
|
||||
plant_glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate(plant_text)
|
||||
]
|
||||
layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*plant_glyphs,
|
||||
*anchor_glyphs,
|
||||
*header,
|
||||
]
|
||||
return layout
|
||||
|
||||
|
||||
def test_anchor_frame_matches_bounded_vertical_translation_without_changing_legacy_profiles():
|
||||
"""同一结构整体下移时仅启用锚点框架的 Profile 可命中,legacy 仍按原规则失败关闭。"""
|
||||
baseline = _layout_with_frame_anchor()
|
||||
shifted = _layout_with_frame_anchor(anchor_y=.095, table_y=.295)
|
||||
framed = _with_signature(_anchor_frame_profile(), baseline)
|
||||
legacy = _with_signature(_profile('PO_LEGACY'), baseline)
|
||||
|
||||
framed_result = match_frozen_coordinate_profiles(profiles=[framed], layout=shifted)
|
||||
legacy_result = match_frozen_coordinate_profiles(profiles=[legacy], layout=shifted)
|
||||
|
||||
# 关键断言:变换来自唯一静态锚点,并且 legacy Profile 未因新能力改变行为。
|
||||
assert framed_result.status == 'unique_match'
|
||||
assert framed_result.candidates[0].coordinate_transform == {
|
||||
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.045,
|
||||
'anchor_ids': ['title'], 'reason_codes': [],
|
||||
}
|
||||
assert legacy_result.candidates[0].coordinate_transform is None
|
||||
|
||||
|
||||
def test_anchor_frame_fails_closed_when_anchor_is_missing_ambiguous_or_out_of_range():
|
||||
"""锚点框架不得因缺锚、重锚或超界平移降级猜测,均须成为模板硬失败。"""
|
||||
baseline = _layout_with_frame_anchor()
|
||||
profile = _with_signature(_anchor_frame_profile(), baseline)
|
||||
missing = _layout()
|
||||
ambiguous = _layout_with_frame_anchor(anchor_y=.08, table_y=.28)
|
||||
ambiguous['coordinate_evidence']['page_glyphs']['1'].extend(
|
||||
_layout_with_frame_anchor(anchor_y=.115)['coordinate_evidence']['page_glyphs']['1'][21:34],
|
||||
)
|
||||
out_of_range = _layout_with_frame_anchor(anchor_y=.14, table_y=.34)
|
||||
|
||||
for layout, reason in (
|
||||
(missing, 'profile_anchor_frame_anchor_missing'),
|
||||
(ambiguous, 'profile_anchor_frame_anchor_ambiguous'),
|
||||
(out_of_range, 'profile_anchor_frame_transform_out_of_range'),
|
||||
):
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
|
||||
assert result.candidates[0].hard_match is False
|
||||
assert reason in result.candidates[0].reason_codes
|
||||
|
||||
|
||||
def test_anchor_frame_matches_static_anchor_embedded_in_a_pdf_line():
|
||||
"""PDF 原生字符常把多个标签拼成一行;锚点应返回自身字符框而非整行框。"""
|
||||
baseline = _layout_with_frame_anchor()
|
||||
title = baseline['coordinate_evidence']['page_glyphs']['1'][21:34]
|
||||
prefix = [{'text': 'X', 'bbox': {'x0': 0, 'y0': 14, 'x1': 5, 'y1': 24}}]
|
||||
suffix = [{'text': 'X', 'bbox': {'x0': 80, 'y0': 14, 'x1': 85, 'y1': 24}}]
|
||||
for glyph in title:
|
||||
glyph['bbox']['y0'] += 10
|
||||
glyph['bbox']['y1'] += 10
|
||||
prefix[0]['bbox']['y0'] += 10
|
||||
prefix[0]['bbox']['y1'] += 10
|
||||
suffix[0]['bbox']['y0'] += 10
|
||||
suffix[0]['bbox']['y1'] += 10
|
||||
baseline['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*baseline['coordinate_evidence']['page_glyphs']['1'][:21],
|
||||
*prefix,
|
||||
*title,
|
||||
*suffix,
|
||||
*baseline['coordinate_evidence']['page_glyphs']['1'][34:],
|
||||
]
|
||||
profile = _with_signature(_anchor_frame_profile(), baseline)
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=baseline)
|
||||
|
||||
# 关键断言:行内静态锚点仍唯一命中,且自身 bbox 不受前后文本扩大影响。
|
||||
assert result.status == 'unique_match'
|
||||
assert result.candidates[0].coordinate_transform == {
|
||||
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.035714,
|
||||
'anchor_ids': ['title'], 'reason_codes': [],
|
||||
}
|
||||
|
||||
|
||||
def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values():
|
||||
"""工厂标签和值关系不受订单号、料号、数量变化影响。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X')
|
||||
@@ -120,6 +238,37 @@ def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
|
||||
assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient'
|
||||
|
||||
|
||||
def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_compacted():
|
||||
"""字符坐标被压缩后,模板匹配仍须使用压缩前持久化的结构特征。"""
|
||||
complete_layout = _layout()
|
||||
profile = _profile('PO_A')
|
||||
profile['definition']['document_match']['required_anchors'] = []
|
||||
profile = _with_signature(profile, complete_layout)
|
||||
compacted_layout = {
|
||||
'tables': complete_layout['tables'],
|
||||
'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']},
|
||||
'matching_features': {
|
||||
'version': 'shipping-layout-matching-features.v1',
|
||||
'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1},
|
||||
'tables': [{
|
||||
'table_id': 'table-1', 'page_no': 1,
|
||||
'bbox': [0.05, 0.25, 0.95, 0.95],
|
||||
'header_tokens': ['item', 'no', 'qty'],
|
||||
'column_centers': [0.1225, 0.2825, 0.4225],
|
||||
'column_width_ratios': [0.1611, 0.0722, 0.1167],
|
||||
}],
|
||||
'static_text_centers': {},
|
||||
},
|
||||
}
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout)
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
candidate = result.candidates[0]
|
||||
assert candidate.dimension_states['header_semantic_position'] == 'matched'
|
||||
assert candidate.dimension_states['column_topology'] == 'matched'
|
||||
|
||||
|
||||
def test_profile_matcher_reports_only_missing_anchor_identifiers():
|
||||
"""缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。"""
|
||||
profile = _profile('PO_A')
|
||||
|
||||
@@ -101,3 +101,78 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch):
|
||||
assert result['auto_gate_allowed'] is False
|
||||
assert result['task_created'] is False
|
||||
assert case.status == 'ready'
|
||||
|
||||
|
||||
def test_resume_auto_confirms_unique_customer_before_validating(monkeypatch):
|
||||
"""保存校验时必须先确认唯一客户候选,再执行 Draft 校验。"""
|
||||
case = _case(can_build=True, can_auto_create=False, validation_status='ready')
|
||||
calls = []
|
||||
monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case)
|
||||
monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None)
|
||||
monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: [])
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.auto_confirm_unique_customer_for_review_case',
|
||||
lambda **_kw: calls.append('customer') or {'status': 'auto_confirmed', 'customer_id': 5555},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'validate_draft',
|
||||
lambda **_kw: calls.append('validate') or {'status': 'ready'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **_kw: None,
|
||||
)
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(svc.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_projection.serialize_review_case',
|
||||
lambda _c: {'case_no': case.case_no},
|
||||
)
|
||||
|
||||
svc.resume_after_review_change(
|
||||
user_id=7,
|
||||
case_no=case.case_no,
|
||||
trigger='draft_validated',
|
||||
skip_validate=False,
|
||||
)
|
||||
|
||||
assert calls == ['customer', 'validate']
|
||||
|
||||
|
||||
def test_validate_draft_api_delegates_versioned_validation_to_resume_coordinator(app, monkeypatch):
|
||||
"""保存校验 API 不可绕过协调器,必须传递乐观锁版本。"""
|
||||
from app.api.workspace import shipping_notice as api
|
||||
from app.services.shipping_notice import order_review_resume_service
|
||||
|
||||
user = SimpleNamespace(id=7)
|
||||
calls = []
|
||||
|
||||
def fake_resume(**kwargs):
|
||||
calls.append(kwargs)
|
||||
return {
|
||||
'case': {'case_no': kwargs['case_no']},
|
||||
'outcome': 'blocked',
|
||||
'gate_recalculated': True,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(api, '_require_user', lambda: user)
|
||||
monkeypatch.setattr(order_review_resume_service, 'resume_after_review_change', fake_resume)
|
||||
with app.test_request_context(
|
||||
'/shipping-notice/order-review-cases/CASE-API/draft/validate',
|
||||
method='POST',
|
||||
json={'expected_draft_version': 12},
|
||||
):
|
||||
response, status = api.workspace_validate_shipping_order_review_draft('CASE-API')
|
||||
|
||||
assert status == 200
|
||||
assert response.get_json()['data']['case'] == {'case_no': 'CASE-API'}
|
||||
assert calls == [{
|
||||
'user_id': 7,
|
||||
'case_no': 'CASE-API',
|
||||
'trigger': 'draft_validated',
|
||||
'change_type': None,
|
||||
'skip_validate': False,
|
||||
'allow_auto_create': True,
|
||||
'expected_draft_version': 12,
|
||||
}]
|
||||
@@ -401,6 +401,32 @@ def _materialized_run(*, user, agent, session, intake):
|
||||
return run
|
||||
|
||||
|
||||
def test_review_case_summary_exposes_only_failed_intake_retry_authorization(app):
|
||||
"""当前阶段卡只消费服务端 parse_failed 的 SNI 编号与 retry_parse 授权。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-INTAKE-RETRY')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
intake.parse_status = 'parse_failed'
|
||||
db.session.commit()
|
||||
|
||||
failed = serialize_review_run(run)['items'][0]
|
||||
# 关键断言:失败节点提供原 SNI 和 retry_parse;不需要重新上传或前端猜测。
|
||||
assert failed['intake_no'] == intake.intake_no
|
||||
assert failed['available_actions'] == ['retry_parse']
|
||||
|
||||
intake.parse_status = 'parsing'
|
||||
db.session.commit()
|
||||
parsing = serialize_review_run(run)['items'][0]
|
||||
# 关键断言:运行中只能等待 Worker 超时回收,不能显示冲突重试动作。
|
||||
assert parsing['available_actions'] == []
|
||||
|
||||
intake.parse_status = 'cancelled'
|
||||
db.session.commit()
|
||||
cancelled = serialize_review_run(run)['items'][0]
|
||||
assert cancelled['available_actions'] == []
|
||||
|
||||
|
||||
def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None:
|
||||
"""
|
||||
为 Review 就绪路径测试注入行级 catch-all 库存源规则。
|
||||
@@ -1768,6 +1794,63 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
|
||||
raise AssertionError('superseded case must not be reparsed')
|
||||
|
||||
|
||||
def test_successful_document_reparse_reconciles_only_activated_replacement_case(app, monkeypatch):
|
||||
"""PDF 重识别成功切换当前版本后,必须补触发新版 Case 的统一自动推进。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice import order_review_disposition_service as disposition
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-PROGRESS')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
source_case = ensure_run_review_cases(run=source)[0]
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other')
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
replacement_case = ensure_run_review_cases(run=replacement)[0]
|
||||
reconciled = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
lambda **kwargs: reconciled.append(kwargs) or {'enqueue_status': 'queued'},
|
||||
)
|
||||
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
|
||||
assert reconciled == [{
|
||||
'case': replacement_case,
|
||||
'trigger': 'document_reparse_succeeded',
|
||||
'refresh_validation': True,
|
||||
}]
|
||||
|
||||
|
||||
def test_document_reparse_does_not_reconcile_when_stream_activation_is_rejected(app, monkeypatch):
|
||||
"""Stream 冲突或已确认旧版本拒绝切换时,不得推进晚到的新版草稿。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-CONFLICT')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
source_case = ensure_run_review_cases(run=source)[0]
|
||||
mark_review_stream_confirmed(case=source_case)
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other')
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
ensure_run_review_cases(run=replacement)
|
||||
reconciled = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
lambda **kwargs: reconciled.append(kwargs),
|
||||
)
|
||||
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
|
||||
assert reconciled == []
|
||||
|
||||
|
||||
def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app):
|
||||
"""Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。"""
|
||||
with app.app_context():
|
||||
@@ -2456,3 +2539,17 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app):
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
|
||||
del agent, session, intake
|
||||
def test_unvalidated_draft_is_not_projected_as_build_blocked(app):
|
||||
"""未执行校验的 Draft 必须保持 not_validated,不能伪造成 can_build=false。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='UNVALIDATED-PROJECTION')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
db.session.flush()
|
||||
|
||||
detail = serialize_review_case(case)
|
||||
eligibility = detail['draft']['build_eligibility']
|
||||
|
||||
assert eligibility['status'] == 'not_validated'
|
||||
assert eligibility['can_build'] is None
|
||||
@@ -106,13 +106,13 @@ def test_fulfillment_action_presentation_declares_lifecycle_surface():
|
||||
)['target_surface'] == 'fulfillment_prep'
|
||||
assert action_presentation(
|
||||
'retry_freight_upload_rpa', gate_code='freight_upload_rpa',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
)['target_surface'] == 'freight_upload'
|
||||
assert action_presentation(
|
||||
'regenerate_manual_upload_todo', gate_code='manual_upload_handoff',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
)['target_surface'] == 'freight_upload'
|
||||
assert action_presentation(
|
||||
'mark_manual_uploaded', gate_code='manual_upload_handoff',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
)['target_surface'] == 'freight_upload'
|
||||
|
||||
|
||||
def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor():
|
||||
@@ -558,7 +558,7 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(
|
||||
'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa',
|
||||
]
|
||||
assert summary['primary_action']['target_surface'] == 'upload_complete'
|
||||
assert summary['primary_action']['target_surface'] == 'freight_upload'
|
||||
assert summary['primary_action']['target_anchor'] == 'manual_upload'
|
||||
|
||||
|
||||
|
||||
@@ -223,9 +223,11 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
|
||||
)
|
||||
|
||||
uploaded = SimpleNamespace(
|
||||
id=None,
|
||||
current_step='', upload_status='uploaded', export_file_path=None,
|
||||
)
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
|
||||
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
|
||||
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
|
||||
|
||||
waiting = SimpleNamespace(
|
||||
current_step='', upload_status='pending', export_file_path='/x.xlsx',
|
||||
|
||||
@@ -103,14 +103,14 @@ def test_map_run_status_to_processing_status() -> None:
|
||||
('inventory_snapshots_ready', 'fulfillment_prep'),
|
||||
('inventory_matched', 'fulfillment_prep'),
|
||||
('excel_generated', 'fulfillment_prep'),
|
||||
('upload_receipt_recorded', 'upload_complete'),
|
||||
('upload_receipt_recorded', 'freight_upload'),
|
||||
],
|
||||
)
|
||||
def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
|
||||
def test_batch_lifecycle_nodes_maps_auto_progress_gate_stages(
|
||||
stage: str,
|
||||
expected_lifecycle_stage: str,
|
||||
) -> None:
|
||||
"""自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。"""
|
||||
"""自动推进 Gate 的真实阶段码必须归入对应五阶段,不能回退到接收解析。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
'stage': stage,
|
||||
'user_stage': stage,
|
||||
@@ -127,7 +127,7 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
|
||||
('item', 'expected_lifecycle_stage'),
|
||||
[
|
||||
({'user_stage': 'inventory_match'}, 'fulfillment_prep'),
|
||||
({'user_stage': 'freight_upload'}, 'upload_complete'),
|
||||
({'user_stage': 'freight_upload'}, 'freight_upload'),
|
||||
({'user_stage': 'customer_resolving'}, 'order_review'),
|
||||
({'user_stage': 'duplicate_checking'}, 'order_review'),
|
||||
({'user_stage': 'waiting_human_review'}, 'order_review'),
|
||||
@@ -142,11 +142,11 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
|
||||
({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'),
|
||||
],
|
||||
)
|
||||
def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases(
|
||||
def test_batch_lifecycle_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases(
|
||||
item: dict[str, object],
|
||||
expected_lifecycle_stage: str,
|
||||
) -> None:
|
||||
"""批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
|
||||
"""批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
**item,
|
||||
'status': 'waiting_human',
|
||||
@@ -177,6 +177,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
|
||||
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
]
|
||||
assert fulfillment_state['primary_action']['execution_mode'] == 'navigate'
|
||||
@@ -232,6 +233,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
|
||||
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
]
|
||||
|
||||
@@ -478,7 +480,7 @@ def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(ap
|
||||
|
||||
|
||||
def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None:
|
||||
"""四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
|
||||
"""五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
|
||||
projection = _conversation_processing_from_work_items([
|
||||
{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW',
|
||||
@@ -503,8 +505,36 @@ def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_s
|
||||
assert projection['unclassified_summary'] == {'count': 1}
|
||||
|
||||
|
||||
def test_batch_payload_exposes_five_nodes_and_unverified_legacy_completion_stays_freight_upload(app) -> None:
|
||||
"""新字段固定五节点,兼容字段同值,旧 technical completed 不得计作通知完成。"""
|
||||
with app.app_context():
|
||||
projection = _conversation_processing_from_work_items([{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-LEGACY-UPLOADED',
|
||||
'root_order_task_no': 'OT-LEGACY-UPLOADED', 'source_type': 'direct_pdf',
|
||||
'shipping_notice_no': 'SN-LEGACY-UPLOADED', 'has_formal_ot': True,
|
||||
'source_summary': {'document_id': 601, 'filename': 'legacy.pdf'},
|
||||
'status': 'completed', 'stage': 'completed',
|
||||
'user_status': 'completed', 'user_stage': 'completed',
|
||||
'verified_upload_success': False,
|
||||
'available_actions': [], 'facts': {'upload_state': 'succeeded'},
|
||||
}])
|
||||
|
||||
assert [node['code'] for node in projection['lifecycle_nodes']] == [
|
||||
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
|
||||
]
|
||||
assert projection['four_stage_nodes'] == projection['lifecycle_nodes']
|
||||
freight = next(node for node in projection['lifecycle_nodes'] if node['code'] == 'freight_upload')
|
||||
assert freight['summary']['needs_action'] == 1
|
||||
assert freight['summary']['completed'] == 0
|
||||
assert projection['summary']['completed'] == 0
|
||||
assert projection['status_groups']['completed'] == []
|
||||
assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [
|
||||
'OT-LEGACY-UPLOADED',
|
||||
]
|
||||
|
||||
|
||||
def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
|
||||
"""同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。"""
|
||||
"""同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': 'INTAKE:SNI-DOUBLE',
|
||||
@@ -632,6 +662,38 @@ def test_conversation_status_groups_use_the_same_current_file_representative() -
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('terminal_status', ['cancelled', 'archived'])
|
||||
def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metrics(
|
||||
app,
|
||||
terminal_status: str,
|
||||
) -> None:
|
||||
"""取消或归档仅保留历史,不得进入会话完成、文件完成或第五阶段统计。"""
|
||||
with app.app_context():
|
||||
work_items = [{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': f'OT-{terminal_status.upper()}',
|
||||
'user_status': terminal_status,
|
||||
'user_stage': 'freight_uploading',
|
||||
# 覆盖历史兼容载荷尚未写入 user_group 的回退路径。
|
||||
'status': terminal_status,
|
||||
'stage': terminal_status,
|
||||
'source_summary': {'document_id': 570, 'filename': 'history.pdf'},
|
||||
}]
|
||||
projection = _conversation_processing_from_work_items(work_items)
|
||||
assert projection['summary']['completed'] == 0
|
||||
assert projection['summary']['history'] == 1
|
||||
assert projection['summary']['total_files'] == 0
|
||||
assert projection['summary']['completed_files'] == 0
|
||||
assert projection['completed'] == []
|
||||
assert [row['user_task_no'] for row in projection['history']] == [
|
||||
f'OT-{terminal_status.upper()}',
|
||||
]
|
||||
assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [
|
||||
f'OT-{terminal_status.upper()}',
|
||||
]
|
||||
assert all(node['summary']['total'] == 0 for node in projection['lifecycle_nodes'])
|
||||
|
||||
|
||||
def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None:
|
||||
"""历史失败项不得在互斥统计后仍抢走批次当前按钮。"""
|
||||
work_items = [
|
||||
@@ -1031,6 +1093,7 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
|
||||
{'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
]
|
||||
assert leaf['intake_parse_authorized'] is True
|
||||
@@ -1172,7 +1235,7 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document
|
||||
|
||||
|
||||
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
|
||||
"""会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。"""
|
||||
"""会话投影一次下发分组、EML 子文件、五阶段及 UI 动作,前端无需二次裁决。"""
|
||||
with app.app_context():
|
||||
items = _aggregate_eml_order_task_work_items([
|
||||
{
|
||||
@@ -1868,16 +1931,16 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
|
||||
assert synced['status'] == 'automating'
|
||||
assert synced['stage'] == 'freight_uploading'
|
||||
|
||||
# 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。
|
||||
# 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。
|
||||
notice.upload_status = 'uploaded'
|
||||
order_task.status = 'automating'
|
||||
order_task.stage = 'freight_uploading'
|
||||
db.session.commit()
|
||||
completed = _project_order_task_work_item(run)
|
||||
assert completed['status'] == 'completed'
|
||||
assert completed['stage'] == 'completed'
|
||||
assert completed['user_status'] == 'completed'
|
||||
assert all(node['status'] == 'passed' for node in completed['stage_nodes'])
|
||||
unverified = _project_order_task_work_item(run)
|
||||
assert unverified['status'] == 'waiting_human'
|
||||
assert unverified['stage'] == 'freight_uploading'
|
||||
assert unverified['user_status'] == 'waiting_human'
|
||||
assert unverified['verified_upload_success'] is False
|
||||
|
||||
|
||||
def test_conversation_processing_rebuild_prefers_work_item_user_status(app):
|
||||
|
||||
@@ -242,8 +242,8 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating():
|
||||
assert stage['source'] == 'domain_facts'
|
||||
|
||||
|
||||
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
|
||||
"""人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。"""
|
||||
def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload():
|
||||
"""历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。"""
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=9,
|
||||
@@ -253,8 +253,8 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
|
||||
step_payload_json=None,
|
||||
)
|
||||
stage = project_stage_for_task(task)
|
||||
assert stage['code'] == 'completed'
|
||||
assert stage['source'] == 'notice_terminal'
|
||||
assert stage['code'] == 'freight_uploading'
|
||||
assert stage['source'] == 'upload_success_unverified'
|
||||
|
||||
|
||||
def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch):
|
||||
|
||||
@@ -18,7 +18,10 @@ 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, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
complete_attempt, has_verified_upload_success, mark_attempt_result_unknown,
|
||||
start_rpa_attempt, void_rejected_artifact,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
|
||||
|
||||
@@ -64,10 +67,34 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app):
|
||||
assert ShippingUploadAttempt.query.count() == 1
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
|
||||
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
|
||||
# 三层成功事实齐全后,才允许任务进入业务「通知完成」。
|
||||
assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True
|
||||
with pytest.raises(ConflictError):
|
||||
start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
|
||||
|
||||
def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app):
|
||||
"""历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。"""
|
||||
with app.app_context():
|
||||
task, _artifact, _reservation = _ready_artifact()
|
||||
task.upload_status = 'uploaded'
|
||||
db.session.flush()
|
||||
|
||||
assert has_verified_upload_success(task) is False
|
||||
|
||||
|
||||
def test_archived_upload_success_is_not_counted_as_completed(app):
|
||||
"""归档任务保留上传审计,但不能再计入当前通知完成统计。"""
|
||||
with app.app_context():
|
||||
task, artifact, _reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
|
||||
complete_attempt(attempt, success=True, callback_id='callback-archived', freight_ref_no='REF-ARCHIVED')
|
||||
task.lifecycle_status = 'archived'
|
||||
db.session.flush()
|
||||
|
||||
assert has_verified_upload_success(task) is False
|
||||
|
||||
|
||||
def test_failed_attempt_does_not_complete_reservation(app):
|
||||
"""RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。"""
|
||||
with app.app_context():
|
||||
|
||||
Reference in new issue
Block a user