feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约

将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。
共享目录与 Worker 契约一次切换至 onhand/inbound/upload,
并补 outbound 骨架与 tt16 排程 job key 迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-17 23:18:48 +08:00
1 parent bf3154033b
commit ffc0d4a430
147 files changed
+4221 -2678

No files matched your search

+81 -81
View File
@@ -28,8 +28,8 @@ def _repo_root() -> Path:
def _load_freight_rpa_worker():
module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
module_path = _repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_under_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
@@ -40,12 +40,12 @@ def _load_freight_rpa_worker():
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
return {
"action": "inventory_export",
"action": "onhand_export",
"task_no": task_no,
"requested_at": "2026-07-01T03:23:25.114522",
"mode": "auto",
"attempt": 3,
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": f"SRC-{task_no}:C1",
"source_code": "DSV360_AWSDU",
"source_run_no": f"SRC-{task_no}",
@@ -87,15 +87,15 @@ def test_single_inventory_trigger_missing_source_run_is_rejected_before_rpa(monk
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
monkeypatch.setattr(worker, "_download_onhand_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
assert callbacks == [
(
"/api/shipping-notice/rpa/inventory-ready",
"/api/freight-rpa/onhand-ready",
{
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": None,
"task_no": "SN-IDENTITY-INVALID",
"business_status": "rejected",
@@ -122,9 +122,9 @@ def test_single_inventory_trigger_missing_callback_id_is_rejected(monkeypatch, t
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
monkeypatch.setattr(worker, "_download_onhand_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
assert callbacks[0][1]["callback_id"] is None
assert callbacks[0][1]["error_code"] == "trigger_identity_invalid"
@@ -156,7 +156,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
}
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "BATCH-001:batch:C1",
"batch_run_no": "BATCH-001",
"task_no": "SN-BATCH-IDENTITY",
@@ -166,9 +166,9 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
result = completed["results"][0]
assert {key: result[key] for key in (
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
@@ -210,7 +210,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
}
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "BATCH-CRANE-DYNAMIC:batch:C1",
"batch_run_no": "BATCH-CRANE-DYNAMIC",
"task_no": "SN-CRANE-DYNAMIC",
@@ -220,9 +220,9 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
assert completed["results"][0]["callback_id"] == "PSR-CRANE-DYNAMIC:C1"
assert completed["results"][0]["expected_warehouse_id"] is None
assert (processed_dir / trigger_path.name).is_file()
@@ -239,7 +239,7 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
trigger_path = trigger_dir / "inventory_export_batch_invalid.json"
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "BATCH-INVALID:batch:C1",
"batch_run_no": "BATCH-INVALID",
"task_no": "SN-BATCH-INVALID",
@@ -259,7 +259,7 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
callbacks: list[tuple[str, dict]] = []
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
assert callbacks[0][1]["callback_id"] == "BATCH-INVALID:batch:C1"
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
@@ -279,7 +279,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
# batch 级无 task_no,逐源无 task_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id。
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "RUN-SCHEDULED:batch:C1",
"batch_run_no": "RUN-SCHEDULED",
"run_no": "RUN-SCHEDULED",
@@ -304,9 +304,9 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
assert completed["schedule_run_id"] == 713
assert completed["trigger_type"] == "scheduled"
result = completed["results"][0]
@@ -314,7 +314,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
assert result["warehouse_id"] == "AWSDU"
assert result["status"] == "success"
# 每完成一个站点应回传一次累计进度,供后端实时回写排程 run 笔数。
progress = next(body for path, body in callbacks if path.endswith("/inventory-batch-progress"))
progress = next(body for path, body in callbacks if path.endswith("/onhand-batch-progress"))
assert progress["schedule_run_id"] == 713
assert progress["batch_run_no"] == "RUN-SCHEDULED"
assert progress["success_count"] == 1
@@ -339,7 +339,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
@@ -363,14 +363,14 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks)
ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready"))
ready = next(body for path, body in callbacks if path.endswith("/onhand-configuration-test-analyze"))
assert ready["run_no"] == run_no
assert ready["status"] == "success"
assert ready.get("file_path")
assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks)
assert not any(path.endswith("/onhand-batch-ready") for path, _ in callbacks)
assert (processed_dir / trigger_path.name).is_file()
assert not (failed_dir / trigger_path.name).exists()
@@ -398,7 +398,7 @@ def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup
}
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "BATCH-INTERRUPT:batch:C1",
"batch_run_no": "BATCH-INTERRUPT",
"task_no": "SN-CRANE-INTERRUPT",
@@ -417,14 +417,14 @@ def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup
monkeypatch.setattr(worker, "_open_browser", lambda *_args, **_kwargs: (_Playwright(), _Context(), object(), tmp_path / "profile"))
monkeypatch.setattr(worker, "_ensure_crane_session", lambda *_args, **_kwargs: None)
monkeypatch.setattr(worker, "_export_crane_inventory_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
monkeypatch.setattr(worker, "_export_crane_onhand_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
with pytest.raises(KeyboardInterrupt):
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
assert stopped == [True]
assert [path for path, _body in callbacks] == ["/api/shipping-notice/rpa/inventory-batch-claimed"]
assert [path for path, _body in callbacks] == ["/api/freight-rpa/onhand-batch-claimed"]
assert trigger_path.is_file()
assert not (processed_dir / trigger_path.name).exists()
@@ -443,10 +443,10 @@ def test_env_strips_wrapping_quotes(monkeypatch):
def test_worker_accepts_business_connector_without_site_id():
"""数据库 Source 的 dbs/crane 业务类型不应要求已删除的 site_id 字段。"""
worker = _load_freight_rpa_worker()
worker._validate_inventory_source_for_rpa({
worker._validate_onhand_source_for_rpa({
"source_code": "DBS_DUB", "connector_type": "dbs", "warehouse_id": "DUB",
})
worker._validate_inventory_source_for_rpa({
worker._validate_onhand_source_for_rpa({
"source_code": "CRANE", "connector_type": "crane",
})
@@ -788,7 +788,7 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
stats = cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger,
onhand_trigger_dir=inv_trigger,
upload_trigger_dir=upload_trigger,
drop_dir=drop,
upload_queue_dir=queue,
@@ -836,7 +836,7 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger,
onhand_trigger_dir=inv_trigger,
browser_profile_dir=profiles,
now_unix=now,
)
@@ -845,36 +845,36 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
assert not orphan_run.exists()
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
def test_cleanup_orphan_runtime_profiles_removes_inbound_prefix(tmp_path):
"""
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
崩溃残留的 inbound_* 临时 Profile 超期必须被清理;_session 目录保留。
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
断言意图:inbound Worker 的一次性 Profile 以 inbound_ 前缀创建,异常中断后
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
未超期的 inbound_* Profile 正在使用中,前缀匹配不得误删。
"""
cleanup = _load_worker_disk_cleanup()
root = tmp_path / "browser_profile"
stale_receipt = root / "receipt_abcd1234"
stale_receipt.mkdir(parents=True)
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
young_receipt = root / "receipt_fresh5678"
young_receipt.mkdir()
stale_inbound = root / "inbound_abcd1234"
stale_inbound.mkdir(parents=True)
(stale_inbound / "Cookies").write_text("drop", encoding="utf-8")
young_inbound = root / "inbound_fresh5678"
young_inbound.mkdir()
session_dir = root / "dsv_session"
session_dir.mkdir()
now = time.time()
old = now - 10 * 24 * 3600
os.utime(stale_receipt, (old, old))
os.utime(young_receipt, (now - 3600, now - 3600))
os.utime(stale_inbound, (old, old))
os.utime(young_inbound, (now - 3600, now - 3600))
os.utime(session_dir, (old, old))
stats = cleanup.DiskCleanupStats()
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
assert not stale_receipt.exists() and session_dir.exists()
assert young_receipt.exists()
# 过期 inbound_* 目录树删除;未过期 inbound_* 与 _session 结尾目录即使过期也保留
assert not stale_inbound.exists() and session_dir.exists()
assert young_inbound.exists()
assert stats.deleted_dirs == 1
@@ -995,17 +995,17 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
callbacks: list[tuple[str, dict]] = []
download_calls: list[dict] = []
def fake_download_inventory_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
def fake_download_onhand_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
download_calls.append(trigger)
out_file = target_drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
out_file = target_drop_dir / "onhand_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
out_file.write_bytes(b"fake inventory content")
return out_file
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
monkeypatch.setattr(worker, "_download_onhand_with_browser", fake_download_onhand_with_browser)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
assert len(download_calls) == 1
trigger = download_calls[0]
@@ -1018,9 +1018,9 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
assert len(callbacks) == 1
callback_path, callback_payload = callbacks[0]
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
assert callback_path == "/api/freight-rpa/onhand-ready"
assert callback_payload == {
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
"task_no": "SN-20260629-2EDADC77",
"source_code": "DSV360_AWSDU",
@@ -1034,7 +1034,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
"expected_warehouse_id": "AWSDU",
"status": "success",
"success": True,
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
"file_path": str(drop_dir / "onhand_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
"file_sha256": hashlib.sha256(b"fake inventory content").hexdigest(),
"rpa_mode": "browser",
}
@@ -1060,12 +1060,12 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_ONHAND", raising=False)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
exported_files = list(drop_dir.glob("inventory_SN-20260629-2EDADC77_*.xlsx"))
exported_files = list(drop_dir.glob("onhand_SN-20260629-2EDADC77_*.xlsx"))
assert len(exported_files) == 1
exported = exported_files[0]
wb = load_workbook(exported, data_only=True, read_only=True)
@@ -1080,9 +1080,9 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
assert rows[2] == ("A002", 50)
assert len(callbacks) == 1
callback_path, callback_payload = callbacks[0]
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
assert callback_path == "/api/freight-rpa/onhand-ready"
assert callback_payload == {
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
"task_no": "SN-20260629-2EDADC77",
"source_code": "DSV360_AWSDU",
@@ -1122,14 +1122,14 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
raise worker.NoInventoryDataError("DSV report has no inventory data")
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
monkeypatch.setattr(worker, "_download_onhand_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)
worker._handle_onhand_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_path == "/api/freight-rpa/onhand-ready"
assert callback_payload["status"] == "skipped"
assert callback_payload["success"] is False
assert callback_payload["skipped"] is True
@@ -1139,10 +1139,10 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
assert not trigger_path.exists()
def test_summarize_inventory_batch_results_all_skipped():
def test_summarize_onhand_batch_results_all_skipped():
"""全 skipped 时 batch 顶层 legacy success 应为 true,status 为 success。"""
worker = _load_freight_rpa_worker()
summary = worker._summarize_inventory_batch_results([
summary = worker._summarize_onhand_batch_results([
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
{"source_code": "B", "status": "skipped", "success": False, "skipped": True},
])
@@ -1153,10 +1153,10 @@ def test_summarize_inventory_batch_results_all_skipped():
assert summary["failed_count"] == 0
def test_summarize_inventory_batch_results_partial_failed():
def test_summarize_onhand_batch_results_partial_failed():
"""存在 failed 但有 success/skipped 时 legacy success 仍为 true,status=partial_failed。"""
worker = _load_freight_rpa_worker()
summary = worker._summarize_inventory_batch_results([
summary = worker._summarize_onhand_batch_results([
{"source_code": "A", "status": "success", "success": True},
{"source_code": "B", "status": "failed", "success": False},
])
@@ -1167,10 +1167,10 @@ def test_summarize_inventory_batch_results_partial_failed():
assert summary["failed_count"] == 1
def test_summarize_inventory_batch_results_empty():
def test_summarize_onhand_batch_results_empty():
"""空 results 应返回全 0 计数,避免 helper 复用时 KeyError。"""
worker = _load_freight_rpa_worker()
summary = worker._summarize_inventory_batch_results([])
summary = worker._summarize_onhand_batch_results([])
assert summary == {
"status": "failed",
"success": False,
@@ -1547,7 +1547,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
assert callbacks == [("/api/shipping-notice/rpa/upload-complete", {
assert callbacks == [("/api/freight-rpa/upload-complete", {
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8",
"result": "failed", "success": False, "error_message": "success marker missing",
})]
@@ -1573,10 +1573,10 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
assert callbacks[0][1]["error_message"] == "queue file missing: <empty>"
def test_summarize_inventory_batch_results_skipped_and_failed():
def test_summarize_onhand_batch_results_skipped_and_failed():
"""仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
worker = _load_freight_rpa_worker()
summary = worker._summarize_inventory_batch_results([
summary = worker._summarize_onhand_batch_results([
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
{"source_code": "B", "status": "failed", "success": False},
])
@@ -1590,18 +1590,18 @@ def test_summarize_inventory_batch_results_skipped_and_failed():
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 worker._normalize_onhand_batch_item_status({}) == "failed"
summary = worker._summarize_onhand_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_is_success():
def test_summarize_onhand_batch_results_all_skipped_is_success():
"""全 skipped 代表链路正常但无库存,不得误报为批量导出失败。"""
worker = _load_freight_rpa_worker()
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
summary = worker._summarize_inventory_batch_results(results)
summary = worker._summarize_onhand_batch_results(results)
assert summary["status"] == "success"
assert summary["has_success"] is False
assert summary["status"] not in {"failed", "partial_failed"}
@@ -2760,7 +2760,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
def test_validate_onhand_excel_accepts_real_report_shape(tmp_path):
"""下载完成后必须能打开 Excel,并包含库存报表标题和关键表头。"""
worker = _load_freight_rpa_worker()
path = tmp_path / "inventory.xlsx"
@@ -2775,17 +2775,17 @@ def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
ws.append(["CADU-0000000100", "Well Trust Precision Technology", f"504-006043-{index:03d}", "Frame"])
wb.save(path)
worker._validate_inventory_excel(path)
worker._validate_onhand_excel(path)
def test_validate_inventory_excel_rejects_invalid_download(tmp_path):
def test_validate_onhand_excel_rejects_invalid_download(tmp_path):
"""下载文件太小或不是有效 Excel 时不能回调 success。"""
worker = _load_freight_rpa_worker()
path = tmp_path / "inventory.xlsx"
path.write_bytes(b"not a complete excel")
with pytest.raises(RuntimeError, match="too small|valid Excel"):
worker._validate_inventory_excel(path)
worker._validate_onhand_excel(path)
def test_find_dsv_report_result_frame_prefers_grid_like_frame():
@@ -2952,7 +2952,7 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
str(tmp_path / "browser_profile"),
)
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
out_file = worker._download_onhand_with_browser(trigger, drop_dir)
assert out_file.is_file()
assert out_file.parent == drop_dir