Files
syops/scripts/rpa/crane_export_smoke.py
T

116 lines
4.4 KiB
Python

"""
scripts/rpa/crane_export_smoke.py
用途:本地手动验证 Crane CRANE 库存源浏览器导出全流程。
依赖:Playwright、FREIGHT_RPA_CRANE_USERNAME/PASSWORD、shipping_inventory_sources.yaml。
逻辑:加载 CRANE rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
用法(仓库根目录):
backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_export_smoke.py
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
import tempfile
import traceback
from datetime import datetime
from pathlib import Path
import yaml
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_crane_export_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _build_source_from_config(source_code: str = "CRANE") -> dict:
"""
从 YAML 构造 worker 兼容的 rpa_inventory_source。
核心逻辑:Crane 走 scheduled_report 异步导出,不依赖 warehouse_id。
"""
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml"
payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
raw = next(
(
item
for item in (payload.get("sources") or [])
if str(item.get("source_code") or "").upper() == source_code.upper()
),
None,
)
if not raw:
raise RuntimeError(f"source_code not found in config: {source_code}")
return {
"source_code": str(raw.get("source_code") or source_code).upper(),
"connector_type": str(raw.get("connector_type") or "crane_footprint").strip().lower(),
"display_name": str(raw.get("display_name") or source_code),
"enabled": bool(raw.get("enabled", True)),
"entry_url": str(raw.get("entry_url") or "https://wms-portal.craneww.com/#/on-hand-details-query"),
"navigation": dict(raw.get("navigation") or {}),
"parameters": [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)],
"query": {},
}
def main() -> int:
source_code = (sys.argv[1] if len(sys.argv) > 1 else "CRANE").strip().upper()
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_CRANE_USERNAME") or not worker._env("FREIGHT_RPA_CRANE_PASSWORD"):
print("[crane-export-smoke] 缺少 FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD")
return 1
source = _build_source_from_config(source_code)
task_no = f"SIF-SMOKE-{datetime.now().strftime('%Y%m%d%H%M%S')}"
trigger = {
"action": "inventory_export",
"task_no": task_no,
"requested_at": datetime.utcnow().isoformat(),
"mode": "smoke",
"attempt": 1,
"rpa_inventory_source": source,
}
drop_dir = Path(tempfile.mkdtemp(prefix=f"crane_export_{source_code.lower()}_"))
print(f"[crane-export-smoke] source={source_code}")
print(f"[crane-export-smoke] navigation={json.dumps(source.get('navigation') or {}, ensure_ascii=False)}")
print(f"[crane-export-smoke] drop_dir={drop_dir}")
print("[crane-export-smoke] 正在打开浏览器执行登录 + Run Report + Schedule 异步导出(预计 3~8 分钟)…")
try:
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
size_kb = out_file.stat().st_size / 1024
print(f"[crane-export-smoke] SUCCESS — {out_file} ({size_kb:.1f} KB)")
return 0
except Exception as exc:
print(f"[crane-export-smoke] FAILED — {exc}")
traceback.print_exc()
print("[crane-export-smoke] FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true,浏览器保持打开以便排查。")
return 2
if __name__ == "__main__":
sys.exit(main())