feat(shipping-notice): 增加 RPA 库存回调处理逻辑,支持跳过无库存情况
This commit is contained in:
1 parent
f21216f81e
commit
c3f05ba96b
25 files changed
+1619
-81
No files matched your search
@@ -0,0 +1,74 @@
|
||||
"""scripts/rpa/dsv_export_batch_smoke.py 轻量单测(退出码与 REQUIRE_EXPORT 开关)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_dsv_export_batch_smoke():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _load_freight_rpa_worker():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke_exit_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_resolve_smoke_scenario_exit_code_all_skipped_default_passes():
|
||||
"""默认不要求导出时,全 skipped 应退出 0。"""
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=False,
|
||||
) == 0
|
||||
|
||||
|
||||
def test_resolve_smoke_scenario_exit_code_all_skipped_require_export_fails():
|
||||
"""FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2。"""
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=True,
|
||||
) == 2
|
||||
|
||||
|
||||
def test_resolve_smoke_scenario_exit_code_has_success_with_require_export():
|
||||
"""require_export=true 但已有 success 导出时仍应退出 0。"""
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [
|
||||
{"source_code": "A", "status": "success", "success": True},
|
||||
{"source_code": "B", "status": "skipped", "success": False, "skipped": True},
|
||||
]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=True,
|
||||
) == 0
|
||||
@@ -33,6 +33,16 @@ def _load_freight_rpa_worker():
|
||||
return module
|
||||
|
||||
|
||||
def _load_dsv_export_batch_smoke():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_worker_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
|
||||
return {
|
||||
@@ -270,18 +280,17 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
assert trigger["rpa_inventory_source"]["query"]["program_label"] == "AWSDU - Prod (JDA)"
|
||||
assert trigger["rpa_inventory_source"]["query"]["owner_code"] == "CADU-0000000100"
|
||||
|
||||
assert callbacks == [
|
||||
(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
{
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"success": True,
|
||||
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"rpa_mode": "browser",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
},
|
||||
)
|
||||
]
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_payload == {
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"rpa_mode": "browser",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
}
|
||||
assert not trigger_path.exists()
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
|
||||
@@ -322,22 +331,153 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
assert rows[0] == ("料号", "可用数量")
|
||||
assert rows[1] == ("A001", 100)
|
||||
assert rows[2] == ("A002", 50)
|
||||
assert callbacks == [
|
||||
(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
{
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"success": True,
|
||||
"file_path": str(exported),
|
||||
"rpa_mode": "mock",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
},
|
||||
)
|
||||
]
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_payload == {
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(exported),
|
||||
"rpa_mode": "mock",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
}
|
||||
assert not trigger_path.exists()
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_path):
|
||||
"""DSV 无库存时应回调 status=skipped,而不是 failed。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
source_trigger = _build_inventory_export_trigger("SN-20260629-NO-STOCK")
|
||||
trigger_dir = tmp_path / "inventory_triggers"
|
||||
trigger_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_SN-20260629-NO-STOCK.json"
|
||||
trigger_path.write_text(json.dumps(source_trigger, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
processed_dir = trigger_dir / "processed"
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
def raise_no_inventory(_trigger: dict, _drop: Path):
|
||||
raise worker.NoInventoryDataError("DSV report has no inventory data")
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_payload["status"] == "skipped"
|
||||
assert callback_payload["success"] is False
|
||||
assert callback_payload["skipped"] is True
|
||||
assert callback_payload["skip_reason"] == "no_inventory_data"
|
||||
assert callback_payload["message"] == "DSV report has no inventory data"
|
||||
assert "error_message" not in callback_payload
|
||||
assert not trigger_path.exists()
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped():
|
||||
"""全 skipped 时 batch 顶层 legacy success 应为 true,status 为 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
|
||||
{"source_code": "B", "status": "skipped", "success": False, "skipped": True},
|
||||
])
|
||||
assert summary["status"] == "success"
|
||||
assert summary["success"] is True
|
||||
assert summary["has_success"] is False
|
||||
assert summary["skipped_count"] == 2
|
||||
assert summary["failed_count"] == 0
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_partial_failed():
|
||||
"""存在 failed 但有 success/skipped 时 legacy success 仍为 true,status=partial_failed。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
{"source_code": "A", "status": "success", "success": True},
|
||||
{"source_code": "B", "status": "failed", "success": False},
|
||||
])
|
||||
assert summary["status"] == "partial_failed"
|
||||
assert summary["success"] is True
|
||||
assert summary["has_success"] is True
|
||||
assert summary["success_count"] == 1
|
||||
assert summary["failed_count"] == 1
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_empty():
|
||||
"""空 results 应返回全 0 计数,避免 helper 复用时 KeyError。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([])
|
||||
assert summary == {
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"has_success": False,
|
||||
"success_count": 0,
|
||||
"skipped_count": 0,
|
||||
"failed_count": 0,
|
||||
}
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_skipped_and_failed():
|
||||
"""仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
|
||||
{"source_code": "B", "status": "failed", "success": False},
|
||||
])
|
||||
assert summary["status"] == "partial_failed"
|
||||
assert summary["success"] is True
|
||||
assert summary["has_success"] is False
|
||||
assert summary["skipped_count"] == 1
|
||||
assert summary["failed_count"] == 1
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_item_empty_dict_counts_as_failed():
|
||||
"""batch 归一化对空 dict 应算 failed,避免缺字段误计 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
assert worker._normalize_inventory_batch_item_status({}) == "failed"
|
||||
summary = worker._summarize_inventory_batch_results([{}])
|
||||
assert summary["failed_count"] == 1
|
||||
assert summary["success_count"] == 0
|
||||
assert summary["success"] is False
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped_smoke_exit_success():
|
||||
"""全 skipped 时 summary status=success,smoke 应退出 0(链路正常、无 Excel)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert summary["status"] not in {"failed", "partial_failed"}
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=False,
|
||||
) == 0
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped_require_export_smoke_exit_fail():
|
||||
"""FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2(无 Excel 导出)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
smoke = _load_dsv_export_batch_smoke()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert smoke._resolve_smoke_scenario_exit_code(
|
||||
results=results,
|
||||
summary=summary,
|
||||
require_export=True,
|
||||
) == 2
|
||||
|
||||
|
||||
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
|
||||
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1253,17 +1393,84 @@ def test_wait_for_dsv_home_ready_skips_duplicate_upgrade_prompt_check(monkeypatc
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(worker, "_dismiss_dsv_password_upgrade_prompt", lambda page: dismiss_calls.__setitem__("value", dismiss_calls["value"] + 1))
|
||||
monkeypatch.setattr(worker, "_is_dsv_home_ready", _fake_is_home_ready)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_app_after_login", _fake_wait_for_app_after_login)
|
||||
monkeypatch.setattr(worker, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(worker, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(worker.dsv_session, "_is_dsv_home_ready", _fake_is_home_ready)
|
||||
monkeypatch.setattr(worker.dsv_session, "_wait_for_dsv_app_after_login", _fake_wait_for_app_after_login)
|
||||
monkeypatch.setattr(worker.dsv_session, "_wait_for_dsv_report_nav_grace", lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(worker.dsv_session, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(worker.dsv_session, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(worker.dsv_session, "_debug_dsv_stage", lambda *args, **kwargs: None)
|
||||
|
||||
worker._wait_for_dsv_home_ready(_FakePage(), timeout_ms=1_000)
|
||||
|
||||
assert dismiss_calls["value"] == 0
|
||||
|
||||
|
||||
def test_wait_for_dsv_home_ready_uses_grace_when_portal_visible(monkeypatch):
|
||||
"""app wait 超时但 portal 壳层已可见时,应走 grace wait 而非立刻 home-not-ready。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
ready_ticks = {"value": 0}
|
||||
|
||||
class _FakePage:
|
||||
url = "https://s360.dbschenker.com/main/portal"
|
||||
frames: list[object] = []
|
||||
|
||||
def _fake_is_home_ready(page) -> bool:
|
||||
ready_ticks["value"] += 1
|
||||
return ready_ticks["value"] >= 2
|
||||
|
||||
import dsv_auth
|
||||
|
||||
monkeypatch.setattr(worker.dsv_session, "_is_dsv_home_ready", _fake_is_home_ready)
|
||||
monkeypatch.setattr(worker.dsv_session, "_wait_for_dsv_app_after_login", lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(worker.dsv_session, "_is_dsv_on_portal_home", lambda page: True)
|
||||
monkeypatch.setattr(worker.dsv_session, "_has_dsv_report_nav_attached", lambda page: True)
|
||||
monkeypatch.setattr(dsv_auth, "has_dsv_password_upgrade_prompt", lambda page, timeout_ms=150: False)
|
||||
monkeypatch.setattr(worker.dsv_session, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(worker.dsv_session, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(worker.dsv_session, "_debug_dsv_stage", lambda *args, **kwargs: None)
|
||||
|
||||
worker._wait_for_dsv_home_ready(_FakePage(), timeout_ms=1_000)
|
||||
|
||||
assert ready_ticks["value"] >= 2
|
||||
|
||||
|
||||
def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
|
||||
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "dsv_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
dsv_report_export = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(dsv_report_export)
|
||||
|
||||
goto_calls: list[str] = []
|
||||
home_ready_calls: list[int] = []
|
||||
|
||||
monkeypatch.setattr(dsv_report_export, "_is_dsv_session_active", lambda page, entry_url: False)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_goto_dsv_entry_url",
|
||||
lambda page, entry_url: goto_calls.append(entry_url),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_maybe_auto_login_dsv",
|
||||
lambda page: (_ for _ in ()).throw(RuntimeError("DSV home page was not ready after login")),
|
||||
)
|
||||
monkeypatch.setattr(dsv_report_export, "_is_dsv_on_entry_site", lambda page, entry_url: True)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_wait_for_dsv_home_ready",
|
||||
lambda page, timeout_ms=None: home_ready_calls.append(timeout_ms or 0),
|
||||
)
|
||||
monkeypatch.setattr(dsv_report_export, "_wait_for_dsv_reports_nav_stable", lambda page, timeout_ms=None: None)
|
||||
|
||||
entry_url = "https://s360.dbschenker.com/"
|
||||
dsv_report_export._ensure_dsv_session(object(), entry_url)
|
||||
|
||||
assert goto_calls == [entry_url, entry_url]
|
||||
assert home_ready_calls == [30_000]
|
||||
|
||||
|
||||
def test_wait_for_dsv_app_after_login_dismisses_late_upgrade_prompt(monkeypatch):
|
||||
"""auth 过渡阶段若稍后出现升级提示,应立即处理,而不是继续 wait-app 空转。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -151,6 +151,196 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
|
||||
assert task.inventory_snapshot_id == inv_file.id
|
||||
|
||||
|
||||
def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, tmp_path):
|
||||
"""无库存 skipped 回调应提示人工上传,且不计入 inventory_rpa_failed。"""
|
||||
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
|
||||
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
|
||||
|
||||
headers = _tool_headers()
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
cb_res = client.post(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_no": task_id,
|
||||
"status": "skipped",
|
||||
"success": False,
|
||||
"skipped": True,
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": "DSV report has no inventory data",
|
||||
"rpa_mode": "browser",
|
||||
},
|
||||
)
|
||||
data = cb_res.get_json()
|
||||
assert data["status"] == "needs_human"
|
||||
assert data.get("checkpoint") == "upload_req"
|
||||
assert "无可用库存" in (data.get("message") or "")
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
assert task.process_status == "waiting_inventory"
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_failed",
|
||||
).all()
|
||||
skipped_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_skipped",
|
||||
).all()
|
||||
assert not failed_events
|
||||
assert len(skipped_events) == 1
|
||||
assert skipped_events[0].detail_json.get("skip_reason") == "no_inventory_data"
|
||||
assert task.error_message is None
|
||||
skipped_meta = (task.step_payload_json or {}).get("inventory_rpa_skipped") or {}
|
||||
assert skipped_meta.get("skip_reason") == "no_inventory_data"
|
||||
assert skipped_meta.get("message")
|
||||
|
||||
|
||||
def test_normalize_rpa_inventory_result_status():
|
||||
"""单任务与 batch item 归一化:单任务宽松、batch 严格。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
_normalize_rpa_inventory_batch_item_status,
|
||||
_normalize_rpa_inventory_result_status,
|
||||
_summarize_rpa_inventory_batch_outcome,
|
||||
)
|
||||
|
||||
assert _normalize_rpa_inventory_result_status({"status": "skipped"}) == "skipped"
|
||||
assert _normalize_rpa_inventory_result_status({"skipped": True, "success": False}) == "skipped"
|
||||
assert _normalize_rpa_inventory_result_status({"success": True}) == "success"
|
||||
assert _normalize_rpa_inventory_result_status({"success": False}) == "failed"
|
||||
assert _normalize_rpa_inventory_result_status({}) == "success"
|
||||
assert _normalize_rpa_inventory_batch_item_status({}) == "failed"
|
||||
assert _normalize_rpa_inventory_batch_item_status({"success": True}) == "success"
|
||||
assert _summarize_rpa_inventory_batch_outcome(created=[{}], skipped=[], failed=[{}]) == "partial_failed"
|
||||
assert _summarize_rpa_inventory_batch_outcome(created=[], skipped=[{}], failed=[]) == "success"
|
||||
assert _summarize_rpa_inventory_batch_outcome(created=[], skipped=[], failed=[{}]) == "failed"
|
||||
|
||||
|
||||
def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path):
|
||||
"""batch results 中空 dict 应直接 failed,不走 success→file_missing 绕路。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": "RUN-EMPTY-ITEM",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{}],
|
||||
})
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "failed"
|
||||
assert result["data"]["result_status"] == "failed"
|
||||
assert result["data"]["failed_count"] == 1
|
||||
assert result["data"]["failed"][0]["error_code"] == "rpa_export_failed"
|
||||
|
||||
|
||||
def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tmp_path):
|
||||
"""同一批 results 含 success+failed 时,顶层 result_status 应为 partial_failed。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_mixed.xlsx"
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.append(["料号", "可用数量"])
|
||||
ws.append(["A001", 1])
|
||||
wb.save(sample)
|
||||
except ImportError:
|
||||
sample.write_bytes(b"placeholder")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": "RUN-MIXED",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [
|
||||
{
|
||||
"source_code": "SRC_OK",
|
||||
"warehouse_id": "WH1",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(sample),
|
||||
},
|
||||
{
|
||||
"source_code": "SRC_FAIL",
|
||||
"warehouse_id": "WH2",
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_message": "timeout",
|
||||
},
|
||||
],
|
||||
})
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "partial_failed"
|
||||
assert result["data"]["result_status"] == "partial_failed"
|
||||
assert result["success_count"] == 1
|
||||
assert result["failed_count"] == 1
|
||||
|
||||
|
||||
def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
|
||||
"""全 failed 时接口 status 仍为 ok,业务结果见 result_status=failed。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
with app.app_context():
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": "RUN-ALL-FAIL",
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{
|
||||
"source_code": "SRC_FAIL",
|
||||
"warehouse_id": "WH1",
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_message": "timeout",
|
||||
}],
|
||||
})
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "failed"
|
||||
assert result["failed_count"] == 1
|
||||
|
||||
|
||||
def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_status():
|
||||
"""排程 finalize 成功时 result_status 应与 run_status 一致。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
_resolve_rpa_inventory_batch_response_outcome,
|
||||
)
|
||||
|
||||
outcome = _resolve_rpa_inventory_batch_response_outcome(
|
||||
created=[{"source_code": "A"}],
|
||||
skipped=[],
|
||||
failed=[],
|
||||
finalize_result={
|
||||
"ok": True,
|
||||
"run_status": "partial_failed",
|
||||
"success_count": 1,
|
||||
"skipped_count": 0,
|
||||
"failed_count": 2,
|
||||
},
|
||||
schedule_run_id=99,
|
||||
)
|
||||
assert outcome["callback_result_status"] == "success"
|
||||
assert outcome["result_status"] == "partial_failed"
|
||||
assert outcome["success_count"] == 1
|
||||
assert outcome["failed_count"] == 2
|
||||
|
||||
|
||||
def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
|
||||
"""确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。"""
|
||||
from app import db
|
||||
|
||||
@@ -454,6 +454,8 @@ def test_compute_run_status_requires_all_sources_success():
|
||||
assert _compute_run_status(total_count=3, success_count=1, failed_count=0) == "partial_failed"
|
||||
assert _compute_run_status(total_count=3, success_count=3, failed_count=0) == "success"
|
||||
assert _compute_run_status(total_count=3, success_count=0, failed_count=3) == "failed"
|
||||
assert _compute_run_status(total_count=3, success_count=1, skipped_count=2, failed_count=0) == "success"
|
||||
assert _compute_run_status(total_count=2, success_count=0, skipped_count=2, failed_count=0) == "success"
|
||||
|
||||
|
||||
def test_build_finalize_details_marks_missing_callback_as_failed():
|
||||
@@ -476,6 +478,34 @@ def test_build_finalize_details_marks_missing_callback_as_failed():
|
||||
assert any(item.get("warehouse_id") == "WH2" for item in missing)
|
||||
|
||||
|
||||
def test_build_finalize_details_marks_skipped_as_handled():
|
||||
"""RPA 回调 skipped 表示已处理但无库存,不应被补成 failed。"""
|
||||
pending = [
|
||||
{"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
|
||||
{"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
|
||||
]
|
||||
details = _build_finalize_details(
|
||||
pending,
|
||||
created=[],
|
||||
failed=[],
|
||||
skipped=[{
|
||||
"source_code": "SRC_A",
|
||||
"warehouse_id": "WH1",
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": "DSV report has no inventory data",
|
||||
}],
|
||||
)
|
||||
|
||||
assert len(details) == 2
|
||||
skipped = [item for item in details if item.get("export_status") == "skipped"]
|
||||
failed = [item for item in details if item.get("export_status") == "failed"]
|
||||
assert len(skipped) == 1
|
||||
assert skipped[0]["warehouse_id"] == "WH1"
|
||||
assert skipped[0]["skip_reason"] == "no_inventory_data"
|
||||
assert len(failed) == 1
|
||||
assert failed[0]["warehouse_id"] == "WH2"
|
||||
|
||||
|
||||
def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
"""回调结果少于触发源数时,排程应 partial_failed。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
@@ -519,7 +549,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
rpa_report_inventory_batch({
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": run.run_no,
|
||||
"schedule_run_id": run.id,
|
||||
"trigger_type": "scheduled",
|
||||
@@ -532,11 +562,75 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
})
|
||||
|
||||
db.session.refresh(run)
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "partial_failed"
|
||||
assert result["data"]["result_status"] == "partial_failed"
|
||||
assert result["data"]["callback_result_status"] == "success"
|
||||
assert result["success_count"] == 1
|
||||
assert result["failed_count"] == 2
|
||||
assert run.status == "partial_failed"
|
||||
assert run.success_count == 1
|
||||
assert run.failed_count == 2
|
||||
|
||||
|
||||
def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app):
|
||||
"""库存为 0 的 skipped 回调应计入 skipped_count,排程不应失败。"""
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
schedule_no="SCH-INV-SKIPPED",
|
||||
username="schedule_inv_skipped_user",
|
||||
)
|
||||
run = ScheduleRun(
|
||||
run_no="RUN20260709080400",
|
||||
schedule_task_id=task.id,
|
||||
status="running",
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
response_summary_json={
|
||||
"awaiting_rpa": True,
|
||||
"pending_details": [{
|
||||
"source_code": "DSV360_AWSBI_BYAWSATL01",
|
||||
"warehouse_id": "BYAWSATL01",
|
||||
"display_name": "ATL01",
|
||||
}],
|
||||
},
|
||||
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
result = rpa_report_inventory_batch({
|
||||
"run_no": run.run_no,
|
||||
"schedule_run_id": run.id,
|
||||
"trigger_type": "scheduled",
|
||||
"results": [{
|
||||
"source_code": "DSV360_AWSBI_BYAWSATL01",
|
||||
"warehouse_id": "BYAWSATL01",
|
||||
"status": "skipped",
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": "DSV report has no inventory data",
|
||||
}],
|
||||
})
|
||||
|
||||
db.session.refresh(run)
|
||||
assert result["status"] == "ok"
|
||||
assert result["result_status"] == "success"
|
||||
assert result["data"]["result_status"] == "success"
|
||||
assert result["data"]["callback_result_status"] == "success"
|
||||
assert result["skipped_count"] == 1
|
||||
assert run.status == "success"
|
||||
assert run.success_count == 0
|
||||
assert run.skipped_count == 1
|
||||
assert run.failed_count == 0
|
||||
summary = run.response_summary_json or {}
|
||||
assert summary.get("skipped_count") == 1
|
||||
assert summary.get("success_count") == 0
|
||||
assert summary.get("failed_count") == 0
|
||||
assert summary.get("total_count") == 1
|
||||
assert summary.get("rpa_finalize", {}).get("skipped_count") == 1
|
||||
assert (run.api_response_json or {}).get("skipped")[0]["skip_reason"] == "no_inventory_data"
|
||||
|
||||
|
||||
def test_is_awaiting_rpa_schedule_run_helper(app):
|
||||
"""awaiting RPA run 应被识别,普通 running 不应误判。"""
|
||||
with app.app_context():
|
||||
@@ -608,3 +702,24 @@ def test_filter_sources_by_match_aliases(app):
|
||||
db.session.commit()
|
||||
sources = _filter_sources(task)
|
||||
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
|
||||
|
||||
|
||||
def test_build_schedule_run_wecom_description_includes_skipped_count():
|
||||
"""企微排程通知正文应包含 skipped_count,与管理端统计口径一致。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.schedule.scheduler_service import _build_schedule_run_wecom_description
|
||||
|
||||
run = SimpleNamespace(
|
||||
run_no="RUN202607100846103654",
|
||||
status="success",
|
||||
total_count=3,
|
||||
success_count=2,
|
||||
skipped_count=1,
|
||||
failed_count=0,
|
||||
response_summary_json=None,
|
||||
)
|
||||
text = _build_schedule_run_wecom_description(run)
|
||||
assert "跳过: 1" in text
|
||||
assert "成功: 2" in text
|
||||
assert "失败: 0" in text
|
||||
Reference in new issue
Block a user