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

+72 -12
View File
@@ -16,6 +16,20 @@ inbound(原收料)使用 `scripts\freight_rpa\inbound\inbound_rpa_worker.py`
inbound Worker 在同一排程内按 Profile 登录一次后串行处理单元;DBS 每个 Warehouse 导出一个文件且不传报表日期,Crane 无论 Profile 登录地址保存为门户首页还是其他页面,都会强制进入 `#/inbound-details-query`,不填写 Warehouse 或查询条件,直接使用页面默认条件生成/等待唯一 Description 对应的 `Inbound Details` 文件。不要把inbound trigger 手工复制到库存目录或反向复制。
## 出站 RPA(独立 Worker)
outbound 使用 `scripts\freight_rpa\outbound\outbound_rpa_worker.py` 与 `scripts\freight_rpa\outbound\start_outbound_worker.ps1`,仅消费 `FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR`,仅写 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`,只回调 `/api/freight-rpa/outbound-batch-ready`。schema `freight_rpa.outbound.v1` / action `outbound_export_batch`;心跳能力 `outbound_export`,Worker ID `<hostname>-outbound`。可与 onhand/inbound 同机并行,目录与日志绝不能共用。
回调 `file_path` **只报 drop 根内文件名**(规格 §4.2):禁止把 `C:\...\drop\xxx.xlsx` 整串作为契约主值。
启动示例:
```powershell
.\scripts\freight_rpa\outbound\start_outbound_worker.ps1 -Environment test -ApiBase "http://<backend>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
DBS 使用站点出站配置的 `report_path_json` 导航,不写死入站/库存报表名。Crane 固定进入 `#/outbound-details-query`,Scheduled Reports 匹配名 `Outbound Details`(与 Task 6 管理端占位一致;**禁止**误用 Inbound Details)。货代实名页尚未用截图/环境确认,若门户 hash 不同只改 `outbound_crane_export.py` 常量并同步管理端校验。不要把 outbound trigger 手工复制到 inbound/onhand 目录。
## 先看这里:文档阅读路径
请按实际场景只走一条路径,不要把“首次部署”和“部署后日常运维”重复执行:
@@ -42,7 +56,7 @@ inbound Worker 在同一排程内按 Profile 登录一次后串行处理单元
| `common/rpa_heartbeat.py` | 向后端上报心跳 + 共享目录哨兵(原 `freight_rpa_heartbeat.py`) |
| `common/worker_disk_cleanup.py` | Worker 本机磁盘保留清理(日志备份 / trigger·drop 归档 / 孤儿 run_* Profile) |
| `common/new_rpa_worker_secret.ps1` | 生成当前用户可解密的 DPAPI Secret 文件 |
| `connectors/` | **登录网站 / 报表系统自动化**(onhand 与 inbound 共用) |
| `connectors/` | **登录网站 / 报表系统自动化**(onhand / inbound / outbound 共用) |
| `connectors/dsv/` | DSV 360 连接器:`dsv_driver` / `dsv_auth` / `dsv_auth_login_flow` / `dsv_session` / `dsv_navigation` / `dsv_report_export` / `dsv_debug` / `dsv_report_parameters` / `dsv_login_smoke` / `dsv_export_timeout_diagnostics` |
| `connectors/crane/` | Crane FootPrint 连接器:`crane_session` / `crane_navigation` / `crane_report_export` / `crane_login_smoke` |
| `onhand/` | **onhand(在手库存)RPA 流程编排** |
@@ -56,18 +70,26 @@ inbound Worker 在同一排程内按 Profile 登录一次后串行处理单元
| `inbound/inbound_dbs_export.py` | DBS 收料报表导出适配器(按 Warehouse) |
| `inbound/start_inbound_worker.ps1` | 启动 inbound Worker 的 PowerShell 启动脚本(原 `start_receipt_rpa_worker.ps1`) |
| `inbound/register_inbound_worker_tasks.ps1` | 注册 test/prod inbound Worker 后台计划任务(headless + hidden,任务名与库存注册脚本相互独立) |
| `outbound/` | **outbound(出站)RPA 流程编排** |
| `outbound/outbound_rpa_worker.py` | 独立 outbound Worker:仅消费 outbound trigger、专用目录与回调 |
| `outbound/outbound_crane_export.py`| Crane 出站报表导出适配器(固定 Outbound Details,禁止 Inbound Details) |
| `outbound/outbound_dbs_export.py` | DBS 出站报表导出适配器(配置 report_path) |
| `outbound/start_outbound_worker.ps1` | 启动 outbound Worker 的 PowerShell 启动脚本 |
| `outbound/register_outbound_worker_tasks.ps1` | 注册 test/prod outbound Worker 后台计划任务(headless + hidden,任务名独立可同机并存) |
## 目录约定
> **目录布局**:RPA 运行期数据统一存放在 `<WorkerRoot>\data\freight_rpa\{onhand,inbound,outbound,upload,common}`(后端 dev 默认对应 `backend/data/freight_rpa/...`,test/prod 对应 SMB 挂载下的 `freight_rpa/...` 子路径)。抓取域叶目录为 triggers/drop/logs/archives;`upload` 叶目录为 triggers/queue;`common` 仅放跨 Worker 共享物(`browser_profile`)。outbound 只预留在途调拨出站抓取。
> **目录布局**:RPA 运行期数据统一存放在 `<WorkerRoot>\data\freight_rpa\{onhand,inbound,outbound,upload,common}`(后端 dev 默认对应 `backend/data/freight_rpa/...`,test/prod 对应 SMB 挂载下的 `freight_rpa/...` 子路径)。抓取域叶目录为 triggers/drop/logs/archives;`upload` 叶目录为 triggers/queue;`common` 仅放跨 Worker 共享物(`browser_profile`)。outbound 为在途调拨出站抓取(独立 Worker)。
| 环境变量 | 用途 |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json` 或 `inventory_export_batch_{run_no}.json`(文件名沿用既有契约,schema/action 为 freight_rpa.onhand.v1 / onhand_export*),RPA 读取后导 onhand |
| `FREIGHT_RPA_SHARED_ONHAND_DROP_DIR` | RPA 落盘 onhand Excel(`.xlsx`),hxops / worker 回调 ingest(onhand-ready) |
| `FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR` | hxops 写入 `outbound_export_batch_{run_no}.json`(schema `freight_rpa.outbound.v1` / action `outbound_export_batch`) |
| `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR` | RPA 落盘 outbound Excel(`.xlsx`),回调 `/api/freight-rpa/outbound-batch-ready`(`file_path` 只报文件名,见规格 §4.2) |
| `FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
| `FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
| `FREIGHT_RPA_WORKER_UPLOAD_ENABLED` | 真实上传浏览器自动化总开关,默认 `false` |
@@ -135,16 +157,16 @@ DSV Worker 默认使用 `#file2`,也可用 `FREIGHT_RPA_WORKER_UPLOAD_FILE_SEL
人工确认导出未完成则移回根目录重跑,已完成则人工补回调后归档。
- 新增 Worker 一律复用 `common/trigger_consumer.py`,禁止再自建目录搬移逻辑。
## Worker 运行能力(onhand / inbound 对齐)
## Worker 运行能力(onhand / inbound / outbound 对齐)
| 能力 | onhand Worker | inbound Worker |
| --- | --- | --- |
| 文件日志(tee+时间戳+轮转) | `FREIGHT_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_rpa\inbound\logs\worker.log`) |
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) |
| 心跳上报 | `<hostname>-onhand`(ps1 注入 `WORKER_ID`,稳定身份) | `<hostname>-inbound`(独立身份,ps1 注入) |
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清 inbound processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`inbound_*`) |
| 能力 | onhand Worker | inbound Worker | outbound Worker |
| --- | --- | --- | --- |
| 文件日志(tee+时间戳+轮转) | `FREIGHT_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_rpa\inbound\logs\worker.log`) | 同左(ps1 默认 `data\freight_rpa\outbound\logs\worker.log`) |
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) | ✅ |
| 心跳上报 | `<hostname>-onhand`(ps1 注入 `WORKER_ID`,稳定身份) | `<hostname>-inbound`(独立身份,ps1 注入) | `<hostname>-outbound`(能力 `outbound_export`) |
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清 inbound processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`inbound_*`) | 同左(清 outbound 归档与孤儿 `outbound_*` Profile) |
规则:**两个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
规则:**三个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
每个 Worker 的 `LOG_FILE` 必须指向各自根目录下的 `logs/worker.log`。
## 部署、启动与停止手册
@@ -204,6 +226,20 @@ Linux HXOPS 后端 Windows RPA Worker
8. 后端:`.env` 追加 `FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR` / `FREIGHT_RPA_SHARED_INBOUND_DROP_DIR` 两个共享子路径(漏配会写容器本地默认路径,Windows 看不到);容器 bind mount 无需新增。收料文件回调后原样归档 MinIO 保留三年,到期清理由平台任务「货代收料归档到期清理」负责。
9. 计划任务注册:`scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1`,与 onhand 注册脚本同构(`AtLogOn + Interactive`、headless + 隐藏控制台、`-Start`/`-Stop`/`-Status`/`-Unregister`/`-Scope` 同款),独立任务名 `HXOPS Freight Inbound RPA Worker TEST/PROD`,可与 onhand 计划任务同机并存;用法同 onhand 注册脚本,把路径换成 inbound 即可。
### outbound Worker 部署增量(与 onhand/inbound Worker 并行)
出站 RPA(出站报表导出 + MinIO 归档)使用独立 Worker,可与 onhand/inbound 同机并行。目录与启动脚本与入站对称:
1. 目录:每个 WorkerRoot 使用 `data\freight_rpa\outbound\{triggers,drop,logs}`(启动脚本按此注入);不得指向任何库存或入站目录。
2. 程序:整目录复制 `scripts\freight_rpa` 时已包含 `outbound\`;`outbound_rpa_worker.py` 要求同级存在 `connectors/`、`common/`、`onhand/`、`outbound/` 子目录。
3. Secret:与 onhand 共用 `new_rpa_worker_secret.ps1` 生成的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`,无需新建。
4. 启动:`scripts\freight_rpa\outbound\start_outbound_worker.ps1`,参数与库存启动脚本一致;成功输出 `[freight_outbound_rpa_worker] started`。
5. 心跳/哨兵:独立身份 `<主机名>-outbound`(ps1 注入 `FREIGHT_RPA_WORKER_ID`),能力 `outbound_export`;哨兵写进 outbound trigger 目录。
6. 日志:ps1 注入 `FREIGHT_RPA_WORKER_LOG_FILE`,默认 `data\freight_rpa\outbound\logs\worker.log`;三个 Worker 禁止共写同一日志文件。
7. 后端:`.env` 追加 `FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR` / `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`。
8. 计划任务:`scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1`,任务名 `HXOPS Freight Outbound RPA Worker TEST/PROD`。
9. 回调路径契约:`file_path` 只报文件名(规格 §4.2),禁止 Windows 绝对路径。
### 从旧布局升级(统一为 `<WorkerRoot>\data\freight_rpa\{onhand,inbound,outbound,upload,common}`,共享根为 `data`)
2026-09-18 起 RPA 运行期数据目录统一为 `freight_rpa\{onhand,inbound,outbound,upload,common}`,且 **SMB 共享根固定为 `<WorkerRoot>\data`**(`scripts` 代码目录不进共享)。outbound 只预留调拨出站抓取;upload 与抓取域同级。按环境现状分两种升级路径:
@@ -365,10 +401,14 @@ Test-Path C:\HxopsRpaTest\scripts\freight_rpa\onhand\start_onhand_worker.ps1
Test-Path C:\HxopsRpaTest\scripts\freight_rpa\common\new_rpa_worker_secret.ps1
Test-Path C:\HxopsRpaTest\scripts\freight_rpa\inbound\inbound_rpa_worker.py
Test-Path C:\HxopsRpaTest\scripts\freight_rpa\inbound\start_inbound_worker.ps1
Test-Path C:\HxopsRpaTest\scripts\freight_rpa\outbound\outbound_rpa_worker.py
Test-Path C:\HxopsRpaTest\scripts\freight_rpa\outbound\start_outbound_worker.ps1
Test-Path C:\HxopsRpaProd\scripts\freight_rpa\onhand\onhand_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\freight_rpa\onhand\start_onhand_worker.ps1
Test-Path C:\HxopsRpaProd\scripts\freight_rpa\inbound\inbound_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\freight_rpa\inbound\start_inbound_worker.ps1
Test-Path C:\HxopsRpaProd\scripts\freight_rpa\outbound\outbound_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\freight_rpa\outbound\start_outbound_worker.ps1
```
每一行都应返回 `True`。不要复制 `.env*`、旧 trigger、旧 `processed/failed`、旧浏览器 profile 和真实密钥文件。
@@ -383,9 +423,11 @@ foreach ($path in @(
"C:\HxopsRpaTest\scripts\freight_rpa\common\new_rpa_worker_secret.ps1",
"C:\HxopsRpaTest\scripts\freight_rpa\onhand\start_onhand_worker.ps1",
"C:\HxopsRpaTest\scripts\freight_rpa\inbound\start_inbound_worker.ps1",
"C:\HxopsRpaTest\scripts\freight_rpa\outbound\start_outbound_worker.ps1",
"C:\HxopsRpaProd\scripts\freight_rpa\common\new_rpa_worker_secret.ps1",
"C:\HxopsRpaProd\scripts\freight_rpa\onhand\start_onhand_worker.ps1",
"C:\HxopsRpaProd\scripts\freight_rpa\inbound\start_inbound_worker.ps1"
"C:\HxopsRpaProd\scripts\freight_rpa\inbound\start_inbound_worker.ps1",
"C:\HxopsRpaProd\scripts\freight_rpa\outbound\start_outbound_worker.ps1"
)) {
$text = [System.IO.File]::ReadAllText($path, [System.Text.UTF8Encoding]::new($false))
[System.IO.File]::WriteAllText($path, $text, $utf8Bom)
@@ -613,6 +655,8 @@ FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/uploa
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/queue
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true
@@ -627,6 +671,8 @@ FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/uploa
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/queue
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/triggers
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/drop
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true
@@ -1134,9 +1180,11 @@ FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhan
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/queue
# 收料共用同一挂载根(详见「inbound Worker 部署增量」)
# 入站/出站共用同一挂载根(详见「inbound/outbound Worker 部署增量」)
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
@@ -1707,6 +1755,18 @@ $env:FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = Join-Path $inboundRoot "inbound\drop"
python scripts/freight_rpa/inbound/inbound_rpa_worker.py
```
outbound Worker 本地联调:
```powershell
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与 backend 一致>"
$env:FREIGHT_RPA_WORKER_MOCK = "true"
$outboundRoot = Join-Path (Get-Location).Path "backend\data\freight_rpa"
$env:FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = Join-Path $outboundRoot "outbound\triggers"
$env:FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = Join-Path $outboundRoot "outbound\drop"
python scripts/freight_rpa/outbound/outbound_rpa_worker.py
```
## 四、Driver 与业务参考
+5 -1
View File
@@ -4,7 +4,7 @@ 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 一律从本模块常量取回调路径,禁止再硬编码;
逻辑:onhand/inbound/outbound Worker 与 rpa_heartbeat 一律从本模块常量取回调路径,禁止再硬编码;
post_callback 复用统一鉴权(双 Header 集成密钥)、脱敏请求日志与 HTTP 错误处理。
路径清单与后端 backend/app/api/freight_rpa.py 蓝图路由一一对应,改动须双侧同步。
"""
@@ -38,6 +38,10 @@ ONHAND_REPAIR = f"{_CALLBACK_BASE}/onhand-repair"
INBOUND_BATCH_READY = f"{_CALLBACK_BASE}/inbound-batch-ready"
INBOUND_UNIT_PROGRESS = f"{_CALLBACK_BASE}/inbound-unit-progress"
INBOUND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/inbound-batch-progress"
# outbound(出站)Worker 回调。
OUTBOUND_BATCH_READY = f"{_CALLBACK_BASE}/outbound-batch-ready"
OUTBOUND_UNIT_PROGRESS = f"{_CALLBACK_BASE}/outbound-unit-progress"
OUTBOUND_BATCH_PROGRESS = f"{_CALLBACK_BASE}/outbound-batch-progress"
# 货代上传结果(URL 词根不变,仅前缀换为 /api/freight-rpa)。
UPLOAD_COMPLETE = f"{_CALLBACK_BASE}/upload-complete"
+13 -6
View File
@@ -3,8 +3,8 @@ scripts/freight_rpa/common/rpa_heartbeat.py
用途:货代 RPA Worker 向后端上报心跳(POST /api/freight-rpa/heartbeat(路径常量见 common/rpa_callbacks.HEARTBEAT))。
依赖:rpa_common.env、urllib、socket。
逻辑:由 onhand/inbound Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
onhand 声明 onhand_export,inbound(原收料)声明 inbound_export;onhand 侧可写共享目录哨兵。
逻辑:由 onhand/inbound/outbound Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
onhand 声明 onhand_export,inbound 声明 inbound_export,outbound 声明 outbound_export;可写共享目录哨兵。
"""
from __future__ import annotations
@@ -138,14 +138,21 @@ def build_heartbeat_payload(
"""
组装心跳 payload。
核心逻辑:onhand Worker 声明 onhand_export;inbound Worker(worker_id 以 -inbound
结尾,或 trigger_dir 路径含 /inbound/)声明 inbound_export;开启上传时附加 freight_rpa_upload。
核心逻辑:outbound Worker(worker_id 以 -outbound 结尾,或 trigger_dir 含 /outbound/)
声明 outbound_export;inbound 同理 inbound_export;其余 onhand_export。开启上传时附加 freight_rpa_upload。
"""
hostname = socket.gethostname()
worker_id = _resolve_worker_id(hostname)
trigger_norm = str(trigger_dir or "").replace("\\", "/").lower()
is_inbound = str(worker_id).lower().endswith("-inbound") or "/inbound/" in f"/{trigger_norm}/"
capabilities = ["inbound_export" if is_inbound else "onhand_export"]
worker_id_l = str(worker_id).lower()
is_outbound = worker_id_l.endswith("-outbound") or "/outbound/" in f"/{trigger_norm}/"
is_inbound = worker_id_l.endswith("-inbound") or "/inbound/" in f"/{trigger_norm}/"
if is_outbound:
capabilities = ["outbound_export"]
elif is_inbound:
capabilities = ["inbound_export"]
else:
capabilities = ["onhand_export"]
upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
"1", "true", "yes", "on",
}
@@ -3,7 +3,7 @@ scripts/freight_rpa/common/worker_disk_cleanup.py
用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。
依赖:rpa_common.env、pathlib、shutil、time。
逻辑:由 onhand(及可复用的 inbound)Worker 主循环周期调用;只删超过保留期的归档与临时物,
逻辑:由 onhand / inbound / outbound Worker 主循环周期调用;只删超过保留期的归档与临时物,
绝不删除进行中的 trigger 根目录 JSON、可复用会话 Profile(*_session)、以及活跃 cleanup 队列。
"""
@@ -48,9 +48,9 @@ _PROTECTED_DROP_DIRNAMES = frozenset(
)
_DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"})
_TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed")
# 一次性运行 Profile 前缀:onhand Worker 用 run_*,inbound Worker 用 inbound_*,
# 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "inbound_")
# 一次性运行 Profile 前缀:onhand 用 run_*,inbound 用 inbound_*,outbound 用 outbound_*,
# 均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。
_RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "inbound_", "outbound_")
_DEFAULT_RETENTION_DAYS = 7
_DEFAULT_INTERVAL_SECONDS = 3600
_DEFAULT_ORPHAN_PROFILE_HOURS = 24
@@ -111,7 +111,7 @@ def cleanup_interval_seconds() -> int:
def orphan_profile_max_age_seconds() -> int:
"""
读取孤儿临时 Profile(run_* / inbound_*)最大存活秒数。
读取孤儿临时 Profile(run_* / inbound_* / outbound_*)最大存活秒数。
核心逻辑:`FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
@@ -335,11 +335,11 @@ def cleanup_orphan_runtime_profiles(
stats: DiskCleanupStats,
) -> None:
"""
清理浏览器 Profile 根下过期的一次性 `run_*` / `inbound_*` 目录。
清理浏览器 Profile 根下过期的一次性 `run_*` / `inbound_*` / `outbound_*` 目录。
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
仅删除 `run_*` / `inbound_*` 临时目录,避免异常中断后残留撑盘。
inbound Worker 一次性 Profile 以 inbound_ 前缀创建,同属清理对象。
仅删除 `run_*` / `inbound_*` / `outbound_*` 临时目录,避免异常中断后残留撑盘。
inbound/outbound Worker 一次性 Profile 以前缀创建,同属清理对象。
"""
if profile_root is None or not profile_root.is_dir():
return
@@ -379,7 +379,7 @@ def run_worker_disk_cleanup(
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `inbound_*` Profile。全部 best-effort。
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `inbound_*` / `outbound_*` Profile。全部 best-effort。
Args:
onhand_trigger_dir: onhand trigger 根目录。
@@ -3,8 +3,8 @@ scripts/freight_rpa/dsv_report_export.py
用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。
依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。
逻辑:worker connector_type=dsv360 / 收料 DBS 时委托本模块;按 export_kind 分流
库存/收料的结果就绪正文标记与明细行探针(结构可参考,字段不复用);
逻辑:worker connector_type=dsv360 / 入站或出站 DBS 时委托本模块;按 export_kind 分流
库存/入站/出站的结果就绪正文标记与明细行探针(结构可参考,字段不复用);
DOM 明细行探测仅作加速,无行时重试 View Report 一次后仍导出,真空由落盘 Excel 判定。
"""
@@ -114,29 +114,48 @@ _DSV_INBOUND_BODY_MARKERS: tuple[str, ...] = (
"whole page",
)
# 出站报表正文标记(Task 12 占位:未拿到实机列头前用通用 shipped/outbound 词 + SSRS UI 词)。
_DSV_OUTBOUND_BODY_MARKERS: tuple[str, ...] = (
"outbound detail",
"outbound details",
"ship qty",
"qty shipped",
"date shipped",
"shipment",
"dispatch",
"page width",
"whole page",
)
def _dsv_export_kind(source: dict[str, Any] | None = None, *, kind: str | None = None) -> str:
"""
解析导出语义:inventory(onhand)| inbound(原 receipt)。
解析导出语义:inventory(onhand)| inbound(原 receipt)| outbound。
核心逻辑:显式 kind / source.__export_kind__ 优先;否则按报表名含 receipt detail 推断。
核心逻辑:显式 kind / source.__export_kind__ 优先;否则按报表名含 receipt/outbound 推断。
"""
explicit = str(kind or "").strip().lower()
if explicit in {"inventory", "inbound"}:
if explicit in {"inventory", "inbound", "outbound"}:
return explicit
if isinstance(source, dict):
flagged = str(source.get("__export_kind__") or "").strip().lower()
if flagged in {"inventory", "inbound"}:
if flagged in {"inventory", "inbound", "outbound"}:
return flagged
report = _dsv_report_name(source).casefold()
if "receipt detail" in report:
return "inbound"
if "outbound" in report:
return "outbound"
return "inventory"
def _dsv_body_markers_for_kind(kind: str) -> tuple[str, ...]:
"""按 export_kind 返回结果正文标记;收料与库存字段列表分离。"""
return _DSV_INBOUND_BODY_MARKERS if kind == "inbound" else _DSV_INVENTORY_BODY_MARKERS
"""按 export_kind 返回结果正文标记;入站/出站/库存字段列表分离。"""
if kind == "inbound":
return _DSV_INBOUND_BODY_MARKERS
if kind == "outbound":
return _DSV_OUTBOUND_BODY_MARKERS
return _DSV_INVENTORY_BODY_MARKERS
def _click_dsv_export_excel(page: Any, *, kind: str = "inventory") -> None:
@@ -746,8 +765,8 @@ def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int, *, kind: str =
f"frameIndex={frame_index}"
)
ready = bool(state["bodyReady"] and not state["asyncWait"])
if export_kind == "inbound":
# 收料:Export 工具栏或 Receipt Detail 正文均可作为就绪信号。
if export_kind in {"inbound", "outbound"}:
# 入站/出站:Export 工具栏或报表正文均可作为就绪信号(避免库存标记永远等不到)。
ready = (not state["asyncWait"]) and (state["bodyReady"] or state["exportReady"])
if ready:
# #region debug-point H2:wait-report-ready
@@ -1730,6 +1749,9 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
# 真空由落盘 Excel 判定(避免慢渲染假空 skip)。收料用 Receipt Detail 行探针。
if export_kind == "inbound":
_ensure_dsv_inbound_rows_or_export_fallback(page, report_name=report_name)
elif export_kind == "outbound":
# 出站 DOM 列头未用实机确认:不走库存/收料行探针,真空由落盘 Excel 判定。
pass
else:
_ensure_dsv_inventory_rows_or_export_fallback(page, report_name=report_name)
except Exception as exc:
@@ -13,7 +13,7 @@ from pathlib import Path
class NoInboundDataError(RuntimeError):
"""收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。"""
"""入站报表可打开且有表头,但无业务明细行(合法 empty / no_inbound_data)。"""
def _normalize_row_joined(row: tuple | list) -> str:
@@ -97,10 +97,10 @@ def inbound_excel_has_detail_rows(path: Path) -> bool | None:
def enforce_inbound_excel_not_empty(path: Path) -> None:
"""
有表头无明细时记为无收料(NoInboundDataError → empty / no_receipt_data)。
有表头无明细时记为无入站(NoInboundDataError → empty / no_inbound_data)。
Raises:
NoInboundDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。
NoInboundDataError: 可识别表头但无业务行;message 固定为 no_inbound_data。
"""
if inbound_excel_has_detail_rows(path) is False:
raise NoInboundDataError('no_receipt_data')
raise NoInboundDataError('no_inbound_data')
@@ -5,7 +5,7 @@ scripts/freight_rpa/inbound/inbound_rpa_worker.py
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
inbound_excel_empty、inbound_dbs_export、inbound_crane_export、connectors/dsv/dsv_report_export。
逻辑:排程写入 inbound trigger → 本进程领取并按 connector/profile 分组串行导出 →
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_receipt_data;
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_inbound_data;
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
"""
@@ -456,18 +456,18 @@ def _validate_unit(unit: dict[str, Any]) -> None:
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
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]})
_post_callback({'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.INBOUND_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
def _report_empty(unit: dict[str, Any], exc: NoInboundDataError) -> None:
"""无业务明细的合法结果:回调 empty + no_receipt_data(后端 finalize 计 skipped)。"""
"""无业务明细的合法结果:回调 empty + no_inbound_data(后端 finalize 计 skipped)。"""
print(f'[inbound-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
_post_callback({
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.get('callback_id'),
'status': 'empty',
'error_code': 'no_receipt_data',
'error_message': str(exc)[:2000] or 'no_receipt_data',
'error_code': 'no_inbound_data',
'error_message': str(exc)[:2000] or 'no_inbound_data',
})
@@ -1,6 +1,6 @@
<#
.SYNOPSIS
Register the test/prod Receipt RPA Worker scheduled tasks in FULL-BACKGROUND mode.
Register the test/prod Inbound RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Receipt Worker as a background scheduled task with NO visible console and
@@ -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') }
}