feat(shipping-notice): 新增库存快照管理与RPA批量导出功能
This commit is contained in:
1 parent
fc694a8f43
commit
d54f51ddc3
48 files changed
+4970
-543
No files matched your search
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
scripts/rpa/dsv_export_smoke.py
|
||||
|
||||
用途:本地手动验证指定 DSV 360 库存源(默认 BYAWSATL01)的浏览器导出全流程。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.json。
|
||||
逻辑:加载 rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
|
||||
|
||||
用法(仓库根目录):
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_smoke.py
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_smoke.py DSV360_AWSBI_BYAWSATL01
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
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_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) -> dict:
|
||||
"""
|
||||
从 JSON 配置构造 worker 兼容的 rpa_inventory_source(不依赖 Flask 上下文)。
|
||||
核心逻辑:复用与 inventory_sources._build_legacy_query 相同的 query 口径。
|
||||
"""
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.json"
|
||||
payload = json.loads(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}")
|
||||
|
||||
navigation = dict(raw.get("navigation") or {})
|
||||
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
|
||||
site = str(raw.get("site") or "dsv360").strip().lower()
|
||||
warehouse_id = str(raw.get("warehouse_id") or raw.get("warehouse_code") or "").strip()
|
||||
|
||||
query: dict[str, object] = {}
|
||||
if site == "dsv360":
|
||||
for key in ("program_group", "program_label", "report_group", "report_name"):
|
||||
if navigation.get(key):
|
||||
query[key] = navigation[key]
|
||||
if warehouse_id:
|
||||
query["warehouse_code"] = warehouse_id
|
||||
|
||||
for parameter in parameters:
|
||||
name = str(parameter.get("name") or "").strip()
|
||||
mode = str(parameter.get("mode") or "single").strip().lower()
|
||||
values = [str(v).strip() for v in (parameter.get("values") or []) if str(v).strip()]
|
||||
if not values:
|
||||
continue
|
||||
if mode == "multi_text":
|
||||
joined = str(parameter.get("joiner") or ",").join(values)
|
||||
if name.lower() == "owner":
|
||||
query["owner_code"] = joined
|
||||
elif name.lower() == "putawayzone":
|
||||
query["putaway_zone"] = joined
|
||||
elif name.lower() == "warehouse":
|
||||
query["warehouse_code"] = joined
|
||||
continue
|
||||
value = values[0]
|
||||
if name.lower() == "owner":
|
||||
query["owner_code"] = value
|
||||
elif name.lower() == "putawayzone":
|
||||
query["putaway_zone"] = value
|
||||
elif name.lower() == "warehouse":
|
||||
query["warehouse_code"] = value
|
||||
|
||||
return {
|
||||
"source_code": str(raw.get("source_code") or source_code).upper(),
|
||||
"source_type": "dsv360" if site == "dsv360" else site,
|
||||
"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://s360.dbschenker.com/"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"warehouse_code": str(raw.get("warehouse_code") or warehouse_id),
|
||||
"navigation": navigation,
|
||||
"parameters": parameters,
|
||||
"query": query,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
source_code = (sys.argv[1] if len(sys.argv) > 1 else "DSV360_AWSBI_BYAWSATL01").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_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
|
||||
print("[export-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_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"dsv_export_{source_code.lower()}_"))
|
||||
|
||||
print(f"[export-smoke] source={source_code} warehouse={source.get('warehouse_id')}")
|
||||
print(f"[export-smoke] query={json.dumps(source.get('query') or {}, ensure_ascii=False)}")
|
||||
print(f"[export-smoke] drop_dir={drop_dir}")
|
||||
print("[export-smoke] 正在打开浏览器执行登录 + 报表导出(预计 3~8 分钟)…")
|
||||
|
||||
try:
|
||||
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
|
||||
size_kb = out_file.stat().st_size / 1024
|
||||
print(f"[export-smoke] SUCCESS — {out_file} ({size_kb:.1f} KB)")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[export-smoke] FAILED — {exc}")
|
||||
traceback.print_exc()
|
||||
print("[export-smoke] FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true,浏览器保持打开以便排查。")
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user