"""Run one database-generated inventory batch trigger without starting the polling worker.""" from __future__ import annotations import importlib.util import os import sys from pathlib import Path def _repo_root() -> Path: """Return the HXOPS repository root for relative operational directories.""" return Path(__file__).resolve().parents[2] def _load_dotenv_dev() -> None: """Load missing local runtime variables without exposing or overwriting credentials.""" 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("=") if key.strip() and key.strip() not in os.environ: os.environ[key.strip()] = value.strip().strip('"').strip("'") def _load_worker(): """Load the polling worker module so manual runs share the production trigger contract.""" 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 main() -> int: """Execute a complete, database-generated batch trigger and post its normal callback.""" if len(sys.argv) < 2: print("usage: python scripts/rpa/run_inventory_batch_trigger.py ") 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 not found: {sys.argv[1]}") return 1 _load_dotenv_dev() os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true") os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile") if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"): os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge") os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052") if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"): print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required") return 1 drop_dir = Path(os.environ.get("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_drop") if not drop_dir.is_absolute(): drop_dir = _repo_root() / 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() worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) return 0 if __name__ == "__main__": raise SystemExit(main())