feat(shipping-notice): 增加 RPA 库存回调处理逻辑,支持跳过无库存情况

This commit is contained in:
hugo committed 2026-07-10 17:21:11 +08:00
1 parent f21216f81e
commit c3f05ba96b
25 files changed
+1619 -81

No files matched your search

+8
View File
@@ -121,6 +121,14 @@ Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,DSV
库存源定义见 `backend/config/shipping_inventory_sources.yaml`(新增 Warehouse 只改 YAML)。
### 本地 batch smoke(`dsv_export_batch_smoke.py`)
联调 DSV 批量导出链路,不回调后端。默认语义:**链路跑完即通过**(全 skipped 无库存也退出码 0)。
| 环境变量 | 默认值 | 用途 |
|---------|--------|------|
| `FREIGHT_RPA_SMOKE_REQUIRE_EXPORT` | `false` | 为 `true` 时要求至少真实导出一个 Excel;全 skipped 将退出码 2(CI 严格模式) |
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
| 环境变量 | 用途 |
+63 -6
View File
@@ -1,10 +1,15 @@
"""
scripts/rpa/dsv_export_batch_smoke.py
用途:本地验证 DSV 360 同一浏览器 session 内连续导出 3 份库存 Excel。
用途:本地验证 DSV 360 同一浏览器 session 内连续批量导出库存(smoke / 联调)。
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.yaml、freight_rpa_worker。
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
Smoke 语义(团队约定):
- 验证目标:**批量导出链路能跑完**(登录 → 导航 → 填参 → View Report → 导出/跳过判定)。
- **不保证**至少导出一个 Excel;全仓无库存(全 skipped)也算通过(退出码 0)。
- 若需“至少真实导出一个 Excel”,设置 FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true。
场景:
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
source_code — 三个不同 source_code(YAML 中独立配置项)
@@ -13,6 +18,10 @@ scripts/rpa/dsv_export_batch_smoke.py
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py source_code
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py all
退出码:
0 — summary.status=success(含全 skipped;或至少一条 success)
2 — 无结果、partial_failed、failed;或 REQUIRE_EXPORT=true 且无 success 导出
"""
from __future__ import annotations
@@ -134,18 +143,34 @@ def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]]
{
"source_code": code,
"warehouse_id": wh,
"status": "success",
"success": True,
"file_path": str(out_file),
"size_kb": round(size_kb, 1),
}
)
print(f"[batch-smoke] OK {code}/{wh} -> {out_file.name} ({size_kb:.1f} KB)")
except worker.NoInventoryDataError as exc:
results.append(
{
"source_code": code,
"warehouse_id": wh,
"status": "skipped",
"success": False,
"skipped": True,
"skip_reason": "no_inventory_data",
"message": str(exc),
}
)
print(f"[batch-smoke] SKIP {code}/{wh}: {exc}")
except Exception as exc:
results.append(
{
"source_code": code,
"warehouse_id": wh,
"status": "failed",
"success": False,
"error_code": "rpa_export_failed",
"error_message": str(exc),
}
)
@@ -161,14 +186,36 @@ def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]]
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
elapsed_s = int(time.monotonic() - started)
ok = sum(1 for item in results if item.get("success"))
summary = worker._summarize_inventory_batch_results(results)
print(
f"[batch-smoke] scenario={scenario} done success={ok}/{len(results)} "
f"[batch-smoke] scenario={scenario} done status={summary['status']} "
f"success={summary['success_count']} skipped={summary['skipped_count']} "
f"failed={summary['failed_count']}/{len(results)} "
f"elapsed={elapsed_s}s drop_dir={drop_dir}"
)
return results
def _resolve_smoke_scenario_exit_code(
*,
results: list[dict[str, Any]],
summary: dict[str, Any],
require_export: bool,
) -> int:
"""
根据 batch summary 与 FREIGHT_RPA_SMOKE_REQUIRE_EXPORT 计算 smoke 退出码。
核心逻辑:默认 status=success 即 0(含全 skipped);require_export 且无 Excel 导出时返回 2。
"""
if not results:
return 2
if summary.get("status") in {"failed", "partial_failed"}:
return 2
if require_export and not summary.get("has_success"):
return 2
return 0
def _run_scenario(worker: Any, scenario: str) -> int:
if scenario == "warehouse":
sources = _build_warehouse_scenario_sources()
@@ -187,9 +234,19 @@ def _run_scenario(worker: Any, scenario: str) -> int:
)
results = _run_batch_exports(worker, scenario, sources, drop_dir)
if not results or not all(item.get("success") for item in results):
return 2
return 0
summary = worker._summarize_inventory_batch_results(results)
require_export = worker._env("FREIGHT_RPA_SMOKE_REQUIRE_EXPORT", "false").lower() == "true"
exit_code = _resolve_smoke_scenario_exit_code(
results=results,
summary=summary,
require_export=require_export,
)
if exit_code == 2 and require_export and not summary.get("has_success") and results:
print(
"[batch-smoke] FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 但未导出任何 Excel",
file=sys.stderr,
)
return exit_code
def main() -> int:
+32 -4
View File
@@ -46,6 +46,15 @@ from dsv_session import (
wait_for_dsv_home_ready as _wait_for_dsv_home_ready,
)
class NoInventoryDataError(RuntimeError):
"""
DSV 报表结果区无库存明细行。
核心逻辑:表示业务上「已查询但无库存」,供 worker 映射为 skipped 而非 failed。
"""
def _click_dsv_export_excel(page: Any) -> None:
"""
触发 DSV SSRS ReportViewer 的 Excel 导出。
@@ -998,15 +1007,34 @@ def _is_dsv_session_active(page: Any, entry_url: str) -> bool:
def _ensure_dsv_session(page: Any, entry_url: str) -> None:
"""DSV 360 一次登录并等待首页/Reports 导航就绪。"""
"""
DSV 360 一次登录并等待首页/Reports 导航就绪。
核心逻辑:登录后 home-not-ready 时,若 session 已在 entry 站点,回 entry 首页重试一次。
"""
if _is_dsv_session_active(page, entry_url):
print("[dsv] session already active on entry site, skip login")
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
return
_goto_dsv_entry_url(page, entry_url)
_maybe_auto_login_dsv(page)
_wait_for_dsv_home_ready(page, timeout_ms=60_000)
home_not_ready_after_login = False
try:
_maybe_auto_login_dsv(page)
except RuntimeError as exc:
if "home page was not ready" not in str(exc):
raise
home_not_ready_after_login = True
print("[dsv] home not ready after login, retry entry reset once", file=sys.stderr)
if home_not_ready_after_login:
if not _is_dsv_on_entry_site(page, entry_url):
raise RuntimeError("DSV home page was not ready after login")
_goto_dsv_entry_url(page, entry_url)
home_timeout_ms = 30_000 if home_not_ready_after_login else 60_000
_wait_for_dsv_home_ready(page, timeout_ms=home_timeout_ms)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
@@ -1145,7 +1173,7 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
pass
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if not _dsv_report_has_inventory_data_rows(page):
raise RuntimeError("DSV report has no inventory data")
raise NoInventoryDataError("DSV report has no inventory data")
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
_click_dsv_export_excel(page)
return download_info.value
+55 -2
View File
@@ -235,8 +235,8 @@ def _wait_for_dsv_home_ready(
"""
等待 DSV 首页真正稳定可操作。
核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现,
失败则直接在“首页阶段”报错,避免主流程跳步到 Reports/View Report。
核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现。
app wait 超时但 portal 壳层已可见时,追加 grace wait;仍失败则在首页阶段报错。
"""
import dsv_auth
@@ -281,6 +281,20 @@ def _wait_for_dsv_home_ready(
)
# #endregion
return
if _wait_for_dsv_report_nav_grace(
page,
timeout_ms=30_000,
on_portal_shell_seen=on_portal_shell_seen,
):
# #region debug-point A:home-ready-after-grace
_report_debug_event(
"A",
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_grace",
"[DEBUG] dsv home became ready during portal grace wait",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
)
# #endregion
return
_debug_dsv_stage(page, "home-not-ready", target_text="Reports")
# #region debug-point A:home-not-ready
_report_debug_event(
@@ -292,6 +306,44 @@ def _wait_for_dsv_home_ready(
# #endregion
raise RuntimeError("DSV home page was not ready after login")
def _wait_for_dsv_report_nav_grace(
page: Any,
*,
timeout_ms: int = 30_000,
on_portal_shell_seen: Callable[[], None] | None = None,
) -> bool:
"""
Portal 首屏已出现但 Reports 导航尚未 visible 时的额外等待。
核心逻辑:SSO/合规页较慢时,portal 壳层(Home/Favorites)常先于顶栏 Reports 可点击;
在判定 home-not-ready 前给导航一次 grace 窗口,降低首条 batch 误失败概率。
Returns:
bool: grace 窗口内首页变为 ready 则 True,否则 False。
"""
import dsv_auth
if not _is_dsv_on_portal_home(page):
return False
print(
"[dsv-home] portal shell visible, grace wait for Reports nav "
f"timeoutMs={timeout_ms} report_nav_attached={_has_dsv_report_nav_attached(page)} "
f"url={page.url!r}"
)
deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline:
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
if _is_dsv_home_ready(page):
if on_portal_shell_seen is not None:
on_portal_shell_seen()
_debug_dsv_stage(page, "home-ready-after-grace", target_text="Reports")
return True
time.sleep(0.5)
return False
def _goto_dsv_entry_url(page: Any, entry_url: str) -> None:
"""
打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。
@@ -328,6 +380,7 @@ is_dsv_on_portal_home = _is_dsv_on_portal_home
iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators
wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login
wait_for_dsv_home_ready = _wait_for_dsv_home_ready
wait_for_dsv_report_nav_grace = _wait_for_dsv_report_nav_grace
# 向后兼容:登录 API 仍可从 dsv_session 引用
from dsv_auth import ( # noqa: E402
+152 -2
View File
@@ -59,6 +59,7 @@ import dsv_debug # noqa: E402
import dsv_driver # noqa: E402
import dsv_navigation # noqa: E402
import dsv_report_export # noqa: E402
from dsv_report_export import NoInventoryDataError # noqa: E402
import dsv_session # noqa: E402
# 测试与 smoke 向后兼容 re-export
@@ -353,7 +354,28 @@ def _browser_profile_root() -> Path:
return _resolve_backend_relative_path(profile, default=default)
def _mask_secret(value: str) -> str:
"""
对 API Key 等敏感字符串做首尾保留脱敏,供 callback 请求日志打印。
Args:
value: 原始密钥字符串。
Returns:
str: 长度 ≤8 时返回 `***`;否则保留前 4 与后 4 字符。
"""
value = str(value or "")
if len(value) <= 8:
return "***"
return f"{value[:4]}...{value[-4:]}"
def _post_callback(path: str, payload: dict) -> None:
"""
向 HXOPS 货代 Tool API 发送 JSON 回调。
核心逻辑:组装 URL 与双 Header 密钥 → 打印脱敏请求日志 → POST;HTTP 错误时打印响应体摘要。
"""
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
key = (
_env("SHIPPING_NOTICE_TOOL_API_KEY")
@@ -372,6 +394,14 @@ def _post_callback(path: str, payload: dict) -> None:
url = f"{base}{path}"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
print(
"[callback-request] "
f"POST {url} "
f"headers={{'Content-Type': 'application/json', "
f"'X-Integration-Key': '{_mask_secret(key)}', "
f"'X-Shipping-Tool-Key': '{_mask_secret(key)}'}} "
f"payload={data.decode('utf-8', errors='replace')[:4000]}"
)
req = urllib.request.Request(
url,
data=data,
@@ -388,6 +418,11 @@ def _post_callback(path: str, payload: dict) -> None:
print(f"[callback] {path} -> {resp.status} {body[:200]}")
except urllib.error.HTTPError as exc:
err = exc.read().decode("utf-8", errors="replace")
print(
"[callback-response] "
f"POST {url} -> HTTP {exc.code} {err[:1000]}",
file=sys.stderr,
)
raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc
@@ -748,6 +783,67 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
def _normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
"""
batch 明细状态归一化(比单任务更严格:缺省字段不算 success)。
核心逻辑:worker 自生成 results 均带 status/success;空 dict 或缺字段归为 failed,
避免 batch summary 误计成功。
"""
raw_status = str(item.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if item.get("skipped"):
return "skipped"
if item.get("success") is True:
return "success"
return "failed"
def _summarize_inventory_batch_results(results: list[dict[str, Any]]) -> dict[str, Any]:
"""
汇总 batch 回调顶层状态。
核心逻辑:
- status:新监控用,区分 success / partial_failed / failed;
- success(legacy):与旧 any(item.success) 兼容,有 success 或 skipped 即为 true;
- has_success:是否至少有一条实际导出成功。
"""
zero = {
"status": "failed",
"success": False,
"has_success": False,
"success_count": 0,
"skipped_count": 0,
"failed_count": 0,
}
statuses = [
_normalize_inventory_batch_item_status(item)
for item in results
if isinstance(item, dict)
]
if not statuses:
return dict(zero)
success_count = sum(1 for status in statuses if status == "success")
skipped_count = sum(1 for status in statuses if status == "skipped")
failed_count = sum(1 for status in statuses if status == "failed")
if failed_count == 0:
top_status = "success"
elif success_count == 0 and skipped_count == 0:
top_status = "failed"
else:
top_status = "partial_failed"
return {
"status": top_status,
"success": (success_count + skipped_count) > 0,
"has_success": success_count > 0,
"success_count": success_count,
"skipped_count": skipped_count,
"failed_count": failed_count,
}
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
run_no = str(body.get("run_no") or trigger_path.stem).strip()
@@ -772,6 +868,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"source_code": source.get("source_code"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"status": "success",
"success": True,
"file_path": str(out_file),
"task_no": task_no or None,
@@ -799,7 +896,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"source_code": source.get("source_code"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"status": "failed",
"success": False,
"error_code": "unsupported_source_type",
"error_message": f"unsupported source_type: {site}",
})
continue
@@ -829,17 +928,32 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"source_code": code,
"site_id": source.get("site_id"),
"warehouse_id": wh,
"status": "success",
"success": True,
"file_path": str(out_file),
"task_no": task_no or None,
})
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
except NoInventoryDataError as exc:
results.append({
"source_code": code,
"site_id": source.get("site_id"),
"warehouse_id": wh,
"status": "skipped",
"success": False,
"skipped": True,
"skip_reason": "no_inventory_data",
"message": str(exc),
})
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
except Exception as exc:
results.append({
"source_code": code,
"site_id": source.get("site_id"),
"warehouse_id": wh,
"status": "failed",
"success": False,
"error_code": "rpa_export_failed",
"error_message": str(exc),
})
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
@@ -852,16 +966,28 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
try:
batch_summary = _summarize_inventory_batch_results(results)
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"run_no": run_no,
"success": any(item.get("success") for item in results),
"status": batch_summary["status"],
"success": batch_summary["success"],
"has_success": batch_summary["has_success"],
"success_count": batch_summary["success_count"],
"skipped_count": batch_summary["skipped_count"],
"failed_count": batch_summary["failed_count"],
"rpa_mode": mode,
"trigger_type": body.get("trigger_type"),
"schedule_run_id": body.get("schedule_run_id"),
"results": results,
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[inventory-batch] callback done run={run_no} success={sum(1 for r in results if r.get('success'))}/{len(results)}")
print(
f"[inventory-batch] callback done run={run_no} "
f"status={batch_summary['status']} "
f"success={batch_summary['success_count']} "
f"skipped={batch_summary['skipped_count']} "
f"failed={batch_summary['failed_count']}/{len(results)}"
)
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
@@ -885,6 +1011,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"status": "success",
"success": True,
"file_path": str(out_file),
"rpa_mode": mode,
@@ -892,11 +1019,34 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
except NoInventoryDataError as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"status": "skipped",
"success": False,
"skipped": True,
"skip_reason": "no_inventory_data",
"message": str(exc),
"rpa_mode": mode,
"source_code": (
(body.get("rpa_inventory_source") or {}).get("source_code")
if isinstance(body.get("rpa_inventory_source"), dict)
else None
),
})
if trigger_path.exists():
trigger_path.unlink(missing_ok=True)
print(f"[inventory] {mode} export skipped for {task_no}: {exc}")
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"status": "failed",
"success": False,
"skipped": False,
"rpa_mode": mode,
"error_message": str(exc),
})