feat(rpa): 恢复FREIGHT_RPA命名空间统一运行目录并完成收料部署对齐与readiness加固

- AGENTS.md §8.1 红线改写:env 命名空间恢复 FREIGHT_RPA_*,SHIPPING_NOTICE_RPA_* 一刀切废弃、不设兼容层
- 全仓机械前缀替换(70 文件)并删除兼容层;4 个既有基线测试失败一并清零(过期桩/存储隔离/排程 fail-fast 接线)
- 运行期数据目录统一 freight_rpa/{inventory,receipt,common}:settings 默认、4 个 env、2 个 ps1 三侧一致
- 代码目录 scripts/rpa 更名 scripts/freight_rpa 与数据根对齐;全仓路径引用同步,README 部署走查与升级小节
- 收料部署对齐库存:计划任务注册脚本(独立任务名)、可选 -SessionReuse 会话复用、DSV 老别名链移除
- readiness 加固:排程离线立即 failed(不挂 awaiting);无 Redis 时追加进程内存储原因码与本地测试指引
- DSV 会话准备遇 SSO 重定向中止时改走自动登录,首源不再因未登录判死
This commit is contained in:
hugo committed 2026-09-19 09:49:25 +08:00
1 parent 95488db656
commit c3eef5cf20
90 files changed
+2022 -1463

No files matched your search

@@ -0,0 +1,57 @@
"""Crane 收料报表导出适配器。"""
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 / "inventory").is_dir() and (_c / "receipt").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
_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
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')
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, '/inbound-details-query'))
def export_receipt_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 Inbound Details 文件,禁止按最新历史文件选择。"""
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')
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)
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)
# 旧 Crane driver 的 Scheduled Reports 匹配名来自 source;收料固定为
# Inbound Details,不能沿用库存的 OnHandDetails.xlsx 默认值。
source = {
'entry_url': entry_url,
'scheduled_report_name': 'Inbound Details',
}
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,42 @@
"""DBS 收料报表导出适配器。"""
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 / "inventory").is_dir() and (_c / "receipt").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
_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 export_receipt_report(page: Any, unit: dict[str, Any], *, entry_url: str, first_in_profile: bool) -> Any:
"""在既有 DBS 登录态内执行收料路径、Warehouse 与受控非日期条件。"""
source = {
'entry_url': entry_url,
'report_path_json': dict(unit.get('report_path_json') or {}),
'parameters': list(unit.get('query_parameters_json') or []),
'__download_dir': str(unit.get('__download_dir') or ''),
}
warehouse_id = str(unit.get('warehouse_id') or '').strip()
if not warehouse_id:
raise RuntimeError('DBS receipt unit requires warehouse_id')
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
if first_in_profile:
dsv_report_export.ensure_dsv_session(page, entry_url)
return dsv_report_export.export_dsv_inventory_source(page, {'action': 'receipt_export_batch'}, source)
@@ -0,0 +1,336 @@
"""独立货代收料 RPA Worker:仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。"""
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 / "inventory").is_dir() and (_c / "receipt").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
_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
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 receipt_crane_export # noqa: E402
import receipt_dbs_export # noqa: E402
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:
"""读取 receipt 专用目录;不回退至库存共享路径。"""
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_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元结果,认证密钥从进程 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}/api/shipping-notice/rpa/receipt-batch-ready',
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=30) as response:
if response.status < 200 or response.status >= 300:
raise RuntimeError(f'receipt callback failed: HTTP {response.status}')
@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 _open_browser(download_dir: Path, reuse_session: bool = False):
"""为一个 receipt Profile 分组创建浏览器上下文,组内登录一次、串行导出。
reuse_session=False(默认):一次性临时 Profile(receipt_* 前缀),批次结束即删,隔离最干净。
reuse_session=True:持久会话 Profile(receipt_session),跨批次复用登录态,适用于同日重跑/重试;
持久目录命中磁盘清理的 *_session 豁免规则,不会被孤儿清理删除。
"""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError('Playwright is required for real receipt RPA') from exc
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
if reuse_session:
runtime_profile = profile_root / 'receipt_session'
runtime_profile.mkdir(parents=True, exist_ok=True)
else:
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
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 _save_download(download: Any, drop_dir: Path, unit: dict[str, Any]) -> Path:
"""保存本单元下载文件到 receipt drop 并计算 callback 需要的身份。"""
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
if suffix != '.xlsx':
raise RuntimeError('receipt report download must be xlsx')
safe_callback = ''.join(ch for ch in str(unit['callback_id']) if ch.isalnum() or ch in {'-', '_'})
target = drop_dir / f'receipt_{safe_callback}_{datetime.utcnow():%Y%m%d%H%M%S}.xlsx'
download.save_as(str(target))
if target.stat().st_size <= 0:
raise RuntimeError('receipt report download is empty')
return target
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}')
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
raise RuntimeError('unsupported receipt 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')
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]})
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
"""按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。"""
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')
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')
_validate_unit(item)
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
for (connector, _profile, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
reuse_session = env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false').lower() == 'true'
resources = (None, None, None, None)
try:
if not mock:
resources = _open_browser(drop_dir, reuse_session=reuse_session)
playwright, context, page, profile_dir = resources
with _profile_credentials(group[0]):
for index, unit in enumerate(group):
try:
if mock:
from openpyxl import Workbook
mock_path = drop_dir / f"receipt_{unit['callback_id'].replace(':', '_')}.xlsx"
workbook = Workbook(); workbook.active.append(['Receipt RPA mock']); workbook.save(mock_path); workbook.close()
output = mock_path
else:
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
if index:
page = context.new_page(); page.set_default_timeout(browser_timeout_ms())
download = receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
else:
download = receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
output = _save_download(download, drop_dir, unit)
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
)
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
except Exception as exc:
_report_failure(unit, exc)
finally:
playwright, context, _page, profile_dir = resources
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
# 会话复用模式保留 receipt_session 持久目录(命中清理豁免),仅一次性模式即删。
if profile_dir is not None and not reuse_session:
shutil.rmtree(profile_dir, ignore_errors=True)
def _claim_and_process(path: Path, drop_dir: Path) -> None:
"""原子领取一个 receipt trigger;成功归档 processed,异常归档 failed。
领取与归档统一走 common/trigger_consumer(四态目录契约),
本函数只保留收料批次处理与 SystemExit 兜底。
"""
claimed = claim_trigger(path)
if claimed is None:
return
print(f'[receipt-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}')
except (Exception, SystemExit):
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
archive_trigger(claimed, 'failed')
print(f'[receipt-trigger] archived failed {claimed.name}')
raise
finally:
rpa_heartbeat.set_worker_runtime_status('idle')
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')
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_receipt_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(
inventory_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}')
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 抖动)。
rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
)
# 心跳节奏交由独立守护线程承担:收料批量导出会长时间阻塞主循环,
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
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'[receipt-trigger] failed {path.name}: {exc}')
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
time.sleep(poll)
if __name__ == '__main__':
main()
@@ -0,0 +1,182 @@
<#
.SYNOPSIS
Register the test/prod Receipt RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Receipt Worker as a background scheduled task with NO visible console and
NO visible browser (the Worker launches Playwright headless via -Headless).
Deliberately ASCII-only so it parses identically under any Windows console code page.
Mirrors register_inventory_worker_tasks.ps1 one-to-one, with distinct task names so
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"
Shape constraints (same as the inventory 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\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
#>
[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 Receipt RPA Worker TEST"
$ProdTask = "HXOPS Receipt 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\receipt\start_receipt_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\receipt\start_receipt_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 Receipt 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,73 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树启动独立货代收料 RPA Worker。
.DESCRIPTION
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
二者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
根(各自在其中创建隔离的一次性子目录)。
#>
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,
# 可选跨批次会话复用:持久 receipt_session Profile(同日重跑/重试免登录);默认一次性临时 Profile。
[switch]$SessionReuse
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" }
$workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\receipt\receipt_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\freight_rpa\{inventory,receipt,common}(与后端 settings/.env 默认值一致)。
$rpaRoot = Join-Path $WorkerRoot 'freight_rpa'
$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 = $(if ($SessionReuse) { 'true' } else { 'false' })
# 不设 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_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_HEARTBEAT_SECONDS = '20'
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $rpaRoot 'receipt\triggers'
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $rpaRoot 'receipt\drop'
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile(各自在其中创建隔离的一次性子目录)。
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
# 本机磁盘保留:与库存 Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/receipt_* 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 root=$WorkerRoot"
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, $null, 'Process') }
}