feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉
- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更 - 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配 - 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定 - 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口 - 同步四语言文案、技术文档与实施计划
This commit is contained in:
1 parent
e38e5a63fe
commit
ea94fb28db
35 files changed
+2675
-83
No files matched your search
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
tests/test_inventory_source_gate_notice_task.py
|
||||
|
||||
用途:锁定「库存源稳定门禁 / 库存身份对 ShippingNotice 的归一」契约。
|
||||
依赖:pytest、inventory_source_gate、inventory_candidate_projection、app 夹具(内存测试库)。
|
||||
逻辑:货代上传入口按 business_no 加载 Notice,而候选集事实挂在 OT 上;门禁必须沿
|
||||
order_task_id 归一读取。历史缺陷:Notice 缺 active_inventory_candidate_set_id
|
||||
字段导致 is_inventory_source_stable(Notice) 恒 False,RPA 上传被
|
||||
「库存源尚未确定」静默拦截(无事件、无 attempt 记录)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _make_frozen_task_with_notice(task_no: str):
|
||||
"""构造带冻结候选集(单源 CRANE)的 OT 及其已绑定 Notice。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
candidate_set = ShippingInventoryCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=1,
|
||||
lifecycle_status='frozen',
|
||||
input_fingerprint=f'fp-{task_no}',
|
||||
routing_rule_version_json={},
|
||||
)
|
||||
db.session.add(candidate_set)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryCandidateSource(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
source_code='CRANE',
|
||||
candidate_order=1,
|
||||
candidate_origin='rule',
|
||||
))
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
line_no=1,
|
||||
part_number='PN-1',
|
||||
reservation_id='3000092917',
|
||||
source_codes_json=['CRANE'],
|
||||
))
|
||||
task.active_inventory_candidate_set_id = int(candidate_set.id)
|
||||
db.session.flush()
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no=f'SN-{task_no}',
|
||||
order_task_id=int(task.id),
|
||||
business_no=f'USZ{task_no[-6:]}',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
return task, notice
|
||||
|
||||
|
||||
def _patch_source_lookup(monkeypatch):
|
||||
"""注入启用的 CRANE 源配置(inventory_match 动态仓),免建 RPA Profile。"""
|
||||
from app.services.shipping_notice import inventory_source_gate as gate_mod
|
||||
|
||||
def _source(code):
|
||||
if str(code).upper() != 'CRANE':
|
||||
return None
|
||||
return {
|
||||
'source_code': 'CRANE',
|
||||
'display_name': 'Crane FootPrint',
|
||||
'connector_type': 'crane',
|
||||
'warehouse_resolution_mode': 'inventory_match',
|
||||
'fixed_warehouse_id': None,
|
||||
'enabled': True,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
|
||||
|
||||
|
||||
def test_inventory_source_stable_resolves_notice_to_order_task(app, monkeypatch):
|
||||
"""门禁对 Notice 必须沿 order_task_id 读取冻结候选集,判定与 OT 一致。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
|
||||
task, notice = _make_frozen_task_with_notice('OT-NOTICE-GATE-OK')
|
||||
# 断言意图:OT 与其 Notice 的稳定性判定一致(历史缺陷:Notice 恒 False)
|
||||
assert is_inventory_source_stable(task) is True
|
||||
assert is_inventory_source_stable(notice) is True
|
||||
# 断言意图:库存身份(RPA 网点/仓库)对两者一致,且能解析到源
|
||||
identity_ot = task_inventory_identity(task)
|
||||
identity_notice = task_inventory_identity(notice)
|
||||
assert identity_ot == identity_notice
|
||||
assert identity_notice['inventory_source_code'] == 'CRANE'
|
||||
|
||||
|
||||
def test_inventory_source_stable_fail_closed_without_order_task(app, monkeypatch):
|
||||
"""Notice 缺 OT 绑定时保持 fail-closed(不得误判稳定)。"""
|
||||
_patch_source_lookup(monkeypatch)
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
|
||||
orphan = ShippingNotice(
|
||||
task_no='SN-ORPHAN-NOTICE',
|
||||
business_no='USZORPH01',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(orphan)
|
||||
db.session.flush()
|
||||
# 断言意图:无法归一到 OT 的 Notice 保持 fail-closed
|
||||
assert is_inventory_source_stable(orphan) is False
|
||||
@@ -187,3 +187,91 @@ def test_persist_updates_part_available_qty_on_existing_row(app):
|
||||
assert rows[0].part_available_qty is None
|
||||
# 断言意图:同快照幂等更新,始终只有一条 current 事实
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 行级文件归因契约(多源池:锚点文件 ≠ 命中文件)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_inventory_file(app, file_no: str, warehouse_id: str) -> int:
|
||||
"""构造最小可用库存快照文件,返回主键。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
|
||||
file_row = ShippingInventoryFile(
|
||||
inventory_file_no=file_no,
|
||||
storage_path=f'/tmp/{file_no}.xlsx',
|
||||
source_code='DSV360_TEST',
|
||||
warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id,
|
||||
snapshot_status='ready',
|
||||
line_count=1,
|
||||
share_mode='warehouse_pool',
|
||||
)
|
||||
db.session.add(file_row)
|
||||
db.session.flush()
|
||||
return int(file_row.id)
|
||||
|
||||
|
||||
def _ok_result(*, line_index: int = 0, inventory_file_no: str | None = None) -> dict:
|
||||
"""构造命中库存的行结果桩;inventory_file_no 模拟匹配器回填的命中文件身份。"""
|
||||
result = {
|
||||
'line_index': line_index,
|
||||
'disposition': 'ok',
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'required_qty': 8.0,
|
||||
'available_qty': 8.0,
|
||||
}
|
||||
if inventory_file_no is not None:
|
||||
result['inventory_file_no'] = inventory_file_no
|
||||
return result
|
||||
|
||||
|
||||
def test_persist_attributes_line_to_hit_file_not_anchor(app):
|
||||
"""多源池下行命中 B 文件时,inventory_snapshot_id 必须归因 B,而非任务锚点 A。
|
||||
|
||||
历史缺陷:持久化把任务级锚点文件 ID 盖到所有行,Excel 仓库列因此写成
|
||||
锚点仓(AWSCV 单写成 CMH01)。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile
|
||||
|
||||
task = _make_snapshot_task('OT-LINE-FILE-ATTR')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR', 'BYAWSCMH01')
|
||||
hit_id = _make_inventory_file(app, 'SIF-TEST-HIT', 'AWSCV')
|
||||
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_ok_result(inventory_file_no='SIF-TEST-HIT')],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:行事实挂到命中文件,而不是任务级锚点文件
|
||||
assert rows[0].inventory_snapshot_id == hit_id
|
||||
assert rows[0].matched_file_no == 'SIF-TEST-HIT'
|
||||
# 断言意图:仓库身份可由命中文件直接推出(Excel 仓库列数据源)
|
||||
hit_file = db.session.get(ShippingInventoryFile, rows[0].inventory_snapshot_id)
|
||||
assert hit_file.warehouse_id == 'AWSCV'
|
||||
|
||||
|
||||
def test_persist_falls_back_to_anchor_without_line_file_no(app):
|
||||
"""行结果未回填文件号(如 not_found)时,保持任务级锚点回退,行为不变。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-LINE-FILE-FALLBACK')
|
||||
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR-FB', 'BYAWSCMH01')
|
||||
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=None)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=anchor_id,
|
||||
)
|
||||
# 断言意图:无命中文件身份的行回退锚点快照(历史行为兼容)
|
||||
assert rows[0].inventory_snapshot_id == anchor_id
|
||||
@@ -31,6 +31,12 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact(Excel 源锁定判断,查库)依赖;
|
||||
# 纯单测无 Flask/DB,打桩为「Excel 已生成」使刷新块短路,保持本用例聚焦行级收窄断言。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_export_archive.py
|
||||
|
||||
用途:shipping_notice 批量导出归档(build_export_archive)下载授权单测。
|
||||
依赖:pytest、ShippingNotice、export_archive.build_export_archive。
|
||||
逻辑:批量选择与单票导出消费同一谓词口径(创建者或管理员);无 Artifact 时
|
||||
保留 manifest missing 语义,并按票携带 business_no 供端点写访问审计。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ShippingNotice
|
||||
|
||||
|
||||
def test_build_export_archive_selects_by_creator_or_admin(app):
|
||||
"""批量归档与单票下载同一谓词:陌生用户整体拒绝,创建者/管理员放行。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
|
||||
owned = ShippingNotice(
|
||||
task_no="SN-ARC-OWNED", business_no="QMN-ARC-1", user_id=7, source_type="manual",
|
||||
)
|
||||
db.session.add(owned)
|
||||
db.session.commit()
|
||||
|
||||
# 非创建者普通用户:任一越权即整体拒绝(防部分成功)。
|
||||
with pytest.raises(NotFoundError):
|
||||
build_export_archive(user_id=8, business_nos=["QMN-ARC-1"])
|
||||
|
||||
# 创建者放行;无 Artifact 时保留 missing_artifact 语义并携带 business_no。
|
||||
_stream, _name, manifest = build_export_archive(user_id=7, business_nos=["QMN-ARC-1"])
|
||||
assert manifest["entries"][0]["status"] == "missing_artifact"
|
||||
assert manifest["entries"][0]["business_no"] == "QMN-ARC-1"
|
||||
|
||||
# 管理员可下载=可见:他人正式 Notice 放行(端点按票补访问审计)。
|
||||
_stream, _name, admin_manifest = build_export_archive(
|
||||
user_id=8, business_nos=["QMN-ARC-1"], is_admin=True,
|
||||
)
|
||||
assert admin_manifest["entries"][0]["task_no"] == "SN-ARC-OWNED"
|
||||
@@ -321,6 +321,28 @@ def test_get_task_for_user_rejects_null_owner(app):
|
||||
assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None
|
||||
|
||||
|
||||
def test_can_download_task_export_creator_or_admin(app):
|
||||
"""导出统一谓词:创建者/管理员可下载;非创建者普通用户与无主单一律拒绝。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.query_service import can_download_task_export
|
||||
|
||||
owned = ShippingNotice(task_no="SN-DL-OWNED", business_no="QMN-DL-1", user_id=7, source_type="manual")
|
||||
orphan = ShippingNotice(task_no="SN-DL-ORPHAN", business_no="QMN-DL-2", user_id=None, source_type="manual")
|
||||
db.session.add_all([owned, orphan])
|
||||
db.session.commit()
|
||||
|
||||
# 创建者可下载;同票对非创建者普通用户拒绝。
|
||||
assert can_download_task_export(owned, user_id=7) is True
|
||||
assert can_download_task_export(owned, user_id=8) is False
|
||||
# 管理员可下载=可见:他人票与无主票均放行(下载留痕审计兜底)。
|
||||
assert can_download_task_export(owned, user_id=8, is_admin=True) is True
|
||||
assert can_download_task_export(orphan, user_id=7) is False
|
||||
assert can_download_task_export(orphan, user_id=7, is_admin=True) is True
|
||||
# 缺实体一律拒绝。
|
||||
assert can_download_task_export(None, user_id=7, is_admin=True) is False
|
||||
|
||||
|
||||
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
|
||||
"""SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -465,6 +465,39 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa
|
||||
assert "download_excel" in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_gates_download_by_viewer(app, monkeypatch) -> None:
|
||||
"""下载动作与导出端点同一谓词:创建者/管理员下发,非创建者不下发;viewer 缺省维持聊天旧口径。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-VIEWER-EXPORT",
|
||||
source_type="manual",
|
||||
user_id=7,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state.resolve_task_export_download',
|
||||
lambda _task: (object(), 'shipping-export.xlsx'),
|
||||
)
|
||||
|
||||
def button_ids(state):
|
||||
return [
|
||||
item.get("code")
|
||||
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
|
||||
if item
|
||||
]
|
||||
|
||||
# 创建者与管理员可见下载动作(管理员可下载=可见,消除"看得到点不动")。
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=7))
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=8, viewer_is_admin=True))
|
||||
# 非创建者普通用户不得收到下载动作(端点仍会拒绝,UI 不再误导)。
|
||||
assert "download_excel" not in button_ids(build_task_ui_state(task, viewer_user_id=8))
|
||||
# viewer 缺省 = 聊天链路(会话与创建者同源),维持仅 Artifact 授权的旧口径。
|
||||
assert "download_excel" in button_ids(build_task_ui_state(task))
|
||||
|
||||
|
||||
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
|
||||
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1651,6 +1651,12 @@ def test_inventory_preparation_mode_maps_by_action_code(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
|
||||
lambda _execution: task,
|
||||
)
|
||||
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact + 候选源刷新前置(查库)依赖;
|
||||
# 本用例聚焦动作码→mode 映射,打桩为「Excel 已生成」使刷新块短路,隔离刷新链副作用。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: SimpleNamespace(id=77),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: candidate_set,
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
"""
|
||||
tests/test_shipping_refresh_inventory_candidates.py
|
||||
|
||||
用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评,
|
||||
未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。
|
||||
依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与
|
||||
inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、
|
||||
process_gate_executor(Task 2 的挂载点集成测试)。
|
||||
逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫
|
||||
(目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在
|
||||
人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _task(set_id=10):
|
||||
"""构造最小 OT 形状:仅 helper/执行器读取的字段。"""
|
||||
return SimpleNamespace(
|
||||
id=19, task_no='SN-REFRESH',
|
||||
order_snapshot_id=3,
|
||||
active_inventory_candidate_set_id=set_id,
|
||||
step_payload_json={},
|
||||
)
|
||||
|
||||
|
||||
def _active_set(line_defs):
|
||||
"""构造最小活动候选集:lines 为 (line_no, codes) 列表。"""
|
||||
return SimpleNamespace(
|
||||
id=10, frozen_by_id=None, sources=[],
|
||||
lines=[
|
||||
SimpleNamespace(
|
||||
line_no=line_no, source_codes_json=list(codes),
|
||||
source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}',
|
||||
)
|
||||
for line_no, codes in line_defs
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'):
|
||||
"""隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.extract_routing_context',
|
||||
lambda _task: {'customer': 'X'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint',
|
||||
lambda _ctx: fingerprint,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version',
|
||||
lambda: config_version,
|
||||
)
|
||||
|
||||
|
||||
# ---------- 任务级刷新 ----------
|
||||
|
||||
def test_refresh_skips_when_single_source_resolved(app, monkeypatch):
|
||||
"""[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU'],
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_refresh_skips_when_manual_selection_exists(app, monkeypatch):
|
||||
"""[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch):
|
||||
"""[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task(set_id=10)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
|
||||
)
|
||||
|
||||
def _fake_readjudicate(_task, **_k):
|
||||
task.active_inventory_candidate_set_id = 11
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
_fake_readjudicate,
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True
|
||||
assert events and events[0][0] == 'inventory_candidates_refreshed'
|
||||
assert events[0][1]['scope'] == 'task'
|
||||
assert events[0][1]['previous_set_id'] == 10
|
||||
assert events[0][1]['new_set_id'] == 11
|
||||
|
||||
|
||||
def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch):
|
||||
"""[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task(set_id=10)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
|
||||
lambda _task, **_k: None,
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_candidates_from_current_routing(task) is False
|
||||
assert not events
|
||||
|
||||
|
||||
# ---------- 行级刷新 ----------
|
||||
|
||||
def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch):
|
||||
"""[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSDU'])]),
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch):
|
||||
"""[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
|
||||
)
|
||||
called = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch):
|
||||
"""[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='unresolved', source_codes=()),
|
||||
)
|
||||
freeze_called = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda *_a, **_k: freeze_called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not freeze_called
|
||||
|
||||
|
||||
def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch):
|
||||
"""[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: None,
|
||||
)
|
||||
freeze_called = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda *_a, **_k: freeze_called.append(1),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not freeze_called
|
||||
|
||||
|
||||
def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch):
|
||||
"""[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([
|
||||
(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']),
|
||||
(2, ['DSV360_AWSCV']),
|
||||
]),
|
||||
)
|
||||
_patch_routing_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: {'source_code': code},
|
||||
)
|
||||
freeze_kwargs = []
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12),
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True
|
||||
projections = freeze_kwargs[0]['line_projections']
|
||||
assert projections[0]['line_no'] == 1
|
||||
assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
assert projections[1]['line_no'] == 2
|
||||
assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV']
|
||||
assert events and events[0][0] == 'inventory_candidates_refreshed'
|
||||
assert events[0][1]['scope'] == 'line'
|
||||
assert events[0][1]['line_no'] == 1
|
||||
assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
|
||||
|
||||
def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch):
|
||||
"""[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。"""
|
||||
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
|
||||
|
||||
task = _task()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
|
||||
)
|
||||
_patch_routing_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
|
||||
lambda _task, **_k: [{'part_number': 'PN1'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
|
||||
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
|
||||
lambda code, **_k: {'source_code': code},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
freeze_service, 'freeze_candidates_for_task',
|
||||
lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10),
|
||||
)
|
||||
events = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.tool_common.log_task_event',
|
||||
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
|
||||
)
|
||||
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
|
||||
assert not events
|
||||
|
||||
|
||||
def _retry_payload(**overrides):
|
||||
base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def _exercise_retry_handler(
|
||||
monkeypatch, task, payload, *,
|
||||
refresh_calls, line_scope=None, excel_artifact=None, ensure_calls=None, line_refresh_result=False,
|
||||
):
|
||||
"""按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。
|
||||
|
||||
refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。
|
||||
line_scope 传 dict 时每次解析都返回它(缺省行为);传 list 时按调用次序逐个弹出
|
||||
(用尽后返回 None),用于断言「刷新产生新集后重解析行作用域」。
|
||||
line_refresh_result 控制行级刷新 helper mock 的返回值(True 表示产生了新候选集)。
|
||||
ensure_calls 顺序捕获 ensure_inventory 收到的 payload(供断言取数范围)。
|
||||
另须打桩 inventory_candidate_projection 三个读取函数:执行器 [STEP 0A] 会真实查库校验
|
||||
活动 CandidateSet,假 Task 不打桩会被提前拦回 inventory_source_routing_required,
|
||||
永远到不了被测的 [STEP 0B] 刷新块(与 test_shipping_line_scoped_inventory_retry 同模式)。
|
||||
"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None)
|
||||
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
|
||||
lambda _task: SimpleNamespace(id=1),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
|
||||
lambda _task: [SimpleNamespace(source_codes_json=['DSV360_AWSDU'])],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
|
||||
lambda _task: [SimpleNamespace(source_code='DSV360_AWSDU')],
|
||||
)
|
||||
if isinstance(line_scope, list):
|
||||
scope_sequence = list(line_scope)
|
||||
monkeypatch.setattr(
|
||||
executor,
|
||||
'_resolve_line_inventory_scope',
|
||||
lambda _task, **_k: scope_sequence.pop(0) if scope_sequence else None,
|
||||
)
|
||||
else:
|
||||
monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope)
|
||||
monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
|
||||
lambda _task: excel_artifact,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing',
|
||||
lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing',
|
||||
lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or line_refresh_result,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
|
||||
lambda **_k: {'outcome': 'passed'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
|
||||
lambda **_k: None,
|
||||
)
|
||||
if ensure_calls is None:
|
||||
ensure_calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda _payload: ensure_calls.append(dict(_payload)) or {'status': 'ok', 'data': {}},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
|
||||
lambda _task: 'inventory_preparation_failed',
|
||||
)
|
||||
return executor._handle_retry_inventory_preparation(
|
||||
execution=execution, gate=gate, payload=payload,
|
||||
)
|
||||
|
||||
|
||||
def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch):
|
||||
"""[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。"""
|
||||
refresh_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls,
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'task'
|
||||
assert refresh_calls[0][1].get('execution_id') == 5
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch):
|
||||
"""[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。"""
|
||||
refresh_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'line'
|
||||
assert refresh_calls[0][1].get('line_no') == 1
|
||||
assert refresh_calls[0][1].get('execution_id') == 5
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch):
|
||||
"""[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。"""
|
||||
refresh_calls = []
|
||||
task = _task()
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'),
|
||||
refresh_calls=refresh_calls,
|
||||
)
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls,
|
||||
excel_artifact=SimpleNamespace(id=77),
|
||||
)
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
excel_artifact=SimpleNamespace(id=77),
|
||||
)
|
||||
assert not refresh_calls
|
||||
|
||||
|
||||
def test_retry_line_refresh_requeries_with_new_scope(app, monkeypatch):
|
||||
"""[断言] 行级刷新产生新候选集后须按同参重解析行作用域:同一次点击的失效与 RPA 取数
|
||||
直接使用新冻结码,而非刷新前解析的旧码;重解析为 None 时才保守沿用旧值。"""
|
||||
refresh_calls = []
|
||||
ensure_calls = []
|
||||
outcome = _exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
|
||||
line_scope=[
|
||||
{'source_codes': ['DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
{'source_codes': ['DSV360_AWSDU', 'DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
|
||||
],
|
||||
line_refresh_result=True,
|
||||
ensure_calls=ensure_calls,
|
||||
)
|
||||
assert refresh_calls and refresh_calls[0][0] == 'line'
|
||||
assert refresh_calls[0][1].get('line_no') == 1
|
||||
assert ensure_calls and ensure_calls[-1].get('source_codes') == ['DSV360_AWSDU', 'DSV360_AWSCV']
|
||||
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
|
||||
|
||||
|
||||
def test_retry_from_preparation_does_not_refresh(app, monkeypatch):
|
||||
"""[断言] retry_inventory_from_preparation 不做候选集刷新前置(仅 retry_inventory_preparation 触发,锁定文档排除项)。"""
|
||||
refresh_calls = []
|
||||
_exercise_retry_handler(
|
||||
monkeypatch, _task(), _retry_payload(action_code='retry_inventory_from_preparation'),
|
||||
refresh_calls=refresh_calls,
|
||||
)
|
||||
assert not refresh_calls
|
||||
Reference in new issue
Block a user