feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
+243
-246
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
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 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"
|
||||
# 货代上传结果(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 Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
|
||||
onhand 声明 onhand_export,inbound(原收料)声明 inbound_export;onhand 侧可写共享目录哨兵。
|
||||
"""
|
||||
|
||||
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,14 +138,14 @@ def build_heartbeat_payload(
|
||||
"""
|
||||
组装心跳 payload。
|
||||
|
||||
核心逻辑:库存 Worker 声明 inventory_export;收料 Worker(worker_id 以 -receipt
|
||||
结尾,或 trigger_dir 路径含 /receipt/)声明 receipt_export;开启上传时附加 freight_upload。
|
||||
核心逻辑:onhand Worker 声明 onhand_export;inbound Worker(worker_id 以 -inbound
|
||||
结尾,或 trigger_dir 路径含 /inbound/)声明 inbound_export;开启上传时附加 freight_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"]
|
||||
is_inbound = str(worker_id).lower().endswith("-inbound") or "/inbound/" in f"/{trigger_norm}/"
|
||||
capabilities = ["inbound_export" if is_inbound else "onhand_export"]
|
||||
upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
|
||||
"1", "true", "yes", "on",
|
||||
}
|
||||
@@ -179,7 +181,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 +227,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 +293,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)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_*,
|
||||
# 一次性运行 Profile 前缀:onhand Worker 用 run_*,inbound Worker 用 inbound_*,
|
||||
# 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_")
|
||||
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "inbound_")
|
||||
_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_*)最大存活秒数。
|
||||
|
||||
核心逻辑:`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_*` 目录。
|
||||
|
||||
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
|
||||
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
|
||||
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
|
||||
仅删除 `run_*` / `inbound_*` 临时目录,避免异常中断后残留撑盘。
|
||||
inbound Worker 一次性 Profile 以 inbound_ 前缀创建,同属清理对象。
|
||||
"""
|
||||
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_*` 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)
|
||||
|
||||
@@ -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)
|
||||
@@ -1167,7 +1167,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)
|
||||
|
||||
@@ -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",
|
||||
@@ -117,26 +117,26 @@ _DSV_RECEIPT_BODY_MARKERS: tuple[str, ...] = (
|
||||
|
||||
def _dsv_export_kind(source: dict[str, Any] | None = None, *, kind: str | None = None) -> str:
|
||||
"""
|
||||
解析导出语义:inventory | receipt。
|
||||
解析导出语义:inventory(onhand)| inbound(原 receipt)。
|
||||
|
||||
核心逻辑:显式 kind / source.__export_kind__ 优先;否则按报表名含 receipt detail 推断。
|
||||
"""
|
||||
explicit = str(kind or "").strip().lower()
|
||||
if explicit in {"inventory", "receipt"}:
|
||||
if explicit in {"inventory", "inbound"}:
|
||||
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"}:
|
||||
return flagged
|
||||
report = _dsv_report_name(source).casefold()
|
||||
if "receipt detail" in report:
|
||||
return "receipt"
|
||||
return "inbound"
|
||||
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
|
||||
return _DSV_INBOUND_BODY_MARKERS if kind == "inbound" else _DSV_INVENTORY_BODY_MARKERS
|
||||
|
||||
|
||||
def _click_dsv_export_excel(page: Any, *, kind: str = "inventory") -> None:
|
||||
@@ -746,7 +746,7 @@ 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":
|
||||
if export_kind == "inbound":
|
||||
# 收料:Export 工具栏或 Receipt Detail 正文均可作为就绪信号。
|
||||
ready = (not state["asyncWait"]) and (state["bodyReady"] or state["exportReady"])
|
||||
if ready:
|
||||
@@ -1003,7 +1003,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 +1102,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 +1728,8 @@ 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)
|
||||
else:
|
||||
_ensure_dsv_inventory_rows_or_export_fallback(page, report_name=report_name)
|
||||
except Exception as exc:
|
||||
@@ -1900,9 +1900,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
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
+11
-11
@@ -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,7 +12,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class NoReceiptDataError(RuntimeError):
|
||||
class NoInboundDataError(RuntimeError):
|
||||
"""收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。"""
|
||||
|
||||
|
||||
@@ -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_receipt_data)。
|
||||
|
||||
Raises:
|
||||
NoReceiptDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。
|
||||
NoInboundDataError: 可识别表头但无业务行;message 固定为 no_receipt_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_receipt_data')
|
||||
+102
-103
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
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 分组串行导出 →
|
||||
inbound_excel_empty、inbound_dbs_export、inbound_crane_export、connectors/dsv/dsv_report_export。
|
||||
逻辑:排程写入 inbound trigger → 本进程领取并按 connector/profile 分组串行导出 →
|
||||
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_receipt_data;
|
||||
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
|
||||
"""
|
||||
@@ -31,11 +31,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 +43,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 +93,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 +105,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 +151,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 +212,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 +227,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 +243,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 +284,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 +327,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 +341,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 +351,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 +363,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 +380,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 +401,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 +434,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,25 +445,25 @@ 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.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
|
||||
|
||||
def _report_empty(unit: dict[str, Any], exc: NoReceiptDataError) -> None:
|
||||
def _report_empty(unit: dict[str, Any], exc: NoInboundDataError) -> 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]}')
|
||||
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',
|
||||
@@ -505,12 +504,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 +527,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 +537,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 +545,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 +556,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 +569,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 +583,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,22 +604,22 @@ 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 偶发同源双文件根因)。
|
||||
"""
|
||||
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)
|
||||
@@ -642,12 +641,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 +665,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,7 +691,7 @@ 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,
|
||||
)
|
||||
progress_counts['empty'] += 1
|
||||
@@ -703,7 +702,7 @@ 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,
|
||||
)
|
||||
progress_counts['failed'] += 1
|
||||
@@ -712,7 +711,7 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
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,7 +722,7 @@ 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,
|
||||
)
|
||||
@@ -739,7 +738,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 +746,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 +767,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 +778,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 +806,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 +834,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)
|
||||
|
||||
+16
-16
@@ -7,12 +7,12 @@
|
||||
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
|
||||
}
|
||||
+130
-163
@@ -5,19 +5,19 @@ Freight RPA worker (PoC).
|
||||
DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。
|
||||
|
||||
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 +61,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 +89,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 +223,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 +272,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 +321,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 +350,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 +364,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 +387,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 +396,7 @@ _INVENTORY_EXCEL_HEADER_MARKERS = (
|
||||
)
|
||||
|
||||
|
||||
def _validate_inventory_excel(path: Path) -> None:
|
||||
def _validate_onhand_excel(path: Path) -> None:
|
||||
"""
|
||||
校验 RPA 下载的库存 Excel 可被打开且具备报表基本结构。
|
||||
核心逻辑:拒绝过小/HTML 错误页伪装文件;检查前几行是否含库存报表表头特征。
|
||||
@@ -441,7 +408,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 +432,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 +492,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 +543,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 +580,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 +590,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 +619,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 +678,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 +817,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 +1074,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 +1097,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 +1113,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 +1135,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 +1152,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 +1170,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 +1201,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 +1214,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 +1252,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 +1272,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 +1304,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 +1324,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 +1337,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 +1390,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 +1414,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 +1436,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 +1451,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 +1478,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 +1494,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 +1524,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 +1546,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 +1561,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,7 +1569,7 @@ 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")})
|
||||
@@ -1634,16 +1601,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 +1620,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 +1639,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 +1654,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 +1687,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 +1701,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 +1711,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 +1725,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 +2405,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 +2453,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 +2466,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 +2501,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 +2515,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 +2532,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 +2553,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 +2574,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 +2589,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 +2597,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 +2612,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 不删。
|
||||
@@ -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