Files
syops/scripts/rpa/run_inventory_batch_trigger.py
T

217 lines
9.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
scripts/rpa/run_inventory_batch_trigger.py
用途:用指定 inventory_export_batch_*.json 直接跑一次真实浏览器批量导出(不启动 worker 轮询)。
依赖:Playwright、freight_rpa_worker、FREIGHT_RPA_* 凭据与 HXOPS_API_BASE/SHIPPING_NOTICE_TOOL_API_KEY。
逻辑:委托 freight_rpa_worker._handle_inventory_batch_trigger 处理 trigger 并回调后端。
用法(仓库根目录):
backend\\venv\\Scripts\\python.exe scripts\\rpa\\run_inventory_batch_trigger.py backend\\data\\shipping_notice\\freight_rpa\\inventory_triggers\\inventory_export_batch_RUN2026070912002659A5.json
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
from pathlib import Path
from typing import Any
import yaml
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_dotenv_dev() -> None:
"""从 .env.dev 注入缺失的 SHIPPING_NOTICE / FREIGHT 目录变量(不覆盖已有 env)。"""
env_path = _repo_root() / ".env.dev"
if not env_path.is_file():
return
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and key not in os.environ:
os.environ[key] = value
def _load_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_runner", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _inventory_sources_config() -> dict[str, dict[str, Any]]:
"""
读取 shipping_inventory_sources.yaml,按 source_code 索引。
核心逻辑:供 enrich 补全旧 trigger 缺失的 site_id / navigation 等字段。
"""
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml"
payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
indexed: dict[str, dict[str, Any]] = {}
for item in payload.get("sources") or []:
if not isinstance(item, dict):
continue
code = str(item.get("source_code") or "").strip().upper()
if code:
indexed[code] = item
return indexed
def _build_query_from_yaml(raw: dict[str, Any]) -> dict[str, Any]:
"""复用 dsv_export_smoke 口径,从 YAML 构造 worker 兼容 query。"""
navigation = dict(raw.get("navigation") or {})
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
connector_type = str(raw.get("connector_type") or "dsv360").strip().lower()
warehouse_id = str(raw.get("warehouse_id") or "").strip()
query: dict[str, Any] = {}
if connector_type == "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 query
def _build_rpa_source_from_yaml(source_code: str) -> dict[str, Any] | None:
"""从 YAML 构造完整 rpa_inventory_source;找不到 source_code 时返回 None。"""
raw = _inventory_sources_config().get(source_code.strip().upper())
if not raw:
return None
navigation = dict(raw.get("navigation") or {})
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
return {
"source_code": str(raw.get("source_code") or source_code).upper(),
"connector_type": str(raw.get("connector_type") or "dsv360").strip().lower(),
"site_id": str(raw.get("site_id") or "").strip().upper() or None,
"warehouse_id": str(raw.get("warehouse_id") or "").strip(),
"entry_url": str(raw.get("entry_url") or ""),
"navigation": navigation,
"parameters": parameters,
"query": _build_query_from_yaml(raw),
}
def _enrich_trigger_sources(trigger_path: Path) -> None:
"""
用 YAML 补全 trigger 中 inventory_sources 的缺失字段(如 site_id)。
核心逻辑:旧排程 trigger 可能缺 site_id;以 YAML 为准 merge,保留 trigger 已有 query 覆盖。
"""
body = json.loads(trigger_path.read_text(encoding="utf-8"))
sources = body.get("inventory_sources") or []
if not isinstance(sources, list):
return
enriched: list[dict[str, Any]] = []
changed = False
for source in sources:
if not isinstance(source, dict):
continue
code = str(source.get("source_code") or "").strip().upper()
baseline = _build_rpa_source_from_yaml(code) if code else None
if baseline:
merged = {**baseline, **{k: v for k, v in source.items() if v not in (None, "", {}, [])}}
if not merged.get("query") and baseline.get("query"):
merged["query"] = baseline["query"]
elif baseline.get("query"):
merged["query"] = {**baseline["query"], **(source.get("query") or {})}
if merged != source:
changed = True
enriched.append(merged)
else:
enriched.append(source)
if not changed:
return
body["inventory_sources"] = enriched
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"[batch-run] 已从 YAML 补全 trigger 字段: {', '.join(str(s.get('source_code')) for s in enriched)}")
def main() -> int:
if len(sys.argv) < 2:
print("用法: python scripts/rpa/run_inventory_batch_trigger.py <trigger.json>")
return 1
trigger_path = Path(sys.argv[1]).expanduser()
if not trigger_path.is_file():
trigger_path = _repo_root() / sys.argv[1]
if not trigger_path.is_file():
print(f"[batch-run] trigger 不存在: {sys.argv[1]}")
return 1
_load_dotenv_dev()
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "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")
os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052")
repo = _repo_root()
drop_dir = Path(os.environ.get("FREIGHT_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_drop")
if not drop_dir.is_absolute():
drop_dir = repo / drop_dir
processed_dir = trigger_path.parent / "processed"
processed_dir.mkdir(parents=True, exist_ok=True)
drop_dir.mkdir(parents=True, exist_ok=True)
worker = _load_worker()
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
print("[batch-run] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
return 1
if not worker._env("SHIPPING_NOTICE_TOOL_API_KEY"):
print("[batch-run] 缺少 SHIPPING_NOTICE_TOOL_API_KEY(或 INTEGRATION_API_KEY)")
return 1
_enrich_trigger_sources(trigger_path)
print(f"[batch-run] trigger={trigger_path}")
print(f"[batch-run] drop_dir={drop_dir}")
print(f"[batch-run] mock={worker._env('FREIGHT_RPA_MOCK', 'false')} headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}")
crane_ready = bool(worker._env("FREIGHT_RPA_CRANE_USERNAME") and worker._env("FREIGHT_RPA_CRANE_PASSWORD"))
if not crane_ready:
print("[batch-run] 提示: 未配置 FREIGHT_RPA_CRANE_USERNAME/PASSWORD,Crane 源预计失败")
print("[batch-run] 正在打开浏览器执行批量导出(DSV + Crane,预计 5~15 分钟)…")
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
print("[batch-run] 完成,请查看 inventory_drop 目录与 worker 日志。")
return 0
if __name__ == "__main__":
raise SystemExit(main())