Merge branch 'hugo-shipping-notice' into dev
# Conflicts: # backend/app/api/__init__.py # backend/app/jobs/types.py # backend/app/models/__init__.py # backend/app/services/schedule/job_registry.py # docs/features/README.md # docs/funclist.md # docs/tec.md # frontend/src/locales/zh-CN/admin.json
This commit is contained in:
commit
dac31e48bd
691 files changed
+53341
-14863
No files matched your search
+129
-79
@@ -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`) |
|
||||
|
||||
|
||||
|
||||
@@ -70,6 +77,8 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 |
|
||||
| `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` | Profile 凭据 Fernet 主密钥;必须与对应环境后端一致,只能由 Secret 渠道或部署脚本安全注入 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响 |
|
||||
| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS` | 持久 Profile 最长保留小时数,默认 `24`;超时后清空目录并重新登录 |
|
||||
|
||||
|
||||
新部署只使用 `new_rpa_worker_secret.ps1` + `start_rpa_worker.ps1`:Secret 由 DPAPI 保护,环境变量只注入对应 Worker 子进程。
|
||||
@@ -78,10 +87,11 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
|
||||
运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,Profile 凭据主密钥使用
|
||||
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。部署文档和启动脚本只使用上述规范命名。
|
||||
|
||||
DSV 库存导出默认每次使用一次性浏览器 Profile。确认只运行单个对应环境 Worker 后,可在
|
||||
`start_rpa_worker.ps1` 启动命令末尾增加 `-ReuseDsvSession`,使 DSV 专用
|
||||
`dsv360_session` Profile 跨任务保留登录态;Crane 与上传任务仍不复用。不要同时启动两个
|
||||
使用同一 WorkerRoot 的 Worker,浏览器会拒绝并发打开同一持久 Profile。
|
||||
DSV/Crane 库存导出默认复用浏览器 Profile(按 `connector + rpa_profile_code` 隔离目录,
|
||||
默认保留 24 小时)。同一 WorkerRoot 只跑一个 Worker,任务串行消费;会话过期或站点踢登
|
||||
仍回落现有登录流程。上传任务保持一次性 Profile。若需强制每次全新登录,启动时加
|
||||
`-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`
|
||||
仍兼容,但请改用 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`。
|
||||
|
||||
### DSV WMS Upload Tool
|
||||
|
||||
@@ -243,11 +253,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 +269,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 +338,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 +348,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 +368,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 +377,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 +391,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 +550,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 +560,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 +581,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 +592,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 +646,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 +782,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 +873,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 +1037,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 +1110,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 +1223,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 +1267,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 +1307,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 +1318,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 +1366,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,18 +1384,58 @@ 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
|
||||
```
|
||||
|
||||
#### PowerShell 执行策略阻止脚本时
|
||||
|
||||
如果直接执行 `.ps1` 时出现“在此系统上禁止运行脚本”(`PSSecurityException` / `UnauthorizedAccess`),优先使用一次性的 `ExecutionPolicy Bypass`,不要修改计算机或用户的全局执行策略:
|
||||
|
||||
```powershell
|
||||
cd C:\HxopsRpaTest
|
||||
|
||||
# 注册 TEST 计划任务
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
|
||||
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1" `
|
||||
-Scope test `
|
||||
-TestApiBase "http://192.168.100.192:8890" `
|
||||
-TestRoot "C:\HxopsRpaTest" `
|
||||
-SecretFile "C:\HxopsRpaSecrets"
|
||||
|
||||
# 启动或查看 TEST 任务
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
|
||||
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1" `
|
||||
-Scope test -Start
|
||||
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
|
||||
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1" `
|
||||
-Scope test -Status
|
||||
```
|
||||
|
||||
如果脚本是从浏览器、邮件或压缩包复制而来,可能带有 Internet 下载标记;确认路径无误后可解除该文件的阻止状态,再按普通方式执行:
|
||||
|
||||
```powershell
|
||||
Unblock-File -LiteralPath `
|
||||
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1"
|
||||
```
|
||||
|
||||
可用以下命令查看当前执行策略:
|
||||
|
||||
```powershell
|
||||
Get-ExecutionPolicy -List
|
||||
```
|
||||
|
||||
不建议直接设置 `Unrestricted`。如果 `MachinePolicy` 或 `UserPolicy` 已由公司组策略设置,`Bypass` 仍可能被拦截,此时需要管理员调整组策略或按公司运维流程批准执行该脚本。
|
||||
|
||||
- **`-Scope test|prod|all`**:`Start/Stop/Status/Unregister`(以及默认注册)都可只作用于单个环境;不带 `-Scope` 时默认操作 test 和 prod 两个任务。两个任务是独立命名的(`HXOPS Inventory RPA Worker TEST` / `...PROD`),也可用原生 `Get-ScheduledTask -TaskName <任务名>` 单独查询。
|
||||
|
||||
- 与 2.3 可见模式仅两处差异:计划任务给 `powershell.exe` 加 `-WindowStyle Hidden`(无控制台),并给 `start_rpa_worker.ps1` 加 `-Headless`(Playwright headless,无可见 Edge)。其余 `AtLogOn`、`Interactive`、`RestartCount/RestartInterval`、`ExecutionTimeLimit=0`、`MultipleInstances=IgnoreNew` 均与 2.3 一致。
|
||||
@@ -1423,12 +1473,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 +1556,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,10 +1592,10 @@ $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。
|
||||
说明:`SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR` 是浏览器 Profile 根目录。库存导出默认开启会话复用:目录形如 `{connector}__{rpa_profile_code}_session`,跨任务保留登录态,默认 TTL 24 小时(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`);关闭复用或上传任务仍使用 `run_*` 一次性子目录并在结束后清理。同一 WorkerRoot 不要并发启动第二个库存 Worker。
|
||||
|
||||
如果登录框默认识别不稳定,可覆盖登录 selector:
|
||||
|
||||
@@ -1568,7 +1618,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 会失败并回调错误,需要人工处理后重试。
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -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
|
||||
+3
-3
@@ -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.
+87
-16
@@ -2,18 +2,42 @@
|
||||
scripts/rpa/crane_report_export.py
|
||||
|
||||
用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。
|
||||
依赖:Playwright Page;由 freight_rpa_worker._export_crane_inventory_source 委托调用。
|
||||
逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行。
|
||||
依赖:Playwright Page、download_artifact_fallback;由 inventory_rpa_worker._export_crane_inventory_source 委托调用。
|
||||
逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行;
|
||||
expect_download 超时时按下载目录新文件做短窗口兜底(与 DSV 同模块,窗口更短)。
|
||||
"""
|
||||
|
||||
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
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file
|
||||
|
||||
# Schedule Report Description 默认取 UUID 前 12 位十六进制(无连字符)。
|
||||
# 48 bit ≈ 2.8e14 种组合,单租户 RPA 导出场景碰撞可忽略;页面示例多为 6~8 位人工填写。
|
||||
_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT = 12
|
||||
@@ -71,6 +95,8 @@ _CRANE_SCHEDULED_COL_DESCRIPTION = 2
|
||||
_CRANE_SCHEDULED_COL_DOWNLOAD = 3
|
||||
_CRANE_SCHEDULED_REPORT_NAME_DEFAULT = "OnHandDetails.xlsx"
|
||||
_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT = 20
|
||||
# Playwright download 事件偶发丢失时,目录兜底窗口(人工下载约 2s;不必拉到 DSV 的 60s)。
|
||||
_CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS = 15.0
|
||||
_CRANE_SESSION_MODULE: Any | None = None
|
||||
|
||||
|
||||
@@ -930,10 +956,24 @@ def _wait_and_click_scheduled_download(
|
||||
description: str = "",
|
||||
expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT,
|
||||
entry_url: str = "",
|
||||
download_dir: str = "",
|
||||
) -> Any:
|
||||
"""
|
||||
轮询 Scheduled Reports 直至目标行 Download 列由 Submitted 变为 Download 并点击。
|
||||
核心逻辑:每 2s 读一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页。
|
||||
核心逻辑:每 2s 探测一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页;
|
||||
expect_download 超时且已配置 download_dir 时,短窗口扫描目录新文件兜底。
|
||||
|
||||
Args:
|
||||
page: Playwright 页面。
|
||||
env: 环境变量读取函数。
|
||||
browser_timeout_ms: 浏览器操作超时(亦用于 expect_download)。
|
||||
description: Schedule 时写入的 Description,用于定位行。
|
||||
expected_report_name: 期望的 Name 列文件名。
|
||||
entry_url: Crane 入口 URL,用于会话恢复。
|
||||
download_dir: worker 注入的浏览器 downloads_path;空则不做目录兜底。
|
||||
|
||||
Returns:
|
||||
Playwright Download 或 FilesystemDownloadArtifact。
|
||||
"""
|
||||
entry = entry_url or _default_crane_entry_url(None)
|
||||
wait_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000")
|
||||
@@ -950,6 +990,7 @@ def _wait_and_click_scheduled_download(
|
||||
last_list_refresh = time.monotonic()
|
||||
poll_index = 0
|
||||
last_status = "not_found"
|
||||
drop_dir = str(download_dir or "").strip()
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
poll_index += 1
|
||||
@@ -1005,15 +1046,44 @@ def _wait_and_click_scheduled_download(
|
||||
f"description={description!r} status={last_status!r} after~{elapsed}s polls={poll_index}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
with page.expect_download(timeout=click_timeout) as download_info:
|
||||
if not _click_locator(locator, browser_timeout_ms=click_timeout):
|
||||
raise RuntimeError(
|
||||
f"Crane scheduled report Download link click failed for description={description!r}"
|
||||
)
|
||||
print(
|
||||
f"[crane-export] download started name={expected_report_name!r} description={description!r}"
|
||||
)
|
||||
return download_info.value
|
||||
baseline_names: set[str] = set()
|
||||
if drop_dir:
|
||||
try:
|
||||
baseline_names = {path.name for path in Path(drop_dir).iterdir() if path.is_file()}
|
||||
except OSError:
|
||||
baseline_names = set()
|
||||
try:
|
||||
# [STEP] 主路径:Playwright download 事件
|
||||
with page.expect_download(timeout=click_timeout) as download_info:
|
||||
if not _click_locator(locator, browser_timeout_ms=click_timeout):
|
||||
raise RuntimeError(
|
||||
f"Crane scheduled report Download link click failed for description={description!r}"
|
||||
)
|
||||
print(
|
||||
f"[crane-export] download started name={expected_report_name!r} description={description!r}"
|
||||
)
|
||||
return download_info.value
|
||||
except RuntimeError:
|
||||
# 点击失败不走目录兜底,避免空等
|
||||
raise
|
||||
except Exception:
|
||||
# [STEP] 事件丢失/晚到:短窗口扫 downloads_path(与 DSV 同模块)
|
||||
if not drop_dir:
|
||||
raise
|
||||
fallback = _wait_for_new_download_file(
|
||||
download_dir=drop_dir,
|
||||
baseline_names=baseline_names,
|
||||
timeout_seconds=_CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS,
|
||||
)
|
||||
if fallback is None:
|
||||
raise
|
||||
print(
|
||||
"[crane-download-fallback] "
|
||||
f"using downloaded file from directory because Playwright download event timed out: "
|
||||
f"{fallback.suggested_filename}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return fallback
|
||||
|
||||
loop_elapsed_ms = int((time.monotonic() - loop_started) * 1000)
|
||||
remaining = int(deadline - time.monotonic())
|
||||
@@ -1091,11 +1161,12 @@ def export_crane_inventory_report(
|
||||
) -> Any:
|
||||
"""
|
||||
导出 Crane 库存报表。
|
||||
核心逻辑:Run Report(等待结果)→ Schedule Report(填 Description)→ Scheduled Reports 按 Description 下载。
|
||||
核心逻辑:Run Report(等待结果)→ Schedule Report(填 Description)→ Scheduled Reports 按 Description 下载;
|
||||
下载时 expect_download 失败则按 source.__download_dir 短窗口目录兜底。
|
||||
|
||||
Args:
|
||||
page: Playwright 页面。
|
||||
source: rpa_inventory_source 配置。
|
||||
source: rpa_inventory_source 配置(可含 worker 注入的 __download_dir)。
|
||||
env: 环境变量读取函数。
|
||||
browser_timeout_ms: 浏览器操作超时。
|
||||
select_or_fill: worker 提供的下拉/输入填充函数。
|
||||
@@ -1103,7 +1174,7 @@ def export_crane_inventory_report(
|
||||
trigger: inventory_export / batch trigger,用于生成唯一 Description。
|
||||
|
||||
Returns:
|
||||
Playwright Download 对象。
|
||||
Playwright Download 或 FilesystemDownloadArtifact。
|
||||
"""
|
||||
download_mode = _resolve_download_mode(source, env=env)
|
||||
entry_url = _default_crane_entry_url(source)
|
||||
@@ -1150,7 +1221,6 @@ def export_crane_inventory_report(
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
entry_url=entry_url,
|
||||
)
|
||||
wait_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000")
|
||||
return _wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=env,
|
||||
@@ -1158,6 +1228,7 @@ def export_crane_inventory_report(
|
||||
description=schedule_description,
|
||||
expected_report_name=scheduled_report_name,
|
||||
entry_url=entry_url,
|
||||
download_dir=str(source.get("__download_dir") or ""),
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
+15
@@ -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 (
|
||||
File renamed without changes.
@@ -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
|
||||
File renamed without changes.
@@ -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
|
||||
+410
-47
@@ -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
|
||||
@@ -19,7 +19,9 @@ Optional:
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
|
||||
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS=24
|
||||
# legacy alias: SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
|
||||
@@ -53,9 +55,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 +82,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 +267,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:
|
||||
@@ -448,18 +460,29 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
|
||||
|
||||
def _close_batch_browser_resources(context: Any, playwright: Any, runtime_profile_dir: Path | None) -> None:
|
||||
"""在正常完成或 Ctrl+C 中断后依序释放批量 RPA 浏览器资源。"""
|
||||
# [DEBUG-TIMING] 逐阶段计时:浏览器关闭 / playwright 停止 / profile 清理各自耗时,
|
||||
# 用于定位「导出完成 → 回调」之间的静默段(export done 后到 _post_callback 前的耗时)。
|
||||
close_started_at = time.monotonic()
|
||||
try:
|
||||
if context is not None:
|
||||
context.close()
|
||||
except BaseException as exc:
|
||||
print(f"[browser] context close interrupted: {exc}", file=sys.stderr)
|
||||
else:
|
||||
print(f"[browser-cleanup] context.close elapsedMs={int((time.monotonic() - close_started_at) * 1000)}")
|
||||
stop_started_at = time.monotonic()
|
||||
try:
|
||||
if playwright is not None:
|
||||
playwright.stop()
|
||||
except BaseException as exc:
|
||||
print(f"[browser] playwright stop interrupted: {exc}", file=sys.stderr)
|
||||
else:
|
||||
print(f"[browser-cleanup] playwright.stop elapsedMs={int((time.monotonic() - stop_started_at) * 1000)}")
|
||||
cleanup_started_at = time.monotonic()
|
||||
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
print(f"[browser-cleanup] profile rmtree elapsedMs={int((time.monotonic() - cleanup_started_at) * 1000)} dir={runtime_profile_dir.name!r}")
|
||||
print(f"[browser-cleanup] total_cleanup elapsedMs={int((time.monotonic() - close_started_at) * 1000)}")
|
||||
|
||||
|
||||
_INVENTORY_V2_REQUIRED_FIELDS = (
|
||||
@@ -727,7 +750,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 +829,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)
|
||||
@@ -831,22 +854,209 @@ def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: d
|
||||
)
|
||||
|
||||
|
||||
_SESSION_META_FILENAME = ".hxops_rpa_session_meta.json"
|
||||
|
||||
|
||||
def _session_reuse_enabled() -> bool:
|
||||
"""
|
||||
返回库存导出是否复用持久浏览器 Profile。
|
||||
|
||||
核心逻辑:优先读 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`;未设置时回落旧名
|
||||
`SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`;两者皆未设置时默认开启,避免同账号
|
||||
重复 RPA 每次重新登录。上传任务仍由调用方传 `reuse_session=False` 强制一次性目录。
|
||||
"""
|
||||
raw = os.getenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE")
|
||||
if raw is None:
|
||||
legacy = os.getenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE")
|
||||
if legacy is not None:
|
||||
return str(legacy).strip().strip("\"'").lower() == "true"
|
||||
return True
|
||||
return str(raw).strip().strip("\"'").lower() == "true"
|
||||
|
||||
|
||||
def _dsv_session_reuse_enabled() -> bool:
|
||||
"""返回是否显式允许 DSV 库存导出复用受控浏览器会话。"""
|
||||
return _env("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "false").lower() == "true"
|
||||
"""兼容旧测试/调用名;语义同 `_session_reuse_enabled`。"""
|
||||
return _session_reuse_enabled()
|
||||
|
||||
|
||||
def _session_reuse_ttl_seconds() -> int:
|
||||
"""
|
||||
返回持久 Profile 最长保留秒数。
|
||||
|
||||
核心逻辑:读取 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS`,默认 24 小时;
|
||||
下限 1 小时,避免误配成 0 导致每次都重建。
|
||||
"""
|
||||
raw = _env("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24") or "24"
|
||||
try:
|
||||
hours = int(raw)
|
||||
except ValueError:
|
||||
hours = 24
|
||||
return max(1, hours) * 3600
|
||||
|
||||
|
||||
def _sanitize_profile_dir_segment(value: str) -> str:
|
||||
"""
|
||||
将 connector / RPA Profile 编码成可作目录名的安全片段。
|
||||
|
||||
Args:
|
||||
value: 原始 connector_type 或 rpa_profile_code。
|
||||
|
||||
Returns:
|
||||
str: 仅保留字母数字与 `-_`,空值回落 `default`,最长 96 字符。
|
||||
"""
|
||||
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:
|
||||
"""
|
||||
返回按连接器与 RPA 账号隔离的持久 Profile 目录。
|
||||
|
||||
核心逻辑:目录形如 `{connector}__{profile_code}_session`,不同货代账号绝不共用;
|
||||
若仍存在历史 `dsv360_session` 且目标目录尚未创建、profile 为 default,则沿用旧目录
|
||||
以保留已有登录态,待 TTL 过期后自然重建到新命名。
|
||||
|
||||
Args:
|
||||
connector_type: Worker 连接器名(如 dsv360 / crane_footprint)。
|
||||
profile_code: 平台 RPA Profile 编码;缺省时用 default。
|
||||
|
||||
Returns:
|
||||
Path: 持久 profile 目录路径(未必已存在)。
|
||||
"""
|
||||
connector = _sanitize_profile_dir_segment(connector_type or "unknown")
|
||||
code = _sanitize_profile_dir_segment(profile_code)
|
||||
target = _browser_profile_root() / f"{connector}__{code}_session"
|
||||
legacy = _browser_profile_root() / "dsv360_session"
|
||||
if (
|
||||
connector == "dsv360"
|
||||
and code == "default"
|
||||
and not target.exists()
|
||||
and legacy.exists()
|
||||
):
|
||||
return legacy
|
||||
return target
|
||||
|
||||
|
||||
def _dsv_session_profile_dir() -> Path:
|
||||
"""返回 DSV 专用持久 profile;该目录不得与其他货代任务共用。"""
|
||||
return _browser_profile_root() / "dsv360_session"
|
||||
"""兼容旧调用:返回 default DSV 持久 profile 路径。"""
|
||||
return _session_profile_dir("dsv360", "default")
|
||||
|
||||
|
||||
def _read_session_meta(profile_dir: Path) -> dict[str, Any]:
|
||||
"""读取持久 Profile 元数据;损坏或缺失时返回空 dict。"""
|
||||
meta_path = profile_dir / _SESSION_META_FILENAME
|
||||
if not meta_path.is_file():
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def _write_session_meta(
|
||||
profile_dir: Path,
|
||||
*,
|
||||
connector_type: str,
|
||||
profile_code: str,
|
||||
created_at_unix: float | None = None,
|
||||
) -> None:
|
||||
"""写入或刷新持久 Profile 元数据(创建时间保留,刷新 last_used)。"""
|
||||
now = time.time()
|
||||
created = float(created_at_unix) if created_at_unix is not None else now
|
||||
payload = {
|
||||
"created_at_unix": created,
|
||||
"created_at": datetime.fromtimestamp(created, tz=UTC).isoformat(),
|
||||
"last_used_at_unix": now,
|
||||
"last_used_at": datetime.fromtimestamp(now, tz=UTC).isoformat(),
|
||||
"connector_type": connector_type,
|
||||
"profile_code": profile_code,
|
||||
"ttl_hours": max(1, _session_reuse_ttl_seconds() // 3600),
|
||||
}
|
||||
meta_path = profile_dir / _SESSION_META_FILENAME
|
||||
meta_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def _prepare_reusable_session_profile(
|
||||
profile_dir: Path,
|
||||
*,
|
||||
connector_type: str,
|
||||
profile_code: str,
|
||||
) -> Path:
|
||||
"""
|
||||
准备可复用 Profile 目录:超 TTL 则清空重建,否则刷新 last_used。
|
||||
|
||||
核心逻辑:以 meta 的 `created_at_unix` 起算;无 meta 时用目录 mtime。超过
|
||||
`SESSION_REUSE_TTL_HOURS`(默认 24h)则整目录删除后重建,迫使重新登录。
|
||||
|
||||
Args:
|
||||
profile_dir: 目标持久目录。
|
||||
connector_type: 连接器名,写入 meta。
|
||||
profile_code: RPA Profile 编码,写入 meta。
|
||||
|
||||
Returns:
|
||||
Path: 已确保存在且未过期的 profile 目录。
|
||||
"""
|
||||
ttl_seconds = _session_reuse_ttl_seconds()
|
||||
now = time.time()
|
||||
if profile_dir.exists():
|
||||
meta = _read_session_meta(profile_dir)
|
||||
created_at = meta.get("created_at_unix")
|
||||
try:
|
||||
created_ts = float(created_at) if created_at is not None else profile_dir.stat().st_mtime
|
||||
except (TypeError, ValueError, OSError):
|
||||
created_ts = now
|
||||
age_seconds = max(0.0, now - created_ts)
|
||||
if age_seconds >= ttl_seconds:
|
||||
print(
|
||||
"[browser] session_reuse expired "
|
||||
f"ageHours={age_seconds / 3600:.1f} ttlHours={ttl_seconds / 3600:.0f} "
|
||||
f"dir={profile_dir.name!r}; recreating"
|
||||
)
|
||||
shutil.rmtree(profile_dir, ignore_errors=True)
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=now,
|
||||
)
|
||||
return profile_dir
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=created_ts,
|
||||
)
|
||||
return profile_dir
|
||||
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_session_meta(
|
||||
profile_dir,
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code,
|
||||
created_at_unix=now,
|
||||
)
|
||||
return profile_dir
|
||||
|
||||
|
||||
def _is_reusable_session_profile_dir(profile_dir: Path) -> bool:
|
||||
"""判断目录是否为应跨任务保留的持久 Profile(非 run_* 临时目录)。"""
|
||||
name = profile_dir.name
|
||||
if name.startswith("run_"):
|
||||
return False
|
||||
if name.endswith("_session"):
|
||||
return True
|
||||
return (profile_dir / _SESSION_META_FILENAME).is_file()
|
||||
|
||||
|
||||
def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
|
||||
"""
|
||||
判断关闭浏览器后是否可删除本次 profile。
|
||||
|
||||
核心逻辑:仅显式开启的 DSV 固定会话目录需要跨任务保留;其余目录都是
|
||||
`_open_browser` 创建的一次性运行目录,应由调用方清理。
|
||||
核心逻辑:持久会话目录(`*_session` 或含 meta)跨任务保留;`run_*` 一次性目录
|
||||
由调用方清理。
|
||||
|
||||
Args:
|
||||
profile_dir: 已传给 Playwright persistent context 的 profile 目录。
|
||||
@@ -854,40 +1064,64 @@ def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
|
||||
Returns:
|
||||
bool: 为 True 时调用方可安全删除该目录。
|
||||
"""
|
||||
return profile_dir.resolve() != _dsv_session_profile_dir().resolve()
|
||||
return not _is_reusable_session_profile_dir(profile_dir)
|
||||
|
||||
|
||||
def _open_browser(download_dir: Path, *, reuse_dsv_session: bool = False):
|
||||
def _source_rpa_profile_code(source: dict[str, Any] | None) -> str:
|
||||
"""从库存 source 提取 RPA Profile 编码,缺省回落 source_code。"""
|
||||
if not isinstance(source, dict):
|
||||
return ""
|
||||
return str(source.get("rpa_profile_code") or source.get("source_code") or "").strip()
|
||||
|
||||
|
||||
def _open_browser(
|
||||
download_dir: Path,
|
||||
*,
|
||||
reuse_session: bool = False,
|
||||
connector_type: str = "",
|
||||
profile_code: str = "",
|
||||
reuse_dsv_session: bool | None = None,
|
||||
):
|
||||
"""
|
||||
打开用于库存 RPA 导出的浏览器上下文。
|
||||
打开用于库存 / 上传 RPA 的浏览器上下文。
|
||||
|
||||
核心逻辑:默认创建一次性的运行时 profile 子目录。仅当调用方明确为 DSV
|
||||
库存导出请求会话复用,且 `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=true` 时,
|
||||
才使用独立的固定 `dsv360_session` 目录;其他货代任务绝不复用该会话。
|
||||
核心逻辑:库存导出在 `reuse_session=True` 且 `SESSION_REUSE` 开启时,使用
|
||||
`{connector}__{profile_code}_session` 持久目录并按 TTL 失效重建;关闭复用或上传
|
||||
任务则创建 `run_*` 一次性目录。会话失效仍由各 connector 登录流程兜底。
|
||||
|
||||
Args:
|
||||
download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。
|
||||
reuse_dsv_session: 仅 DSV 库存调用可传 True;环境开关关闭时仍使用临时目录。
|
||||
download_dir: 当前任务下载目录,浏览器 downloads_path 指向此处。
|
||||
reuse_session: 调用方是否请求复用(库存 True,上传 False)。
|
||||
connector_type: 连接器名,用于隔离持久目录。
|
||||
profile_code: RPA 账号编码,用于隔离持久目录。
|
||||
reuse_dsv_session: 旧参数别名;若传入则覆盖 `reuse_session`。
|
||||
|
||||
Returns:
|
||||
tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir`
|
||||
为本次执行使用的 profile 目录。调用方必须用
|
||||
tuple: `(playwright, context, page, runtime_profile_dir)`。调用方须用
|
||||
`_should_cleanup_browser_profile` 决定是否清理。
|
||||
"""
|
||||
if reuse_dsv_session is not None:
|
||||
reuse_session = bool(reuse_dsv_session)
|
||||
sync_playwright, _timeout = _require_playwright()
|
||||
playwright = sync_playwright().start()
|
||||
profile_root = _browser_profile_root()
|
||||
profile_root.mkdir(parents=True, exist_ok=True)
|
||||
use_reused_dsv_session = reuse_dsv_session and _dsv_session_reuse_enabled()
|
||||
runtime_profile_dir = (
|
||||
_dsv_session_profile_dir()
|
||||
if use_reused_dsv_session
|
||||
else Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||||
)
|
||||
use_reused_session = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
|
||||
if use_reused_session:
|
||||
runtime_profile_dir = _prepare_reusable_session_profile(
|
||||
_session_profile_dir(connector_type, profile_code),
|
||||
connector_type=connector_type,
|
||||
profile_code=profile_code or "default",
|
||||
)
|
||||
profile_mode = "session_reuse"
|
||||
else:
|
||||
runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||||
profile_mode = "temporary"
|
||||
runtime_profile_dir.mkdir(parents=True, exist_ok=True)
|
||||
print(
|
||||
"[browser] profile_mode="
|
||||
f"{'dsv_session_reuse' if use_reused_dsv_session else 'temporary'}"
|
||||
f"{profile_mode} connector={connector_type or '-'} profile={profile_code or '-'} "
|
||||
f"dir={runtime_profile_dir.name!r}"
|
||||
)
|
||||
headless = _env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false").lower() == "true"
|
||||
channel = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL")
|
||||
@@ -941,7 +1175,9 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(
|
||||
drop_dir,
|
||||
reuse_dsv_session=connector_type == "dsv360",
|
||||
reuse_session=True,
|
||||
connector_type=connector_type,
|
||||
profile_code=_source_rpa_profile_code(source),
|
||||
)
|
||||
with _profile_credentials(source):
|
||||
if connector_type == "dsv360":
|
||||
@@ -1113,6 +1349,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
sources = body.get("inventory_sources") or []
|
||||
failed_dir = trigger_path.parent / "failed"
|
||||
# [DEBUG-TIMING] 批处理整体耗时基线:从进入 handler 到回调完成。
|
||||
batch_started_at = time.monotonic()
|
||||
print(f"[inventory-batch-timing] handler start run={run_no}")
|
||||
if not isinstance(sources, list) or not sources:
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
return
|
||||
@@ -1254,7 +1493,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(
|
||||
drop_dir,
|
||||
reuse_dsv_session=site == "dsv360",
|
||||
reuse_session=True,
|
||||
connector_type=site,
|
||||
profile_code=_profile_code,
|
||||
)
|
||||
if site not in {"dsv360", "crane_footprint"}:
|
||||
raise RuntimeError(f"unsupported connector_type: {site}")
|
||||
@@ -1381,6 +1622,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"schedule_run_id": body.get("schedule_run_id"),
|
||||
"results": results,
|
||||
}
|
||||
# [DEBUG-TIMING] 到达回调前打点:若此前有明显的静默段(浏览器清理),此处能看到
|
||||
# handler 启动到回调前的累计耗时,配合 _close_batch_browser_resources 的逐段计时即可定位。
|
||||
print(f"[inventory-batch-timing] before callback run={run_no} totalElapsedMs={int((time.monotonic() - batch_started_at) * 1000)}")
|
||||
_post_callback(callback_path, callback_payload)
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(
|
||||
@@ -1624,7 +1868,7 @@ def _capture_success_page_evidence(
|
||||
|
||||
def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str, Any]:
|
||||
"""
|
||||
仅以 DSV History 同名行的绿色 success DOM 确认上传受理;Reference 可选。
|
||||
兼容旧调用方的 History 证据读取。上传主流程不再调用此函数判定成功。
|
||||
|
||||
核心逻辑:succeeded=true 即成功;reference 可为空字符串。
|
||||
|
||||
@@ -1689,6 +1933,72 @@ def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str,
|
||||
)
|
||||
|
||||
|
||||
def _dsv_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
"""判断 DSV 上传页结果:成功按钮且 Upload File/WMS 错误均为空。"""
|
||||
return (
|
||||
str(state.get('button') or '').strip().lower() == 'upload successful'
|
||||
and not str(state.get('upload_file_errors') or '').strip()
|
||||
and not str(state.get('wms_errors') or '').strip()
|
||||
)
|
||||
|
||||
|
||||
def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
|
||||
"""判断 Crane 发货通知行是否进入 Processing/Shipping Order Allocated。"""
|
||||
return (
|
||||
bool(state.get('found'))
|
||||
and str(state.get('order_status') or '').strip().lower() == 'processing'
|
||||
and str(state.get('order_status_description') or '').strip().lower() == 'shipping order allocated'
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_dsv_upload_result(page: Any, filename: str) -> dict[str, Any]:
|
||||
"""轮询 DSV 上传结果页,不再使用 History 绿图标作为成功依据。
|
||||
|
||||
成功条件:`.alert.alert-success`(文本为 Upload Successful!)可见,且
|
||||
Upload File Errors 与 WMS Errors 各自结果单元格为空或显示 No Errors;
|
||||
`.alert.alert-danger`(文本为 Upload Unsuccessful)始终判定失败。
|
||||
"""
|
||||
script = """
|
||||
() => {
|
||||
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
|
||||
const success = document.querySelector('.alert.alert-success, [role="alert"].alert-success');
|
||||
const unsuccessful = document.querySelector('.alert.alert-danger, [role="alert"].alert-danger');
|
||||
const button = clean((success || unsuccessful)?.textContent).match(/Upload (?:Un)?Successful!?/i)?.[0] || '';
|
||||
const valueByHeader = (label) => {
|
||||
const heading = Array.from(document.querySelectorAll('th')).find((n) => clean(n.textContent).toLowerCase() === label.toLowerCase());
|
||||
if (!heading) return '';
|
||||
const value = heading.closest('table')?.querySelector('tbody tr td') || heading.parentElement?.nextElementSibling?.querySelector('td');
|
||||
return clean(value?.textContent);
|
||||
};
|
||||
const normalizeError = (value) => /^(no errors?|none|n\\/a)$/i.test(clean(value)) ? '' : clean(value);
|
||||
return { button, upload_file_errors: normalizeError(valueByHeader('Upload File Errors')), wms_errors: normalizeError(valueByHeader('WMS Errors')) };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (_browser_timeout_ms() / 1000)
|
||||
last_state: dict[str, Any] = {}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(script) or {}
|
||||
if isinstance(state, dict):
|
||||
last_state = state
|
||||
if str(state.get('button') or '').strip().lower() == 'upload unsuccessful':
|
||||
raise RuntimeError(f"DSV upload unsuccessful for {filename!r}: {state}")
|
||||
if _dsv_upload_result_is_success(state):
|
||||
return {
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='dsv_upload_success_dom', selector='div[role="alert"]',
|
||||
filename=filename, reference=None,
|
||||
),
|
||||
}
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"DSV upload result was not confirmed for {filename!r}; last_state={last_state}")
|
||||
|
||||
|
||||
class _UploadResultUnknownError(RuntimeError):
|
||||
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
|
||||
|
||||
@@ -1722,21 +2032,20 @@ class _BaseUploadAdapter:
|
||||
|
||||
|
||||
class DsvUploadAdapter(_BaseUploadAdapter):
|
||||
"""DSV 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → History 绿色判定。"""
|
||||
"""DSV 受控上传流程:登录、提交后按上传结果页提示与错误区域判定。"""
|
||||
|
||||
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
|
||||
"""选择 DSV 文件后强制点击 Process File,再读取结果页三项成功条件。"""
|
||||
self._require('entry_url', 'file_input_selector')
|
||||
_ensure_dsv_session(page, login_url)
|
||||
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
|
||||
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
|
||||
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
|
||||
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
|
||||
submit_selector = str(self.config.get('submit_selector') or '').strip()
|
||||
if not submit_selector:
|
||||
raise RuntimeError('DSV click_submit upload requires submit_selector')
|
||||
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
|
||||
# DSV 页面选择文件后只完成预览;必须点击真实二次确认按钮才会提交上传。
|
||||
submit_selector = 'button.btn.btn-primary.upload-button:has-text("Process File")'
|
||||
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
|
||||
try:
|
||||
return _wait_for_dsv_upload_history_receipt(page, self.file_path.name)
|
||||
return _wait_for_dsv_upload_result(page, self.file_path.name)
|
||||
except RuntimeError as exc:
|
||||
# 文件已选择/可能已提交但未取得可核验成功证据 → unknown,转人工。
|
||||
raise _UploadResultUnknownError(str(exc)) from exc
|
||||
@@ -1882,6 +2191,11 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
def _resolve_result(self, page: Any) -> dict[str, Any]:
|
||||
result_mode = str(self.config.get('result_mode') or '').strip()
|
||||
filename = self.file_path.name
|
||||
# [STEP 1] Crane 页面成功反馈后仍需核对发货通知列表中的业务状态,
|
||||
# 只有 Processing + Shipping Order Allocated 才视为真正上传成功。
|
||||
status_result = self._wait_for_order_status(page, filename)
|
||||
if status_result:
|
||||
return status_result
|
||||
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
|
||||
self._raise_if_crane_error(page)
|
||||
success = self._success_from_popup(page, filename)
|
||||
@@ -1949,6 +2263,51 @@ class CraneUploadAdapter(_BaseUploadAdapter):
|
||||
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
|
||||
)
|
||||
|
||||
def _wait_for_order_status(self, page: Any, filename: str) -> dict[str, Any] | None:
|
||||
"""轮询 Crane 发货通知表,按上传单号核对 Processing/Shipping Order Allocated。"""
|
||||
result_selector = str(self.config.get('result_selector') or '').strip()
|
||||
script = """
|
||||
({ filename, resultSelector }) => {
|
||||
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
|
||||
const wanted = clean(filename).replace(/\\.[^.]+$/, '');
|
||||
const roots = resultSelector ? document.querySelectorAll(resultSelector) : document.querySelectorAll('tr[id^="shipping-order-"]');
|
||||
for (const root of roots) {
|
||||
const row = root.closest('tr') || root;
|
||||
const text = clean(row.textContent);
|
||||
if (!text || (!text.includes(filename) && !text.includes(wanted))) continue;
|
||||
const cells = Array.from(row.querySelectorAll(':scope > td')).map((cell) => clean(cell.textContent));
|
||||
const headers = Array.from(row.closest('table')?.querySelectorAll('thead th') || []).map((n) => clean(n.textContent).toLowerCase());
|
||||
const at = (label) => { const i = headers.findIndex((h) => h === label); return i >= 0 ? cells[i] || '' : ''; };
|
||||
const status = at('order status');
|
||||
const description = at('order status description');
|
||||
return { found: true, order_status: status, order_status_description: description };
|
||||
}
|
||||
return { found: false, order_status: '', order_status_description: '' };
|
||||
}
|
||||
"""
|
||||
deadline = time.monotonic() + (self._timeout_ms() / 1000)
|
||||
last_state: dict[str, Any] = {}
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
state = page.evaluate(script, {'filename': filename, 'resultSelector': result_selector}) or {}
|
||||
if isinstance(state, dict):
|
||||
last_state = state
|
||||
if _crane_upload_result_is_success(state):
|
||||
return {
|
||||
'reference': '',
|
||||
'success_evidence': _capture_success_page_evidence(
|
||||
page, kind='crane_order_status_dom', selector='tr[id^="shipping-order-"]',
|
||||
filename=filename, reference=None,
|
||||
),
|
||||
}
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception:
|
||||
# 旧版/非列表页面没有可执行的状态查询时,交回既有弹窗/配置判定。
|
||||
return None
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def _upload_shipment_with_browser(
|
||||
file_path: Path, *, connector_type: str = "", upload_source: dict[str, Any] | None = None,
|
||||
@@ -1994,7 +2353,11 @@ def _upload_shipment_with_browser(
|
||||
playwright = context = runtime_profile_dir = None
|
||||
failed = False
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
|
||||
# 上传保持一次性 Profile,避免与库存持久登录态互相污染。
|
||||
playwright, context, page, runtime_profile_dir = _open_browser(
|
||||
file_path.parent,
|
||||
reuse_session=False,
|
||||
)
|
||||
with _profile_credentials(upload_source):
|
||||
return adapter.run(page, login_url=login_url)
|
||||
except Exception:
|
||||
@@ -2107,13 +2470,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 +2508,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 +2516,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,
|
||||
+10
-10
@@ -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:
|
||||
+5
-2
@@ -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)
|
||||
+14
-3
@@ -8,6 +8,7 @@
|
||||
每个环境必须有独立 root、scope、共享目录、browser profile、日志和 DPAPI Secret 文件。
|
||||
DSV/Crane 登录地址、账号和密码来自 HXOPS trigger 的 credential_envelope,
|
||||
不从本机 Secret 文件读取。
|
||||
默认开启库存会话复用(SESSION_REUSE + 24h TTL);需要每次全新登录时传 -NoSessionReuse。
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
@@ -26,6 +27,10 @@ param(
|
||||
[string]$PythonExe = "python.exe",
|
||||
[switch]$Mock,
|
||||
[switch]$Headless,
|
||||
# 默认开启库存会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
|
||||
[switch]$NoSessionReuse,
|
||||
# 兼容旧文档:等价于开启复用(现在默认已开启)。
|
||||
[switch]$ReuseSession,
|
||||
[switch]$ReuseDsvSession
|
||||
)
|
||||
|
||||
@@ -34,7 +39,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"
|
||||
}
|
||||
@@ -60,6 +65,12 @@ foreach ($required in @("ToolApiKey", "CredentialKey")) {
|
||||
}
|
||||
}
|
||||
|
||||
# 库存 Profile 默认按 connector+rpa_profile 复用,TTL 24h;-NoSessionReuse 可关闭。
|
||||
$sessionReuse = if ($NoSessionReuse) { "false" } else { "true" }
|
||||
if ($ReuseSession -or $ReuseDsvSession) {
|
||||
$sessionReuse = "true"
|
||||
}
|
||||
|
||||
# 只设置当前 launcher 及其 Worker 子进程可见的环境变量;不写 User/Machine 持久配置。
|
||||
$processVars = [ordered]@{
|
||||
HXOPS_API_BASE = $ApiBase
|
||||
@@ -70,8 +81,8 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
|
||||
# 仅显式启用时让 DSV 库存任务复用专属 profile;默认继续使用一次性会话。
|
||||
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE = $(if ($ReuseDsvSession) { "true" } else { "false" })
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE = $sessionReuse
|
||||
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS = "24"
|
||||
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
|
||||
+15
@@ -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
|
||||
+23
-10
@@ -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
|
||||
+3
-2
@@ -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 {
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user