Merge branch 'hugo-auto-transfer' into dev
This commit is contained in:
commit
e15b7b1ac2
790 files changed
+71443
-26080
No files matched your search
+310
-253
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
scripts/freight_rpa/common/rpa_callbacks.py
|
||||
|
||||
用途:货代 RPA Worker → 后端回调 URL 的单一真相(/api/freight-rpa/* 前缀,批次 R 起
|
||||
取代旧 shipping-notice rpa 回调前缀,无双路由、无兼容层)与统一 POST 实现。
|
||||
依赖:rpa_common.env、urllib、json(Worker 独立运行,禁止 import 后端 app)。
|
||||
逻辑:onhand/inbound/outbound Worker 与 rpa_heartbeat 一律从本模块常量取回调路径,禁止再硬编码;
|
||||
post_callback 复用统一鉴权(双 Header 集成密钥)、脱敏请求日志与 HTTP 错误处理。
|
||||
路径清单与后端 backend/app/api/freight_rpa.py 蓝图路由一一对应,改动须双侧同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from rpa_common import env as _env
|
||||
|
||||
_CALLBACK_BASE = "/api/freight-rpa"
|
||||
|
||||
# 心跳(rpa_heartbeat.post_heartbeat 使用;Worker 守护线程周期上报)。
|
||||
HEARTBEAT = f"{_CALLBACK_BASE}/heartbeat"
|
||||
# onhand(在手库存)Worker 回调。
|
||||
ONHAND_READY = f"{_CALLBACK_BASE}/onhand-ready"
|
||||
ONHAND_BATCH_CLAIMED = f"{_CALLBACK_BASE}/onhand-batch-claimed"
|
||||
ONHAND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/onhand-batch-progress"
|
||||
ONHAND_BATCH_READY = f"{_CALLBACK_BASE}/onhand-batch-ready"
|
||||
# onhand 配置测试(旧 inventory-configuration-test-*:batch-progress→start、ready→analyze、
|
||||
# batch-ready→complete,与后端蓝图分发语义一一对应)。
|
||||
ONHAND_CONFIGURATION_TEST_START = f"{_CALLBACK_BASE}/onhand-configuration-test-start"
|
||||
ONHAND_CONFIGURATION_TEST_ANALYZE = f"{_CALLBACK_BASE}/onhand-configuration-test-analyze"
|
||||
ONHAND_CONFIGURATION_TEST_COMPLETE = f"{_CALLBACK_BASE}/onhand-configuration-test-complete"
|
||||
# onhand 受控修复(人工/运维补偿链路,复用正式 v2 ingest 流程)。
|
||||
ONHAND_REPAIR = f"{_CALLBACK_BASE}/onhand-repair"
|
||||
# inbound(入站,原收料)Worker 回调。
|
||||
INBOUND_BATCH_READY = f"{_CALLBACK_BASE}/inbound-batch-ready"
|
||||
INBOUND_UNIT_PROGRESS = f"{_CALLBACK_BASE}/inbound-unit-progress"
|
||||
INBOUND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/inbound-batch-progress"
|
||||
# outbound(出站)Worker 回调。
|
||||
OUTBOUND_BATCH_READY = f"{_CALLBACK_BASE}/outbound-batch-ready"
|
||||
OUTBOUND_UNIT_PROGRESS = f"{_CALLBACK_BASE}/outbound-unit-progress"
|
||||
OUTBOUND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/outbound-batch-progress"
|
||||
# 货代上传结果(URL 词根不变,仅前缀换为 /api/freight-rpa)。
|
||||
UPLOAD_COMPLETE = f"{_CALLBACK_BASE}/upload-complete"
|
||||
|
||||
|
||||
def _mask_secret(value: str) -> str:
|
||||
"""对集成密钥做首尾保留脱敏:长度 ≤8 返回 ***,否则保留前 4 后 4。"""
|
||||
value = str(value or "")
|
||||
if len(value) <= 8:
|
||||
return "***"
|
||||
return f"{value[:4]}...{value[-4:]}"
|
||||
|
||||
|
||||
def post_callback(path: str, payload: dict, *, timeout: int = 30) -> None:
|
||||
"""
|
||||
向 HXOPS 货代回调 API 发送 JSON 请求(所有 Worker 回调的统一出口)。
|
||||
|
||||
【AI 触发时机】:Worker 完成导出/上传/领取等节点需要回传后端时调用;
|
||||
path 必须传本模块导出的常量,禁止拼接旧 shipping-notice rpa 回调前缀字符串。
|
||||
|
||||
核心逻辑:HXOPS_API_BASE + path 组装 URL → 双 Header 密钥鉴权 → 打印脱敏请求日志 →
|
||||
POST;HTTP 非 2xx 时打印响应体摘要并抛 RuntimeError(由调用方决定归档 failed)。
|
||||
|
||||
Args:
|
||||
path: 回调路径,仅允许本模块 *_READY / *_PROGRESS / *_CLAIMED / HEARTBEAT /
|
||||
UPLOAD_COMPLETE 等常量;业务约束——禁止传入完整 URL 或未知路径。
|
||||
payload: JSON 请求体(dict,UTF-8 序列化)。
|
||||
timeout: 请求超时秒数,默认 30。
|
||||
|
||||
Raises:
|
||||
SystemExit: 三个集成密钥环境变量全部缺失。
|
||||
RuntimeError: 密钥含非 ASCII 字符,或后端返回 HTTP 非 2xx。
|
||||
"""
|
||||
base = str(_env("HXOPS_API_BASE", "http://127.0.0.1:5052") or "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=timeout) 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
|
||||
@@ -14,11 +14,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
scripts/freight_rpa/common/rpa_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
|
||||
用途:货代 RPA Worker 向后端上报心跳(POST /api/freight-rpa/heartbeat(路径常量见 common/rpa_callbacks.HEARTBEAT))。
|
||||
依赖:rpa_common.env、urllib、socket。
|
||||
逻辑:由库存/收料 Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
|
||||
库存声明 inventory_export,收料声明 receipt_export;库存侧可写共享目录哨兵。
|
||||
逻辑:由 onhand/inbound/outbound Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
|
||||
onhand 声明 onhand_export,inbound 声明 inbound_export,outbound 声明 outbound_export;可写共享目录哨兵。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,11 +15,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -37,6 +37,8 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import env as _env
|
||||
# 心跳路径单一真相(/api/freight-rpa/heartbeat),与业务回调共用 rpa_callbacks 常量。
|
||||
from rpa_callbacks import HEARTBEAT as _HEARTBEAT_PATH # noqa: E402
|
||||
|
||||
_RUNTIME_STATUS = "idle"
|
||||
_LAST_HEARTBEAT_MONO = 0.0
|
||||
@@ -82,7 +84,7 @@ def _resolve_shared_scope_id() -> str:
|
||||
value = str(raw or "").strip()
|
||||
if value:
|
||||
return value
|
||||
trigger = str(_env("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
|
||||
trigger = str(_env("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR") or "").replace("\\", "/").lower()
|
||||
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
|
||||
if token in trigger:
|
||||
return token
|
||||
@@ -136,19 +138,26 @@ def build_heartbeat_payload(
|
||||
"""
|
||||
组装心跳 payload。
|
||||
|
||||
核心逻辑:库存 Worker 声明 inventory_export;收料 Worker(worker_id 以 -receipt
|
||||
结尾,或 trigger_dir 路径含 /receipt/)声明 receipt_export;开启上传时附加 freight_upload。
|
||||
核心逻辑:outbound Worker(worker_id 以 -outbound 结尾,或 trigger_dir 含 /outbound/)
|
||||
声明 outbound_export;inbound 同理 inbound_export;其余 onhand_export。开启上传时附加 freight_rpa_upload。
|
||||
"""
|
||||
hostname = socket.gethostname()
|
||||
worker_id = _resolve_worker_id(hostname)
|
||||
trigger_norm = str(trigger_dir or "").replace("\\", "/").lower()
|
||||
is_receipt = str(worker_id).lower().endswith("-receipt") or "/receipt/" in f"/{trigger_norm}/"
|
||||
capabilities = ["receipt_export" if is_receipt else "inventory_export"]
|
||||
worker_id_l = str(worker_id).lower()
|
||||
is_outbound = worker_id_l.endswith("-outbound") or "/outbound/" in f"/{trigger_norm}/"
|
||||
is_inbound = worker_id_l.endswith("-inbound") or "/inbound/" in f"/{trigger_norm}/"
|
||||
if is_outbound:
|
||||
capabilities = ["outbound_export"]
|
||||
elif is_inbound:
|
||||
capabilities = ["inbound_export"]
|
||||
else:
|
||||
capabilities = ["onhand_export"]
|
||||
upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
|
||||
"1", "true", "yes", "on",
|
||||
}
|
||||
if upload_enabled:
|
||||
capabilities.append("freight_upload")
|
||||
capabilities.append("freight_rpa_upload")
|
||||
return {
|
||||
"worker_id": worker_id,
|
||||
"hostname": hostname,
|
||||
@@ -179,7 +188,7 @@ def post_heartbeat(payload: dict[str, Any]) -> bool:
|
||||
print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
|
||||
return False
|
||||
|
||||
url = f"{base}/api/shipping-notice/rpa/heartbeat"
|
||||
url = f"{base}{_HEARTBEAT_PATH}"
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
@@ -225,7 +234,7 @@ def _start_heartbeat_request(payload: dict[str, Any]) -> bool:
|
||||
thread = threading.Thread(
|
||||
target=post_heartbeat,
|
||||
args=(payload,),
|
||||
name="shipping-rpa-heartbeat",
|
||||
name="freight-rpa-heartbeat",
|
||||
daemon=True,
|
||||
)
|
||||
_HEARTBEAT_THREAD = thread
|
||||
@@ -291,6 +300,6 @@ def start_heartbeat_loop(
|
||||
except Exception:
|
||||
print("[heartbeat] loop tick failed", file=sys.stderr)
|
||||
|
||||
thread = threading.Thread(target=_loop, name="shipping-rpa-heartbeat-loop", daemon=True)
|
||||
thread = threading.Thread(target=_loop, name="freight-rpa-heartbeat-loop", daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
@@ -3,7 +3,7 @@ scripts/freight_rpa/common/worker_disk_cleanup.py
|
||||
|
||||
用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。
|
||||
依赖:rpa_common.env、pathlib、shutil、time。
|
||||
逻辑:由 inventory(及可复用的 receipt)Worker 主循环周期调用;只删超过保留期的归档与临时物,
|
||||
逻辑:由 onhand / inbound / outbound Worker 主循环周期调用;只删超过保留期的归档与临时物,
|
||||
绝不删除进行中的 trigger 根目录 JSON、可复用会话 Profile(*_session)、以及活跃 cleanup 队列。
|
||||
"""
|
||||
|
||||
@@ -18,13 +18,13 @@ _RPA_ROOT = next(
|
||||
for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir()
|
||||
and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir()
|
||||
and (_c / "receipt").is_dir()
|
||||
and (_c / "onhand").is_dir()
|
||||
and (_c / "inbound").is_dir()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -48,9 +48,9 @@ _PROTECTED_DROP_DIRNAMES = frozenset(
|
||||
)
|
||||
_DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"})
|
||||
_TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed")
|
||||
# 一次性运行 Profile 前缀:库存 Worker 用 run_*,收料 Worker 用 receipt_*,
|
||||
# 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
|
||||
# 一次性运行 Profile 前缀:onhand 用 run_*,inbound 用 inbound_*,outbound 用 outbound_*,
|
||||
# 均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "inbound_", "outbound_")
|
||||
_DEFAULT_RETENTION_DAYS = 7
|
||||
_DEFAULT_INTERVAL_SECONDS = 3600
|
||||
_DEFAULT_ORPHAN_PROFILE_HOURS = 24
|
||||
@@ -111,7 +111,7 @@ def cleanup_interval_seconds() -> int:
|
||||
|
||||
def orphan_profile_max_age_seconds() -> int:
|
||||
"""
|
||||
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
|
||||
读取孤儿临时 Profile(run_* / inbound_* / outbound_*)最大存活秒数。
|
||||
|
||||
核心逻辑:`FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
|
||||
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
|
||||
@@ -335,11 +335,11 @@ def cleanup_orphan_runtime_profiles(
|
||||
stats: DiskCleanupStats,
|
||||
) -> None:
|
||||
"""
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` / `inbound_*` / `outbound_*` 目录。
|
||||
|
||||
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
|
||||
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
|
||||
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
|
||||
仅删除 `run_*` / `inbound_*` / `outbound_*` 临时目录,避免异常中断后残留撑盘。
|
||||
inbound/outbound Worker 一次性 Profile 以前缀创建,同属清理对象。
|
||||
"""
|
||||
if profile_root is None or not profile_root.is_dir():
|
||||
return
|
||||
@@ -365,7 +365,7 @@ def cleanup_orphan_runtime_profiles(
|
||||
|
||||
def run_worker_disk_cleanup(
|
||||
*,
|
||||
inventory_trigger_dir: Path | None = None,
|
||||
onhand_trigger_dir: Path | None = None,
|
||||
upload_trigger_dir: Path | None = None,
|
||||
drop_dir: Path | None = None,
|
||||
upload_queue_dir: Path | None = None,
|
||||
@@ -379,12 +379,12 @@ def run_worker_disk_cleanup(
|
||||
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
|
||||
|
||||
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `inbound_*` / `outbound_*` Profile。全部 best-effort。
|
||||
|
||||
Args:
|
||||
inventory_trigger_dir: 库存 trigger 根目录。
|
||||
onhand_trigger_dir: onhand trigger 根目录。
|
||||
upload_trigger_dir: 上传 trigger 根目录。
|
||||
drop_dir: 库存 drop 根目录。
|
||||
drop_dir: onhand drop 根目录。
|
||||
upload_queue_dir: 上传队列目录。
|
||||
browser_profile_dir: 浏览器 Profile 根目录。
|
||||
log_file: 当前 worker 日志文件路径。
|
||||
@@ -398,7 +398,7 @@ def run_worker_disk_cleanup(
|
||||
days = retention_days()
|
||||
if days > 0:
|
||||
cutoff = now - (days * 86400)
|
||||
cleanup_trigger_archives(inventory_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_trigger_archives(onhand_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_trigger_archives(upload_trigger_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_drop_archives(drop_dir, cutoff_unix=cutoff, stats=stats)
|
||||
cleanup_upload_queue(upload_queue_dir, cutoff_unix=cutoff, stats=stats)
|
||||
|
||||
@@ -22,8 +22,8 @@ from pathlib import Path
|
||||
|
||||
def _load_worker():
|
||||
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
|
||||
module_path = repo_root / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_crane_smoke", module_path)
|
||||
module_path = repo_root / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_crane_smoke", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
"""
|
||||
scripts/freight_rpa/crane_navigation.py
|
||||
scripts/freight_rpa/connectors/crane/crane_navigation.py
|
||||
|
||||
用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。
|
||||
依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。
|
||||
逻辑:优先点击首页 Queries 区 On Hand Details 卡片;失败再走顶部 Queries 下拉菜单;最后 goto entry_url。
|
||||
用途:Crane FootPrint Portal 报表页导航(On Hand / Inbound / Outbound Details 等查询页通用)。
|
||||
依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后按 entry_url 调用,
|
||||
onhand/inbound/outbound Worker 共用本模块。
|
||||
逻辑:报表目标(卡片/菜单标签与 hash 路由)一律由 entry_url 推导,禁止硬编码某一报表;
|
||||
优先点击首页 Queries 区目标卡片 → 顶部 Queries 菜单 → goto entry_url;
|
||||
登录态下禁止任何整页导航(goto 根地址/reload),兜底只就地赋 hash——
|
||||
Crane 门户登录态不随整页加载恢复,刷新即登出(2026-10-20 出站死循环根因)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,18 +17,37 @@ import time
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
_ON_HAND_DETAILS_LABEL = "On Hand Details"
|
||||
_ON_HAND_DETAILS_ROUTE = "on-hand-details-query"
|
||||
|
||||
# 首页 Queries 区大卡片:Vue hash 路由常见 href="#/on-hand-details-query"(非 "/on-hand-details-query")
|
||||
_CRANE_DASHBOARD_REPORT_TILE_SELECTORS: tuple[str, ...] = (
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'a.box[href*="on-hand-details-query"]',
|
||||
'a.box.has-text-centered[href*="on-hand-details-query"]',
|
||||
'a.box:has-text("On Hand Details")',
|
||||
'a:has-text("On Hand Details")',
|
||||
'.box:has-text("On Hand Details")',
|
||||
)
|
||||
# 报表路由 → 页面标签(与门户 Queries 菜单实名一致);未知路由按 kebab-case 推导。
|
||||
_CRANE_REPORT_ROUTE_LABELS: dict[str, str] = {
|
||||
"inbound-details-query": "Inbound Details",
|
||||
"on-hand-details-query": "On Hand Details",
|
||||
"outbound-details-query": "Outbound Details",
|
||||
}
|
||||
_ON_HAND_DETAILS_LABEL = "On Hand Details"
|
||||
|
||||
|
||||
def _dashboard_tile_selectors(label: str, route: str) -> tuple[str, ...]:
|
||||
"""按目标报表生成首页卡片选择器(生产实证的 box 标签优先,href 路由次之兜底)。"""
|
||||
return (
|
||||
f'.columns .box:has-text("{label}")',
|
||||
f'section:has-text("Queries") .box:has-text("{label}")',
|
||||
f'a[href*="{route}"]',
|
||||
f'a.box[href*="{route}"]',
|
||||
f'a.box:has-text("{label}")',
|
||||
f'.box:has-text("{label}")',
|
||||
f'[class*="box"]:has-text("{label}")',
|
||||
)
|
||||
|
||||
|
||||
def _navbar_report_item_selectors(label: str) -> tuple[str, ...]:
|
||||
"""按目标报表生成顶部 Queries 下拉项选择器。"""
|
||||
return (
|
||||
f'.navbar-dropdown a.navbar-item:has-text("{label}")',
|
||||
f'a.navbar-item:has-text("{label}")',
|
||||
)
|
||||
|
||||
|
||||
# 顶部导航 Queries 下拉(第二张图)
|
||||
_CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = (
|
||||
@@ -32,11 +55,6 @@ _CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = (
|
||||
'.navbar-item.has-dropdown > a.navbar-link',
|
||||
)
|
||||
|
||||
_CRANE_NAV_ON_HAND_DETAILS_SELECTORS: tuple[str, ...] = (
|
||||
'.navbar-dropdown a.navbar-item:has-text("On Hand Details")',
|
||||
'a.navbar-item:has-text("On Hand Details")',
|
||||
)
|
||||
|
||||
# 报表表单就绪信号:必须出现 Run Report 或报表参数字段;首页 Queries 区标题不算 ready
|
||||
_CRANE_REPORT_FORM_READY_SELECTORS: tuple[str, ...] = (
|
||||
'button:has-text("Run Report")',
|
||||
@@ -67,6 +85,15 @@ def _report_route_from_entry_url(entry_url: str) -> str:
|
||||
return _ON_HAND_DETAILS_ROUTE
|
||||
|
||||
|
||||
def _report_label_from_entry_url(entry_url: str) -> str:
|
||||
"""由 entry 路由推导报表页标签;已知路由查表,未知路由按 kebab-case 推导。"""
|
||||
route = _report_route_from_entry_url(entry_url)
|
||||
if route in _CRANE_REPORT_ROUTE_LABELS:
|
||||
return _CRANE_REPORT_ROUTE_LABELS[route]
|
||||
stem = route.removesuffix("-query").replace("-", " ").strip()
|
||||
return stem.title() if stem else _ON_HAND_DETAILS_LABEL
|
||||
|
||||
|
||||
def _current_url_fragment(page: Any) -> str:
|
||||
"""读取当前页 URL hash 片段(不含 #/ 前缀)。"""
|
||||
try:
|
||||
@@ -80,7 +107,7 @@ def _current_url_fragment(page: Any) -> str:
|
||||
def is_crane_on_homepage(page: Any) -> bool:
|
||||
"""
|
||||
判定是否停在 Crane 登录后首页(/#/ 或空 hash)。
|
||||
核心逻辑:首页 Queries 区有 On Hand Details 卡片,但报表表单尚未打开,不能视为 ready。
|
||||
核心逻辑:首页 Queries 区有报表卡片,但报表表单尚未打开,不能视为 ready。
|
||||
"""
|
||||
fragment = _current_url_fragment(page)
|
||||
if not fragment or fragment in {"home", "dashboard", "index"}:
|
||||
@@ -107,7 +134,7 @@ def _has_report_form_controls(page: Any) -> bool:
|
||||
|
||||
def is_crane_report_form_ready(page: Any, entry_url: str) -> bool:
|
||||
"""
|
||||
判定 On Hand Details Query 报表表单是否已就绪。
|
||||
判定目标报表表单是否已就绪。
|
||||
核心逻辑:首页 /#/ 不算 ready;必须 hash 落在报表路由且出现 Run Report / 参数字段。
|
||||
"""
|
||||
if is_crane_on_homepage(page):
|
||||
@@ -130,18 +157,24 @@ def _click_visible_locator(locator: Any, *, browser_timeout_ms: int) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_crane_homepage_ready(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
def _wait_for_crane_homepage_ready(
|
||||
page: Any,
|
||||
*,
|
||||
label: str,
|
||||
route: str,
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
登录后等待首页 Queries 区渲染完成。
|
||||
核心逻辑:On Hand Details 卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。
|
||||
核心逻辑:目标报表卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。
|
||||
"""
|
||||
deadline = time.monotonic() + (min(browser_timeout_ms, 20_000) / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for selector in (
|
||||
'text=On Hand Details',
|
||||
'text=Queries',
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'.box:has-text("On Hand Details")',
|
||||
f"text={label}",
|
||||
"text=Queries",
|
||||
f'a[href*="{route}"]',
|
||||
f'.box:has-text("{label}")',
|
||||
):
|
||||
if _visible_locator(page, selector) is not None:
|
||||
print("[crane-nav] homepage shell ready")
|
||||
@@ -162,38 +195,25 @@ def _click_by_role_link(page: Any, name: str, *, browser_timeout_ms: int) -> boo
|
||||
return False
|
||||
|
||||
|
||||
def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
def _click_report_tile_by_text(page: Any, *, label: str, browser_timeout_ms: int) -> bool:
|
||||
"""
|
||||
通过文本语义点击首页 Queries 区的 On Hand Details 卡片。
|
||||
核心逻辑:hash 路由下 tile 可能是 a[href*=#/on-hand-details-query] 或 .box 包裹的 router-link。
|
||||
通过文本语义点击首页 Queries 区目标报表卡片(role link 与祖先节点兜底)。
|
||||
核心逻辑:hash 路由下 tile 可能是 a[href*=#/<route>] 或 .box 包裹的 router-link。
|
||||
"""
|
||||
tile_selectors = (
|
||||
'.columns .box:has-text("On Hand Details")',
|
||||
'section:has-text("Queries") .box:has-text("On Hand Details")',
|
||||
'.box:has-text("On Hand Details")',
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'[class*="box"]:has-text("On Hand Details")',
|
||||
)
|
||||
for selector in tile_selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked On Hand Details tile selector={selector!r}")
|
||||
return True
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_role("link", name=_ON_HAND_DETAILS_LABEL, exact=False).first
|
||||
locator = root.get_by_role("link", name=label, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _click_visible_locator(
|
||||
locator, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print("[crane-nav] clicked On Hand Details tile via link role")
|
||||
print("[crane-nav] clicked report tile via link role")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_text(_ON_HAND_DETAILS_LABEL, exact=False).first
|
||||
locator = root.get_by_text(label, exact=False).first
|
||||
if not locator.is_visible(timeout=500):
|
||||
continue
|
||||
for candidate in (
|
||||
@@ -206,7 +226,7 @@ def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
if target.is_visible(timeout=300) and _click_visible_locator(
|
||||
target, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print("[crane-nav] clicked On Hand Details tile via text locator")
|
||||
print("[crane-nav] clicked report tile via text locator")
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
@@ -215,34 +235,34 @@ def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _click_dashboard_on_hand_details(
|
||||
def _click_dashboard_report_tile(
|
||||
page: Any,
|
||||
*,
|
||||
label: str,
|
||||
route: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
点击首页 Queries 区域的 On Hand Details 卡片(优先策略)。
|
||||
核心逻辑:先文本语义定位 tile,再匹配 href*=on-hand-details-query 的 hash 路由链接。
|
||||
点击首页 Queries 区域的目标报表卡片(优先策略)。
|
||||
核心逻辑:卡片选择器由 entry 路由推导(box 标签优先、href 兜底,对齐库存生产路径);
|
||||
环境变量 selector 次之,保留为运维紧急覆盖手段;最后走文本语义兜底。
|
||||
"""
|
||||
if _click_on_hand_details_tile(page, browser_timeout_ms=browser_timeout_ms):
|
||||
return True
|
||||
|
||||
selectors = tuple(
|
||||
item
|
||||
for item in (env("FREIGHT_RPA_WORKER_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS)
|
||||
for item in (
|
||||
*_dashboard_tile_selectors(label, route),
|
||||
env("FREIGHT_RPA_WORKER_CRANE_DASHBOARD_REPORT_SELECTOR"),
|
||||
)
|
||||
if item
|
||||
)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked dashboard tile selector={selector!r}")
|
||||
print(f"[crane-nav] clicked report tile selector={selector!r}")
|
||||
return True
|
||||
|
||||
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] clicked dashboard tile via link role")
|
||||
return True
|
||||
return False
|
||||
return _click_report_tile_by_text(page, label=label, browser_timeout_ms=browser_timeout_ms)
|
||||
|
||||
|
||||
def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool:
|
||||
@@ -279,15 +299,16 @@ def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser
|
||||
return False
|
||||
|
||||
|
||||
def _click_navbar_on_hand_details(
|
||||
def _click_navbar_report_item(
|
||||
page: Any,
|
||||
*,
|
||||
label: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
通过顶部 Queries 下拉进入 On Hand Details(回退策略)。
|
||||
核心逻辑:先展开 Queries navbar-dropdown,再点 a.navbar-item On Hand Details。
|
||||
通过顶部 Queries 下拉进入目标报表页(回退策略)。
|
||||
核心逻辑:先展开 Queries navbar-dropdown,再点由 entry 路由推导的 navbar 项。
|
||||
"""
|
||||
if not _open_queries_nav_menu(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] Queries navbar menu not opened", file=sys.stderr)
|
||||
@@ -295,7 +316,9 @@ def _click_navbar_on_hand_details(
|
||||
|
||||
time.sleep(0.35)
|
||||
selectors = tuple(
|
||||
item for item in (env("FREIGHT_RPA_WORKER_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item
|
||||
item
|
||||
for item in (env("FREIGHT_RPA_WORKER_CRANE_NAV_REPORT_SELECTOR"), *_navbar_report_item_selectors(label))
|
||||
if item
|
||||
)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
@@ -303,8 +326,8 @@ def _click_navbar_on_hand_details(
|
||||
print(f"[crane-nav] clicked navbar item selector={selector!r}")
|
||||
return True
|
||||
|
||||
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] clicked navbar On Hand Details via link role")
|
||||
if _click_by_role_link(page, label, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] clicked navbar report item via link role")
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -324,45 +347,71 @@ def _wait_for_report_navigation(
|
||||
return False
|
||||
|
||||
|
||||
def _crane_entry_host(entry_url: str) -> str:
|
||||
"""从 entry_url 提取 host(小写),用于域内就地赋 hash 的守卫。"""
|
||||
parsed = urlparse(str(entry_url or "").strip())
|
||||
return (parsed.netloc or "").lower()
|
||||
|
||||
|
||||
_HASH_ROUTE_ASSIGN_JS = """
|
||||
(route) => {
|
||||
const hash = route.startsWith('/') ? route : `/${route}`;
|
||||
if (window.location.hash !== `#${hash}`) {
|
||||
window.location.hash = hash;
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _assign_hash_route_in_place(page: Any, entry_url: str, route: str, *, browser_timeout_ms: int) -> None:
|
||||
"""
|
||||
登录态下就地切换 hash 路由;仅 portal 域内执行。
|
||||
|
||||
核心逻辑:window.location.hash 赋值属 same-document 导航,不触发整页加载、
|
||||
不丢登录态;不在 portal 域时跳过(此时本就无会话可丢,交由上层重登流程处理)。
|
||||
"""
|
||||
host = _crane_entry_host(entry_url)
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if not host or host not in current_url:
|
||||
print(
|
||||
f"[crane-nav] skip in-place hash assign; not on portal host={host!r} url={current_url!r}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
print(f"[crane-nav] assigning hash route in-place route={route!r}")
|
||||
try:
|
||||
page.evaluate(_HASH_ROUTE_ASSIGN_JS, route)
|
||||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||||
except Exception as exc:
|
||||
print(f"[crane-nav] in-place hash assignment failed: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
def _navigate_hash_route(page: Any, entry_url: str, *, browser_timeout_ms: int) -> None:
|
||||
"""
|
||||
通过 goto + hash 赋值进入 SPA 报表路由。
|
||||
核心逻辑:登录后常落在 /#/ 首页,仅 goto 完整 entry_url 时 Vue 路由可能不切换。
|
||||
通过 goto + 就地 hash 赋值进入 SPA 报表路由(登录态下禁止整页导航)。
|
||||
|
||||
核心逻辑:goto entry_url 属 same-document hash 导航;SPA 换页存在渲染间隙,
|
||||
须先轮询表单就绪再考虑兜底。兜底仅就地 `window.location.hash` 赋值——
|
||||
Crane 门户登录态不随整页加载恢复,goto 根地址/reload 等于强制登出
|
||||
(2026-10-20 出站死循环根因),本函数不得出现任何 full page navigation。
|
||||
"""
|
||||
target = str(entry_url or "").strip()
|
||||
if not target:
|
||||
raise RuntimeError("Crane report navigation failed: entry_url is empty")
|
||||
|
||||
route = _report_route_from_entry_url(entry_url)
|
||||
parsed = urlparse(target)
|
||||
base_url = f"{parsed.scheme}://{parsed.netloc}/"
|
||||
|
||||
print(f"[crane-nav] fallback direct goto entry_url={target!r}")
|
||||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
if is_crane_on_report_route(page, entry_url) and _has_report_form_controls(page):
|
||||
|
||||
# [STEP 1] hash 切换后 SPA 需要换页渲染,先轮询等待而非瞬时判定
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return
|
||||
|
||||
print(f"[crane-nav] assigning hash route via SPA base={base_url!r} route={route!r}")
|
||||
try:
|
||||
page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
page.evaluate(
|
||||
"""
|
||||
(route) => {
|
||||
const hash = route.startsWith('/') ? route : `/${route}`;
|
||||
if (window.location.hash !== `#${hash}`) {
|
||||
window.location.hash = hash;
|
||||
}
|
||||
}
|
||||
""",
|
||||
route,
|
||||
)
|
||||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
print(f"[crane-nav] hash route assignment failed: {exc}", file=sys.stderr)
|
||||
# [STEP 2] goto 未驱动路由时才就地赋 hash 兜底(绝不整页导航)
|
||||
_assign_hash_route_in_place(page, entry_url, route, browser_timeout_ms=browser_timeout_ms)
|
||||
|
||||
|
||||
def navigate_to_crane_report(
|
||||
@@ -373,8 +422,8 @@ def navigate_to_crane_report(
|
||||
browser_timeout_ms: int,
|
||||
) -> str:
|
||||
"""
|
||||
导航至 On Hand Details Query 报表页。
|
||||
核心逻辑:[STEP 1] 首页卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] 直接 goto entry_url。
|
||||
导航至 entry_url 指定的 Crane 报表页(标签与路由均由 entry_url 推导)。
|
||||
核心逻辑:[STEP 1] 首页目标卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] goto + 就地 hash。
|
||||
|
||||
Returns:
|
||||
使用的导航模式:`already_ready` | `dashboard_tile` | `navbar_menu` | `direct_goto`。
|
||||
@@ -382,25 +431,39 @@ def navigate_to_crane_report(
|
||||
Raises:
|
||||
RuntimeError: 三种方式均未能进入报表表单。
|
||||
"""
|
||||
route = _report_route_from_entry_url(entry_url)
|
||||
label = _report_label_from_entry_url(entry_url)
|
||||
|
||||
if is_crane_report_form_ready(page, entry_url):
|
||||
print("[crane-nav] report form already ready, skip navigation")
|
||||
return "already_ready"
|
||||
|
||||
_wait_for_crane_homepage_ready(page, browser_timeout_ms=browser_timeout_ms)
|
||||
_wait_for_crane_homepage_ready(page, label=label, route=route, browser_timeout_ms=browser_timeout_ms)
|
||||
|
||||
# [STEP 1] 首页 Queries 区 On Hand Details 卡片
|
||||
if _click_dashboard_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
# [STEP 1] 首页 Queries 区目标报表卡片
|
||||
if _click_dashboard_report_tile(
|
||||
page,
|
||||
label=label,
|
||||
route=route,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
):
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "dashboard_tile"
|
||||
print("[crane-nav] dashboard tile click did not reach report form, trying navbar", file=sys.stderr)
|
||||
|
||||
# [STEP 2] 顶部 Queries → On Hand Details
|
||||
if _click_navbar_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
# [STEP 2] 顶部 Queries → 目标报表项
|
||||
if _click_navbar_report_item(
|
||||
page,
|
||||
label=label,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
):
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "navbar_menu"
|
||||
print("[crane-nav] navbar navigation did not reach report form, trying direct goto", file=sys.stderr)
|
||||
|
||||
# [STEP 3] 直接打开配置的 entry_url(hash 路由)
|
||||
# [STEP 3] 直接打开配置的 entry_url(hash 路由;登录态下绝不整页导航)
|
||||
_navigate_hash_route(page, entry_url, browser_timeout_ms=browser_timeout_ms)
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "direct_goto"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
scripts/freight_rpa/crane_report_export.py
|
||||
|
||||
用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。
|
||||
依赖:Playwright Page、download_artifact_fallback;由 inventory_rpa_worker._export_crane_inventory_source 委托调用。
|
||||
依赖:Playwright Page、download_artifact_fallback;由 onhand_rpa_worker._export_crane_onhand_source 委托调用。
|
||||
逻辑:不填写页面查询条件;必须先 Run Report 产出查询结果,再 Schedule 异步导出;
|
||||
轮询仅在 scheduled-reports 路由进行;expect_download 超时时按下载目录新文件做短窗口兜底。
|
||||
"""
|
||||
@@ -18,13 +18,13 @@ _RPA_ROOT = next(
|
||||
for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir()
|
||||
and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir()
|
||||
and (_c / "receipt").is_dir()
|
||||
and (_c / "onhand").is_dir()
|
||||
and (_c / "inbound").is_dir()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -604,7 +604,8 @@ def _refresh_scheduled_reports_list(
|
||||
) -> None:
|
||||
"""
|
||||
从服务端重新拉取 Scheduled Reports 列表。
|
||||
核心逻辑:goto 同一路由刷新数据;reload 后等表格就绪;表格在则不重登,避免闪回登录页。
|
||||
核心逻辑:goto 同一路由刷新数据后等表格就绪;goto 失败时就地重赋 hash 兜底
|
||||
(登录态下禁止 reload/goto 根地址——Crane 门户刷新即掉登录);表格在则不重登。
|
||||
"""
|
||||
fragment = _current_url_fragment(page)
|
||||
on_route = _CRANE_SCHEDULED_REPORTS_ROUTE in fragment
|
||||
@@ -624,12 +625,14 @@ def _refresh_scheduled_reports_list(
|
||||
try:
|
||||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
except Exception as exc:
|
||||
print(f"[crane-export] scheduled reports goto refresh failed: {exc}; trying reload", file=sys.stderr)
|
||||
try:
|
||||
page.reload(wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
except Exception as reload_exc:
|
||||
print(f"[crane-export] scheduled reports reload failed: {reload_exc}", file=sys.stderr)
|
||||
return
|
||||
# 登录态下禁止 reload/goto 根地址——Crane 门户登录态不随整页加载恢复,
|
||||
# 刷新即登出(2026-10-20 出站死循环根因);goto 失败时就地重赋 hash 继续,
|
||||
# 恢复不了由外层重登流程(_recover_crane_session_on_scheduled_reports)接管。
|
||||
print(
|
||||
f"[crane-export] scheduled reports goto refresh failed: {exc}; re-assign hash in place",
|
||||
file=sys.stderr,
|
||||
)
|
||||
_goto_scheduled_reports_hash(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||||
|
||||
if not _wait_for_scheduled_reports_list_ready(page, browser_timeout_ms=browser_timeout_ms):
|
||||
if _is_crane_login_blocking(page):
|
||||
@@ -713,7 +716,9 @@ def _probe_scheduled_download_status(
|
||||
def _goto_scheduled_reports_hash(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None:
|
||||
"""
|
||||
通过 SPA hash 路由进入 Scheduled Reports。
|
||||
核心逻辑:Run Report 后仍停在 on-hand-details-query 时,点击链接可能无效,需显式改 hash。
|
||||
核心逻辑:Run Report 后仍停在 on-hand-details-query 时,点击链接可能无效,需显式改 hash;
|
||||
portal 域内且未掉登录时只就地赋 hash,绝不整页导航(Crane 门户刷新即登出);
|
||||
仅已掉登录(无会话可丢)才允许 goto 根地址重新拉起 SPA。
|
||||
"""
|
||||
target = _scheduled_reports_url(page, env=env)
|
||||
parsed = urlparse(target)
|
||||
@@ -1167,7 +1172,7 @@ def export_crane_inventory_report(
|
||||
browser_timeout_ms: 浏览器操作超时。
|
||||
select_or_fill: worker 提供的下拉/输入填充函数。
|
||||
click_text: worker 提供的文本点击函数(file_download 直出模式备用)。
|
||||
trigger: inventory_export / batch trigger,用于生成唯一 Description。
|
||||
trigger: onhand_export / batch trigger,用于生成唯一 Description。
|
||||
|
||||
Returns:
|
||||
Playwright Download 或 FilesystemDownloadArtifact。
|
||||
|
||||
@@ -17,11 +17,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -18,11 +18,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -14,11 +14,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -14,11 +14,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -22,8 +22,8 @@ from pathlib import Path
|
||||
|
||||
def _load_worker():
|
||||
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
|
||||
module_path = repo_root / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_smoke", module_path)
|
||||
module_path = repo_root / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_smoke", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
@@ -14,11 +14,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
@@ -3,8 +3,8 @@ scripts/freight_rpa/dsv_report_export.py
|
||||
|
||||
用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。
|
||||
依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。
|
||||
逻辑:worker connector_type=dsv360 / 收料 DBS 时委托本模块;按 export_kind 分流
|
||||
库存/收料的结果就绪正文标记与明细行探针(结构可参考,字段不复用);
|
||||
逻辑:worker connector_type=dsv360 / 入站或出站 DBS 时委托本模块;按 export_kind 分流
|
||||
库存/入站/出站的结果就绪正文标记与明细行探针(结构可参考,字段不复用);
|
||||
DOM 明细行探测仅作加速,无行时重试 View Report 一次后仍导出,真空由落盘 Excel 判定。
|
||||
"""
|
||||
|
||||
@@ -16,11 +16,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -100,7 +100,7 @@ _DSV_INVENTORY_BODY_MARKERS: tuple[str, ...] = (
|
||||
)
|
||||
|
||||
# Receipt Detail 专用正文标记(AWSRTM 实机列头,2026-09-28);可与库存共享 UI 词,不含库存专用语义。
|
||||
_DSV_RECEIPT_BODY_MARKERS: tuple[str, ...] = (
|
||||
_DSV_INBOUND_BODY_MARKERS: tuple[str, ...] = (
|
||||
"receipt detail",
|
||||
"external asn",
|
||||
"wms receipt",
|
||||
@@ -114,29 +114,48 @@ _DSV_RECEIPT_BODY_MARKERS: tuple[str, ...] = (
|
||||
"whole page",
|
||||
)
|
||||
|
||||
# 出站报表正文标记(Task 12 占位:未拿到实机列头前用通用 shipped/outbound 词 + SSRS UI 词)。
|
||||
_DSV_OUTBOUND_BODY_MARKERS: tuple[str, ...] = (
|
||||
"outbound detail",
|
||||
"outbound details",
|
||||
"ship qty",
|
||||
"qty shipped",
|
||||
"date shipped",
|
||||
"shipment",
|
||||
"dispatch",
|
||||
"page width",
|
||||
"whole page",
|
||||
)
|
||||
|
||||
|
||||
def _dsv_export_kind(source: dict[str, Any] | None = None, *, kind: str | None = None) -> str:
|
||||
"""
|
||||
解析导出语义:inventory | receipt。
|
||||
解析导出语义:inventory(onhand)| inbound(原 receipt)| outbound。
|
||||
|
||||
核心逻辑:显式 kind / source.__export_kind__ 优先;否则按报表名含 receipt detail 推断。
|
||||
核心逻辑:显式 kind / source.__export_kind__ 优先;否则按报表名含 receipt/outbound 推断。
|
||||
"""
|
||||
explicit = str(kind or "").strip().lower()
|
||||
if explicit in {"inventory", "receipt"}:
|
||||
if explicit in {"inventory", "inbound", "outbound"}:
|
||||
return explicit
|
||||
if isinstance(source, dict):
|
||||
flagged = str(source.get("__export_kind__") or "").strip().lower()
|
||||
if flagged in {"inventory", "receipt"}:
|
||||
if flagged in {"inventory", "inbound", "outbound"}:
|
||||
return flagged
|
||||
report = _dsv_report_name(source).casefold()
|
||||
if "receipt detail" in report:
|
||||
return "receipt"
|
||||
return "inbound"
|
||||
if "outbound" in report:
|
||||
return "outbound"
|
||||
return "inventory"
|
||||
|
||||
|
||||
def _dsv_body_markers_for_kind(kind: str) -> tuple[str, ...]:
|
||||
"""按 export_kind 返回结果正文标记;收料与库存字段列表分离。"""
|
||||
return _DSV_RECEIPT_BODY_MARKERS if kind == "receipt" else _DSV_INVENTORY_BODY_MARKERS
|
||||
"""按 export_kind 返回结果正文标记;入站/出站/库存字段列表分离。"""
|
||||
if kind == "inbound":
|
||||
return _DSV_INBOUND_BODY_MARKERS
|
||||
if kind == "outbound":
|
||||
return _DSV_OUTBOUND_BODY_MARKERS
|
||||
return _DSV_INVENTORY_BODY_MARKERS
|
||||
|
||||
|
||||
def _click_dsv_export_excel(page: Any, *, kind: str = "inventory") -> None:
|
||||
@@ -746,8 +765,8 @@ def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int, *, kind: str =
|
||||
f"frameIndex={frame_index}"
|
||||
)
|
||||
ready = bool(state["bodyReady"] and not state["asyncWait"])
|
||||
if export_kind == "receipt":
|
||||
# 收料:Export 工具栏或 Receipt Detail 正文均可作为就绪信号。
|
||||
if export_kind in {"inbound", "outbound"}:
|
||||
# 入站/出站:Export 工具栏或报表正文均可作为就绪信号(避免库存标记永远等不到)。
|
||||
ready = (not state["asyncWait"]) and (state["bodyReady"] or state["exportReady"])
|
||||
if ready:
|
||||
# #region debug-point H2:wait-report-ready
|
||||
@@ -1003,7 +1022,7 @@ def _ensure_dsv_inventory_rows_or_export_fallback(page: Any, *, report_name: str
|
||||
|
||||
|
||||
# Receipt Detail 明细行探针:表头看 External ASN / WMS Receipt / Qty Expected|Received,不用库存 Qty Available。
|
||||
_DSV_RECEIPT_DATA_ROWS_PROBE_JS = """
|
||||
_DSV_INBOUND_DATA_ROWS_PROBE_JS = """
|
||||
() => {
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
|
||||
const PARAMETER_ROOT_SELECTORS = [
|
||||
@@ -1102,56 +1121,56 @@ _DSV_RECEIPT_DATA_ROWS_PROBE_JS = """
|
||||
"""
|
||||
|
||||
|
||||
def _dsv_report_has_receipt_data_rows(page: Any) -> bool:
|
||||
def _dsv_report_has_inbound_data_rows(page: Any) -> bool:
|
||||
"""
|
||||
判断 Receipt Detail 结果页是否已出现收料明细行。
|
||||
判断 Receipt Detail 结果页是否已出现入站明细行。
|
||||
|
||||
核心逻辑:结构对齐库存行探针,但表头/明细字段用 External ASN、WMS Receipt、
|
||||
Qty Expected/Received 等收料列,禁止复用 Qty Available 库存判定。
|
||||
"""
|
||||
selected = _find_dsv_report_result_frame(page, kind="receipt")
|
||||
selected = _find_dsv_report_result_frame(page, kind="inbound")
|
||||
if selected is None:
|
||||
return False
|
||||
_frame_index, frame, _state = selected
|
||||
try:
|
||||
return bool(frame.evaluate(_DSV_RECEIPT_DATA_ROWS_PROBE_JS))
|
||||
return bool(frame.evaluate(_DSV_INBOUND_DATA_ROWS_PROBE_JS))
|
||||
except Exception as exc:
|
||||
print(f"[dsv-report] receipt data row probe failed: {exc}", file=sys.stderr)
|
||||
print(f"[dsv-report] inbound data row probe failed: {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def _wait_dsv_report_receipt_rows(page: Any, *, timeout_ms: int) -> bool:
|
||||
def _wait_dsv_report_inbound_rows(page: Any, *, timeout_ms: int) -> bool:
|
||||
"""条件轮询等待 Receipt Detail 明细行;超时返回 False,交由导出+Excel 判空。"""
|
||||
deadline = time.monotonic() + max(1.0, timeout_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if _dsv_report_has_receipt_data_rows(page):
|
||||
if _dsv_report_has_inbound_data_rows(page):
|
||||
return True
|
||||
time.sleep(1.0)
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_dsv_receipt_rows_or_export_fallback(page: Any, *, report_name: str) -> None:
|
||||
def _ensure_dsv_inbound_rows_or_export_fallback(page: Any, *, report_name: str) -> None:
|
||||
"""
|
||||
收料 DOM 有行则继续;无行重试一次 View Report,仍无行也不抛空——交给 Excel 判空。
|
||||
|
||||
核心逻辑:与库存兜底同构,但就绪等待与行探针均走 receipt kind。
|
||||
核心逻辑:与库存兜底同构,但就绪等待与行探针均走 inbound kind。
|
||||
"""
|
||||
row_wait_ms = min(_browser_timeout_ms(), 45_000)
|
||||
if _wait_dsv_report_receipt_rows(page, timeout_ms=row_wait_ms):
|
||||
if _wait_dsv_report_inbound_rows(page, timeout_ms=row_wait_ms):
|
||||
return
|
||||
|
||||
print(
|
||||
f"[dsv-report] receipt rows not visible after ready reportName={report_name!r}; "
|
||||
f"[dsv-report] inbound rows not visible after ready reportName={report_name!r}; "
|
||||
"retry View Report once",
|
||||
file=sys.stderr,
|
||||
)
|
||||
_click_dsv_view_report(page)
|
||||
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms(), kind="receipt")
|
||||
if _wait_dsv_report_receipt_rows(page, timeout_ms=row_wait_ms):
|
||||
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms(), kind="inbound")
|
||||
if _wait_dsv_report_inbound_rows(page, timeout_ms=row_wait_ms):
|
||||
return
|
||||
|
||||
print(
|
||||
f"[dsv-report] receipt rows still missing after View Report retry "
|
||||
f"[dsv-report] inbound rows still missing after View Report retry "
|
||||
f"reportName={report_name!r}; proceed to Excel export fallback",
|
||||
file=sys.stderr,
|
||||
)
|
||||
@@ -1728,8 +1747,11 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
|
||||
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms(), kind=export_kind)
|
||||
# [STEP 2] DOM 明细行仅作加速;无行时重试 View Report,仍无则继续导出,
|
||||
# 真空由落盘 Excel 判定(避免慢渲染假空 skip)。收料用 Receipt Detail 行探针。
|
||||
if export_kind == "receipt":
|
||||
_ensure_dsv_receipt_rows_or_export_fallback(page, report_name=report_name)
|
||||
if export_kind == "inbound":
|
||||
_ensure_dsv_inbound_rows_or_export_fallback(page, report_name=report_name)
|
||||
elif export_kind == "outbound":
|
||||
# 出站 DOM 列头未用实机确认:不走库存/收料行探针,真空由落盘 Excel 判定。
|
||||
pass
|
||||
else:
|
||||
_ensure_dsv_inventory_rows_or_export_fallback(page, report_name=report_name)
|
||||
except Exception as exc:
|
||||
@@ -1900,9 +1922,9 @@ wait_dsv_report_ready = _wait_dsv_report_ready
|
||||
dsv_report_has_inventory_data_rows = _dsv_report_has_inventory_data_rows
|
||||
wait_dsv_report_inventory_rows = _wait_dsv_report_inventory_rows
|
||||
ensure_dsv_inventory_rows_or_export_fallback = _ensure_dsv_inventory_rows_or_export_fallback
|
||||
dsv_report_has_receipt_data_rows = _dsv_report_has_receipt_data_rows
|
||||
wait_dsv_report_receipt_rows = _wait_dsv_report_receipt_rows
|
||||
ensure_dsv_receipt_rows_or_export_fallback = _ensure_dsv_receipt_rows_or_export_fallback
|
||||
dsv_report_has_inbound_data_rows = _dsv_report_has_inbound_data_rows
|
||||
wait_dsv_report_inbound_rows = _wait_dsv_report_inbound_rows
|
||||
ensure_dsv_inbound_rows_or_export_fallback = _ensure_dsv_inbound_rows_or_export_fallback
|
||||
dsv_export_kind = _dsv_export_kind
|
||||
dsv_body_markers_for_kind = _dsv_body_markers_for_kind
|
||||
fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed
|
||||
|
||||
@@ -3,10 +3,10 @@ scripts/freight_rpa/dsv_report_parameters.py
|
||||
|
||||
用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。
|
||||
依赖:Playwright Page/Frame;由 dsv_report_export.fill_report_parameters 委托调用。
|
||||
逻辑:识别 multi-value checkbox 与 ValidValue select,在 report iframe 内操作并等待控件启用;
|
||||
控件 ID 按报表名模板解析(含库存 3lv/JDA 与收料 Receipt Detail);
|
||||
同名报表可用 `报表名@program_label` 覆盖站点差异(如 Receipt Detail@AWSRTM → ctl29 multi_value);
|
||||
模板命中时整表替换默认控件,禁止默认 ctl17_ddValue 污染 multi_value 回退路径。
|
||||
逻辑:优先按 ParamLabelCell + label[for] / 行内控件形态现场派生(select 或 multi_value),
|
||||
ctlNN 禁止当主键;报表名模板仅作结构性解析失败时的回退;
|
||||
同名报表可用 `报表名@program_label` 覆盖站点差异(如 Receipt Detail@AWSRTM);
|
||||
Warehouse 禁止把过期 ctl*_txtValue 当文本兜底(会写进漂移后的 Project ID)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -79,6 +79,22 @@ _DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown",
|
||||
},
|
||||
},
|
||||
# Shipment Order Detail(AWS/Bison/AWSBI,2026-10-19 实机):Owner、Warehouse 均为
|
||||
# readonly txtValue + 下拉,不是库存默认 select。ctl 会漂移,填参时结构性解析优先,本表只作回退。
|
||||
"shipment order detail": {
|
||||
"Owner": {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
|
||||
},
|
||||
"Warehouse": {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl31_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl31_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl31_divDropDown",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -115,8 +131,10 @@ def resolve_parameter_controls(
|
||||
|
||||
|
||||
# 结构性解析脚本:在 SSRS 参数网格(ParametersGrid)中按 ParamLabelCell 标签定位参数行,
|
||||
# 从行内 _txtValue 的 id 基座派生 multi_value 三件套(_txtValue/_ctl01/_divDropDown)。
|
||||
# 再按 label[for] / 行内真实控件形态派生选择器(select 或 multi_value)。
|
||||
# 控件位(ctlNN)是随报表实例变化的实现细节,禁止在代码/配置中写死——一律由此派生。
|
||||
# [2026-10-20] Cincinnati CVG611:Warehouse=label[for]=ctl19_ddValue(原生 select),
|
||||
# 旧模板写死 ctl17_txtValue 已漂移为 Project ID,必须靠 for/行内 select 现场映射。
|
||||
_STRUCTURAL_CONTROLS_JS = """(label) => {
|
||||
const wanted = String(label || "").trim().toLowerCase();
|
||||
const rows = Array.from(document.querySelectorAll(
|
||||
@@ -126,35 +144,63 @@ _STRUCTURAL_CONTROLS_JS = """(label) => {
|
||||
if (!cell) continue;
|
||||
const text = (cell.innerText || cell.textContent || "").trim().toLowerCase();
|
||||
if (text !== wanted) continue;
|
||||
|
||||
// [STEP 1] label[for] → 真实控件(截图:Warehouse for=..._ctl19_ddValue)
|
||||
const labelEl = cell.querySelector("label[for]");
|
||||
const forId = labelEl && labelEl.getAttribute("for");
|
||||
if (forId) {
|
||||
const target = document.getElementById(forId);
|
||||
if (target) {
|
||||
const tag = String(target.tagName || "").toLowerCase();
|
||||
if (tag === "select" || forId.endsWith("_ddValue")) {
|
||||
return { control: "select", selector: "#" + forId };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// [STEP 2] 行内 ParamEntryCell 的原生 select(无 for 或 for 指向其它节点时)
|
||||
const entry = row.querySelector(".ParamEntryCell") || row;
|
||||
const select = entry.querySelector("select[id$='_ddValue'], select[id]");
|
||||
if (select && select.id) {
|
||||
return { control: "select", selector: "#" + select.id };
|
||||
}
|
||||
|
||||
// [STEP 3] multi_value:行内 _txtValue + _ctl01 + _divDropDown 三件套
|
||||
const txt = row.querySelector("[id$='_txtValue']");
|
||||
if (!txt || !txt.id) continue;
|
||||
const base = txt.id.replace(/_txtValue$/, "");
|
||||
const toggle = document.getElementById(base + "_ctl01");
|
||||
const dropdown = document.getElementById(base + "_divDropDown");
|
||||
if (!toggle || !dropdown) return null;
|
||||
return { text: "#" + base + "_txtValue", toggle: "#" + base + "_ctl01", dropdown: "#" + base + "_divDropDown" };
|
||||
if (toggle && dropdown) {
|
||||
return {
|
||||
control: "multi_value",
|
||||
text: "#" + base + "_txtValue",
|
||||
toggle: "#" + base + "_ctl01",
|
||||
dropdown: "#" + base + "_divDropDown",
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}"""
|
||||
|
||||
|
||||
def resolve_parameter_controls_structural(page: Any, label: str) -> dict[str, str] | None:
|
||||
"""按参数标签在 SSRS 参数网格中结构性解析 multi_value 控件三件套(免硬编码/免发版)。
|
||||
"""按参数标签在 SSRS 参数网格中结构性解析控件(select 或 multi_value,免硬编码 ctl)。
|
||||
|
||||
【AI 触发时机】:报表/站点的控件位未登记注册表模板时调用(如 Owner@Receipt
|
||||
Detail@AWSRTM);SSRS 参数行自带 ParamLabelCell 标签与 _txtValue/_ctl01/_divDropDown
|
||||
控件族,按标签定位行即可派生控件位,适配任意站点/报表,无需为每个站点改代码。
|
||||
【AI 触发时机】:填 Owner / Warehouse / PutawayZone 时优先调用;SSRS 参数行自带
|
||||
ParamLabelCell、label[for]、可选 data-parametername,按标签定位后映射真实控件,
|
||||
适配 ctl 编号漂移(如 Warehouse 从 ctl17 漂到 ctl19,旧 ctl17 变成 Project ID)。
|
||||
|
||||
核心逻辑:逐 frame 在 ParametersGrid 中找标签匹配的参数行 → 行内 _txtValue 的 id
|
||||
基座 → 校验 _ctl01/_divDropDown 存在 → 返回三件套;任一 frame 命中即返回,
|
||||
全部未命中(或命中但非 multi_value 形态)返回 None,由调用方回退默认/通用路径。
|
||||
核心逻辑:逐 frame 在 ParametersGrid 找标签匹配行 → 优先 label[for]/行内 select
|
||||
判为 select → 否则校验 multi_value 三件套 → 任一 frame 命中即返回;
|
||||
全部未命中返回 None,由调用方回退报表模板。
|
||||
|
||||
Args:
|
||||
page: Playwright Page(跨主文档与全部 frame 探测)。
|
||||
label: 参数名(与页面 ParamLabelCell 展示文本一致,如 Owner)。
|
||||
label: 参数名(与页面 ParamLabelCell 展示文本一致,如 Warehouse)。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: {text, toggle, dropdown} 三件套选择器;未命中为 None。
|
||||
dict[str, str]: 含 control=select|multi_value 及对应选择器;未命中为 None。
|
||||
"""
|
||||
wanted = str(label or "").strip()
|
||||
if not wanted or page is None:
|
||||
@@ -164,11 +210,71 @@ def resolve_parameter_controls_structural(page: Any, label: str) -> dict[str, st
|
||||
found = frame.evaluate(_STRUCTURAL_CONTROLS_JS, wanted)
|
||||
except Exception:
|
||||
continue # 跨域/已销毁帧等探测失败:换下一 frame
|
||||
if isinstance(found, dict) and found.get("text"):
|
||||
return {key: str(found[key]) for key in ("text", "toggle", "dropdown")}
|
||||
if not isinstance(found, dict):
|
||||
continue
|
||||
control = str(found.get("control") or "").strip()
|
||||
if control == "select" and found.get("selector"):
|
||||
return {"control": "select", "selector": str(found["selector"])}
|
||||
if control == "multi_value" and found.get("text"):
|
||||
return {
|
||||
"control": "multi_value",
|
||||
"text": str(found["text"]),
|
||||
"toggle": str(found.get("toggle") or ""),
|
||||
"dropdown": str(found.get("dropdown") or ""),
|
||||
}
|
||||
# 兼容旧脚本只返回三件套、无 control 字段的探测结果
|
||||
if found.get("text") and found.get("toggle") and found.get("dropdown"):
|
||||
return {
|
||||
"control": "multi_value",
|
||||
"text": str(found["text"]),
|
||||
"toggle": str(found["toggle"]),
|
||||
"dropdown": str(found["dropdown"]),
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def _apply_structural_parameter_fill(
|
||||
page: Any,
|
||||
label: str,
|
||||
text: str,
|
||||
values: list[str],
|
||||
*,
|
||||
timeout_ms: int,
|
||||
structural: dict[str, str],
|
||||
) -> bool:
|
||||
"""按结构性解析结果填充参数:select 走 ddValue,multi_value 走 checkbox 下拉。
|
||||
|
||||
Args:
|
||||
page: Playwright Page。
|
||||
label: 参数名。
|
||||
text: 原始填充文本(select 用)。
|
||||
values: 拆分后的目标值列表(multi_value 用)。
|
||||
timeout_ms: 操作超时。
|
||||
structural: resolve_parameter_controls_structural 的返回值。
|
||||
|
||||
Returns:
|
||||
bool: 是否填充成功。
|
||||
"""
|
||||
control = str(structural.get("control") or "").strip()
|
||||
if control == "select":
|
||||
selector = str(structural.get("selector") or "").strip()
|
||||
return bool(
|
||||
selector
|
||||
and _fill_select_parameter(page, label, text, selector, timeout_ms=timeout_ms)
|
||||
)
|
||||
if control == "multi_value" or all(structural.get(k) for k in ("text", "toggle", "dropdown")):
|
||||
return _fill_multi_value_parameter(
|
||||
page,
|
||||
label,
|
||||
values,
|
||||
timeout_ms=timeout_ms,
|
||||
config_override={"control": "multi_value", **{
|
||||
k: structural[k] for k in ("text", "toggle", "dropdown") if structural.get(k)
|
||||
}},
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def _iter_dsv_report_roots(page: Any) -> list[Any]:
|
||||
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
|
||||
matched: list[Any] = []
|
||||
@@ -630,9 +736,9 @@ def fill_dsv_filter_if_needed(
|
||||
"""
|
||||
按 ReportViewer 控件类型填充 DSV 报表参数。
|
||||
|
||||
核心逻辑:报表模板(report_name + program_label)命中时整表替换默认控件;
|
||||
multi_value(如 Receipt Detail@AWSRTM Warehouse=ctl29)优先勾选 checkbox,
|
||||
失败时只回退同模板 txtValue,禁止残留默认 ctl17_ddValue 误走库存 select。
|
||||
核心逻辑:Owner/Warehouse/PutawayZone 先按 ParamLabelCell + label[for] 现场派生
|
||||
(select 或 multi_value);失败再回退报表模板。Warehouse 禁止用写死 ctl*_txtValue
|
||||
做文本兜底——ctl 漂移后会写进 Project ID(2026-10-20 Cincinnati CVG611)。
|
||||
|
||||
Returns:
|
||||
bool: True 表示已填充或合法跳过(值为空/未配置控件);False 表示配置了值
|
||||
@@ -660,7 +766,17 @@ def fill_dsv_filter_if_needed(
|
||||
pass
|
||||
|
||||
timeout_ms = browser_timeout_ms()
|
||||
# 报表模板优先:同一参数名在不同报表/站点的控件长相不同(3lv select vs JDA/AWSRTM multi_value)。
|
||||
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
|
||||
# [STEP 0] Owner / Warehouse / PutawayZone:按标签 + label[for] 现场派生控件类型与选择器。
|
||||
# Cincinnati CVG611 实机 Warehouse=ctl19_ddValue(select),旧 JDA 模板 ctl17 已是 Project ID。
|
||||
if label in {"Owner", "Warehouse", "PutawayZone"}:
|
||||
structural = resolve_parameter_controls_structural(page, label)
|
||||
if structural and _apply_structural_parameter_fill(
|
||||
page, label, text, values, timeout_ms=timeout_ms, structural=structural,
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return True
|
||||
# 报表模板回退:同一参数名在不同报表/站点的控件长相不同(3lv select vs JDA/AWSRTM multi_value)。
|
||||
# [STEP] 模板命中时整表替换默认控件,禁止 update 残留默认 Warehouse.selector=ctl17_ddValue;
|
||||
# 否则 multi_value 偶发未就绪时会误走库存默认 select(AWSRTM Receipt Detail 2026-09-29)。
|
||||
template_controls = resolve_parameter_controls(
|
||||
@@ -682,8 +798,6 @@ def fill_dsv_filter_if_needed(
|
||||
_debug(f"filter-no-selector-{label.lower()}", text)
|
||||
return True
|
||||
|
||||
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
|
||||
|
||||
# [STEP 1] 模板登记为 multi_value(或 Owner/PutawayZone 固有多选)时,优先走 checkbox 下拉填充。
|
||||
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
|
||||
if _fill_multi_value_parameter(
|
||||
@@ -692,7 +806,7 @@ def fill_dsv_filter_if_needed(
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return True
|
||||
|
||||
# [STEP 2] 仅当控件类型确认为 select 时走 ddValue;禁止用 endswith(ddValue) 盖过 multi_value。
|
||||
# [STEP 2] 模板确认为 select,或结构性已确认是 select 但 STEP 0 未就绪时再试 ddValue。
|
||||
if defaults.get("control") == "select":
|
||||
select_selector = custom_selector or defaults.get("selector", "")
|
||||
if select_selector and _fill_select_parameter(
|
||||
@@ -700,8 +814,33 @@ def fill_dsv_filter_if_needed(
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return True
|
||||
# 模板误判为 multi_value(如 JDA 模板套到 Cincinnati select 页)时:再做一次结构性 select。
|
||||
if label == "Warehouse":
|
||||
structural_retry = resolve_parameter_controls_structural(page, label)
|
||||
if (
|
||||
structural_retry
|
||||
and structural_retry.get("control") == "select"
|
||||
and _apply_structural_parameter_fill(
|
||||
page, label, text, values, timeout_ms=timeout_ms, structural=structural_retry,
|
||||
)
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return True
|
||||
# [STEP 3 禁区] Warehouse 禁止用写死/漂移的 *_txtValue 文本兜底(会写进 Project ID)。
|
||||
print(
|
||||
f"[dsv-filter] {label} control probe: "
|
||||
f"{json.dumps(_probe_report_parameter_controls(page), ensure_ascii=False)[:1500]}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(
|
||||
f"[dsv] failed to fill {label} filter text={text!r}; "
|
||||
"refusing stale txtValue fallback",
|
||||
file=sys.stderr,
|
||||
)
|
||||
_debug(f"filter-failed-{label.lower()}", text)
|
||||
return False
|
||||
|
||||
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
|
||||
# [STEP 3] 文本输入/脚本兜底:仅用于非 Warehouse 的普通文本参数与多选输入框。
|
||||
if not selector:
|
||||
print(
|
||||
f"[dsv-filter] {label} control probe: "
|
||||
@@ -757,14 +896,19 @@ def fill_dsv_multi_select_parameter(
|
||||
核心逻辑:selectors 缺省时**优先按参数标签结构性解析控件位**——SSRS 参数控件的
|
||||
ctl 编号每次渲染都会漂移(2026-10-08 实测:昨夜登记的 ctl29 今日漂移为 Project ID,
|
||||
RTM 被写进错误栏位),任何 ctl 编号注册条目都不可靠;结构性解析失败才回退
|
||||
报表模板/默认表。两者都没有则返回 False。
|
||||
报表模板/默认表。结构性命中但形态是 select(非 multi_value)时返回 False,
|
||||
由调用方走 fill_dsv_filter_if_needed 的 select 路径。
|
||||
"""
|
||||
config_override = {"control": "multi_value"}
|
||||
effective_selectors = selectors or (
|
||||
resolve_parameter_controls_structural(page, label)
|
||||
or resolve_parameter_controls(report_name, label, program_label=program_label)
|
||||
or None
|
||||
)
|
||||
effective_selectors = selectors
|
||||
if not effective_selectors:
|
||||
structural = resolve_parameter_controls_structural(page, label)
|
||||
if structural and structural.get("control") == "select":
|
||||
return False
|
||||
effective_selectors = structural or (
|
||||
resolve_parameter_controls(report_name, label, program_label=program_label)
|
||||
or None
|
||||
)
|
||||
if effective_selectors:
|
||||
for key in ("text", "toggle", "dropdown"):
|
||||
value = str(effective_selectors.get(key) or "").strip()
|
||||
|
||||
@@ -16,11 +16,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
+7
-7
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
scripts/freight_rpa/receipt/receipt_crane_export.py
|
||||
scripts/freight_rpa/inbound/inbound_crane_export.py
|
||||
|
||||
用途:Crane 收料报表导出适配器——固定 Inbound Details,委托共享 crane_report_export。
|
||||
依赖:crane_report_export、crane_session。
|
||||
逻辑:receipt_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
|
||||
逻辑:inbound_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
|
||||
driver 在 Playwright 未返回 Download 时做目录兜底。
|
||||
"""
|
||||
|
||||
@@ -15,11 +15,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -35,11 +35,11 @@ def _inbound_details_entry_url(login_url: str) -> str:
|
||||
"""将复用的 Crane Profile 登录地址固定到收料 Inbound Details 路由。"""
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise RuntimeError('Crane receipt unit requires an absolute login_url')
|
||||
raise RuntimeError('Crane inbound unit requires an absolute login_url')
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, '/inbound-details-query'))
|
||||
|
||||
|
||||
def export_receipt_report(
|
||||
def export_inbound_report(
|
||||
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
|
||||
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
|
||||
) -> Any:
|
||||
@@ -51,7 +51,7 @@ def export_receipt_report(
|
||||
"""
|
||||
report_path = dict(unit.get('report_path_json') or {})
|
||||
if str(report_path.get('report_name') or '').strip() != 'Inbound Details':
|
||||
raise RuntimeError('Crane receipt report must be Inbound Details')
|
||||
raise RuntimeError('Crane inbound report must be Inbound Details')
|
||||
entry_url = _inbound_details_entry_url(str(unit.get('login_url') or '').strip())
|
||||
if first_in_profile:
|
||||
page.goto(entry_url, wait_until='domcontentloaded', timeout=browser_timeout_ms)
|
||||
+10
-10
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
scripts/freight_rpa/receipt/receipt_dbs_export.py
|
||||
scripts/freight_rpa/inbound/inbound_dbs_export.py
|
||||
|
||||
用途:DBS 收料报表导出适配器——把 unit 转成与库存同构的 DSV source,再委托共享导出驱动。
|
||||
依赖:connectors/dsv/dsv_report_export。
|
||||
逻辑:receipt_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
|
||||
逻辑:inbound_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
|
||||
调用 prepare_dsv_batch_export_step 完成;本模块只负责 source 组装与单次导出。
|
||||
source 写入 __export_kind__=receipt,共享驱动用 Receipt Detail 就绪/行探针。
|
||||
source 写入 __export_kind__=inbound,共享驱动用 Receipt Detail 就绪/行探针。
|
||||
query_parameters 原样下发;仅当 unit.warehouse_id 有值时追加单值 Warehouse
|
||||
(兼容旧 trigger);空条件表示使用页面默认,不强制 Warehouse。
|
||||
"""
|
||||
@@ -18,11 +18,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -32,7 +32,7 @@ from typing import Any
|
||||
import dsv_report_export
|
||||
|
||||
|
||||
def build_receipt_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
|
||||
def build_inbound_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
将收料 unit 组装为共享 dsv_report_export 可消费的 source。
|
||||
|
||||
@@ -55,7 +55,7 @@ def build_receipt_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[st
|
||||
'parameters': list(unit.get('query_parameters_json') or []),
|
||||
'__download_dir': str(unit.get('__download_dir') or ''),
|
||||
# 显式标记收料导出:共享 dsv_report_export 用 Receipt Detail 就绪/行探针,不用库存字段。
|
||||
'__export_kind__': 'receipt',
|
||||
'__export_kind__': 'inbound',
|
||||
}
|
||||
# 兼容旧 trigger:仅当排程曾写入 warehouse_id 时追加,避免与参数里已有 Warehouse 双写需由旧载荷保证互斥。
|
||||
warehouse_id = str(unit.get('warehouse_id') or '').strip()
|
||||
@@ -67,7 +67,7 @@ def build_receipt_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[st
|
||||
return source
|
||||
|
||||
|
||||
def export_receipt_report(
|
||||
def export_inbound_report(
|
||||
page: Any,
|
||||
unit: dict[str, Any],
|
||||
*,
|
||||
@@ -90,10 +90,10 @@ def export_receipt_report(
|
||||
Returns:
|
||||
Playwright Download 对象。
|
||||
"""
|
||||
source = build_receipt_dsv_source(unit, entry_url=entry_url)
|
||||
source = build_inbound_dsv_source(unit, entry_url=entry_url)
|
||||
return dsv_report_export.export_dsv_inventory_source(
|
||||
page,
|
||||
{'action': 'receipt_export_batch'},
|
||||
{'action': 'inbound_export_batch'},
|
||||
source,
|
||||
skip_navigation=skip_navigation,
|
||||
)
|
||||
+12
-12
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
scripts/freight_rpa/receipt/receipt_excel_empty.py
|
||||
scripts/freight_rpa/inbound/inbound_excel_empty.py
|
||||
|
||||
用途:收料 Excel「有表头无明细」判空(真相源,对齐库存 Excel 判空)。
|
||||
依赖:openpyxl(运行期可选;缺失时不强制 empty)。
|
||||
逻辑:receipt_rpa_worker 落盘校验后调用;标题行(如 AWS Receipt Detail)
|
||||
逻辑:inbound_rpa_worker 落盘校验后调用;标题行(如 AWS Receipt Detail)
|
||||
不得当成表头,否则真表头会被误判为明细导致假 success。
|
||||
"""
|
||||
|
||||
@@ -12,8 +12,8 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class NoReceiptDataError(RuntimeError):
|
||||
"""收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。"""
|
||||
class NoInboundDataError(RuntimeError):
|
||||
"""入站报表可打开且有表头,但无业务明细行(合法 empty / no_inbound_data)。"""
|
||||
|
||||
|
||||
def _normalize_row_joined(row: tuple | list) -> str:
|
||||
@@ -32,7 +32,7 @@ def _normalize_row_joined(row: tuple | list) -> str:
|
||||
return ' | '.join(parts)
|
||||
|
||||
|
||||
def is_receipt_excel_header_row(joined: str) -> bool:
|
||||
def is_inbound_excel_header_row(joined: str) -> bool:
|
||||
"""
|
||||
判断是否为收料列标题行(非报表标题行)。
|
||||
|
||||
@@ -55,7 +55,7 @@ def is_receipt_excel_header_row(joined: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def receipt_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
def inbound_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
"""
|
||||
判断收料 Excel 列标题之后是否有明细行。
|
||||
|
||||
@@ -83,7 +83,7 @@ def receipt_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
if not joined:
|
||||
continue
|
||||
if header_idx is None:
|
||||
if is_receipt_excel_header_row(joined):
|
||||
if is_inbound_excel_header_row(joined):
|
||||
header_idx = idx
|
||||
continue
|
||||
if idx > header_idx:
|
||||
@@ -95,12 +95,12 @@ def receipt_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def enforce_receipt_excel_not_empty(path: Path) -> None:
|
||||
def enforce_inbound_excel_not_empty(path: Path) -> None:
|
||||
"""
|
||||
有表头无明细时记为无收料(NoReceiptDataError → empty / no_receipt_data)。
|
||||
有表头无明细时记为无入站(NoInboundDataError → empty / no_inbound_data)。
|
||||
|
||||
Raises:
|
||||
NoReceiptDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。
|
||||
NoInboundDataError: 可识别表头但无业务行;message 固定为 no_inbound_data。
|
||||
"""
|
||||
if receipt_excel_has_detail_rows(path) is False:
|
||||
raise NoReceiptDataError('no_receipt_data')
|
||||
if inbound_excel_has_detail_rows(path) is False:
|
||||
raise NoInboundDataError('no_inbound_data')
|
||||
+152
-107
@@ -1,12 +1,14 @@
|
||||
"""
|
||||
scripts/freight_rpa/receipt/receipt_rpa_worker.py
|
||||
scripts/freight_rpa/inbound/inbound_rpa_worker.py
|
||||
|
||||
用途:独立货代收料 RPA Worker——仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。
|
||||
用途:独立货代收料 RPA Worker——仅消费 inbound trigger,不触及库存 Worker 的目录或 callback。
|
||||
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
|
||||
receipt_excel_empty、receipt_dbs_export、receipt_crane_export、connectors/dsv/dsv_report_export。
|
||||
逻辑:排程写入 receipt trigger → 本进程领取并按 connector/profile 分组串行导出 →
|
||||
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_receipt_data;
|
||||
inbound_excel_empty、inbound_dbs_export、inbound_crane_export、connectors/dsv/dsv_report_export。
|
||||
逻辑:排程写入 inbound trigger → 本进程领取并按 connector/profile 分组串行导出 →
|
||||
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_inbound_data;
|
||||
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
|
||||
批级失败(如 launch_persistent_context 浏览器已关)须对本组未终态单元逐笔
|
||||
failed 回调,否则后端单元永久 awaiting_rpa、来源投影永久 fetching。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,11 +33,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -43,23 +45,29 @@ if _RPA_ROOT is not None:
|
||||
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file # noqa: E402
|
||||
import rpa_callbacks # noqa: E402
|
||||
from rpa_callbacks import ( # noqa: E402
|
||||
INBOUND_BATCH_PROGRESS,
|
||||
INBOUND_BATCH_READY,
|
||||
INBOUND_UNIT_PROGRESS,
|
||||
)
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_logging # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
|
||||
import dsv_report_export # noqa: E402
|
||||
import receipt_crane_export # noqa: E402
|
||||
import receipt_dbs_export # noqa: E402
|
||||
from receipt_excel_empty import ( # noqa: E402
|
||||
NoReceiptDataError,
|
||||
enforce_receipt_excel_not_empty as _enforce_receipt_excel_not_empty,
|
||||
import inbound_crane_export # noqa: E402
|
||||
import inbound_dbs_export # noqa: E402
|
||||
from inbound_excel_empty import ( # noqa: E402
|
||||
NoInboundDataError,
|
||||
enforce_inbound_excel_not_empty as _enforce_inbound_excel_not_empty,
|
||||
)
|
||||
|
||||
_EXPORT_UNIT_MAX_ATTEMPTS = 2
|
||||
_EXPORT_UNIT_RETRY_WAIT_SECONDS = 30
|
||||
_RECEIPT_EXCEL_MIN_BYTES = 512
|
||||
# 结构校验可用较宽标记;「有表头无明细」判空见 receipt_excel_empty(禁止用单字 receipt 当表头)。
|
||||
_RECEIPT_EXCEL_HEADER_MARKERS = (
|
||||
_INBOUND_EXCEL_MIN_BYTES = 512
|
||||
# 结构校验可用较宽标记;「有表头无明细」判空见 inbound_excel_empty(禁止用单字 receipt 当表头)。
|
||||
_INBOUND_EXCEL_HEADER_MARKERS = (
|
||||
'receipt',
|
||||
'inbound',
|
||||
'asn',
|
||||
@@ -87,7 +95,7 @@ def _mask_secret(value: str | None) -> str:
|
||||
|
||||
|
||||
def _require_dir(variable: str) -> Path:
|
||||
"""读取 receipt 专用目录;不回退至库存共享路径。"""
|
||||
"""读取 inbound 专用目录;不回退至 onhand 共享路径。"""
|
||||
value = env(variable)
|
||||
if not value:
|
||||
raise SystemExit(f'Missing env: {variable}')
|
||||
@@ -99,51 +107,44 @@ def _require_dir(variable: str) -> Path:
|
||||
|
||||
|
||||
def _post_rpa(path: str, payload: dict[str, Any], *, timeout: int = 30) -> None:
|
||||
"""向 HXOPS 收料 RPA API 上报;认证密钥从进程 Secret 注入。"""
|
||||
key = env('SHIPPING_NOTICE_TOOL_API_KEY') or env('INTEGRATION_API_KEY')
|
||||
if not key:
|
||||
raise RuntimeError('Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY')
|
||||
base = env('HXOPS_API_BASE', 'http://127.0.0.1:5052').rstrip('/')
|
||||
request = urllib.request.Request(
|
||||
f'{base}{path}',
|
||||
data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), method='POST',
|
||||
headers={'Content-Type': 'application/json', 'X-Integration-Key': key},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
if response.status < 200 or response.status >= 300:
|
||||
raise RuntimeError(f'receipt rpa callback failed: HTTP {response.status} path={path}')
|
||||
"""向 HXOPS 入站(原收料)RPA 回调 API 上报(薄封装,统一走 /api/freight-rpa/*)。
|
||||
|
||||
核心逻辑:鉴权、脱敏日志与 HTTP 错误处理收拢到 common/rpa_callbacks.post_callback;
|
||||
保留 (path, payload, timeout) 签名,便于测试 monkeypatch 与既有调用点零改动。
|
||||
"""
|
||||
rpa_callbacks.post_callback(path, payload, timeout=timeout)
|
||||
|
||||
|
||||
def _post_callback(payload: dict[str, Any]) -> None:
|
||||
"""向独立收料 callback 上报一个单元终态结果。"""
|
||||
_post_rpa('/api/shipping-notice/rpa/receipt-batch-ready', payload)
|
||||
_post_rpa(INBOUND_BATCH_READY, payload)
|
||||
|
||||
|
||||
def _mark_unit_processing(unit: dict[str, Any]) -> None:
|
||||
"""开始导出前标记 processing;失败不影响导出主链路。"""
|
||||
try:
|
||||
_post_rpa(
|
||||
'/api/shipping-notice/rpa/receipt-unit-progress',
|
||||
INBOUND_UNIT_PROGRESS,
|
||||
{
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.get('callback_id'),
|
||||
'status': 'processing',
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f'[receipt-unit] processing progress failed: {exc}', file=_sys.stderr)
|
||||
print(f'[inbound-unit] processing progress failed: {exc}', file=_sys.stderr)
|
||||
|
||||
|
||||
def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
|
||||
"""每完成一笔导出回传累计进度(对齐库存 inventory-batch-progress)。"""
|
||||
"""每完成一笔导出回传累计进度(对齐 onhand-batch-progress)。"""
|
||||
schedule_run_id = body.get('schedule_run_id')
|
||||
if schedule_run_id is None:
|
||||
return
|
||||
try:
|
||||
_post_rpa(
|
||||
'/api/shipping-notice/rpa/receipt-batch-progress',
|
||||
INBOUND_BATCH_PROGRESS,
|
||||
{
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'schedule_run_id': schedule_run_id,
|
||||
'batch_run_no': body.get('batch_run_no') or body.get('run_no'),
|
||||
'success_count': int(counts.get('success') or 0),
|
||||
@@ -152,7 +153,7 @@ def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f'[receipt-batch] progress callback failed: {exc}', file=_sys.stderr)
|
||||
print(f'[inbound-batch] progress callback failed: {exc}', file=_sys.stderr)
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -213,7 +214,7 @@ def _session_profile_dir(connector_type: str, profile_code: str = '') -> Path:
|
||||
按 connector + RPA Profile 隔离的持久收料会话目录。
|
||||
|
||||
核心逻辑:形如 `{connector}__{profile_code}_session`(dbs/crane 与库存 dsv360/crane_footprint
|
||||
命名空间分离,避免串 Cookie);禁止所有收料源共用单一 receipt_session。
|
||||
命名空间分离,避免串 Cookie);禁止所有收料源共用单一 inbound_session。
|
||||
"""
|
||||
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
|
||||
connector = _sanitize_profile_dir_segment(connector_type or 'unknown')
|
||||
@@ -228,15 +229,15 @@ def _open_browser(
|
||||
connector_type: str = '',
|
||||
profile_code: str = '',
|
||||
):
|
||||
"""为一个 receipt Profile 分组创建浏览器上下文,组内登录一次、串行导出。
|
||||
"""为一个 inbound Profile 分组创建浏览器上下文,组内登录一次、串行导出。
|
||||
|
||||
reuse_session=True 且 SESSION_REUSE 开启:持久 `{connector}__{profile}_session`;
|
||||
否则一次性临时 Profile(receipt_* 前缀),批次结束即删。
|
||||
否则一次性临时 Profile(inbound_* 前缀),批次结束即删。
|
||||
"""
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('Playwright is required for real receipt RPA') from exc
|
||||
raise RuntimeError('Playwright is required for real inbound RPA') from exc
|
||||
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
|
||||
use_reused = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
|
||||
if use_reused:
|
||||
@@ -244,7 +245,7 @@ def _open_browser(
|
||||
runtime_profile.mkdir(parents=True, exist_ok=True)
|
||||
profile_mode = 'session_reuse'
|
||||
else:
|
||||
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
|
||||
runtime_profile = Path(tempfile.mkdtemp(prefix='inbound_', dir=str(profile_root)))
|
||||
profile_mode = 'temporary'
|
||||
print(
|
||||
f'[browser] profile_mode={profile_mode} connector={connector_type or "-"} '
|
||||
@@ -285,7 +286,7 @@ def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
|
||||
try:
|
||||
current_page.close()
|
||||
except Exception as exc:
|
||||
print(f'[receipt-batch] close previous page failed: {exc}', file=_sys.stderr)
|
||||
print(f'[inbound-batch] close previous page failed: {exc}', file=_sys.stderr)
|
||||
return next_page
|
||||
|
||||
|
||||
@@ -328,7 +329,7 @@ def _persist_download_to_dest(
|
||||
if not _is_playwright_target_closed_error(exc):
|
||||
raise
|
||||
print(
|
||||
f'[receipt-artifact] stage=download_save status=fallback '
|
||||
f'[inbound-artifact] stage=download_save status=fallback '
|
||||
f'reason=browser_closed path={dest.name!r}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
@@ -342,7 +343,7 @@ def _persist_download_to_dest(
|
||||
artifact.save_as(str(dest))
|
||||
|
||||
|
||||
def _receipt_download_name(
|
||||
def _inbound_download_name(
|
||||
batch_run_no: str,
|
||||
source_code: str,
|
||||
warehouse_id: str | None,
|
||||
@@ -352,7 +353,7 @@ def _receipt_download_name(
|
||||
"""
|
||||
收料落盘文件名,对齐库存 `_batch_download_name`。
|
||||
|
||||
核心逻辑:`receipt_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
|
||||
核心逻辑:`inbound_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
|
||||
不写入 callback_id(关联仍靠 callback JSON)。
|
||||
|
||||
Args:
|
||||
@@ -364,11 +365,11 @@ def _receipt_download_name(
|
||||
Returns:
|
||||
安全化后的文件名(不含目录)。
|
||||
"""
|
||||
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'receipt'
|
||||
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'inbound'
|
||||
safe_source = ''.join(ch for ch in str(source_code or '') if ch.isalnum() or ch in {'-', '_'}) or 'UNKNOWN'
|
||||
safe_wh = ''.join(ch for ch in str(warehouse_id or '') if ch.isalnum() or ch in {'-', '_'}) or 'NA'
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')
|
||||
return f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
|
||||
return f'inbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
|
||||
|
||||
|
||||
def _save_download(
|
||||
@@ -381,14 +382,14 @@ def _save_download(
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> Path:
|
||||
"""
|
||||
保存本单元下载文件到 receipt drop;必要时在浏览器关闭后走目录兜底。
|
||||
保存本单元下载文件到 inbound drop;必要时在浏览器关闭后走目录兜底。
|
||||
|
||||
核心逻辑:按 run+source(+仓) 命名后 `_persist_download_to_dest`;空文件拒绝。
|
||||
"""
|
||||
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
|
||||
if suffix != '.xlsx':
|
||||
raise RuntimeError('receipt report download must be xlsx')
|
||||
target = drop_dir / _receipt_download_name(
|
||||
raise RuntimeError('inbound report download must be xlsx')
|
||||
target = drop_dir / _inbound_download_name(
|
||||
batch_run_no,
|
||||
str(unit.get('source_code') or ''),
|
||||
unit.get('warehouse_id'),
|
||||
@@ -402,24 +403,24 @@ def _save_download(
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if target.stat().st_size <= 0:
|
||||
raise RuntimeError('receipt report download is empty')
|
||||
raise RuntimeError('inbound report download is empty')
|
||||
return target
|
||||
|
||||
|
||||
def _validate_receipt_excel(path: Path) -> None:
|
||||
def _validate_inbound_excel(path: Path) -> None:
|
||||
"""
|
||||
校验收料 Excel 可打开且具备报表基本结构。
|
||||
|
||||
核心逻辑:对齐库存 `_validate_inventory_excel`——拒过小/HTML 伪装文件;
|
||||
核心逻辑:对齐 onhand `_validate_onhand_excel`——拒过小/HTML 伪装文件;
|
||||
前几行或 sheet 标题须含收料报表特征,避免错误页当 success 归档。
|
||||
"""
|
||||
size = path.stat().st_size
|
||||
if size < _RECEIPT_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f'downloaded receipt Excel is too small ({size} bytes)')
|
||||
if size < _INBOUND_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f'downloaded inbound Excel is too small ({size} bytes)')
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('openpyxl required to validate receipt Excel') from exc
|
||||
raise RuntimeError('openpyxl required to validate inbound Excel') from exc
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception as exc:
|
||||
@@ -435,9 +436,9 @@ def _validate_receipt_excel(path: Path) -> None:
|
||||
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 _RECEIPT_EXCEL_HEADER_MARKERS):
|
||||
if not any(marker in haystack for marker in _INBOUND_EXCEL_HEADER_MARKERS):
|
||||
if 'receipt' not in title and 'inbound' not in title:
|
||||
raise RuntimeError('downloaded file is not valid Excel: missing receipt report headers')
|
||||
raise RuntimeError('downloaded file is not valid Excel: missing inbound report headers')
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
@@ -446,29 +447,56 @@ def _validate_unit(unit: dict[str, Any]) -> None:
|
||||
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
|
||||
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
|
||||
if not str(unit.get(key) or '').strip():
|
||||
raise RuntimeError(f'receipt unit missing {key}')
|
||||
raise RuntimeError(f'inbound unit missing {key}')
|
||||
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
|
||||
raise RuntimeError('unsupported receipt connector_type')
|
||||
raise RuntimeError('unsupported inbound connector_type')
|
||||
parameters = list(unit.get('query_parameters_json') or [])
|
||||
if any('date' in str(row.get('name') or '').lower() for row in parameters if isinstance(row, dict)):
|
||||
raise RuntimeError('receipt date filtering is forbidden')
|
||||
raise RuntimeError('inbound date filtering is forbidden')
|
||||
|
||||
|
||||
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
|
||||
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
|
||||
print(f'[receipt-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
|
||||
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
print(f'[inbound-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
|
||||
_post_callback({'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.INBOUND_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
|
||||
|
||||
def _report_empty(unit: dict[str, Any], exc: NoReceiptDataError) -> None:
|
||||
"""无业务明细的合法结果:回调 empty + no_receipt_data(后端 finalize 计 skipped)。"""
|
||||
print(f'[receipt-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
|
||||
def _report_group_open_failure(group: list[dict[str, Any]], exc: Exception) -> None:
|
||||
"""批级浏览器打开/组级异常时,为组内全部单元补发 failed 回调。
|
||||
|
||||
用途:``_open_browser`` 在进入单元循环前失败时,原先只把 trigger 归档到 failed/
|
||||
而不回调 → 后端单元永久 awaiting_rpa、来源选择卡永久「抓取中」且批量重试锁死
|
||||
(须等 FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 孤儿回收)。本函数 best-effort 逐笔
|
||||
``_report_failure``,单笔回调失败只打日志不中断其余。
|
||||
|
||||
Args:
|
||||
group: 同一 connector/profile/login 下尚未进入终态回调的单元列表。
|
||||
exc: 批级异常(通常为 Playwright TargetClosed / launch_persistent_context)。
|
||||
"""
|
||||
print(
|
||||
f'[inbound-batch] open/group failed; reporting {len(group)} unit failure callback(s): '
|
||||
f'{str(exc)[:200]}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
for unit in group:
|
||||
try:
|
||||
_report_failure(unit, exc)
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[inbound-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def _report_empty(unit: dict[str, Any], exc: NoInboundDataError) -> None:
|
||||
"""无业务明细的合法结果:回调 empty + no_inbound_data(后端 finalize 计 skipped)。"""
|
||||
print(f'[inbound-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
|
||||
_post_callback({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.get('callback_id'),
|
||||
'status': 'empty',
|
||||
'error_code': 'no_receipt_data',
|
||||
'error_message': str(exc)[:2000] or 'no_receipt_data',
|
||||
'error_code': 'no_inbound_data',
|
||||
'error_message': str(exc)[:2000] or 'no_inbound_data',
|
||||
})
|
||||
|
||||
|
||||
@@ -505,12 +533,12 @@ def _export_unit_download(
|
||||
"""
|
||||
unit['__download_dir'] = str(drop_dir)
|
||||
if connector == 'dbs':
|
||||
source = receipt_dbs_export.build_receipt_dsv_source(unit, entry_url=login_url)
|
||||
source = inbound_dbs_export.build_inbound_dsv_source(unit, entry_url=login_url)
|
||||
# 重试尝试强制完整重导航:不携带前一单元上下文,prepare 从入口页重选菜单进报表。
|
||||
force_full_navigation = attempt > 1
|
||||
previous_unit = group[index - 1] if (index > 0 and not force_full_navigation) else None
|
||||
previous_source = (
|
||||
receipt_dbs_export.build_receipt_dsv_source(previous_unit, entry_url=login_url)
|
||||
inbound_dbs_export.build_inbound_dsv_source(previous_unit, entry_url=login_url)
|
||||
if previous_unit is not None else None
|
||||
)
|
||||
skip_navigation = False
|
||||
@@ -528,7 +556,7 @@ def _export_unit_download(
|
||||
if any(token in message for token in ('invalid', 'verification')):
|
||||
raise
|
||||
print(
|
||||
f'[receipt-batch] dbs prepare failed for {unit.get("source_code")}, '
|
||||
f'[inbound-batch] dbs prepare failed for {unit.get("source_code")}, '
|
||||
f'retry with clean page: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
@@ -538,7 +566,7 @@ def _export_unit_download(
|
||||
page, login_url, None, source, index=0,
|
||||
)
|
||||
)
|
||||
download = receipt_dbs_export.export_receipt_report(
|
||||
download = inbound_dbs_export.export_inbound_report(
|
||||
page, unit, entry_url=login_url, skip_navigation=skip_navigation,
|
||||
)
|
||||
return download, page
|
||||
@@ -546,7 +574,7 @@ def _export_unit_download(
|
||||
# Crane 重试尝试同样强制完整重登导航(first_in_profile=True 走首源完整登录)。
|
||||
first_in_profile = index == 0 or attempt > 1
|
||||
try:
|
||||
download = receipt_crane_export.export_receipt_report(
|
||||
download = inbound_crane_export.export_inbound_report(
|
||||
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
|
||||
select_or_fill=select_or_fill, click_text=click_text,
|
||||
first_in_profile=first_in_profile,
|
||||
@@ -557,12 +585,12 @@ def _export_unit_download(
|
||||
if not _is_login_session_error(exc):
|
||||
raise
|
||||
print(
|
||||
f'[receipt-batch] crane session failed for {unit.get("source_code")}, '
|
||||
f'[inbound-batch] crane session failed for {unit.get("source_code")}, '
|
||||
f'retry with clean page: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
download = receipt_crane_export.export_receipt_report(
|
||||
download = inbound_crane_export.export_inbound_report(
|
||||
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
|
||||
select_or_fill=select_or_fill, click_text=click_text,
|
||||
first_in_profile=True,
|
||||
@@ -570,7 +598,7 @@ def _export_unit_download(
|
||||
return download, page
|
||||
|
||||
|
||||
def _write_mock_receipt_excel(path: Path) -> None:
|
||||
def _write_mock_inbound_excel(path: Path) -> None:
|
||||
"""Mock 模式写出带表头+一行明细的合法收料 Excel,便于走校验与 success 回调。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
@@ -584,13 +612,13 @@ def _write_mock_receipt_excel(path: Path) -> None:
|
||||
|
||||
|
||||
def _post_unit_ready(unit: dict[str, Any], output: Path) -> None:
|
||||
"""落盘成功后上报 receipt-batch-ready(归档);调用方须放在导出重试之外。
|
||||
"""落盘成功后上报 inbound-batch-ready(归档);调用方须放在导出重试之外。
|
||||
|
||||
file_path 契约为「drop 根内文件名」:Worker(Windows)与后端(Linux 挂载根)分属
|
||||
两机、根路径不同,后端按自身挂载根拼接定位(跨机部署下发本机绝对路径必 400)。
|
||||
"""
|
||||
_post_callback({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit['callback_id'],
|
||||
'status': 'success',
|
||||
'file_path': output.name,
|
||||
@@ -605,25 +633,29 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
|
||||
核心逻辑:DBS 与库存对齐——同 Profile 组内复用同一 tab;导出失败批次内最多重试 2 次,
|
||||
**重试只覆盖导出/落盘/校验**(对齐库存 record_result 前段)。落盘成功后先轻量
|
||||
``receipt-batch-progress``(管理端实时笔数),再调 ``receipt-batch-ready`` 归档;
|
||||
``inbound-batch-progress``(管理端实时笔数),再调 ``inbound-batch-ready`` 归档;
|
||||
ready/empty/failed 回调失败不得触发重新下载(2026-09-28 偶发同源双文件根因)。
|
||||
批级异常(浏览器 launch 失败等)经 ``_report_group_open_failure`` 给未终态单元
|
||||
补 failed 回调,禁止只归档 trigger 却让后端单元永久 awaiting_rpa。
|
||||
"""
|
||||
units = body.get('units')
|
||||
if body.get('schema_version') != 'shipping_receipt_rpa.v1' or body.get('action') != 'receipt_export_batch' or not isinstance(units, list) or not units:
|
||||
raise RuntimeError('invalid receipt trigger contract')
|
||||
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'receipt').strip() or 'receipt'
|
||||
if body.get('schema_version') != 'freight_rpa.inbound.v1' or body.get('action') != 'inbound_export_batch' or not isinstance(units, list) or not units:
|
||||
raise RuntimeError('invalid inbound trigger contract')
|
||||
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'inbound').strip() or 'inbound'
|
||||
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
|
||||
for item in units:
|
||||
if not isinstance(item, dict):
|
||||
raise RuntimeError('receipt unit must be object')
|
||||
raise RuntimeError('inbound unit must be object')
|
||||
_validate_unit(item)
|
||||
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
|
||||
progress_counts = {'success': 0, 'empty': 0, 'failed': 0}
|
||||
for (connector, profile_code, login_url), group in grouped.items():
|
||||
print(f'[receipt-batch] connector={connector} profile={profile_code} units={len(group)}')
|
||||
print(f'[inbound-batch] connector={connector} profile={profile_code} units={len(group)}')
|
||||
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
|
||||
reuse_session = _session_reuse_enabled()
|
||||
resources = (None, None, None, None)
|
||||
# [STEP] 已终态回调的 callback_id:批级异常时只给剩余单元补 failed,避免双重终态。
|
||||
reported_callback_ids: set[str] = set()
|
||||
try:
|
||||
if not mock:
|
||||
resources = _open_browser(
|
||||
@@ -642,12 +674,12 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
for attempt in range(1, _EXPORT_UNIT_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
if mock:
|
||||
mock_path = drop_dir / _receipt_download_name(
|
||||
mock_path = drop_dir / _inbound_download_name(
|
||||
batch_run_no,
|
||||
str(unit.get('source_code') or ''),
|
||||
unit.get('warehouse_id'),
|
||||
)
|
||||
_write_mock_receipt_excel(mock_path)
|
||||
_write_mock_inbound_excel(mock_path)
|
||||
output = mock_path
|
||||
else:
|
||||
baseline_names = _download_dir_baseline_names(drop_dir)
|
||||
@@ -666,17 +698,17 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
download, drop_dir, unit, batch_run_no=batch_run_no,
|
||||
baseline_names=baseline_names,
|
||||
)
|
||||
_validate_receipt_excel(output)
|
||||
_enforce_receipt_excel_not_empty(output)
|
||||
_validate_inbound_excel(output)
|
||||
_enforce_inbound_excel_not_empty(output)
|
||||
break
|
||||
except NoReceiptDataError as exc:
|
||||
except NoInboundDataError as exc:
|
||||
terminal = ('empty', exc)
|
||||
output = None
|
||||
break
|
||||
except Exception as exc:
|
||||
if attempt < _EXPORT_UNIT_MAX_ATTEMPTS:
|
||||
print(
|
||||
f'[receipt-batch] export failed {unit.get("source_code")} '
|
||||
f'[inbound-batch] export failed {unit.get("source_code")} '
|
||||
f'(attempt {attempt}/{_EXPORT_UNIT_MAX_ATTEMPTS}), '
|
||||
f'retry in {_EXPORT_UNIT_RETRY_WAIT_SECONDS}s: {exc}',
|
||||
file=_sys.stderr,
|
||||
@@ -692,9 +724,10 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
_report_empty(unit, terminal[1]) # type: ignore[arg-type]
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[receipt-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
f'[inbound-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
reported_callback_ids.add(str(unit.get('callback_id') or ''))
|
||||
progress_counts['empty'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
continue
|
||||
@@ -703,16 +736,17 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
_report_failure(unit, terminal[1]) # type: ignore[arg-type]
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[receipt-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
f'[inbound-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
reported_callback_ids.add(str(unit.get('callback_id') or ''))
|
||||
progress_counts['failed'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
continue
|
||||
if output is None:
|
||||
continue
|
||||
print(
|
||||
f'[receipt-unit] success source={unit["source_code"]} '
|
||||
f'[inbound-unit] success source={unit["source_code"]} '
|
||||
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
|
||||
)
|
||||
progress_counts['success'] += 1
|
||||
@@ -723,10 +757,21 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
# 文件已落盘:回调超时只打日志,禁止回到导出重试(同源双文件根因)。
|
||||
# 不调用 failed 回调,避免晚到的 ready 与 failed 竞态;人工可按 drop 文件补档。
|
||||
print(
|
||||
f'[receipt-unit] ready callback failed source={unit.get("source_code")} '
|
||||
f'[inbound-unit] ready callback failed source={unit.get("source_code")} '
|
||||
f'file={output.name}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
reported_callback_ids.add(str(unit.get('callback_id') or ''))
|
||||
except Exception as exc:
|
||||
# [STEP] 批级失败(浏览器未开 / 凭据上下文崩 / 未捕获逃逸):剩余单元补 failed,
|
||||
# 否则 awaiting_rpa 永挂、前端「抓取中」锁死批量重试(2026-10-20 本地事故)。
|
||||
remaining = [
|
||||
unit for unit in group
|
||||
if str(unit.get('callback_id') or '') not in reported_callback_ids
|
||||
]
|
||||
if remaining:
|
||||
_report_group_open_failure(remaining, exc)
|
||||
raise
|
||||
finally:
|
||||
playwright, context, _page, profile_dir = resources
|
||||
if context is not None:
|
||||
@@ -739,7 +784,7 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
|
||||
|
||||
def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
"""原子领取一个 receipt trigger;成功归档 processed,异常归档 failed。
|
||||
"""原子领取一个 inbound trigger;成功归档 processed,异常归档 failed。
|
||||
|
||||
领取与归档统一走 common/trigger_consumer(四态目录契约),
|
||||
本函数只保留收料批次处理与 SystemExit 兜底。
|
||||
@@ -747,19 +792,19 @@ def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
return
|
||||
print(f'[receipt-trigger] claimed {claimed.name}')
|
||||
print(f'[inbound-trigger] claimed {claimed.name}')
|
||||
# 心跳运行态对齐库存 Worker:领取成功即 busy,处理结束(含归档 failed 后 re-raise)
|
||||
# 由 finally 恢复 idle,保证 SystemExit 兜底路径也不会让监控长期挂 busy。
|
||||
rpa_heartbeat.set_worker_runtime_status('busy')
|
||||
try:
|
||||
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
|
||||
archive_trigger(claimed, 'processed')
|
||||
print(f'[receipt-trigger] archived processed {claimed.name}')
|
||||
print(f'[inbound-trigger] archived processed {claimed.name}')
|
||||
except (Exception, SystemExit):
|
||||
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
|
||||
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
|
||||
archive_trigger(claimed, 'failed')
|
||||
print(f'[receipt-trigger] archived failed {claimed.name}')
|
||||
print(f'[inbound-trigger] archived failed {claimed.name}')
|
||||
raise
|
||||
finally:
|
||||
rpa_heartbeat.set_worker_runtime_status('idle')
|
||||
@@ -768,8 +813,8 @@ def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
def main() -> None:
|
||||
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
|
||||
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
|
||||
drop_dir = _require_dir('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR')
|
||||
trigger_dir = _require_dir('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR')
|
||||
drop_dir = _require_dir('FREIGHT_RPA_SHARED_INBOUND_DROP_DIR')
|
||||
trigger_dir = _require_dir('FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR')
|
||||
poll = max(1, int(env('FREIGHT_RPA_WORKER_POLL_SECONDS', '3') or '3'))
|
||||
heartbeat_seconds = max(
|
||||
15,
|
||||
@@ -779,7 +824,7 @@ def main() -> None:
|
||||
cleanup_interval = cleanup_interval_seconds()
|
||||
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
|
||||
print(
|
||||
'[freight_receipt_rpa_worker] started\n'
|
||||
'[freight_inbound_rpa_worker] started\n'
|
||||
f' mock={env("FREIGHT_RPA_WORKER_MOCK", "false")}\n'
|
||||
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
|
||||
f' poll_seconds={poll}\n'
|
||||
@@ -807,20 +852,20 @@ def main() -> None:
|
||||
profile_root_raw = str(env('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
|
||||
try:
|
||||
stats = run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
|
||||
onhand_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
|
||||
drop_dir=drop_dir,
|
||||
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
|
||||
log_file=worker_logging.active_log_path(),
|
||||
)
|
||||
print(format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
print(f'[receipt-cleanup] failed: {exc}')
|
||||
print(f'[inbound-cleanup] failed: {exc}')
|
||||
return now_mono
|
||||
|
||||
# [STEP 2] 启动即清一轮(对齐库存节奏),避免重启前堆积的归档/孤儿 Profile 撑盘。
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
|
||||
# 启动时立即上报一次心跳(对齐库存 Worker),让监控端第一时间出现独立的
|
||||
# `<hostname>-receipt` 收料 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
|
||||
# `<hostname>-inbound` 收料 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
|
||||
)
|
||||
@@ -835,7 +880,7 @@ def main() -> None:
|
||||
try:
|
||||
_claim_and_process(path, drop_dir)
|
||||
except Exception as exc:
|
||||
print(f'[receipt-trigger] failed {path.name}: {exc}')
|
||||
print(f'[inbound-trigger] failed {path.name}: {exc}')
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
|
||||
time.sleep(poll)
|
||||
|
||||
+17
-17
@@ -1,18 +1,18 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Register the test/prod Receipt RPA Worker scheduled tasks in FULL-BACKGROUND mode.
|
||||
Register the test/prod Inbound RPA Worker scheduled tasks in FULL-BACKGROUND mode.
|
||||
|
||||
.DESCRIPTION
|
||||
Runs the Receipt Worker as a background scheduled task with NO visible console and
|
||||
NO visible browser (the Worker launches Playwright headless via -Headless).
|
||||
Deliberately ASCII-only so it parses identically under any Windows console code page.
|
||||
|
||||
Mirrors register_inventory_worker_tasks.ps1 one-to-one, with distinct task names so
|
||||
Mirrors register_onhand_worker_tasks.ps1 one-to-one, with distinct task names so
|
||||
both Workers can be registered side by side on the same host:
|
||||
- Inventory: "HXOPS Inventory RPA Worker TEST/PROD"
|
||||
- Receipt: "HXOPS Receipt RPA Worker TEST/PROD"
|
||||
- Onhand: "HXOPS Freight Onhand RPA Worker TEST/PROD"
|
||||
- Inbound: "HXOPS Freight Inbound RPA Worker TEST/PROD"
|
||||
|
||||
Shape constraints (same as the inventory registration):
|
||||
Shape constraints (same as the onhand registration):
|
||||
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
|
||||
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
|
||||
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
|
||||
@@ -27,13 +27,13 @@
|
||||
All actions can target one environment or both via -Scope test|prod|all (default all).
|
||||
|
||||
Usage (run in the RPA account's PowerShell):
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Unregister # unregister both
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1 -Unregister # unregister both
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
@@ -53,8 +53,8 @@ param(
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$TestTask = "HXOPS Receipt RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Receipt RPA Worker PROD"
|
||||
$TestTask = "HXOPS Freight Inbound RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Freight Inbound RPA Worker PROD"
|
||||
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
|
||||
function Get-TasksForScope {
|
||||
@@ -70,7 +70,7 @@ function Get-TasksForScope {
|
||||
function Assert-Launcher {
|
||||
# Validate the launcher and DPAPI Secret file required for one environment.
|
||||
param([string]$Root, [string]$Environment)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\receipt\start_receipt_worker.ps1"
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\inbound\start_inbound_worker.ps1"
|
||||
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
|
||||
throw "Launcher not found: $launcher"
|
||||
}
|
||||
@@ -87,7 +87,7 @@ function New-TaskDefinition {
|
||||
[string]$ApiBase,
|
||||
[string]$EnvName
|
||||
)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\receipt\start_receipt_worker.ps1"
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\inbound\start_inbound_worker.ps1"
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
|
||||
|
||||
# Key differences vs the visible scheduled task:
|
||||
@@ -116,7 +116,7 @@ function New-TaskDefinition {
|
||||
-Trigger $trigger `
|
||||
-Principal $principal `
|
||||
-Settings $settings `
|
||||
-Description "HXOPS Receipt RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
-Description "HXOPS Freight Inbound RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
}
|
||||
|
||||
# Default action is Register when no switch is given.
|
||||
+13
-13
@@ -1,9 +1,9 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
在当前 PowerShell 进程树启动独立货代收料 RPA Worker。
|
||||
在当前 PowerShell 进程树启动独立货代入站(原收料)RPA Worker。
|
||||
|
||||
.DESCRIPTION
|
||||
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
|
||||
只设置 Process 级环境变量和 inbound 专用目录;可与 onhand Worker 并行运行,
|
||||
二者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
|
||||
根(各自按 connector+profile 隔离会话目录)。
|
||||
默认开启会话复用(SESSION_REUSE,对齐库存);需要每次全新登录时传 -NoSessionReuse。
|
||||
@@ -27,7 +27,7 @@ param(
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。" }
|
||||
$workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\receipt\receipt_rpa_worker.py'
|
||||
$workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\inbound\inbound_rpa_worker.py'
|
||||
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
|
||||
|
||||
function ConvertTo-PlainText {
|
||||
@@ -41,7 +41,7 @@ $secret = Import-Clixml -LiteralPath $SecretFile
|
||||
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
|
||||
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
|
||||
}
|
||||
# freight_rpa 三层布局根:$WorkerRoot\data\freight_rpa\{inventory,receipt,common}
|
||||
# freight_rpa 分域布局根:$WorkerRoot\data\freight_rpa\{onhand,inbound,outbound,common}
|
||||
$rpaRoot = Join-Path $WorkerRoot 'data\freight_rpa'
|
||||
# 共享 scope 标识(与库存同口径):Windows 本地路径不含共享名,无法推导,必须显式注入;
|
||||
# 心跳线程据此把哨兵写进收料 trigger 目录,后端就绪检查按 scope 比对。
|
||||
@@ -53,8 +53,8 @@ if ($Environment -eq 'test') {
|
||||
# 局部变量名刻意避开参数名:PS 变量名大小写不敏感,$sessionReuse 曾与旧开关
|
||||
# $SessionReuse 互为同一变量,字符串 'true'/'false' 覆盖开关值,在部分 Windows build
|
||||
# 上于启动阶段以 SwitchParameter 转换异常爆出(2026-09-30 修复)。开关现统一为
|
||||
# $ReuseSession(与库存同名),局部变量保持 $reuseFlag 防回归。
|
||||
$reuseFlag = if ($NoSessionReuse) { 'false' } else { 'true' }
|
||||
# $ReuseSession(与库存同名),局部变量统一为 $sessionReuse(与 onhand Worker 同名,便于契约测试断言)。
|
||||
$sessionReuse = if ($NoSessionReuse) { 'false' } else { 'true' }
|
||||
if ($ReuseSession -and $NoSessionReuse) {
|
||||
Write-Warning '同时指定 -ReuseSession 与 -NoSessionReuse 时以 -NoSessionReuse 为准'
|
||||
}
|
||||
@@ -65,30 +65,30 @@ $processVars = [ordered]@{
|
||||
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
|
||||
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
|
||||
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
|
||||
FREIGHT_RPA_WORKER_SESSION_REUSE = $reuseFlag
|
||||
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
|
||||
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
|
||||
FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
|
||||
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'receipt\logs\worker.log'
|
||||
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'inbound\logs\worker.log'
|
||||
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = '10485760'
|
||||
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = '5'
|
||||
# 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。
|
||||
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
|
||||
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-inbound"
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
|
||||
# 共享 scope 标识(与库存同口径):缺省时收料 Worker 不写哨兵、心跳 scope 为空,
|
||||
# test/prod 后端收料就绪检查会报 shared_sentinel_missing / shared_scope_mismatch。
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $rpaRoot 'receipt\triggers'
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $rpaRoot 'receipt\drop'
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = Join-Path $rpaRoot 'inbound\triggers'
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = Join-Path $rpaRoot 'inbound\drop'
|
||||
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile;会话按 connector+profile 分目录。
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
|
||||
# 本机磁盘保留:与库存 Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/receipt_* Profile)。
|
||||
# 本机磁盘保留:与 onhand Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/inbound_* Profile)。
|
||||
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
|
||||
FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = '3600'
|
||||
FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = '24'
|
||||
}
|
||||
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
|
||||
try {
|
||||
Write-Host "Starting receipt RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot sessionReuse=$reuseFlag"
|
||||
Write-Host "Starting inbound RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot sessionReuse=$sessionReuse"
|
||||
& $PythonExe $workerScript
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
+173
-168
@@ -1,23 +1,27 @@
|
||||
"""
|
||||
Freight RPA worker (PoC).
|
||||
scripts/freight_rpa/onhand/onhand_rpa_worker.py
|
||||
|
||||
轮询 trigger JSON → 按 connector_type 调用 DSV/Crane driver → 回调 hxops Tool API。
|
||||
DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。
|
||||
用途:货代库存(onhand)RPA Worker——轮询 onhand trigger → 按 connector/profile 分组导出 →
|
||||
批末 ONHAND_BATCH_READY 回调 hxops。
|
||||
依赖:rpa_callbacks、dsv_report_export / dsv_session、crane_*、rpa_common。
|
||||
逻辑:同 Profile 组内单次登录串行导出;批级/Profile 打开失败时须为组内尚未入 results
|
||||
的源补 failed(error_code=rpa_profile_failed),再继续其他组并批末回调——与
|
||||
inbound/outbound「剩余单元补 failed」同契约,禁止静默丢源导致 awaiting 永挂。
|
||||
|
||||
Usage:
|
||||
python scripts/freight_rpa/inventory/inventory_rpa_worker.py
|
||||
python scripts/freight_rpa/onhand/onhand_rpa_worker.py
|
||||
|
||||
Required env (same as backend):
|
||||
HXOPS_API_BASE e.g. http://127.0.0.1:5052
|
||||
SHIPPING_NOTICE_TOOL_API_KEY
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR
|
||||
Optional:
|
||||
FREIGHT_RPA_WORKER_MOCK=false
|
||||
FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||||
FREIGHT_RPA_WORKER_SAMPLE_ONHAND=path/to/sample.xlsx
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||
FREIGHT_RPA_WORKER_SESSION_REUSE=true
|
||||
FREIGHT_RPA_WORKER_HEADLESS=false
|
||||
@@ -61,11 +65,11 @@ from pathlib import Path as _Path
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
and (_c / "onhand").is_dir() and (_c / "inbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
@@ -89,6 +93,18 @@ from download_artifact_fallback import ( # noqa: E402
|
||||
wait_for_new_download_file as _wait_for_new_download_file,
|
||||
)
|
||||
from trigger_consumer import claim_trigger # noqa: E402
|
||||
# 回调 URL 单一真相(/api/freight-rpa/*)与统一 POST 实现收拢至 common/rpa_callbacks。
|
||||
import rpa_callbacks # noqa: E402
|
||||
from rpa_callbacks import ( # noqa: E402
|
||||
ONHAND_BATCH_CLAIMED,
|
||||
ONHAND_BATCH_PROGRESS,
|
||||
ONHAND_BATCH_READY,
|
||||
ONHAND_CONFIGURATION_TEST_ANALYZE,
|
||||
ONHAND_CONFIGURATION_TEST_COMPLETE,
|
||||
ONHAND_CONFIGURATION_TEST_START,
|
||||
ONHAND_READY,
|
||||
UPLOAD_COMPLETE,
|
||||
)
|
||||
# 日志实现已提取至公共模块(scripts/freight_rpa/common/worker_logging.py),本 Worker 仅委托调用。
|
||||
from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402
|
||||
|
||||
@@ -211,7 +227,7 @@ def _browser_profile_root() -> Path:
|
||||
解析 Playwright 运行时 profile 根目录。
|
||||
|
||||
核心逻辑:bare-run(未配置环境变量)默认 `<backend>/data/freight_rpa/common/browser_profile`,
|
||||
与 freight_rpa 三层布局(inventory / receipt / common)保持一致;已配置环境变量时按
|
||||
与 freight_rpa 三层布局(onhand / inbound / common)保持一致;已配置环境变量时按
|
||||
backend 相对路径字面解析,无任何兼容改写(本分支红线:不做旧布局迁移层)。
|
||||
|
||||
Returns:
|
||||
@@ -260,58 +276,13 @@ def _resolve_tool_api_auth_debug() -> tuple[str, str]:
|
||||
|
||||
def _post_callback(path: str, payload: dict) -> None:
|
||||
"""
|
||||
向 HXOPS 货代 Tool API 发送 JSON 回调。
|
||||
向 HXOPS 货代 Tool API 发送 JSON 回调(薄封装)。
|
||||
|
||||
核心逻辑:组装 URL 与双 Header 密钥 → 打印脱敏请求日志 → POST;HTTP 错误时打印响应体摘要。
|
||||
核心逻辑:URL 组装、双 Header 密钥鉴权、脱敏请求日志与 HTTP 错误处理统一收拢到
|
||||
common/rpa_callbacks.post_callback(/api/freight-rpa/* 单一真相);本函数保留
|
||||
(path, payload) 签名,便于测试 monkeypatch 与既有调用点零改动。
|
||||
"""
|
||||
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
|
||||
rpa_callbacks.post_callback(path, payload)
|
||||
|
||||
|
||||
def _move_trigger(trigger_path: Path, target_dir: Path, reason: str) -> None:
|
||||
@@ -354,27 +325,27 @@ def _close_batch_browser_resources(context: Any, playwright: Any, runtime_profil
|
||||
print(f"[browser-cleanup] total_cleanup elapsedMs={int((time.monotonic() - close_started_at) * 1000)}")
|
||||
|
||||
|
||||
_INVENTORY_V2_REQUIRED_FIELDS = (
|
||||
_ONHAND_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]:
|
||||
def _onhand_v2_identity_errors(body: dict[str, Any]) -> list[str]:
|
||||
"""校验库存 RPA v2 Trigger 身份;缺失字段时禁止启动外部库存操作。"""
|
||||
missing = []
|
||||
for key in _INVENTORY_V2_REQUIRED_FIELDS:
|
||||
for key in _ONHAND_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":
|
||||
if body.get("schema_version") != "freight_rpa.onhand.v1":
|
||||
missing.append("schema_version")
|
||||
return list(dict.fromkeys(missing))
|
||||
|
||||
|
||||
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
|
||||
sample = _env("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY")
|
||||
def _write_sample_onhand(drop_dir: Path, task_no: str) -> Path:
|
||||
sample = _env("FREIGHT_RPA_WORKER_SAMPLE_ONHAND")
|
||||
if sample and Path(sample).is_file():
|
||||
dest = drop_dir / Path(sample).name
|
||||
shutil.copy2(sample, dest)
|
||||
@@ -383,7 +354,7 @@ def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
|
||||
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"
|
||||
dest = drop_dir / f"onhand_{task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Inventory"
|
||||
@@ -397,7 +368,7 @@ def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
|
||||
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}"
|
||||
return f"onhand_{task_no}_{safe_source}_{stamp}{suffix}"
|
||||
|
||||
|
||||
def _require_playwright():
|
||||
@@ -420,8 +391,8 @@ def _require_playwright():
|
||||
# #endregion
|
||||
|
||||
|
||||
_INVENTORY_EXCEL_MIN_BYTES = 512
|
||||
_INVENTORY_EXCEL_HEADER_MARKERS = (
|
||||
_ONHAND_EXCEL_MIN_BYTES = 512
|
||||
_ONHAND_EXCEL_HEADER_MARKERS = (
|
||||
"on hand inventory",
|
||||
"supplier id",
|
||||
"aws sku",
|
||||
@@ -429,7 +400,7 @@ _INVENTORY_EXCEL_HEADER_MARKERS = (
|
||||
)
|
||||
|
||||
|
||||
def _validate_inventory_excel(path: Path) -> None:
|
||||
def _validate_onhand_excel(path: Path) -> None:
|
||||
"""
|
||||
校验 RPA 下载的库存 Excel 可被打开且具备报表基本结构。
|
||||
核心逻辑:拒绝过小/HTML 错误页伪装文件;检查前几行是否含库存报表表头特征。
|
||||
@@ -441,7 +412,7 @@ def _validate_inventory_excel(path: Path) -> None:
|
||||
started_at = time.monotonic()
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
if size < _INVENTORY_EXCEL_MIN_BYTES:
|
||||
if size < _ONHAND_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)")
|
||||
|
||||
try:
|
||||
@@ -465,24 +436,24 @@ def _validate_inventory_excel(path: Path) -> None:
|
||||
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 not any(marker in haystack for marker in _ONHAND_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 "
|
||||
"[onhand-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 "
|
||||
"[onhand-artifact] stage=excel_structure_validation status=end "
|
||||
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
|
||||
)
|
||||
|
||||
|
||||
def _dsv_inventory_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
def _dsv_onhand_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
"""
|
||||
判断 DSV 风格库存 Excel 表头之后是否有明细行。
|
||||
|
||||
@@ -525,13 +496,13 @@ def _dsv_inventory_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _enforce_inventory_excel_not_empty(path: Path) -> None:
|
||||
def _enforce_onhand_excel_not_empty(path: Path) -> None:
|
||||
"""
|
||||
DSV Excel 有表头无明细时记为无库存(NoInventoryDataError → skipped)。
|
||||
|
||||
核心逻辑:配合导出路径「DOM 无行仍导出」;真真空才 skip,避免 DOM 慢渲染假空。
|
||||
"""
|
||||
detail = _dsv_inventory_excel_has_detail_rows(path)
|
||||
detail = _dsv_onhand_excel_has_detail_rows(path)
|
||||
if detail is False:
|
||||
raise NoInventoryDataError("DSV report has no inventory data")
|
||||
|
||||
@@ -576,7 +547,7 @@ def _persist_download_to_dest(
|
||||
if not _is_playwright_target_closed_error(exc):
|
||||
raise
|
||||
print(
|
||||
"[inventory-artifact] stage=download_save status=fallback "
|
||||
"[onhand-artifact] stage=download_save status=fallback "
|
||||
f"reason=browser_closed path={dest.name!r}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
@@ -613,8 +584,8 @@ def _save_download(
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
|
||||
_validate_inventory_excel(dest)
|
||||
_enforce_inventory_excel_not_empty(dest)
|
||||
_validate_onhand_excel(dest)
|
||||
_enforce_onhand_excel_not_empty(dest)
|
||||
return dest
|
||||
|
||||
|
||||
@@ -623,7 +594,7 @@ def _batch_download_name(run_no: str, source_code: str, warehouse_id: str, suffi
|
||||
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}"
|
||||
return f"onhand_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}"
|
||||
|
||||
|
||||
def _save_batch_download(
|
||||
@@ -652,16 +623,16 @@ def _save_batch_download(
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
print(
|
||||
"[inventory-artifact] stage=download_save status=end "
|
||||
"[onhand-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)
|
||||
_enforce_inventory_excel_not_empty(dest)
|
||||
_validate_onhand_excel(dest)
|
||||
_enforce_onhand_excel_not_empty(dest)
|
||||
return dest
|
||||
|
||||
|
||||
def _validate_inventory_source_for_rpa(source: dict[str, Any]) -> None:
|
||||
def _validate_onhand_source_for_rpa(source: dict[str, Any]) -> None:
|
||||
"""
|
||||
校验单个库存 RPA source 的最小定位条件。
|
||||
核心逻辑:业务 connector_type 为 dbs/crane,driver 类型由 worker_connector_type 指定;
|
||||
@@ -711,7 +682,7 @@ def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
|
||||
try:
|
||||
current_page.close()
|
||||
except Exception as exc:
|
||||
print(f"[inventory-batch] close previous page failed: {exc}", file=sys.stderr)
|
||||
print(f"[onhand-batch] close previous page failed: {exc}", file=sys.stderr)
|
||||
return next_page
|
||||
|
||||
|
||||
@@ -850,7 +821,7 @@ def _load_crane_report_export_module() -> Any:
|
||||
return module
|
||||
|
||||
|
||||
def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
def _export_crane_onhand_source(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
"""
|
||||
在已登录 Crane session 上导出库存。
|
||||
核心逻辑:Run Report → Schedule Report → Scheduled Reports 异步下载(不填 Warehouse)。
|
||||
@@ -1107,21 +1078,21 @@ def _open_browser(
|
||||
return playwright, context, page, runtime_profile_dir
|
||||
|
||||
|
||||
def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
def _download_dsv360_onhand(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:
|
||||
def _download_crane_onhand(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)
|
||||
return _export_crane_onhand_source(page, trigger, source)
|
||||
|
||||
|
||||
def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> Path:
|
||||
def _download_onhand_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):
|
||||
@@ -1130,7 +1101,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
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)
|
||||
_validate_onhand_source_for_rpa(source)
|
||||
|
||||
playwright = context = runtime_profile_dir = None
|
||||
keep_open_on_error = _env("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
|
||||
@@ -1146,9 +1117,9 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
# [STEP] 导出前拍摄目录基线:save_as 若因浏览器关闭失败,可识别 downloads_path 新文件。
|
||||
baseline_names = _download_dir_baseline_names(drop_dir)
|
||||
if connector_type == "dsv360":
|
||||
download = _download_dsv360_inventory(page, trigger, source)
|
||||
download = _download_dsv360_onhand(page, trigger, source)
|
||||
elif connector_type == "crane_footprint":
|
||||
download = _download_crane_inventory(page, trigger, source)
|
||||
download = _download_crane_onhand(page, trigger, source)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported inventory connector_type: {connector_type}")
|
||||
return _save_download(download, drop_dir, task_no, source_code, baseline_names=baseline_names)
|
||||
@@ -1168,7 +1139,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
def _normalize_onhand_batch_item_status(item: dict[str, Any]) -> str:
|
||||
"""
|
||||
batch 明细状态归一化(比单任务更严格:缺省字段不算 success)。
|
||||
|
||||
@@ -1185,7 +1156,7 @@ def _normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
return "failed"
|
||||
|
||||
|
||||
def _summarize_inventory_batch_results(results: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
def _summarize_onhand_batch_results(results: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 batch 回调顶层状态。
|
||||
|
||||
@@ -1203,7 +1174,7 @@ def _summarize_inventory_batch_results(results: list[dict[str, Any]]) -> dict[st
|
||||
"failed_count": 0,
|
||||
}
|
||||
statuses = [
|
||||
_normalize_inventory_batch_item_status(item)
|
||||
_normalize_onhand_batch_item_status(item)
|
||||
for item in results
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
@@ -1234,7 +1205,7 @@ 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)。
|
||||
必须回调 /api/freight-rpa/onhand-configuration-test-analyze(站点停用时生产 batch 接口会报 unknown_or_disabled_source)。
|
||||
|
||||
Args:
|
||||
run_no: 测试运行号(CONFIG-...)。
|
||||
@@ -1247,7 +1218,7 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
|
||||
(
|
||||
item
|
||||
for item in results
|
||||
if isinstance(item, dict) and _normalize_inventory_batch_item_status(item) == "success"
|
||||
if isinstance(item, dict) and _normalize_onhand_batch_item_status(item) == "success"
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -1285,17 +1256,17 @@ def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[s
|
||||
定时排程批量导出每完成一个站点即上报累计进度,后端实时回写排程 run 笔数。
|
||||
|
||||
核心逻辑:仅 scheduled 触发且携带 schedule_run_id 时上报,按需单票不受影响;
|
||||
best-effort,上报失败不影响导出与最终回调;最终笔数以 inventory-batch-ready 为准。
|
||||
best-effort,上报失败不影响导出与最终回调;最终笔数以 onhand-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)
|
||||
summary = _summarize_onhand_batch_results(results)
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-batch-progress", {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
_post_callback(ONHAND_BATCH_PROGRESS, {
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": body.get("callback_id"),
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
@@ -1305,7 +1276,7 @@ def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[s
|
||||
"failed_count": summary["failed_count"],
|
||||
})
|
||||
except Exception as exc:
|
||||
print(f"[inventory-batch] progress callback failed {run_no}: {exc}", file=sys.stderr)
|
||||
print(f"[onhand-batch] progress callback failed {run_no}: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
# 批内单源导出的暂态失败重试参数:DSV s360 服务端报表错误(rsProcessingAborted 等)
|
||||
@@ -1337,13 +1308,13 @@ def _export_source_max_attempts(exc: Exception) -> int:
|
||||
)
|
||||
|
||||
|
||||
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
def _handle_onhand_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
"""
|
||||
消费 inventory_export_batch trigger:按 Profile 分组导出并回调后端。
|
||||
消费 onhand_export_batch trigger:按 Profile 分组导出并回调后端。
|
||||
|
||||
核心逻辑:先按 trigger_type 做身份门禁——scheduled / configuration_test(_batch)
|
||||
只校验信封字段;按需单票保持逐源 Attempt/Gate fail-closed。导出后按类型路由到
|
||||
inventory-batch-ready 或 inventory-configuration-test(-batch)-ready。
|
||||
onhand-batch-ready 或 onhand-configuration-test(-batch)-ready。
|
||||
|
||||
Args:
|
||||
trigger_path: 待处理的 batch trigger JSON 路径。
|
||||
@@ -1357,12 +1328,12 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
# [DEBUG-TIMING] 批处理整体耗时基线:从进入 handler 到回调完成。
|
||||
batch_started_at = time.monotonic()
|
||||
print(f"[inventory-batch-timing] handler start run={run_no}")
|
||||
print(f"[onhand-batch-timing] handler start run={run_no}")
|
||||
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":
|
||||
if body.get("schema_version") != "freight_rpa.onhand.v1":
|
||||
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")
|
||||
@@ -1370,13 +1341,13 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
# - scheduled:按 run 计价,仅 run_no/schedule_run_id,无逐源 Attempt/Gate。
|
||||
# - configuration_test / configuration_test_batch:管理端停用站点连通性验证,
|
||||
# 不创建订单 Attempt/Gate,故意不写 task_no/source_run_no 等生产身份;
|
||||
# 终态走 inventory-configuration-test(-batch)-ready,不得用生产身份 fail-closed。
|
||||
# 终态走 onhand-configuration-test(-batch)-ready,不得用生产身份 fail-closed。
|
||||
# - 其余(按需单票/多源准备):保持逐源身份 fail-closed。
|
||||
trigger_type = str(body.get("trigger_type") or "").strip()
|
||||
is_run_scoped_batch = trigger_type in {
|
||||
"scheduled", "configuration_test", "configuration_test_batch",
|
||||
}
|
||||
source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
|
||||
source_required = set(_ONHAND_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
|
||||
if is_run_scoped_batch:
|
||||
source_required -= {
|
||||
"task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id",
|
||||
@@ -1423,8 +1394,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
for source in sources
|
||||
if isinstance(source, dict)
|
||||
]
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
_post_callback(ONHAND_BATCH_READY, {
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": body.get("callback_id"),
|
||||
"batch_run_no": run_no or None,
|
||||
"business_status": "rejected",
|
||||
@@ -1447,19 +1418,19 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
_emit_batch_progress(body, run_no, results)
|
||||
|
||||
# v2 claimed 回调只记录领取事实,不代表业务成功。
|
||||
if body.get("schema_version") == "shipping_inventory_rpa.v2":
|
||||
if body.get("schema_version") == "freight_rpa.onhand.v1":
|
||||
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,
|
||||
_post_callback(ONHAND_BATCH_CLAIMED, {
|
||||
"schema_version": "freight_rpa.onhand.v1", "batch_run_no": run_no,
|
||||
"claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("FREIGHT_RPA_WORKER_ID", "worker"),
|
||||
"items": claimed_items,
|
||||
})
|
||||
except Exception as exc:
|
||||
print(f"[inventory-batch] claimed callback failed: {exc}", file=sys.stderr)
|
||||
print(f"[onhand-batch] claimed callback failed: {exc}", file=sys.stderr)
|
||||
|
||||
def report_configuration_test_progress(source: dict) -> None:
|
||||
"""实际操作站点前回传领取状态;进度回调故障不能中断库存导出。"""
|
||||
@@ -1469,14 +1440,14 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
if not validation_run_no:
|
||||
return
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-configuration-test-batch-progress", {
|
||||
_post_callback(ONHAND_CONFIGURATION_TEST_START, {
|
||||
"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)
|
||||
print(f"[onhand-batch] progress callback failed {validation_run_no}: {exc}", file=sys.stderr)
|
||||
|
||||
if mock:
|
||||
for source in sources:
|
||||
@@ -1484,7 +1455,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
continue
|
||||
report_configuration_test_progress(source)
|
||||
task_stub = run_no
|
||||
out_file = _write_sample_inventory(drop_dir, task_stub)
|
||||
out_file = _write_sample_onhand(drop_dir, task_stub)
|
||||
record_result({
|
||||
"source_code": source.get("source_code"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
@@ -1511,7 +1482,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
)
|
||||
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
|
||||
export_fn = _export_dsv_inventory_source if site == "dsv360" else _export_crane_onhand_source
|
||||
# 同组的 Profile 相同,登录和导出期间使用同一组临时凭据。
|
||||
with _profile_credentials(site_sources[0]):
|
||||
for index, source in enumerate(site_sources):
|
||||
@@ -1527,7 +1498,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
try:
|
||||
if attempt == 1:
|
||||
report_configuration_test_progress(source)
|
||||
_validate_inventory_source_for_rpa(source)
|
||||
_validate_onhand_source_for_rpa(source)
|
||||
skip_navigation = False
|
||||
if site == "dsv360":
|
||||
# [STEP 3] 批内同一 Profile 只登录一次:首源完整登录,后续源复用当前 tab
|
||||
@@ -1557,7 +1528,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
if not login_related or credential_mismatch:
|
||||
raise
|
||||
print(
|
||||
f"[inventory-batch] dsv360 session prepare failed for {code}, retry with clean page: {exc}",
|
||||
f"[onhand-batch] dsv360 session prepare failed for {code}, retry with clean page: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
@@ -1579,11 +1550,11 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
baseline_names=baseline_names,
|
||||
)
|
||||
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, "worker_attempt": attempt, "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}")
|
||||
print(f"[onhand-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||||
break
|
||||
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), "worker_attempt": attempt, "validation_run_no": source.get("validation_run_no")})
|
||||
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
|
||||
print(f"[onhand-batch] {site} export skipped {code}/{wh}: {exc}")
|
||||
break
|
||||
except Exception as exc:
|
||||
error_code = (
|
||||
@@ -1594,7 +1565,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
if attempt < _export_source_max_attempts(exc):
|
||||
retry_wait_seconds = _export_source_retry_wait_seconds(exc)
|
||||
print(
|
||||
f"[inventory-batch] {site} export failed {code}/{wh} "
|
||||
f"[onhand-batch] {site} export failed {code}/{wh} "
|
||||
f"(attempt {attempt}/{_export_source_max_attempts(exc)}), "
|
||||
f"retry in {retry_wait_seconds}s: {exc}",
|
||||
file=sys.stderr,
|
||||
@@ -1602,10 +1573,44 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
time.sleep(retry_wait_seconds)
|
||||
continue
|
||||
record_result({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": error_code, "error_message": str(exc), "worker_attempt": attempt, "validation_run_no": source.get("validation_run_no")})
|
||||
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
|
||||
print(f"[onhand-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")})
|
||||
# [STEP] 批级/Profile 组失败(含 launch_persistent_context 浏览器已关):
|
||||
# 只给尚未写入 results 的源补 failed;已 success/skipped/failed 的源不得二次追加
|
||||
# (否则批末 summary 重复计失败)。与 inbound/outbound 的「剩余单元补 failed 回调」
|
||||
# 同契约——onhand 走 results 数组 + 批末 ONHAND_BATCH_READY,不逐源 HTTP 终态。
|
||||
recorded_keys = {
|
||||
(
|
||||
str(item.get("source_code") or "").strip().upper(),
|
||||
str(item.get("warehouse_id") or item.get("expected_warehouse_id") or "").strip().upper(),
|
||||
)
|
||||
for item in results
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
remaining = [
|
||||
source for source in site_sources
|
||||
if isinstance(source, dict)
|
||||
and (
|
||||
str(source.get("source_code") or "").strip().upper(),
|
||||
str(source.get("warehouse_id") or source.get("expected_warehouse_id") or "").strip().upper(),
|
||||
) not in recorded_keys
|
||||
]
|
||||
if remaining:
|
||||
print(
|
||||
f"[onhand-batch] open/group failed; recording {len(remaining)} source failure(s): "
|
||||
f"{str(exc)[:200]}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
for source in remaining:
|
||||
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)
|
||||
|
||||
@@ -1634,16 +1639,16 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
result[key] = source.get(key)
|
||||
|
||||
try:
|
||||
batch_summary = _summarize_inventory_batch_results(results)
|
||||
batch_summary = _summarize_onhand_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_path = ONHAND_CONFIGURATION_TEST_ANALYZE
|
||||
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_path = ONHAND_CONFIGURATION_TEST_COMPLETE
|
||||
callback_payload = {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
@@ -1653,9 +1658,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"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_path = ONHAND_BATCH_READY
|
||||
callback_payload = {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
@@ -1672,11 +1677,11 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
}
|
||||
# [DEBUG-TIMING] 到达回调前打点:若此前有明显的静默段(浏览器清理),此处能看到
|
||||
# handler 启动到回调前的累计耗时,配合 _close_batch_browser_resources 的逐段计时即可定位。
|
||||
print(f"[inventory-batch-timing] before callback run={run_no} totalElapsedMs={int((time.monotonic() - batch_started_at) * 1000)}")
|
||||
print(f"[onhand-batch-timing] before callback run={run_no} totalElapsedMs={int((time.monotonic() - batch_started_at) * 1000)}")
|
||||
_post_callback(callback_path, callback_payload)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(
|
||||
f"[inventory-batch] callback done run={run_no} "
|
||||
f"[onhand-batch] callback done run={run_no} "
|
||||
f"path={callback_path} "
|
||||
f"status={batch_summary['status']} "
|
||||
f"success={batch_summary['success_count']} "
|
||||
@@ -1687,23 +1692,23 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
|
||||
|
||||
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
def _handle_onhand_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)
|
||||
action = str(body.get("action") or "onhand_export").strip()
|
||||
if action == "onhand_export_batch":
|
||||
_handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
return
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
failed_dir = processed_dir.parent / "failed"
|
||||
if not task_no:
|
||||
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
|
||||
print(f"[skip] invalid onhand trigger: {trigger_path.name}")
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
identity_errors = _inventory_v2_identity_errors({**body, "task_no": task_no})
|
||||
identity_errors = _onhand_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",
|
||||
_post_callback(ONHAND_READY, {
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": None,
|
||||
"task_no": task_no,
|
||||
"business_status": "rejected",
|
||||
@@ -1720,7 +1725,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
|
||||
# 单源 Trigger 与 batch 使用同一 v2 身份契约;Worker 只能回传后端冻结的字段。
|
||||
identity = {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"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(),
|
||||
@@ -1734,8 +1739,8 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
"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", {
|
||||
out_file = _write_sample_onhand(drop_dir, task_no) if mock else _download_onhand_with_browser(body, drop_dir)
|
||||
_post_callback(ONHAND_READY, {
|
||||
**identity,
|
||||
"status": "success",
|
||||
"success": True,
|
||||
@@ -1744,10 +1749,10 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
"rpa_mode": mode,
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
|
||||
print(f"[onhand] {mode} export done for {task_no} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||||
_post_callback(ONHAND_READY, {
|
||||
**identity,
|
||||
"status": "skipped",
|
||||
"success": False,
|
||||
@@ -1758,12 +1763,12 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
})
|
||||
if trigger_path.exists():
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
print(f"[inventory] {mode} export skipped for {task_no}: {exc}")
|
||||
print(f"[onhand] {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", {
|
||||
_post_callback(ONHAND_READY, {
|
||||
**identity,
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
@@ -2438,7 +2443,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
mock = _env("FREIGHT_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", {
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
@@ -2486,7 +2491,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
)
|
||||
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", {
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
@@ -2499,7 +2504,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||||
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", {
|
||||
_post_callback(UPLOAD_COMPLETE, {
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"callback_id": callback_id,
|
||||
@@ -2534,7 +2539,7 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
|
||||
def _run_periodic_disk_cleanup(
|
||||
*,
|
||||
inv_trigger_dir: Path,
|
||||
onhand_trigger_dir: Path,
|
||||
upload_trigger_dir: Path,
|
||||
drop_dir: Path,
|
||||
upload_queue_dir: Path,
|
||||
@@ -2548,7 +2553,7 @@ def _run_periodic_disk_cleanup(
|
||||
日志备份、upload_queue 残留与孤儿 `run_*` Profile;同时按大小轮转打开中的 worker.log。
|
||||
|
||||
Args:
|
||||
inv_trigger_dir: 库存 trigger 根目录。
|
||||
onhand_trigger_dir: 库存 trigger 根目录。
|
||||
upload_trigger_dir: 上传 trigger 根目录。
|
||||
drop_dir: 库存 drop 根目录。
|
||||
upload_queue_dir: 上传队列目录。
|
||||
@@ -2565,7 +2570,7 @@ def _run_periodic_disk_cleanup(
|
||||
try:
|
||||
maybe_rotate_open_log()
|
||||
stats = worker_disk_cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger_dir,
|
||||
onhand_trigger_dir=onhand_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
@@ -2586,13 +2591,13 @@ def main() -> None:
|
||||
防止长期运行撑爆 RPA 主机盘符。
|
||||
"""
|
||||
log_path = configure_file_logging()
|
||||
drop_dir = _require_path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR")
|
||||
inv_trigger_dir = _require_path("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR")
|
||||
drop_dir = _require_path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR")
|
||||
onhand_trigger_dir = _require_path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR")
|
||||
upload_queue_dir = _require_path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
upload_trigger_dir = _require_path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
|
||||
poll = max(1, int(_env("FREIGHT_RPA_WORKER_POLL_SECONDS", "3") or "3"))
|
||||
|
||||
inv_processed = inv_trigger_dir / "processed"
|
||||
onhand_processed = onhand_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(
|
||||
@@ -2607,7 +2612,7 @@ def main() -> None:
|
||||
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" onhand_triggers={onhand_trigger_dir}")
|
||||
print(f" upload_triggers={upload_trigger_dir}")
|
||||
print(f" drop={drop_dir}")
|
||||
print(f" queue={upload_queue_dir}")
|
||||
@@ -2622,7 +2627,7 @@ def main() -> None:
|
||||
|
||||
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=inv_trigger_dir,
|
||||
trigger_dir=onhand_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
@@ -2630,14 +2635,14 @@ def main() -> None:
|
||||
# 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环,
|
||||
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
|
||||
rpa_heartbeat.start_heartbeat_loop(
|
||||
trigger_dir=inv_trigger_dir,
|
||||
trigger_dir=onhand_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
|
||||
# [STEP 1] 启动即清一轮,避免重启前长期堆积的归档立刻撑盘
|
||||
last_cleanup_mono = _run_periodic_disk_cleanup(
|
||||
inv_trigger_dir=inv_trigger_dir,
|
||||
onhand_trigger_dir=onhand_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
@@ -2645,10 +2650,10 @@ def main() -> None:
|
||||
)
|
||||
|
||||
while True:
|
||||
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
|
||||
_scan_triggers(onhand_trigger_dir, _handle_onhand_trigger, (drop_dir, onhand_processed))
|
||||
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
|
||||
last_cleanup_mono = _run_periodic_disk_cleanup(
|
||||
inv_trigger_dir=inv_trigger_dir,
|
||||
onhand_trigger_dir=onhand_trigger_dir,
|
||||
upload_trigger_dir=upload_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
upload_queue_dir=upload_queue_dir,
|
||||
+13
-13
@@ -9,7 +9,7 @@
|
||||
|
||||
Differences vs the standard "visible" scheduled task (README step 11 / 2.3):
|
||||
- powershell.exe gets -WindowStyle Hidden -> no console window to close by accident.
|
||||
- start_inventory_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
|
||||
- start_onhand_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
|
||||
|
||||
Shape constraints (same as README 2.3):
|
||||
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
|
||||
@@ -26,13 +26,13 @@
|
||||
All actions can target one environment or both via -Scope test|prod|all (default all).
|
||||
|
||||
Usage (run in the RPA account's PowerShell):
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # unregister both
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\freight_rpa\onhand\register_onhand_worker_tasks.ps1 -Unregister # unregister both
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
@@ -52,8 +52,8 @@ param(
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$TestTask = "HXOPS Inventory RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Inventory RPA Worker PROD"
|
||||
$TestTask = "HXOPS Freight Onhand RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Freight Onhand RPA Worker PROD"
|
||||
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
|
||||
function Get-TasksForScope {
|
||||
@@ -69,7 +69,7 @@ function Get-TasksForScope {
|
||||
function Assert-Launcher {
|
||||
# Validate the launcher and DPAPI Secret file required for one environment.
|
||||
param([string]$Root, [string]$Environment)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\inventory\start_inventory_worker.ps1"
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\onhand\start_onhand_worker.ps1"
|
||||
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
|
||||
throw "Launcher not found: $launcher"
|
||||
}
|
||||
@@ -86,7 +86,7 @@ function New-TaskDefinition {
|
||||
[string]$ApiBase,
|
||||
[string]$EnvName
|
||||
)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\inventory\start_inventory_worker.ps1"
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\onhand\start_onhand_worker.ps1"
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
|
||||
|
||||
# Key differences vs the visible scheduled task:
|
||||
@@ -115,7 +115,7 @@ function New-TaskDefinition {
|
||||
-Trigger $trigger `
|
||||
-Principal $principal `
|
||||
-Settings $settings `
|
||||
-Description "HXOPS RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
-Description "HXOPS Freight Onhand RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
}
|
||||
|
||||
# Default action is Register when no switch is given.
|
||||
+6
-6
@@ -1,4 +1,4 @@
|
||||
"""Run one database-generated inventory batch trigger without starting the polling worker."""
|
||||
"""Run one database-generated onhand batch trigger without starting the polling worker."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
@@ -31,8 +31,8 @@ def _load_dotenv_dev() -> None:
|
||||
|
||||
def _load_worker():
|
||||
"""Load the polling worker module so manual runs share the production trigger contract."""
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_batch_runner", module_path)
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_batch_runner", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
@@ -42,7 +42,7 @@ def _load_worker():
|
||||
def main() -> int:
|
||||
"""Execute a complete, database-generated batch trigger and post its normal callback."""
|
||||
if len(sys.argv) < 2:
|
||||
print("usage: python scripts/freight_rpa/run_inventory_batch_trigger.py <trigger.json>")
|
||||
print("usage: python scripts/freight_rpa/onhand/run_onhand_batch_trigger.py <trigger.json>")
|
||||
return 1
|
||||
trigger_path = Path(sys.argv[1]).expanduser()
|
||||
if not trigger_path.is_file():
|
||||
@@ -60,14 +60,14 @@ def main() -> int:
|
||||
if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"):
|
||||
print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required")
|
||||
return 1
|
||||
drop_dir = Path(os.environ.get("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR") or "backend/data/freight_rpa/inventory/drop")
|
||||
drop_dir = Path(os.environ.get("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR") or "backend/data/freight_rpa/onhand/drop")
|
||||
if not drop_dir.is_absolute():
|
||||
drop_dir = _repo_root() / drop_dir
|
||||
processed_dir = trigger_path.parent / "processed"
|
||||
processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
worker = _load_worker()
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
return 0
|
||||
|
||||
|
||||
+13
-9
@@ -40,7 +40,7 @@ $ErrorActionPreference = "Stop"
|
||||
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) {
|
||||
throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。"
|
||||
}
|
||||
$workerScript = Join-Path $WorkerRoot "scripts\freight_rpa\inventory\inventory_rpa_worker.py"
|
||||
$workerScript = Join-Path $WorkerRoot "scripts\freight_rpa\onhand\onhand_rpa_worker.py"
|
||||
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) {
|
||||
throw "Worker 不存在:$workerScript"
|
||||
}
|
||||
@@ -50,7 +50,9 @@ if ($Environment -eq "test") {
|
||||
} else {
|
||||
$scopeId = "hxops-rpa-prod-data"
|
||||
}
|
||||
# freight_rpa 三层布局根:$WorkerRoot\data\freight_rpa\{inventory,receipt,common}(data 即 SMB 共享 hxops-rpa-*-data 的根,代码包 scripts 不进共享)。
|
||||
# freight_rpa 分域布局根:$WorkerRoot\data\freight_rpa\{onhand,inbound,outbound,common}
|
||||
# (data 即 SMB 共享 hxops-rpa-*-data 的根,代码包 scripts 不进共享;2026-10-16 批次 R 起
|
||||
# inventory/receipt 目录名切换为 onhand/inbound,upload 域迁至独立 outbound/)。
|
||||
$rpaRoot = Join-Path $WorkerRoot "data\freight_rpa"
|
||||
|
||||
function ConvertTo-PlainText {
|
||||
@@ -79,8 +81,9 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
|
||||
FREIGHT_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
|
||||
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
|
||||
# 稳定 Worker 身份:监控端心跳卡片不再随进程重启漂移(缺省回退 <hostname>-<pid>)。
|
||||
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-inventory"
|
||||
# 稳定 Worker 身份:监控端心跳卡片不再随进程重启漂移(缺省回退 <hostname>-<pid>);
|
||||
# onhand 固定后缀 -onhand,与 inbound Worker 的 -inbound 区分(后端就绪检查按后缀判定)。
|
||||
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-onhand"
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = "20"
|
||||
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
|
||||
@@ -89,12 +92,13 @@ $processVars = [ordered]@{
|
||||
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium。
|
||||
# Edge 152 + 持久 Profile 下载会原生崩溃(TargetClosed / .crdownload),禁止默认 msedge。
|
||||
FREIGHT_RPA_WORKER_POLL_SECONDS = "3"
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaRoot "inventory\triggers"
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaRoot "inventory\drop"
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaRoot "inventory\upload_triggers"
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaRoot "inventory\upload_queue"
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = Join-Path $rpaRoot "onhand\triggers"
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = Join-Path $rpaRoot "onhand\drop"
|
||||
# 上传与 onhand/inbound/outbound 同级:freight_rpa/upload/{triggers,queue}。
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaRoot "upload\triggers"
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaRoot "upload\queue"
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot "common\browser_profile"
|
||||
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot "inventory\logs\worker.log"
|
||||
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot "onhand\logs\worker.log"
|
||||
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = "10485760"
|
||||
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = "5"
|
||||
# 本机磁盘保留:归档 trigger/drop、日志备份、upload_queue、孤儿 run_* Profile;会话 Profile 不删。
|
||||
@@ -0,0 +1,78 @@
|
||||
"""
|
||||
scripts/freight_rpa/outbound/outbound_crane_export.py
|
||||
|
||||
用途:Crane 出站报表导出适配器——固定 Outbound Details,委托共享 crane_report_export。
|
||||
依赖:crane_report_export、crane_session。
|
||||
逻辑:outbound_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
|
||||
driver 在 Playwright 未返回 Download 时做目录兜底。
|
||||
页面名/hash 已实测确认(2026-10-20):report_name=Outbound Details、
|
||||
hash=#/outbound-details-query 与门户 Queries 菜单实名一致(导航侧由
|
||||
crane_navigation 按 entry_url 推导卡片/菜单;门户刷新即掉登录,登录态下禁止整页导航)。
|
||||
若门户调整 hash,只改本文件常量并同步管理端校验。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "onhand").is_dir() and (_c / "outbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound", "outbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
import crane_report_export
|
||||
import crane_session
|
||||
|
||||
# Task 6 / D7 占位:与管理端 Crane outbound 固定页同名。禁止改成 Inbound Details。
|
||||
_OUTBOUND_REPORT_NAME = 'Outbound Details'
|
||||
_OUTBOUND_DETAILS_HASH = '/outbound-details-query'
|
||||
|
||||
|
||||
def _outbound_details_entry_url(login_url: str) -> str:
|
||||
"""将复用的 Crane Profile 登录地址固定到出站 Outbound Details 路由。"""
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise RuntimeError('Crane outbound unit requires an absolute login_url')
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, _OUTBOUND_DETAILS_HASH))
|
||||
|
||||
|
||||
def export_outbound_report(
|
||||
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
|
||||
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
|
||||
) -> Any:
|
||||
"""
|
||||
创建并下载唯一 Description 对应的 Crane Outbound Details 文件。
|
||||
|
||||
核心逻辑:固定 scheduled_report_name=Outbound Details;把 unit.__download_dir
|
||||
写入 source,供共享 crane_report_export 目录兜底(对齐库存/入站)。
|
||||
"""
|
||||
report_path = dict(unit.get('report_path_json') or {})
|
||||
if str(report_path.get('report_name') or '').strip() != _OUTBOUND_REPORT_NAME:
|
||||
raise RuntimeError('Crane outbound report must be Outbound Details')
|
||||
entry_url = _outbound_details_entry_url(str(unit.get('login_url') or '').strip())
|
||||
if first_in_profile:
|
||||
page.goto(entry_url, wait_until='domcontentloaded', timeout=browser_timeout_ms)
|
||||
crane_session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||||
crane_session.wait_for_crane_app_ready(page, entry_url, env=env, browser_timeout_ms=browser_timeout_ms)
|
||||
# Scheduled Reports 匹配名来自 source;出站固定为 Outbound Details,
|
||||
# 不能沿用库存 OnHandDetails.xlsx 或入站 Inbound Details。
|
||||
source = {
|
||||
'entry_url': entry_url,
|
||||
'scheduled_report_name': 'Outbound Details',
|
||||
'__download_dir': str(unit.get('__download_dir') or ''),
|
||||
}
|
||||
return crane_report_export.export_crane_inventory_report(
|
||||
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
|
||||
browser_timeout_ms=browser_timeout_ms, select_or_fill=select_or_fill, click_text=click_text,
|
||||
)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
scripts/freight_rpa/outbound/outbound_dbs_export.py
|
||||
|
||||
用途:DBS 出站报表导出适配器——把 unit 转成与库存同构的 DSV source,再委托共享导出驱动。
|
||||
依赖:connectors/dsv/dsv_report_export。
|
||||
逻辑:outbound_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
|
||||
调用 prepare_dsv_batch_export_step 完成;本模块只负责 source 组装与单次导出。
|
||||
source 写入 __export_kind__=outbound,共享驱动用出站就绪探针,不用库存/收料字段。
|
||||
导航取配置 report_path_json(禁止写死入站/库存报表名);query_parameters 原样下发;
|
||||
仅当 unit.warehouse_id 有值时追加单值 Warehouse(兼容旧 trigger)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "onhand").is_dir() and (_c / "outbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound", "outbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from typing import Any
|
||||
|
||||
import dsv_report_export
|
||||
|
||||
|
||||
def build_outbound_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
将出站 unit 组装为共享 dsv_report_export 可消费的 source。
|
||||
|
||||
核心逻辑:report_path_json → navigation(驱动只读 navigation/query);
|
||||
parameters 取自 query_parameters_json;有 warehouse_id 时追加单值 Warehouse。
|
||||
|
||||
Args:
|
||||
unit: 出站 trigger 单元(含 report_path_json / query_parameters_json 等)。
|
||||
entry_url: 该 Profile 分组的登录入口 URL。
|
||||
|
||||
Returns:
|
||||
与库存 trigger source 同构的 dict,可供 prepare_dsv_batch_export_step 与导出使用。
|
||||
"""
|
||||
report_path = dict(unit.get('report_path_json') or {})
|
||||
source: dict[str, Any] = {
|
||||
'entry_url': entry_url,
|
||||
'report_path_json': report_path,
|
||||
# 与库存 trigger 同构:Source.report_path_json → navigation,供菜单导航使用。
|
||||
'navigation': report_path,
|
||||
'parameters': list(unit.get('query_parameters_json') or []),
|
||||
'__download_dir': str(unit.get('__download_dir') or ''),
|
||||
# 显式标记出站导出:共享 dsv_report_export 用 outbound 就绪探针,不用库存/收料字段。
|
||||
'__export_kind__': 'outbound',
|
||||
}
|
||||
warehouse_id = str(unit.get('warehouse_id') or '').strip()
|
||||
if warehouse_id:
|
||||
source['parameters'].append({
|
||||
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
|
||||
'required': True, 'select_all': False,
|
||||
})
|
||||
return source
|
||||
|
||||
|
||||
def export_outbound_report(
|
||||
page: Any,
|
||||
unit: dict[str, Any],
|
||||
*,
|
||||
entry_url: str,
|
||||
skip_navigation: bool = False,
|
||||
) -> Any:
|
||||
"""
|
||||
在既有 DBS 登录态内执行出站路径与受控非日期条件。
|
||||
|
||||
核心逻辑:组装 source 后委托 export_dsv_inventory_source;会话登录与参数页复用
|
||||
由 Worker 侧 prepare_dsv_batch_export_step 完成。skip_navigation=True 时跳过菜单导航,
|
||||
直接在已就绪的参数页填参导出(同导航批内复用)。
|
||||
|
||||
Args:
|
||||
page: 当前 Playwright Page(批内复用同一 tab,禁止每源 new_page)。
|
||||
unit: 出站 trigger 单元。
|
||||
entry_url: 登录入口 URL。
|
||||
skip_navigation: 为 True 时跳过报表菜单导航(参数页已由 prepare 就绪)。
|
||||
|
||||
Returns:
|
||||
Playwright Download 对象。
|
||||
"""
|
||||
source = build_outbound_dsv_source(unit, entry_url=entry_url)
|
||||
return dsv_report_export.export_dsv_inventory_source(
|
||||
page,
|
||||
{'action': 'outbound_export_batch'},
|
||||
source,
|
||||
skip_navigation=skip_navigation,
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
scripts/freight_rpa/outbound/outbound_excel_empty.py
|
||||
|
||||
用途:出站 Excel「有表头无明细」判空(真相源,对齐入站 Excel 判空)。
|
||||
依赖:openpyxl(运行期可选;缺失时不强制 empty)。
|
||||
逻辑:outbound_rpa_worker 落盘校验后调用;标题行(如 Outbound Details)
|
||||
不得当成表头,否则真表头会被误判为明细导致假 success。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class NoOutboundDataError(RuntimeError):
|
||||
"""出站报表可打开且有表头,但无业务明细行(合法 empty / no_outbound_data)。"""
|
||||
|
||||
|
||||
def _normalize_row_joined(row: tuple | list) -> str:
|
||||
"""
|
||||
将一行单元格规范为小写比较串。
|
||||
|
||||
核心逻辑:换行压成空格,去空白后用 | 拼接。
|
||||
"""
|
||||
parts: list[str] = []
|
||||
for cell in row:
|
||||
if cell is None:
|
||||
continue
|
||||
text = ' '.join(str(cell).replace('\n', ' ').replace('\r', ' ').split()).strip()
|
||||
if text:
|
||||
parts.append(text.lower())
|
||||
return ' | '.join(parts)
|
||||
|
||||
|
||||
def is_outbound_excel_header_row(joined: str) -> bool:
|
||||
"""
|
||||
判断是否为出站列标题行(非报表标题行)。
|
||||
|
||||
核心逻辑:要求 sku/quantity 与 outbound/shipment/dispatch 等组合特征;
|
||||
单独含 outbound(如「Outbound Details」标题)不得命中。
|
||||
"""
|
||||
if not joined:
|
||||
return False
|
||||
has_sku = 'sku' in joined or 'part number' in joined or 'item' in joined
|
||||
has_qty = 'quantity' in joined or 'qty' in joined
|
||||
has_move = (
|
||||
'outbound' in joined
|
||||
or 'shipment' in joined
|
||||
or 'dispatch' in joined
|
||||
or 'shipped' in joined
|
||||
or 'ship to' in joined
|
||||
)
|
||||
if has_sku and has_qty and has_move:
|
||||
return True
|
||||
if 'warehouse' in joined and has_move and (has_sku or has_qty):
|
||||
return True
|
||||
if 'supplier id' in joined and 'aws sku' in joined and has_move:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def outbound_excel_has_detail_rows(path: Path) -> bool | None:
|
||||
"""
|
||||
判断出站 Excel 列标题之后是否有明细行。
|
||||
|
||||
核心逻辑:先定位严格表头行,再扫描其后非空行;无法识别表头时返回 None
|
||||
(不强制 empty,由结构校验兜底)。
|
||||
|
||||
Returns:
|
||||
True: 有明细;False: 有表头无明细;None: 未识别表头形态。
|
||||
"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError:
|
||||
return None
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
worksheet = workbook.active
|
||||
if worksheet is None:
|
||||
return None
|
||||
header_idx: int | None = None
|
||||
for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1):
|
||||
joined = _normalize_row_joined(row or ())
|
||||
if not joined:
|
||||
continue
|
||||
if header_idx is None:
|
||||
if is_outbound_excel_header_row(joined):
|
||||
header_idx = idx
|
||||
continue
|
||||
if idx > header_idx:
|
||||
return True
|
||||
if header_idx is None:
|
||||
return None
|
||||
return False
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def enforce_outbound_excel_not_empty(path: Path) -> None:
|
||||
"""
|
||||
有表头无明细时记为无出站(NoOutboundDataError → empty / no_outbound_data)。
|
||||
|
||||
Raises:
|
||||
NoOutboundDataError: 可识别表头但无业务行;message 固定为 no_outbound_data。
|
||||
"""
|
||||
if outbound_excel_has_detail_rows(path) is False:
|
||||
raise NoOutboundDataError('no_outbound_data')
|
||||
@@ -0,0 +1,876 @@
|
||||
"""
|
||||
scripts/freight_rpa/outbound/outbound_rpa_worker.py
|
||||
|
||||
用途:独立货代出站 RPA Worker——仅消费 outbound trigger,不触及库存/入站 Worker 的目录或 callback。
|
||||
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
|
||||
outbound_excel_empty、outbound_dbs_export、outbound_crane_export、connectors/dsv/dsv_report_export。
|
||||
逻辑:排程写入 outbound trigger → 本进程领取并按 connector/profile 分组串行导出 →
|
||||
导出重试只覆盖落盘/校验(对齐库存/入站);有表头无明细 → empty/no_outbound_data;
|
||||
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
|
||||
批级失败(如 launch_persistent_context 浏览器已关)须对本组未终态单元逐笔
|
||||
failed 回调——与 inbound/onhand 同契约,禁止只归档 trigger 不收口单元。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "onhand").is_dir() and (_c / "outbound").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound", "outbound"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file # noqa: E402
|
||||
import rpa_callbacks # noqa: E402
|
||||
from rpa_callbacks import ( # noqa: E402
|
||||
OUTBOUND_BATCH_PROGRESS,
|
||||
OUTBOUND_BATCH_READY,
|
||||
OUTBOUND_UNIT_PROGRESS,
|
||||
)
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_logging # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
|
||||
import dsv_report_export # noqa: E402
|
||||
import outbound_crane_export # noqa: E402
|
||||
import outbound_dbs_export # noqa: E402
|
||||
from outbound_excel_empty import ( # noqa: E402
|
||||
NoOutboundDataError,
|
||||
enforce_outbound_excel_not_empty as _enforce_outbound_excel_not_empty,
|
||||
)
|
||||
|
||||
_EXPORT_UNIT_MAX_ATTEMPTS = 2
|
||||
_EXPORT_UNIT_RETRY_WAIT_SECONDS = 30
|
||||
_OUTBOUND_EXCEL_MIN_BYTES = 512
|
||||
# 结构校验可用较宽标记;「有表头无明细」判空见 outbound_excel_empty。
|
||||
_OUTBOUND_EXCEL_HEADER_MARKERS = (
|
||||
'outbound',
|
||||
'shipment',
|
||||
'dispatch',
|
||||
'shipped',
|
||||
'ship qty',
|
||||
'po number',
|
||||
'po #',
|
||||
'sku',
|
||||
'quantity',
|
||||
'warehouse',
|
||||
)
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
|
||||
return _RPA_ROOT.parents[1] / 'backend'
|
||||
|
||||
|
||||
def _mask_secret(value: str | None) -> str:
|
||||
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
|
||||
value = str(value or '').strip()
|
||||
if len(value) <= 8:
|
||||
return '***' if value else 'missing'
|
||||
return f'{value[:4]}....{value[-4:]}'
|
||||
|
||||
|
||||
def _require_dir(variable: str) -> Path:
|
||||
"""读取 outbound 专用目录;不回退至 onhand/inbound 共享路径。"""
|
||||
value = env(variable)
|
||||
if not value:
|
||||
raise SystemExit(f'Missing env: {variable}')
|
||||
path = Path(value)
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / value).resolve()
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _post_rpa(path: str, payload: dict[str, Any], *, timeout: int = 30) -> None:
|
||||
"""向 HXOPS 出站 RPA 回调 API 上报(薄封装,统一走 /api/freight-rpa/*)。
|
||||
|
||||
核心逻辑:鉴权、脱敏日志与 HTTP 错误处理收拢到 common/rpa_callbacks.post_callback;
|
||||
保留 (path, payload, timeout) 签名,便于测试 monkeypatch 与既有调用点零改动。
|
||||
"""
|
||||
rpa_callbacks.post_callback(path, payload, timeout=timeout)
|
||||
|
||||
|
||||
def _post_callback(payload: dict[str, Any]) -> None:
|
||||
"""向独立出站 callback 上报一个单元终态结果。"""
|
||||
_post_rpa(OUTBOUND_BATCH_READY, payload)
|
||||
|
||||
|
||||
def _mark_unit_processing(unit: dict[str, Any]) -> None:
|
||||
"""开始导出前标记 processing;失败不影响导出主链路。"""
|
||||
try:
|
||||
_post_rpa(
|
||||
OUTBOUND_UNIT_PROGRESS,
|
||||
{
|
||||
'schema_version': 'freight_rpa.outbound.v1',
|
||||
'callback_id': unit.get('callback_id'),
|
||||
'status': 'processing',
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f'[outbound-unit] processing progress failed: {exc}', file=_sys.stderr)
|
||||
|
||||
|
||||
def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
|
||||
"""每完成一笔导出回传累计进度(对齐 inbound-batch-progress)。"""
|
||||
schedule_run_id = body.get('schedule_run_id')
|
||||
if schedule_run_id is None:
|
||||
return
|
||||
try:
|
||||
_post_rpa(
|
||||
OUTBOUND_BATCH_PROGRESS,
|
||||
{
|
||||
'schema_version': 'freight_rpa.outbound.v1',
|
||||
'schedule_run_id': schedule_run_id,
|
||||
'batch_run_no': body.get('batch_run_no') or body.get('run_no'),
|
||||
'success_count': int(counts.get('success') or 0),
|
||||
'skipped_count': int(counts.get('empty') or 0),
|
||||
'failed_count': int(counts.get('failed') or 0),
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f'[outbound-batch] progress callback failed: {exc}', file=_sys.stderr)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _profile_credentials(unit: dict[str, Any]):
|
||||
"""在单个 Profile 分组内临时解密凭据并清理环境,绝不输出明文。"""
|
||||
envelope = unit.get('credential_envelope') or {}
|
||||
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('FREIGHT_RPA_CREDENTIAL_KEY')
|
||||
if not key:
|
||||
raise RuntimeError('FREIGHT_RPA_CREDENTIAL_KEY is required')
|
||||
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 = str(unit.get('connector_type') or '').lower()
|
||||
names = ('FREIGHT_RPA_WORKER_DSV_USERNAME', 'FREIGHT_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('FREIGHT_RPA_WORKER_CRANE_USERNAME', 'FREIGHT_RPA_WORKER_CRANE_PASSWORD')
|
||||
before = {name: os.environ.get(name) for name in names}
|
||||
os.environ[names[0]], os.environ[names[1]] = username, password
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for name, old_value in before.items():
|
||||
if old_value is None:
|
||||
os.environ.pop(name, None)
|
||||
else:
|
||||
os.environ[name] = old_value
|
||||
|
||||
|
||||
def _session_reuse_enabled() -> bool:
|
||||
"""
|
||||
出站是否复用持久浏览器 Profile。
|
||||
|
||||
核心逻辑:对齐库存/入站——未设置或空值时默认开启;仅显式 false 时关闭。
|
||||
"""
|
||||
raw = env('FREIGHT_RPA_WORKER_SESSION_REUSE')
|
||||
if raw is None or str(raw).strip() == '':
|
||||
return True
|
||||
return str(raw).strip().strip("\"'").lower() == 'true'
|
||||
|
||||
|
||||
def _sanitize_profile_dir_segment(value: str) -> str:
|
||||
"""将 connector / profile_code 收成可作目录名的安全片段。"""
|
||||
text = str(value or '').strip()
|
||||
cleaned = ''.join(ch if (ch.isalnum() or ch in '-_') else '_' for ch in text)
|
||||
return (cleaned[:96] or 'default')
|
||||
|
||||
|
||||
def _session_profile_dir(connector_type: str, profile_code: str = '') -> Path:
|
||||
"""
|
||||
按 connector + RPA Profile 隔离的持久出站会话目录。
|
||||
|
||||
核心逻辑:形如 `{connector}__{profile_code}_session`(dbs/crane 与库存 dsv360/crane_footprint
|
||||
命名空间分离,避免串 Cookie);禁止所有出站源共用单一 outbound_session。
|
||||
"""
|
||||
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
|
||||
connector = _sanitize_profile_dir_segment(connector_type or 'unknown')
|
||||
code = _sanitize_profile_dir_segment(profile_code)
|
||||
return profile_root / f'{connector}__{code}_session'
|
||||
|
||||
|
||||
def _open_browser(
|
||||
download_dir: Path,
|
||||
*,
|
||||
reuse_session: bool = False,
|
||||
connector_type: str = '',
|
||||
profile_code: str = '',
|
||||
):
|
||||
"""为一个 outbound Profile 分组创建浏览器上下文,组内登录一次、串行导出。
|
||||
|
||||
reuse_session=True 且 SESSION_REUSE 开启:持久 `{connector}__{profile}_session`;
|
||||
否则一次性临时 Profile(outbound_* 前缀),批次结束即删。
|
||||
"""
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('Playwright is required for real outbound RPA') from exc
|
||||
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
|
||||
use_reused = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
|
||||
if use_reused:
|
||||
runtime_profile = _session_profile_dir(connector_type, profile_code)
|
||||
runtime_profile.mkdir(parents=True, exist_ok=True)
|
||||
profile_mode = 'session_reuse'
|
||||
else:
|
||||
runtime_profile = Path(tempfile.mkdtemp(prefix='outbound_', dir=str(profile_root)))
|
||||
profile_mode = 'temporary'
|
||||
print(
|
||||
f'[browser] profile_mode={profile_mode} connector={connector_type or "-"} '
|
||||
f'profile={profile_code or "-"} dir={runtime_profile.name!r}'
|
||||
)
|
||||
playwright = sync_playwright().start()
|
||||
options: dict[str, Any] = {
|
||||
'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true',
|
||||
'accept_downloads': True,
|
||||
'downloads_path': str(download_dir),
|
||||
}
|
||||
channel = env('FREIGHT_RPA_WORKER_BROWSER_CHANNEL')
|
||||
if channel:
|
||||
options['channel'] = channel
|
||||
context = playwright.chromium.launch_persistent_context(str(runtime_profile), **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
|
||||
|
||||
|
||||
def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
|
||||
"""
|
||||
在同一登录上下文中切换到干净页面,隔离上一站的 DSV 报表状态。
|
||||
|
||||
核心逻辑:对齐库存 Worker——新开空白页并关闭旧页;Cookie 仍在 context 内,
|
||||
仅用于会话准备失败后的一次完整登录重试,禁止作为常态「每源新开空白页」。
|
||||
|
||||
Args:
|
||||
context: 已建立登录态的 Playwright browser context。
|
||||
current_page: 上一站页面;关闭以避免报表 iframe / 下载菜单残留。
|
||||
|
||||
Returns:
|
||||
可重新进入出站报表的空白页面。
|
||||
"""
|
||||
next_page = context.new_page()
|
||||
next_page.set_default_timeout(browser_timeout_ms())
|
||||
if current_page is not None:
|
||||
try:
|
||||
current_page.close()
|
||||
except Exception as exc:
|
||||
print(f'[outbound-batch] close previous page failed: {exc}', file=_sys.stderr)
|
||||
return next_page
|
||||
|
||||
|
||||
def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
|
||||
"""
|
||||
导出前拍摄下载目录已有文件名,供目录兜底识别「本次新文件」。
|
||||
|
||||
核心逻辑:仅收集普通文件名;目录不可读时返回空集合(对齐库存)。
|
||||
"""
|
||||
try:
|
||||
return {path.name for path in drop_dir.iterdir() if path.is_file()}
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def _is_playwright_target_closed_error(exc: BaseException) -> bool:
|
||||
"""判断是否为 Playwright 页面/上下文已关闭导致的落盘失败。"""
|
||||
message = str(exc).lower()
|
||||
return 'has been closed' in message or 'target closed' in message or 'targetclosed' in message
|
||||
|
||||
|
||||
def _persist_download_to_dest(
|
||||
download: Any,
|
||||
dest: Path,
|
||||
*,
|
||||
drop_dir: Path,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> None:
|
||||
"""
|
||||
将 Playwright Download 落到规范路径;浏览器已关闭时走 downloads_path 目录兜底。
|
||||
|
||||
核心逻辑:对齐库存 `_persist_download_to_dest`——先 save_as,TargetClosed
|
||||
再按 baseline 等待稳定新文件后搬迁。
|
||||
"""
|
||||
try:
|
||||
download.save_as(str(dest))
|
||||
return
|
||||
except Exception as exc:
|
||||
if not _is_playwright_target_closed_error(exc):
|
||||
raise
|
||||
print(
|
||||
f'[outbound-artifact] stage=download_save status=fallback '
|
||||
f'reason=browser_closed path={dest.name!r}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
artifact = _wait_for_new_download_file(
|
||||
download_dir=drop_dir,
|
||||
baseline_names=set(baseline_names or ()),
|
||||
timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if artifact is None:
|
||||
raise
|
||||
artifact.save_as(str(dest))
|
||||
|
||||
|
||||
def _outbound_download_name(
|
||||
batch_run_no: str,
|
||||
source_code: str,
|
||||
warehouse_id: str | None,
|
||||
*,
|
||||
suffix: str = '.xlsx',
|
||||
) -> str:
|
||||
"""
|
||||
出站落盘文件名,对齐库存 `_batch_download_name`。
|
||||
|
||||
核心逻辑:`outbound_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
|
||||
不写入 callback_id(关联仍靠 callback JSON)。
|
||||
|
||||
Args:
|
||||
batch_run_no: trigger 顶层批次号。
|
||||
source_code: 库存源编码(辨识用)。
|
||||
warehouse_id: 可选仓码;空则 NA。
|
||||
suffix: 扩展名,默认 .xlsx。
|
||||
|
||||
Returns:
|
||||
安全化后的文件名(不含目录)。
|
||||
"""
|
||||
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'outbound'
|
||||
safe_source = ''.join(ch for ch in str(source_code or '') if ch.isalnum() or ch in {'-', '_'}) or 'UNKNOWN'
|
||||
safe_wh = ''.join(ch for ch in str(warehouse_id or '') if ch.isalnum() or ch in {'-', '_'}) or 'NA'
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')
|
||||
return f'outbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
|
||||
|
||||
|
||||
def _save_download(
|
||||
download: Any,
|
||||
drop_dir: Path,
|
||||
unit: dict[str, Any],
|
||||
*,
|
||||
batch_run_no: str,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> Path:
|
||||
"""
|
||||
保存本单元下载文件到 outbound drop;必要时在浏览器关闭后走目录兜底。
|
||||
|
||||
核心逻辑:按 run+source(+仓) 命名后 `_persist_download_to_dest`;空文件拒绝。
|
||||
"""
|
||||
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
|
||||
if suffix != '.xlsx':
|
||||
raise RuntimeError('outbound report download must be xlsx')
|
||||
target = drop_dir / _outbound_download_name(
|
||||
batch_run_no,
|
||||
str(unit.get('source_code') or ''),
|
||||
unit.get('warehouse_id'),
|
||||
suffix=suffix,
|
||||
)
|
||||
_persist_download_to_dest(
|
||||
download,
|
||||
target,
|
||||
drop_dir=drop_dir,
|
||||
baseline_names=baseline_names,
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if target.stat().st_size <= 0:
|
||||
raise RuntimeError('outbound report download is empty')
|
||||
return target
|
||||
|
||||
|
||||
def _validate_outbound_excel(path: Path) -> None:
|
||||
"""
|
||||
校验出站 Excel 可打开且具备报表基本结构。
|
||||
|
||||
核心逻辑:对齐 inbound `_validate_inbound_excel`——拒过小/HTML 伪装文件;
|
||||
前几行或 sheet 标题须含出站报表特征,避免错误页当 success 归档。
|
||||
"""
|
||||
size = path.stat().st_size
|
||||
if size < _OUTBOUND_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f'downloaded outbound Excel is too small ({size} bytes)')
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('openpyxl required to validate outbound 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 _OUTBOUND_EXCEL_HEADER_MARKERS):
|
||||
if 'outbound' not in title and 'shipment' not in title:
|
||||
raise RuntimeError('downloaded file is not valid Excel: missing outbound report headers')
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _validate_unit(unit: dict[str, Any]) -> None:
|
||||
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
|
||||
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
|
||||
if not str(unit.get(key) or '').strip():
|
||||
raise RuntimeError(f'outbound unit missing {key}')
|
||||
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
|
||||
raise RuntimeError('unsupported outbound connector_type')
|
||||
parameters = list(unit.get('query_parameters_json') or [])
|
||||
if any('date' in str(row.get('name') or '').lower() for row in parameters if isinstance(row, dict)):
|
||||
raise RuntimeError('outbound date filtering is forbidden')
|
||||
|
||||
|
||||
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
|
||||
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
|
||||
print(f'[outbound-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
|
||||
_post_callback({'schema_version': 'freight_rpa.outbound.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.OUTBOUND_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
|
||||
|
||||
def _report_group_open_failure(group: list[dict[str, Any]], exc: Exception) -> None:
|
||||
"""批级浏览器打开/组级异常时,为组内全部单元补发 failed 回调。
|
||||
|
||||
用途:``_open_browser`` 在进入单元循环前失败时,原先只把 trigger 归档到 failed/
|
||||
而不回调 → 后端单元永久 awaiting_rpa、调拨来源投影永久 fetching 且批量重试锁死
|
||||
(须等 FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 孤儿回收)。与 inbound Worker
|
||||
``_report_group_open_failure`` 同契约。本函数 best-effort 逐笔 ``_report_failure``,
|
||||
单笔回调失败只打日志不中断其余。
|
||||
|
||||
Args:
|
||||
group: 同一 connector/profile/login 下尚未进入终态回调的单元列表。
|
||||
exc: 批级异常(通常为 Playwright TargetClosed / launch_persistent_context)。
|
||||
"""
|
||||
print(
|
||||
f'[outbound-batch] open/group failed; reporting {len(group)} unit failure callback(s): '
|
||||
f'{str(exc)[:200]}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
for unit in group:
|
||||
try:
|
||||
_report_failure(unit, exc)
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[outbound-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def _report_empty(unit: dict[str, Any], exc: NoOutboundDataError) -> None:
|
||||
"""无业务明细的合法结果:回调 empty + no_outbound_data(后端 finalize 计 skipped)。"""
|
||||
print(f'[outbound-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
|
||||
_post_callback({
|
||||
'schema_version': 'freight_rpa.outbound.v1',
|
||||
'callback_id': unit.get('callback_id'),
|
||||
'status': 'empty',
|
||||
'error_code': 'no_outbound_data',
|
||||
'error_message': str(exc)[:2000] or 'no_outbound_data',
|
||||
})
|
||||
|
||||
|
||||
def _is_login_session_error(exc: BaseException) -> bool:
|
||||
"""登录/会话类偶发异常可干净页重试;凭据校验类不重试。"""
|
||||
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'))
|
||||
return login_related and not credential_mismatch
|
||||
|
||||
|
||||
def _export_unit_download(
|
||||
*,
|
||||
connector: str,
|
||||
unit: dict[str, Any],
|
||||
group: list[dict[str, Any]],
|
||||
index: int,
|
||||
login_url: str,
|
||||
page: Any,
|
||||
context: Any,
|
||||
drop_dir: Path,
|
||||
attempt: int = 1,
|
||||
) -> tuple[Any, Any]:
|
||||
"""
|
||||
导出单个出站单元的 Playwright Download;必要时干净页重试会话。
|
||||
|
||||
Args:
|
||||
attempt: 第几次尝试(1 起)。>1 时强制完整重导航(对齐库存 2026-09-20 AWSRTM
|
||||
兜底:报表页导出菜单缺失属瞬态故障,绝不在错误页上直接重试,须回入口页
|
||||
重选菜单进报表),且 prepare 的导航/会话类异常一并走干净页安全网
|
||||
(凭据校验类 invalid/verification 为确定性失败,不重试)。
|
||||
Returns:
|
||||
(download, page):download 为 Playwright Download;page 可能已切换为干净页。
|
||||
"""
|
||||
unit['__download_dir'] = str(drop_dir)
|
||||
if connector == 'dbs':
|
||||
source = outbound_dbs_export.build_outbound_dsv_source(unit, entry_url=login_url)
|
||||
force_full_navigation = attempt > 1
|
||||
previous_unit = group[index - 1] if (index > 0 and not force_full_navigation) else None
|
||||
previous_source = (
|
||||
outbound_dbs_export.build_outbound_dsv_source(previous_unit, entry_url=login_url)
|
||||
if previous_unit is not None else None
|
||||
)
|
||||
skip_navigation = False
|
||||
try:
|
||||
skip_navigation = bool(
|
||||
dsv_report_export.prepare_dsv_batch_export_step(
|
||||
page, login_url, previous_source, source,
|
||||
index=0 if force_full_navigation else index,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
message = str(exc).lower()
|
||||
if any(token in message for token in ('invalid', 'verification')):
|
||||
raise
|
||||
print(
|
||||
f'[outbound-batch] dbs prepare failed for {unit.get("source_code")}, '
|
||||
f'retry with clean page: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
skip_navigation = bool(
|
||||
dsv_report_export.prepare_dsv_batch_export_step(
|
||||
page, login_url, None, source, index=0,
|
||||
)
|
||||
)
|
||||
download = outbound_dbs_export.export_outbound_report(
|
||||
page, unit, entry_url=login_url, skip_navigation=skip_navigation,
|
||||
)
|
||||
return download, page
|
||||
|
||||
first_in_profile = index == 0 or attempt > 1
|
||||
try:
|
||||
download = outbound_crane_export.export_outbound_report(
|
||||
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
|
||||
select_or_fill=select_or_fill, click_text=click_text,
|
||||
first_in_profile=first_in_profile,
|
||||
)
|
||||
return download, page
|
||||
except Exception as exc:
|
||||
if not _is_login_session_error(exc):
|
||||
raise
|
||||
print(
|
||||
f'[outbound-batch] crane session failed for {unit.get("source_code")}, '
|
||||
f'retry with clean page: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
download = outbound_crane_export.export_outbound_report(
|
||||
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
|
||||
select_or_fill=select_or_fill, click_text=click_text,
|
||||
first_in_profile=True,
|
||||
)
|
||||
return download, page
|
||||
|
||||
|
||||
def _write_mock_outbound_excel(path: Path) -> None:
|
||||
"""Mock 模式写出带表头+一行明细的合法出站 Excel,便于走校验与 success 回调。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = 'OutboundDetail'
|
||||
sheet.append(['Warehouse', 'SKU', 'Quantity Shipped', 'Outbound'])
|
||||
sheet.append(['WH-MOCK-1', 'SKU-1', 1, 'OUT-1'])
|
||||
workbook.save(path)
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _post_unit_ready(unit: dict[str, Any], output: Path) -> None:
|
||||
"""落盘成功后上报 outbound-batch-ready(归档);调用方须放在导出重试之外。
|
||||
|
||||
file_path 契约为「drop 根内文件名」:Worker(Windows)与后端(Linux 挂载根)分属
|
||||
两机、根路径不同。规格 §4.2 跨机路径契约:必须 Path(local_drop_file).name,
|
||||
禁止把 C:\\...\\drop\\xxx.xlsx 整串作为契约主值(跨机下发本机绝对路径必 400)。
|
||||
"""
|
||||
_post_callback({
|
||||
'schema_version': 'freight_rpa.outbound.v1',
|
||||
'callback_id': unit['callback_id'],
|
||||
'status': 'success',
|
||||
'file_path': output.name,
|
||||
'original_filename': output.name,
|
||||
'sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
})
|
||||
|
||||
|
||||
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
"""
|
||||
按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 出站单元。
|
||||
|
||||
核心逻辑:DBS 与库存对齐——同 Profile 组内复用同一 tab;导出失败批次内最多重试 2 次,
|
||||
**重试只覆盖导出/落盘/校验**(对齐库存 record_result 前段)。落盘成功后先轻量
|
||||
``outbound-batch-progress``(管理端实时笔数),再调 ``outbound-batch-ready`` 归档;
|
||||
ready/empty/failed 回调失败不得触发重新下载(2026-09-28 偶发同源双文件根因)。
|
||||
"""
|
||||
units = body.get('units')
|
||||
if body.get('schema_version') != 'freight_rpa.outbound.v1' or body.get('action') != 'outbound_export_batch' or not isinstance(units, list) or not units:
|
||||
raise RuntimeError('invalid outbound trigger contract')
|
||||
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'outbound').strip() or 'outbound'
|
||||
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
|
||||
for item in units:
|
||||
if not isinstance(item, dict):
|
||||
raise RuntimeError('outbound unit must be object')
|
||||
_validate_unit(item)
|
||||
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
|
||||
progress_counts = {'success': 0, 'empty': 0, 'failed': 0}
|
||||
for (connector, profile_code, login_url), group in grouped.items():
|
||||
print(f'[outbound-batch] connector={connector} profile={profile_code} units={len(group)}')
|
||||
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
|
||||
reuse_session = _session_reuse_enabled()
|
||||
resources = (None, None, None, None)
|
||||
# [STEP] 已终态回调的 callback_id:批级异常时只给剩余单元补 failed,避免双重终态。
|
||||
reported_callback_ids: set[str] = set()
|
||||
try:
|
||||
if not mock:
|
||||
resources = _open_browser(
|
||||
drop_dir,
|
||||
reuse_session=reuse_session,
|
||||
connector_type=connector,
|
||||
profile_code=profile_code,
|
||||
)
|
||||
playwright, context, page, profile_dir = resources
|
||||
with _profile_credentials(group[0]):
|
||||
for index, unit in enumerate(group):
|
||||
_mark_unit_processing(unit)
|
||||
output: Path | None = None
|
||||
terminal: tuple[str, BaseException] | None = None
|
||||
# [RETRY] 仅导出/落盘/校验;ready 回调禁止进入本循环。
|
||||
for attempt in range(1, _EXPORT_UNIT_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
if mock:
|
||||
mock_path = drop_dir / _outbound_download_name(
|
||||
batch_run_no,
|
||||
str(unit.get('source_code') or ''),
|
||||
unit.get('warehouse_id'),
|
||||
)
|
||||
_write_mock_outbound_excel(mock_path)
|
||||
output = mock_path
|
||||
else:
|
||||
baseline_names = _download_dir_baseline_names(drop_dir)
|
||||
download, page = _export_unit_download(
|
||||
connector=connector,
|
||||
unit=unit,
|
||||
group=group,
|
||||
index=index,
|
||||
login_url=login_url,
|
||||
page=page,
|
||||
context=context,
|
||||
drop_dir=drop_dir,
|
||||
attempt=attempt,
|
||||
)
|
||||
output = _save_download(
|
||||
download, drop_dir, unit, batch_run_no=batch_run_no,
|
||||
baseline_names=baseline_names,
|
||||
)
|
||||
_validate_outbound_excel(output)
|
||||
_enforce_outbound_excel_not_empty(output)
|
||||
break
|
||||
except NoOutboundDataError as exc:
|
||||
terminal = ('empty', exc)
|
||||
output = None
|
||||
break
|
||||
except Exception as exc:
|
||||
if attempt < _EXPORT_UNIT_MAX_ATTEMPTS:
|
||||
print(
|
||||
f'[outbound-batch] export failed {unit.get("source_code")} '
|
||||
f'(attempt {attempt}/{_EXPORT_UNIT_MAX_ATTEMPTS}), '
|
||||
f'retry in {_EXPORT_UNIT_RETRY_WAIT_SECONDS}s: {exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
time.sleep(_EXPORT_UNIT_RETRY_WAIT_SECONDS)
|
||||
continue
|
||||
terminal = ('failed', exc)
|
||||
output = None
|
||||
|
||||
# [STEP] 导出循环外:轻量 progress + 终态回调(对齐库存 progress / 批末 ready)
|
||||
if terminal is not None and terminal[0] == 'empty':
|
||||
try:
|
||||
_report_empty(unit, terminal[1]) # type: ignore[arg-type]
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[outbound-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
reported_callback_ids.add(str(unit.get('callback_id') or ''))
|
||||
progress_counts['empty'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
continue
|
||||
if terminal is not None and terminal[0] == 'failed':
|
||||
try:
|
||||
_report_failure(unit, terminal[1]) # type: ignore[arg-type]
|
||||
except Exception as callback_exc:
|
||||
print(
|
||||
f'[outbound-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
reported_callback_ids.add(str(unit.get('callback_id') or ''))
|
||||
progress_counts['failed'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
continue
|
||||
if output is None:
|
||||
continue
|
||||
print(
|
||||
f'[outbound-unit] success source={unit["source_code"]} '
|
||||
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
|
||||
)
|
||||
progress_counts['success'] += 1
|
||||
_emit_batch_progress(body, progress_counts)
|
||||
try:
|
||||
_post_unit_ready(unit, output)
|
||||
except Exception as callback_exc:
|
||||
# 文件已落盘:回调超时只打日志,禁止回到导出重试(同源双文件根因)。
|
||||
# 不调用 failed 回调,避免晚到的 ready 与 failed 竞态;人工可按 drop 文件补档。
|
||||
print(
|
||||
f'[outbound-unit] ready callback failed source={unit.get("source_code")} '
|
||||
f'file={output.name}: {callback_exc}',
|
||||
file=_sys.stderr,
|
||||
)
|
||||
reported_callback_ids.add(str(unit.get('callback_id') or ''))
|
||||
except Exception as exc:
|
||||
# [STEP] 批级失败(浏览器未开 / 凭据上下文崩 / 未捕获逃逸):剩余单元补 failed,
|
||||
# 与 inbound/onhand 同契约——禁止只归档 trigger 导致 awaiting_rpa 永挂。
|
||||
remaining = [
|
||||
unit for unit in group
|
||||
if str(unit.get('callback_id') or '') not in reported_callback_ids
|
||||
]
|
||||
if remaining:
|
||||
_report_group_open_failure(remaining, exc)
|
||||
raise
|
||||
finally:
|
||||
playwright, context, _page, profile_dir = resources
|
||||
if context is not None:
|
||||
context.close()
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
if profile_dir is not None and not (reuse_session and _session_reuse_enabled()):
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
"""原子领取一个 outbound trigger;成功归档 processed,异常归档 failed。
|
||||
|
||||
领取与归档统一走 common/trigger_consumer(四态目录契约),
|
||||
本函数只保留出站批次处理与 SystemExit 兜底。
|
||||
"""
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
return
|
||||
print(f'[outbound-trigger] claimed {claimed.name}')
|
||||
rpa_heartbeat.set_worker_runtime_status('busy')
|
||||
try:
|
||||
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
|
||||
archive_trigger(claimed, 'processed')
|
||||
print(f'[outbound-trigger] archived processed {claimed.name}')
|
||||
except (Exception, SystemExit):
|
||||
archive_trigger(claimed, 'failed')
|
||||
print(f'[outbound-trigger] archived failed {claimed.name}')
|
||||
raise
|
||||
finally:
|
||||
rpa_heartbeat.set_worker_runtime_status('idle')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""轮询出站专用 trigger 目录;不加载或扫描任何库存/inbound/upload 目录。"""
|
||||
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
|
||||
drop_dir = _require_dir('FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR')
|
||||
trigger_dir = _require_dir('FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR')
|
||||
poll = max(1, int(env('FREIGHT_RPA_WORKER_POLL_SECONDS', '3') or '3'))
|
||||
heartbeat_seconds = max(
|
||||
15,
|
||||
int(env('FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
|
||||
)
|
||||
last_cleanup_mono = 0.0
|
||||
cleanup_interval = cleanup_interval_seconds()
|
||||
# [STEP 1] 启动 banner:字段对齐库存/入站 Worker,排查时一处看全运行配置。
|
||||
print(
|
||||
'[freight_outbound_rpa_worker] started\n'
|
||||
f' mock={env("FREIGHT_RPA_WORKER_MOCK", "false")}\n'
|
||||
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
|
||||
f' poll_seconds={poll}\n'
|
||||
f' heartbeat_seconds={heartbeat_seconds}\n'
|
||||
f' headless={env("FREIGHT_RPA_WORKER_HEADLESS", "false")} '
|
||||
f'channel={env("FREIGHT_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
|
||||
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
|
||||
f' credential_key={_mask_secret(env("FREIGHT_RPA_CREDENTIAL_KEY"))}\n'
|
||||
f' trigger_dir={trigger_dir}\n'
|
||||
f' drop_dir={drop_dir}\n'
|
||||
f' browser_profile_dir={env("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
|
||||
f' log={worker_logging.active_log_path() or "stdout-only"}\n'
|
||||
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
|
||||
)
|
||||
|
||||
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
|
||||
"""按间隔执行保留清理;启动时强制一轮。
|
||||
|
||||
best-effort 语义:清理失败仅打印告警,不中断主循环;且无论成败都推进
|
||||
上次清理时钟(返回 now_mono),避免持续性故障在每次 poll 后立刻重试刷屏。
|
||||
"""
|
||||
nonlocal last_cleanup_mono
|
||||
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
|
||||
return last_cleanup_mono
|
||||
profile_root_raw = str(env('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
|
||||
try:
|
||||
stats = run_worker_disk_cleanup(
|
||||
onhand_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
|
||||
drop_dir=drop_dir,
|
||||
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
|
||||
log_file=worker_logging.active_log_path(),
|
||||
)
|
||||
print(format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
print(f'[outbound-cleanup] failed: {exc}')
|
||||
return now_mono
|
||||
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
|
||||
# 启动时立即上报一次心跳,让监控端第一时间出现独立的
|
||||
# `<hostname>-outbound` 出站 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
|
||||
)
|
||||
rpa_heartbeat.start_heartbeat_loop(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
while True:
|
||||
for path in sorted(trigger_dir.glob('*.json')):
|
||||
worker_logging.maybe_rotate_open_log()
|
||||
try:
|
||||
_claim_and_process(path, drop_dir)
|
||||
except Exception as exc:
|
||||
print(f'[outbound-trigger] failed {path.name}: {exc}')
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,183 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Register the test/prod Outbound RPA Worker scheduled tasks in FULL-BACKGROUND mode.
|
||||
|
||||
.DESCRIPTION
|
||||
Runs the Outbound Worker as a background scheduled task with NO visible console and
|
||||
NO visible browser (the Worker launches Playwright headless via -Headless).
|
||||
Deliberately ASCII-only so it parses identically under any Windows console code page.
|
||||
|
||||
Mirrors register_onhand_worker_tasks.ps1 one-to-one, with distinct task names so
|
||||
all three Workers can be registered side by side on the same host:
|
||||
- Onhand: "HXOPS Freight Onhand RPA Worker TEST/PROD"
|
||||
- Inbound: "HXOPS Freight Inbound RPA Worker TEST/PROD"
|
||||
- Outbound: "HXOPS Freight Outbound RPA Worker TEST/PROD"
|
||||
|
||||
Shape constraints (same as the onhand registration):
|
||||
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
|
||||
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
|
||||
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
|
||||
decrypted in a non-interactive context.
|
||||
- The RPA account should be configured for auto-logon and must not be locked
|
||||
/ logged-off, otherwise the AtLogOn task does not stay resident.
|
||||
- Before trusting headless, run the headless smoke preflight:
|
||||
set FREIGHT_RPA_WORKER_HEADLESS=true then run crane_login_smoke.py
|
||||
(the DBS portal has no smoke script - verify the first headless run visually).
|
||||
|
||||
Scope:
|
||||
All actions can target one environment or both via -Scope test|prod|all (default all).
|
||||
|
||||
Usage (run in the RPA account's PowerShell):
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 # register test+prod
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Scope test # register only test
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Start # start both now
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Start -Scope prod # start only prod
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Status -Scope test # only test
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Stop -Scope prod # stop only prod
|
||||
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Unregister # unregister both
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Register,
|
||||
[switch]$Start,
|
||||
[switch]$Stop,
|
||||
[switch]$Status,
|
||||
[switch]$Unregister,
|
||||
[ValidateSet("test", "prod", "all")]
|
||||
[string]$Scope = "all",
|
||||
[string]$TestApiBase = "http://192.168.100.192:8890",
|
||||
[string]$ProdApiBase = "http://192.168.100.230:8890",
|
||||
[string]$TestRoot = "C:\HxopsRpaTest",
|
||||
[string]$ProdRoot = "C:\HxopsRpaProd",
|
||||
[string]$SecretFile = "C:\HxopsRpaSecrets"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$TestTask = "HXOPS Freight Outbound RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Freight Outbound RPA Worker PROD"
|
||||
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
|
||||
function Get-TasksForScope {
|
||||
# Return the task name(s) selected by -Scope.
|
||||
param([string]$Scope)
|
||||
switch ($Scope) {
|
||||
"test" { return @($TestTask) }
|
||||
"prod" { return @($ProdTask) }
|
||||
default { return @($TestTask, $ProdTask) }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-Launcher {
|
||||
# Validate the launcher and DPAPI Secret file required for one environment.
|
||||
param([string]$Root, [string]$Environment)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\outbound\start_outbound_worker.ps1"
|
||||
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
|
||||
throw "Launcher not found: $launcher"
|
||||
}
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
|
||||
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
|
||||
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
|
||||
}
|
||||
}
|
||||
|
||||
function New-TaskDefinition {
|
||||
param(
|
||||
[string]$TaskName,
|
||||
[string]$Root,
|
||||
[string]$ApiBase,
|
||||
[string]$EnvName
|
||||
)
|
||||
$launcher = Join-Path $Root "scripts\freight_rpa\outbound\start_outbound_worker.ps1"
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
|
||||
|
||||
# Key differences vs the visible scheduled task:
|
||||
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
|
||||
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
|
||||
$action = New-ScheduledTaskAction `
|
||||
-Execute "powershell.exe" `
|
||||
-Argument $actionArgs `
|
||||
-WorkingDirectory $Root
|
||||
|
||||
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
|
||||
$principal = New-ScheduledTaskPrincipal `
|
||||
-UserId $RunAsUser `
|
||||
-LogonType Interactive `
|
||||
-RunLevel Limited
|
||||
$settings = New-ScheduledTaskSettingsSet `
|
||||
-StartWhenAvailable `
|
||||
-RestartCount 10 `
|
||||
-RestartInterval (New-TimeSpan -Minutes 1) `
|
||||
-ExecutionTimeLimit ([TimeSpan]::Zero) `
|
||||
-MultipleInstances IgnoreNew
|
||||
|
||||
Register-ScheduledTask `
|
||||
-TaskName $TaskName `
|
||||
-Action $action `
|
||||
-Trigger $trigger `
|
||||
-Principal $principal `
|
||||
-Settings $settings `
|
||||
-Description "HXOPS Freight Outbound RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
}
|
||||
|
||||
# Default action is Register when no switch is given.
|
||||
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
|
||||
# handled below
|
||||
} else {
|
||||
$Register = $true
|
||||
}
|
||||
|
||||
if ($Unregister) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
|
||||
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
|
||||
Write-Host "Unregistered task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Start) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Start-ScheduledTask -TaskName $t
|
||||
Write-Host "Started task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Stop) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Stop-ScheduledTask -TaskName $t
|
||||
Write-Host "Stopped task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Status) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
|
||||
if ($tobj) {
|
||||
$info = Get-ScheduledTaskInfo -TaskName $t
|
||||
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
|
||||
Write-Host " (267009 / 0x41301 = running, not an error)"
|
||||
} else {
|
||||
Write-Host "Task not registered yet: $t"
|
||||
}
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Register) {
|
||||
if ($Scope -eq "test" -or $Scope -eq "all") {
|
||||
Assert-Launcher $TestRoot "test"
|
||||
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
|
||||
}
|
||||
if ($Scope -eq "prod" -or $Scope -eq "all") {
|
||||
Assert-Launcher $ProdRoot "prod"
|
||||
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
|
||||
}
|
||||
Write-Host "Registered background task(s) for scope=${Scope}:"
|
||||
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
|
||||
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
|
||||
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
|
||||
exit 0
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
在当前 PowerShell 进程树启动独立货代出站 RPA Worker。
|
||||
|
||||
.DESCRIPTION
|
||||
只设置 Process 级环境变量和 outbound 专用目录;可与 onhand/inbound Worker 并行运行,
|
||||
三者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
|
||||
根(各自按 connector+profile 隔离会话目录)。
|
||||
默认开启会话复用(SESSION_REUSE,对齐库存);需要每次全新登录时传 -NoSessionReuse。
|
||||
与库存同口径注入 FREIGHT_RPA_SHARED_SCOPE_ID:心跳线程据此把共享哨兵
|
||||
.hxops_rpa_shared_mount 写进出站 trigger 目录,后端写 trigger 前按
|
||||
心跳+哨兵+scope 做在线 fail-fast 检查(漏配时出站排程报 shared_sentinel_missing)。
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
|
||||
[Parameter(Mandatory = $true)][string]$ApiBase,
|
||||
[Parameter(Mandatory = $true)][string]$WorkerRoot,
|
||||
[Parameter(Mandatory = $true)][string]$SecretFile,
|
||||
[string]$PythonExe = 'python.exe',
|
||||
[switch]$Mock,
|
||||
[switch]$Headless,
|
||||
# 默认开启出站会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
|
||||
[switch]$NoSessionReuse,
|
||||
# 兼容旧文档:等价于开启复用(现在默认已开启);与库存开关同名,语义完全一致。
|
||||
[switch]$ReuseSession
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。" }
|
||||
$workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\outbound\outbound_rpa_worker.py'
|
||||
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
|
||||
|
||||
function ConvertTo-PlainText {
|
||||
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
|
||||
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
|
||||
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
|
||||
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
|
||||
}
|
||||
|
||||
$secret = Import-Clixml -LiteralPath $SecretFile
|
||||
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
|
||||
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
|
||||
}
|
||||
# freight_rpa 分域布局根:$WorkerRoot\data\freight_rpa\{onhand,inbound,outbound,common}
|
||||
$rpaRoot = Join-Path $WorkerRoot 'data\freight_rpa'
|
||||
# 共享 scope 标识(与库存同口径):Windows 本地路径不含共享名,无法推导,必须显式注入;
|
||||
# 心跳线程据此把哨兵写进出站 trigger 目录,后端就绪检查按 scope 比对。
|
||||
if ($Environment -eq 'test') {
|
||||
$scopeId = 'hxops-rpa-test-data'
|
||||
} else {
|
||||
$scopeId = 'hxops-rpa-prod-data'
|
||||
}
|
||||
# 局部变量名刻意避开参数名:PS 变量名大小写不敏感,$sessionReuse 曾与旧开关
|
||||
# $SessionReuse 互为同一变量,字符串 'true'/'false' 覆盖开关值,在部分 Windows build
|
||||
# 上于启动阶段以 SwitchParameter 转换异常爆出(2026-09-30 修复)。开关现统一为
|
||||
# $ReuseSession(与库存同名),局部变量统一为 $sessionReuse(与 onhand Worker 同名,便于契约测试断言)。
|
||||
$sessionReuse = if ($NoSessionReuse) { 'false' } else { 'true' }
|
||||
if ($ReuseSession -and $NoSessionReuse) {
|
||||
Write-Warning '同时指定 -ReuseSession 与 -NoSessionReuse 时以 -NoSessionReuse 为准'
|
||||
}
|
||||
$processVars = [ordered]@{
|
||||
HXOPS_API_BASE = $ApiBase
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
|
||||
FREIGHT_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
|
||||
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
|
||||
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
|
||||
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
|
||||
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
|
||||
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
|
||||
FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
|
||||
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'outbound\logs\worker.log'
|
||||
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = '10485760'
|
||||
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = '5'
|
||||
# 独立 Worker 身份:监控端按 worker_id 出独立出站卡片,固定后缀避免与库存/入站 Worker/按 pid 的身份抖动。
|
||||
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-outbound"
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
|
||||
# 共享 scope 标识(与库存同口径):缺省时出站 Worker 不写哨兵、心跳 scope 为空,
|
||||
# test/prod 后端出站就绪检查会报 shared_sentinel_missing / shared_scope_mismatch。
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = Join-Path $rpaRoot 'outbound\triggers'
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = Join-Path $rpaRoot 'outbound\drop'
|
||||
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile;会话按 connector+profile 分目录。
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
|
||||
# 本机磁盘保留:与 onhand Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/outbound_* Profile)。
|
||||
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
|
||||
FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = '3600'
|
||||
FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = '24'
|
||||
}
|
||||
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
|
||||
try {
|
||||
Write-Host "Starting outbound RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot sessionReuse=$sessionReuse"
|
||||
& $PythonExe $workerScript
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
finally {
|
||||
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, $null, 'Process') }
|
||||
}
|
||||
@@ -42,7 +42,7 @@ def main() -> int:
|
||||
print(json.dumps({'dry_run': True, 'items': decisions}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
# 正式 API 调用由部署环境注入;脚本不持有凭据,也不旁路写库。
|
||||
print(json.dumps({'apply_requested': True, 'items': decisions, 'next_action': 'POST /api/shipping-notice/rpa/inventory-repair'}, ensure_ascii=False, indent=2))
|
||||
print(json.dumps({'apply_requested': True, 'items': decisions, 'next_action': 'POST /api/freight-rpa/onhand-repair'}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ function Stop-StaleHxopsPythonProcesses {
|
||||
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
|
||||
[regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")),
|
||||
[regex]::Escape((Join-Path $BackendPath "workers\worker_in_transit_transfer.py")),
|
||||
[regex]::Escape((Join-Path $RepoRoot "scripts\freight_rpa\inventory\inventory_rpa_worker.py"))
|
||||
[regex]::Escape((Join-Path $RepoRoot "scripts\freight_rpa\onhand\onhand_rpa_worker.py"))
|
||||
)
|
||||
# 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。
|
||||
# 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。
|
||||
@@ -480,7 +480,7 @@ function Start-FreightRpaWorkerWindow {
|
||||
-Title "freight-rpa-worker" `
|
||||
-WorkingDirectory $RepoRoot `
|
||||
-EnvPrefix $envPrefix `
|
||||
-Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\freight_rpa\inventory\inventory_rpa_worker.py"
|
||||
-Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\freight_rpa\onhand\onhand_rpa_worker.py"
|
||||
}
|
||||
|
||||
function Start-FrontendWindow {
|
||||
|
||||
Reference in new issue
Block a user