feat(shipping-notice): 收敛复核阶段同源投影与 OT 后履约推进
统一 Case/Progress 阶段 label_key、修复 Job 成功未推进 OT 的可重试失败投影与写路径,并落地 OT 后行级匹配/波次履约与版面诊断开关。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
74270adc22
commit
fd6a23f870
100 files changed
+12138
-1017
No files matched your search
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
tests/test_line_inventory_allowed_actions.py
|
||||
|
||||
用途:锁定 inventory/line 动作分域矩阵(无 wait/换源;RPA 运行中无 preparation)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_shortage_allows_retry_preparation_not_wait():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
resolve_line_allowed_actions,
|
||||
)
|
||||
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='ready',
|
||||
match_result='not_found',
|
||||
is_shortage=True,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='shortage',
|
||||
)
|
||||
line = resolve_line_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='shortage',
|
||||
)
|
||||
assert inv == ['retry_inventory_preparation']
|
||||
assert 'wait_inventory' not in inv
|
||||
assert 'change_inventory_source' not in inv
|
||||
assert line == ['close_unfulfillable']
|
||||
|
||||
|
||||
def test_rpa_running_hides_inventory_actions():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
)
|
||||
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='preparing',
|
||||
match_result='preparing',
|
||||
is_shortage=False,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='acquiring_inventory',
|
||||
inventory_rpa_running=True,
|
||||
)
|
||||
assert inv == []
|
||||
|
||||
|
||||
def test_match_failed_with_snapshot_allows_matching():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
)
|
||||
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='mapping_failed',
|
||||
match_result='mapping_failed',
|
||||
is_shortage=False,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='inventory_match_failed',
|
||||
has_usable_snapshot=True,
|
||||
)
|
||||
assert inv == ['retry_inventory_preparation', 'retry_inventory_matching']
|
||||
|
||||
|
||||
def test_matched_hides_inventory_icon_actions():
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
)
|
||||
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='ready',
|
||||
match_result='matched',
|
||||
is_shortage=False,
|
||||
stored_line_status='ready_to_fulfill',
|
||||
user_line_status='inventory_matched',
|
||||
)
|
||||
assert inv == []
|
||||
|
||||
|
||||
def test_fallback_only_without_lines():
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
build_inventory_issue_fallback,
|
||||
)
|
||||
|
||||
assert build_inventory_issue_fallback(
|
||||
has_formal_ot=True,
|
||||
line_fulfillment={'lines': [{'line_key': 'L1'}]},
|
||||
process_gate={'blocking_reason_code': 'inventory_file_missing'},
|
||||
automation={'status': 'failed'},
|
||||
) is None
|
||||
|
||||
fb = build_inventory_issue_fallback(
|
||||
has_formal_ot=True,
|
||||
line_fulfillment={'lines': []},
|
||||
process_gate={'blocking_reason_code': 'inventory_file_missing'},
|
||||
automation={'status': 'failed'},
|
||||
)
|
||||
assert fb is not None
|
||||
assert fb['allowed_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_waiting_to_start_allows_retry_preparation():
|
||||
"""automation waiting_to_start 不得清空库存重试动作(非真正 RPA 运行中)。"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
resolve_inventory_allowed_actions,
|
||||
project_user_line_status,
|
||||
)
|
||||
|
||||
user_status = project_user_line_status(
|
||||
inventory_status='preparing',
|
||||
match_result='preparing',
|
||||
is_shortage=False,
|
||||
stored_line_status='pending_decision',
|
||||
inventory_rpa_running=False,
|
||||
)
|
||||
assert user_status == 'inventory_file_missing'
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='preparing',
|
||||
match_result='preparing',
|
||||
is_shortage=False,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status=user_status,
|
||||
inventory_rpa_running=False,
|
||||
)
|
||||
assert inv == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_fallback_hidden_while_waiting():
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
build_inventory_issue_fallback,
|
||||
)
|
||||
|
||||
assert build_inventory_issue_fallback(
|
||||
has_formal_ot=True,
|
||||
line_fulfillment={'lines': []},
|
||||
process_gate={},
|
||||
automation={'status': 'waiting_to_start'},
|
||||
) is None
|
||||
|
||||
|
||||
def test_waiting_inventory_maps_to_inventory_fetching_stage():
|
||||
"""waiting_inventory 必须映射到获取库存阶,禁止再落到 matching。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.processing_projection_invariants import (
|
||||
map_notice_to_processing_status_stage,
|
||||
)
|
||||
|
||||
status, stage = map_notice_to_processing_status_stage(
|
||||
SimpleNamespace(process_status='waiting_inventory', current_step=None, export_file_path=None),
|
||||
)
|
||||
assert status == 'automating'
|
||||
assert stage == 'inventory_fetching'
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
tests/test_line_inventory_match_persistence.py
|
||||
|
||||
用途:锁定 disposition → match_result 映射与 not_found/invalid_key 语义。
|
||||
依赖:pytest、line_inventory_match_persistence。
|
||||
逻辑:纯单元;不写库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
map_disposition_to_match_codes,
|
||||
)
|
||||
|
||||
|
||||
def test_complete_key_not_found_is_ready_not_found():
|
||||
"""键完整且 not_found → ready + not_found。"""
|
||||
match_result, status = map_disposition_to_match_codes(
|
||||
disposition='not_found',
|
||||
part_number='PN-1',
|
||||
reservation_id='RSV-1',
|
||||
)
|
||||
assert match_result == 'not_found'
|
||||
assert status == 'ready'
|
||||
|
||||
|
||||
def test_missing_key_is_invalid_not_zero_stock():
|
||||
"""缺料号/预约单 → invalid_key,不得当零库存。"""
|
||||
match_result, status = map_disposition_to_match_codes(
|
||||
disposition='not_found',
|
||||
part_number='',
|
||||
reservation_id='RSV-1',
|
||||
)
|
||||
assert match_result == 'invalid_key'
|
||||
assert status == 'invalid_key'
|
||||
|
||||
|
||||
def test_multi_file_conflict_maps_to_source_conflict():
|
||||
"""多源冲突 → source_conflict。"""
|
||||
match_result, status = map_disposition_to_match_codes(
|
||||
disposition='multi_file_conflict',
|
||||
part_number='PN-1',
|
||||
reservation_id='RSV-1',
|
||||
)
|
||||
assert match_result == 'source_conflict'
|
||||
assert status == 'source_conflict'
|
||||
|
||||
|
||||
def test_ok_and_shortage_are_matched_ready():
|
||||
"""ok/shortage 均为 ready+matched(数量差由投影比较)。"""
|
||||
assert map_disposition_to_match_codes(
|
||||
disposition='ok', part_number='A', reservation_id='B',
|
||||
) == ('matched', 'ready')
|
||||
assert map_disposition_to_match_codes(
|
||||
disposition='shortage', part_number='A', reservation_id='B',
|
||||
) == ('matched', 'ready')
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
tests/test_line_inventory_match_projection.py
|
||||
|
||||
用途:锁定库存匹配投影契约——not_found→0、result_missing 不得转 0、动作分域。
|
||||
依赖:pytest、line_inventory_match_projection。
|
||||
逻辑:纯单元测试,不启 Flask 全应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
ACTION_CLOSE,
|
||||
ACTION_RETRY_MATCHING,
|
||||
ACTION_RETRY_PREPARATION,
|
||||
ACTION_VIEW_FULFILLMENT,
|
||||
normalize_match_quantities,
|
||||
project_line_inventory_view,
|
||||
project_user_line_status,
|
||||
resolve_inventory_allowed_actions,
|
||||
resolve_line_allowed_actions,
|
||||
)
|
||||
|
||||
|
||||
def test_ready_not_found_normalizes_to_zero_shortage():
|
||||
"""ready + not_found 必须规范为 available=0 并标短缺。"""
|
||||
qty = normalize_match_quantities(
|
||||
match_result='not_found',
|
||||
inventory_status='ready',
|
||||
required_qty='30',
|
||||
available_qty=None,
|
||||
)
|
||||
assert qty['available_qty'] == '0'
|
||||
assert qty['shortage_qty'] == '30'
|
||||
assert qty['is_shortage'] is True
|
||||
|
||||
|
||||
def test_ready_result_missing_must_not_become_zero():
|
||||
"""ready + result_missing 不得转 0,也不能标短缺。"""
|
||||
qty = normalize_match_quantities(
|
||||
match_result='result_missing',
|
||||
inventory_status='ready',
|
||||
required_qty='30',
|
||||
available_qty=None,
|
||||
)
|
||||
assert qty['available_qty'] is None
|
||||
assert qty['shortage_qty'] is None
|
||||
assert qty['is_shortage'] is False
|
||||
assert qty['display_available'] == 'pending'
|
||||
|
||||
|
||||
def test_preparing_keeps_null_quantities():
|
||||
"""库存处理中:可用数量保持未知。"""
|
||||
qty = normalize_match_quantities(
|
||||
match_result='preparing',
|
||||
inventory_status='preparing',
|
||||
required_qty='30',
|
||||
available_qty=None,
|
||||
)
|
||||
assert qty['available_qty'] is None
|
||||
assert qty['is_shortage'] is False
|
||||
|
||||
|
||||
def test_matched_compares_quantities():
|
||||
"""matched 按实际数量比较短缺。"""
|
||||
ok = normalize_match_quantities(
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
required_qty='30',
|
||||
available_qty='50',
|
||||
)
|
||||
assert ok['is_shortage'] is False
|
||||
assert ok['available_qty'] == '50'
|
||||
short = normalize_match_quantities(
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
required_qty='30',
|
||||
available_qty='10',
|
||||
)
|
||||
assert short['is_shortage'] is True
|
||||
assert short['shortage_qty'] == '20'
|
||||
|
||||
|
||||
def test_preparing_without_rpa_allows_retry_preparation():
|
||||
"""文件未准备(非 RPA 运行中)可重试获取;关闭在 line 域。"""
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='preparing',
|
||||
match_result='preparing',
|
||||
is_shortage=False,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='inventory_file_missing',
|
||||
inventory_rpa_running=False,
|
||||
)
|
||||
line = resolve_line_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='inventory_file_missing',
|
||||
)
|
||||
assert inv == [ACTION_RETRY_PREPARATION]
|
||||
assert ACTION_CLOSE in line
|
||||
assert ACTION_RETRY_MATCHING not in inv
|
||||
|
||||
|
||||
def test_shortage_actions_preparation_and_close_only():
|
||||
"""短缺:库存域仅 preparation;行域可关闭;禁止 wait/换源。"""
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='ready',
|
||||
match_result='not_found',
|
||||
is_shortage=True,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='shortage',
|
||||
)
|
||||
line = resolve_line_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
stored_line_status='pending_decision',
|
||||
user_line_status='shortage',
|
||||
)
|
||||
assert inv == [ACTION_RETRY_PREPARATION]
|
||||
assert line == [ACTION_CLOSE]
|
||||
|
||||
|
||||
def test_wave_created_only_view_detail():
|
||||
"""已入波次仅查看履约详情。"""
|
||||
line = resolve_line_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
stored_line_status='task_created',
|
||||
user_line_status='wave_created',
|
||||
)
|
||||
inv = resolve_inventory_allowed_actions(
|
||||
has_formal_ot=True,
|
||||
inventory_status='ready',
|
||||
match_result='matched',
|
||||
is_shortage=False,
|
||||
stored_line_status='task_created',
|
||||
user_line_status='wave_created',
|
||||
)
|
||||
assert inv == []
|
||||
assert line == [ACTION_VIEW_FULFILLMENT]
|
||||
|
||||
|
||||
def test_result_missing_projects_file_missing_and_retry_prep():
|
||||
"""结果缺失投影为文件未准备,开放重试获取,不当短缺。"""
|
||||
view = project_line_inventory_view(
|
||||
has_formal_ot=True,
|
||||
fact={
|
||||
'match_result': 'result_missing',
|
||||
'inventory_status': 'ready',
|
||||
'available_qty': None,
|
||||
'inventory_snapshot_id': 9,
|
||||
'matched_at': '2026-08-07T00:00:00',
|
||||
},
|
||||
required_qty='30',
|
||||
stored_line_status='pending_decision',
|
||||
decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
assert view['available_qty'] is None
|
||||
assert view['is_shortage'] is False
|
||||
assert view['user_line_status'] == 'inventory_file_missing'
|
||||
assert ACTION_RETRY_PREPARATION in view['inventory_allowed_actions']
|
||||
assert ACTION_CLOSE in view['line_allowed_actions']
|
||||
|
||||
|
||||
def test_user_status_maps_closed_and_system_ready():
|
||||
"""存储态关闭与系统 ready 投影为用户态。"""
|
||||
assert project_user_line_status(
|
||||
inventory_status='ready',
|
||||
match_result='matched',
|
||||
is_shortage=False,
|
||||
stored_line_status='closed_unfulfillable',
|
||||
) == 'closed'
|
||||
assert project_user_line_status(
|
||||
inventory_status='ready',
|
||||
match_result='matched',
|
||||
is_shortage=False,
|
||||
stored_line_status='ready_to_fulfill',
|
||||
decision_source='system',
|
||||
) == 'auto_fulfilling'
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
tests/test_post_ot_auto_fulfill_p1.py
|
||||
|
||||
用途:锁定 BE-4/5/6/7——ot_created 接线、补偿入口、无快照 fail-closed、单位匹配键、失败列。
|
||||
依赖:pytest、unittest.mock。
|
||||
逻辑:定向单测,不依赖真实排程 runner。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_persist_without_snapshot_forbids_ready_not_found(app):
|
||||
"""BE-5:无 snapshot 时不得写入 ready/not_found。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=None)
|
||||
added = []
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc, 'resolve_review_case_for_task', return_value=None),
|
||||
patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'L1'}),
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
match_q.filter_by.return_value.filter.return_value.first.return_value = None
|
||||
match_q.filter_by.return_value.update.return_value = None
|
||||
match_q.filter_by.return_value.first.return_value = None
|
||||
|
||||
svc.persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
inventory_snapshot_id=None,
|
||||
match_payload={
|
||||
'line_results': [{
|
||||
'line_index': 0,
|
||||
'disposition': 'not_found',
|
||||
'part_number': 'PN1',
|
||||
'reservation_id': 'R1',
|
||||
'required_qty': 10,
|
||||
'available_qty': 0,
|
||||
'shortage_qty': 10,
|
||||
}],
|
||||
'resolutions': [],
|
||||
},
|
||||
)
|
||||
|
||||
assert len(added) == 1
|
||||
assert added[0].match_result == 'result_missing'
|
||||
assert added[0].inventory_status == 'unavailable'
|
||||
assert added[0].available_qty is None
|
||||
|
||||
|
||||
def test_unit_participates_in_match_key():
|
||||
"""BE-6:同料号预约单但单位不同不得命中。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
|
||||
out = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '12345',
|
||||
'quantity': 2,
|
||||
'uom': 'PCS',
|
||||
}],
|
||||
inventory_lines=[{
|
||||
'reservation_id': '12345',
|
||||
'part_number': 'PN-1',
|
||||
'uom': 'BOX',
|
||||
'qty': 100,
|
||||
'__source_code': 'SRC1',
|
||||
}],
|
||||
header_reservation_id=None,
|
||||
)
|
||||
assert out['line_results'][0]['disposition'] == 'not_found'
|
||||
|
||||
out_ok = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '12345',
|
||||
'quantity': 2,
|
||||
'uom': 'PCS',
|
||||
}],
|
||||
inventory_lines=[{
|
||||
'reservation_id': '12345',
|
||||
'part_number': 'PN-1',
|
||||
'uom': 'PCS',
|
||||
'qty': 100,
|
||||
'__source_code': 'SRC1',
|
||||
}],
|
||||
header_reservation_id=None,
|
||||
)
|
||||
assert out_ok['line_results'][0]['disposition'] == 'ok'
|
||||
assert out_ok['line_results'][0].get('unit') == 'PCS'
|
||||
|
||||
|
||||
def test_compensation_runner_noops_when_flag_disabled(app, monkeypatch):
|
||||
"""BE-4:flag 关闭时补偿扫描空跑。"""
|
||||
from app.services.schedule import shipping_post_ot_auto_fulfill_compensation_job as job
|
||||
|
||||
monkeypatch.setattr(job, 'line_auto_fulfill_enabled', lambda: False)
|
||||
with app.app_context():
|
||||
result = job.run_post_ot_auto_fulfill_compensation(limit=10)
|
||||
assert result['reason'] == 'line_auto_fulfill_disabled'
|
||||
assert result['scanned'] == 0
|
||||
|
||||
|
||||
def test_mark_auto_fulfill_failed_sets_fact_columns(app):
|
||||
"""BE-7:失败写入匹配事实独立列,不新建 wait_inventory。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=1, case_no='RC-1', confirmed_task_id=9)
|
||||
fact = SimpleNamespace(
|
||||
detail_json={},
|
||||
auto_fulfill_failed=False,
|
||||
auto_fulfill_error_code=None,
|
||||
auto_fulfill_error_message=None,
|
||||
auto_fulfill_failed_at=None,
|
||||
updated_at=None,
|
||||
)
|
||||
added = []
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(coord.ShippingOrderReviewLineDecision, 'query') as dec_q,
|
||||
patch.object(coord.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
):
|
||||
match_q.filter_by.return_value.first.return_value = fact
|
||||
dec_q.filter_by.return_value.first.return_value = None
|
||||
coord._mark_auto_fulfill_failed(
|
||||
case,
|
||||
line_keys=['L1'],
|
||||
error_code='SHIPPING.AUTO_FULFILL_FAILED',
|
||||
message='boom',
|
||||
)
|
||||
|
||||
assert fact.auto_fulfill_failed is True
|
||||
assert fact.auto_fulfill_error_code == 'SHIPPING.AUTO_FULFILL_FAILED'
|
||||
assert added == []
|
||||
|
||||
|
||||
def test_aggregate_line_fulfillment_counts_keeps_shortage_visible():
|
||||
"""UI-3/BE:系统进度与短缺分列,失败单独计数。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
_aggregate_line_fulfillment_counts,
|
||||
)
|
||||
|
||||
counts = _aggregate_line_fulfillment_counts([
|
||||
{'user_line_status': 'auto_fulfilling'},
|
||||
{'user_line_status': 'wave_created'},
|
||||
{'user_line_status': 'shortage', 'is_shortage': True},
|
||||
{'user_line_status': 'inventory_pending'},
|
||||
{'user_line_status': 'auto_fulfill_failed'},
|
||||
])
|
||||
assert counts['auto_progress_count'] == 2
|
||||
assert counts['manual_pending_count'] == 1
|
||||
assert counts['inventory_pending_count'] == 1
|
||||
assert counts['system_failed_count'] == 1
|
||||
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
tests/test_post_ot_fulfillment_wave_p0.py
|
||||
|
||||
用途:锁定本轮 P0——整波失败回滚、幂等回放、参数冲突 409、post-OT 不调用 confirm 推进。
|
||||
依赖:pytest、unittest.mock、ConflictError、post_ot / coordinator / progress 服务。
|
||||
逻辑:以 mock 隔离 DB 与队列;断言事务边界与调度边界。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
|
||||
def test_create_post_ot_wave_idempotent_replay_returns_original(app):
|
||||
"""同 key 且参数一致必须返回原 wave,不二次建波。"""
|
||||
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
|
||||
|
||||
existing = SimpleNamespace(
|
||||
id=11,
|
||||
decision_source='system',
|
||||
line_keys_hash=svc._line_keys_hash(['L1']),
|
||||
inventory_snapshot_fingerprint='9',
|
||||
result_json={
|
||||
'case_no': 'RC-1',
|
||||
'task_no': 'SN-1',
|
||||
'wave_no': 2,
|
||||
'accepted_line_keys': ['L1'],
|
||||
'skipped_line_keys': [],
|
||||
},
|
||||
)
|
||||
case = SimpleNamespace(id=1, case_no='RC-1', run=None)
|
||||
task = SimpleNamespace(id=7, task_no='SN-1')
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc.ShippingOrderReviewCase, 'query') as case_q,
|
||||
patch.object(svc, 'assert_case_is_current_workflow_version'),
|
||||
patch.object(svc, 'resolve_formal_ot', return_value={'has_formal_ot': True, 'task': task}),
|
||||
patch.object(
|
||||
svc,
|
||||
'project_review_case_line_decisions',
|
||||
return_value={
|
||||
'lines': [{
|
||||
'line_key': 'L1',
|
||||
'inventory_status': 'ready',
|
||||
'match_result': 'matched',
|
||||
'is_shortage': False,
|
||||
'required_qty': '10',
|
||||
'available_qty': '10',
|
||||
'inventory_snapshot_id': 9,
|
||||
}],
|
||||
},
|
||||
),
|
||||
patch.object(svc.ShippingOrderReviewWaveIdempotency, 'query') as idem_q,
|
||||
):
|
||||
case_q.filter_by.return_value.first.return_value = case
|
||||
idem_q.filter_by.return_value.first.return_value = existing
|
||||
|
||||
out = svc.create_post_ot_fulfillment_wave(
|
||||
case_no='RC-1',
|
||||
line_keys=['L1'],
|
||||
decision_source='system',
|
||||
idempotency_key='k-replay',
|
||||
)
|
||||
|
||||
assert out['idempotent_replay'] is True
|
||||
assert out['wave_no'] == 2
|
||||
assert out['idempotency_row_id'] == 11
|
||||
|
||||
|
||||
def test_create_post_ot_wave_param_conflict_raises_409(app):
|
||||
"""同 key 但 line_set/snapshot/source 不一致 → ConflictError(409)。"""
|
||||
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
|
||||
|
||||
existing = SimpleNamespace(
|
||||
id=11,
|
||||
decision_source='system',
|
||||
line_keys_hash=svc._line_keys_hash(['L1']),
|
||||
inventory_snapshot_fingerprint='9',
|
||||
result_json={},
|
||||
)
|
||||
case = SimpleNamespace(id=1, case_no='RC-1', run=None)
|
||||
task = SimpleNamespace(id=7, task_no='SN-1')
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc.ShippingOrderReviewCase, 'query') as case_q,
|
||||
patch.object(svc, 'assert_case_is_current_workflow_version'),
|
||||
patch.object(svc, 'resolve_formal_ot', return_value={'has_formal_ot': True, 'task': task}),
|
||||
patch.object(
|
||||
svc,
|
||||
'project_review_case_line_decisions',
|
||||
return_value={
|
||||
'lines': [{
|
||||
'line_key': 'L1',
|
||||
'inventory_status': 'ready',
|
||||
'match_result': 'matched',
|
||||
'is_shortage': False,
|
||||
'required_qty': '10',
|
||||
'available_qty': '10',
|
||||
'inventory_snapshot_id': 99, # 与已存 fingerprint=9 冲突
|
||||
}],
|
||||
},
|
||||
),
|
||||
patch.object(svc.ShippingOrderReviewWaveIdempotency, 'query') as idem_q,
|
||||
):
|
||||
case_q.filter_by.return_value.first.return_value = case
|
||||
idem_q.filter_by.return_value.first.return_value = existing
|
||||
|
||||
with pytest.raises(ConflictError) as ei:
|
||||
svc.create_post_ot_fulfillment_wave(
|
||||
case_no='RC-1',
|
||||
line_keys=['L1'],
|
||||
decision_source='system',
|
||||
idempotency_key='k-conflict',
|
||||
)
|
||||
|
||||
assert ei.value.http_status == 409
|
||||
assert ei.value.code == 'SHIPPING.REVIEW_POST_OT_WAVE_IDEMPOTENCY_CONFLICT'
|
||||
|
||||
|
||||
def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
|
||||
"""整波失败必须 rollback,且失败标记不得创建 wait_inventory 半成品。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=3, case_no='RC-FAIL', confirmed_task_id=8)
|
||||
calls: list[str] = []
|
||||
|
||||
def _boom(**_kwargs):
|
||||
calls.append('create')
|
||||
raise RuntimeError('wave_explode')
|
||||
|
||||
def _mark(case_obj, **kwargs):
|
||||
calls.append('mark')
|
||||
assert kwargs['line_keys'] == ['L1']
|
||||
assert case_obj.case_no == 'RC-FAIL'
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord, 'line_auto_fulfill_enabled', return_value=True),
|
||||
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']),
|
||||
patch.object(coord, 'create_post_ot_fulfillment_wave', side_effect=_boom),
|
||||
patch.object(coord.db.session, 'rollback', side_effect=lambda: calls.append('rollback')),
|
||||
patch.object(coord.db.session, 'flush', side_effect=lambda: calls.append('flush')),
|
||||
patch.object(coord.ShippingOrderReviewCase, 'query') as case_q,
|
||||
patch.object(coord, '_mark_auto_fulfill_failed', side_effect=_mark),
|
||||
patch.object(coord, 'schedule_post_ot_wave_progress') as schedule_mock,
|
||||
):
|
||||
case_q.filter_by.return_value.first.return_value = case
|
||||
out = coord.coordinate_post_ot_auto_fulfill(case=case, trigger='inventory_ready')
|
||||
|
||||
assert out['status'] == 'failed'
|
||||
assert calls == ['create', 'rollback', 'mark', 'flush']
|
||||
schedule_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app):
|
||||
"""无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。"""
|
||||
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
|
||||
|
||||
case = SimpleNamespace(id=4, case_no='RC-2', confirmed_task_id=12)
|
||||
fact = SimpleNamespace(detail_json={}, updated_at=None)
|
||||
added: list = []
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(coord.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(coord.ShippingOrderReviewLineDecision, 'query') as dec_q,
|
||||
patch.object(coord.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
):
|
||||
match_q.filter_by.return_value.first.return_value = fact
|
||||
dec_q.filter_by.return_value.first.return_value = None
|
||||
coord._mark_auto_fulfill_failed(
|
||||
case,
|
||||
line_keys=['L9'],
|
||||
error_code='SHIPPING.AUTO_FULFILL_FAILED',
|
||||
message='boom',
|
||||
)
|
||||
|
||||
assert fact.detail_json.get('auto_fulfill_failed') is True
|
||||
assert added == []
|
||||
|
||||
|
||||
def test_post_ot_api_does_not_call_confirm_auto_progress(app, monkeypatch):
|
||||
"""正式 OT 的 wave API 必须走 schedule_post_ot_wave_progress,禁止 confirm 推进。"""
|
||||
from app.api.workspace import shipping_notice as api
|
||||
|
||||
calls: dict[str, int] = {'confirm': 0, 'post': 0}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
return {
|
||||
'task_no': 'SN-9',
|
||||
'wave_no': 3,
|
||||
'accepted_line_keys': ['L1'],
|
||||
'review_case_id': 1,
|
||||
'idempotency_row_id': 5,
|
||||
'idempotency_key': 'k1',
|
||||
'line_fulfillment': {'lines': []},
|
||||
}
|
||||
|
||||
def _fake_post(**kwargs):
|
||||
calls['post'] += 1
|
||||
return {'auto_progress_started': True, 'status': 'queued', 'wave_no': 3}
|
||||
|
||||
def _fake_confirm(**kwargs):
|
||||
calls['confirm'] += 1
|
||||
raise AssertionError('must not call schedule_auto_progress_after_review_confirm')
|
||||
|
||||
user = SimpleNamespace(id=1)
|
||||
case = SimpleNamespace(id=1, case_no='RC-9')
|
||||
|
||||
with app.app_context():
|
||||
with app.test_request_context(
|
||||
'/api/workspace/shipping-notice/order-review-cases/RC-9/line-fulfillment/wave',
|
||||
method='POST',
|
||||
json={'line_keys': ['L1'], 'idempotency_key': 'k1'},
|
||||
):
|
||||
monkeypatch.setattr(api, '_require_user', lambda: user)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_draft_service.soft_load_review_case_for_audit',
|
||||
lambda **_k: case,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
lambda _c: {'has_formal_ot': True, 'task': SimpleNamespace(task_no='SN-9')},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.post_ot_fulfillment_wave_service.create_post_ot_fulfillment_wave',
|
||||
_fake_create,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.post_ot_wave_progress_service.schedule_post_ot_wave_progress',
|
||||
_fake_post,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_confirmation_service.schedule_auto_progress_after_review_confirm',
|
||||
_fake_confirm,
|
||||
)
|
||||
monkeypatch.setattr(api.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(api, '_ok', lambda data: data)
|
||||
|
||||
out = api.workspace_create_shipping_order_review_fulfillment_wave('RC-9')
|
||||
|
||||
assert calls['post'] == 1
|
||||
assert calls['confirm'] == 0
|
||||
assert out['post_ot_wave'] is True
|
||||
assert out['wave_progress']['wave_no'] == 3
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_diagnostics.py
|
||||
|
||||
用途:验证 Layout Job PR-0 脱敏 timings/counts 契约与 OCR 计时拆分。
|
||||
依赖:layout_diagnostics、ocr_pdf、unittest.mock。
|
||||
逻辑:覆盖全键初始化、freeze 规范化、extract_ocr_lines 推理计数,以及诊断字段不进入快照的断言辅助。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
|
||||
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
|
||||
LayoutJobDiagnostics,
|
||||
empty_layout_counts,
|
||||
empty_layout_timings,
|
||||
freeze_layout_diagnostics,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
|
||||
|
||||
def test_empty_diagnostics_contain_full_contract_keys():
|
||||
"""PR-0 初始化必须保证全部 timing/count 键存在,未执行阶段为 0。"""
|
||||
timings = empty_layout_timings()
|
||||
counts = empty_layout_counts()
|
||||
assert set(timings) >= set(LAYOUT_DIAGNOSTIC_TIMING_KEYS)
|
||||
assert set(counts) >= set(LAYOUT_DIAGNOSTIC_COUNT_KEYS)
|
||||
assert all(timings[key] == 0 for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS)
|
||||
assert counts['ocr_engine_warm'] is False
|
||||
assert all(counts[key] == 0 for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS if key != 'ocr_engine_warm')
|
||||
|
||||
|
||||
def test_freeze_layout_diagnostics_normalizes_types_and_keeps_extra_timing():
|
||||
"""freeze 输出 int/bool,并保留额外 timing 键供降级路径兼容。"""
|
||||
timings = empty_layout_timings()
|
||||
counts = empty_layout_counts()
|
||||
timings['native_layout_build_ms'] = 12.7
|
||||
timings['native_table_detect_ms'] = 3
|
||||
counts['ocr_call_count'] = 2
|
||||
counts['ocr_engine_warm'] = 1
|
||||
frozen_timings, frozen_counts = freeze_layout_diagnostics(timings, counts)
|
||||
assert frozen_timings['native_layout_build_ms'] == 12
|
||||
assert frozen_timings['native_table_detect_ms'] == 3
|
||||
assert frozen_counts['ocr_call_count'] == 2
|
||||
assert frozen_counts['ocr_engine_warm'] is True
|
||||
|
||||
|
||||
def test_extract_ocr_lines_records_inference_without_changing_lines():
|
||||
"""传入 diagnostics 时必须增加 ocr_call_count,且行坐标结果与无诊断调用一致。"""
|
||||
image = np.zeros((200, 400, 3), dtype=np.uint8)
|
||||
response = [
|
||||
[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95],
|
||||
]
|
||||
diagnostics = LayoutJobDiagnostics()
|
||||
with patch('app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine') as engine:
|
||||
engine.return_value.return_value = (response, 0.1)
|
||||
# mock 无 cache_info 时不得把调用计为 engine init
|
||||
lines_with = extract_ocr_lines(
|
||||
image, page_width=200, page_height=100,
|
||||
diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
lines_without = extract_ocr_lines(image, page_width=200, page_height=100)
|
||||
|
||||
assert lines_with[0].text == lines_without[0].text
|
||||
assert lines_with[0].bbox.model_dump() == lines_without[0].bbox.model_dump()
|
||||
assert diagnostics.counts['ocr_call_count'] == 1
|
||||
assert diagnostics.counts['ocr_page_count'] == 1
|
||||
assert diagnostics.timings['ocr_engine_init_ms'] == 0
|
||||
assert diagnostics.timings['ocr_inference_ms'] >= 0
|
||||
|
||||
|
||||
def test_snapshot_must_not_embed_diagnostics_keys():
|
||||
"""回归辅助:正式 snapshot 不得出现 timings/counts 诊断字段。"""
|
||||
snapshot = {
|
||||
'status': 'ready',
|
||||
'tables': [],
|
||||
'layout_candidate': {'pages': []},
|
||||
'coordinate_evidence': {'tables': {}, 'pages': {}},
|
||||
}
|
||||
assert 'timings' not in snapshot
|
||||
assert 'counts' not in snapshot
|
||||
assert 'timings' not in snapshot['layout_candidate']
|
||||
assert 'counts' not in snapshot['coordinate_evidence']
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/tests/test_shipping_document_layout_job.py
|
||||
|
||||
用途:验证独立布局 Job 从对象存储读取附件、按 lease 收口并在失败时同步版本状态。
|
||||
依赖:shipping_document_layout handler、lifecycle、通用 Job queue。
|
||||
逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease。
|
||||
依赖:shipping_document_layout handler、lifecycle、layout_diagnostics、通用 Job queue。
|
||||
逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease;
|
||||
PR-0 断言 Job result 含全量 timings/counts,且诊断字段不进入 layout snapshot。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,10 +17,37 @@ from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.shipping_document_layout import LAYOUT_JOB_ERROR, run_shipping_document_layout
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
|
||||
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot
|
||||
|
||||
|
||||
def _assert_layout_job_diagnostics_contract(result: dict) -> None:
|
||||
"""
|
||||
断言 Job result 含 PR-0 全量 timings/counts,且诊断字段不进 snapshot。
|
||||
|
||||
核心断言:契约键齐全;未执行阶段为 0;ocr_engine_warm 为 bool。
|
||||
"""
|
||||
timings = result.get('timings')
|
||||
counts = result.get('counts')
|
||||
assert isinstance(timings, dict)
|
||||
assert isinstance(counts, dict)
|
||||
for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS:
|
||||
assert key in timings
|
||||
assert isinstance(timings[key], int)
|
||||
assert timings[key] >= 0
|
||||
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
|
||||
assert key in counts
|
||||
if key == 'ocr_engine_warm':
|
||||
assert isinstance(counts[key], bool)
|
||||
else:
|
||||
assert isinstance(counts[key], int)
|
||||
assert counts[key] >= 0
|
||||
|
||||
|
||||
def _running_layout_job(app):
|
||||
"""创建布局版本并模拟通用队列已领取该 Job。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
@@ -59,6 +87,9 @@ def test_layout_job_completes_version_and_updates_document_current(app):
|
||||
assert job.result_json['status'] == 'ready'
|
||||
assert job.result_json['provider_status'] == 'ready'
|
||||
assert job.message == '文档版面解析完成'
|
||||
_assert_layout_job_diagnostics_contract(job.result_json)
|
||||
assert 'timings' not in version.payload_json
|
||||
assert 'counts' not in version.payload_json
|
||||
|
||||
|
||||
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
|
||||
@@ -182,6 +213,12 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
assert version.payload_json['xfa_capability']['structure_analysis_ready'] is True
|
||||
assert document.current_layout_version_id == version.id
|
||||
assert job.status == 'success'
|
||||
_assert_layout_job_diagnostics_contract(job.result_json)
|
||||
# XFA 早退未走 OCR/OpenCV;细分字段仍存在且为 0。
|
||||
assert job.result_json['counts']['ocr_call_count'] == 0
|
||||
assert job.result_json['timings']['ocr_inference_ms'] == 0
|
||||
assert 'timings' not in version.payload_json
|
||||
assert 'counts' not in version.payload_json
|
||||
|
||||
|
||||
def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
|
||||
|
||||
@@ -23,6 +23,7 @@ from app.services.shipping_notice.document_layout.mineru import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
NativePdfPage,
|
||||
attach_native_pdf_page_images,
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
extract_native_pdf_pages,
|
||||
@@ -76,6 +77,44 @@ def _page(text: str) -> NativePdfPage:
|
||||
)
|
||||
|
||||
|
||||
def test_attach_native_pdf_page_images_renders_only_missing_pages():
|
||||
"""PR-2:已有 image 的页不得重渲染;缺图页补齐后字符层保持原引用。"""
|
||||
writer = PdfWriter()
|
||||
writer.add_blank_page(width=200, height=100)
|
||||
writer.add_blank_page(width=200, height=100)
|
||||
buffer = BytesIO()
|
||||
writer.write(buffer)
|
||||
content = buffer.getvalue()
|
||||
|
||||
chars_a = [
|
||||
PositionedCharacter(
|
||||
text='A', source_index=0, bbox=LayoutBBox(x0=1, y0=1, x1=2, y1=2),
|
||||
),
|
||||
]
|
||||
chars_b = [
|
||||
PositionedCharacter(
|
||||
text='B', source_index=0, bbox=LayoutBBox(x0=1, y0=1, x1=2, y1=2),
|
||||
),
|
||||
]
|
||||
existing = np.full((20, 40), 7, dtype=np.uint8)
|
||||
pages = [
|
||||
NativePdfPage(
|
||||
page_no=1, width=200, height=100, rotation=0,
|
||||
characters=chars_a, image=existing,
|
||||
),
|
||||
NativePdfPage(
|
||||
page_no=2, width=200, height=100, rotation=0,
|
||||
characters=chars_b, image=None,
|
||||
),
|
||||
]
|
||||
attached = attach_native_pdf_page_images(content, pages, render_scale=1.0)
|
||||
assert attached[0].image is existing
|
||||
assert attached[0].characters is chars_a
|
||||
assert attached[1].image is not None
|
||||
assert attached[1].image.shape[0] > 0
|
||||
assert attached[1].characters is chars_b
|
||||
|
||||
|
||||
def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
|
||||
"""PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。"""
|
||||
class FakeTextPage:
|
||||
@@ -232,7 +271,7 @@ def test_native_pdf_repeated_text_does_not_create_cells():
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[_page('QtyQty')],
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry',
|
||||
'app.services.shipping_notice.document_layout.native_pdf.cached_reconstruct_opencv_table_geometry',
|
||||
) as opencv:
|
||||
opencv.return_value.ready = False
|
||||
opencv.return_value.issues = ['opencv_table_grid_not_detected']
|
||||
@@ -351,8 +390,14 @@ def test_scanned_pdf_uses_ocr_tokens_only_after_grid_evidence():
|
||||
evidence = OcrTableEvidence(
|
||||
ready=True,
|
||||
lines=[
|
||||
OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=60, y1=30), confidence=.99),
|
||||
OcrLine(text='Qty', bbox=LayoutBBox(x0=110, y0=10, x1=150, y1=30), confidence=.98),
|
||||
OcrLine(
|
||||
text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=60, y1=30), confidence=.99,
|
||||
line_id='ocr-line-0', image_width=400, image_height=200,
|
||||
),
|
||||
OcrLine(
|
||||
text='Qty', bbox=LayoutBBox(x0=110, y0=10, x1=150, y1=30), confidence=.98,
|
||||
line_id='ocr-line-1', image_width=400, image_height=200,
|
||||
),
|
||||
],
|
||||
cells=[
|
||||
OcrCellEvidence(
|
||||
@@ -369,7 +414,7 @@ def test_scanned_pdf_uses_ocr_tokens_only_after_grid_evidence():
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[page],
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry',
|
||||
'app.services.shipping_notice.document_layout.native_pdf.cached_reconstruct_opencv_table_geometry',
|
||||
) as geometry, patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.validate_opencv_cell_text',
|
||||
) as validation, patch(
|
||||
|
||||
@@ -14,10 +14,13 @@ import numpy as np
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import (
|
||||
OcrLine,
|
||||
build_ocr_table_evidence,
|
||||
extract_ocr_lines,
|
||||
extract_table_crop_ocr_lines,
|
||||
get_page_ocr_lines,
|
||||
page_bbox_to_normalized,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
@@ -91,9 +94,12 @@ def test_ocr_table_requires_geometry_and_all_cell_text():
|
||||
_ocr_line('Qty', LayoutBBox(x0=120, y0=10, x1=150, y1=30), .98, index=1),
|
||||
]
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', return_value=lines,
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.get_page_ocr_lines', return_value=lines,
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.reconstruct_opencv_table_geometry',
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.layout_ocr_crop_enabled',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.cached_reconstruct_opencv_table_geometry',
|
||||
return_value=geometry,
|
||||
):
|
||||
result = build_ocr_table_evidence(
|
||||
@@ -107,11 +113,12 @@ def test_ocr_table_requires_geometry_and_all_cell_text():
|
||||
assert all(item.normalized_bbox is not None for item in result.cells)
|
||||
|
||||
|
||||
def test_ocr_engine_failure_is_safe_unsupported_candidate():
|
||||
def test_ocr_engine_failure_is_safe_unsupported_candidate(app):
|
||||
"""OCR 引擎缺失或异常必须返回机器问题码,不得抛出或生成 cell。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED'] = False
|
||||
grid = parse_html_grid('<table><tr><td>A</td></tr></table>', table_id='fail')
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines',
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.get_page_ocr_lines',
|
||||
side_effect=RuntimeError('model missing'),
|
||||
):
|
||||
result = build_ocr_table_evidence(
|
||||
@@ -122,3 +129,75 @@ def test_ocr_engine_failure_is_safe_unsupported_candidate():
|
||||
assert result.ready is False
|
||||
assert result.cells == []
|
||||
assert result.issues == ['ocr_engine_unavailable']
|
||||
|
||||
|
||||
def test_page_ocr_cache_reuses_lines_within_same_job(app):
|
||||
"""同一 Job 同页二次 OCR 必须命中缓存,只推理一次。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED'] = True
|
||||
image = np.zeros((200, 400, 3), dtype=np.uint8)
|
||||
response = [[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95]]
|
||||
diagnostics = LayoutJobDiagnostics()
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine',
|
||||
) as engine:
|
||||
engine.return_value.return_value = (response, 0.1)
|
||||
first = get_page_ocr_lines(
|
||||
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
second = get_page_ocr_lines(
|
||||
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
|
||||
assert first[0].text == second[0].text == 'Part'
|
||||
assert diagnostics.counts['ocr_call_count'] == 1
|
||||
assert diagnostics.counts['ocr_page_cache_miss'] == 1
|
||||
assert diagnostics.counts['ocr_page_cache_hit'] == 1
|
||||
assert engine.return_value.call_count == 1
|
||||
|
||||
|
||||
def test_page_ocr_cache_disabled_always_infers(app):
|
||||
"""关闭页面缓存时,同页多次调用必须重复推理。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED'] = False
|
||||
image = np.zeros((200, 400, 3), dtype=np.uint8)
|
||||
response = [[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95]]
|
||||
diagnostics = LayoutJobDiagnostics()
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine',
|
||||
) as engine:
|
||||
engine.return_value.return_value = (response, 0.1)
|
||||
get_page_ocr_lines(
|
||||
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
get_page_ocr_lines(
|
||||
image, page_width=200, page_height=100, diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
|
||||
assert diagnostics.counts['ocr_call_count'] == 2
|
||||
assert diagnostics.counts['ocr_page_cache_hit'] == 0
|
||||
assert engine.return_value.call_count == 2
|
||||
|
||||
|
||||
def test_table_crop_ocr_maps_coordinates_back_to_page(app, monkeypatch):
|
||||
"""裁剪 OCR 必须把 crop 像素原点加回整页后再换算页面坐标。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED'] = True
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_crop_margin_ratio',
|
||||
lambda: 0.0,
|
||||
)
|
||||
image = np.zeros((100, 200, 3), dtype=np.uint8)
|
||||
# 表格区域 [100,0]-[200,50] 页面坐标 → 像素 [100,0]-[200,50]
|
||||
table_bbox = LayoutBBox(x0=100, y0=0, x1=200, y1=50)
|
||||
# crop 内相对多边形
|
||||
response = [[[[10, 10], [40, 10], [40, 30], [10, 30]], 'SKU', 0.99]]
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine',
|
||||
) as engine:
|
||||
engine.return_value.return_value = (response, 0.05)
|
||||
lines = extract_table_crop_ocr_lines(
|
||||
image, page_width=200, page_height=100, table_bbox=table_bbox, page_no=1,
|
||||
)
|
||||
|
||||
assert len(lines) == 1
|
||||
assert lines[0].text == 'SKU'
|
||||
# origin_x=100 → 页面 x = (10+100)*200/200 = 110
|
||||
assert lines[0].bbox.model_dump() == {'x0': 110.0, 'y0': 10.0, 'x1': 140.0, 'y1': 30.0}
|
||||
@@ -14,8 +14,10 @@ import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
DEFAULT_GRID_CONFIGS,
|
||||
cached_reconstruct_opencv_table_geometry,
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
@@ -205,6 +207,28 @@ def test_opencv_text_validation_rejects_required_cell_mismatch_even_above_rate()
|
||||
assert 'opencv_table_required_cell_text_mismatch' in result.issues
|
||||
|
||||
|
||||
def test_cached_opencv_geometry_hits_within_same_job():
|
||||
"""同 Job 二次同表几何重建必须命中缓存,且 ready 结果不变。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>A</th><th>B</th></tr><tr><td>C</td><td>D</td></tr></table>',
|
||||
table_id='cache',
|
||||
)
|
||||
image = _page_with_grid(rows=2, columns=2)
|
||||
diagnostics = LayoutJobDiagnostics()
|
||||
first = cached_reconstruct_opencv_table_geometry(
|
||||
image, page_width=600, page_height=400, table_bbox=_bbox(), grid=grid,
|
||||
diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
second = cached_reconstruct_opencv_table_geometry(
|
||||
image, page_width=600, page_height=400, table_bbox=_bbox(), grid=grid,
|
||||
diagnostics=diagnostics, page_no=1,
|
||||
)
|
||||
assert first.ready is True
|
||||
assert second is first
|
||||
assert diagnostics.counts['opencv_geometry_cache_miss'] == 1
|
||||
assert diagnostics.counts['opencv_geometry_cache_hit'] == 1
|
||||
|
||||
|
||||
def test_opencv_text_validation_rejects_low_overall_match_rate():
|
||||
"""非高风险 cell 大量错位也必须因整表一致率不足而拒绝。"""
|
||||
grid = parse_html_grid(
|
||||
|
||||
@@ -37,30 +37,59 @@ def test_resolve_confirm_outcome_distinguishes_progress_failure():
|
||||
|
||||
|
||||
def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monkeypatch):
|
||||
"""已确认且任务仍 created+Extraction 时,投影需 needs_retry 供前端刷新恢复。"""
|
||||
"""Job success 但 OT 仍 created 时,投影 needs_retry 供前端刷新恢复。"""
|
||||
from types import SimpleNamespace as NS
|
||||
from app.services.shipping_notice import order_review_projection as projection
|
||||
from app.services.shipping_notice import order_review_workbench_projection as workbench
|
||||
|
||||
case = MagicMock(status='confirmed', confirmed_task_id=9)
|
||||
stuck = MagicMock(task_no='SN-STUCK-1', process_status='created', current_order_extraction_id=3)
|
||||
finished = NS(
|
||||
id=55,
|
||||
status='success',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
result_json={},
|
||||
error_message=None,
|
||||
finished_at=None,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(projection.db.session, 'get', lambda model, pk: stuck)
|
||||
monkeypatch.setattr(
|
||||
workbench,
|
||||
'resolve_formal_ot',
|
||||
lambda _case: {
|
||||
'has_formal_ot': True,
|
||||
'task_missing': False,
|
||||
'task': stuck,
|
||||
'task_no': 'SN-STUCK-1',
|
||||
'task_id': 9,
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(workbench, 'find_active_shipping_notice_run_job', lambda **_k: None)
|
||||
monkeypatch.setattr(workbench, 'find_latest_shipping_notice_run_job', lambda **_k: finished)
|
||||
|
||||
summary = projection._project_post_confirm_auto_progress(case)
|
||||
|
||||
# 关键断言:刷新后可据此恢复琥珀色重试入口。
|
||||
# 关键断言:刷新后可据此恢复琥珀色重试入口,且保留成功 Job 身份。
|
||||
assert summary is not None
|
||||
assert summary['task_no'] == 'SN-STUCK-1'
|
||||
assert summary['needs_retry'] is True
|
||||
assert summary['status'] == 'needs_retry'
|
||||
assert summary['job_id'] == 55
|
||||
assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced'
|
||||
|
||||
|
||||
def test_task_needs_post_confirm_auto_progress_requires_created_with_extraction():
|
||||
"""仅 created 且已挂 Extraction 的任务需要确认后补推。"""
|
||||
def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction():
|
||||
"""created/parsed 且已挂 Extraction 的任务需要确认后补推。"""
|
||||
stuck = MagicMock(
|
||||
process_status='created',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
parsed = MagicMock(
|
||||
process_status='parsed',
|
||||
current_order_extraction_id=12,
|
||||
)
|
||||
progressed = MagicMock(
|
||||
process_status='waiting_upload',
|
||||
current_order_extraction_id=12,
|
||||
@@ -70,6 +99,7 @@ def test_task_needs_post_confirm_auto_progress_requires_created_with_extraction(
|
||||
current_order_extraction_id=None,
|
||||
)
|
||||
assert _task_needs_post_confirm_auto_progress(stuck) is True
|
||||
assert _task_needs_post_confirm_auto_progress(parsed) is True
|
||||
assert _task_needs_post_confirm_auto_progress(progressed) is False
|
||||
assert _task_needs_post_confirm_auto_progress(shell) is False
|
||||
assert _task_needs_post_confirm_auto_progress(None) is False
|
||||
@@ -113,6 +143,42 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch):
|
||||
assert db.session.get(Job, job_id) is None
|
||||
|
||||
|
||||
def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch):
|
||||
"""确认后 process_status=parsed 仍须入队(CONFIRM_PARSE 后常见态)。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-PARSED',
|
||||
user_id=1,
|
||||
process_status='parsed',
|
||||
current_order_extraction_id=99,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker')
|
||||
schedule = schedule_auto_progress_after_review_confirm(
|
||||
task_no=task.task_no,
|
||||
idempotent_replay=False,
|
||||
created_by_id=1,
|
||||
commit=False,
|
||||
)
|
||||
assert schedule is not None
|
||||
assert schedule.get('auto_progress_started') is True
|
||||
job = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
Job.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
Job.business_ref == task.task_no,
|
||||
Job.status == 'queued',
|
||||
)
|
||||
.one()
|
||||
)
|
||||
assert int(job.id) > 0
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
|
||||
def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkeypatch):
|
||||
"""幂等回放在任务仍悬挂于 created 时必须补推,不能无条件跳过。"""
|
||||
with app.app_context():
|
||||
@@ -221,20 +287,18 @@ def test_finalize_sync_auto_progress_swallows_execution_errors():
|
||||
|
||||
def test_run_single_task_auto_progresses_created_task_with_extraction(app, monkeypatch):
|
||||
"""复核确认后的 created+Extraction 任务必须由编排器调用 auto_progress。"""
|
||||
from app.models import ShippingBatch
|
||||
from app.services.shipping_notice import batch_orchestrator
|
||||
|
||||
with app.app_context():
|
||||
batch = ShippingBatch(batch_no='SB-CONFIRM-AP', file_count=1)
|
||||
# ShippingBatch 已物理下线;仅用 ShippingNotice 表达确认建单后的悬挂态。
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CONFIRM-AP-4',
|
||||
batch=batch,
|
||||
user_id=1,
|
||||
source_type='review_confirmation',
|
||||
process_status='created',
|
||||
current_order_extraction_id=66,
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
task_no = task.task_no
|
||||
called: dict[str, object] = {}
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
"""
|
||||
tests/test_shipping_review_workbench_stage_layering.py
|
||||
|
||||
用途:锁定复核工作台正式 OT 后状态分层——Gate 清除、automation phase、
|
||||
field_completeness、completed_checks、profile_match 四态、
|
||||
part_number(内部料号 / Schema field_id)与 reservation 分离。
|
||||
依赖:pytest、order_review_workbench_projection、types.SimpleNamespace。
|
||||
逻辑:纯单元测试;断言关键契约,不启 Flask 全应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
apply_post_ot_gate_rules,
|
||||
assert_part_number_not_reservation,
|
||||
enrich_automation_status,
|
||||
extract_line_part_number,
|
||||
extract_line_required_qty,
|
||||
map_profile_match_user_status,
|
||||
project_completed_checks,
|
||||
project_field_completeness,
|
||||
project_stage_for_task,
|
||||
project_user_profile_match,
|
||||
sanitize_part_number_vs_reservation,
|
||||
)
|
||||
|
||||
|
||||
def test_profile_match_unknown_not_collapsed_to_unmatched():
|
||||
"""unknown / 无结论不得伪装成 unmatched。"""
|
||||
assert map_profile_match_user_status('unknown') == 'unknown'
|
||||
assert map_profile_match_user_status('needs_review', candidates=[], needs_review=True) == 'unknown'
|
||||
assert map_profile_match_user_status('needs_review', candidates=[{'x': 1}], needs_review=True) == 'ambiguous'
|
||||
assert map_profile_match_user_status('matched') == 'matched'
|
||||
assert map_profile_match_user_status('not_matched') == 'unmatched'
|
||||
|
||||
|
||||
def test_user_profile_match_strips_admin_fields():
|
||||
"""普通用户不得看到候选分 / Profile code。"""
|
||||
payload = project_user_profile_match({
|
||||
'available': True,
|
||||
'status': 'matched',
|
||||
'needs_review': False,
|
||||
'candidates': [{'profile_code': 'P1', 'score': 0.9}],
|
||||
'selected_profile': {'profile_code': 'P1', 'display_name': '模板A', 'checksum': 'abc'},
|
||||
'fallback_reason_codes': ['x'],
|
||||
})
|
||||
assert payload['status'] == 'matched'
|
||||
assert payload['candidates'] == []
|
||||
assert payload['fallback_reason_codes'] == []
|
||||
assert payload['selected_profile'] == {'display_name': '模板A'}
|
||||
|
||||
|
||||
def test_field_completeness_ready_after_formal_ot():
|
||||
"""正式 OT 后 field_completeness 强制 ready,issues 清空。"""
|
||||
blocked = project_field_completeness(
|
||||
validation={
|
||||
'issues': [{'code': 'required_field_missing', 'field_code': 'part_number'}],
|
||||
'failed_gates': ['field_completeness'],
|
||||
},
|
||||
has_formal_ot=False,
|
||||
)
|
||||
assert blocked['status'] == 'blocked'
|
||||
assert blocked['issues']
|
||||
|
||||
ready = project_field_completeness(
|
||||
validation={
|
||||
'issues': [{'code': 'required_field_missing', 'field_code': 'part_number'}],
|
||||
'failed_gates': ['field_completeness'],
|
||||
},
|
||||
has_formal_ot=True,
|
||||
)
|
||||
assert ready['status'] == 'ready'
|
||||
assert ready['issues'] == []
|
||||
|
||||
|
||||
def test_completed_checks_include_formal_ot_milestone():
|
||||
"""正式 OT 里程碑进入 completed_checks。"""
|
||||
case = SimpleNamespace(updated_at=None)
|
||||
checks = project_completed_checks(
|
||||
case=case,
|
||||
process_gate={
|
||||
'gates_track': [
|
||||
{'gate_code': 'field_completeness', 'status': 'passed'},
|
||||
{'gate_code': 'customer_resolution', 'status': 'passed'},
|
||||
],
|
||||
},
|
||||
customer_resolution={'resolved': True},
|
||||
duplicate={'needs_adjudication': False},
|
||||
field_conflicts=[],
|
||||
field_completeness={'status': 'ready'},
|
||||
profile_match={'status': 'matched'},
|
||||
formal_ot={'has_formal_ot': True, 'task': SimpleNamespace(created_at=None)},
|
||||
)
|
||||
codes = {item['code'] for item in checks}
|
||||
assert 'formal_ot_created' in codes
|
||||
assert 'field_completeness' in codes
|
||||
assert 'order_review_completed' in codes
|
||||
|
||||
|
||||
def test_post_ot_clears_pre_ot_blocking_gate():
|
||||
"""正式 OT 后建单前 Gate 不得成为当前阻断。"""
|
||||
summary = apply_post_ot_gate_rules(
|
||||
{
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'field_completeness',
|
||||
'status': 'blocked_manual',
|
||||
},
|
||||
'next_action_code': 'edit_order_fields',
|
||||
'technical_auto_only': False,
|
||||
'blocking_reason_code': 'required_field_missing',
|
||||
'blocking_message': '缺字段',
|
||||
},
|
||||
has_formal_ot=True,
|
||||
)
|
||||
assert summary['current_blocking_gate'] is None
|
||||
assert summary['technical_auto_only'] is True
|
||||
assert summary['owner_type'] == 'system'
|
||||
|
||||
|
||||
def test_inventory_preparation_is_system_wait_not_human_blocker():
|
||||
"""库存准备 Worker 等待不得冒充人工待办。"""
|
||||
summary = apply_post_ot_gate_rules(
|
||||
{
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'waiting_external',
|
||||
},
|
||||
'next_action_code': 'poll_inventory_preparation',
|
||||
'technical_auto_only': False,
|
||||
},
|
||||
has_formal_ot=True,
|
||||
)
|
||||
assert summary['current_blocking_gate'] is None
|
||||
assert summary['technical_auto_only'] is True
|
||||
assert summary['owner_type'] == 'system'
|
||||
|
||||
|
||||
def test_human_inventory_gate_kept_after_ot():
|
||||
"""正式 OT 后人工库存阻断可保留。"""
|
||||
summary = apply_post_ot_gate_rules(
|
||||
{
|
||||
'current_blocking_gate': {
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked_manual',
|
||||
},
|
||||
'next_action_code': 'submit_fulfillment_decision',
|
||||
'technical_auto_only': False,
|
||||
},
|
||||
has_formal_ot=True,
|
||||
)
|
||||
assert summary['current_blocking_gate']['gate_code'] == 'inventory_sufficiency'
|
||||
assert summary['owner_type'] == 'human'
|
||||
assert summary['technical_auto_only'] is False
|
||||
|
||||
|
||||
def test_automation_phase_post_ot_waiting_to_start():
|
||||
"""正式 OT 后无 Job → waiting_to_start + phase=post_ot_progress。"""
|
||||
result = enrich_automation_status(
|
||||
{'status': 'idle', 'job_id': None},
|
||||
formal_ot={'has_formal_ot': True, 'task_missing': False, 'task_no': 'OT-1'},
|
||||
is_admin=True,
|
||||
)
|
||||
assert result['phase'] == 'post_ot_progress'
|
||||
assert result['status'] == 'waiting_to_start'
|
||||
assert result['owner_type'] == 'system'
|
||||
assert result['technical']['enqueue_status'] == 'no_job'
|
||||
|
||||
|
||||
def test_task_missing_does_not_reopen_confirm():
|
||||
"""task_missing 标记 failed,不可重试伪装建单。"""
|
||||
result = enrich_automation_status(
|
||||
{'status': 'idle'},
|
||||
formal_ot={'has_formal_ot': False, 'task_missing': True, 'task_id': 9},
|
||||
is_admin=True,
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is False
|
||||
assert result['reason_code'] == 'task_missing'
|
||||
|
||||
|
||||
def test_project_stage_for_task_created_is_order_creating():
|
||||
"""正式 OT 仍为 created 时阶段统一为 order_creating,label_key=waiting_system_start。"""
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
order_task_id=None,
|
||||
process_status='created',
|
||||
current_step=None,
|
||||
stage_nodes_json=None,
|
||||
step_payload_json=None,
|
||||
)
|
||||
stage = project_stage_for_task(task)
|
||||
assert stage['code'] == 'order_creating'
|
||||
assert stage['label_key'] == 'waiting_system_start'
|
||||
assert stage['source'] == 'process_status'
|
||||
|
||||
|
||||
def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch):
|
||||
"""Job success + OT 仍 created → failed/retryable,保留 job_id,不得伪装 waiting。"""
|
||||
from types import SimpleNamespace as NS
|
||||
from app.services.shipping_notice import order_review_workbench_projection as mod
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
project_post_ot_automation_from_job,
|
||||
)
|
||||
|
||||
task = NS(
|
||||
task_no='SN-HANG-1',
|
||||
process_status='created',
|
||||
current_order_extraction_id=9,
|
||||
)
|
||||
finished = NS(
|
||||
id=77,
|
||||
status='success',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
result_json={},
|
||||
error_message=None,
|
||||
finished_at=None,
|
||||
)
|
||||
monkeypatch.setattr(mod, 'find_active_shipping_notice_run_job', lambda **_k: None)
|
||||
monkeypatch.setattr(mod, 'find_latest_shipping_notice_run_job', lambda **_k: finished)
|
||||
|
||||
auto = project_post_ot_automation_from_job(task)
|
||||
|
||||
assert auto['status'] == 'failed'
|
||||
assert auto['retryable'] is True
|
||||
assert auto['needs_retry'] is True
|
||||
assert auto['job_id'] == 77
|
||||
assert auto['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced'
|
||||
assert auto['attempts'] == 1
|
||||
|
||||
|
||||
def test_project_stage_for_task_without_ot_is_order_review():
|
||||
"""无正式 OT 时右侧阶段固定 order_review。"""
|
||||
stage = project_stage_for_task(None, default_code='order_review')
|
||||
assert stage['code'] == 'order_review'
|
||||
|
||||
|
||||
def test_sanitize_part_number_fail_closed():
|
||||
"""生产投影串位时丢弃料号。"""
|
||||
assert sanitize_part_number_vs_reservation(part_number='A', reservation_id='B') == 'A'
|
||||
assert sanitize_part_number_vs_reservation(part_number='SAME', reservation_id='SAME') is None
|
||||
|
||||
|
||||
def test_part_number_never_falls_back_to_reservation():
|
||||
"""料号不得回退为预约单号。"""
|
||||
part = extract_line_part_number(
|
||||
{'reservation_id': 'RSV-1', 'part_number': 'RSV-1'},
|
||||
{'effective_reservation_id': 'RSV-1'},
|
||||
)
|
||||
assert part is None
|
||||
part2 = extract_line_part_number(
|
||||
{'reservation_id': 'RSV-1', 'part_number': '2000484577'},
|
||||
{},
|
||||
)
|
||||
assert part2 == '2000484577'
|
||||
assert_part_number_not_reservation(part_number='A', reservation_id='B')
|
||||
try:
|
||||
assert_part_number_not_reservation(part_number='SAME', reservation_id='SAME')
|
||||
raised = False
|
||||
except AssertionError:
|
||||
raised = True
|
||||
assert raised
|
||||
|
||||
|
||||
def test_part_number_resolves_from_schema_field_id_values():
|
||||
"""内部料号在 values[field_id] 时须解析为履约表料号,且不等于预约单号。"""
|
||||
part_field_id = 'fld-part-uuid-001'
|
||||
qty_field_id = 'fld-qty-uuid-002'
|
||||
schema_fields = {
|
||||
part_field_id: {
|
||||
'field_id': part_field_id,
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'display_name': '内部料号',
|
||||
},
|
||||
qty_field_id: {
|
||||
'field_id': qty_field_id,
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'display_name': '数量',
|
||||
},
|
||||
}
|
||||
draft_line = {
|
||||
'line_key': 'L1',
|
||||
'reservation_id': '2000484577',
|
||||
'values': {
|
||||
part_field_id: {'value': 'PN-INTERNAL-88', 'source': 'manual'},
|
||||
qty_field_id: {'value': '12', 'source': 'machine'},
|
||||
},
|
||||
'machine_fields': [],
|
||||
}
|
||||
# 无 Schema 时 UUID key 无法猜出料号
|
||||
assert extract_line_part_number(draft_line, {}) is None
|
||||
# 有 Schema 时与订单明细内部料号一致
|
||||
part = extract_line_part_number(draft_line, {}, schema_fields=schema_fields)
|
||||
assert part == 'PN-INTERNAL-88'
|
||||
assert part != '2000484577'
|
||||
qty = extract_line_required_qty(draft_line, {}, schema_fields=schema_fields)
|
||||
assert str(qty) == '12'
|
||||
# 料号若误存为预约单号则丢弃
|
||||
bad = {
|
||||
**draft_line,
|
||||
'values': {
|
||||
part_field_id: {'value': '2000484577', 'source': 'manual'},
|
||||
},
|
||||
}
|
||||
assert extract_line_part_number(bad, {}, schema_fields=schema_fields) is None
|
||||
@@ -89,7 +89,7 @@ def test_automation_failed_retryable_when_post_confirm_needs_retry():
|
||||
|
||||
|
||||
def test_serialize_review_case_hides_profile_match_for_non_admin():
|
||||
"""普通用户不得收到模板 ID / 候选分;仅 admin_only 占位。"""
|
||||
"""普通用户只拿四态裁剪,不得收到候选分 / Profile ID。"""
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
|
||||
case = SimpleNamespace(
|
||||
@@ -128,6 +128,19 @@ def test_serialize_review_case_hides_profile_match_for_non_admin():
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
|
||||
return_value={
|
||||
'available': True,
|
||||
'status': 'matched',
|
||||
'candidates': [{'profile_code': 'P1', 'score': 0.9}],
|
||||
'selected_profile': {'profile_code': 'P1', 'display_name': 'T'},
|
||||
'fallback_reason_codes': ['x'],
|
||||
'needs_review': False,
|
||||
},
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
return_value={'has_formal_ot': False, 'task_missing': False, 'task': None, 'task_no': None, 'task_id': None},
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_projection.db',
|
||||
) as mock_db, patch(
|
||||
@@ -137,9 +150,12 @@ def test_serialize_review_case_hides_profile_match_for_non_admin():
|
||||
mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None
|
||||
payload = serialize_review_case(case, is_admin=False)
|
||||
|
||||
assert payload['profile_match']['available'] is False
|
||||
assert payload['profile_match']['visibility'] == 'admin_only'
|
||||
assert payload['profile_match']['visibility'] == 'user'
|
||||
assert payload['profile_match']['status'] == 'matched'
|
||||
assert payload['profile_match'].get('candidates') == []
|
||||
assert payload['automation']['phase'] == 'pre_ot_stp'
|
||||
assert 'field_completeness' in payload
|
||||
assert 'completed_checks' in payload
|
||||
assert payload['automation']['status'] in {'idle', 'waiting_to_start'}
|
||||
|
||||
|
||||
@@ -193,6 +209,9 @@ def test_serialize_review_case_exposes_profile_match_for_admin():
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
|
||||
return_value=admin_payload,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
return_value={'has_formal_ot': False, 'task_missing': False, 'task': None, 'task_no': None, 'task_id': None},
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_projection.db',
|
||||
) as mock_db, patch(
|
||||
@@ -205,6 +224,92 @@ def test_serialize_review_case_exposes_profile_match_for_admin():
|
||||
assert payload['profile_match']['available'] is True
|
||||
assert payload['profile_match']['visibility'] == 'admin'
|
||||
assert payload['profile_match']['candidates'][0]['profile_id'] == 9
|
||||
assert payload['profile_match']['status'] == 'matched'
|
||||
|
||||
|
||||
def test_task_missing_technical_progress_admin_only():
|
||||
"""task_missing 时 technical_progress 仅管理员可见;普通用户不得拿到诊断对象。"""
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=3,
|
||||
case_no='SORC-TM-1',
|
||||
run_id=3,
|
||||
unit_id=None,
|
||||
document_id=12,
|
||||
candidate_id=None,
|
||||
status='confirmed',
|
||||
disposition=None,
|
||||
confirmed_task_id=99,
|
||||
current_draft=None,
|
||||
run=SimpleNamespace(
|
||||
run_no='RUN-TM',
|
||||
schema_version_id=1,
|
||||
input_snapshot_json={'schema': {'definition': {'fields': []}}, 'documents': []},
|
||||
),
|
||||
)
|
||||
formal_ot = {
|
||||
'has_formal_ot': False,
|
||||
'task_missing': True,
|
||||
'task': None,
|
||||
'task_no': None,
|
||||
'task_id': 99,
|
||||
}
|
||||
|
||||
common_patches = [
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.project_review_case_customer_resolution',
|
||||
return_value={'resolved': True},
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_field_conflict_service.project_review_case_field_conflicts',
|
||||
return_value=[],
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_duplicate_service.project_review_case_duplicate',
|
||||
return_value={'needs_adjudication': False},
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_reservation_service.project_review_case_reservation',
|
||||
return_value=None,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_fulfillment_decision_service.project_review_case_line_decisions',
|
||||
return_value=None,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate',
|
||||
return_value=None,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
|
||||
return_value={'available': False, 'status': 'unavailable', 'candidates': []},
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
return_value=formal_ot,
|
||||
),
|
||||
patch('app.services.shipping_notice.order_review_projection.db'),
|
||||
patch('app.models.ShippingProcessExecution'),
|
||||
]
|
||||
|
||||
with common_patches[0], common_patches[1], common_patches[2], common_patches[3], \
|
||||
common_patches[4], common_patches[5], common_patches[6], common_patches[7], \
|
||||
common_patches[8] as mock_db, common_patches[9] as mock_exec:
|
||||
mock_db.session.get.return_value = None
|
||||
mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None
|
||||
user_payload = serialize_review_case(case, is_admin=False)
|
||||
admin_payload = serialize_review_case(case, is_admin=True)
|
||||
|
||||
assert user_payload['task_missing'] is True
|
||||
assert user_payload.get('technical_progress') in (None, {})
|
||||
assert not (user_payload.get('automation') or {}).get('technical')
|
||||
|
||||
assert admin_payload['task_missing'] is True
|
||||
tech = admin_payload.get('technical_progress') or {}
|
||||
assert tech.get('status') == 'task_missing'
|
||||
assert tech.get('confirmed_task_id') == 99
|
||||
assert (admin_payload.get('automation') or {}).get('technical', {}).get('enqueue_status') == 'task_missing'
|
||||
|
||||
|
||||
def test_project_user_gate_summary_clears_stale_confirm_customer(monkeypatch):
|
||||
|
||||
@@ -170,3 +170,73 @@ def test_automation_projection_uses_active_job_over_failed_history(app):
|
||||
)
|
||||
assert result['status'] == 'queued'
|
||||
assert result['job_id'] == 88
|
||||
|
||||
|
||||
def test_stp_handler_accepts_worker_contract_and_finishes_owned_attempt(app):
|
||||
"""Worker 按 handler(ctx, payload) 调用时,STP Handler 应消费冻结载荷并按代次成功收口。"""
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import shipping_stp_auto_create as handler
|
||||
|
||||
job = SimpleNamespace(
|
||||
id=906,
|
||||
attempts=2,
|
||||
payload_json={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3},
|
||||
)
|
||||
ctx = JobContext(config={}, logger=MagicMock(), extras={})
|
||||
with patch.object(handler.db.session, 'get', return_value=job), patch.object(
|
||||
handler,
|
||||
'execute_stp_auto_create_job',
|
||||
return_value={'ok': True, 'message': 'done', 'task_no': 'SN-1'},
|
||||
) as execute_mock, patch.object(handler, 'finish_job') as finish_mock, patch.object(
|
||||
handler,
|
||||
'fail_job',
|
||||
) as fail_mock:
|
||||
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 906})
|
||||
|
||||
execute_mock.assert_called_once_with(
|
||||
payload={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3, 'job_id': 906},
|
||||
job_id=906,
|
||||
)
|
||||
finish_mock.assert_called_once_with(
|
||||
906,
|
||||
result={'ok': True, 'message': 'done', 'task_no': 'SN-1'},
|
||||
message='done',
|
||||
owned_attempt=2,
|
||||
)
|
||||
fail_mock.assert_not_called()
|
||||
|
||||
|
||||
def test_stp_handler_uses_fail_job_contract_for_business_failure(app):
|
||||
"""业务失败必须使用 fail_job(error/result/retryable/owned_attempt),不得传旧参数名。"""
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import shipping_stp_auto_create as handler
|
||||
|
||||
job = SimpleNamespace(
|
||||
id=907,
|
||||
attempts=1,
|
||||
payload_json={'case_no': 'SORC-STP-HANDLER-FAIL'},
|
||||
)
|
||||
result = {
|
||||
'ok': False,
|
||||
'error_code': 'SHIPPING.STP_NOT_ELIGIBLE',
|
||||
'message': 'not eligible',
|
||||
}
|
||||
ctx = JobContext(config={}, logger=MagicMock(), extras={})
|
||||
with patch.object(handler.db.session, 'get', return_value=job), patch.object(
|
||||
handler,
|
||||
'execute_stp_auto_create_job',
|
||||
return_value=result,
|
||||
), patch.object(handler, 'finish_job') as finish_mock, patch.object(
|
||||
handler,
|
||||
'fail_job',
|
||||
) as fail_mock:
|
||||
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 907})
|
||||
|
||||
fail_mock.assert_called_once_with(
|
||||
907,
|
||||
error='not eligible',
|
||||
result=result,
|
||||
retryable=True,
|
||||
owned_attempt=1,
|
||||
)
|
||||
finish_mock.assert_not_called()
|
||||
@@ -211,8 +211,8 @@ def test_allowed_system_facts_use_export_sequence_not_line_no():
|
||||
assert 'line_no' not in ALLOWED_SYSTEM_FACTS
|
||||
|
||||
|
||||
def test_default_derivation_rules_are_disabled_copy_if_empty():
|
||||
"""新草稿预置 customer_po_line_no→line_no,默认关闭。"""
|
||||
def test_default_derivation_rules_are_enabled_copy_if_empty():
|
||||
"""新草稿预置 customer_po_line_no→line_no,默认启用,空项次自动从客户PO行号派生。"""
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
default_derivation_rules,
|
||||
normalize_derivation_rules,
|
||||
@@ -221,7 +221,7 @@ def test_default_derivation_rules_are_disabled_copy_if_empty():
|
||||
rules = default_derivation_rules()
|
||||
assert rules == [{
|
||||
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO',
|
||||
'enabled': False,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
|
||||
Reference in new issue
Block a user