2170 lines
95 KiB
Python
2170 lines
95 KiB
Python
"""
|
||
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_DSV_SESSION_REUSE=false
|
||
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
|
||
# 上传采用“用连接 login_url 登录 → 直接访问 upload_entry_url 上传页”;文件选择、提交动作与
|
||
# 结果判定由受控 DsvUploadAdapter / CraneUploadAdapter 固化,禁止后端注入任意脚本或 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")
|
||
|
||
|
||
def _close_batch_browser_resources(context: Any, playwright: Any, runtime_profile_dir: Path | None) -> None:
|
||
"""在正常完成或 Ctrl+C 中断后依序释放批量 RPA 浏览器资源。"""
|
||
try:
|
||
if context is not None:
|
||
context.close()
|
||
except BaseException as exc:
|
||
print(f"[browser] context close interrupted: {exc}", file=sys.stderr)
|
||
try:
|
||
if playwright is not None:
|
||
playwright.stop()
|
||
except BaseException as exc:
|
||
print(f"[browser] playwright stop interrupted: {exc}", file=sys.stderr)
|
||
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
|
||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||
|
||
|
||
_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 或缺少库存报表关键表头。
|
||
"""
|
||
started_at = time.monotonic()
|
||
try:
|
||
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()
|
||
except Exception:
|
||
print(
|
||
"[inventory-artifact] stage=excel_structure_validation status=error "
|
||
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
|
||
)
|
||
raise
|
||
print(
|
||
"[inventory-artifact] stage=excel_structure_validation status=end "
|
||
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
|
||
)
|
||
|
||
|
||
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)
|
||
save_started_at = time.monotonic()
|
||
download.save_as(str(dest))
|
||
print(
|
||
"[inventory-artifact] stage=download_save status=end "
|
||
f"elapsedMs={int((time.monotonic() - save_started_at) * 1000)} path={dest.name!r}"
|
||
)
|
||
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 _dsv_session_reuse_enabled() -> bool:
|
||
"""返回是否显式允许 DSV 库存导出复用受控浏览器会话。"""
|
||
return _env("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "false").lower() == "true"
|
||
|
||
|
||
def _dsv_session_profile_dir() -> Path:
|
||
"""返回 DSV 专用持久 profile;该目录不得与其他货代任务共用。"""
|
||
return _browser_profile_root() / "dsv360_session"
|
||
|
||
|
||
def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
|
||
"""
|
||
判断关闭浏览器后是否可删除本次 profile。
|
||
|
||
核心逻辑:仅显式开启的 DSV 固定会话目录需要跨任务保留;其余目录都是
|
||
`_open_browser` 创建的一次性运行目录,应由调用方清理。
|
||
|
||
Args:
|
||
profile_dir: 已传给 Playwright persistent context 的 profile 目录。
|
||
|
||
Returns:
|
||
bool: 为 True 时调用方可安全删除该目录。
|
||
"""
|
||
return profile_dir.resolve() != _dsv_session_profile_dir().resolve()
|
||
|
||
|
||
def _open_browser(download_dir: Path, *, reuse_dsv_session: bool = False):
|
||
"""
|
||
打开用于库存 RPA 导出的浏览器上下文。
|
||
|
||
核心逻辑:默认创建一次性的运行时 profile 子目录。仅当调用方明确为 DSV
|
||
库存导出请求会话复用,且 `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=true` 时,
|
||
才使用独立的固定 `dsv360_session` 目录;其他货代任务绝不复用该会话。
|
||
|
||
Args:
|
||
download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。
|
||
reuse_dsv_session: 仅 DSV 库存调用可传 True;环境开关关闭时仍使用临时目录。
|
||
|
||
Returns:
|
||
tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir`
|
||
为本次执行使用的 profile 目录。调用方必须用
|
||
`_should_cleanup_browser_profile` 决定是否清理。
|
||
"""
|
||
sync_playwright, _timeout = _require_playwright()
|
||
playwright = sync_playwright().start()
|
||
profile_root = _browser_profile_root()
|
||
profile_root.mkdir(parents=True, exist_ok=True)
|
||
use_reused_dsv_session = reuse_dsv_session and _dsv_session_reuse_enabled()
|
||
runtime_profile_dir = (
|
||
_dsv_session_profile_dir()
|
||
if use_reused_dsv_session
|
||
else Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||
)
|
||
runtime_profile_dir.mkdir(parents=True, exist_ok=True)
|
||
print(
|
||
"[browser] profile_mode="
|
||
f"{'dsv_session_reuse' if use_reused_dsv_session else 'temporary'}"
|
||
)
|
||
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,
|
||
reuse_dsv_session=connector_type == "dsv360",
|
||
)
|
||
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 and _should_cleanup_browser_profile(runtime_profile_dir):
|
||
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 _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[str, Any]]) -> None:
|
||
"""
|
||
定时排程批量导出每完成一个站点即上报累计进度,后端实时回写排程 run 笔数。
|
||
|
||
核心逻辑:仅 scheduled 触发且携带 schedule_run_id 时上报,按需单票不受影响;
|
||
best-effort,上报失败不影响导出与最终回调;最终笔数以 inventory-batch-ready 为准。
|
||
"""
|
||
if str(body.get("trigger_type") or "").strip() != "scheduled":
|
||
return
|
||
schedule_run_id = body.get("schedule_run_id")
|
||
if schedule_run_id is None:
|
||
return
|
||
summary = _summarize_inventory_batch_results(results)
|
||
try:
|
||
_post_callback("/api/shipping-notice/rpa/inventory-batch-progress", {
|
||
"schema_version": "shipping_inventory_rpa.v2",
|
||
"callback_id": body.get("callback_id"),
|
||
"batch_run_no": run_no,
|
||
"run_no": run_no,
|
||
"schedule_run_id": schedule_run_id,
|
||
"success_count": summary["success_count"],
|
||
"skipped_count": summary["skipped_count"],
|
||
"failed_count": summary["failed_count"],
|
||
})
|
||
except Exception as exc:
|
||
print(f"[inventory-batch] progress callback failed {run_no}: {exc}", file=sys.stderr)
|
||
|
||
|
||
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")
|
||
# 定时排程批量触发是按 run 计价的:只携带 run_no/schedule_run_id,没有逐源
|
||
# Attempt/Gate 身份。身份校验按模式取值:scheduled 只强制信封与站点分发字段,
|
||
# 业务终态由后端按 schedule_run_id + DB 配置校验;其余模式保持逐源身份 fail-closed。
|
||
is_scheduled_batch = str(body.get("trigger_type") or "").strip() == "scheduled"
|
||
source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
|
||
if is_scheduled_batch:
|
||
source_required -= {
|
||
"task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id",
|
||
"execution_id", "gate_id", "callback_id", "expected_warehouse_id",
|
||
}
|
||
if not is_scheduled_batch and (
|
||
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
|
||
# Crane 的 Warehouse 由导出 Excel 中 reservation_id + part_number 解析,
|
||
# trigger 阶段不存在固定预期库位;其余来源仍必须绑定预期库位。
|
||
requires_expected_warehouse = str(
|
||
source.get("worker_connector_type") or source.get("connector_type") or ""
|
||
).strip().lower() not in {"crane", "crane_footprint"}
|
||
identity_errors.extend(
|
||
f"inventory_sources[{index}].{key}"
|
||
for key in source_required
|
||
if (key != "expected_warehouse_id" or requires_expected_warehouse)
|
||
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
|
||
)
|
||
if identity_errors:
|
||
try:
|
||
# 即使 trigger 身份不完整,也保留每个 source 已携带的身份片段;
|
||
# 后端据此将可定位的 Attempt/Gate 立即收口,不能等轮询超时。
|
||
rejected_results = [
|
||
{
|
||
**{
|
||
key: source.get(key)
|
||
for key in (
|
||
"callback_id", "task_no", "source_code", "attempt_no",
|
||
"source_run_no", "lease_token", "candidate_set_id",
|
||
"execution_id", "gate_id", "expected_warehouse_id",
|
||
)
|
||
},
|
||
"status": "failed",
|
||
"success": False,
|
||
"error_code": "trigger_identity_invalid",
|
||
"error_message": "RPA trigger identity is invalid.",
|
||
}
|
||
for source in sources
|
||
if isinstance(source, dict)
|
||
]
|
||
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
|
||
"schema_version": "shipping_inventory_rpa.v2",
|
||
"callback_id": body.get("callback_id"),
|
||
"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": rejected_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]] = []
|
||
|
||
def record_result(item: dict[str, Any]) -> None:
|
||
"""记录单站点结果并即时上报累计进度(仅定时排程会真正上报)。"""
|
||
results.append(item)
|
||
_emit_batch_progress(body, run_no, results)
|
||
|
||
# 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)
|
||
record_result({
|
||
"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,
|
||
reuse_dsv_session=site == "dsv360",
|
||
)
|
||
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":
|
||
# [STEP 3] 批内同一 Profile 只登录一次:首源完整登录,后续源复用当前 tab
|
||
# 的登录态——同导航走 _return_to_dsv_report_parameters 复用参数页,
|
||
# 导航不同走 _reset_dsv_export_entry(goto entry + 会话检测,不重复 OAuth)。
|
||
# 曾因"每源新开空白页 + 写死 index=0"导致每源重复走 SSO 重定向链
|
||
# (每源 2-2.5 分钟,且偶发 OAuth 空白页单源失败),现已移除。
|
||
# 页面串站状态由整页/帧重载兜底,无需隔离页。
|
||
previous_source = site_sources[index - 1] if index > 0 else None
|
||
try:
|
||
# 返回 True 表示参数页已就绪:后续跳过菜单导航直接填参/导出。
|
||
skip_navigation = bool(
|
||
_prepare_dsv_batch_export_step(page, entry_url, previous_source, source, index=index)
|
||
)
|
||
except Exception as exc:
|
||
# 会话复用的安全网:登录/会话类偶发异常(SSO/OAuth 链、
|
||
# “密码升级”弹窗遮挡、字段未渲染)时,新开干净页面重试一次完整登录;
|
||
# 凭据校验类(invalid/verification)不重试,直接失败。
|
||
message = str(exc).lower()
|
||
login_related = any(token in message for token in ("login", "session", "oauth"))
|
||
credential_mismatch = any(token in message for token in ("invalid", "verification"))
|
||
if not login_related or credential_mismatch:
|
||
raise
|
||
print(
|
||
f"[inventory-batch] dsv360 session prepare failed for {code}, retry with clean page: {exc}",
|
||
file=sys.stderr,
|
||
)
|
||
page = _open_clean_batch_page(context, page)
|
||
skip_navigation = bool(
|
||
_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)
|
||
record_result({"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:
|
||
record_result({"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:
|
||
record_result({"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:
|
||
record_result({"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:
|
||
_close_batch_browser_resources(context, playwright, runtime_profile_dir)
|
||
|
||
# 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}"
|
||
)
|
||
|
||
|
||
class _UploadResultUnknownError(RuntimeError):
|
||
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
|
||
|
||
|
||
class _BaseUploadAdapter:
|
||
"""受控上传适配器基类:由连接级 upload_config 提供页面参数,代码负责浏览器动作与安全边界。
|
||
|
||
设计约束:禁止把任意脚本/URL 模板/Cookie/任意浏览器动作开放到后台配置;config 只决定
|
||
“该连接使用哪个已支持的受控流程及其页面参数”。Adapter 负责登录、打开 entry 页、选择 Excel、
|
||
提交与结果判定。Worker 不再根据环境变量拼接 DSV/Crane 页面动作。
|
||
"""
|
||
|
||
def __init__(self, *, file_path: Path, upload_config: dict[str, Any]):
|
||
self.file_path = file_path
|
||
self.config = upload_config or {}
|
||
|
||
def _timeout_ms(self) -> int:
|
||
try:
|
||
seconds = int(self.config.get('timeout_seconds') or 120)
|
||
except (TypeError, ValueError):
|
||
seconds = 120
|
||
return max(1, seconds) * 1000
|
||
|
||
def _require(self, *fields: str) -> None:
|
||
missing = [field for field in fields if not str(self.config.get(field) or '').strip()]
|
||
if missing:
|
||
raise RuntimeError(f"upload config missing required field(s): {', '.join(missing)}")
|
||
|
||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||
raise NotImplementedError
|
||
|
||
|
||
class DsvUploadAdapter(_BaseUploadAdapter):
|
||
"""DSV 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → History 绿色判定。"""
|
||
|
||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||
self._require('entry_url', 'file_input_selector')
|
||
_ensure_dsv_session(page, login_url)
|
||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
|
||
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
|
||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||
submit_selector = str(self.config.get('submit_selector') or '').strip()
|
||
if not submit_selector:
|
||
raise RuntimeError('DSV click_submit upload requires submit_selector')
|
||
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
|
||
try:
|
||
return _wait_for_dsv_upload_history_receipt(page, self.file_path.name)
|
||
except RuntimeError as exc:
|
||
# 文件已选择/可能已提交但未取得可核验成功证据 → unknown,转人工。
|
||
raise _UploadResultUnknownError(str(exc)) from exc
|
||
|
||
|
||
class CraneUploadAdapter(_BaseUploadAdapter):
|
||
"""Crane 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → 结果判定。
|
||
|
||
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
|
||
"""
|
||
|
||
# SweetAlert2 上传失败弹窗识别(受控 Adapter 内置,禁止开放到 upload_config):Crane 上传
|
||
# 失败会弹 swal2-icon-error(如 “The Customer account [...] was not found” / “Warehouse [...] not found”),
|
||
# 必须读取原因并点击 OK 关闭,否则页面被模态框拦截,无法继续上传下一个文件。
|
||
_ERROR_DIALOG_SELECTORS = (
|
||
'.swal2-popup.swal2-icon-error',
|
||
'.swal2-icon.swal2-error',
|
||
'.swal2-x-mark',
|
||
)
|
||
_ERROR_MESSAGE_SELECTORS = (
|
||
'.swal2-html-container',
|
||
'.swal2-content',
|
||
'.swal2-title',
|
||
)
|
||
_ERROR_OK_SELECTOR = '.swal2-confirm'
|
||
|
||
# SweetAlert2 上传成功弹窗识别(绿色勾):Crane 上传成功同样以 swal2 弹窗反馈。
|
||
# 即便 upload_config.result_selector 配置错误,也能据此确认成功,避免误报 unknown。
|
||
_SUCCESS_DIALOG_SELECTORS = (
|
||
'.swal2-popup.swal2-icon-success',
|
||
'.swal2-icon.swal2-success',
|
||
)
|
||
|
||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||
self._require('entry_url', 'file_input_selector', 'submit_mode')
|
||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||
self._require('submit_selector')
|
||
self._require_result_fields()
|
||
_ensure_crane_session(page, login_url)
|
||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||
page.locator(str(self.config['file_input_selector'])).first.set_input_files(
|
||
str(self.file_path), timeout=self._timeout_ms(),
|
||
)
|
||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||
page.locator(str(self.config['submit_selector'])).first.click(timeout=self._timeout_ms())
|
||
return self._resolve_result(page)
|
||
|
||
def _require_result_fields(self) -> None:
|
||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||
if result_mode == 'page_notice':
|
||
if not str(self.config.get('result_selector') or '').strip() or not self.config.get('success_texts'):
|
||
raise RuntimeError('Crane page_notice upload requires result_selector and success_texts')
|
||
elif result_mode == 'history_record' and not str(self.config.get('result_selector') or '').strip():
|
||
raise RuntimeError('Crane history_record upload requires result_selector')
|
||
else:
|
||
raise RuntimeError('Crane upload requires a supported result_mode')
|
||
|
||
def _take_error_popup_reason(self, page: Any) -> str | None:
|
||
"""检测 Crane 上传失败的 SweetAlert2 错误弹窗。
|
||
|
||
命中时读取失败原因(swal2-html-container,回退 swal2-content / swal2-title)并点击 OK 关闭,
|
||
关闭后返回原因文本;未出现错误弹窗时返回 None。点击 OK 是继续上传下一个文件的前提。
|
||
"""
|
||
try:
|
||
popup = None
|
||
for selector in self._ERROR_DIALOG_SELECTORS:
|
||
loc = page.locator(selector).first
|
||
if loc.count() > 0:
|
||
try:
|
||
if loc.is_visible():
|
||
popup = loc
|
||
break
|
||
except Exception:
|
||
continue
|
||
if popup is None:
|
||
return None
|
||
reason = ''
|
||
# 优先逐条取 html-container 内的错误行(.my-1),多错误用分号连接;
|
||
# 无则回退到容器整体文本,再回退标题。
|
||
try:
|
||
items = [
|
||
str(text or '').strip()
|
||
for text in page.locator('.swal2-html-container .my-1').all_text_contents()
|
||
if str(text or '').strip()
|
||
]
|
||
if items:
|
||
reason = '; '.join(items)
|
||
except Exception:
|
||
items = []
|
||
if not reason:
|
||
for selector in self._ERROR_MESSAGE_SELECTORS:
|
||
try:
|
||
text = str(page.locator(selector).first.text_content(timeout=1000) or '').strip()
|
||
if text:
|
||
reason = text
|
||
break
|
||
except Exception:
|
||
continue
|
||
ok = page.locator(self._ERROR_OK_SELECTOR).first
|
||
try:
|
||
if ok.count() > 0:
|
||
ok.click(timeout=2000)
|
||
except Exception:
|
||
pass
|
||
return reason or 'Crane upload rejected'
|
||
except Exception:
|
||
return None
|
||
|
||
def _take_success_popup(self, page: Any) -> str | None:
|
||
"""检测 Crane 上传成功的 SweetAlert2 成功弹窗(绿色勾),返回命中的选择器;未出现返回 None。"""
|
||
try:
|
||
for selector in self._SUCCESS_DIALOG_SELECTORS:
|
||
loc = page.locator(selector).first
|
||
if loc.count() > 0:
|
||
try:
|
||
if loc.is_visible():
|
||
return selector
|
||
except Exception:
|
||
continue
|
||
return None
|
||
except Exception:
|
||
return None
|
||
|
||
def _raise_if_crane_error(self, page: Any) -> None:
|
||
"""若出现 Crane 上传失败弹窗:读取原因、点击 OK 关闭后抛出失败,交由调用方上报真实原因。"""
|
||
reason = self._take_error_popup_reason(page)
|
||
if reason:
|
||
raise RuntimeError(f"Crane upload rejected: {reason}")
|
||
|
||
def _success_from_popup(self, page: Any, filename: str) -> dict[str, Any] | None:
|
||
"""返回成功弹窗的 success_evidence;未命中成功弹窗时返回 None。"""
|
||
selector = self._take_success_popup(page)
|
||
if selector:
|
||
return {
|
||
'reference': '',
|
||
'success_evidence': _capture_success_page_evidence(
|
||
page, kind='crane_page_notice', selector=selector,
|
||
filename=filename, reference=None,
|
||
),
|
||
}
|
||
return None
|
||
|
||
def _resolve_result(self, page: Any) -> dict[str, Any]:
|
||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||
filename = self.file_path.name
|
||
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
|
||
self._raise_if_crane_error(page)
|
||
success = self._success_from_popup(page, filename)
|
||
if success:
|
||
return success
|
||
if result_mode == 'history_record':
|
||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||
try:
|
||
loc = page.locator(result_selector).first
|
||
loc.wait_for(state='visible', timeout=self._timeout_ms())
|
||
except Exception as exc:
|
||
# 判定期内可能出现失败弹窗(如 Customer/Warehouse 未找到);先读取并关闭,
|
||
# 以真实原因上报失败;否则仍按“结果未知”转人工。
|
||
self._raise_if_crane_error(page)
|
||
success = self._success_from_popup(page, filename)
|
||
if success:
|
||
return success
|
||
raise _UploadResultUnknownError(
|
||
f"无法判断上传是否成功/失败:{filename!r} 历史结果未确认({exc});"
|
||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||
) from exc
|
||
try:
|
||
reference = str(loc.text_content(timeout=self._timeout_ms()) or '').strip()
|
||
except Exception:
|
||
reference = ''
|
||
return {
|
||
'reference': reference,
|
||
'success_evidence': _capture_success_page_evidence(
|
||
page, kind='crane_history_record', selector=result_selector,
|
||
filename=filename, reference=reference or None,
|
||
),
|
||
}
|
||
# page_notice:要求 result_selector 可见且内容命中任一 success_texts。
|
||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||
success_texts = [str(t).strip() for t in (self.config.get('success_texts') or []) if str(t).strip()]
|
||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||
last_snippet = ''
|
||
while time.monotonic() < deadline:
|
||
# 上传失败时 Crane 会先弹错误窗而非成功提示;命中则读取原因、点 OK 关闭并上报失败。
|
||
self._raise_if_crane_error(page)
|
||
# 成功也可能以 SweetAlert2 成功弹窗反馈;优先于配置 result_selector 判定,避免配置错误误报 unknown。
|
||
success = self._success_from_popup(page, filename)
|
||
if success:
|
||
return success
|
||
try:
|
||
loc = page.locator(result_selector).first
|
||
if loc.count() > 0 and loc.is_visible():
|
||
snippet = str(loc.text_content(timeout=1000) or '').strip()
|
||
last_snippet = snippet
|
||
if any(text in snippet for text in success_texts):
|
||
return {
|
||
'reference': '',
|
||
'success_evidence': _capture_success_page_evidence(
|
||
page, kind='crane_page_notice', selector=result_selector,
|
||
filename=filename, reference=None,
|
||
),
|
||
}
|
||
except Exception:
|
||
pass
|
||
time.sleep(1)
|
||
raise _UploadResultUnknownError(
|
||
f"无法判断上传是否成功/失败:{filename!r} 结果未确认(last_snippet={last_snippet!r});"
|
||
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
|
||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||
)
|
||
|
||
|
||
def _upload_shipment_with_browser(
|
||
file_path: Path, *, connector_type: str = "", upload_source: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
在受控 Adapter 下执行货代 Excel 上传,并以可核验证据作为回调成功前提。
|
||
|
||
触发条件:连接 upload_config.enabled=true(代表管理员已审核该连接的上传行为),且 Worker 上传与
|
||
最终提交两项开关均为 true。未满足/未审核时抛异常并回调失败/未知,绝不猜测站点、选择器或
|
||
提交按钮,也不允许后台配置注入任意脚本或浏览器动作。
|
||
|
||
Args:
|
||
file_path: 已由 HXOPS 写入共享上传队列且存在的 Excel 文件。
|
||
connector_type: 业务连接类型(dbs / crane),决定使用哪个受控 Adapter。
|
||
upload_source: 该连接上传快照(含 login_url / credential_envelope / upload_config_json)。
|
||
|
||
Returns:
|
||
dict: reference(可空)与 success_evidence。
|
||
"""
|
||
upload_source = upload_source or {}
|
||
upload_config = upload_source.get('upload_config_json')
|
||
if not isinstance(upload_config, dict) or not upload_config.get('enabled'):
|
||
raise RuntimeError(
|
||
"upload RPA is not enabled for this connection; enable it in '系统连接' after validation"
|
||
)
|
||
if not _upload_worker_enabled():
|
||
raise RuntimeError("upload RPA worker 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")
|
||
business = str(connector_type or '').strip().lower()
|
||
if business not in {'dbs', 'crane'} and connector_type:
|
||
business = {'dsv360': 'dbs', 'crane_footprint': 'crane'}.get(
|
||
_worker_connector_type({"connector_type": connector_type}), business,
|
||
)
|
||
if business == 'dbs':
|
||
adapter = DsvUploadAdapter(file_path=file_path, upload_config=upload_config)
|
||
elif business == 'crane':
|
||
adapter = CraneUploadAdapter(file_path=file_path, upload_config=upload_config)
|
||
else:
|
||
raise RuntimeError(f'unsupported upload connector_type: {connector_type or "<empty>"}')
|
||
login_url = str(upload_source.get('login_url') or '').strip()
|
||
|
||
playwright = context = runtime_profile_dir = None
|
||
failed = False
|
||
try:
|
||
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
|
||
with _profile_credentials(upload_source):
|
||
return adapter.run(page, login_url=login_url)
|
||
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,
|
||
"result": "failed",
|
||
"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("connector_type") or "").strip()
|
||
upload_source = {
|
||
"connector_type": connector_type,
|
||
"login_url": str(body.get("login_url") or "").strip(),
|
||
"credential_envelope": body.get("credential_envelope"),
|
||
"upload_config_json": body.get("upload_config"),
|
||
}
|
||
raw = _upload_shipment_with_browser(
|
||
Path(file_path), connector_type=connector_type, upload_source=upload_source,
|
||
)
|
||
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,
|
||
"result": "success",
|
||
"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,
|
||
"result": "unknown" if isinstance(exc, _UploadResultUnknownError) else "failed",
|
||
"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}")
|
||
|
||
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
|
||
freight_rpa_heartbeat.maybe_send_heartbeat(
|
||
trigger_dir=inv_trigger_dir,
|
||
drop_dir=drop_dir,
|
||
last_sent_mono=0.0,
|
||
force=True,
|
||
)
|
||
# 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环,
|
||
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
|
||
freight_rpa_heartbeat.start_heartbeat_loop(
|
||
trigger_dir=inv_trigger_dir,
|
||
drop_dir=drop_dir,
|
||
interval_seconds=heartbeat_seconds,
|
||
)
|
||
|
||
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()
|