refactor(rpa): 重构 scripts/rpa 目录结构与命名

按 common/connectors/inventory/receipt 分层并重命名

- common/: rpa_common, rpa_heartbeat, download_artifact_fallback,
  new_rpa_worker_secret
- connectors/dsv|crane/: 登录网站连接器,库存与收料共用
- inventory/: inventory_rpa_worker, run_inventory_batch_trigger,
  start_inventory_worker, register_inventory_worker_tasks
- receipt/: receipt_rpa_worker, receipt_crane/dbs_export,
  start_receipt_worker

保留裸 import + sys.path 引导;修正懒加载路径;
按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks;
同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。

(cherry picked from commit f3050164d0)
This commit is contained in:
hugo committed 2026-08-28 17:23:39 +08:00
1 parent 09deada712
commit 12521489c6
40 files changed
+384 -172

No files matched your search

+1 -1
View File
@@ -137,7 +137,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/u
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
# 本地 RPA(scripts/rpa/inventory/inventory_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
+2 -2
View File
@@ -160,7 +160,7 @@ SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
@@ -174,7 +174,7 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queu
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选)
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
+1 -1
View File
@@ -10,7 +10,7 @@ import pytest
def _load_navigation():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_navigation.py"
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py"
spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
+1 -1
View File
@@ -10,7 +10,7 @@ import pytest
def _load_export():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_report_export.py"
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py"
spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
+2 -2
View File
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
def _load_crane_session():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_session.py"
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py"
spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
"""batch 内 session 有效时不应重复 goto + login。"""
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py"
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
assert spec and spec.loader
worker = importlib.util.module_from_spec(spec)
+1 -1
View File
@@ -7,7 +7,7 @@ from pathlib import Path
def _load_module():
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "dsv_report_parameters.py"
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -7,7 +7,7 @@ from pathlib import Path
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'freight_receipt_rpa_worker.py').read_text(encoding='utf-8')
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
assert 'shipping_receipt_rpa.v1' in text
@@ -19,8 +19,8 @@ def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract
def test_receipt_crane_driver_forces_inbound_details_match_name():
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
receipt_driver = (root / 'freight_receipt_crane_export.py').read_text(encoding='utf-8')
crane_driver = (root / 'crane_report_export.py').read_text(encoding='utf-8')
receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8')
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver
@@ -28,7 +28,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
def test_receipt_crane_driver_forces_inbound_details_entry_route():
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
module_path = root / 'freight_receipt_crane_export.py'
module_path = root / 'receipt' / 'receipt_crane_export.py'
sys.path.insert(0, str(root))
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
assert spec and spec.loader
+1 -1
View File
@@ -13,7 +13,7 @@ def _load_freight_rpa_heartbeat_module():
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa"
if str(rpa_dir) not in sys.path:
sys.path.insert(0, str(rpa_dir))
module_path = rpa_dir / "freight_rpa_heartbeat.py"
module_path = rpa_dir / "common" / "rpa_heartbeat.py"
spec = importlib.util.spec_from_file_location("freight_rpa_heartbeat_test", module_path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
+3 -3
View File
@@ -26,8 +26,8 @@ def _repo_root() -> Path:
def _load_freight_rpa_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_under_test", module_path)
module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
@@ -1627,7 +1627,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
module_path = _repo_root() / "scripts" / "rpa" / "dsv_report_export.py"
module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py"
spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
assert spec is not None and spec.loader is not None
dsv_report_export = importlib.util.module_from_spec(spec)
@@ -20,8 +20,21 @@ def _load_dsv_auth_login_flow():
return _load_rpa_module("dsv_auth_login_flow")
_RPA_MODULE_PATHS = {
"freight_rpa_worker": "inventory/inventory_rpa_worker.py",
"inventory_rpa_worker": "inventory/inventory_rpa_worker.py",
"dsv_report_export": "connectors/dsv/dsv_report_export.py",
"dsv_auth_login_flow": "connectors/dsv/dsv_auth_login_flow.py",
"dsv_navigation": "connectors/dsv/dsv_navigation.py",
"dsv_auth": "connectors/dsv/dsv_auth.py",
"dsv_session": "connectors/dsv/dsv_session.py",
"dsv_debug": "connectors/dsv/dsv_debug.py",
}
def _load_rpa_module(module_name: str):
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py")
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel
scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
@@ -12,7 +12,7 @@
## Global Constraints
- 禁止修改 `scripts/rpa/freight_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。
- 禁止修改 `scripts/rpa/inventory/inventory_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。
- 首版不实现库存和收料间的登录会话复用、同 Profile 互斥锁或跨排程协调;运维上错开使用同一 Profile 的排程时间。
- 收料 Worker 在单次排程内以 `connector_type + rpa_profile_id + login_url` 分组,每个分组登录一次、串行处理其全部单元。
- DBS 每个收料配置 Warehouse 展开一条单元;报表日期固定不传。Crane 每站点创建 `Inbound Details`,通过本次唯一 Description 轮询并下载。
@@ -88,10 +88,10 @@
### Task 4: 实现独立 DBS/Crane 收料 Windows Worker
**Files:**
- Create: `scripts/rpa/freight_receipt_rpa_worker.py`
- Create: `scripts/rpa/freight_receipt_dbs_export.py`
- Create: `scripts/rpa/freight_receipt_crane_export.py`
- Create: `scripts/rpa/start_receipt_rpa_worker.ps1`
- Create: `scripts/rpa/receipt/receipt_rpa_worker.py`
- Create: `scripts/rpa/receipt/receipt_dbs_export.py`
- Create: `scripts/rpa/receipt/receipt_crane_export.py`
- Create: `scripts/rpa/receipt/start_receipt_worker.ps1`
- Modify: `scripts/rpa/README.md`
- Test: `backend/tests/test_freight_receipt_worker_contract.py`
+28 -28
View File
@@ -1873,7 +1873,7 @@ GET /api/admin/shipping-order-schema/published-contract
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true"
python scripts/rpa/freight_rpa_worker.py
python scripts/rpa/inventory/inventory_rpa_worker.py
```
### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端)
@@ -1941,24 +1941,24 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
从项目仓库复制以下文件到 Windows RPA 主机:
```text
scripts\rpa\freight_rpa_worker.py
scripts\rpa\dsv_report_parameters.py
scripts\rpa\dsv_login_smoke.py
scripts\rpa\run_inventory_batch_trigger.py
scripts\rpa\inventory\inventory_rpa_worker.py
scripts\rpa\connectors\dsv\dsv_report_parameters.py
scripts\rpa\connectors\dsv\dsv_login_smoke.py
scripts\rpa\inventory\run_inventory_batch_trigger.py
```
放置为:
```text
C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py
C:\HxopsRpaTest\scripts\rpa\dsv_report_parameters.py
C:\HxopsRpaTest\scripts\rpa\dsv_login_smoke.py
C:\HxopsRpaTest\scripts\rpa\run_inventory_batch_trigger.py
C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py
C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_report_parameters.py
C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_login_smoke.py
C:\HxopsRpaTest\scripts\rpa\inventory\run_inventory_batch_trigger.py
C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py
C:\HxopsRpaProd\scripts\rpa\dsv_report_parameters.py
C:\HxopsRpaProd\scripts\rpa\dsv_login_smoke.py
C:\HxopsRpaProd\scripts\rpa\run_inventory_batch_trigger.py
C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py
C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_report_parameters.py
C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_login_smoke.py
C:\HxopsRpaProd\scripts\rpa\inventory\run_inventory_batch_trigger.py
```
不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。
@@ -2093,7 +2093,7 @@ cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount
先验证 DSV 登录:
```powershell
python scripts\rpa\dsv_login_smoke.py
python scripts\rpa\connectors\dsv\dsv_login_smoke.py
```
成功时会看到:
@@ -2105,7 +2105,7 @@ SUCCESS — DSV session ready
库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行:
```powershell
python scripts\rpa\run_inventory_batch_trigger.py <trigger.json>
python scripts\rpa\inventory\run_inventory_batch_trigger.py <trigger.json>
```
该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。
@@ -2294,8 +2294,8 @@ DSV 库存导出默认使用一次性浏览器 Profile。仅在一个对应环
Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1" -Environment test
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" -Environment prod
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment test
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment prod
```
若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。
@@ -2306,8 +2306,8 @@ Windows PowerShell 5.1 读取无 BOM UTF-8 脚本时可能出现中文变乱和
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod
```
默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。
@@ -2320,7 +2320,7 @@ DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Prof
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" `
"C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" `
-Environment test `
-ApiBase "http://<test后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaTest" `
@@ -2330,8 +2330,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
若脚本来自网络或压缩包,先确认路径并按需解除文件阻止:
```powershell
Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
Test-Path "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1"
Unblock-File "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1"
```
`-ApiBase` 必须是 HXOPS 测试业务后端地址。`HXOPS_TOOLS_API_BASE`(例如 `:8890`)是 Tool API,不能填入 Worker 的 `-ApiBase`。如果使用 `http://192.168.100.192:5052`,必须先确认该地址确实是测试后端并可从 Windows Worker 访问:
@@ -2346,7 +2346,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing
连通性确认后,也可以使用仓库原始命令:
```powershell
.\scripts\rpa\start_rpa_worker.ps1 `
.\scripts\rpa\inventory\start_inventory_worker.ps1 `
-Environment test `
-ApiBase "http://测试后端:端口" `
-WorkerRoot "C:\HxopsRpaTest" `
@@ -2356,7 +2356,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing
手工启动 prod:
```powershell
C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 `
C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 `
-Environment prod `
-ApiBase "http://正式后端:端口" `
-WorkerRoot "C:\HxopsRpaProd" `
@@ -2367,7 +2367,7 @@ C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1 `
#### 1.5.11 端到端验证
1. Windows 手工打开 Edge,确认能访问 DSV/Crane。
2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py`。
2. Windows 执行 `python scripts\rpa\connectors\dsv\dsv_login_smoke.py`。
3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。
4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。
5. Windows 按当前方案执行 `start_rpa_worker.ps1`;不要直接运行 `freight_rpa_worker.py`。
@@ -2435,7 +2435,7 @@ $env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "uploa
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log"
\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope:
@@ -3110,7 +3110,7 @@ API 层
| `backend/tests/test_shipping_inventory_routing_engine.py` | 通用路由规则引擎单测 |
| `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 |
| `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 |
| `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) |
| `scripts/rpa/inventory/inventory_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) |
---
@@ -3147,7 +3147,7 @@ API 层
- **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
- **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。
- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger`
- Worker:`scripts/rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger`
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。
- **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。
+81 -74
View File
@@ -9,7 +9,7 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
启动示例:
```powershell
.\scripts\rpa\start_receipt_rpa_worker.ps1 -Environment test -ApiBase "http://<backend>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
.\scripts\rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://<backend>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
收料 Worker 在同一排程内按 Profile 登录一次后串行处理单元;DBS 每个 Warehouse 导出一个文件且不传报表日期,Crane 无论 Profile 登录地址保存为门户首页还是其他页面,都会强制进入 `#/inbound-details-query`,不填写 Warehouse 或查询条件,直接使用页面默认条件生成/等待唯一 Description 对应的 `Inbound Details` 文件。不要把收料 trigger 手工复制到库存目录或反向复制。
@@ -32,19 +32,26 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
## 模块结构
| 文件 | 职责 |
| --------------------------------------------- | ------------------------------------------------------ |
| `freight_rpa_worker.py` | 轮询 trigger、打开浏览器、按 `connector_type` 分发、HTTP 回调(~900 行) |
| `rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 |
| `dsv_driver.py` | DSV 对外入口:`download_dsv360_inventory` |
| `dsv_auth.py` | DSV PingID 分步登录(表单/探测辅助) |
| `dsv_auth_login_flow.py` | DSV 自动登录主编排 `maybe_auto_login_dsv` |
| `dsv_session.py` | DSV portal 壳层检测、首页 ready、entry_url |
| `dsv_navigation.py` | DSV Reports 菜单 → 报表参数页 |
| `dsv_report_export.py` | DSV 填参、View Report、Excel 导出、batch 复用 |
| `dsv_debug.py` | DSV 调试探针与链路日志 |
| `dsv_report_parameters.py` | SSRS 参数控件填充(已有) |
| `crane_session.py` / `crane_report_export.py` | Crane 登录与异步导出 |
| 目录 / 文件 | 职责 |
| ----------------------------------- | ------------------------------------------------------ |
| `common/` | **跨域通用**(与流程、连接器无关) |
| `common/rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 |
| `common/download_artifact_fallback.py` | 浏览器已落盘但 Playwright 未返回 Download 时的下载适配器 |
| `common/rpa_heartbeat.py` | 向后端上报心跳 + 共享目录哨兵(原 `freight_rpa_heartbeat.py`) |
| `common/new_rpa_worker_secret.ps1` | 生成当前用户可解密的 DPAPI Secret 文件 |
| `connectors/` | **登录网站 / 报表系统自动化**(库存与收料共用) |
| `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` |
| `inventory/` | **库存(发货通知)RPA 流程编排** |
| `inventory/inventory_rpa_worker.py` | 库存 Worker:轮询 trigger、按 `connector_type` 分发、HTTP 回调(原 `freight_rpa_worker.py`) |
| `inventory/run_inventory_batch_trigger.py` | 手工执行一条数据库生成的 inventory batch trigger |
| `inventory/start_inventory_worker.ps1` | 启动库存 Worker 的 PowerShell 启动脚本(原 `start_rpa_worker.ps1`) |
| `inventory/register_inventory_worker_tasks.ps1` | 注册 test/prod 库存 Worker 后台计划任务(headless + hidden) |
| `receipt/` | **收料 RPA 流程编排** |
| `receipt/receipt_rpa_worker.py` | 独立收料 Worker:仅消费 receipt trigger、专用目录与回调(原 `freight_receipt_rpa_worker.py`) |
| `receipt/receipt_crane_export.py` | Crane 收料报表导出适配器(强制 Inbound Details) |
| `receipt/receipt_dbs_export.py` | DBS 收料报表导出适配器(按 Warehouse) |
| `receipt/start_receipt_worker.ps1` | 启动收料 Worker 的 PowerShell 启动脚本(原 `start_receipt_rpa_worker.ps1`) |
@@ -243,11 +250,11 @@ Get-ChildItem C:\HxopsRpaProd\data
验证关键文件:
```powershell
Test-Path C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py
Test-Path C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1
Test-Path C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1
Test-Path C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1
Test-Path C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py
Test-Path C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1
Test-Path C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1
Test-Path C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1
```
每一行都应返回 `True`。不要复制 `.env*`、旧 trigger、旧 `processed/failed`、旧浏览器 profile 和真实密钥文件。
@@ -259,10 +266,10 @@ Windows PowerShell 5.1 如仍已经报中文变乱,请在仓库根目录用 Po
```powershell
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
foreach ($path in @(
"C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1",
"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1",
"C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1",
"C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1"
"C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1",
"C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1",
"C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1",
"C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1"
)) {
$text = [System.IO.File]::ReadAllText($path, [System.Text.UTF8Encoding]::new($false))
[System.IO.File]::WriteAllText($path, $text, $utf8Bom)
@@ -328,7 +335,7 @@ Secret 必须用最终运行任务的同一 Windows 账号创建。
powershell.exe `
-NoProfile `
-ExecutionPolicy Bypass `
-File "C:\HxopsTest\scripts\rpa\new_rpa_worker_secret.ps1" `
-File "C:\HxopsTest\scripts\rpa\common\new_rpa_worker_secret.ps1" `
-Environment test
```
@@ -338,15 +345,15 @@ powershell.exe `
powershell.exe `
-NoProfile `
-ExecutionPolicy Bypass `
-File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1" `
-File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" `
-Environment prod
```
如果仍然提示文件被阻止,先解除从网络或压缩包复制来的文件标记,再重试:
```powershell
Unblock-File "C:\HxopsRpaTest\scripts\rpa\new_rpa_worker_secret.ps1"
Unblock-File "C:\HxopsRpaProd\scripts\rpa\new_rpa_worker_secret.ps1"
Unblock-File "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1"
Unblock-File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1"
```
也可以只对当前 PowerShell 窗口临时放行:
@@ -358,7 +365,7 @@ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
然后再执行:
```powershell
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test
```
不要执行 `Set-ExecutionPolicy Unrestricted` 或 `Set-ExecutionPolicy RemoteSigned -Scope LocalMachine` 等永久放宽系统策略的命令。后台任务自身已使用 `-ExecutionPolicy Bypass`,不需要修改系统策略。
@@ -367,7 +374,7 @@ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test
```
按提示输入两项:
@@ -381,7 +388,7 @@ DSV/Crane 登录地址、账号和密码不在 Windows 部署时输入:它们
```powershell
cd C:\HxopsRpaProd
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod
```
这次必须输入 prod 的 Tool API Key 和 RPA Credential Key,不要复制 test 值。DSV/Crane 凭据仍在 HXOPS prod RPA Profile 中配置。
@@ -540,7 +547,7 @@ docker compose --env-file .env.prod exec -T hxops-backend sh -lc 'ls -ld /mnt/hx
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" `
"C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" `
-Environment test `
-ApiBase "http://192.168.100.192:8890" `
-WorkerRoot "C:\HxopsRpaTest" `
@@ -550,13 +557,13 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
先确认脚本确实已复制到 Worker 根目录:
```powershell
Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
Test-Path "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1"
```
若脚本来自网络或压缩包且仍被标记为阻止,可只解除该文件的阻止标记:
```powershell
Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
Unblock-File "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1"
```
`-ApiBase` 必须填 Worker 实际可达的 HXOPS API 入口,判据是 `{base}/api/shipping-notice/rpa/heartbeat` 能访问到后端。Docker Compose 部署下后端容器内部监听 `5000`(`backend/deploy/gunicorn_config.py` 绑定 `0.0.0.0:5000`),而 `docker-compose.yml` 把宿主 `5052` 映射到容器内一个无监听端口,因此 `http://<host>:5052` 直连不可用;前端 nginx 网关(宿主 `8890`)把 `/api/` 反代到 `hxops-backend:5000`(见 `frontend/nginx.conf`),所以 Worker 应填网关地址,如 `http://192.168.100.192:8890`。该地址与 `HXOPS_TOOLS_API_BASE` 指向同一对外网关(都经 `/api/` 反代),实际以“`{base}/api/...` 可达”为准,不必拘泥于 Tool API / 业务后端的命名区分。启动前先验证网关端口连通:
@@ -571,7 +578,7 @@ Test-NetConnection 192.168.100.192 -Port 8890
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\start_rpa_worker.ps1 `
.\scripts\rpa\inventory\start_inventory_worker.ps1 `
-Environment test `
-ApiBase "http://<test后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaTest" `
@@ -582,7 +589,7 @@ cd C:\HxopsRpaTest
```powershell
cd C:\HxopsRpaProd
.\scripts\rpa\start_rpa_worker.ps1 `
.\scripts\rpa\inventory\start_inventory_worker.ps1 `
-Environment prod `
-ApiBase "http://<prod后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaProd" `
@@ -636,12 +643,12 @@ $Principal = New-ScheduledTaskPrincipal `
$TestAction = New-ScheduledTaskAction `
-Execute $PowerShellExe `
-Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1`" -Environment test -ApiBase `"$TestApiBase`" -WorkerRoot `"C:\HxopsRpaTest`" -SecretFile `"C:\HxopsRpaSecrets\test.xml`" -PythonExe `"$PythonExe`"" `
-Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1`" -Environment test -ApiBase `"$TestApiBase`" -WorkerRoot `"C:\HxopsRpaTest`" -SecretFile `"C:\HxopsRpaSecrets\test.xml`" -PythonExe `"$PythonExe`"" `
-WorkingDirectory "C:\HxopsRpaTest"
$ProdAction = New-ScheduledTaskAction `
-Execute $PowerShellExe `
-Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1`" -Environment prod -ApiBase `"$ProdApiBase`" -WorkerRoot `"C:\HxopsRpaProd`" -SecretFile `"C:\HxopsRpaSecrets\prod.xml`" -PythonExe `"$PythonExe`"" `
-Argument "-NoProfile -ExecutionPolicy Bypass -File `"C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1`" -Environment prod -ApiBase `"$ProdApiBase`" -WorkerRoot `"C:\HxopsRpaProd`" -SecretFile `"C:\HxopsRpaSecrets\prod.xml`" -PythonExe `"$PythonExe`"" `
-WorkingDirectory "C:\HxopsRpaProd"
$Trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
@@ -772,16 +779,16 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
从待部署的已审核仓库版本复制整个 `scripts\rpa` 目录到 test/prod 的 `scripts\rpa`,保证 Worker、driver、session、heartbeat、调试工具和公共模块来自同一版本。其中至少包含:
```text
scripts\rpa\freight_rpa_worker.py
scripts\rpa\rpa_common.py
scripts\rpa\freight_rpa_heartbeat.py
scripts\rpa\dsv_driver.py
scripts\rpa\dsv_login_smoke.py
scripts\rpa\dsv_report_parameters.py
scripts\rpa\run_inventory_batch_trigger.py
scripts\rpa\crane_login_smoke.py
scripts\rpa\new_rpa_worker_secret.ps1
scripts\rpa\start_rpa_worker.ps1
scripts\rpa\inventory\inventory_rpa_worker.py
scripts\rpa\common\rpa_common.py
scripts\rpa\common\rpa_heartbeat.py
scripts\rpa\connectors\dsv\dsv_driver.py
scripts\rpa\connectors\dsv\dsv_login_smoke.py
scripts\rpa\connectors\dsv\dsv_report_parameters.py
scripts\rpa\inventory\run_inventory_batch_trigger.py
scripts\rpa\connectors\crane\crane_login_smoke.py
scripts\rpa\common\new_rpa_worker_secret.ps1
scripts\rpa\inventory\start_inventory_worker.ps1
```
不得复制 `.env*`、密码文件、`backend\data` 旧运行数据、旧浏览器 profile、旧 trigger 以及 `processed` / `failed` 文件。
@@ -863,14 +870,14 @@ $env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码"
先执行登录烟测:
```powershell
python scripts\rpa\dsv_login_smoke.py
python scripts\rpa\crane_login_smoke.py
python scripts\rpa\connectors\dsv\dsv_login_smoke.py
python scripts\rpa\connectors\crane\crane_login_smoke.py
```
DSV 成功时会输出 `SUCCESS — DSV session ready`。如需人工联调已由平台生成的 trigger,执行:
```powershell
python scripts\rpa\run_inventory_batch_trigger.py <trigger.json>
python scripts\rpa\inventory\run_inventory_batch_trigger.py <trigger.json>
```
该入口不从 YAML 或本地文件读取账号密码;Profile 密文凭据和页面操作由平台 trigger 提供。
@@ -1027,7 +1034,7 @@ services:
### 1.10 端到端验收
1. Windows 手工打开 Edge,确认能访问 DSV/Crane。
2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py` 和必要的 Crane smoke。
2. Windows 执行 `python scripts\rpa\connectors\dsv\dsv_login_smoke.py` 和必要的 Crane smoke。
3. 在管理端创建库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。
4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认对应文件可见,然后删除测试文件。
5. Windows 按“步骤 10”使用 `start_rpa_worker.ps1` 启动对应环境 Worker。
@@ -1100,7 +1107,7 @@ $env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "uploa
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log"
\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "http://<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "http://<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
若只验证 trigger 扫描、文件流转与回调而不访问真实货代网站,可把 `SHIPPING_NOTICE_RPA_WORKER_MOCK` 设为 `true`。真实库存导出保持 `false`,并使用 HXOPS RPA Profile 随 trigger 下发的加密凭据。
@@ -1213,7 +1220,7 @@ docker compose --env-file .env.test up -d --force-recreate hxops-backend
```powershell
cd C:\HxopsRpaTest
\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "http://<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "http://<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
应同时验证以下四项后,再在管理端对**停用的库存站点**发起“测试导出”:
@@ -1257,7 +1264,7 @@ docker compose --env-file .env.test stop hxops-kb-worker hxops-backend
```powershell
$TaskName = "HXOPS Inventory RPA Worker TEST"
$WorkerRoot = "C:\HxopsRpaTest"
$Launcher = "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
$Launcher = "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1"
$SecretFile = "C:\HxopsRpaSecrets\test.xml"
$ApiBase = "http://<测试后端地址>:<端口>"
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
@@ -1297,7 +1304,7 @@ Register-ScheduledTask `
```powershell
$TaskName = "HXOPS Inventory RPA Worker PROD"
$WorkerRoot = "C:\HxopsRpaProd"
$Launcher = "C:\HxopsRpaProd\scripts\rpa\start_rpa_worker.ps1"
$Launcher = "C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1"
$SecretFile = "C:\HxopsRpaSecrets\prod.xml"
$ApiBase = "http://<正式后端地址>:<端口>"
```
@@ -1308,8 +1315,8 @@ test 和 prod 可在同一台主机、同一个交互式用户会话中并行,
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod
```
Secret 文件默认位于 `C:\HxopsRpaSecrets\test.xml` 和 `prod.xml`,使用当前 Windows 用户 DPAPI 保护;不得复制到仓库、共享目录或其他账号。
@@ -1356,15 +1363,15 @@ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
#### 2.3.1 headless 后台模式(无可见 Edge,完全后台)
> 适用:希望彻底摆脱「可见 Edge + 交互式桌面」,让 Worker 无控制台、无浏览器窗口地后台常驻。
> 交付脚本:`scripts/rpa/register_rpa_background_tasks.ps1`(test/prod 双任务,headless + 隐藏控制台,仍为 RPA 账号的 `AtLogOn + Interactive` 任务)。
> 交付脚本:`scripts/rpa/inventory/register_inventory_worker_tasks.ps1`(test/prod 双任务,headless + 隐藏控制台,仍为 RPA 账号的 `AtLogOn + Interactive` 任务)。
**切换前必须先完成 headless 冒烟预检(风险最高,不要跳过):**
```powershell
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "true"
# 在 RPA 主机验证真实登录/导出可通:
python scripts\rpa\dsv_login_smoke.py
python scripts\rpa\crane_login_smoke.py
python scripts\rpa\connectors\dsv\dsv_login_smoke.py
python scripts\rpa\connectors\crane\crane_login_smoke.py
# 若触及上传,再验证一次 headless 下的上传流程
```
@@ -1374,16 +1381,16 @@ python scripts\rpa\crane_login_smoke.py
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\register_rpa_background_tasks.ps1 # 注册 test/prod 两个任务
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start # 立即启动(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Status # 查看状态(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Stop # 停止(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # 注销(默认 all)
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 # 注册 test/prod 两个任务
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start # 立即启动(默认 all)
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Status # 查看状态(默认 all)
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Stop # 停止(默认 all)
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # 注销(默认 all)
# 区分环境:用 -Scope test|prod|all(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test -Status # 只看 test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope prod -Start # 只启动 prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test -Unregister # 只注销 test
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test -Status # 只看 test
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope prod -Start # 只启动 prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test -Unregister # 只注销 test
```
- **`-Scope test|prod|all`**:`Start/Stop/Status/Unregister`(以及默认注册)都可只作用于单个环境;不带 `-Scope` 时默认操作 test 和 prod 两个任务。两个任务是独立命名的(`HXOPS Inventory RPA Worker TEST` / `...PROD`),也可用原生 `Get-ScheduledTask -TaskName <任务名>` 单独查询。
@@ -1423,12 +1430,12 @@ cd C:\HxopsRpaTest
```powershell
cd C:\HxopsRpaProd
.\scripts\rpa\new_rpa_worker_secret.ps1 -Environment prod
.\scripts\rpa\start_rpa_worker.ps1 -Environment prod -ApiBase "http://<正式后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaProd" -SecretFile "C:\HxopsRpaSecrets\prod.xml"
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod
.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment prod -ApiBase "http://<正式后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaProd" -SecretFile "C:\HxopsRpaSecrets\prod.xml"
# 关闭并重新打开 PowerShell 后执行
cd C:\HxopsRpaProd
\.\scripts\rpa\start_rpa_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
```
@@ -1506,7 +1513,7 @@ $env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与 backend 一致>"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true"
# 四个 SHIPPING_NOTICE_RPA_SHARED_* 目录与 backend 相同
python scripts/rpa/freight_rpa_worker.py
python scripts/rpa/inventory/inventory_rpa_worker.py
```
1. 在 Chat 中走 `ensure_inventory` / `upload_to_freight`,worker 会自动回调 `/api/shipping-notice/rpa/*`。
@@ -1542,7 +1549,7 @@ $env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "<DSV密码>"
$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "<Crane账号>"
$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "<Crane密码>"
python scripts/rpa/freight_rpa_worker.py
python scripts/rpa/inventory/inventory_rpa_worker.py
```
说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 现在仅作为“运行时 profile 根目录”。每次库存导出都会在该目录下自动创建一个全新的临时子目录,并在任务结束后清理,不会复用任何已有 profile。
@@ -1568,7 +1575,7 @@ Crane 登录烟测(仅验证 User Name / Password / Sign in):
```powershell
$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "<Crane账号>"
$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "<Crane密码>"
backend\venv\Scripts\python.exe scripts\rpa\crane_login_smoke.py
backend\venv\Scripts\python.exe scripts\rpa\connectors\crane\crane_login_smoke.py
```
若页面出现 MFA、验证码或 SSO 二次确认,worker 会失败并回调错误,需要人工处理后重试。
@@ -8,6 +8,21 @@ scripts/rpa/rpa_common.py
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)
import json
import os
import sys
@@ -203,7 +218,7 @@ def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value:
import importlib.util
from pathlib import Path
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
module_path = _RPA_ROOT / "connectors" / "dsv" / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -1,5 +1,5 @@
"""
scripts/rpa/freight_rpa_heartbeat.py
scripts/rpa/common/rpa_heartbeat.py
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
依赖:rpa_common.env、urllib、socket。
@@ -8,6 +8,21 @@ scripts/rpa/freight_rpa_heartbeat.py
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)
import json
import os
import socket
@@ -21,9 +21,9 @@ from pathlib import Path
def _load_worker():
repo_root = Path(__file__).resolve().parents[2]
module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_smoke", module_path)
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
module_path = repo_root / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_crane_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
File renamed without changes.
@@ -8,6 +8,21 @@ scripts/rpa/dsv_auth.py
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)
import sys
import time
from typing import Any, Callable
@@ -8,6 +8,21 @@ scripts/rpa/dsv_auth_login_flow.py
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)
import sys
import time
from typing import Any, Callable
@@ -8,6 +8,21 @@ scripts/rpa/dsv_debug.py
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)
import json
import sys
import time
@@ -163,7 +178,7 @@ def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None:
# #region debug-point A:reports-debug-server
def _debug_server_config() -> tuple[str, str]:
"""读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。"""
env_path = Path(__file__).resolve().parents[2] / ".dbg" / "reports-menu-stuck.env"
env_path = _RPA_ROOT.parents[1] / ".dbg" / "reports-menu-stuck.env"
url = "http://127.0.0.1:7778/event"
session_id = "reports-menu-stuck"
try:
@@ -8,6 +8,21 @@ scripts/rpa/dsv_driver.py
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
from dsv_report_export import (
@@ -21,9 +21,9 @@ from pathlib import Path
def _load_worker():
repo_root = Path(__file__).resolve().parents[2]
module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke", module_path)
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
module_path = repo_root / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
@@ -8,6 +8,21 @@ scripts/rpa/dsv_navigation.py
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)
import json
import sys
import time
@@ -8,6 +8,21 @@ scripts/rpa/dsv_report_export.py
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)
import importlib.util
import sys
import time
@@ -8,6 +8,21 @@ scripts/rpa/dsv_session.py
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)
import sys
import time
from typing import Any, Callable
@@ -5,7 +5,7 @@ Freight RPA worker (PoC).
DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。
Usage:
python scripts/rpa/freight_rpa_worker.py
python scripts/rpa/inventory/inventory_rpa_worker.py
Required env (same as backend):
HXOPS_API_BASE e.g. http://127.0.0.1:5052
@@ -53,9 +53,19 @@ from typing import Any, Callable, TextIO
from cryptography.fernet import Fernet, InvalidToken
import sys as _sys
_RPA_DIR = Path(__file__).resolve().parent
if str(_RPA_DIR) not in _sys.path:
_sys.path.insert(0, str(_RPA_DIR))
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 ( # noqa: E402
browser_timeout_ms as _browser_timeout_ms,
@@ -70,7 +80,7 @@ import dsv_navigation # noqa: E402
import dsv_report_export # noqa: E402
from dsv_report_export import NoInventoryDataError # noqa: E402
import dsv_session # noqa: E402
import freight_rpa_heartbeat # noqa: E402
import rpa_heartbeat # noqa: E402
# 测试与 smoke 向后兼容 re-export
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
@@ -255,7 +265,7 @@ def _backend_dir() -> Path:
Returns:
Path: backend 目录的绝对路径。
"""
return Path(__file__).resolve().parents[2] / "backend"
return _RPA_ROOT.parents[1] / "backend"
def _resolve_backend_relative_path(value: str, *, default: Path | None = None) -> Path:
@@ -727,7 +737,7 @@ def _load_crane_session_module() -> Any:
import importlib.util
from pathlib import Path
module_path = Path(__file__).resolve().parent / "crane_session.py"
module_path = _RPA_ROOT / "connectors" / "crane" / "crane_session.py"
spec = importlib.util.spec_from_file_location("crane_session_runtime", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -806,7 +816,7 @@ def _load_crane_report_export_module() -> Any:
import importlib.util
from pathlib import Path
module_path = Path(__file__).resolve().parent / "crane_report_export.py"
module_path = _RPA_ROOT / "connectors" / "crane" / "crane_report_export.py"
spec = importlib.util.spec_from_file_location("crane_report_export_runtime", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
@@ -2107,13 +2117,13 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
for path in sorted(trigger_dir.glob("*.json")):
if not path.is_file():
continue
freight_rpa_heartbeat.set_worker_runtime_status("busy")
rpa_heartbeat.set_worker_runtime_status("busy")
try:
handler(path, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
finally:
freight_rpa_heartbeat.set_worker_runtime_status("idle")
rpa_heartbeat.set_worker_runtime_status("idle")
def main() -> None:
@@ -2145,7 +2155,7 @@ def main() -> None:
print(f" queue={upload_queue_dir}")
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
freight_rpa_heartbeat.maybe_send_heartbeat(
rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=0.0,
@@ -2153,7 +2163,7 @@ def main() -> None:
)
# 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环,
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
freight_rpa_heartbeat.start_heartbeat_loop(
rpa_heartbeat.start_heartbeat_loop(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
interval_seconds=heartbeat_seconds,
@@ -9,7 +9,7 @@
Differences vs the standard "visible" scheduled task (README step 11 / 2.3):
- powershell.exe gets -WindowStyle Hidden -> no console window to close by accident.
- start_rpa_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
- start_inventory_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
Shape constraints (same as README 2.3):
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
@@ -26,13 +26,13 @@
All actions can target one environment or both via -Scope test|prod|all (default all).
Usage (run in the RPA account's PowerShell):
.\scripts\rpa\register_rpa_background_tasks.ps1 # register test+prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test # register only test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start # start both now
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Status -Scope test # only test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # unregister both
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 # register test+prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test # register only test
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start # start both now
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Status -Scope test # only test
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # unregister both
#>
[CmdletBinding()]
param(
@@ -69,7 +69,7 @@ function Get-TasksForScope {
function Assert-Launcher {
# Validate the launcher and DPAPI Secret file required for one environment.
param([string]$Root, [string]$Environment)
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
$launcher = Join-Path $Root "scripts\rpa\inventory\start_inventory_worker.ps1"
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
throw "Launcher not found: $launcher"
}
@@ -86,7 +86,7 @@ function New-TaskDefinition {
[string]$ApiBase,
[string]$EnvName
)
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
$launcher = Join-Path $Root "scripts\rpa\inventory\start_inventory_worker.ps1"
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
# Key differences vs the visible scheduled task:
@@ -9,6 +9,9 @@ from pathlib import Path
def _repo_root() -> Path:
"""Return the HXOPS repository root for relative operational directories."""
for _p in Path(__file__).resolve().parents:
if (_p / "backend").is_dir() and (_p / "frontend").is_dir() and (_p / "scripts").is_dir():
return _p
return Path(__file__).resolve().parents[2]
@@ -28,8 +31,8 @@ def _load_dotenv_dev() -> None:
def _load_worker():
"""Load the polling worker module so manual runs share the production trigger contract."""
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_runner", module_path)
module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_batch_runner", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
@@ -34,7 +34,7 @@ $ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) {
throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。"
}
$workerScript = Join-Path $WorkerRoot "scripts\rpa\freight_rpa_worker.py"
$workerScript = Join-Path $WorkerRoot "scripts\rpa\inventory\inventory_rpa_worker.py"
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) {
throw "Worker 不存在:$workerScript"
}
@@ -2,6 +2,21 @@
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
@@ -2,6 +2,21 @@
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
@@ -16,18 +16,29 @@ from typing import Any
from cryptography.fernet import Fernet, InvalidToken
_RPA_DIR = Path(__file__).resolve().parent
if str(_RPA_DIR) not in __import__('sys').path:
__import__('sys').path.insert(0, str(_RPA_DIR))
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
import freight_receipt_crane_export # noqa: E402
import freight_receipt_dbs_export # noqa: E402
import receipt_crane_export # noqa: E402
import receipt_dbs_export # noqa: E402
def _backend_dir() -> Path:
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
return Path(__file__).resolve().parents[2] / 'backend'
return _RPA_ROOT.parents[1] / 'backend'
def _require_dir(variable: str) -> Path:
@@ -98,7 +109,7 @@ def _open_browser(download_dir: Path):
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('SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR')
profile_root = _require_dir('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR')
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
playwright = sync_playwright().start()
options: dict[str, Any] = {'headless': env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)}
@@ -172,9 +183,9 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
if connector == 'dbs':
if index:
page = context.new_page(); page.set_default_timeout(browser_timeout_ms())
download = freight_receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
download = receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
else:
download = freight_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)
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)
_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:
@@ -202,7 +213,9 @@ def _claim_and_process(path: Path, drop_dir: Path, processed_dir: Path, failed_d
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
processed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(processed_dir / claimed.name)
except Exception:
except (Exception, SystemExit):
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
failed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(failed_dir / claimed.name)
raise
@@ -18,7 +18,7 @@ param(
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" }
$workerScript = Join-Path $WorkerRoot 'scripts\rpa\freight_receipt_rpa_worker.py'
$workerScript = Join-Path $WorkerRoot 'scripts\rpa\receipt\receipt_rpa_worker.py'
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
function ConvertTo-PlainText {
@@ -44,7 +44,8 @@ $processVars = [ordered]@{
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'
SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR = Join-Path $dataRoot 'browser_profile'
# 浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致),不另设 RECEIPT_* 冗余变量。
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $WorkerRoot 'data\shipping_notice\freight_rpa\browser_profile'
}
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try {
+2 -2
View File
@@ -72,7 +72,7 @@ function Stop-StaleHxopsPythonProcesses {
[regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")),
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py"))
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\inventory\inventory_rpa_worker.py"))
)
# 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。
# 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。
@@ -445,7 +445,7 @@ function Start-FreightRpaWorkerWindow {
-Title "freight-rpa-worker" `
-WorkingDirectory $RepoRoot `
-EnvPrefix $envPrefix `
-Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py"
-Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\rpa\inventory\inventory_rpa_worker.py"
}
function Start-FrontendWindow {