283 lines
11 KiB
Python
283 lines
11 KiB
Python
"""
|
||
scripts/rpa/dsv_export_batch_smoke.py
|
||
|
||
用途:本地验证 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 中独立配置项)
|
||
|
||
用法:
|
||
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
|
||
|
||
import importlib.util
|
||
import json
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import traceback
|
||
from copy import deepcopy
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
|
||
def _repo_root() -> Path:
|
||
return Path(__file__).resolve().parents[2]
|
||
|
||
|
||
def _load_worker():
|
||
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_smoke", module_path)
|
||
assert spec and spec.loader
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
|
||
|
||
def _load_export_smoke_helpers():
|
||
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_smoke.py"
|
||
spec = importlib.util.spec_from_file_location("dsv_export_smoke_batch", module_path)
|
||
assert spec and spec.loader
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
|
||
|
||
def _with_warehouse(source: dict[str, Any], warehouse: str, *, keep_source_code: bool) -> dict[str, Any]:
|
||
"""
|
||
克隆 source 并替换 Warehouse 参数与 query。
|
||
keep_source_code=True 时用于「同 source、仅 Warehouse 变化」场景。
|
||
"""
|
||
cloned = deepcopy(source)
|
||
wh = str(warehouse).strip()
|
||
if not keep_source_code:
|
||
cloned["source_code"] = f"DSV360_AWSBI_{wh}"
|
||
cloned["warehouse_id"] = wh
|
||
query = dict(cloned.get("query") or {})
|
||
query["warehouse_code"] = wh
|
||
cloned["query"] = query
|
||
parameters = []
|
||
for item in cloned.get("parameters") or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
param = dict(item)
|
||
if str(param.get("name") or "").lower() == "warehouse":
|
||
param["values"] = [wh]
|
||
parameters.append(param)
|
||
cloned["parameters"] = parameters
|
||
return cloned
|
||
|
||
|
||
def _build_warehouse_scenario_sources() -> list[dict[str, Any]]:
|
||
"""场景 1:同一 source_code,3lv 报表不变,仅 Warehouse 下拉值变化。"""
|
||
helper = _load_export_smoke_helpers()
|
||
base = helper._build_source_from_config("DSV360_AWSBI_BYAWSCMH01")
|
||
warehouses = ["BYAWSATL01", "BYAWSCMH01", "BYAWSAVP01"]
|
||
return [_with_warehouse(base, wh, keep_source_code=True) for wh in warehouses]
|
||
|
||
|
||
def _build_source_code_scenario_sources() -> list[dict[str, Any]]:
|
||
"""场景 2:三个独立 source_code。"""
|
||
helper = _load_export_smoke_helpers()
|
||
codes = [
|
||
"DSV360_AWSBI_BYAWSATL01",
|
||
"DSV360_AWSBI_BYAWSCMH01",
|
||
"DSV360_AWSBI_BYAWSAVP01",
|
||
]
|
||
return [helper._build_source_from_config(code) for code in codes]
|
||
|
||
|
||
def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]], drop_dir: Path) -> list[dict[str, Any]]:
|
||
"""
|
||
在同一 DSV session 内连续导出多份库存。
|
||
核心逻辑:与 _handle_inventory_batch_trigger 浏览器分支一致,但不 POST callback。
|
||
"""
|
||
run_no = f"BATCH-SMOKE-{scenario.upper()}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
||
trigger = {"run_no": run_no, "task_no": run_no}
|
||
entry_url = str((sources[0] or {}).get("entry_url") or "https://s360.dbschenker.com/").strip()
|
||
results: list[dict[str, Any]] = []
|
||
started = time.monotonic()
|
||
|
||
playwright = context = runtime_profile_dir = None
|
||
try:
|
||
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
|
||
export_fn = worker._export_dsv_inventory_source
|
||
previous_source: dict[str, Any] | None = None
|
||
for index, source in enumerate(sources):
|
||
code = str(source.get("source_code") or "")
|
||
wh = str(source.get("warehouse_id") or "")
|
||
print(
|
||
f"[batch-smoke] scenario={scenario} step={index + 1}/{len(sources)} "
|
||
f"source_code={code} warehouse={wh}"
|
||
)
|
||
try:
|
||
skip_navigation = worker._prepare_dsv_batch_export_step(
|
||
page,
|
||
entry_url,
|
||
previous_source,
|
||
source,
|
||
index=index,
|
||
)
|
||
download = export_fn(page, trigger, source, skip_navigation=skip_navigation)
|
||
out_file = worker._save_batch_download(download, drop_dir, run_no, source)
|
||
size_kb = out_file.stat().st_size / 1024
|
||
results.append(
|
||
{
|
||
"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),
|
||
}
|
||
)
|
||
print(f"[batch-smoke] FAIL {code}/{wh}: {exc}", file=sys.stderr)
|
||
traceback.print_exc()
|
||
previous_source = source
|
||
finally:
|
||
if context is not None:
|
||
context.close()
|
||
if playwright is not None:
|
||
playwright.stop()
|
||
if runtime_profile_dir is not None:
|
||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||
|
||
elapsed_s = int(time.monotonic() - started)
|
||
summary = worker._summarize_inventory_batch_results(results)
|
||
print(
|
||
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()
|
||
elif scenario == "source_code":
|
||
sources = _build_source_code_scenario_sources()
|
||
else:
|
||
raise ValueError(f"unknown scenario: {scenario}")
|
||
|
||
drop_dir = Path(tempfile.mkdtemp(prefix=f"dsv_batch_{scenario}_"))
|
||
print(f"[batch-smoke] scenario={scenario} exports={len(sources)} drop_dir={drop_dir}")
|
||
for index, source in enumerate(sources, start=1):
|
||
print(
|
||
f"[batch-smoke] plan[{index}] source_code={source.get('source_code')} "
|
||
f"warehouse={source.get('warehouse_id')} "
|
||
f"query={json.dumps(source.get('query') or {}, ensure_ascii=False)}"
|
||
)
|
||
|
||
results = _run_batch_exports(worker, scenario, sources, drop_dir)
|
||
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:
|
||
scenario_arg = (sys.argv[1] if len(sys.argv) > 1 else "all").strip().lower()
|
||
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
|
||
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
|
||
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
|
||
os.environ.setdefault(
|
||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||
"backend/data/shipping_notice/freight_rpa/browser_profile",
|
||
)
|
||
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
|
||
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
|
||
|
||
worker = _load_worker()
|
||
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
|
||
print("[batch-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
|
||
return 1
|
||
|
||
scenarios = ["warehouse", "source_code"] if scenario_arg == "all" else [scenario_arg]
|
||
exit_code = 0
|
||
for scenario in scenarios:
|
||
if scenario not in {"warehouse", "source_code"}:
|
||
print(f"[batch-smoke] 未知场景: {scenario}(可用 warehouse / source_code / all)")
|
||
return 1
|
||
print(f"\n[batch-smoke] ===== 开始场景: {scenario} =====")
|
||
code = _run_scenario(worker, scenario)
|
||
exit_code = max(exit_code, code)
|
||
return exit_code
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|