feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务

- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
hugo committed 2026-10-19 18:45:16 +08:00
1 parent 39fe3c05f2
commit 911afa0f73
152 files changed
+9861 -2984

No files matched your search

@@ -0,0 +1,78 @@
"""
scripts/freight_rpa/outbound/outbound_crane_export.py
用途:Crane 出站报表导出适配器——固定 Outbound Details,委托共享 crane_report_export。
依赖:crane_report_export、crane_session。
逻辑:outbound_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
driver 在 Playwright 未返回 Download 时做目录兜底。
页面名/hash 与 Task 6 占位一致:report_name=Outbound Details、
hash=#/outbound-details-query(入站对称占位;禁止误用 Inbound Details)。
来源:Task 6 Crane 校验器 + 设计 D7 固定页;货代实名页尚未用截图/环境确认,
若门户 hash 不同,只改本文件常量并同步管理端校验。
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_RPA_ROOT = next(
(_c for _c in _Path(__file__).resolve().parents
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
and (_c / "onhand").is_dir() and (_c / "outbound").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound", "outbound"):
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
if _dir not in _sys.path:
_sys.path.insert(0, _dir)
from typing import Any, Callable
from urllib.parse import urlsplit, urlunsplit
import crane_report_export
import crane_session
# Task 6 / D7 占位:与管理端 Crane outbound 固定页同名。禁止改成 Inbound Details。
_OUTBOUND_REPORT_NAME = 'Outbound Details'
_OUTBOUND_DETAILS_HASH = '/outbound-details-query'
def _outbound_details_entry_url(login_url: str) -> str:
"""将复用的 Crane Profile 登录地址固定到出站 Outbound Details 路由。"""
parsed = urlsplit(str(login_url or '').strip())
if not parsed.scheme or not parsed.netloc:
raise RuntimeError('Crane outbound unit requires an absolute login_url')
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, _OUTBOUND_DETAILS_HASH))
def export_outbound_report(
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
) -> Any:
"""
创建并下载唯一 Description 对应的 Crane Outbound Details 文件。
核心逻辑:固定 scheduled_report_name=Outbound Details;把 unit.__download_dir
写入 source,供共享 crane_report_export 目录兜底(对齐库存/入站)。
"""
report_path = dict(unit.get('report_path_json') or {})
if str(report_path.get('report_name') or '').strip() != _OUTBOUND_REPORT_NAME:
raise RuntimeError('Crane outbound report must be Outbound Details')
entry_url = _outbound_details_entry_url(str(unit.get('login_url') or '').strip())
if first_in_profile:
page.goto(entry_url, wait_until='domcontentloaded', timeout=browser_timeout_ms)
crane_session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms)
crane_session.wait_for_crane_app_ready(page, entry_url, env=env, browser_timeout_ms=browser_timeout_ms)
# Scheduled Reports 匹配名来自 source;出站固定为 Outbound Details,
# 不能沿用库存 OnHandDetails.xlsx 或入站 Inbound Details。
source = {
'entry_url': entry_url,
'scheduled_report_name': 'Outbound Details',
'__download_dir': str(unit.get('__download_dir') or ''),
}
return crane_report_export.export_crane_inventory_report(
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
browser_timeout_ms=browser_timeout_ms, select_or_fill=select_or_fill, click_text=click_text,
)
@@ -0,0 +1,98 @@
"""
scripts/freight_rpa/outbound/outbound_dbs_export.py
用途:DBS 出站报表导出适配器——把 unit 转成与库存同构的 DSV source,再委托共享导出驱动。
依赖:connectors/dsv/dsv_report_export。
逻辑:outbound_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
调用 prepare_dsv_batch_export_step 完成;本模块只负责 source 组装与单次导出。
source 写入 __export_kind__=outbound,共享驱动用出站就绪探针,不用库存/收料字段。
导航取配置 report_path_json(禁止写死入站/库存报表名);query_parameters 原样下发;
仅当 unit.warehouse_id 有值时追加单值 Warehouse(兼容旧 trigger)。
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_RPA_ROOT = next(
(_c for _c in _Path(__file__).resolve().parents
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
and (_c / "onhand").is_dir() and (_c / "outbound").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound", "outbound"):
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
if _dir not in _sys.path:
_sys.path.insert(0, _dir)
from typing import Any
import dsv_report_export
def build_outbound_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
"""
将出站 unit 组装为共享 dsv_report_export 可消费的 source。
核心逻辑:report_path_json → navigation(驱动只读 navigation/query);
parameters 取自 query_parameters_json;有 warehouse_id 时追加单值 Warehouse。
Args:
unit: 出站 trigger 单元(含 report_path_json / query_parameters_json 等)。
entry_url: 该 Profile 分组的登录入口 URL。
Returns:
与库存 trigger source 同构的 dict,可供 prepare_dsv_batch_export_step 与导出使用。
"""
report_path = dict(unit.get('report_path_json') or {})
source: dict[str, Any] = {
'entry_url': entry_url,
'report_path_json': report_path,
# 与库存 trigger 同构:Source.report_path_json → navigation,供菜单导航使用。
'navigation': report_path,
'parameters': list(unit.get('query_parameters_json') or []),
'__download_dir': str(unit.get('__download_dir') or ''),
# 显式标记出站导出:共享 dsv_report_export 用 outbound 就绪探针,不用库存/收料字段。
'__export_kind__': 'outbound',
}
warehouse_id = str(unit.get('warehouse_id') or '').strip()
if warehouse_id:
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
return source
def export_outbound_report(
page: Any,
unit: dict[str, Any],
*,
entry_url: str,
skip_navigation: bool = False,
) -> Any:
"""
在既有 DBS 登录态内执行出站路径与受控非日期条件。
核心逻辑:组装 source 后委托 export_dsv_inventory_source;会话登录与参数页复用
由 Worker 侧 prepare_dsv_batch_export_step 完成。skip_navigation=True 时跳过菜单导航,
直接在已就绪的参数页填参导出(同导航批内复用)。
Args:
page: 当前 Playwright Page(批内复用同一 tab,禁止每源 new_page)。
unit: 出站 trigger 单元。
entry_url: 登录入口 URL。
skip_navigation: 为 True 时跳过报表菜单导航(参数页已由 prepare 就绪)。
Returns:
Playwright Download 对象。
"""
source = build_outbound_dsv_source(unit, entry_url=entry_url)
return dsv_report_export.export_dsv_inventory_source(
page,
{'action': 'outbound_export_batch'},
source,
skip_navigation=skip_navigation,
)
@@ -0,0 +1,110 @@
"""
scripts/freight_rpa/outbound/outbound_excel_empty.py
用途:出站 Excel「有表头无明细」判空(真相源,对齐入站 Excel 判空)。
依赖:openpyxl(运行期可选;缺失时不强制 empty)。
逻辑:outbound_rpa_worker 落盘校验后调用;标题行(如 Outbound Details)
不得当成表头,否则真表头会被误判为明细导致假 success。
"""
from __future__ import annotations
from pathlib import Path
class NoOutboundDataError(RuntimeError):
"""出站报表可打开且有表头,但无业务明细行(合法 empty / no_outbound_data)。"""
def _normalize_row_joined(row: tuple | list) -> str:
"""
将一行单元格规范为小写比较串。
核心逻辑:换行压成空格,去空白后用 | 拼接。
"""
parts: list[str] = []
for cell in row:
if cell is None:
continue
text = ' '.join(str(cell).replace('\n', ' ').replace('\r', ' ').split()).strip()
if text:
parts.append(text.lower())
return ' | '.join(parts)
def is_outbound_excel_header_row(joined: str) -> bool:
"""
判断是否为出站列标题行(非报表标题行)。
核心逻辑:要求 sku/quantity 与 outbound/shipment/dispatch 等组合特征;
单独含 outbound(如「Outbound Details」标题)不得命中。
"""
if not joined:
return False
has_sku = 'sku' in joined or 'part number' in joined or 'item' in joined
has_qty = 'quantity' in joined or 'qty' in joined
has_move = (
'outbound' in joined
or 'shipment' in joined
or 'dispatch' in joined
or 'shipped' in joined
or 'ship to' in joined
)
if has_sku and has_qty and has_move:
return True
if 'warehouse' in joined and has_move and (has_sku or has_qty):
return True
if 'supplier id' in joined and 'aws sku' in joined and has_move:
return True
return False
def outbound_excel_has_detail_rows(path: Path) -> bool | None:
"""
判断出站 Excel 列标题之后是否有明细行。
核心逻辑:先定位严格表头行,再扫描其后非空行;无法识别表头时返回 None
(不强制 empty,由结构校验兜底)。
Returns:
True: 有明细;False: 有表头无明细;None: 未识别表头形态。
"""
try:
from openpyxl import load_workbook
except ImportError:
return None
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception:
return None
try:
worksheet = workbook.active
if worksheet is None:
return None
header_idx: int | None = None
for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1):
joined = _normalize_row_joined(row or ())
if not joined:
continue
if header_idx is None:
if is_outbound_excel_header_row(joined):
header_idx = idx
continue
if idx > header_idx:
return True
if header_idx is None:
return None
return False
finally:
workbook.close()
def enforce_outbound_excel_not_empty(path: Path) -> None:
"""
有表头无明细时记为无出站(NoOutboundDataError → empty / no_outbound_data)。
Raises:
NoOutboundDataError: 可识别表头但无业务行;message 固定为 no_outbound_data。
"""
if outbound_excel_has_detail_rows(path) is False:
raise NoOutboundDataError('no_outbound_data')
@@ -0,0 +1,831 @@
"""
scripts/freight_rpa/outbound/outbound_rpa_worker.py
用途:独立货代出站 RPA Worker——仅消费 outbound trigger,不触及库存/入站 Worker 的目录或 callback。
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
outbound_excel_empty、outbound_dbs_export、outbound_crane_export、connectors/dsv/dsv_report_export。
逻辑:排程写入 outbound trigger → 本进程领取并按 connector/profile 分组串行导出 →
导出重试只覆盖落盘/校验(对齐库存/入站);有表头无明细 → empty/no_outbound_data;
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import tempfile
import time
import urllib.request
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any
from cryptography.fernet import Fernet, InvalidToken
import sys as _sys
from pathlib import Path as _Path
_RPA_ROOT = next(
(_c for _c in _Path(__file__).resolve().parents
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
and (_c / "onhand").is_dir() and (_c / "outbound").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "onhand", "inbound", "outbound"):
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
if _dir not in _sys.path:
_sys.path.insert(0, _dir)
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file # noqa: E402
import rpa_callbacks # noqa: E402
from rpa_callbacks import ( # noqa: E402
OUTBOUND_BATCH_PROGRESS,
OUTBOUND_BATCH_READY,
OUTBOUND_UNIT_PROGRESS,
)
import rpa_heartbeat # noqa: E402
import worker_logging # noqa: E402
import worker_disk_cleanup # noqa: E402
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
import dsv_report_export # noqa: E402
import outbound_crane_export # noqa: E402
import outbound_dbs_export # noqa: E402
from outbound_excel_empty import ( # noqa: E402
NoOutboundDataError,
enforce_outbound_excel_not_empty as _enforce_outbound_excel_not_empty,
)
_EXPORT_UNIT_MAX_ATTEMPTS = 2
_EXPORT_UNIT_RETRY_WAIT_SECONDS = 30
_OUTBOUND_EXCEL_MIN_BYTES = 512
# 结构校验可用较宽标记;「有表头无明细」判空见 outbound_excel_empty。
_OUTBOUND_EXCEL_HEADER_MARKERS = (
'outbound',
'shipment',
'dispatch',
'shipped',
'ship qty',
'po number',
'po #',
'sku',
'quantity',
'warehouse',
)
def _backend_dir() -> Path:
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
return _RPA_ROOT.parents[1] / 'backend'
def _mask_secret(value: str | None) -> str:
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
value = str(value or '').strip()
if len(value) <= 8:
return '***' if value else 'missing'
return f'{value[:4]}....{value[-4:]}'
def _require_dir(variable: str) -> Path:
"""读取 outbound 专用目录;不回退至 onhand/inbound 共享路径。"""
value = env(variable)
if not value:
raise SystemExit(f'Missing env: {variable}')
path = Path(value)
if not path.is_absolute():
path = (_backend_dir() / value).resolve()
path.mkdir(parents=True, exist_ok=True)
return path
def _post_rpa(path: str, payload: dict[str, Any], *, timeout: int = 30) -> None:
"""向 HXOPS 出站 RPA 回调 API 上报(薄封装,统一走 /api/freight-rpa/*)。
核心逻辑:鉴权、脱敏日志与 HTTP 错误处理收拢到 common/rpa_callbacks.post_callback;
保留 (path, payload, timeout) 签名,便于测试 monkeypatch 与既有调用点零改动。
"""
rpa_callbacks.post_callback(path, payload, timeout=timeout)
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立出站 callback 上报一个单元终态结果。"""
_post_rpa(OUTBOUND_BATCH_READY, payload)
def _mark_unit_processing(unit: dict[str, Any]) -> None:
"""开始导出前标记 processing;失败不影响导出主链路。"""
try:
_post_rpa(
OUTBOUND_UNIT_PROGRESS,
{
'schema_version': 'freight_rpa.outbound.v1',
'callback_id': unit.get('callback_id'),
'status': 'processing',
},
)
except Exception as exc:
print(f'[outbound-unit] processing progress failed: {exc}', file=_sys.stderr)
def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
"""每完成一笔导出回传累计进度(对齐 inbound-batch-progress)。"""
schedule_run_id = body.get('schedule_run_id')
if schedule_run_id is None:
return
try:
_post_rpa(
OUTBOUND_BATCH_PROGRESS,
{
'schema_version': 'freight_rpa.outbound.v1',
'schedule_run_id': schedule_run_id,
'batch_run_no': body.get('batch_run_no') or body.get('run_no'),
'success_count': int(counts.get('success') or 0),
'skipped_count': int(counts.get('empty') or 0),
'failed_count': int(counts.get('failed') or 0),
},
)
except Exception as exc:
print(f'[outbound-batch] progress callback failed: {exc}', file=_sys.stderr)
@contextmanager
def _profile_credentials(unit: dict[str, Any]):
"""在单个 Profile 分组内临时解密凭据并清理环境,绝不输出明文。"""
envelope = unit.get('credential_envelope') or {}
username_ciphertext = str(envelope.get('username_ciphertext') or '').strip()
password_ciphertext = str(envelope.get('password_ciphertext') or '').strip()
if not username_ciphertext and not password_ciphertext:
yield
return
if not username_ciphertext or not password_ciphertext:
raise RuntimeError('RPA Profile credentials are incomplete')
key = env('FREIGHT_RPA_CREDENTIAL_KEY')
if not key:
raise RuntimeError('FREIGHT_RPA_CREDENTIAL_KEY is required')
try:
fernet = Fernet(key.encode('ascii'))
username = fernet.decrypt(username_ciphertext.encode('ascii')).decode('utf-8')
password = fernet.decrypt(password_ciphertext.encode('ascii')).decode('utf-8')
except (ValueError, InvalidToken, UnicodeDecodeError) as exc:
raise RuntimeError('RPA Profile credentials cannot be decrypted') from exc
connector = str(unit.get('connector_type') or '').lower()
names = ('FREIGHT_RPA_WORKER_DSV_USERNAME', 'FREIGHT_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('FREIGHT_RPA_WORKER_CRANE_USERNAME', 'FREIGHT_RPA_WORKER_CRANE_PASSWORD')
before = {name: os.environ.get(name) for name in names}
os.environ[names[0]], os.environ[names[1]] = username, password
try:
yield
finally:
for name, old_value in before.items():
if old_value is None:
os.environ.pop(name, None)
else:
os.environ[name] = old_value
def _session_reuse_enabled() -> bool:
"""
出站是否复用持久浏览器 Profile。
核心逻辑:对齐库存/入站——未设置或空值时默认开启;仅显式 false 时关闭。
"""
raw = env('FREIGHT_RPA_WORKER_SESSION_REUSE')
if raw is None or str(raw).strip() == '':
return True
return str(raw).strip().strip("\"'").lower() == 'true'
def _sanitize_profile_dir_segment(value: str) -> str:
"""将 connector / profile_code 收成可作目录名的安全片段。"""
text = str(value or '').strip()
cleaned = ''.join(ch if (ch.isalnum() or ch in '-_') else '_' for ch in text)
return (cleaned[:96] or 'default')
def _session_profile_dir(connector_type: str, profile_code: str = '') -> Path:
"""
按 connector + RPA Profile 隔离的持久出站会话目录。
核心逻辑:形如 `{connector}__{profile_code}_session`(dbs/crane 与库存 dsv360/crane_footprint
命名空间分离,避免串 Cookie);禁止所有出站源共用单一 outbound_session。
"""
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
connector = _sanitize_profile_dir_segment(connector_type or 'unknown')
code = _sanitize_profile_dir_segment(profile_code)
return profile_root / f'{connector}__{code}_session'
def _open_browser(
download_dir: Path,
*,
reuse_session: bool = False,
connector_type: str = '',
profile_code: str = '',
):
"""为一个 outbound Profile 分组创建浏览器上下文,组内登录一次、串行导出。
reuse_session=True 且 SESSION_REUSE 开启:持久 `{connector}__{profile}_session`;
否则一次性临时 Profile(outbound_* 前缀),批次结束即删。
"""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError('Playwright is required for real outbound RPA') from exc
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
use_reused = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
if use_reused:
runtime_profile = _session_profile_dir(connector_type, profile_code)
runtime_profile.mkdir(parents=True, exist_ok=True)
profile_mode = 'session_reuse'
else:
runtime_profile = Path(tempfile.mkdtemp(prefix='outbound_', dir=str(profile_root)))
profile_mode = 'temporary'
print(
f'[browser] profile_mode={profile_mode} connector={connector_type or "-"} '
f'profile={profile_code or "-"} dir={runtime_profile.name!r}'
)
playwright = sync_playwright().start()
options: dict[str, Any] = {
'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true',
'accept_downloads': True,
'downloads_path': str(download_dir),
}
channel = env('FREIGHT_RPA_WORKER_BROWSER_CHANNEL')
if channel:
options['channel'] = channel
context = playwright.chromium.launch_persistent_context(str(runtime_profile), **options)
page = context.pages[0] if context.pages else context.new_page()
page.set_default_timeout(browser_timeout_ms())
return playwright, context, page, runtime_profile
def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
"""
在同一登录上下文中切换到干净页面,隔离上一站的 DSV 报表状态。
核心逻辑:对齐库存 Worker——新开空白页并关闭旧页;Cookie 仍在 context 内,
仅用于会话准备失败后的一次完整登录重试,禁止作为常态「每源新开空白页」。
Args:
context: 已建立登录态的 Playwright browser context。
current_page: 上一站页面;关闭以避免报表 iframe / 下载菜单残留。
Returns:
可重新进入出站报表的空白页面。
"""
next_page = context.new_page()
next_page.set_default_timeout(browser_timeout_ms())
if current_page is not None:
try:
current_page.close()
except Exception as exc:
print(f'[outbound-batch] close previous page failed: {exc}', file=_sys.stderr)
return next_page
def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
"""
导出前拍摄下载目录已有文件名,供目录兜底识别「本次新文件」。
核心逻辑:仅收集普通文件名;目录不可读时返回空集合(对齐库存)。
"""
try:
return {path.name for path in drop_dir.iterdir() if path.is_file()}
except OSError:
return set()
def _is_playwright_target_closed_error(exc: BaseException) -> bool:
"""判断是否为 Playwright 页面/上下文已关闭导致的落盘失败。"""
message = str(exc).lower()
return 'has been closed' in message or 'target closed' in message or 'targetclosed' in message
def _persist_download_to_dest(
download: Any,
dest: Path,
*,
drop_dir: Path,
baseline_names: set[str] | None = None,
fallback_timeout_seconds: float = 60.0,
) -> None:
"""
将 Playwright Download 落到规范路径;浏览器已关闭时走 downloads_path 目录兜底。
核心逻辑:对齐库存 `_persist_download_to_dest`——先 save_as,TargetClosed
再按 baseline 等待稳定新文件后搬迁。
"""
try:
download.save_as(str(dest))
return
except Exception as exc:
if not _is_playwright_target_closed_error(exc):
raise
print(
f'[outbound-artifact] stage=download_save status=fallback '
f'reason=browser_closed path={dest.name!r}',
file=_sys.stderr,
)
artifact = _wait_for_new_download_file(
download_dir=drop_dir,
baseline_names=set(baseline_names or ()),
timeout_seconds=fallback_timeout_seconds,
)
if artifact is None:
raise
artifact.save_as(str(dest))
def _outbound_download_name(
batch_run_no: str,
source_code: str,
warehouse_id: str | None,
*,
suffix: str = '.xlsx',
) -> str:
"""
出站落盘文件名,对齐库存 `_batch_download_name`。
核心逻辑:`outbound_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
不写入 callback_id(关联仍靠 callback JSON)。
Args:
batch_run_no: trigger 顶层批次号。
source_code: 库存源编码(辨识用)。
warehouse_id: 可选仓码;空则 NA。
suffix: 扩展名,默认 .xlsx。
Returns:
安全化后的文件名(不含目录)。
"""
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'outbound'
safe_source = ''.join(ch for ch in str(source_code or '') if ch.isalnum() or ch in {'-', '_'}) or 'UNKNOWN'
safe_wh = ''.join(ch for ch in str(warehouse_id or '') if ch.isalnum() or ch in {'-', '_'}) or 'NA'
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')
return f'outbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
def _save_download(
download: Any,
drop_dir: Path,
unit: dict[str, Any],
*,
batch_run_no: str,
baseline_names: set[str] | None = None,
fallback_timeout_seconds: float = 60.0,
) -> Path:
"""
保存本单元下载文件到 outbound drop;必要时在浏览器关闭后走目录兜底。
核心逻辑:按 run+source(+仓) 命名后 `_persist_download_to_dest`;空文件拒绝。
"""
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
if suffix != '.xlsx':
raise RuntimeError('outbound report download must be xlsx')
target = drop_dir / _outbound_download_name(
batch_run_no,
str(unit.get('source_code') or ''),
unit.get('warehouse_id'),
suffix=suffix,
)
_persist_download_to_dest(
download,
target,
drop_dir=drop_dir,
baseline_names=baseline_names,
fallback_timeout_seconds=fallback_timeout_seconds,
)
if target.stat().st_size <= 0:
raise RuntimeError('outbound report download is empty')
return target
def _validate_outbound_excel(path: Path) -> None:
"""
校验出站 Excel 可打开且具备报表基本结构。
核心逻辑:对齐 inbound `_validate_inbound_excel`——拒过小/HTML 伪装文件;
前几行或 sheet 标题须含出站报表特征,避免错误页当 success 归档。
"""
size = path.stat().st_size
if size < _OUTBOUND_EXCEL_MIN_BYTES:
raise RuntimeError(f'downloaded outbound Excel is too small ({size} bytes)')
try:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError('openpyxl required to validate outbound Excel') from exc
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception as exc:
raise RuntimeError(f'downloaded file is not valid Excel: {exc}') from exc
try:
worksheet = workbook.active
if worksheet is None:
raise RuntimeError('downloaded file is not valid Excel: missing active sheet')
preview_lines: list[str] = []
for row in worksheet.iter_rows(max_row=6, values_only=True):
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
if cells:
preview_lines.append(' | '.join(cells).lower())
haystack = '\n'.join(preview_lines)
title = str(worksheet.title or '').lower().replace('_', '')
if not any(marker in haystack for marker in _OUTBOUND_EXCEL_HEADER_MARKERS):
if 'outbound' not in title and 'shipment' not in title:
raise RuntimeError('downloaded file is not valid Excel: missing outbound report headers')
finally:
workbook.close()
def _validate_unit(unit: dict[str, Any]) -> None:
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
if not str(unit.get(key) or '').strip():
raise RuntimeError(f'outbound unit missing {key}')
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
raise RuntimeError('unsupported outbound connector_type')
parameters = list(unit.get('query_parameters_json') or [])
if any('date' in str(row.get('name') or '').lower() for row in parameters if isinstance(row, dict)):
raise RuntimeError('outbound date filtering is forbidden')
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
print(f'[outbound-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
_post_callback({'schema_version': 'freight_rpa.outbound.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.OUTBOUND_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
def _report_empty(unit: dict[str, Any], exc: NoOutboundDataError) -> None:
"""无业务明细的合法结果:回调 empty + no_outbound_data(后端 finalize 计 skipped)。"""
print(f'[outbound-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
_post_callback({
'schema_version': 'freight_rpa.outbound.v1',
'callback_id': unit.get('callback_id'),
'status': 'empty',
'error_code': 'no_outbound_data',
'error_message': str(exc)[:2000] or 'no_outbound_data',
})
def _is_login_session_error(exc: BaseException) -> bool:
"""登录/会话类偶发异常可干净页重试;凭据校验类不重试。"""
message = str(exc).lower()
login_related = any(token in message for token in ('login', 'session', 'oauth'))
credential_mismatch = any(token in message for token in ('invalid', 'verification'))
return login_related and not credential_mismatch
def _export_unit_download(
*,
connector: str,
unit: dict[str, Any],
group: list[dict[str, Any]],
index: int,
login_url: str,
page: Any,
context: Any,
drop_dir: Path,
attempt: int = 1,
) -> tuple[Any, Any]:
"""
导出单个出站单元的 Playwright Download;必要时干净页重试会话。
Args:
attempt: 第几次尝试(1 起)。>1 时强制完整重导航(对齐库存 2026-09-20 AWSRTM
兜底:报表页导出菜单缺失属瞬态故障,绝不在错误页上直接重试,须回入口页
重选菜单进报表),且 prepare 的导航/会话类异常一并走干净页安全网
(凭据校验类 invalid/verification 为确定性失败,不重试)。
Returns:
(download, page):download 为 Playwright Download;page 可能已切换为干净页。
"""
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
source = outbound_dbs_export.build_outbound_dsv_source(unit, entry_url=login_url)
force_full_navigation = attempt > 1
previous_unit = group[index - 1] if (index > 0 and not force_full_navigation) else None
previous_source = (
outbound_dbs_export.build_outbound_dsv_source(previous_unit, entry_url=login_url)
if previous_unit is not None else None
)
skip_navigation = False
try:
skip_navigation = bool(
dsv_report_export.prepare_dsv_batch_export_step(
page, login_url, previous_source, source,
index=0 if force_full_navigation else index,
)
)
except Exception as exc:
message = str(exc).lower()
if any(token in message for token in ('invalid', 'verification')):
raise
print(
f'[outbound-batch] dbs prepare failed for {unit.get("source_code")}, '
f'retry with clean page: {exc}',
file=_sys.stderr,
)
page = _open_clean_batch_page(context, page)
skip_navigation = bool(
dsv_report_export.prepare_dsv_batch_export_step(
page, login_url, None, source, index=0,
)
)
download = outbound_dbs_export.export_outbound_report(
page, unit, entry_url=login_url, skip_navigation=skip_navigation,
)
return download, page
first_in_profile = index == 0 or attempt > 1
try:
download = outbound_crane_export.export_outbound_report(
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
select_or_fill=select_or_fill, click_text=click_text,
first_in_profile=first_in_profile,
)
return download, page
except Exception as exc:
if not _is_login_session_error(exc):
raise
print(
f'[outbound-batch] crane session failed for {unit.get("source_code")}, '
f'retry with clean page: {exc}',
file=_sys.stderr,
)
page = _open_clean_batch_page(context, page)
download = outbound_crane_export.export_outbound_report(
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
select_or_fill=select_or_fill, click_text=click_text,
first_in_profile=True,
)
return download, page
def _write_mock_outbound_excel(path: Path) -> None:
"""Mock 模式写出带表头+一行明细的合法出站 Excel,便于走校验与 success 回调。"""
from openpyxl import Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = 'OutboundDetail'
sheet.append(['Warehouse', 'SKU', 'Quantity Shipped', 'Outbound'])
sheet.append(['WH-MOCK-1', 'SKU-1', 1, 'OUT-1'])
workbook.save(path)
workbook.close()
def _post_unit_ready(unit: dict[str, Any], output: Path) -> None:
"""落盘成功后上报 outbound-batch-ready(归档);调用方须放在导出重试之外。
file_path 契约为「drop 根内文件名」:Worker(Windows)与后端(Linux 挂载根)分属
两机、根路径不同。规格 §4.2 跨机路径契约:必须 Path(local_drop_file).name,
禁止把 C:\\...\\drop\\xxx.xlsx 整串作为契约主值(跨机下发本机绝对路径必 400)。
"""
_post_callback({
'schema_version': 'freight_rpa.outbound.v1',
'callback_id': unit['callback_id'],
'status': 'success',
'file_path': output.name,
'original_filename': output.name,
'sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
})
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
"""
按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 出站单元。
核心逻辑:DBS 与库存对齐——同 Profile 组内复用同一 tab;导出失败批次内最多重试 2 次,
**重试只覆盖导出/落盘/校验**(对齐库存 record_result 前段)。落盘成功后先轻量
``outbound-batch-progress``(管理端实时笔数),再调 ``outbound-batch-ready`` 归档;
ready/empty/failed 回调失败不得触发重新下载(2026-09-28 偶发同源双文件根因)。
"""
units = body.get('units')
if body.get('schema_version') != 'freight_rpa.outbound.v1' or body.get('action') != 'outbound_export_batch' or not isinstance(units, list) or not units:
raise RuntimeError('invalid outbound trigger contract')
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'outbound').strip() or 'outbound'
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
for item in units:
if not isinstance(item, dict):
raise RuntimeError('outbound unit must be object')
_validate_unit(item)
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
progress_counts = {'success': 0, 'empty': 0, 'failed': 0}
for (connector, profile_code, login_url), group in grouped.items():
print(f'[outbound-batch] connector={connector} profile={profile_code} units={len(group)}')
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
reuse_session = _session_reuse_enabled()
resources = (None, None, None, None)
try:
if not mock:
resources = _open_browser(
drop_dir,
reuse_session=reuse_session,
connector_type=connector,
profile_code=profile_code,
)
playwright, context, page, profile_dir = resources
with _profile_credentials(group[0]):
for index, unit in enumerate(group):
_mark_unit_processing(unit)
output: Path | None = None
terminal: tuple[str, BaseException] | None = None
# [RETRY] 仅导出/落盘/校验;ready 回调禁止进入本循环。
for attempt in range(1, _EXPORT_UNIT_MAX_ATTEMPTS + 1):
try:
if mock:
mock_path = drop_dir / _outbound_download_name(
batch_run_no,
str(unit.get('source_code') or ''),
unit.get('warehouse_id'),
)
_write_mock_outbound_excel(mock_path)
output = mock_path
else:
baseline_names = _download_dir_baseline_names(drop_dir)
download, page = _export_unit_download(
connector=connector,
unit=unit,
group=group,
index=index,
login_url=login_url,
page=page,
context=context,
drop_dir=drop_dir,
attempt=attempt,
)
output = _save_download(
download, drop_dir, unit, batch_run_no=batch_run_no,
baseline_names=baseline_names,
)
_validate_outbound_excel(output)
_enforce_outbound_excel_not_empty(output)
break
except NoOutboundDataError as exc:
terminal = ('empty', exc)
output = None
break
except Exception as exc:
if attempt < _EXPORT_UNIT_MAX_ATTEMPTS:
print(
f'[outbound-batch] export failed {unit.get("source_code")} '
f'(attempt {attempt}/{_EXPORT_UNIT_MAX_ATTEMPTS}), '
f'retry in {_EXPORT_UNIT_RETRY_WAIT_SECONDS}s: {exc}',
file=_sys.stderr,
)
time.sleep(_EXPORT_UNIT_RETRY_WAIT_SECONDS)
continue
terminal = ('failed', exc)
output = None
# [STEP] 导出循环外:轻量 progress + 终态回调(对齐库存 progress / 批末 ready)
if terminal is not None and terminal[0] == 'empty':
try:
_report_empty(unit, terminal[1]) # type: ignore[arg-type]
except Exception as callback_exc:
print(
f'[outbound-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
file=_sys.stderr,
)
progress_counts['empty'] += 1
_emit_batch_progress(body, progress_counts)
continue
if terminal is not None and terminal[0] == 'failed':
try:
_report_failure(unit, terminal[1]) # type: ignore[arg-type]
except Exception as callback_exc:
print(
f'[outbound-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
file=_sys.stderr,
)
progress_counts['failed'] += 1
_emit_batch_progress(body, progress_counts)
continue
if output is None:
continue
print(
f'[outbound-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
)
progress_counts['success'] += 1
_emit_batch_progress(body, progress_counts)
try:
_post_unit_ready(unit, output)
except Exception as callback_exc:
# 文件已落盘:回调超时只打日志,禁止回到导出重试(同源双文件根因)。
# 不调用 failed 回调,避免晚到的 ready 与 failed 竞态;人工可按 drop 文件补档。
print(
f'[outbound-unit] ready callback failed source={unit.get("source_code")} '
f'file={output.name}: {callback_exc}',
file=_sys.stderr,
)
finally:
playwright, context, _page, profile_dir = resources
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
if profile_dir is not None and not (reuse_session and _session_reuse_enabled()):
shutil.rmtree(profile_dir, ignore_errors=True)
def _claim_and_process(path: Path, drop_dir: Path) -> None:
"""原子领取一个 outbound trigger;成功归档 processed,异常归档 failed。
领取与归档统一走 common/trigger_consumer(四态目录契约),
本函数只保留出站批次处理与 SystemExit 兜底。
"""
claimed = claim_trigger(path)
if claimed is None:
return
print(f'[outbound-trigger] claimed {claimed.name}')
rpa_heartbeat.set_worker_runtime_status('busy')
try:
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
archive_trigger(claimed, 'processed')
print(f'[outbound-trigger] archived processed {claimed.name}')
except (Exception, SystemExit):
archive_trigger(claimed, 'failed')
print(f'[outbound-trigger] archived failed {claimed.name}')
raise
finally:
rpa_heartbeat.set_worker_runtime_status('idle')
def main() -> None:
"""轮询出站专用 trigger 目录;不加载或扫描任何库存/inbound/upload 目录。"""
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
drop_dir = _require_dir('FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR')
trigger_dir = _require_dir('FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR')
poll = max(1, int(env('FREIGHT_RPA_WORKER_POLL_SECONDS', '3') or '3'))
heartbeat_seconds = max(
15,
int(env('FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
)
last_cleanup_mono = 0.0
cleanup_interval = cleanup_interval_seconds()
# [STEP 1] 启动 banner:字段对齐库存/入站 Worker,排查时一处看全运行配置。
print(
'[freight_outbound_rpa_worker] started\n'
f' mock={env("FREIGHT_RPA_WORKER_MOCK", "false")}\n'
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
f' poll_seconds={poll}\n'
f' heartbeat_seconds={heartbeat_seconds}\n'
f' headless={env("FREIGHT_RPA_WORKER_HEADLESS", "false")} '
f'channel={env("FREIGHT_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
f' credential_key={_mask_secret(env("FREIGHT_RPA_CREDENTIAL_KEY"))}\n'
f' trigger_dir={trigger_dir}\n'
f' drop_dir={drop_dir}\n'
f' browser_profile_dir={env("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
f' log={worker_logging.active_log_path() or "stdout-only"}\n'
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
)
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
"""按间隔执行保留清理;启动时强制一轮。
best-effort 语义:清理失败仅打印告警,不中断主循环;且无论成败都推进
上次清理时钟(返回 now_mono),避免持续性故障在每次 poll 后立刻重试刷屏。
"""
nonlocal last_cleanup_mono
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
return last_cleanup_mono
profile_root_raw = str(env('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
try:
stats = run_worker_disk_cleanup(
onhand_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
drop_dir=drop_dir,
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
log_file=worker_logging.active_log_path(),
)
print(format_cleanup_summary(stats))
except Exception as exc:
print(f'[outbound-cleanup] failed: {exc}')
return now_mono
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
# 启动时立即上报一次心跳,让监控端第一时间出现独立的
# `<hostname>-outbound` 出站 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
)
rpa_heartbeat.start_heartbeat_loop(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
)
while True:
for path in sorted(trigger_dir.glob('*.json')):
worker_logging.maybe_rotate_open_log()
try:
_claim_and_process(path, drop_dir)
except Exception as exc:
print(f'[outbound-trigger] failed {path.name}: {exc}')
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
time.sleep(poll)
if __name__ == '__main__':
main()
@@ -0,0 +1,183 @@
<#
.SYNOPSIS
Register the test/prod Outbound RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Outbound Worker as a background scheduled task with NO visible console and
NO visible browser (the Worker launches Playwright headless via -Headless).
Deliberately ASCII-only so it parses identically under any Windows console code page.
Mirrors register_onhand_worker_tasks.ps1 one-to-one, with distinct task names so
all three Workers can be registered side by side on the same host:
- Onhand: "HXOPS Freight Onhand RPA Worker TEST/PROD"
- Inbound: "HXOPS Freight Inbound RPA Worker TEST/PROD"
- Outbound: "HXOPS Freight Outbound RPA Worker TEST/PROD"
Shape constraints (same as the onhand registration):
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
decrypted in a non-interactive context.
- The RPA account should be configured for auto-logon and must not be locked
/ logged-off, otherwise the AtLogOn task does not stay resident.
- Before trusting headless, run the headless smoke preflight:
set FREIGHT_RPA_WORKER_HEADLESS=true then run crane_login_smoke.py
(the DBS portal has no smoke script - verify the first headless run visually).
Scope:
All actions can target one environment or both via -Scope test|prod|all (default all).
Usage (run in the RPA account's PowerShell):
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 # register test+prod
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Scope test # register only test
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Start # start both now
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Status -Scope test # only test
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1 -Unregister # unregister both
#>
[CmdletBinding()]
param(
[switch]$Register,
[switch]$Start,
[switch]$Stop,
[switch]$Status,
[switch]$Unregister,
[ValidateSet("test", "prod", "all")]
[string]$Scope = "all",
[string]$TestApiBase = "http://192.168.100.192:8890",
[string]$ProdApiBase = "http://192.168.100.230:8890",
[string]$TestRoot = "C:\HxopsRpaTest",
[string]$ProdRoot = "C:\HxopsRpaProd",
[string]$SecretFile = "C:\HxopsRpaSecrets"
)
$ErrorActionPreference = "Stop"
$TestTask = "HXOPS Freight Outbound RPA Worker TEST"
$ProdTask = "HXOPS Freight Outbound RPA Worker PROD"
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
function Get-TasksForScope {
# Return the task name(s) selected by -Scope.
param([string]$Scope)
switch ($Scope) {
"test" { return @($TestTask) }
"prod" { return @($ProdTask) }
default { return @($TestTask, $ProdTask) }
}
}
function Assert-Launcher {
# Validate the launcher and DPAPI Secret file required for one environment.
param([string]$Root, [string]$Environment)
$launcher = Join-Path $Root "scripts\freight_rpa\outbound\start_outbound_worker.ps1"
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
throw "Launcher not found: $launcher"
}
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
}
}
function New-TaskDefinition {
param(
[string]$TaskName,
[string]$Root,
[string]$ApiBase,
[string]$EnvName
)
$launcher = Join-Path $Root "scripts\freight_rpa\outbound\start_outbound_worker.ps1"
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
# Key differences vs the visible scheduled task:
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
$action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument $actionArgs `
-WorkingDirectory $Root
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
$principal = New-ScheduledTaskPrincipal `
-UserId $RunAsUser `
-LogonType Interactive `
-RunLevel Limited
$settings = New-ScheduledTaskSettingsSet `
-StartWhenAvailable `
-RestartCount 10 `
-RestartInterval (New-TimeSpan -Minutes 1) `
-ExecutionTimeLimit ([TimeSpan]::Zero) `
-MultipleInstances IgnoreNew
Register-ScheduledTask `
-TaskName $TaskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description "HXOPS Freight Outbound RPA Worker ($EnvName) background (headless + hidden console)"
}
# Default action is Register when no switch is given.
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
# handled below
} else {
$Register = $true
}
if ($Unregister) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Unregistered task: $t"
}
exit 0
}
if ($Start) {
foreach ($t in (Get-TasksForScope $Scope)) {
Start-ScheduledTask -TaskName $t
Write-Host "Started task: $t"
}
exit 0
}
if ($Stop) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t
Write-Host "Stopped task: $t"
}
exit 0
}
if ($Status) {
foreach ($t in (Get-TasksForScope $Scope)) {
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
if ($tobj) {
$info = Get-ScheduledTaskInfo -TaskName $t
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
Write-Host " (267009 / 0x41301 = running, not an error)"
} else {
Write-Host "Task not registered yet: $t"
}
}
exit 0
}
if ($Register) {
if ($Scope -eq "test" -or $Scope -eq "all") {
Assert-Launcher $TestRoot "test"
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
}
if ($Scope -eq "prod" -or $Scope -eq "all") {
Assert-Launcher $ProdRoot "prod"
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
}
Write-Host "Registered background task(s) for scope=${Scope}:"
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
exit 0
}
@@ -0,0 +1,97 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树启动独立货代出站 RPA Worker。
.DESCRIPTION
只设置 Process 级环境变量和 outbound 专用目录;可与 onhand/inbound Worker 并行运行,
三者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
根(各自按 connector+profile 隔离会话目录)。
默认开启会话复用(SESSION_REUSE,对齐库存);需要每次全新登录时传 -NoSessionReuse。
与库存同口径注入 FREIGHT_RPA_SHARED_SCOPE_ID:心跳线程据此把共享哨兵
.hxops_rpa_shared_mount 写进出站 trigger 目录,后端写 trigger 前按
心跳+哨兵+scope 做在线 fail-fast 检查(漏配时出站排程报 shared_sentinel_missing)。
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
[Parameter(Mandatory = $true)][string]$ApiBase,
[Parameter(Mandatory = $true)][string]$WorkerRoot,
[Parameter(Mandatory = $true)][string]$SecretFile,
[string]$PythonExe = 'python.exe',
[switch]$Mock,
[switch]$Headless,
# 默认开启出站会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
[switch]$NoSessionReuse,
# 兼容旧文档:等价于开启复用(现在默认已开启);与库存开关同名,语义完全一致。
[switch]$ReuseSession
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。" }
$workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\outbound\outbound_rpa_worker.py'
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
}
$secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
}
# freight_rpa 分域布局根:$WorkerRoot\data\freight_rpa\{onhand,inbound,outbound,common}
$rpaRoot = Join-Path $WorkerRoot 'data\freight_rpa'
# 共享 scope 标识(与库存同口径):Windows 本地路径不含共享名,无法推导,必须显式注入;
# 心跳线程据此把哨兵写进出站 trigger 目录,后端就绪检查按 scope 比对。
if ($Environment -eq 'test') {
$scopeId = 'hxops-rpa-test-data'
} else {
$scopeId = 'hxops-rpa-prod-data'
}
# 局部变量名刻意避开参数名:PS 变量名大小写不敏感,$sessionReuse 曾与旧开关
# $SessionReuse 互为同一变量,字符串 'true'/'false' 覆盖开关值,在部分 Windows build
# 上于启动阶段以 SwitchParameter 转换异常爆出(2026-09-30 修复)。开关现统一为
# $ReuseSession(与库存同名),局部变量统一为 $sessionReuse(与 onhand Worker 同名,便于契约测试断言)。
$sessionReuse = if ($NoSessionReuse) { 'false' } else { 'true' }
if ($ReuseSession -and $NoSessionReuse) {
Write-Warning '同时指定 -ReuseSession 与 -NoSessionReuse 时以 -NoSessionReuse 为准'
}
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
FREIGHT_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'outbound\logs\worker.log'
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = '10485760'
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = '5'
# 独立 Worker 身份:监控端按 worker_id 出独立出站卡片,固定后缀避免与库存/入站 Worker/按 pid 的身份抖动。
FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-outbound"
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
# 共享 scope 标识(与库存同口径):缺省时出站 Worker 不写哨兵、心跳 scope 为空,
# test/prod 后端出站就绪检查会报 shared_sentinel_missing / shared_scope_mismatch。
FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = Join-Path $rpaRoot 'outbound\triggers'
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = Join-Path $rpaRoot 'outbound\drop'
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile;会话按 connector+profile 分目录。
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
# 本机磁盘保留:与 onhand Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/outbound_* Profile)。
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = '3600'
FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = '24'
}
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try {
Write-Host "Starting outbound RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot sessionReuse=$sessionReuse"
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, $null, 'Process') }
}