""" Freight RPA worker (PoC). 轮询 trigger JSON → 按 source_type 调用 DSV/Crane driver → 回调 hxops Tool API。 DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。 Usage: python scripts/rpa/freight_rpa_worker.py Required env (same as backend): HXOPS_API_BASE e.g. http://127.0.0.1:5052 SHIPPING_NOTICE_TOOL_API_KEY FREIGHT_INVENTORY_DROP_DIR FREIGHT_RPA_INVENTORY_TRIGGER_DIR FREIGHT_UPLOAD_QUEUE_DIR FREIGHT_RPA_UPLOAD_TRIGGER_DIR Optional: FREIGHT_RPA_MOCK=false FREIGHT_RPA_POLL_SECONDS=3 FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile FREIGHT_RPA_HEADLESS=false FREIGHT_RPA_BROWSER_CHANNEL=msedge FREIGHT_RPA_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe FREIGHT_RPA_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log FREIGHT_RPA_LOG_MAX_BYTES=10485760 FREIGHT_RPA_LOG_BACKUP_COUNT=5 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD """ from __future__ import annotations import atexit import json import os import shutil import sys import tempfile import time import urllib.error import urllib.request from datetime import UTC, datetime from pathlib import Path from typing import Any, Callable, TextIO import sys as _sys _RPA_DIR = Path(__file__).resolve().parent if str(_RPA_DIR) not in _sys.path: _sys.path.insert(0, str(_RPA_DIR)) from rpa_common import ( # noqa: E402 browser_timeout_ms as _browser_timeout_ms, click_text as _click_text, env as _env, select_or_fill as _select_or_fill, wait_for_visible_selector as _wait_for_visible_selector, ) import dsv_debug # noqa: E402 import dsv_driver # noqa: E402 import dsv_navigation # noqa: E402 import dsv_report_export # noqa: E402 import dsv_session # noqa: E402 # 测试与 smoke 向后兼容 re-export _maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv _fill_dsv_username = dsv_session.fill_dsv_username _click_dsv_continue = dsv_session.click_dsv_continue _click_dsv_password_method = dsv_session.click_dsv_password_method _fill_dsv_password_page_fields = dsv_session.fill_dsv_password_page_fields _wait_for_dsv_human_check_if_present = dsv_session.wait_for_dsv_human_check_if_present _wait_for_dsv_app_after_login = dsv_session.wait_for_dsv_app_after_login _wait_for_dsv_login_method_page = dsv_session.wait_for_dsv_login_method_page _is_dsv_username_page = dsv_session.is_dsv_username_page _find_dsv_password_locator = dsv_session.find_dsv_password_locator _submit_dsv_password_form = dsv_session.submit_dsv_password_form _dismiss_dsv_password_upgrade_prompt = dsv_session.dismiss_dsv_password_upgrade_prompt _wait_for_dsv_home_ready = dsv_session.wait_for_dsv_home_ready _report_dsv_chain_stage = dsv_debug.report_dsv_chain_stage _report_debug_event = dsv_debug.report_debug_event _collect_dsv_reports_probe = dsv_debug.collect_dsv_reports_probe _debug_dsv_stage = dsv_debug.debug_dsv_stage _emit_debug_event = dsv_debug.emit_debug_event _looks_like_dsv_login_method_page = dsv_session.looks_like_dsv_login_method_page _has_dsv_human_check_prompt = dsv_session.has_dsv_human_check_prompt _wait_for_dsv_reports_nav_stable = dsv_navigation.wait_for_dsv_reports_nav_stable _ensure_dsv_session = dsv_report_export.ensure_dsv_session _export_dsv_inventory_source = dsv_report_export.export_dsv_inventory_source _prepare_dsv_batch_export_step = dsv_report_export.prepare_dsv_batch_export_step _fill_dsv_filter_if_needed = dsv_report_export.fill_dsv_filter_if_needed _click_dsv_reports_menu = dsv_navigation.click_dsv_reports_menu _wait_for_dsv_report_form_ready = dsv_navigation.wait_for_dsv_report_form_ready _click_dsv_view_report = dsv_navigation.click_dsv_view_report _click_dsv_export_excel = dsv_report_export.click_dsv_export_excel _wait_for_dsv_report_result_ready = dsv_report_export.wait_for_dsv_report_result_ready _find_dsv_report_result_frame = dsv_report_export.find_dsv_report_result_frame _get_dsv_report_result_state = dsv_report_export.get_dsv_report_result_state _is_dsv_home_ready = dsv_session.is_dsv_home_ready _has_dsv_password_upgrade_prompt = dsv_session.has_dsv_password_upgrade_prompt try: from openpyxl import Workbook except ImportError: Workbook = None # type: ignore def _env(name: str, default: str = "") -> str: """ 读取 RPA 环境变量,并兼容 .env 中常见的外层单双引号写法。 核心逻辑:先读取原始环境变量并去除首尾空白;若值整体被同种引号包裹, 再剥离最外层一对引号,避免账号密码把引号一并输入到第三方登录页。 Args: name: 环境变量名。 default: 未设置时的默认值。 Returns: str: 去除空白与外层成对引号后的环境变量值。 """ value = str(os.getenv(name) or default).strip() if len(value) >= 2 and ( (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")) ): return value[1:-1] return value def _log_line_timestamp() -> str: """ 生成 worker 日志行首时间戳(本地时区)。 核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。 Returns: str: `YYYY-MM-DD HH:MM:SS` 格式字符串。 """ return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S") class _TeeStream: """ 同时写入控制台与日志文件的轻量 stream。 核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出; 每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量 保留最后几行排障信息。 """ def __init__(self, console: TextIO, log_file: TextIO) -> None: self._console = console self._log_file = log_file self._pending = "" self.encoding = getattr(console, "encoding", "utf-8") def _emit_line(self, line: str, *, newline: bool) -> None: """将单行(可含时间戳前缀)写入控制台与日志文件。""" if line: stamped = f"{_log_line_timestamp()} {line}" self._console.write(stamped) self._log_file.write(stamped) if newline: self._console.write("\n") self._log_file.write("\n") def write(self, text: str) -> int: self._pending += text while "\n" in self._pending: line, self._pending = self._pending.split("\n", 1) self._emit_line(line, newline=True) self.flush() return len(text) def flush(self) -> None: if self._pending: self._emit_line(self._pending, newline=False) self._pending = "" self._console.flush() self._log_file.flush() def isatty(self) -> bool: return bool(getattr(self._console, "isatty", lambda: False)()) def _configure_file_logging() -> Path | None: """ 按 FREIGHT_RPA_LOG_FILE 启用 worker 文件日志。 【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量, 让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查 登录、下载、回调失败与长批次耗时。 Returns: Path | None: 已启用的日志路径;未配置时返回 None。 """ raw = _env("FREIGHT_RPA_LOG_FILE") if not raw: return None path = Path(raw).expanduser() if not path.is_absolute(): path = (_backend_dir() / path).resolve() path.parent.mkdir(parents=True, exist_ok=True) _rotate_log_file_if_needed(path) log_file = path.open("a", encoding="utf-8", buffering=1) original_stdout = sys.stdout original_stderr = sys.stderr sys.stdout = _TeeStream(original_stdout, log_file) # type: ignore[assignment] sys.stderr = _TeeStream(original_stderr, log_file) # type: ignore[assignment] def _close_log() -> None: sys.stdout = original_stdout sys.stderr = original_stderr log_file.close() atexit.register(_close_log) print(f"[logging] tee enabled path={path}") return path def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int: """读取日志相关整数环境变量;非法值回退默认值。""" try: value = int(_env(name, str(default)) or str(default)) except ValueError: return default return max(value, min_value) def _rotate_log_file_if_needed(path: Path) -> None: """ 在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。 核心逻辑:当 `FREIGHT_RPA_LOG_FILE` 已存在且大小达到 `FREIGHT_RPA_LOG_MAX_BYTES` 时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `FREIGHT_RPA_LOG_BACKUP_COUNT` 的旧文件会被删除。`FREIGHT_RPA_LOG_MAX_BYTES<=0` 时禁用轮转。 """ max_bytes = _log_int_env("FREIGHT_RPA_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0) backup_count = _log_int_env("FREIGHT_RPA_LOG_BACKUP_COUNT", 5, min_value=0) if max_bytes <= 0 or not path.is_file(): return try: if path.stat().st_size < max_bytes: return except OSError: return if backup_count <= 0: path.unlink(missing_ok=True) return oldest = Path(f"{path}.{backup_count}") oldest.unlink(missing_ok=True) for index in range(backup_count - 1, 0, -1): src = Path(f"{path}.{index}") if src.exists(): src.replace(Path(f"{path}.{index + 1}")) path.replace(Path(f"{path}.1")) def _backend_dir() -> Path: """ 返回仓库内 backend 根目录。 核心逻辑:RPA worker 通常从仓库根目录启动,但也可能由计划任务从其他 cwd 启动;统一从脚本路径反推 backend,避免相对路径写到错误目录。 Returns: Path: backend 目录的绝对路径。 """ return Path(__file__).resolve().parents[2] / "backend" def _resolve_backend_relative_path(value: str, *, default: Path | None = None) -> Path: """ 将 RPA 环境变量路径解析为 backend 根目录下的绝对路径。 核心逻辑:兼容 `data/...` 与历史 `backend/data/...` 两种写法;绝对路径保持不变。 Args: value: 环境变量中的路径值。 default: value 为空时使用的默认路径。 Returns: Path: 解析后的绝对路径。 Raises: ValueError: value 与 default 同时为空。 """ raw = str(value or "").strip() if not raw: if default is None: raise ValueError("path is required when no default is provided") return default.resolve() path = Path(raw) if path.is_absolute(): return path.resolve() normalized = raw.replace("\\", "/") backend_dir = _backend_dir() if normalized.startswith("backend/"): return (backend_dir / normalized[len("backend/") :]).resolve() return (backend_dir / raw).resolve() def _require_path(name: str) -> Path: """ 读取必填目录环境变量,并确保目录存在。 核心逻辑:复用 backend 相对路径解析,保持 worker 与 Flask 配置的目录语义一致。 Args: name: 必填目录环境变量名。 Returns: Path: 已创建的绝对目录路径。 Raises: SystemExit: 环境变量未配置时退出 worker。 """ value = _env(name) if not value: raise SystemExit(f"Missing env: {name}") path = _resolve_backend_relative_path(value) path.mkdir(parents=True, exist_ok=True) return path def _browser_profile_root() -> Path: """ 解析 Playwright 运行时 profile 根目录。 核心逻辑:默认落到 `backend/data/shipping_notice/freight_rpa/browser_profile`; 若本机残留旧的 `data/freight_rpa/browser_profile` 配置,强制迁到 shipping_notice 命名空间,避免库存导出继续污染旧目录。 Returns: Path: 已解析但未创建的 profile 根目录。 """ default = _backend_dir() / "data" / "shipping_notice" / "freight_rpa" / "browser_profile" legacy_default = _backend_dir() / "data" / "freight_rpa" / "browser_profile" profile = _env("FREIGHT_RPA_BROWSER_PROFILE_DIR") normalized = profile.replace("\\", "/").strip("/") if normalized in { "data/freight_rpa/browser_profile", "backend/data/freight_rpa/browser_profile", } or (Path(profile).is_absolute() and Path(profile).resolve() == legacy_default.resolve()): print( "[warn] FREIGHT_RPA_BROWSER_PROFILE_DIR points to legacy data/freight_rpa; " f"using {default} instead" ) return default.resolve() return _resolve_backend_relative_path(profile, default=default) def _post_callback(path: str, payload: dict) -> None: base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/") key = ( _env("SHIPPING_NOTICE_TOOL_API_KEY") or _env("INTEGRATION_API_KEY") or _env("HXOPS_TOOLS_API_KEY") ) if not key: raise SystemExit("Missing SHIPPING_NOTICE_TOOL_API_KEY, INTEGRATION_API_KEY, or HXOPS_TOOLS_API_KEY") try: key.encode("latin-1") except UnicodeEncodeError as exc: raise RuntimeError( "SHIPPING_NOTICE_TOOL_API_KEY/INTEGRATION_API_KEY must be an ASCII token, " "not a Chinese placeholder or description" ) from exc url = f"{base}{path}" data = json.dumps(payload, ensure_ascii=False).encode("utf-8") req = urllib.request.Request( url, data=data, headers={ "Content-Type": "application/json", "X-Integration-Key": key, "X-Shipping-Tool-Key": key, }, method="POST", ) try: with urllib.request.urlopen(req, timeout=30) as resp: body = resp.read().decode("utf-8") print(f"[callback] {path} -> {resp.status} {body[:200]}") except urllib.error.HTTPError as exc: err = exc.read().decode("utf-8", errors="replace") raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc def _move_trigger(trigger_path: Path, target_dir: Path, reason: str) -> None: target_dir.mkdir(parents=True, exist_ok=True) done = target_dir / trigger_path.name trigger_path.replace(done) print(f"[trigger] {reason}: {trigger_path.name} -> {target_dir.name}") def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exception) -> None: print(f"[callback-error] {trigger_path.name}: {exc}", file=sys.stderr) if trigger_path.exists(): _move_trigger(trigger_path, failed_dir, "callback failed") def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path: sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY") if sample and Path(sample).is_file(): dest = drop_dir / Path(sample).name shutil.copy2(sample, dest) return dest if Workbook is None: raise RuntimeError("openpyxl required to generate mock inventory") dest = drop_dir / f"inventory_{task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx" wb = Workbook() ws = wb.active ws.title = "Inventory" ws.append(["料号", "可用数量"]) ws.append(["A001", 100]) ws.append(["A002", 50]) wb.save(dest) return dest def _download_name(task_no: str, source_code: str, suffix: str = ".xlsx") -> str: safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN" stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S") return f"inventory_{task_no}_{safe_source}_{stamp}{suffix}" def _require_playwright(): try: from playwright.sync_api import TimeoutError as PlaywrightTimeoutError from playwright.sync_api import sync_playwright except ImportError as exc: raise RuntimeError( "Playwright is required for real RPA. Install it on the RPA terminal with: " "pip install playwright && python -m playwright install chromium" ) from exc return sync_playwright, PlaywrightTimeoutError # #region debug-point H1:debug-reporter # #endregion _INVENTORY_EXCEL_MIN_BYTES = 512 _INVENTORY_EXCEL_HEADER_MARKERS = ( "on hand inventory", "supplier id", "aws sku", "sku description", ) def _validate_inventory_excel(path: Path) -> None: """ 校验 RPA 下载的库存 Excel 可被打开且具备报表基本结构。 核心逻辑:拒绝过小/HTML 错误页伪装文件;检查前几行是否含库存报表表头特征。 Args: path: 本地 Excel 路径。 Raises: RuntimeError: 文件过小、非 Excel 或缺少库存报表关键表头。 """ size = path.stat().st_size if size < _INVENTORY_EXCEL_MIN_BYTES: raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)") try: from openpyxl import load_workbook except ImportError as exc: raise RuntimeError("openpyxl required to validate inventory Excel") from exc try: workbook = load_workbook(path, read_only=True, data_only=True) except Exception as exc: raise RuntimeError(f"downloaded file is not valid Excel: {exc}") from exc try: worksheet = workbook.active if worksheet is None: raise RuntimeError("downloaded file is not valid Excel: missing active sheet") preview_lines: list[str] = [] for row in worksheet.iter_rows(max_row=6, values_only=True): cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()] if cells: preview_lines.append(" | ".join(cells).lower()) haystack = "\n".join(preview_lines) title = str(worksheet.title or "").lower().replace("_", "") if not any(marker in haystack for marker in _INVENTORY_EXCEL_HEADER_MARKERS): if "inventory" not in title and "onhand" not in title: raise RuntimeError("downloaded file is not valid Excel: missing inventory report headers") finally: workbook.close() def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path: suggested = str(download.suggested_filename or "") suffix = Path(suggested).suffix or ".xlsx" dest = drop_dir / _download_name(task_no, source_code, suffix=suffix) download.save_as(str(dest)) if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}: _validate_inventory_excel(dest) return dest def _batch_download_name(run_no: str, source_code: str, warehouse_id: str, suffix: str = ".xlsx") -> str: safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch" safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN" safe_wh = "".join(ch for ch in warehouse_id if ch.isalnum() or ch in {"-", "_"}) or "WH" stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S") return f"inventory_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}" def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dict[str, Any]) -> Path: suggested = str(download.suggested_filename or "") suffix = Path(suggested).suffix or ".xlsx" source_code = str(source.get("source_code") or "UNKNOWN") warehouse_id = str(source.get("warehouse_id") or "WH") dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix) download.save_as(str(dest)) if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}: _validate_inventory_excel(dest) return dest def _validate_inventory_source_for_rpa(source: dict[str, Any]) -> None: """ 校验单个库存 RPA source 的最小定位条件。 核心逻辑:DSV 必须有 site_id;Crane 只需要 source_type 即可分发,warehouse id 由库存 Excel 结果决定。 """ source_type = str(source.get("source_type") or "").strip() source_code = str(source.get("source_code") or "").strip() or "UNKNOWN" site_id = str(source.get("site_id") or "").strip() if source_type not in {"dsv360", "crane_footprint"}: raise RuntimeError(f"{source_code}: source_type must be dsv360 or crane_footprint") if source_type == "dsv360" and not site_id: raise RuntimeError(f"{source_code}: site_id is required for dsv360") def _load_crane_session_module() -> Any: """运行时加载 crane_session,避免 freight_rpa_worker 继续膨胀。""" import importlib.util from pathlib import Path module_path = Path(__file__).resolve().parent / "crane_session.py" spec = importlib.util.spec_from_file_location("crane_session_runtime", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def _maybe_auto_login_crane(page: Any) -> None: """Crane FootPrint 登录:User Name / Password / Sign in(见 crane_session.py)。""" module = _load_crane_session_module() module.maybe_auto_login_crane( page, env=_env, browser_timeout_ms=_browser_timeout_ms(), ) def _is_crane_session_active(page: Any, entry_url: str) -> bool: """判定 Crane portal 是否已登录且无需重复填写登录表单。""" module = _load_crane_session_module() return bool(module.is_crane_session_active(page, entry_url)) def _wait_for_crane_app_ready(page: Any, entry_url: str) -> None: """登录后等待 On Hand Details Query 等目标路由就绪。""" module = _load_crane_session_module() module.wait_for_crane_app_ready( page, entry_url, env=_env, browser_timeout_ms=_browser_timeout_ms(), ) def _goto_crane_entry_url(page: Any, entry_url: str) -> None: """打开 Crane 报表入口;已在目标站点且 session 有效时可跳过 goto。""" if _is_crane_session_active(page, entry_url): print("[crane] session already active on entry site, skip goto") _wait_for_crane_app_ready(page, entry_url) return page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) def _ensure_crane_session(page: Any, entry_url: str) -> None: """ Crane FootPrint 一次登录并等待报表页就绪。 核心逻辑:session 已有效时仅等待报表路由,不重复填写登录表单。 """ if _is_crane_session_active(page, entry_url): print("[crane] session already active on entry site, skip login") _wait_for_crane_app_ready(page, entry_url) return _goto_crane_entry_url(page, entry_url) _maybe_auto_login_crane(page) _wait_for_crane_app_ready(page, entry_url) def _reset_crane_export_entry(page: Any, entry_url: str) -> None: """ 批量导出中每个 Crane source 前回到报表表单入口。 核心逻辑:同 entry_url 且 session 仍有效时仅 reload 路由,不重复登录。 """ print("[crane] reset export entry before next source") if _is_crane_session_active(page, entry_url): print("[crane] same entry_url session active, skip re-login") page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) _wait_for_crane_app_ready(page, entry_url) return page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) _maybe_auto_login_crane(page) _wait_for_crane_app_ready(page, entry_url) def _load_crane_report_export_module() -> Any: """运行时加载 crane_report_export。""" import importlib.util from pathlib import Path module_path = Path(__file__).resolve().parent / "crane_report_export.py" spec = importlib.util.spec_from_file_location("crane_report_export_runtime", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: """ 在已登录 Crane session 上导出库存。 核心逻辑:Run Report → Schedule Report → Scheduled Reports 异步下载(不填 Warehouse)。 """ module = _load_crane_report_export_module() return module.export_crane_inventory_report( page, source, trigger=trigger, env=_env, browser_timeout_ms=_browser_timeout_ms(), select_or_fill=_select_or_fill, click_text=_click_text, ) def _open_browser(download_dir: Path): """ 打开用于库存 RPA 导出的浏览器上下文。 核心逻辑:无论正式执行还是测试执行,都基于 `FREIGHT_RPA_BROWSER_PROFILE_DIR` 创建一次性的运行时 profile 子目录,再交给 Playwright 的 persistent context。 这样既能保留 Chrome/Edge 可执行文件与下载目录配置,又能避免复用任何已有登录态。 Args: download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。 Returns: tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir` 为本次执行独占的临时 profile 目录,调用方负责在关闭浏览器后清理。 """ sync_playwright, _timeout = _require_playwright() playwright = sync_playwright().start() profile_root = _browser_profile_root() profile_root.mkdir(parents=True, exist_ok=True) runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root))) headless = _env("FREIGHT_RPA_HEADLESS", "false").lower() == "true" channel = _env("FREIGHT_RPA_BROWSER_CHANNEL") executable_path = _env("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH") launch_options: dict[str, Any] = { "headless": headless, "accept_downloads": True, "downloads_path": str(download_dir), } if executable_path: launch_options["executable_path"] = executable_path elif channel: launch_options["channel"] = channel context = playwright.chromium.launch_persistent_context( str(runtime_profile_dir), **launch_options, ) page = context.pages[0] if context.pages else context.new_page() page.set_default_timeout(_browser_timeout_ms()) return playwright, context, page, runtime_profile_dir def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: """单票 DSV 360 导出;委托 dsv_driver。""" return dsv_driver.download_dsv360_inventory(page, trigger, source) def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: """单票 trigger 的 Crane 导出;与批量共用 session + export 函数。""" entry_url = str(source.get("entry_url") or "").strip() if not entry_url: raise RuntimeError("Crane inventory source missing entry_url") _ensure_crane_session(page, entry_url) return _export_crane_inventory_source(page, trigger, source) def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> Path: task_no = str(trigger.get("task_no") or "").strip() source = trigger.get("rpa_inventory_source") if not isinstance(source, dict): raise RuntimeError("inventory trigger missing rpa_inventory_source") source_type = str(source.get("source_type") or "").strip() source_code = str(source.get("source_code") or "").strip() or source_type or "UNKNOWN" _validate_inventory_source_for_rpa(source) playwright = context = runtime_profile_dir = None keep_open_on_error = _env("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true" failed = False try: playwright, context, page, runtime_profile_dir = _open_browser(drop_dir) if source_type == "dsv360": download = _download_dsv360_inventory(page, trigger, source) elif source_type == "crane_footprint": download = _download_crane_inventory(page, trigger, source) else: raise RuntimeError(f"unsupported inventory source_type: {source_type}") return _save_download(download, drop_dir, task_no, source_code) except Exception: failed = True raise finally: if failed and keep_open_on_error: print("[browser] keeping browser open after error because FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true") while True: time.sleep(3600) 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) def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None: body = json.loads(trigger_path.read_text(encoding="utf-8")) run_no = str(body.get("run_no") or trigger_path.stem).strip() task_no = str(body.get("task_no") or "").strip() sources = body.get("inventory_sources") or [] failed_dir = trigger_path.parent / "failed" if not isinstance(sources, list) or not sources: trigger_path.unlink(missing_ok=True) return mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true" mode = "mock" if mock else "browser" results: list[dict[str, Any]] = [] if mock: for source in sources: if not isinstance(source, dict): continue task_stub = run_no out_file = _write_sample_inventory(drop_dir, task_stub) results.append({ "source_code": source.get("source_code"), "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "success": True, "file_path": str(out_file), "task_no": task_no or None, }) else: grouped: dict[str, list[dict[str, Any]]] = {} for source in sources: if not isinstance(source, dict): continue site = str(source.get("source_type") or "").strip() grouped.setdefault(site, []).append(source) for site, site_sources in grouped.items(): entry_url = str((site_sources[0] or {}).get("entry_url") or "").strip() playwright = context = runtime_profile_dir = None try: playwright, context, page, runtime_profile_dir = _open_browser(drop_dir) if site == "dsv360": export_fn = _export_dsv_inventory_source elif site == "crane_footprint": export_fn = _export_crane_inventory_source else: for source in site_sources: results.append({ "source_code": source.get("source_code"), "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "success": False, "error_message": f"unsupported source_type: {site}", }) continue for index, source in enumerate(site_sources): code = str(source.get("source_code") or "") wh = str(source.get("warehouse_id") or "") try: _validate_inventory_source_for_rpa(source) skip_navigation = False if site == "dsv360": skip_navigation = _prepare_dsv_batch_export_step( page, entry_url, site_sources[index - 1] if index > 0 else None, source, index=index, ) elif site == "crane_footprint": if index == 0: _ensure_crane_session(page, entry_url) else: _reset_crane_export_entry(page, entry_url) download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source) out_file = _save_batch_download(download, drop_dir, run_no, source) results.append({ "source_code": code, "site_id": source.get("site_id"), "warehouse_id": wh, "success": True, "file_path": str(out_file), "task_no": task_no or None, }) print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}") except Exception as exc: results.append({ "source_code": code, "site_id": source.get("site_id"), "warehouse_id": wh, "success": False, "error_message": str(exc), }) print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr) 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) try: _post_callback("/api/shipping-notice/rpa/inventory-batch-ready", { "run_no": run_no, "success": any(item.get("success") for item in results), "rpa_mode": mode, "trigger_type": body.get("trigger_type"), "schedule_run_id": body.get("schedule_run_id"), "results": results, }) _move_trigger(trigger_path, processed_dir, "processed") print(f"[inventory-batch] callback done run={run_no} success={sum(1 for r in results if r.get('success'))}/{len(results)}") except Exception as callback_exc: _report_callback_failure(trigger_path, failed_dir, callback_exc) def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None: body = json.loads(trigger_path.read_text(encoding="utf-8")) action = str(body.get("action") or "inventory_export").strip() if action == "inventory_export_batch": _handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) return task_no = str(body.get("task_no") or "").strip() failed_dir = trigger_path.parent / "failed" if not task_no: print(f"[skip] invalid inventory trigger: {trigger_path.name}") trigger_path.unlink(missing_ok=True) return mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true" mode = "mock" if mock else "browser" try: out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir) _post_callback("/api/shipping-notice/rpa/inventory-ready", { "task_no": task_no, "success": True, "file_path": str(out_file), "rpa_mode": mode, "source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None), }) _move_trigger(trigger_path, processed_dir, "processed") print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}") except Exception as exc: try: _post_callback("/api/shipping-notice/rpa/inventory-ready", { "task_no": task_no, "success": False, "rpa_mode": mode, "error_message": str(exc), }) if trigger_path.exists(): trigger_path.unlink(missing_ok=True) except Exception as callback_exc: _report_callback_failure(trigger_path, failed_dir, callback_exc) def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None: body = json.loads(trigger_path.read_text(encoding="utf-8")) task_no = str(body.get("task_no") or "").strip() file_path = str(body.get("file_path") or "").strip() failed_dir = trigger_path.parent / "failed" if not task_no: trigger_path.unlink(missing_ok=True) return mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true" if not mock: print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}") return if file_path and not Path(file_path).is_file(): try: _post_callback("/api/shipping-notice/rpa/upload-complete", { "task_no": task_no, "success": False, "error_message": f"queue file missing: {file_path}", }) trigger_path.unlink(missing_ok=True) except Exception as callback_exc: _report_callback_failure(trigger_path, failed_dir, callback_exc) return ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}" try: _post_callback("/api/shipping-notice/rpa/upload-complete", { "task_no": task_no, "success": True, "freight_ref_no": ref, }) _move_trigger(trigger_path, processed_dir, "processed") print(f"[upload] mock upload done for {task_no} ref={ref}") except Exception as callback_exc: _report_callback_failure(trigger_path, failed_dir, callback_exc) def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None: if not trigger_dir.is_dir(): return for path in sorted(trigger_dir.glob("*.json")): if not path.is_file(): continue try: handler(path, *extra_args) except Exception as exc: print(f"[error] {path.name}: {exc}", file=sys.stderr) def main() -> None: _configure_file_logging() drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR") inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR") upload_trigger_dir = _require_path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR") poll = max(1, int(_env("FREIGHT_RPA_POLL_SECONDS", "3") or "3")) inv_processed = inv_trigger_dir / "processed" upload_processed = upload_trigger_dir / "processed" print("[freight_rpa_worker] started") print(f" mock={_env('FREIGHT_RPA_MOCK', 'false')}") print(f" inventory_triggers={inv_trigger_dir}") print(f" upload_triggers={upload_trigger_dir}") print(f" drop={drop_dir}") print(f" queue={upload_queue_dir}") while True: _scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed)) _scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,)) time.sleep(poll) if __name__ == "__main__": main()