feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议
This commit is contained in:
1 parent
46eb63f5bb
commit
e9bdd81f1a
320 files changed
+28361
-10487
No files matched your search
+150
-155
@@ -10,27 +10,28 @@ Usage:
|
||||
Required env (same as backend):
|
||||
HXOPS_API_BASE e.g. http://127.0.0.1:5052
|
||||
SHIPPING_NOTICE_TOOL_API_KEY
|
||||
FREIGHT_INVENTORY_DROP_DIR
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR
|
||||
FREIGHT_UPLOAD_QUEUE_DIR
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR
|
||||
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:
|
||||
FREIGHT_RPA_MOCK=false
|
||||
FREIGHT_RPA_POLL_SECONDS=3
|
||||
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
FREIGHT_RPA_HEADLESS=false
|
||||
FREIGHT_RPA_BROWSER_CHANNEL=msedge
|
||||
FREIGHT_RPA_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
|
||||
FREIGHT_RPA_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
|
||||
FREIGHT_RPA_LOG_MAX_BYTES=10485760
|
||||
FREIGHT_RPA_LOG_BACKUP_COUNT=5
|
||||
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
|
||||
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
|
||||
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
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -43,6 +44,8 @@ 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:
|
||||
@@ -105,29 +108,6 @@ except ImportError:
|
||||
Workbook = None # type: ignore
|
||||
|
||||
|
||||
def _env(name: str, default: str = "") -> str:
|
||||
"""
|
||||
读取 RPA 环境变量,并兼容 .env 中常见的外层单双引号写法。
|
||||
|
||||
核心逻辑:先读取原始环境变量并去除首尾空白;若值整体被同种引号包裹,
|
||||
再剥离最外层一对引号,避免账号密码把引号一并输入到第三方登录页。
|
||||
|
||||
Args:
|
||||
name: 环境变量名。
|
||||
default: 未设置时的默认值。
|
||||
|
||||
Returns:
|
||||
str: 去除空白与外层成对引号后的环境变量值。
|
||||
"""
|
||||
value = str(os.getenv(name) or default).strip()
|
||||
if len(value) >= 2 and (
|
||||
(value.startswith('"') and value.endswith('"'))
|
||||
or (value.startswith("'") and value.endswith("'"))
|
||||
):
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def _log_line_timestamp() -> str:
|
||||
"""
|
||||
生成 worker 日志行首时间戳(本地时区)。
|
||||
@@ -186,7 +166,7 @@ class _TeeStream:
|
||||
|
||||
def _configure_file_logging() -> Path | None:
|
||||
"""
|
||||
按 FREIGHT_RPA_LOG_FILE 启用 worker 文件日志。
|
||||
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
|
||||
@@ -195,7 +175,7 @@ def _configure_file_logging() -> Path | None:
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
"""
|
||||
raw = _env("FREIGHT_RPA_LOG_FILE")
|
||||
raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE")
|
||||
if not raw:
|
||||
return None
|
||||
path = Path(raw).expanduser()
|
||||
@@ -232,12 +212,12 @@ def _rotate_log_file_if_needed(path: Path) -> None:
|
||||
"""
|
||||
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
|
||||
|
||||
核心逻辑:当 `FREIGHT_RPA_LOG_FILE` 已存在且大小达到 `FREIGHT_RPA_LOG_MAX_BYTES`
|
||||
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `FREIGHT_RPA_LOG_BACKUP_COUNT`
|
||||
的旧文件会被删除。`FREIGHT_RPA_LOG_MAX_BYTES<=0` 时禁用轮转。
|
||||
核心逻辑:当 `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("FREIGHT_RPA_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
backup_count = _log_int_env("FREIGHT_RPA_LOG_BACKUP_COUNT", 5, min_value=0)
|
||||
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:
|
||||
@@ -341,14 +321,14 @@ def _browser_profile_root() -> Path:
|
||||
"""
|
||||
default = _backend_dir() / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
legacy_default = _backend_dir() / "data" / "freight_rpa" / "browser_profile"
|
||||
profile = _env("FREIGHT_RPA_BROWSER_PROFILE_DIR")
|
||||
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] FREIGHT_RPA_BROWSER_PROFILE_DIR points to legacy data/freight_rpa; "
|
||||
"[warn] SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR points to legacy data/freight_rpa; "
|
||||
f"using {default} instead"
|
||||
)
|
||||
return default.resolve()
|
||||
@@ -441,7 +421,7 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
|
||||
|
||||
|
||||
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
|
||||
sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY")
|
||||
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)
|
||||
@@ -570,17 +550,77 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic
|
||||
def _validate_inventory_source_for_rpa(source: dict[str, Any]) -> None:
|
||||
"""
|
||||
校验单个库存 RPA source 的最小定位条件。
|
||||
核心逻辑:DSV 必须有 site_id;Crane 只需要 connector_type 即可分发,warehouse id 由库存 Excel 结果决定。
|
||||
核心逻辑:业务 connector_type 为 dbs/crane,driver 类型由 worker_connector_type 指定;
|
||||
DBS 固定仓以 warehouse_id 作为导出筛选,Crane 多仓导出不要求预置 Warehouse。
|
||||
"""
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
connector_type = _worker_connector_type(source)
|
||||
source_code = str(source.get("source_code") or "").strip() or "UNKNOWN"
|
||||
site_id = str(source.get("site_id") or "").strip()
|
||||
warehouse_id = str(source.get("warehouse_id") or "").strip()
|
||||
if connector_type not in {"dsv360", "crane_footprint"}:
|
||||
raise RuntimeError(
|
||||
f"{source_code}: connector_type must be dsv360 or crane_footprint"
|
||||
f"{source_code}: worker connector_type must be dsv360 or crane_footprint"
|
||||
)
|
||||
if connector_type == "dsv360" and not site_id:
|
||||
raise RuntimeError(f"{source_code}: site_id is required for dsv360")
|
||||
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
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
|
||||
@@ -698,7 +738,7 @@ def _open_browser(download_dir: Path):
|
||||
"""
|
||||
打开用于库存 RPA 导出的浏览器上下文。
|
||||
|
||||
核心逻辑:无论正式执行还是测试执行,都基于 `FREIGHT_RPA_BROWSER_PROFILE_DIR`
|
||||
核心逻辑:无论正式执行还是测试执行,都基于 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`
|
||||
创建一次性的运行时 profile 子目录,再交给 Playwright 的 persistent context。
|
||||
这样既能保留 Chrome/Edge 可执行文件与下载目录配置,又能避免复用任何已有登录态。
|
||||
|
||||
@@ -714,9 +754,9 @@ def _open_browser(download_dir: Path):
|
||||
profile_root = _browser_profile_root()
|
||||
profile_root.mkdir(parents=True, exist_ok=True)
|
||||
runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||||
headless = _env("FREIGHT_RPA_HEADLESS", "false").lower() == "true"
|
||||
channel = _env("FREIGHT_RPA_BROWSER_CHANNEL")
|
||||
executable_path = _env("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH")
|
||||
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,
|
||||
@@ -742,7 +782,7 @@ def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[
|
||||
|
||||
def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
"""单票 trigger 的 Crane 导出;与批量共用 session + export 函数。"""
|
||||
entry_url = str(source.get("entry_url") or "").strip()
|
||||
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)
|
||||
@@ -754,28 +794,29 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
source = trigger.get("rpa_inventory_source")
|
||||
if not isinstance(source, dict):
|
||||
raise RuntimeError("inventory trigger missing rpa_inventory_source")
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
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("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
|
||||
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)
|
||||
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}")
|
||||
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 FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true")
|
||||
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:
|
||||
@@ -857,7 +898,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true"
|
||||
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
mode = "mock" if mock else "browser"
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
@@ -869,7 +910,6 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
out_file = _write_sample_inventory(drop_dir, task_stub)
|
||||
results.append({
|
||||
"source_code": source.get("source_code"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"status": "success",
|
||||
"success": True,
|
||||
@@ -877,89 +917,44 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"task_no": task_no or None,
|
||||
})
|
||||
else:
|
||||
grouped: dict[str, list[dict[str, Any]]] = {}
|
||||
for source in sources:
|
||||
if not isinstance(source, dict):
|
||||
continue
|
||||
site = str(source.get("connector_type") or "").strip()
|
||||
grouped.setdefault(site, []).append(source)
|
||||
# 一个 Profile 对应一个独立浏览器登录态;同 Driver 的不同账号绝不能共用 session。
|
||||
grouped = _group_batch_sources_by_profile(sources)
|
||||
|
||||
for site, site_sources in grouped.items():
|
||||
entry_url = str((site_sources[0] or {}).get("entry_url") or "").strip()
|
||||
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 == "dsv360":
|
||||
export_fn = _export_dsv_inventory_source
|
||||
elif site == "crane_footprint":
|
||||
export_fn = _export_crane_inventory_source
|
||||
else:
|
||||
for source in site_sources:
|
||||
results.append({
|
||||
"source_code": source.get("source_code"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_code": "unsupported_connector_type",
|
||||
"error_message": f"unsupported connector_type: {site}",
|
||||
})
|
||||
continue
|
||||
|
||||
for index, source in enumerate(site_sources):
|
||||
code = str(source.get("source_code") or "")
|
||||
wh = str(source.get("warehouse_id") or "")
|
||||
try:
|
||||
_validate_inventory_source_for_rpa(source)
|
||||
skip_navigation = False
|
||||
if site == "dsv360":
|
||||
skip_navigation = _prepare_dsv_batch_export_step(
|
||||
page,
|
||||
entry_url,
|
||||
site_sources[index - 1] if index > 0 else None,
|
||||
source,
|
||||
index=index,
|
||||
)
|
||||
elif site == "crane_footprint":
|
||||
if index == 0:
|
||||
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):
|
||||
code = str(source.get("source_code") or "")
|
||||
wh = str(source.get("warehouse_id") or "")
|
||||
try:
|
||||
_validate_inventory_source_for_rpa(source)
|
||||
skip_navigation = False
|
||||
if site == "dsv360":
|
||||
skip_navigation = _prepare_dsv_batch_export_step(page, entry_url, site_sources[index - 1] if index > 0 else None, source, index=index)
|
||||
elif index == 0:
|
||||
_ensure_crane_session(page, entry_url)
|
||||
else:
|
||||
_reset_crane_export_entry(page, entry_url)
|
||||
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
|
||||
out_file = _save_batch_download(download, drop_dir, run_no, source)
|
||||
results.append({
|
||||
"source_code": code,
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": wh,
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(out_file),
|
||||
"task_no": task_no or None,
|
||||
})
|
||||
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
results.append({
|
||||
"source_code": code,
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": wh,
|
||||
"status": "skipped",
|
||||
"success": False,
|
||||
"skipped": True,
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": str(exc),
|
||||
})
|
||||
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
|
||||
except Exception as exc:
|
||||
results.append({
|
||||
"source_code": code,
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": wh,
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_code": "rpa_export_failed",
|
||||
"error_message": str(exc),
|
||||
})
|
||||
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
|
||||
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 None})
|
||||
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)})
|
||||
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)})
|
||||
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)})
|
||||
finally:
|
||||
if context is not None:
|
||||
context.close()
|
||||
@@ -1008,7 +1003,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true"
|
||||
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
mode = "mock" if mock else "browser"
|
||||
try:
|
||||
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
|
||||
@@ -1068,7 +1063,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true"
|
||||
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
|
||||
if not mock:
|
||||
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
|
||||
return
|
||||
@@ -1115,17 +1110,17 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
|
||||
def main() -> None:
|
||||
_configure_file_logging()
|
||||
drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR")
|
||||
inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
|
||||
upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR")
|
||||
upload_trigger_dir = _require_path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
|
||||
poll = max(1, int(_env("FREIGHT_RPA_POLL_SECONDS", "3") or "3"))
|
||||
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"
|
||||
|
||||
print("[freight_rpa_worker] started")
|
||||
print(f" mock={_env('FREIGHT_RPA_MOCK', 'false')}")
|
||||
print(f" mock={_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')}")
|
||||
print(f" inventory_triggers={inv_trigger_dir}")
|
||||
print(f" upload_triggers={upload_trigger_dir}")
|
||||
print(f" drop={drop_dir}")
|
||||
|
||||
Reference in new issue
Block a user