fix(shipping-notice,admin-schedule,frontend): 修复发货通知与后台排程的业务bug并优化各模块功能
1. 后端发货通知模块:
清空重试任务旧状态避免残留,新增RPA进度回调接口
优化库存匹配性能,修复人工确认校验逻辑与登录弹窗遮挡问题
新增排程worker启动脚本,清理冗余环境配置与缓存查询开销
2. 前端后台排程模块:
新增任务key归一化工具兼容历史格式,修复参数表单隐藏问题
添加加载错误处理,更新多语言文案替换裸JSON占位符
This commit is contained in:
1 parent
1e5aedb9ed
commit
06c18b3c7c
81 files changed
+3301
-424
No files matched your search
+48
-7
@@ -123,7 +123,8 @@ Linux HXOPS 后端 Windows RPA Worker
|
||||
- Linux 后端负责生成 trigger、接收回调、校验库存文件结构并入库;不在 Linux 上执行浏览器自动化。
|
||||
- Windows Worker 负责浏览器自动化、读取 trigger、写入库存文件和发送心跳;它不直接连接 HXOPS 数据库。
|
||||
- test 与 prod 必须使用不同的 SMB 共享、Windows 根目录、Linux 挂载目录、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID`、API Base、Tool API Key 和 RPA 凭据主密钥。
|
||||
- Worker 进程启动后会在库存 trigger 目录写入 `.hxops_rpa_shared_mount`,并每 15 至 30 秒向 `/api/shipping-notice/rpa/heartbeat` 发送心跳。HXOPS 在 test/prod 写 trigger 前会检查 Worker 心跳、环境和共享 scope。
|
||||
- Worker 进程启动后会在库存 trigger 目录写入 `.hxops_rpa_shared_mount`,并由**独立守护心跳线程**按 `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS`(默认 20s)周期向 `/api/shipping-notice/rpa/heartbeat` 发送心跳——心跳与批量导出解耦,长任务执行期间不会停发、后端不会误判离线。HXOPS 在 test/prod 写 trigger 前会检查 Worker 心跳、环境和共享 scope。
|
||||
- 定时排程批量导出(`trigger_type=scheduled`)每完成一个站点,Worker 会调用 `/api/shipping-notice/rpa/inventory-batch-progress` 上报累计成功/跳过/失败笔数,管理端"库存RPA·执行记录"可实时看到当前 run 的进度;最终笔数仍以 `inventory-batch-ready` 回调为准。
|
||||
|
||||
|
||||
|
||||
@@ -541,7 +542,7 @@ docker compose --env-file .env.prod exec -T hxops-backend sh -lc 'ls -ld /mnt/hx
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
|
||||
"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" `
|
||||
-Environment test `
|
||||
-ApiBase "http://192.168.100.192:5052" `
|
||||
-ApiBase "http://192.168.100.192:8890" `
|
||||
-WorkerRoot "C:\HxopsRpaTest" `
|
||||
-SecretFile "C:\HxopsRpaSecrets\test.xml"
|
||||
```
|
||||
@@ -558,14 +559,13 @@ Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
|
||||
Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
|
||||
```
|
||||
|
||||
`-ApiBase` 必须填写 HXOPS 业务后端地址,不要填写 `HXOPS_TOOLS_API_BASE`(Tool API)。例如 `http://192.168.100.192:5052` 只有在该服务器确实监听测试后端并允许 Worker 访问时才可使用。启动前验证:
|
||||
`-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 / 业务后端的命名区分。启动前先验证网关端口连通:
|
||||
|
||||
```powershell
|
||||
Test-NetConnection 192.168.100.192 -Port 5052
|
||||
Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing
|
||||
Test-NetConnection 192.168.100.192 -Port 8890
|
||||
```
|
||||
|
||||
若 `TcpTestSucceeded` 为 `False`,应先核对测试服务器端口映射、防火墙和实际发布地址,不要改用 Tool API 端口代替。
|
||||
注意 `<网关>:8890/health` 会命中前端 SPA、不会透传到后端,不能作为后端连通性判据;是否可达以后端为准(Worker 心跳 `[heartbeat]` 上报成功或管理端显示 Worker 在线)。若 `TcpTestSucceeded` 为 `False`,应先核对测试服务器网关端口映射、nginx `/api/` 反代与防火墙。
|
||||
|
||||
确认通过后,也可以在当前窗口执行普通命令:
|
||||
|
||||
@@ -609,7 +609,7 @@ test 必须包含 `scope_id=hxops-rpa-test-data`,prod 必须包含 `scope_id=h
|
||||
|
||||
### 步骤 11:创建 test/prod 后台任务
|
||||
|
||||
使用 RPA Windows 账号打开 PowerShell。先把 `$PythonExe`、test/prod API Base 替换成真实值,然后整段执行:
|
||||
使用 RPA Windows 账号打开 PowerShell。先把 `$PythonExe`、test/prod API Base 替换成真实值,然后整段执行。test/prod 的 `-ApiBase` 应填实际可达的后端入口(同步骤 10:Docker Compose 部署填网关地址如 `http://192.168.100.192:8890`):
|
||||
|
||||
```powershell
|
||||
$PythonExe = "C:\Users\<RPA用户>\AppData\Local\Programs\Python\Python312\python.exe"
|
||||
@@ -1353,6 +1353,47 @@ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
|
||||
|
||||
计划维护时,必须按“暂停新触发 → 处理/记录运行中 trigger → 停止任务”的顺序执行。恢复时按“确认 SMB 挂载 → 确认 HXOPS 后端 → 启动 Worker → 等待心跳/哨兵 → 恢复排程”的顺序执行。
|
||||
|
||||
#### 2.3.1 headless 后台模式(无可见 Edge,完全后台)
|
||||
|
||||
> 适用:希望彻底摆脱「可见 Edge + 交互式桌面」,让 Worker 无控制台、无浏览器窗口地后台常驻。
|
||||
> 交付脚本:`scripts/rpa/register_rpa_background_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
|
||||
# 若触及上传,再验证一次 headless 下的上传流程
|
||||
```
|
||||
|
||||
只有 DSV/Crane 在 headless 下登录、下载、回调(以及在启用时的上传)都能通过,才切换正式运行;否则仍用 2.3 的可见模式。
|
||||
|
||||
**注册后台任务(在 RPA 账号的 PowerShell 中执行):**
|
||||
|
||||
```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)
|
||||
|
||||
# 区分环境:用 -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
|
||||
```
|
||||
|
||||
- **`-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 一致。
|
||||
- **不能改成 `SYSTEM` / `AtStartup` / Session 0 服务**:此处约束已从“浏览器需要交互桌面”变为“Secret 文件是用户级 DPAPI”。`new_rpa_worker_secret.ps1` 用 `Export-Clixml` 生成用户级 DPAPI 密文,改成非交互上下文(SYSTEM/服务/其他账号)会解密失败。
|
||||
- **RPA 账号请配置自动登录,且不要锁屏/注销**:headless 去掉了浏览器窗口依赖,但 `AtLogOn + Interactive` 仍要求该账号保持交互登录,否则任务不会常驻。
|
||||
- `-ApiBase` 同样填前端 nginx 网关地址(例如 `http://192.168.100.192:8890`),与 2.3 一致;脚本默认值已按此预填,可按实际地址改。
|
||||
- **回滚**:改用 2.3 的可见模式重新注册即可(去掉 `-Headless` 与 `-WindowStyle Hidden`),无需改动 Worker 或共享目录。
|
||||
|
||||
### 2.4 Linux 正式环境:Windows Prod Worker + SMB 共享
|
||||
|
||||
正式环境的流程与测试环境相同,但资源必须全部切换为 prod。**禁止**复制 test 的 `.env`、Windows 环境变量、浏览器 profile 或共享目录后直接上线。
|
||||
|
||||
@@ -477,6 +477,10 @@ def _submit_dsv_password_form(page: Any) -> bool:
|
||||
核心逻辑:优先直接点击可见登录按钮;如果页面使用 Vue/隐藏字段组合提交,
|
||||
则退回到 DOM 脚本里触发 `pf.ok` / form submit / Enter,避免“密码已填完但未真正登录”。
|
||||
"""
|
||||
# 密码已填写后 DSV 也可能弹出“使用密码升级登录!”(也许以后/立即启用)遮挡登录按钮;
|
||||
# 提交前先关闭,避免“DSV login password step detected but login button was not found”。
|
||||
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
|
||||
_dismiss_dsv_password_upgrade_prompt(page)
|
||||
selectors = (
|
||||
'button[name="login"]',
|
||||
'button[type="submit"]',
|
||||
@@ -546,6 +550,10 @@ def _submit_dsv_password_form(page: Any) -> bool:
|
||||
|
||||
|
||||
def _looks_like_dsv_login_method_page(page: Any) -> bool:
|
||||
# 升级提示弹窗文案含“密码”(“使用密码升级登录!”),会命中“选择登录方法”的
|
||||
# 宽泛 needle 造成误判(反复尝试点击“密码方式”而非关闭弹窗);命中升级提示时直接判非方法页。
|
||||
if _has_dsv_password_upgrade_prompt(page):
|
||||
return False
|
||||
needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method")
|
||||
for frame in page.frames:
|
||||
try:
|
||||
|
||||
@@ -30,6 +30,7 @@ _DSV_USERNAME_SELECTORS = dsv_auth._DSV_USERNAME_SELECTORS
|
||||
_click_dsv_continue = dsv_auth._click_dsv_continue
|
||||
_click_dsv_password_method = dsv_auth._click_dsv_password_method
|
||||
_debug_dsv_login_method_page = dsv_auth._debug_dsv_login_method_page
|
||||
_dismiss_dsv_password_upgrade_prompt = dsv_auth._dismiss_dsv_password_upgrade_prompt
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect = dsv_auth._dismiss_dsv_password_upgrade_prompt_after_login_redirect
|
||||
_dsv_login_debug_value = dsv_auth._dsv_login_debug_value
|
||||
_dsv_login_ready_timeout_ms = dsv_auth._dsv_login_ready_timeout_ms
|
||||
@@ -37,8 +38,10 @@ _fill_dsv_password_page_fields = dsv_auth._fill_dsv_password_page_fields
|
||||
_fill_dsv_username = dsv_auth._fill_dsv_username
|
||||
_find_dsv_password_locator = dsv_auth._find_dsv_password_locator
|
||||
_has_dsv_human_check_prompt = dsv_auth._has_dsv_human_check_prompt
|
||||
_has_dsv_password_upgrade_prompt = dsv_auth._has_dsv_password_upgrade_prompt
|
||||
_is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition
|
||||
_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url
|
||||
_is_dsv_password_upgrade_redirect = dsv_auth._is_dsv_password_upgrade_redirect
|
||||
_is_dsv_username_page = dsv_auth._is_dsv_username_page
|
||||
_submit_dsv_password_form = dsv_auth._submit_dsv_password_form
|
||||
_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready
|
||||
@@ -241,6 +244,10 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
password_method_clicked_at = 0.0
|
||||
username_retry_allowed_at = time.monotonic() + 6
|
||||
while time.monotonic() < login_deadline:
|
||||
# [STEP 1] DSV 在密码阶段前(authorization.ping)也会弹出“使用密码升级登录!”
|
||||
# 引导弹窗(也许以后/立即启用),会遮挡密码表单和登录按钮;先点“也许以后”关闭再探测。
|
||||
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
|
||||
_dismiss_dsv_password_upgrade_prompt(page)
|
||||
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
|
||||
if password_locator is not None:
|
||||
break
|
||||
|
||||
@@ -840,8 +840,39 @@ def _dsv_report_has_inventory_data_rows(page: Any) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。"""
|
||||
def _wait_dsv_report_inventory_rows(page: Any, *, timeout_ms: int) -> bool:
|
||||
"""
|
||||
条件轮询等待 SSRS 结果页出现真实库存明细行。
|
||||
|
||||
核心逻辑:result_ready(分页/导出按钮状态)先就绪,但当前页明细行是异步渲染进 DOM 的,
|
||||
单次快照可能撞上"分页已出、行未渲染"的窗口,把有数据的报表误判为无数据;
|
||||
这里以 1s 间隔轮询,直到明细行出现或超时,再交给调用方决定 success/skip。
|
||||
"""
|
||||
deadline = time.monotonic() + max(1.0, timeout_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if _dsv_report_has_inventory_data_rows(page):
|
||||
return True
|
||||
time.sleep(1.0)
|
||||
return False
|
||||
|
||||
|
||||
def _fill_dsv_filter_if_needed(
|
||||
page: Any,
|
||||
selector_env: str,
|
||||
label: str,
|
||||
value: str | None,
|
||||
*,
|
||||
report_name: str | None = None,
|
||||
) -> None:
|
||||
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。
|
||||
|
||||
Args:
|
||||
page: Playwright Page。
|
||||
selector_env: Warehouse/Owner/PutawayZone 对应 selector 环境变量名。
|
||||
label: 参数名。
|
||||
value: 参数值。
|
||||
report_name: 报表名;透传给 dsv_report_parameters 按报表模板解析控件。
|
||||
"""
|
||||
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
|
||||
assert spec and spec.loader
|
||||
@@ -855,6 +886,7 @@ def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value:
|
||||
env=_env,
|
||||
browser_timeout_ms=_browser_timeout_ms,
|
||||
debug_stage=_debug_dsv_stage,
|
||||
report_name=report_name,
|
||||
)
|
||||
|
||||
|
||||
@@ -866,11 +898,13 @@ def _fill_dsv_multi_select(
|
||||
*,
|
||||
selectors: dict[str, str] | None = None,
|
||||
select_all: bool = False,
|
||||
report_name: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
填充 DSV 报表多选控件(multi_select)。
|
||||
核心逻辑:显式配置 SSRS checkbox 下拉时委托 dsv_report_parameters;
|
||||
否则优先 select_option 多值,失败则展开控件后逐条点击 option/checkbox。
|
||||
report_name 用于按报表模板解析控件(同参数名在不同报表控件长相不同)。
|
||||
"""
|
||||
cleaned = [str(item).strip() for item in values if str(item).strip()]
|
||||
if not cleaned and not select_all:
|
||||
@@ -888,6 +922,7 @@ def _fill_dsv_multi_select(
|
||||
selectors=selectors,
|
||||
select_all=select_all,
|
||||
browser_timeout_ms=_browser_timeout_ms,
|
||||
report_name=report_name,
|
||||
):
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
@@ -918,13 +953,14 @@ def _fill_dsv_multi_select(
|
||||
except Exception as exc:
|
||||
print(f"[dsv-filter] {label} multi_select click fallback failed: {exc}", file=sys.stderr)
|
||||
for value in cleaned:
|
||||
_fill_dsv_filter_if_needed(page, selector_env, label, value)
|
||||
_fill_dsv_filter_if_needed(page, selector_env, label, value, report_name=report_name)
|
||||
|
||||
|
||||
def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
|
||||
def _fill_report_parameter(page: Any, parameter: dict[str, Any], *, report_name: str | None = None) -> None:
|
||||
"""按库存源业务参数填充 DSV 报表条件(single / multi_text / multi_select)。
|
||||
|
||||
核心逻辑:selector 从 Driver 内部参数名映射获取,不允许库存源配置携带页面实现细节。
|
||||
核心逻辑:selector 从 Driver 内部参数名映射获取,不允许库存源配置携带页面实现细节;
|
||||
report_name 交给 dsv_report_parameters 按报表模板解析控件类型(3lv select vs JDA multi_value)。
|
||||
"""
|
||||
if not isinstance(parameter, dict):
|
||||
return
|
||||
@@ -936,7 +972,7 @@ def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
|
||||
return
|
||||
if mode == "multi_text":
|
||||
joiner = str(parameter.get("joiner") or ",")
|
||||
_fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values))
|
||||
_fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values), report_name=report_name)
|
||||
return
|
||||
if mode == "multi_select":
|
||||
_fill_dsv_multi_select(
|
||||
@@ -946,9 +982,10 @@ def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
|
||||
values,
|
||||
selectors=None,
|
||||
select_all=bool(parameter.get("select_all", False)),
|
||||
report_name=report_name,
|
||||
)
|
||||
return
|
||||
_fill_dsv_filter_if_needed(page, selector_env, name, values[0])
|
||||
_fill_dsv_filter_if_needed(page, selector_env, name, values[0], report_name=report_name)
|
||||
|
||||
|
||||
def _dsv_parameter_selector_env(parameter_name: str) -> str:
|
||||
@@ -966,15 +1003,16 @@ def _dsv_parameter_selector_env(parameter_name: str) -> str:
|
||||
|
||||
def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None:
|
||||
"""填充 source.parameters;无 parameters 时回退 query 字段。"""
|
||||
report_name = _dsv_report_name(source)
|
||||
parameters = source.get("parameters")
|
||||
if isinstance(parameters, list) and parameters:
|
||||
for item in parameters:
|
||||
_fill_report_parameter(page, item)
|
||||
_fill_report_parameter(page, item, report_name=report_name)
|
||||
return
|
||||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||||
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"))
|
||||
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"))
|
||||
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"))
|
||||
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"), report_name=report_name)
|
||||
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"), report_name=report_name)
|
||||
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"), report_name=report_name)
|
||||
|
||||
|
||||
def _dsv_entry_url_host(entry_url: str) -> str:
|
||||
@@ -1164,46 +1202,65 @@ def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None:
|
||||
_wait_for_dsv_report_form_ready(page, report_name)
|
||||
|
||||
|
||||
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
|
||||
"""从 portal 首页导航至目标报表参数页,并记录完整导航耗时。"""
|
||||
def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_name: str) -> None:
|
||||
"""单次报表导航:开 Reports 菜单 → program_group → program_label → 分组 → 报表 → 等表单就绪。"""
|
||||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||||
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR")
|
||||
if reports_selector:
|
||||
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||||
else:
|
||||
_click_dsv_reports_menu(page)
|
||||
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
|
||||
|
||||
program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
|
||||
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
|
||||
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
|
||||
|
||||
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR")
|
||||
if program_selector:
|
||||
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
if program_group and program_group != program_label:
|
||||
_click_dsv_menu_item(page, program_group, next_text=program_label)
|
||||
_click_dsv_menu_item(page, program_label, next_text=report_group)
|
||||
|
||||
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_GROUP_SELECTOR")
|
||||
if report_group_selector:
|
||||
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
_click_dsv_report_group(page, report_group, next_text=report_name)
|
||||
|
||||
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_NAME_SELECTOR")
|
||||
if report_name_selector:
|
||||
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
_click_dsv_menu_item(page, report_name)
|
||||
|
||||
_wait_for_dsv_report_form_ready(page, report_name)
|
||||
|
||||
|
||||
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
|
||||
"""
|
||||
从当前页导航至目标报表参数页,并记录完整导航耗时。
|
||||
|
||||
核心逻辑:直连优先——当前页若已带常驻 Reports 导航(批内后续源),直接开菜单导航;
|
||||
失败时整页回 portal 首页重置一次再试(清理旧 SSRS 状态),仍失败才上抛。
|
||||
"""
|
||||
report_name = _dsv_report_name(source)
|
||||
entry_url = str(source.get("entry_url") or source.get("login_url") or "").strip()
|
||||
started_at = time.monotonic()
|
||||
_report_dsv_chain_stage("report_navigation", "start", extra={"reportName": report_name})
|
||||
try:
|
||||
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR")
|
||||
if reports_selector:
|
||||
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||||
else:
|
||||
_click_dsv_reports_menu(page)
|
||||
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
|
||||
|
||||
program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
|
||||
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
|
||||
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
|
||||
|
||||
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR")
|
||||
if program_selector:
|
||||
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
if program_group and program_group != program_label:
|
||||
_click_dsv_menu_item(page, program_group, next_text=program_label)
|
||||
_click_dsv_menu_item(page, program_label, next_text=report_group)
|
||||
|
||||
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_GROUP_SELECTOR")
|
||||
if report_group_selector:
|
||||
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
_click_dsv_report_group(page, report_group, next_text=report_name)
|
||||
|
||||
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_NAME_SELECTOR")
|
||||
if report_name_selector:
|
||||
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
|
||||
else:
|
||||
_click_dsv_menu_item(page, report_name)
|
||||
|
||||
_wait_for_dsv_report_form_ready(page, report_name)
|
||||
try:
|
||||
_navigate_dsv_to_report_form_once(page, source, report_name)
|
||||
except Exception as exc:
|
||||
# [RETRY] 报表上下文直连失败:整页回首页清掉旧 SSRS/菜单状态后重试一次。
|
||||
if not entry_url:
|
||||
raise
|
||||
print(f"[dsv-navigation] direct navigation failed, reset home and retry once: {exc}", file=sys.stderr)
|
||||
_reset_dsv_export_entry(page, entry_url)
|
||||
_navigate_dsv_to_report_form_once(page, source, report_name)
|
||||
except Exception as exc:
|
||||
_report_dsv_chain_stage(
|
||||
"report_navigation", "error", started_at=started_at,
|
||||
@@ -1214,6 +1271,17 @@ def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
|
||||
return report_name
|
||||
|
||||
|
||||
def _dsv_download_wait_ms() -> int:
|
||||
"""
|
||||
DSV Excel 导出下载等待窗口(毫秒)。
|
||||
|
||||
核心逻辑:按实测 P99 设定——报表结果就绪后,SSRS 端生成+响应在 34s~90s+ 波动
|
||||
(2026-08-26 实测 54s 命中、87s 兜底救回、90s+ 超时)。默认 240s 覆盖长尾,
|
||||
用 `SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS` 可按站点调整。
|
||||
"""
|
||||
return max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS", "240000") or "240000"))
|
||||
|
||||
|
||||
def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any:
|
||||
"""参数页已就绪后:填参 → View Report → 等结果 → 导出 Excel,并分别记录阶段耗时。"""
|
||||
report_name = _dsv_report_name(source)
|
||||
@@ -1240,7 +1308,9 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
|
||||
# [STEP 1] DSV 页面会维持长连接;等待 networkidle 不能说明 SSRS 已可导出,
|
||||
# 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件。
|
||||
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
|
||||
if not _dsv_report_has_inventory_data_rows(page):
|
||||
# [STEP 2] result_ready 只代表分页/导出状态就绪,明细行异步渲染可能晚几秒;
|
||||
# 用条件轮询等待真实数据行,避免把"有数据但行未渲染"误判成 skip。
|
||||
if not _wait_dsv_report_inventory_rows(page, timeout_ms=min(_browser_timeout_ms(), 45_000)):
|
||||
raise NoInventoryDataError("DSV report has no inventory data")
|
||||
except Exception as exc:
|
||||
_report_dsv_chain_stage(
|
||||
@@ -1267,7 +1337,7 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
|
||||
download_event_started_at = time.monotonic()
|
||||
_report_dsv_chain_stage("excel_download_event", "start", extra={"reportName": report_name})
|
||||
try:
|
||||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||||
with page.expect_download(timeout=_dsv_download_wait_ms()) as download_info:
|
||||
_click_dsv_export_excel(page)
|
||||
except Exception as exc:
|
||||
selected = _find_dsv_report_result_frame(page)
|
||||
@@ -1301,9 +1371,11 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
|
||||
file=sys.stderr,
|
||||
)
|
||||
if download_dir:
|
||||
# 事件确实晚到/丢失时的目录兜底:窗口放宽到 60s,覆盖已观测的"超时后 0-3s 落盘"场景。
|
||||
fallback_download = _wait_for_new_download_file(
|
||||
download_dir=download_dir,
|
||||
baseline_names=baseline_names,
|
||||
timeout_seconds=60.0,
|
||||
)
|
||||
if fallback_download is not None:
|
||||
print(
|
||||
@@ -1373,7 +1445,9 @@ def _prepare_dsv_batch_export_step(
|
||||
return True
|
||||
except Exception as exc:
|
||||
print(f"[dsv-batch] parameter reuse failed, fallback home reset: {exc}", file=sys.stderr)
|
||||
_reset_dsv_export_entry(page, entry_url)
|
||||
# 导航不同的后续源:当前页已带登录态与常驻 Reports 导航,直接进入菜单导航,
|
||||
# 不再整页 goto portal 首页(省 ~12s 且避开 public/login 认证回落一闪)。
|
||||
# 旧 SSRS 状态串站/导航失败由 _navigate_dsv_to_report_form 内部"重置首页重试一次"兜底。
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -34,6 +34,51 @@ _DSV_REPORT_PARAM_DEFAULTS: dict[str, dict[str, str]] = {
|
||||
}
|
||||
|
||||
|
||||
def _normalize_report_name(report_name: str) -> str:
|
||||
"""报表名归一化:去首尾空白并折叠连续空白、统一小写,用于模板精确匹配。"""
|
||||
return " ".join(str(report_name or "").strip().lower().split())
|
||||
|
||||
|
||||
# 报表名 → 参数控件模板。同名的 SSRS 参数在不同报表里的控件长相不同:
|
||||
# - 3lv 版(On Hand Inventory By Location 3lv,Bison/AWSBI):Warehouse 是原生 select(ddValue);
|
||||
# - JDA 版(On Hand Inventory by Location,Moerdijk 等):Warehouse 是 txtValue + toggle + divDropDown
|
||||
# 组成的多选框下拉(multi_value),历史 YAML 为该源配置的 selectors 即源于此。
|
||||
# 模板按"归一化报表名"精确匹配;未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
|
||||
_DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
|
||||
"on hand inventory by location 3lv": {
|
||||
"Warehouse": {
|
||||
"control": "select",
|
||||
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
|
||||
},
|
||||
},
|
||||
"on hand inventory by location": {
|
||||
"Warehouse": {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def resolve_parameter_controls(report_name: str | None, label: str) -> dict[str, str]:
|
||||
"""
|
||||
按(报表名, 参数名)解析 SSRS 控件配置;报表模板优先,未命中返回空 dict。
|
||||
|
||||
Args:
|
||||
report_name: 当前报表名(如 navigation.report_name),允许为空。
|
||||
label: 参数名(Owner / PutawayZone / Warehouse)。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: 控件配置(control/selector 或 control/text/toggle/dropdown);
|
||||
报表未登记时为空 dict,由调用方回退参数名默认值。
|
||||
"""
|
||||
key = _normalize_report_name(report_name)
|
||||
template = _DSV_REPORT_PARAM_TEMPLATES.get(key) or {}
|
||||
return dict(template.get(str(label or "").strip()) or {})
|
||||
|
||||
|
||||
def _iter_dsv_report_roots(page: Any) -> list[Any]:
|
||||
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
|
||||
matched: list[Any] = []
|
||||
@@ -370,6 +415,52 @@ def _fill_select_parameter(page: Any, label: str, value: str, selector: str, *,
|
||||
return False
|
||||
|
||||
|
||||
def _probe_report_parameter_controls(page: Any) -> dict[str, Any]:
|
||||
"""
|
||||
枚举报表参数区(ReportViewerMain_ctl08)的实际控件,用于填参失败时定位控件类型漂移。
|
||||
|
||||
核心逻辑:SSRS 对同一参数名在不同报表里可能渲染成原生 select、文本框或多选框下拉;
|
||||
失败日志带上本探针后,无需人工开浏览器即可判断目标控件是否存在、option 数是否为空。
|
||||
"""
|
||||
roots = _iter_dsv_report_roots(page)
|
||||
probe: dict[str, Any] = {"roots": len(roots), "controls": []}
|
||||
for root in roots:
|
||||
try:
|
||||
items = root.evaluate(
|
||||
"""
|
||||
() => {
|
||||
const normalize = (text) => ((text || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
const nodes = Array.from(document.querySelectorAll(
|
||||
'#ReportViewerMain_ctl08 select, #ReportViewerMain_ctl08 input, ' +
|
||||
'#ReportViewerMain_ctl08 [id$="_divDropDown"]'
|
||||
));
|
||||
return nodes.slice(0, 60).map((node) => {
|
||||
const table = node.tagName.toLowerCase() === 'select'
|
||||
? Array.from(node.options || []).map((item) => normalize(item.textContent)).filter(Boolean)
|
||||
: [];
|
||||
const dropdown = node.getAttribute('id') || '';
|
||||
return {
|
||||
id: dropdown,
|
||||
tag: node.tagName.toLowerCase(),
|
||||
type: node.getAttribute('type') || '',
|
||||
hidden: node.getAttribute('type') === 'hidden',
|
||||
optionCount: table.length,
|
||||
firstOptions: table.slice(0, 12),
|
||||
labelText: normalize(
|
||||
(node.closest('td') || {}).innerText || ''
|
||||
).slice(0, 120),
|
||||
};
|
||||
});
|
||||
}
|
||||
""",
|
||||
)
|
||||
if isinstance(items, list):
|
||||
probe["controls"].extend(items)
|
||||
except Exception as exc:
|
||||
probe["controls"].append({"probe_error": str(exc)[:120]})
|
||||
return probe
|
||||
|
||||
|
||||
def fill_dsv_filter_if_needed(
|
||||
page: Any,
|
||||
selector_env: str,
|
||||
@@ -379,10 +470,13 @@ def fill_dsv_filter_if_needed(
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: Callable[[], int],
|
||||
debug_stage: Callable[..., None] | None = None,
|
||||
report_name: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
按 ReportViewer 控件类型填充 DSV 报表参数。
|
||||
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
|
||||
报表模板(_DSV_REPORT_PARAM_TEMPLATES)登记了同类报表的控件差异:传入 report_name 时,
|
||||
先按模板选择 multi_value/select;未命中的报表回退参数名默认值(旧行为)。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
@@ -401,7 +495,11 @@ def fill_dsv_filter_if_needed(
|
||||
pass
|
||||
|
||||
timeout_ms = browser_timeout_ms()
|
||||
defaults = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
|
||||
defaults = dict(_DSV_REPORT_PARAM_DEFAULTS.get(label, {}))
|
||||
# 报表模板优先:同一参数名在不同报表的控件长相不同(3lv select vs JDA multi_value)。
|
||||
template_controls = resolve_parameter_controls(report_name, label)
|
||||
if template_controls:
|
||||
defaults.update(template_controls)
|
||||
custom_selector = str(env(selector_env) or "").strip()
|
||||
selector = custom_selector or defaults.get("selector") or defaults.get("text")
|
||||
|
||||
@@ -412,17 +510,22 @@ def fill_dsv_filter_if_needed(
|
||||
|
||||
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
|
||||
|
||||
# [STEP 1] 模板登记为 multi_value(或 Owner/PutawayZone 固有多选)时,优先走 checkbox 下拉填充。
|
||||
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
|
||||
if _fill_multi_value_parameter(page, label, values, timeout_ms=timeout_ms):
|
||||
if _fill_multi_value_parameter(
|
||||
page, label, values, timeout_ms=timeout_ms, config_override=defaults,
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
|
||||
# [STEP 2] 原生 select 路径:模板为 select 或未登记时继续旧行为(ddValue + 选项等待/脚本赋值)。
|
||||
select_selector = custom_selector or defaults.get("selector", "")
|
||||
if defaults.get("control") == "select" or label == "Warehouse" or select_selector.endswith("ddValue"):
|
||||
if select_selector and (defaults.get("control") == "select" or select_selector.endswith("ddValue")):
|
||||
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
|
||||
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
|
||||
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
|
||||
for root in _iter_dsv_report_roots(page):
|
||||
if _fill_input_via_script(root, selector, text):
|
||||
@@ -440,6 +543,12 @@ def fill_dsv_filter_if_needed(
|
||||
except Exception as exc:
|
||||
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
|
||||
|
||||
# 全部路径失败:输出参数区控件探针,便于下轮直接定位控件 ID/类型漂移。
|
||||
print(
|
||||
f"[dsv-filter] {label} control probe: "
|
||||
f"{json.dumps(_probe_report_parameter_controls(page), ensure_ascii=False)[:1500]}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
|
||||
_debug(f"filter-failed-{label.lower()}", text)
|
||||
|
||||
@@ -452,16 +561,19 @@ def fill_dsv_multi_select_parameter(
|
||||
selectors: dict[str, str] | None = None,
|
||||
select_all: bool = False,
|
||||
browser_timeout_ms: Callable[[], int],
|
||||
report_name: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
|
||||
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
|
||||
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
|
||||
核心逻辑:selectors 缺省时按报表模板(report_name)解析控件;两者都没有则返回 False。
|
||||
"""
|
||||
config_override = {"control": "multi_value"}
|
||||
if selectors:
|
||||
effective_selectors = selectors or (resolve_parameter_controls(report_name, label) or None)
|
||||
if effective_selectors:
|
||||
for key in ("text", "toggle", "dropdown"):
|
||||
value = str(selectors.get(key) or "").strip()
|
||||
value = str(effective_selectors.get(key) or "").strip()
|
||||
if value:
|
||||
config_override[key] = value
|
||||
if not all(config_override.get(key) for key in ("text", "toggle", "dropdown")):
|
||||
|
||||
@@ -235,3 +235,42 @@ def maybe_send_heartbeat(
|
||||
_start_heartbeat_request(payload)
|
||||
_LAST_HEARTBEAT_MONO = now
|
||||
return now
|
||||
|
||||
|
||||
def start_heartbeat_loop(
|
||||
*,
|
||||
trigger_dir: str | Path,
|
||||
drop_dir: str | Path,
|
||||
interval_seconds: float,
|
||||
) -> threading.Thread:
|
||||
"""
|
||||
启动独立守护心跳线程,使心跳节奏与业务主循环解耦。
|
||||
|
||||
核心逻辑:批量站点导出(浏览器登录+下载)会长时间阻塞 worker 主循环;若心跳由
|
||||
主循环发送,执行期间会停发,后端按心跳 TTL 误判 Worker 离线。本线程按固定间隔
|
||||
持续上报,主循环只负责业务扫描;线程内异常仅打印,绝不退出。
|
||||
|
||||
Args:
|
||||
trigger_dir: 触发目录(哨兵写入与心跳 payload 使用)。
|
||||
drop_dir: 库存落盘目录(心跳 payload 使用)。
|
||||
interval_seconds: 心跳间隔;实际以环境变量最小 15s 为准。
|
||||
|
||||
Returns:
|
||||
已启动的守护线程(daemon,随进程退出)。
|
||||
"""
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
time.sleep(max(5.0, float(interval_seconds)))
|
||||
try:
|
||||
maybe_send_heartbeat(
|
||||
trigger_dir=trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
except Exception:
|
||||
print("[heartbeat] loop tick failed", file=sys.stderr)
|
||||
|
||||
thread = threading.Thread(target=_loop, name="shipping-rpa-heartbeat-loop", daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
@@ -1080,6 +1080,34 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[str, Any]]) -> None:
|
||||
"""
|
||||
定时排程批量导出每完成一个站点即上报累计进度,后端实时回写排程 run 笔数。
|
||||
|
||||
核心逻辑:仅 scheduled 触发且携带 schedule_run_id 时上报,按需单票不受影响;
|
||||
best-effort,上报失败不影响导出与最终回调;最终笔数以 inventory-batch-ready 为准。
|
||||
"""
|
||||
if str(body.get("trigger_type") or "").strip() != "scheduled":
|
||||
return
|
||||
schedule_run_id = body.get("schedule_run_id")
|
||||
if schedule_run_id is None:
|
||||
return
|
||||
summary = _summarize_inventory_batch_results(results)
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-batch-progress", {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": body.get("callback_id"),
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
"schedule_run_id": schedule_run_id,
|
||||
"success_count": summary["success_count"],
|
||||
"skipped_count": summary["skipped_count"],
|
||||
"failed_count": summary["failed_count"],
|
||||
})
|
||||
except Exception as exc:
|
||||
print(f"[inventory-batch] progress callback failed {run_no}: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
|
||||
@@ -1094,7 +1122,19 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
identity_errors.append("schema_version")
|
||||
if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()):
|
||||
identity_errors.append("callback_id")
|
||||
if body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip()):
|
||||
# 定时排程批量触发是按 run 计价的:只携带 run_no/schedule_run_id,没有逐源
|
||||
# Attempt/Gate 身份。身份校验按模式取值:scheduled 只强制信封与站点分发字段,
|
||||
# 业务终态由后端按 schedule_run_id + DB 配置校验;其余模式保持逐源身份 fail-closed。
|
||||
is_scheduled_batch = str(body.get("trigger_type") or "").strip() == "scheduled"
|
||||
source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
|
||||
if is_scheduled_batch:
|
||||
source_required -= {
|
||||
"task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id",
|
||||
"execution_id", "gate_id", "callback_id", "expected_warehouse_id",
|
||||
}
|
||||
if not is_scheduled_batch and (
|
||||
body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip())
|
||||
):
|
||||
identity_errors.append("task_no")
|
||||
for index, source in enumerate(sources):
|
||||
if not isinstance(source, dict):
|
||||
@@ -1107,9 +1147,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
).strip().lower() not in {"crane", "crane_footprint"}
|
||||
identity_errors.extend(
|
||||
f"inventory_sources[{index}].{key}"
|
||||
for key in _INVENTORY_V2_REQUIRED_FIELDS
|
||||
if key not in {"schema_version", "task_no", "callback_id"}
|
||||
and (key != "expected_warehouse_id" or requires_expected_warehouse)
|
||||
for key in source_required
|
||||
if (key != "expected_warehouse_id" or requires_expected_warehouse)
|
||||
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
|
||||
)
|
||||
if identity_errors:
|
||||
@@ -1152,6 +1191,11 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
mode = "mock" if mock else "browser"
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
def record_result(item: dict[str, Any]) -> None:
|
||||
"""记录单站点结果并即时上报累计进度(仅定时排程会真正上报)。"""
|
||||
results.append(item)
|
||||
_emit_batch_progress(body, run_no, results)
|
||||
|
||||
# v2 claimed 回调只记录领取事实,不代表业务成功。
|
||||
if body.get("schema_version") == "shipping_inventory_rpa.v2":
|
||||
claimed_items = []
|
||||
@@ -1191,7 +1235,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
report_configuration_test_progress(source)
|
||||
task_stub = run_no
|
||||
out_file = _write_sample_inventory(drop_dir, task_stub)
|
||||
results.append({
|
||||
record_result({
|
||||
"source_code": source.get("source_code"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"status": "success",
|
||||
@@ -1228,28 +1272,52 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
_validate_inventory_source_for_rpa(source)
|
||||
skip_navigation = False
|
||||
if site == "dsv360":
|
||||
# DSV 报表页会保留 iframe、导出菜单与下载等待状态;同一 tab
|
||||
# 串行切换站点会让下一站误用上一站页面。复用 context 登录态,但每站新开页面。
|
||||
if index > 0:
|
||||
# [STEP 3] 批内同一 Profile 只登录一次:首源完整登录,后续源复用当前 tab
|
||||
# 的登录态——同导航走 _return_to_dsv_report_parameters 复用参数页,
|
||||
# 导航不同走 _reset_dsv_export_entry(goto entry + 会话检测,不重复 OAuth)。
|
||||
# 曾因"每源新开空白页 + 写死 index=0"导致每源重复走 SSO 重定向链
|
||||
# (每源 2-2.5 分钟,且偶发 OAuth 空白页单源失败),现已移除。
|
||||
# 页面串站状态由整页/帧重载兜底,无需隔离页。
|
||||
previous_source = site_sources[index - 1] if index > 0 else None
|
||||
try:
|
||||
# 返回 True 表示参数页已就绪:后续跳过菜单导航直接填参/导出。
|
||||
skip_navigation = bool(
|
||||
_prepare_dsv_batch_export_step(page, entry_url, previous_source, source, index=index)
|
||||
)
|
||||
except Exception as exc:
|
||||
# 会话复用的安全网:登录/会话类偶发异常(SSO/OAuth 链、
|
||||
# “密码升级”弹窗遮挡、字段未渲染)时,新开干净页面重试一次完整登录;
|
||||
# 凭据校验类(invalid/verification)不重试,直接失败。
|
||||
message = str(exc).lower()
|
||||
login_related = any(token in message for token in ("login", "session", "oauth"))
|
||||
credential_mismatch = any(token in message for token in ("invalid", "verification"))
|
||||
if not login_related or credential_mismatch:
|
||||
raise
|
||||
print(
|
||||
f"[inventory-batch] dsv360 session prepare failed for {code}, retry with clean page: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
page = _open_clean_batch_page(context, page)
|
||||
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
|
||||
skip_navigation = bool(
|
||||
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
|
||||
)
|
||||
elif index == 0:
|
||||
_ensure_crane_session(page, entry_url)
|
||||
else:
|
||||
_reset_crane_export_entry(page, entry_url)
|
||||
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
|
||||
out_file = _save_batch_download(download, drop_dir, run_no, source)
|
||||
results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
|
||||
record_result({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
|
||||
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
results.append({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
record_result({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
|
||||
except Exception as exc:
|
||||
results.append({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
record_result({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
|
||||
except Exception as exc:
|
||||
for source in site_sources:
|
||||
results.append({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
record_result({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
finally:
|
||||
_close_batch_browser_resources(context, playwright, runtime_profile_dir)
|
||||
|
||||
@@ -1837,20 +1905,22 @@ def main() -> None:
|
||||
print(f" drop={drop_dir}")
|
||||
print(f" queue={upload_queue_dir}")
|
||||
|
||||
last_heartbeat_mono = 0.0
|
||||
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
|
||||
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
|
||||
freight_rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=inv_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
last_sent_mono=last_heartbeat_mono,
|
||||
last_sent_mono=0.0,
|
||||
force=True,
|
||||
)
|
||||
# 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环,
|
||||
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
|
||||
freight_rpa_heartbeat.start_heartbeat_loop(
|
||||
trigger_dir=inv_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
|
||||
while True:
|
||||
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=inv_trigger_dir,
|
||||
drop_dir=drop_dir,
|
||||
last_sent_mono=last_heartbeat_mono,
|
||||
)
|
||||
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
|
||||
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
|
||||
time.sleep(poll)
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Register the test/prod RPA Worker scheduled tasks in FULL-BACKGROUND mode.
|
||||
|
||||
.DESCRIPTION
|
||||
Runs the Worker as a background scheduled task with NO visible console and NO
|
||||
visible Edge (the Worker launches Playwright headless via -Headless). Deliberately
|
||||
ASCII-only so it parses identically under any Windows console code page.
|
||||
|
||||
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.
|
||||
|
||||
Shape constraints (same as README 2.3):
|
||||
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
|
||||
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
|
||||
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
|
||||
decrypted in a non-interactive context.
|
||||
- The RPA account should be configured for auto-logon and must not be locked
|
||||
/ logged-off, otherwise the AtLogOn task does not stay resident.
|
||||
- Before trusting headless, run the headless smoke preflight (README 2.3.1):
|
||||
set $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS="true" then run
|
||||
dsv_login_smoke.py / crane_login_smoke.py.
|
||||
|
||||
Scope:
|
||||
All actions can target one environment or both via -Scope test|prod|all (default all).
|
||||
|
||||
Usage (run in the RPA account's PowerShell):
|
||||
.\scripts\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
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$Register,
|
||||
[switch]$Start,
|
||||
[switch]$Stop,
|
||||
[switch]$Status,
|
||||
[switch]$Unregister,
|
||||
[ValidateSet("test", "prod", "all")]
|
||||
[string]$Scope = "all",
|
||||
[string]$TestApiBase = "http://192.168.100.192:8890",
|
||||
[string]$ProdApiBase = "http://192.168.100.230:8890",
|
||||
[string]$TestRoot = "C:\HxopsRpaTest",
|
||||
[string]$ProdRoot = "C:\HxopsRpaProd",
|
||||
[string]$SecretFile = "C:\HxopsRpaSecrets"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$TestTask = "HXOPS Inventory RPA Worker TEST"
|
||||
$ProdTask = "HXOPS Inventory RPA Worker PROD"
|
||||
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
|
||||
function Get-TasksForScope {
|
||||
# Return the task name(s) selected by -Scope.
|
||||
param([string]$Scope)
|
||||
switch ($Scope) {
|
||||
"test" { return @($TestTask) }
|
||||
"prod" { return @($ProdTask) }
|
||||
default { return @($TestTask, $ProdTask) }
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-Launcher {
|
||||
# Validate the launcher and DPAPI Secret file required for one environment.
|
||||
param([string]$Root, [string]$Environment)
|
||||
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
|
||||
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
|
||||
throw "Launcher not found: $launcher"
|
||||
}
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
|
||||
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
|
||||
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
|
||||
}
|
||||
}
|
||||
|
||||
function New-TaskDefinition {
|
||||
param(
|
||||
[string]$TaskName,
|
||||
[string]$Root,
|
||||
[string]$ApiBase,
|
||||
[string]$EnvName
|
||||
)
|
||||
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
|
||||
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
|
||||
|
||||
# Key differences vs the visible scheduled task:
|
||||
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
|
||||
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
|
||||
$action = New-ScheduledTaskAction `
|
||||
-Execute "powershell.exe" `
|
||||
-Argument $actionArgs `
|
||||
-WorkingDirectory $Root
|
||||
|
||||
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
|
||||
$principal = New-ScheduledTaskPrincipal `
|
||||
-UserId $RunAsUser `
|
||||
-LogonType Interactive `
|
||||
-RunLevel Limited
|
||||
$settings = New-ScheduledTaskSettingsSet `
|
||||
-StartWhenAvailable `
|
||||
-RestartCount 10 `
|
||||
-RestartInterval (New-TimeSpan -Minutes 1) `
|
||||
-ExecutionTimeLimit ([TimeSpan]::Zero) `
|
||||
-MultipleInstances IgnoreNew
|
||||
|
||||
Register-ScheduledTask `
|
||||
-TaskName $TaskName `
|
||||
-Action $action `
|
||||
-Trigger $trigger `
|
||||
-Principal $principal `
|
||||
-Settings $settings `
|
||||
-Description "HXOPS RPA Worker ($EnvName) background (headless + hidden console)"
|
||||
}
|
||||
|
||||
# Default action is Register when no switch is given.
|
||||
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
|
||||
# handled below
|
||||
} else {
|
||||
$Register = $true
|
||||
}
|
||||
|
||||
if ($Unregister) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
|
||||
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
|
||||
Write-Host "Unregistered task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Start) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Start-ScheduledTask -TaskName $t
|
||||
Write-Host "Started task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Stop) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
Stop-ScheduledTask -TaskName $t
|
||||
Write-Host "Stopped task: $t"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Status) {
|
||||
foreach ($t in (Get-TasksForScope $Scope)) {
|
||||
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
|
||||
if ($tobj) {
|
||||
$info = Get-ScheduledTaskInfo -TaskName $t
|
||||
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
|
||||
Write-Host " (267009 / 0x41301 = running, not an error)"
|
||||
} else {
|
||||
Write-Host "Task not registered yet: $t"
|
||||
}
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Register) {
|
||||
if ($Scope -eq "test" -or $Scope -eq "all") {
|
||||
Assert-Launcher $TestRoot "test"
|
||||
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
|
||||
}
|
||||
if ($Scope -eq "prod" -or $Scope -eq "all") {
|
||||
Assert-Launcher $ProdRoot "prod"
|
||||
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
|
||||
}
|
||||
Write-Host "Registered background task(s) for scope=${Scope}:"
|
||||
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
|
||||
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
|
||||
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
|
||||
exit 0
|
||||
}
|
||||
@@ -94,8 +94,16 @@ $jobs += Start-Job -Name "hxops-shipping-worker" -ScriptBlock {
|
||||
Set-Location $dir
|
||||
& $python .\worker_shipping.py 2>&1
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, $ShippingConcurrency)
|
||||
# 排程 worker:消费 schedule 队列并执行到期 ScheduleTask(入口为 backend/workers/worker_scheduler.py,与 start_local.ps1 的 schedule-worker 对齐)
|
||||
$jobs += Start-Job -Name "hxops-schedule-worker" -ScriptBlock {
|
||||
param($dir, $python, $db)
|
||||
if ($db) { $env:DATABASE_URL = $db }
|
||||
$env:ENV_NAME = "dev"
|
||||
Set-Location $dir
|
||||
& $python .\workers\worker_scheduler.py 2>&1
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL)
|
||||
|
||||
Write-Host "[startup] backend, frontend, kb-worker and shipping-worker are running in this IDE terminal." -ForegroundColor Green
|
||||
Write-Host "[startup] backend, frontend, kb-worker, shipping-worker and schedule-worker are running in this IDE terminal." -ForegroundColor Green
|
||||
Write-Host "[startup] Press Ctrl+C to stop all services." -ForegroundColor DarkGray
|
||||
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user