Files
syops/scripts/rpa/freight_rpa_worker.py
T
hugo c94d173f92 feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口
完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
2026-08-11 14:04:39 +08:00

1762 lines
74 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.
"""
Freight RPA worker (PoC).
轮询 trigger JSON → 按 connector_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
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR
Optional:
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5
SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR
SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR
"""
from __future__ import annotations
import atexit
from contextlib import contextmanager
import json
import os
import shutil
import hashlib
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
from cryptography.fernet import Fernet, InvalidToken
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
from dsv_report_export import NoInventoryDataError # noqa: E402
import dsv_session # noqa: E402
import freight_rpa_heartbeat # 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 _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:
"""
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
登录、下载、回调失败与长批次耗时。
Returns:
Path | None: 已启用的日志路径;未配置时返回 None。
"""
raw = _env("SHIPPING_NOTICE_RPA_WORKER_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 单个日志无限增长。
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT`
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
"""
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
backup_count = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_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("SHIPPING_NOTICE_RPA_WORKER_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] SHIPPING_NOTICE_RPA_WORKER_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 _mask_secret(value: str) -> str:
"""
对 API Key 等敏感字符串做首尾保留脱敏,供 callback 请求日志打印。
Args:
value: 原始密钥字符串。
Returns:
str: 长度 ≤8 时返回 `***`;否则保留前 4 与后 4 字符。
"""
value = str(value or "")
if len(value) <= 8:
return "***"
return f"{value[:4]}...{value[-4:]}"
def _resolve_tool_api_auth_debug() -> tuple[str, str]:
"""
返回 Tool API 鉴权来源与脱敏后的 Key,供 Worker 启动日志快速排查环境变量问题。
核心逻辑:按实际请求相同的优先级检查三个环境变量;只返回来源名与脱敏值,避免明文泄露。
Returns:
tuple[str, str]: `(source, masked_value)`;未配置时返回 `("missing", "")`。
"""
for env_name in (
"SHIPPING_NOTICE_TOOL_API_KEY",
"INTEGRATION_API_KEY",
"HXOPS_TOOLS_API_KEY",
):
key = _env(env_name)
if key:
return env_name, _mask_secret(key)
return "missing", ""
def _post_callback(path: str, payload: dict) -> None:
"""
向 HXOPS 货代 Tool API 发送 JSON 回调。
核心逻辑:组装 URL 与双 Header 密钥 → 打印脱敏请求日志 → POST;HTTP 错误时打印响应体摘要。
"""
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")
print(
"[callback-request] "
f"POST {url} "
f"headers={{'Content-Type': 'application/json', "
f"'X-Integration-Key': '{_mask_secret(key)}', "
f"'X-Shipping-Tool-Key': '{_mask_secret(key)}'}} "
f"payload={data.decode('utf-8', errors='replace')[:4000]}"
)
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")
print(
"[callback-response] "
f"POST {url} -> HTTP {exc.code} {err[:1000]}",
file=sys.stderr,
)
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")
_INVENTORY_V2_REQUIRED_FIELDS = (
"schema_version", "callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id",
"expected_warehouse_id",
)
def _inventory_v2_identity_errors(body: dict[str, Any]) -> list[str]:
"""校验库存 RPA v2 Trigger 身份;缺失字段时禁止启动外部库存操作。"""
missing = []
for key in _INVENTORY_V2_REQUIRED_FIELDS:
value = body.get(key)
if value is None or (isinstance(value, str) and not value.strip()):
missing.append(key)
if body.get("schema_version") != "shipping_inventory_rpa.v2":
missing.append("schema_version")
return list(dict.fromkeys(missing))
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("SHIPPING_NOTICE_RPA_WORKER_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 的最小定位条件。
核心逻辑:业务 connector_type 为 dbs/crane,driver 类型由 worker_connector_type 指定;
DBS 固定仓以 warehouse_id 作为导出筛选,Crane 多仓导出不要求预置 Warehouse。
"""
connector_type = _worker_connector_type(source)
source_code = str(source.get("source_code") or "").strip() or "UNKNOWN"
warehouse_id = str(source.get("warehouse_id") or "").strip()
if connector_type not in {"dsv360", "crane_footprint"}:
raise RuntimeError(
f"{source_code}: worker connector_type must be dsv360 or crane_footprint"
)
if connector_type == "dsv360" and not warehouse_id:
raise RuntimeError(f"{source_code}: warehouse_id is required for dbs")
def _worker_connector_type(source: dict[str, Any]) -> str:
"""将业务 connector_type 规范化为现有 RPA driver 名称。"""
raw = str(source.get("worker_connector_type") or source.get("connector_type") or "").strip().lower()
return {"dbs": "dsv360", "crane": "crane_footprint"}.get(raw, raw)
def _group_batch_sources_by_profile(sources: list[Any]) -> dict[tuple[str, str], list[dict[str, Any]]]:
"""按 Driver 和 RPA Profile 分组,隔离不同登录账号的浏览器会话。"""
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {}
for source in sources:
if not isinstance(source, dict):
continue
driver = _worker_connector_type(source)
profile_code = str(source.get("rpa_profile_code") or source.get("source_code") or "").strip()
grouped.setdefault((driver, profile_code), []).append(source)
return grouped
def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
"""在同一登录上下文中切换到干净页面,隔离上一站的 DSV 报表状态。
Args:
context: 已建立登录态的 Playwright browser context,Cookie 会继续复用。
current_page: 上一站使用的页面;关闭它避免报表 iframe 和下载菜单残留。
Returns:
Any: 可重新进入库存报表的空白页面,不会触发新的浏览器登录。
"""
next_page = context.new_page()
if current_page is not None:
try:
current_page.close()
except Exception as exc:
print(f"[inventory-batch] close previous page failed: {exc}", file=sys.stderr)
return next_page
@contextmanager
def _profile_credentials(source: dict[str, Any]):
"""仅在单 Profile 执行范围内解密凭据并暂存环境变量,退出时恢复原值。"""
envelope = source.get("credential_envelope") or {}
if not isinstance(envelope, dict):
raise RuntimeError("invalid credential_envelope")
username_ciphertext = str(envelope.get("username_ciphertext") or "").strip()
password_ciphertext = str(envelope.get("password_ciphertext") or "").strip()
if not username_ciphertext and not password_ciphertext:
yield
return
if not username_ciphertext or not password_ciphertext:
raise RuntimeError("RPA Profile credentials are incomplete")
key = _env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY")
if not key:
raise RuntimeError("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is required for RPA Profile credentials")
try:
fernet = Fernet(key.encode("ascii"))
username = fernet.decrypt(username_ciphertext.encode("ascii")).decode("utf-8")
password = fernet.decrypt(password_ciphertext.encode("ascii")).decode("utf-8")
except (ValueError, InvalidToken, UnicodeDecodeError) as exc:
raise RuntimeError("RPA Profile credentials cannot be decrypted") from exc
connector = _worker_connector_type(source)
if connector == "dsv360":
username_key, password_key = "SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD"
elif connector == "crane_footprint":
username_key, password_key = "SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME", "SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD"
else:
raise RuntimeError(f"unsupported worker connector_type: {connector}")
old = {username_key: os.environ.get(username_key), password_key: os.environ.get(password_key)}
os.environ[username_key], os.environ[password_key] = username, password
try:
yield
finally:
for env_key, old_value in old.items():
if old_value is None:
os.environ.pop(env_key, None)
else:
os.environ[env_key] = old_value
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 导出的浏览器上下文。
核心逻辑:无论正式执行还是测试执行,都基于 `SHIPPING_NOTICE_RPA_WORKER_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("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false").lower() == "true"
channel = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL")
executable_path = _env("SHIPPING_NOTICE_RPA_WORKER_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 source.get("login_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 = dict(source)
source["__download_dir"] = str(drop_dir)
connector_type = _worker_connector_type(source)
source_code = str(source.get("source_code") or "").strip() or connector_type or "UNKNOWN"
_validate_inventory_source_for_rpa(source)
playwright = context = runtime_profile_dir = None
keep_open_on_error = _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
failed = False
try:
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
with _profile_credentials(source):
if connector_type == "dsv360":
download = _download_dsv360_inventory(page, trigger, source)
elif connector_type == "crane_footprint":
download = _download_crane_inventory(page, trigger, source)
else:
raise RuntimeError(f"unsupported inventory connector_type: {connector_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 SHIPPING_NOTICE_RPA_WORKER_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 _normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
"""
batch 明细状态归一化(比单任务更严格:缺省字段不算 success)。
核心逻辑:worker 自生成 results 均带 status/success;空 dict 或缺字段归为 failed,
避免 batch summary 误计成功。
"""
raw_status = str(item.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if item.get("skipped"):
return "skipped"
if item.get("success") is True:
return "success"
return "failed"
def _summarize_inventory_batch_results(results: list[dict[str, Any]]) -> dict[str, Any]:
"""
汇总 batch 回调顶层状态。
核心逻辑:
- status:新监控用,区分 success / partial_failed / failed;
- success(legacy):与旧 any(item.success) 兼容,有 success 或 skipped 即为 true;
- has_success:是否至少有一条实际导出成功。
"""
zero = {
"status": "failed",
"success": False,
"has_success": False,
"success_count": 0,
"skipped_count": 0,
"failed_count": 0,
}
statuses = [
_normalize_inventory_batch_item_status(item)
for item in results
if isinstance(item, dict)
]
if not statuses:
return dict(zero)
success_count = sum(1 for status in statuses if status == "success")
skipped_count = sum(1 for status in statuses if status == "skipped")
failed_count = sum(1 for status in statuses if status == "failed")
if failed_count == 0:
top_status = "success"
elif success_count == 0 and skipped_count == 0:
top_status = "failed"
else:
top_status = "partial_failed"
return {
"status": top_status,
"success": (success_count + skipped_count) > 0,
"has_success": success_count > 0,
"success_count": success_count,
"skipped_count": skipped_count,
"failed_count": failed_count,
}
def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
"""
将 batch 导出结果收敛为库存站点测试专用回调载荷。
核心逻辑:配置测试只测单站点,取首个 success 的 file_path;无库存是有效业务结果,单独上报 empty。
必须回调 /rpa/inventory-configuration-test-ready(站点停用时生产 batch 接口会报 unknown_or_disabled_source)。
Args:
run_no: 测试运行号(CONFIG-...)。
results: Worker 各 source 导出结果列表。
Returns:
dict: report_test_export 所需的 run_no / status / file_path 或 error_message。
"""
success_item = next(
(
item
for item in results
if isinstance(item, dict) and _normalize_inventory_batch_item_status(item) == "success"
),
None,
)
if success_item is not None:
return {
"run_no": run_no,
"status": "success",
"file_path": str(success_item.get("file_path") or ""),
}
empty_item = next(
(
item for item in results
if isinstance(item, dict) and str(item.get("skip_reason") or "") == "no_inventory_data"
),
None,
)
if empty_item is not None:
return {
"run_no": run_no,
"status": "empty",
"message": str(empty_item.get("message") or "库存查询成功但当前无库存数据")[:500],
}
first = next((item for item in results if isinstance(item, dict)), {})
return {
"run_no": run_no,
"status": "failed",
"error_message": str(
first.get("error_message") or first.get("message") or "测试导出失败"
)[:500],
}
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("batch_run_no") or 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
identity_errors = []
if body.get("schema_version") != "shipping_inventory_rpa.v2":
identity_errors.append("schema_version")
if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()):
identity_errors.append("callback_id")
if body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip()):
identity_errors.append("task_no")
for index, source in enumerate(sources):
if not isinstance(source, dict):
identity_errors.append(f"inventory_sources[{index}]")
continue
identity_errors.extend(
f"inventory_sources[{index}].{key}"
for key in _INVENTORY_V2_REQUIRED_FIELDS
if key not in {"schema_version", "task_no", "callback_id"}
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
)
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"batch_run_no": run_no or None,
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": list(dict.fromkeys(identity_errors)),
"results": [],
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser"
results: list[dict[str, Any]] = []
# v2 claimed 回调只记录领取事实,不代表业务成功。
if body.get("schema_version") == "shipping_inventory_rpa.v2":
claimed_items = []
for source in sources:
if isinstance(source, dict) and source.get("source_run_no"):
claimed_items.append({k: source.get(k) for k in ("task_no", "source_code", "attempt_no", "source_run_no", "lease_token")})
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-claimed", {
"schema_version": "shipping_inventory_rpa.v2", "batch_run_no": run_no,
"claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("SHIPPING_NOTICE_RPA_WORKER_ID", "worker"),
"items": claimed_items,
})
except Exception as exc:
print(f"[inventory-batch] claimed callback failed: {exc}", file=sys.stderr)
def report_configuration_test_progress(source: dict) -> None:
"""实际操作站点前回传领取状态;进度回调故障不能中断库存导出。"""
if str(body.get("trigger_type") or "").strip() != "configuration_test_batch":
return
validation_run_no = str(source.get("validation_run_no") or "").strip()
if not validation_run_no:
return
try:
_post_callback("/api/shipping-notice/rpa/inventory-configuration-test-batch-progress", {
"run_no": run_no,
"validation_batch_id": body.get("validation_batch_id"),
"validation_run_no": validation_run_no,
"stage": "rpa_exporting",
})
except Exception as exc:
print(f"[inventory-batch] progress callback failed {validation_run_no}: {exc}", file=sys.stderr)
if mock:
for source in sources:
if not isinstance(source, dict):
continue
report_configuration_test_progress(source)
task_stub = run_no
out_file = _write_sample_inventory(drop_dir, task_stub)
results.append({
"source_code": source.get("source_code"),
"warehouse_id": source.get("warehouse_id"),
"status": "success",
"success": True,
"file_path": str(out_file),
"task_no": task_no or None,
"validation_run_no": source.get("validation_run_no"),
**{k: source.get(k) for k in ("task_no", "attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")},
})
else:
# 一个 Profile 对应一个独立浏览器登录态;同 Driver 的不同账号绝不能共用 session。
grouped = _group_batch_sources_by_profile(sources)
for (site, _profile_code), site_sources in grouped.items():
entry_url = str((site_sources[0] or {}).get("entry_url") or (site_sources[0] or {}).get("login_url") or "").strip()
playwright = context = runtime_profile_dir = None
try:
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
if site not in {"dsv360", "crane_footprint"}:
raise RuntimeError(f"unsupported connector_type: {site}")
export_fn = _export_dsv_inventory_source if site == "dsv360" else _export_crane_inventory_source
# 同组的 Profile 相同,登录和导出期间使用同一组临时凭据。
with _profile_credentials(site_sources[0]):
for index, source in enumerate(site_sources):
source = dict(source)
source["__download_dir"] = str(drop_dir)
code = str(source.get("source_code") or "")
wh = str(source.get("warehouse_id") or "")
try:
report_configuration_test_progress(source)
_validate_inventory_source_for_rpa(source)
skip_navigation = False
if site == "dsv360":
# DSV 报表页会保留 iframe、导出菜单与下载等待状态;同一 tab
# 串行切换站点会让下一站误用上一站页面。复用 context 登录态,但每站新开页面。
if index > 0:
page = _open_clean_batch_page(context, page)
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
elif 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, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
except NoInventoryDataError as exc:
results.append({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
except Exception as exc:
results.append({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
except Exception as exc:
for source in site_sources:
results.append({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
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)
# v2 业务结果必须原样保留逐源身份,后端据此绑定 SourceAttempt;
# Worker 不生成新身份,只从已校验的 trigger source 复制。
source_identity_by_key = {
(
str(source.get("source_code") or "").strip().upper(),
str(source.get("expected_warehouse_id") or source.get("warehouse_id") or "").strip().upper(),
): source
for source in sources
if isinstance(source, dict)
}
for result in results:
source = source_identity_by_key.get((
str(result.get("source_code") or "").strip().upper(),
str(result.get("warehouse_id") or result.get("expected_warehouse_id") or "").strip().upper(),
))
if not source:
continue
for key in (
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id", "expected_warehouse_id",
):
if key in source:
result[key] = source.get(key)
try:
batch_summary = _summarize_inventory_batch_results(results)
trigger_type = str(body.get("trigger_type") or "").strip()
# [STEP] 配置测试必须走专用回调;停用站点走生产 batch 会得到 unknown_or_disabled_source
if trigger_type == "configuration_test":
callback_path = "/api/shipping-notice/rpa/inventory-configuration-test-ready"
callback_payload = _configuration_test_callback_payload(run_no, results)
elif trigger_type == "configuration_test_batch":
callback_path = "/api/shipping-notice/rpa/inventory-configuration-test-batch-ready"
callback_payload = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
"validation_batch_id": body.get("validation_batch_id"),
"batch_no": body.get("batch_no"),
"rpa_mode": mode,
"results": [{**item, "callback_id": f"{run_no}:{item.get('source_run_no')}:C1"} for item in results],
}
else:
callback_path = "/api/shipping-notice/rpa/inventory-batch-ready"
callback_payload = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
"status": batch_summary["status"],
"success": batch_summary["success"],
"has_success": batch_summary["has_success"],
"success_count": batch_summary["success_count"],
"skipped_count": batch_summary["skipped_count"],
"failed_count": batch_summary["failed_count"],
"rpa_mode": mode,
"trigger_type": body.get("trigger_type"),
"schedule_run_id": body.get("schedule_run_id"),
"results": results,
}
_post_callback(callback_path, callback_payload)
_move_trigger(trigger_path, processed_dir, "processed")
print(
f"[inventory-batch] callback done run={run_no} "
f"path={callback_path} "
f"status={batch_summary['status']} "
f"success={batch_summary['success_count']} "
f"skipped={batch_summary['skipped_count']} "
f"failed={batch_summary['failed_count']}/{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
identity_errors = _inventory_v2_identity_errors({**body, "task_no": task_no})
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"task_no": task_no,
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": identity_errors,
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser"
# 单源 Trigger 与 batch 使用同一 v2 身份契约;Worker 只能回传后端冻结的字段。
identity = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": str(body.get("callback_id") or "").strip(),
"task_no": task_no,
"source_code": str(body.get("source_code") or ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else "") or "").strip().upper(),
"source_run_no": str(body.get("source_run_no") or "").strip(),
"run_no": str(body.get("source_run_no") or "").strip(),
"attempt_no": body.get("attempt_no") or body.get("attempt"),
"lease_token": str(body.get("lease_token") or "").strip(),
"candidate_set_id": body.get("candidate_set_id"),
"execution_id": body.get("execution_id"),
"gate_id": body.get("gate_id"),
"expected_warehouse_id": body.get("expected_warehouse_id"),
}
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", {
**identity,
"status": "success",
"success": True,
"file_path": str(out_file),
"file_sha256": hashlib.sha256(out_file.read_bytes()).hexdigest(),
"rpa_mode": mode,
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
except NoInventoryDataError as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
**identity,
"status": "skipped",
"success": False,
"skipped": True,
"skip_reason": "no_inventory_data",
"message": str(exc),
"rpa_mode": mode,
})
if trigger_path.exists():
trigger_path.unlink(missing_ok=True)
print(f"[inventory] {mode} export skipped for {task_no}: {exc}")
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
**identity,
"status": "failed",
"success": False,
"skipped": 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 _upload_worker_enabled() -> bool:
"""返回上传浏览器自动化开关;默认关闭,避免仅部署 Worker 就提交货代文件。"""
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false").lower() == "true"
def _upload_submit_confirmed() -> bool:
"""返回真实提交二次确认开关;页面填文件与最终提交必须显式分开授权。"""
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "false").lower() == "true"
def _click_dsv_upload_tool_entry(page: Any, *, section: str | None = None) -> bool:
"""点击已确认的 DSV Upload Tool 入口;返回是否已打开 WMS 上传页。"""
section_selector = (
f":has-text({json.dumps(section)})" if section else ""
)
selectors = (
f"{section_selector} a:has-text('Upload Tool')" if section else "",
f"{section_selector} button:has-text('Upload Tool')" if section else "",
"a:has-text('Upload Tool')" if not section else "",
"button:has-text('Upload Tool')" if not section else "",
"[role='link']:has-text('Upload Tool')" if not section else "",
)
for selector in (item for item in selectors if item):
try:
locator = page.locator(selector).first
locator.wait_for(state="visible", timeout=3_000)
locator.click(timeout=3_000)
page.get_by_text("WMS Upload Tool", exact=False).first.wait_for(
state="visible", timeout=_browser_timeout_ms()
)
return True
except Exception:
continue
return False
def _navigate_dsv_to_upload_tool(page: Any, entry_url: str) -> None:
"""
复用 DSV 登录态进入 WMS Upload Tool,优先首页入口,再退回 Apps 菜单。
Args:
page: 已由 Worker 创建的 Playwright 页面。
entry_url: 已审核的 DSV Portal 入口,不允许用代码猜测站点地址。
Raises:
RuntimeError: Portal 未提供截图已确认的任一 Upload Tool 入口时抛出。
"""
_ensure_dsv_session(page, entry_url)
if _click_dsv_upload_tool_entry(page, section="My Applications"):
return
for selector in (
"nav a:has-text('Apps')",
"a.nav-link:has-text('Apps')",
"[role='button']:has-text('Apps')",
):
try:
apps = page.locator(selector).first
apps.wait_for(state="visible", timeout=3_000)
apps.click(timeout=3_000, force=True)
break
except Exception:
continue
if _click_dsv_upload_tool_entry(page):
return
raise RuntimeError("DSV WMS Upload Tool was not found via My Applications or Apps")
def _capture_success_page_evidence(
page: Any,
*,
kind: str,
selector: str,
filename: str,
reference: str | None = None,
) -> dict[str, Any]:
"""
采集 RPA 成功页的不可变 DOM/截图证据(与后端 success_evidence 契约对齐)。
核心逻辑:截取 selector outerHTML(失败则 page.content 前 8KB)并算 sha256;
可选截图 base64(≤200KB);page_url 缺失时用 about:blank。
Args:
page: Playwright 页面对象。
kind: 白名单 evidence kind。
selector: 成功 DOM 选择器。
filename: 上传文件名。
reference: 可选货代回执号。
Returns:
success_evidence dict。
"""
import base64
import hashlib
from datetime import datetime, timezone
observed_at = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
try:
page_url = str(getattr(page, "url", None) or page.url or "").strip()
except Exception:
page_url = ""
snippet = ""
try:
loc = page.locator(selector).first
snippet = str(loc.evaluate("el => el.outerHTML") or "").strip()
except Exception:
snippet = ""
if not snippet:
try:
snippet = str(page.content() or "")[:8000]
except Exception:
snippet = ""
if not snippet:
snippet = f'<evidence kind="{kind}" selector="{selector}" filename="{filename}"/>'
snippet = snippet[:8000]
if not page_url:
page_url = "about:blank"
evidence: dict[str, Any] = {
"kind": kind,
"selector": selector,
"filename": filename,
"reference": reference,
"observed_at": observed_at,
"page_url": page_url,
"dom_snippet": snippet,
"dom_sha256": hashlib.sha256(snippet.encode("utf-8")).hexdigest(),
}
try:
shot = page.screenshot(type="png", full_page=False)
if isinstance(shot, (bytes, bytearray)) and 0 < len(shot) <= 200_000:
evidence["screenshot_base64"] = base64.b64encode(bytes(shot)).decode("ascii")
evidence["screenshot_sha256"] = hashlib.sha256(bytes(shot)).hexdigest()
except Exception:
pass
return evidence
def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str, Any]:
"""
仅以 DSV History 同名行的绿色 success DOM 确认上传受理;Reference 可选。
核心逻辑:succeeded=true 即成功;reference 可为空字符串。
Args:
page: Playwright 页面对象。
filename: 上传文件名(History 表匹配键)。
Returns:
dict: reference(str,可空)与 success_evidence(含不可变 DOM 证据)。
"""
try:
page.get_by_text("History", exact=True).first.click(timeout=_browser_timeout_ms())
except Exception as exc:
raise RuntimeError("DSV Upload History tab was not available") from exc
receipt_script = """
({ filename }) => {
const clean = (value) => String(value || '').replace(/\\s+/g, ' ').trim();
for (const table of document.querySelectorAll('table')) {
const headers = Array.from(table.querySelectorAll('thead th')).map((node) => clean(node.textContent));
const filenameIndex = headers.findIndex((value) => value.toLowerCase() === 'filename');
const referenceIndex = headers.findIndex((value) => value.toLowerCase() === 'reference #');
if (filenameIndex < 0 || referenceIndex < 0) continue;
for (const row of table.querySelectorAll('tbody tr')) {
const cells = Array.from(row.querySelectorAll(':scope > td'));
if (clean(cells[filenameIndex]?.textContent) !== filename) continue;
return {
found: true,
succeeded: Boolean(row.querySelector('em.fa.fa-circle.success-color.status-icon')),
reference: clean(cells[referenceIndex]?.textContent),
};
}
}
return { found: false, succeeded: false, reference: '' };
}
"""
selector = 'em.fa.fa-circle.success-color.status-icon'
deadline = time.monotonic() + (_browser_timeout_ms() / 1000)
last_state: dict[str, Any] = {"found": False, "succeeded": False, "reference": ""}
while time.monotonic() < deadline:
try:
state = page.evaluate(receipt_script, {"filename": filename}) or {}
last_state = state if isinstance(state, dict) else last_state
except Exception:
last_state = {"found": False, "succeeded": False, "reference": ""}
if bool(last_state.get("succeeded")):
reference = str(last_state.get("reference") or "").strip()
return {
"reference": reference,
"success_evidence": _capture_success_page_evidence(
page,
kind="dsv_history_green_dom",
selector=selector,
filename=filename,
reference=reference or None,
),
}
time.sleep(1)
raise RuntimeError(
"DSV upload History did not confirm a green success status "
f"for {filename!r}; last_state={last_state}"
)
def _upload_shipment_with_browser(
file_path: Path, *, connector_type: str = "", dsv_entry_url: str = ""
) -> dict[str, Any]:
"""
在受控配置下执行货代 Excel 上传,并以页面成功证据作为回调成功前提。
触发条件:仅当 Worker 非 mock、上传与最终提交两个开关均为 true,且 URL、文件
控件、提交控件和成功标识均已配置时执行。未满足任何条件时抛异常并回调失败,绝不
猜测站点、选择器或提交按钮。
Args:
file_path: 已由 HXOPS 写入共享上传队列且存在的 Excel 文件。
Returns:
dict: reference(可空)与 success_evidence(DSV 绿 DOM 或通用 success 选择器)。
"""
if not _upload_worker_enabled():
raise RuntimeError("upload RPA is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation")
if not _upload_submit_confirmed():
raise RuntimeError("upload RPA submit is not confirmed; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=true after dry run")
normalized_connector = _worker_connector_type({"connector_type": connector_type}) if connector_type else ""
upload_url = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL")
file_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR")
submit_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR")
success_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR")
if normalized_connector == "crane_footprint":
raise RuntimeError("CRANE upload RPA is not implemented because its upload path is unverified")
if normalized_connector == "dsv360":
dsv_entry_url = dsv_entry_url or _env("SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL")
if not dsv_entry_url:
raise RuntimeError("DSV upload RPA requires a reviewed DSV upload entry URL")
# DSV WMS Upload Tool 已在真实页面确认 Browse 与 Process File 的 DOM。
file_selector = file_selector or "#file2"
submit_selector = submit_selector or 'button.upload-button:has-text("Process File")'
elif not upload_url:
raise RuntimeError("upload RPA configuration requires a reviewed upload URL")
if not all((file_selector, submit_selector)) or (
normalized_connector != "dsv360" and not success_selector
):
raise RuntimeError("upload RPA configuration requires file, submit and success selectors")
playwright = context = runtime_profile_dir = None
failed = False
try:
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
if normalized_connector == "dsv360":
_navigate_dsv_to_upload_tool(page, dsv_entry_url)
else:
page.goto(upload_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
file_input = page.locator(file_selector).first
file_input.set_input_files(str(file_path), timeout=_browser_timeout_ms())
submit = page.locator(submit_selector).first
submit.click(timeout=_browser_timeout_ms())
if normalized_connector == "dsv360":
return _wait_for_dsv_upload_history_receipt(page, file_path.name)
page.locator(success_selector).first.wait_for(state="visible", timeout=_browser_timeout_ms())
receipt_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR")
reference = ''
if receipt_selector:
receipt = page.locator(receipt_selector).first
reference = str(receipt.text_content(timeout=_browser_timeout_ms()) or "").strip()
return {
"reference": reference,
"success_evidence": _capture_success_page_evidence(
page,
kind="configured_success_selector",
selector=success_selector,
filename=file_path.name,
reference=reference or None,
),
}
except Exception:
failed = True
raise
finally:
if failed and _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true":
print("[browser] keeping browser open after upload error because SHIPPING_NOTICE_RPA_WORKER_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_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()
attempt_id = body.get("attempt_id")
callback_id = str(body.get("callback_id") or "").strip()
failed_dir = trigger_path.parent / "failed"
if not task_no:
trigger_path.unlink(missing_ok=True)
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
if not file_path or not Path(file_path).is_file():
try:
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"success": False,
"error_message": f"queue file missing: {file_path or '<empty>'}",
})
trigger_path.unlink(missing_ok=True)
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
return
try:
upload_result: dict[str, Any]
if mock:
from datetime import datetime, timezone
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
observed_at = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + 'Z'
mock_snippet = f'<mock-upload task="{task_no}"/>'
import hashlib
upload_result = {
"reference": ref,
"success_evidence": {
"kind": "green_success_dom",
"selector": "#mock-success",
"filename": Path(file_path).name,
"reference": ref,
"observed_at": observed_at,
"page_url": "about:blank",
"dom_snippet": mock_snippet,
"dom_sha256": hashlib.sha256(mock_snippet.encode("utf-8")).hexdigest(),
},
}
else:
connector_type = str(body.get("inventory_connector_type") or "").strip()
dsv_entry_url = str(body.get("inventory_entry_url") or "").strip()
# 兼容旧 trigger;新 trigger 才携带站点路由信息并进入专用 Driver。
raw = (
_upload_shipment_with_browser(
Path(file_path), connector_type=connector_type, dsv_entry_url=dsv_entry_url
)
if connector_type
else _upload_shipment_with_browser(Path(file_path))
)
upload_result = raw if isinstance(raw, dict) else {"reference": str(raw or ''), "success_evidence": None}
ref = str(upload_result.get("reference") or "").strip()
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"success": True,
"freight_ref_no": ref or None,
"success_evidence": upload_result.get("success_evidence"),
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[upload] {'mock' if mock else 'browser'} upload done for {task_no} ref={ref or '-'}")
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"success": False,
"error_message": str(exc)[:500],
})
_move_trigger(trigger_path, processed_dir, "processed after upload failure")
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
freight_rpa_heartbeat.set_worker_runtime_status("busy")
try:
handler(path, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
finally:
freight_rpa_heartbeat.set_worker_runtime_status("idle")
def main() -> None:
_configure_file_logging()
drop_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
inv_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
upload_queue_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
upload_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR")
poll = max(1, int(_env("SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS", "3") or "3"))
inv_processed = inv_trigger_dir / "processed"
upload_processed = upload_trigger_dir / "processed"
api_base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
heartbeat_seconds = max(
15,
int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"),
)
auth_source, masked_auth = _resolve_tool_api_auth_debug()
print("[freight_rpa_worker] started")
print(f" mock={_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')}")
print(f" api_base={api_base}")
print(f" heartbeat_seconds={heartbeat_seconds}")
print(f" auth_source={auth_source}")
print(f" auth_key={masked_auth or 'missing'}")
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}")
last_heartbeat_mono = 0.0
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=last_heartbeat_mono,
force=True,
)
while True:
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=last_heartbeat_mono,
)
_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()