feat(schedule): 增加库存源选项描述字段与站点ID支持
This commit is contained in:
1 parent
f4e74f7b07
commit
8b1efbedb9
37 files changed
+8488
-4126
No files matched your search
+50
-11
@@ -2,6 +2,22 @@
|
||||
|
||||
Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA 脚本在 Windows 货代终端上运行(或由本 PoC worker 在开发环境模拟)。
|
||||
|
||||
## 模块结构
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `freight_rpa_worker.py` | 轮询 trigger、打开浏览器、按 `source_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 登录与异步导出 |
|
||||
|
||||
## 目录约定
|
||||
|
||||
| 环境变量 | 用途 |
|
||||
@@ -64,9 +80,20 @@ python scripts/rpa/freight_rpa_worker.py
|
||||
| `FREIGHT_RPA_DSV_USERNAME_SELECTOR` | DSV 用户名输入框 |
|
||||
| `FREIGHT_RPA_DSV_PASSWORD_SELECTOR` | DSV 密码输入框 |
|
||||
| `FREIGHT_RPA_DSV_LOGIN_BUTTON_SELECTOR` | DSV 登录按钮 |
|
||||
| `FREIGHT_RPA_CRANE_USERNAME_SELECTOR` | Crane 用户名输入框 |
|
||||
| `FREIGHT_RPA_CRANE_PASSWORD_SELECTOR` | Crane 密码输入框 |
|
||||
| `FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR` | Crane 登录按钮 |
|
||||
| `FREIGHT_RPA_CRANE_USERNAME_SELECTOR` | Crane 用户名(默认 `input[placeholder="Enter user name..."]`) |
|
||||
| `FREIGHT_RPA_CRANE_PASSWORD_SELECTOR` | Crane 密码(默认 `input[placeholder="Enter password..."]`) |
|
||||
| `FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR` | Crane 登录按钮(默认 `button.button.is-primary:has-text("Sign in")`;填写凭据前为 disabled) |
|
||||
| `FREIGHT_RPA_CRANE_DASHBOARD_REPORT_SELECTOR` | Crane 首页 Queries 区 On Hand Details 卡片(默认 `a.box[href="/on-hand-details-query"]`) |
|
||||
| `FREIGHT_RPA_CRANE_NAV_QUERIES_SELECTOR` | Crane 顶部 Queries 下拉触发(默认 `a.navbar-link:has-text("Queries")`) |
|
||||
| `FREIGHT_RPA_CRANE_NAV_REPORT_SELECTOR` | Crane 顶部菜单 On Hand Details 项(默认 `a.navbar-item:has-text("On Hand Details")`) |
|
||||
|
||||
Crane 登录烟测(仅验证 User Name / Password / Sign in):
|
||||
|
||||
```powershell
|
||||
$env:FREIGHT_RPA_CRANE_USERNAME = "<Crane账号>"
|
||||
$env:FREIGHT_RPA_CRANE_PASSWORD = "<Crane密码>"
|
||||
backend\venv\Scripts\python.exe scripts\rpa\crane_login_smoke.py
|
||||
```
|
||||
|
||||
若页面出现 MFA、验证码或 SSO 二次确认,worker 会失败并回调错误,需要人工处理后重试。
|
||||
|
||||
@@ -75,7 +102,7 @@ python scripts/rpa/freight_rpa_worker.py
|
||||
| source_type | Driver |
|
||||
|-------------|--------|
|
||||
| `dsv360` | 打开 DSV 360,进入 Reports / Program / Inventory 报表并下载 |
|
||||
| `crane_footprint` | 打开 Crane FootPrint On Hand Details Query,选择 Owner/Project/Warehouse 后下载 |
|
||||
| `crane_footprint` | 打开 On Hand Details Query → Run Report → Schedule Report → Scheduled Reports 下载 |
|
||||
|
||||
### 批量库存导出(`inventory_export_batch`)
|
||||
|
||||
@@ -86,11 +113,11 @@ python scripts/rpa/freight_rpa_worker.py
|
||||
"action": "inventory_export_batch",
|
||||
"run_no": "RUN20260707030000",
|
||||
"trigger_type": "scheduled",
|
||||
"inventory_sources": [{ "source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU" }]
|
||||
"inventory_sources": [{ "source_code": "DSV360_AWSBI_BYAWSATL01", "source_type": "dsv360", "site_id": "AWSBI", "warehouse_id": "BYAWSATL01" }]
|
||||
}
|
||||
```
|
||||
|
||||
Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Crane 一次登录**循环各 Warehouse;完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。
|
||||
Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,DSV source 必须包含 `site_id`(如 `AWSBI` / `AWSDBU`),部分站点还需要具体 `warehouse_id`;**Crane 一次登录**循环导出,Crane 不要求 `site_id` 或 `warehouse_id`。无 `site_id` 时,后端会从实际库存 Excel 的 Warehouse ID 列提取发货 Excel 要写入的 Warehouse ID。完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。
|
||||
|
||||
库存源定义见 `backend/config/shipping_inventory_sources.yaml`(新增 Warehouse 只改 YAML)。
|
||||
|
||||
@@ -104,11 +131,23 @@ Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Cr
|
||||
| `FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR` | DSV On Hand Inventory by Location |
|
||||
| `FREIGHT_RPA_DSV_OWNER_SELECTOR` | DSV Owner 输入框 |
|
||||
| `FREIGHT_RPA_DSV_EXPORT_SELECTOR` | DSV 导出按钮 |
|
||||
| `FREIGHT_RPA_CRANE_OWNER_SELECTOR` | Crane Owner 下拉/输入 |
|
||||
| `FREIGHT_RPA_CRANE_PROJECT_SELECTOR` | Crane Project 下拉/输入 |
|
||||
| `FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR` | Crane Warehouse 下拉/输入 |
|
||||
| `FREIGHT_RPA_CRANE_RUN_SELECTOR` | Crane Run Report 按钮 |
|
||||
| `FREIGHT_RPA_CRANE_EXPORT_SELECTOR` | Crane 下载按钮 |
|
||||
| `FREIGHT_RPA_CRANE_RUN_SELECTOR` | Crane Run Report 按钮(默认 `button.button.is-primary:has-text("Run Report")`) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULE_REPORT_SELECTOR` | Crane Schedule Report 按钮(默认 `button:has-text("Schedule Report")`) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_SELECTOR` | Schedule Report 弹窗 Description 输入框 |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULE_OK_SELECTOR` | Schedule Report 弹窗 Ok 按钮 |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION` | 覆盖自动生成的 Description |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN` | Description 十六进制长度(默认 **12**,范围 8~32) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_SELECTOR` | Crane Scheduled Reports 入口(默认 `a.has-link[href="#/scheduled-reports"]`) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_DOWNLOAD_SELECTOR` | Scheduled Reports 列表中的下载按钮 |
|
||||
| `FREIGHT_RPA_CRANE_SUBMISSION_COMPLETE_WAIT_MS` | 等待 Report Submitted 提示消失的最长时间(默认 120000) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_TABLE_SELECTOR` | Scheduled Reports 表格行选择器 |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_REPORT_NAME` | Scheduled Reports 目标文件名(Name 列,默认 `OnHandDetails.xlsx`) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_REPORT_WAIT_MS` | 等待列表行 Submitted→Download 的最长时间(默认 300000) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_REPORT_POLL_SECONDS` | 轮询 Scheduled Reports 间隔秒数(默认 3) |
|
||||
| `FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_URL` | Scheduled Reports 页面 URL(默认由当前站点 hash 推导) |
|
||||
| `FREIGHT_RPA_CRANE_OWNER_SELECTOR` | Crane Owner 下拉/输入(可选) |
|
||||
| `FREIGHT_RPA_CRANE_PROJECT_SELECTOR` | Crane Project 下拉/输入(可选) |
|
||||
| `FREIGHT_RPA_CRANE_EXPORT_SELECTOR` | Crane 直出下载按钮(仅 `download_mode: file_download` 时使用) |
|
||||
|
||||
发货 Excel 上传仍保留原 PoC 行为:`FREIGHT_RPA_MOCK=false` 时不会自动上传,需后续实现上传 Driver 或接入 UiPath / Power Automate。
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
scripts/rpa/crane_export_smoke.py
|
||||
|
||||
用途:本地手动验证 Crane CRANE 库存源浏览器导出全流程。
|
||||
依赖:Playwright、FREIGHT_RPA_CRANE_USERNAME/PASSWORD、shipping_inventory_sources.yaml。
|
||||
逻辑:加载 CRANE rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
|
||||
|
||||
用法(仓库根目录):
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_export_smoke.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_worker():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_export_smoke", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _build_source_from_config(source_code: str = "CRANE") -> dict:
|
||||
"""
|
||||
从 YAML 构造 worker 兼容的 rpa_inventory_source。
|
||||
核心逻辑:Crane 走 scheduled_report 异步导出,不依赖 warehouse_id。
|
||||
"""
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml"
|
||||
payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
raw = next(
|
||||
(
|
||||
item
|
||||
for item in (payload.get("sources") or [])
|
||||
if str(item.get("source_code") or "").upper() == source_code.upper()
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not raw:
|
||||
raise RuntimeError(f"source_code not found in config: {source_code}")
|
||||
|
||||
return {
|
||||
"source_code": str(raw.get("source_code") or source_code).upper(),
|
||||
"source_type": str(raw.get("source_type") or "crane_footprint").strip().lower(),
|
||||
"display_name": str(raw.get("display_name") or source_code),
|
||||
"enabled": bool(raw.get("enabled", True)),
|
||||
"entry_url": str(raw.get("entry_url") or "https://wms-portal.craneww.com/#/on-hand-details-query"),
|
||||
"navigation": dict(raw.get("navigation") or {}),
|
||||
"parameters": [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)],
|
||||
"query": {},
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
source_code = (sys.argv[1] if len(sys.argv) > 1 else "CRANE").strip().upper()
|
||||
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
|
||||
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
|
||||
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
|
||||
os.environ.setdefault(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||||
"backend/data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
|
||||
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
|
||||
|
||||
worker = _load_worker()
|
||||
if not worker._env("FREIGHT_RPA_CRANE_USERNAME") or not worker._env("FREIGHT_RPA_CRANE_PASSWORD"):
|
||||
print("[crane-export-smoke] 缺少 FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD")
|
||||
return 1
|
||||
|
||||
source = _build_source_from_config(source_code)
|
||||
task_no = f"SIF-SMOKE-{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
||||
trigger = {
|
||||
"action": "inventory_export",
|
||||
"task_no": task_no,
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
"mode": "smoke",
|
||||
"attempt": 1,
|
||||
"rpa_inventory_source": source,
|
||||
}
|
||||
drop_dir = Path(tempfile.mkdtemp(prefix=f"crane_export_{source_code.lower()}_"))
|
||||
|
||||
print(f"[crane-export-smoke] source={source_code}")
|
||||
print(f"[crane-export-smoke] navigation={json.dumps(source.get('navigation') or {}, ensure_ascii=False)}")
|
||||
print(f"[crane-export-smoke] drop_dir={drop_dir}")
|
||||
print("[crane-export-smoke] 正在打开浏览器执行登录 + Run Report + Schedule 异步导出(预计 3~8 分钟)…")
|
||||
|
||||
try:
|
||||
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
|
||||
size_kb = out_file.stat().st_size / 1024
|
||||
print(f"[crane-export-smoke] SUCCESS — {out_file} ({size_kb:.1f} KB)")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[crane-export-smoke] FAILED — {exc}")
|
||||
traceback.print_exc()
|
||||
print("[crane-export-smoke] FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true,浏览器保持打开以便排查。")
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
scripts/rpa/crane_login_smoke.py
|
||||
|
||||
用途:本地手动验证 Crane FootPrint Portal 自动登录。
|
||||
依赖:Playwright、FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD。
|
||||
逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。
|
||||
|
||||
用法(仓库根目录):
|
||||
$env:FREIGHT_RPA_HEADLESS = "false"
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_login_smoke.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
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)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def main() -> int:
|
||||
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
|
||||
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
|
||||
os.environ.setdefault(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||||
"backend/data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
|
||||
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
|
||||
|
||||
worker = _load_worker()
|
||||
username = worker._env("FREIGHT_RPA_CRANE_USERNAME")
|
||||
password = worker._env("FREIGHT_RPA_CRANE_PASSWORD")
|
||||
if not username or not password:
|
||||
print("[crane-smoke] 缺少 FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD,请先配置环境变量。")
|
||||
return 1
|
||||
|
||||
entry_url = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
drop_dir = Path(tempfile.mkdtemp(prefix="crane_smoke_drop_"))
|
||||
playwright = context = runtime_profile_dir = None
|
||||
|
||||
print(f"[crane-smoke] headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}")
|
||||
print(f"[crane-smoke] user={username[:3]}*** entry={entry_url}")
|
||||
print("[crane-smoke] 正在打开浏览器并执行 Crane 自动登录…")
|
||||
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
|
||||
worker._ensure_crane_session(page, entry_url)
|
||||
print(f"[crane-smoke] SUCCESS — Crane session ready, url={page.url}")
|
||||
print("[crane-smoke] 请在浏览器中确认 On Hand Details Query 表单可见。按 Enter 关闭浏览器…")
|
||||
try:
|
||||
input()
|
||||
except EOFError:
|
||||
import time
|
||||
|
||||
print("[crane-smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
|
||||
time.sleep(300)
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[crane-smoke] FAILED — {exc}")
|
||||
traceback.print_exc()
|
||||
print("[crane-smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
|
||||
try:
|
||||
input()
|
||||
except EOFError:
|
||||
import time
|
||||
|
||||
time.sleep(120)
|
||||
return 2
|
||||
finally:
|
||||
if context is not None:
|
||||
try:
|
||||
context.close()
|
||||
except Exception:
|
||||
pass
|
||||
if playwright is not None:
|
||||
try:
|
||||
playwright.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
shutil.rmtree(drop_dir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,410 @@
|
||||
"""
|
||||
scripts/rpa/crane_navigation.py
|
||||
|
||||
用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。
|
||||
依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。
|
||||
逻辑:优先点击首页 Queries 区 On Hand Details 卡片;失败再走顶部 Queries 下拉菜单;最后 goto entry_url。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
_ON_HAND_DETAILS_LABEL = "On Hand Details"
|
||||
_ON_HAND_DETAILS_ROUTE = "on-hand-details-query"
|
||||
|
||||
# 首页 Queries 区大卡片:Vue hash 路由常见 href="#/on-hand-details-query"(非 "/on-hand-details-query")
|
||||
_CRANE_DASHBOARD_REPORT_TILE_SELECTORS: tuple[str, ...] = (
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'a.box[href*="on-hand-details-query"]',
|
||||
'a.box.has-text-centered[href*="on-hand-details-query"]',
|
||||
'a.box:has-text("On Hand Details")',
|
||||
'a:has-text("On Hand Details")',
|
||||
'.box:has-text("On Hand Details")',
|
||||
)
|
||||
|
||||
# 顶部导航 Queries 下拉(第二张图)
|
||||
_CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = (
|
||||
'a.navbar-link:has-text("Queries")',
|
||||
'.navbar-item.has-dropdown > a.navbar-link',
|
||||
)
|
||||
|
||||
_CRANE_NAV_ON_HAND_DETAILS_SELECTORS: tuple[str, ...] = (
|
||||
'.navbar-dropdown a.navbar-item:has-text("On Hand Details")',
|
||||
'a.navbar-item:has-text("On Hand Details")',
|
||||
)
|
||||
|
||||
# 报表表单就绪信号:必须出现 Run Report 或报表参数字段;首页 Queries 区标题不算 ready
|
||||
_CRANE_REPORT_FORM_READY_SELECTORS: tuple[str, ...] = (
|
||||
'button:has-text("Run Report")',
|
||||
'[role="button"]:has-text("Run Report")',
|
||||
'text=Choose Warehouse',
|
||||
'text=Select Owner',
|
||||
)
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str) -> Any | None:
|
||||
"""在 page 与各 frame 中查找首个可见 locator。"""
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.is_visible(timeout=500):
|
||||
return locator
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _report_route_from_entry_url(entry_url: str) -> str:
|
||||
"""从 entry_url hash 提取报表路由片段,默认 on-hand-details-query。"""
|
||||
parsed = urlparse(str(entry_url or "").strip())
|
||||
fragment = (parsed.fragment or "").strip().lstrip("/").lower()
|
||||
if fragment:
|
||||
return fragment
|
||||
return _ON_HAND_DETAILS_ROUTE
|
||||
|
||||
|
||||
def _current_url_fragment(page: Any) -> str:
|
||||
"""读取当前页 URL hash 片段(不含 #/ 前缀)。"""
|
||||
try:
|
||||
current_url = str(page.url or "")
|
||||
except Exception:
|
||||
return ""
|
||||
parsed = urlparse(current_url)
|
||||
return (parsed.fragment or "").strip().lstrip("/").lower()
|
||||
|
||||
|
||||
def is_crane_on_homepage(page: Any) -> bool:
|
||||
"""
|
||||
判定是否停在 Crane 登录后首页(/#/ 或空 hash)。
|
||||
核心逻辑:首页 Queries 区有 On Hand Details 卡片,但报表表单尚未打开,不能视为 ready。
|
||||
"""
|
||||
fragment = _current_url_fragment(page)
|
||||
if not fragment or fragment in {"home", "dashboard", "index"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def is_crane_on_report_route(page: Any, entry_url: str) -> bool:
|
||||
"""当前 URL hash 是否已落在目标报表路由。"""
|
||||
target_route = _report_route_from_entry_url(entry_url)
|
||||
fragment = _current_url_fragment(page)
|
||||
if not fragment:
|
||||
return False
|
||||
return target_route in fragment
|
||||
|
||||
|
||||
def _has_report_form_controls(page: Any) -> bool:
|
||||
"""Run Report 或报表参数字段是否可见。"""
|
||||
for selector in _CRANE_REPORT_FORM_READY_SELECTORS:
|
||||
if _visible_locator(page, selector) is not None:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def is_crane_report_form_ready(page: Any, entry_url: str) -> bool:
|
||||
"""
|
||||
判定 On Hand Details Query 报表表单是否已就绪。
|
||||
核心逻辑:首页 /#/ 不算 ready;必须 hash 落在报表路由且出现 Run Report / 参数字段。
|
||||
"""
|
||||
if is_crane_on_homepage(page):
|
||||
return False
|
||||
if not is_crane_on_report_route(page, entry_url):
|
||||
return False
|
||||
return _has_report_form_controls(page)
|
||||
|
||||
|
||||
def _click_visible_locator(locator: Any, *, browser_timeout_ms: int) -> bool:
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms, force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_crane_homepage_ready(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
"""
|
||||
登录后等待首页 Queries 区渲染完成。
|
||||
核心逻辑:On Hand Details 卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。
|
||||
"""
|
||||
deadline = time.monotonic() + (min(browser_timeout_ms, 20_000) / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for selector in (
|
||||
'text=On Hand Details',
|
||||
'text=Queries',
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'.box:has-text("On Hand Details")',
|
||||
):
|
||||
if _visible_locator(page, selector) is not None:
|
||||
print("[crane-nav] homepage shell ready")
|
||||
return True
|
||||
time.sleep(0.25)
|
||||
print("[crane-nav] homepage shell not detected before timeout", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def _click_by_role_link(page: Any, name: str, *, browser_timeout_ms: int) -> bool:
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_role("link", name=name, exact=False).first
|
||||
if locator.is_visible(timeout=500):
|
||||
return _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
"""
|
||||
通过文本语义点击首页 Queries 区的 On Hand Details 卡片。
|
||||
核心逻辑:hash 路由下 tile 可能是 a[href*=#/on-hand-details-query] 或 .box 包裹的 router-link。
|
||||
"""
|
||||
tile_selectors = (
|
||||
'.columns .box:has-text("On Hand Details")',
|
||||
'section:has-text("Queries") .box:has-text("On Hand Details")',
|
||||
'.box:has-text("On Hand Details")',
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'[class*="box"]:has-text("On Hand Details")',
|
||||
)
|
||||
for selector in tile_selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked On Hand Details tile selector={selector!r}")
|
||||
return True
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_role("link", name=_ON_HAND_DETAILS_LABEL, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _click_visible_locator(
|
||||
locator, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print("[crane-nav] clicked On Hand Details tile via link role")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_text(_ON_HAND_DETAILS_LABEL, exact=False).first
|
||||
if not locator.is_visible(timeout=500):
|
||||
continue
|
||||
for candidate in (
|
||||
locator.locator("xpath=ancestor-or-self::a[1]"),
|
||||
locator.locator("xpath=ancestor-or-self::*[contains(@class,'box')][1]"),
|
||||
locator,
|
||||
):
|
||||
try:
|
||||
target = candidate.first
|
||||
if target.is_visible(timeout=300) and _click_visible_locator(
|
||||
target, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print("[crane-nav] clicked On Hand Details tile via text locator")
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_dashboard_on_hand_details(
|
||||
page: Any,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
点击首页 Queries 区域的 On Hand Details 卡片(优先策略)。
|
||||
核心逻辑:先文本语义定位 tile,再匹配 href*=on-hand-details-query 的 hash 路由链接。
|
||||
"""
|
||||
if _click_on_hand_details_tile(page, browser_timeout_ms=browser_timeout_ms):
|
||||
return True
|
||||
|
||||
selectors = tuple(
|
||||
item
|
||||
for item in (env("FREIGHT_RPA_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS)
|
||||
if item
|
||||
)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked dashboard tile selector={selector!r}")
|
||||
return True
|
||||
|
||||
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] clicked dashboard tile via link role")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool:
|
||||
"""展开顶部 Queries 下拉菜单。"""
|
||||
selectors = tuple(
|
||||
item for item in (env("FREIGHT_RPA_CRANE_NAV_QUERIES_SELECTOR"), *_CRANE_NAV_QUERIES_MENU_SELECTORS) if item
|
||||
)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is None:
|
||||
continue
|
||||
try:
|
||||
locator.hover(timeout=min(browser_timeout_ms, 5_000))
|
||||
except Exception:
|
||||
pass
|
||||
if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] opened Queries menu selector={selector!r}")
|
||||
return True
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_role("link", name="Queries", exact=False).first
|
||||
if not locator.is_visible(timeout=500):
|
||||
continue
|
||||
try:
|
||||
locator.hover(timeout=3_000)
|
||||
except Exception:
|
||||
pass
|
||||
if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] opened Queries menu via link role")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_navbar_on_hand_details(
|
||||
page: Any,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
通过顶部 Queries 下拉进入 On Hand Details(回退策略)。
|
||||
核心逻辑:先展开 Queries navbar-dropdown,再点 a.navbar-item On Hand Details。
|
||||
"""
|
||||
if not _open_queries_nav_menu(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] Queries navbar menu not opened", file=sys.stderr)
|
||||
return False
|
||||
|
||||
time.sleep(0.35)
|
||||
selectors = tuple(
|
||||
item for item in (env("FREIGHT_RPA_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item
|
||||
)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked navbar item selector={selector!r}")
|
||||
return True
|
||||
|
||||
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] clicked navbar On Hand Details via link role")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_report_navigation(
|
||||
page: Any,
|
||||
entry_url: str,
|
||||
*,
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""点击导航后短等待目标路由或表单控件出现。"""
|
||||
deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if is_crane_report_form_ready(page, entry_url):
|
||||
return True
|
||||
time.sleep(0.25)
|
||||
return False
|
||||
|
||||
|
||||
def _navigate_hash_route(page: Any, entry_url: str, *, browser_timeout_ms: int) -> None:
|
||||
"""
|
||||
通过 goto + hash 赋值进入 SPA 报表路由。
|
||||
核心逻辑:登录后常落在 /#/ 首页,仅 goto 完整 entry_url 时 Vue 路由可能不切换。
|
||||
"""
|
||||
target = str(entry_url or "").strip()
|
||||
if not target:
|
||||
raise RuntimeError("Crane report navigation failed: entry_url is empty")
|
||||
|
||||
route = _report_route_from_entry_url(entry_url)
|
||||
parsed = urlparse(target)
|
||||
base_url = f"{parsed.scheme}://{parsed.netloc}/"
|
||||
|
||||
print(f"[crane-nav] fallback direct goto entry_url={target!r}")
|
||||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
if is_crane_on_report_route(page, entry_url) and _has_report_form_controls(page):
|
||||
return
|
||||
|
||||
print(f"[crane-nav] assigning hash route via SPA base={base_url!r} route={route!r}")
|
||||
try:
|
||||
page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
page.evaluate(
|
||||
"""
|
||||
(route) => {
|
||||
const hash = route.startsWith('/') ? route : `/${route}`;
|
||||
if (window.location.hash !== `#${hash}`) {
|
||||
window.location.hash = hash;
|
||||
}
|
||||
}
|
||||
""",
|
||||
route,
|
||||
)
|
||||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
print(f"[crane-nav] hash route assignment failed: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
def navigate_to_crane_report(
|
||||
page: Any,
|
||||
entry_url: str,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> str:
|
||||
"""
|
||||
导航至 On Hand Details Query 报表页。
|
||||
核心逻辑:[STEP 1] 首页卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] 直接 goto entry_url。
|
||||
|
||||
Returns:
|
||||
使用的导航模式:`already_ready` | `dashboard_tile` | `navbar_menu` | `direct_goto`。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 三种方式均未能进入报表表单。
|
||||
"""
|
||||
if is_crane_report_form_ready(page, entry_url):
|
||||
print("[crane-nav] report form already ready, skip navigation")
|
||||
return "already_ready"
|
||||
|
||||
_wait_for_crane_homepage_ready(page, browser_timeout_ms=browser_timeout_ms)
|
||||
|
||||
# [STEP 1] 首页 Queries 区 On Hand Details 卡片
|
||||
if _click_dashboard_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "dashboard_tile"
|
||||
print("[crane-nav] dashboard tile click did not reach report form, trying navbar", file=sys.stderr)
|
||||
|
||||
# [STEP 2] 顶部 Queries → On Hand Details
|
||||
if _click_navbar_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "navbar_menu"
|
||||
print("[crane-nav] navbar navigation did not reach report form, trying direct goto", file=sys.stderr)
|
||||
|
||||
# [STEP 3] 直接打开配置的 entry_url(hash 路由)
|
||||
_navigate_hash_route(page, entry_url, browser_timeout_ms=browser_timeout_ms)
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "direct_goto"
|
||||
|
||||
raise RuntimeError(
|
||||
"Crane report navigation failed: dashboard tile, navbar menu, and direct goto did not reach report form"
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,382 @@
|
||||
"""
|
||||
scripts/rpa/crane_session.py
|
||||
|
||||
用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。
|
||||
依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。
|
||||
逻辑:识别登录页并自动填写;登录后委托 navigate_to_crane_report 进入 On Hand Details Query。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# Crane FootPrint 登录页(Bulma 表单)实测控件;用户名无 name 属性,靠 placeholder/label 定位。
|
||||
_CRANE_USERNAME_SELECTORS: tuple[str, ...] = (
|
||||
'input[placeholder="Enter user name..."]',
|
||||
'input[placeholder*="user name" i]',
|
||||
'form input.input[type="text"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="username"]',
|
||||
)
|
||||
|
||||
_CRANE_PASSWORD_SELECTORS: tuple[str, ...] = (
|
||||
'input[placeholder="Enter password..."]',
|
||||
'input.input.is-small.p-2.mt-1[type="password"]',
|
||||
'input[placeholder*="password" i]',
|
||||
'form input.input[type="password"]',
|
||||
'input[type="password"]',
|
||||
)
|
||||
|
||||
_CRANE_LOGIN_SUBMIT_SELECTORS: tuple[str, ...] = (
|
||||
'button.button.is-primary:has-text("Sign in")',
|
||||
'form button.button.is-primary',
|
||||
'button.button.is-primary',
|
||||
)
|
||||
|
||||
_CRANE_LOGIN_SUBMIT_TEXTS: tuple[str, ...] = ("Sign in", "Login", "Log in", "登录")
|
||||
|
||||
|
||||
def _load_crane_navigation_module() -> Any:
|
||||
"""运行时加载 crane_navigation,避免与 crane_session 循环 import。"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
module_path = Path(__file__).resolve().parent / "crane_navigation.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_navigation_runtime", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str) -> Any | None:
|
||||
"""在 page 与各 frame 中查找首个可见 locator。"""
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.is_visible(timeout=500):
|
||||
return locator
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _dispatch_input_events(locator: Any) -> None:
|
||||
"""触发 input/change 事件,驱动 Vue 表单解除 Sign in 按钮 disabled。"""
|
||||
try:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
node.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
node.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _fill_visible_locator(locator: Any, value: str, *, browser_timeout_ms: int) -> bool:
|
||||
"""向已定位控件写入文本,并触发前端校验以启用 Sign in。"""
|
||||
try:
|
||||
locator.fill(value, timeout=browser_timeout_ms)
|
||||
_dispatch_input_events(locator)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=3_000)
|
||||
locator.press("Control+A")
|
||||
locator.press("Backspace")
|
||||
locator.type(value, delay=30)
|
||||
_dispatch_input_events(locator)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_crane_button_enabled(locator: Any) -> bool:
|
||||
"""Sign in 初始为 disabled,需等用户名/密码填写后解除。"""
|
||||
try:
|
||||
return bool(
|
||||
locator.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
if (!node) return false;
|
||||
const disabled = Boolean(node.disabled);
|
||||
const ariaDisabled = String(node.getAttribute('aria-disabled') || '').toLowerCase() === 'true';
|
||||
const classDisabled = node.classList && node.classList.contains('is-disabled');
|
||||
return !disabled && !ariaDisabled && !classDisabled;
|
||||
}
|
||||
"""
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return locator.is_enabled(timeout=500)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_crane_sign_in_button(
|
||||
page: Any,
|
||||
*,
|
||||
selector_env: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> Any | None:
|
||||
"""
|
||||
查找已启用的 Sign in 按钮。
|
||||
核心逻辑:页面按钮 class 为 button is-primary,填写凭据前带 disabled 属性。
|
||||
"""
|
||||
selectors = tuple(
|
||||
item
|
||||
for item in (env(selector_env), *_CRANE_LOGIN_SUBMIT_SELECTORS, 'button[type="submit"]')
|
||||
if item
|
||||
)
|
||||
deadline = time.monotonic() + (browser_timeout_ms / 1000)
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _is_crane_button_enabled(locator):
|
||||
return locator
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
for text in _CRANE_LOGIN_SUBMIT_TEXTS:
|
||||
try:
|
||||
locator = root.get_by_role("button", name=text, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _is_crane_button_enabled(locator):
|
||||
return locator
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.25)
|
||||
|
||||
# 最后再试一次可见按钮(部分环境 disabled 属性更新滞后,但 click 仍有效)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
return locator
|
||||
return None
|
||||
|
||||
|
||||
def _fill_crane_field(
|
||||
page: Any,
|
||||
*,
|
||||
selector_env: str,
|
||||
value: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
fallback_selectors: tuple[str, ...],
|
||||
label: str | None = None,
|
||||
placeholder: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
填写 Crane 登录字段。
|
||||
核心逻辑:优先环境变量 selector,再试页面实测 fallback,最后用 label/placeholder 语义定位。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
|
||||
selectors = tuple(item for item in (env(selector_env), *fallback_selectors) if item)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _fill_visible_locator(locator, text, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-login] filled field via selector={selector!r}")
|
||||
return True
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
if label:
|
||||
try:
|
||||
locator = root.get_by_label(label, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _fill_visible_locator(
|
||||
locator, text, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print(f"[crane-login] filled field via label={label!r}")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
if placeholder:
|
||||
try:
|
||||
locator = root.get_by_placeholder(placeholder, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _fill_visible_locator(
|
||||
locator, text, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print(f"[crane-login] filled field via placeholder={placeholder!r}")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_crane_login_submit(
|
||||
page: Any,
|
||||
*,
|
||||
selector_env: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
点击 Crane Sign in 按钮。
|
||||
核心逻辑:等待 button.button.is-primary 解除 disabled 后再点击。
|
||||
"""
|
||||
locator = _find_crane_sign_in_button(
|
||||
page,
|
||||
selector_env=selector_env,
|
||||
env=env,
|
||||
browser_timeout_ms=min(browser_timeout_ms, 15_000),
|
||||
)
|
||||
if locator is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms, force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def is_crane_login_page(page: Any) -> bool:
|
||||
"""当前页是否为 Crane FootPrint 登录表单。"""
|
||||
for selector in (
|
||||
'input[placeholder="Enter user name..."]',
|
||||
'input[placeholder="Enter password..."]',
|
||||
):
|
||||
if _visible_locator(page, selector) is not None:
|
||||
return True
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
if root.get_by_label("User Name", exact=False).first.is_visible(timeout=500):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _crane_entry_host(entry_url: str) -> str:
|
||||
"""从 entry_url 提取 host。"""
|
||||
parsed = urlparse(str(entry_url or "").strip())
|
||||
return (parsed.netloc or "").lower()
|
||||
|
||||
|
||||
def is_crane_session_active(page: Any, entry_url: str) -> bool:
|
||||
"""
|
||||
判定浏览器是否已在 Crane portal 维持有效登录态。
|
||||
核心逻辑:仍在 craneww 域且不再显示登录表单,即视为 session 有效。
|
||||
"""
|
||||
host = _crane_entry_host(entry_url)
|
||||
if not host:
|
||||
return False
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
if host not in current_url:
|
||||
return False
|
||||
if is_crane_login_page(page):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def wait_for_crane_app_ready(
|
||||
page: Any,
|
||||
entry_url: str,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> None:
|
||||
"""
|
||||
登录后导航并等待 Crane 报表表单就绪。
|
||||
核心逻辑:先 navigate_to_crane_report(首页卡片 → 顶部菜单 → goto),再轮询表单控件。
|
||||
"""
|
||||
navigation = _load_crane_navigation_module()
|
||||
mode = navigation.navigate_to_crane_report(
|
||||
page,
|
||||
entry_url,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
)
|
||||
print(f"[crane-nav] navigation mode={mode!r}")
|
||||
|
||||
deadline = time.monotonic() + (browser_timeout_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if navigation.is_crane_report_form_ready(page, entry_url):
|
||||
print("[crane-login] report form ready")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
|
||||
raise RuntimeError("Crane report form did not become ready after navigation; check selectors or permissions")
|
||||
|
||||
|
||||
def maybe_auto_login_crane(
|
||||
page: Any,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> None:
|
||||
"""
|
||||
Crane FootPrint 自动登录:User Name → Password → Sign in。
|
||||
核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。
|
||||
"""
|
||||
username = env("FREIGHT_RPA_CRANE_USERNAME")
|
||||
password = env("FREIGHT_RPA_CRANE_PASSWORD")
|
||||
if not username or not password:
|
||||
return
|
||||
|
||||
if not is_crane_login_page(page):
|
||||
print("[crane-login] no login form detected, skip auto login")
|
||||
return
|
||||
|
||||
user_filled = _fill_crane_field(
|
||||
page,
|
||||
selector_env="FREIGHT_RPA_CRANE_USERNAME_SELECTOR",
|
||||
value=username,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
fallback_selectors=_CRANE_USERNAME_SELECTORS,
|
||||
label="User Name",
|
||||
placeholder="Enter user name...",
|
||||
)
|
||||
password_filled = _fill_crane_field(
|
||||
page,
|
||||
selector_env="FREIGHT_RPA_CRANE_PASSWORD_SELECTOR",
|
||||
value=password,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
fallback_selectors=_CRANE_PASSWORD_SELECTORS,
|
||||
label="Password",
|
||||
placeholder="Enter password...",
|
||||
)
|
||||
if not user_filled and not password_filled:
|
||||
print("[crane-login] login form visible but fields not filled", file=sys.stderr)
|
||||
return
|
||||
if user_filled != password_filled:
|
||||
raise RuntimeError("CRANE login form partially detected; please configure login selectors")
|
||||
|
||||
if not _click_crane_login_submit(
|
||||
page,
|
||||
selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
):
|
||||
raise RuntimeError("CRANE login fields detected but Sign in button was not found")
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||||
if is_crane_login_page(page):
|
||||
raise RuntimeError("CRANE login did not complete; MFA/SSO/manual verification may be required")
|
||||
|
||||
# [STEP] 登录后 Crane 常先落到 /#/ 首页,等待 SPA 壳层渲染再进入报表导航
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 15_000))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,993 @@
|
||||
"""
|
||||
scripts/rpa/dsv_auth.py
|
||||
|
||||
用途:DSV 360 PingID 分步登录(邮箱 → 密码方式 → 密码 → portal)。
|
||||
依赖:rpa_common、dsv_debug;登录主编排见 dsv_auth_login_flow。
|
||||
逻辑:由 dsv_session / dsv_report_export 在 ensure session 时调用 maybe_auto_login_dsv。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
from dsv_debug import (
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
debug_dsv_stage as _debug_dsv_stage,
|
||||
report_debug_event as _report_debug_event,
|
||||
report_dsv_chain_stage as _report_dsv_chain_stage,
|
||||
)
|
||||
|
||||
|
||||
def _click_dsv_password_method(page: Any) -> bool:
|
||||
def password_ready() -> bool:
|
||||
"""密码输入框已出现即视为方法页切换成功;兼容轻量探测与通用等待。"""
|
||||
if _find_dsv_password_locator(page, timeout_ms=250) is not None:
|
||||
return True
|
||||
return _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_PASSWORD_SELECTOR",
|
||||
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
|
||||
timeout_ms=250,
|
||||
) is not None
|
||||
|
||||
def transition_confirmed() -> bool:
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
if password_ready():
|
||||
return True
|
||||
if not _looks_like_dsv_login_method_page(page):
|
||||
try:
|
||||
body_text = page.locator("body").inner_text(timeout=1_000)
|
||||
except Exception:
|
||||
body_text = ""
|
||||
lowered = body_text.lower()
|
||||
looks_like_password_page = (
|
||||
("输入您的密码" in body_text or "忘记密码" in body_text or "password" in lowered)
|
||||
and "通行密钥" not in body_text
|
||||
and "passkey" not in lowered
|
||||
and "验证失败" not in body_text
|
||||
and "validation failed" not in lowered
|
||||
)
|
||||
if looks_like_password_page:
|
||||
time.sleep(0.3)
|
||||
continue
|
||||
return False
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
script_row_click = """
|
||||
() => {
|
||||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||||
const isVisible = (node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
const style = window.getComputedStyle(node);
|
||||
return !(style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0);
|
||||
};
|
||||
const isPasswordMethod = (text) => (
|
||||
(text === '密码' || text === 'Password' || text === '输入您的密码并登录。' || text.includes('输入您的密码并登录'))
|
||||
&& !text.includes('忘记密码')
|
||||
&& !text.includes('取消')
|
||||
&& !text.includes('返回')
|
||||
&& !text.includes('通行密钥')
|
||||
&& !text.includes('电子邮件验证码')
|
||||
&& !text.includes('移动应用程序')
|
||||
&& !text.toLowerCase().includes('cancel')
|
||||
&& !text.toLowerCase().includes('back')
|
||||
&& !text.toLowerCase().includes('passkey')
|
||||
);
|
||||
const rows = Array.from(document.querySelectorAll("form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2"))
|
||||
.filter((node) => isVisible(node));
|
||||
const row = rows.find((node) => isPasswordMethod(textOf(node)));
|
||||
if (!row) return false;
|
||||
const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row;
|
||||
target.scrollIntoView({ block: 'center', inline: 'center' });
|
||||
if (target.tagName === 'FORM') {
|
||||
if (typeof target.requestSubmit === 'function') target.requestSubmit();
|
||||
else target.submit();
|
||||
return true;
|
||||
}
|
||||
if (typeof target.click === 'function') target.click();
|
||||
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
|
||||
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
"""
|
||||
for frame in page.frames:
|
||||
try:
|
||||
_clicked = frame.evaluate(script_row_click)
|
||||
if _clicked and transition_confirmed():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
rows = page.locator("form[name='mfaForm'] li.mb-2").all()
|
||||
for row in rows:
|
||||
text = row.inner_text(timeout=1_000)
|
||||
lowered = text.lower()
|
||||
if ("密码" in text or "Password" in text) and "忘记密码" not in text and "取消" not in text and "返回" not in text and "cancel" not in lowered and "back" not in lowered:
|
||||
row.scroll_into_view_if_needed(timeout=3_000)
|
||||
try:
|
||||
row.click(timeout=3_000, force=True)
|
||||
except Exception:
|
||||
row.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
if (typeof node.click === 'function') node.click();
|
||||
node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
""",
|
||||
timeout=2_000,
|
||||
)
|
||||
if transition_confirmed():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def _submit_dsv_username_form(username_locator: Any) -> bool:
|
||||
try:
|
||||
return bool(
|
||||
username_locator.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
const form = node.closest('form');
|
||||
if (!form) return false;
|
||||
if (typeof form.requestSubmit === 'function') {
|
||||
form.requestSubmit();
|
||||
} else {
|
||||
form.submit();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
""",
|
||||
timeout=2_000,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _click_dsv_continue(page: Any, username_locator: Any | None = None) -> bool:
|
||||
if username_locator is not None:
|
||||
if _submit_dsv_username_form(username_locator):
|
||||
return True
|
||||
try:
|
||||
username_locator.press("Enter", timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for selector in (
|
||||
'button:has-text("继续")',
|
||||
'button:has-text("Continue")',
|
||||
'input[value="继续"]',
|
||||
'input[value="Continue"]',
|
||||
'[role="button"]:has-text("继续")',
|
||||
'[role="button"]:has-text("Continue")',
|
||||
'a:has-text("继续")',
|
||||
'a:has-text("Continue")',
|
||||
'.dbs-sims-button-primary',
|
||||
'button[type="submit"]',
|
||||
'input[type="submit"]',
|
||||
):
|
||||
for frame in page.frames:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
try:
|
||||
locator.click(timeout=1_000)
|
||||
except Exception:
|
||||
locator.click(timeout=1_000, force=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for frame in page.frames:
|
||||
try:
|
||||
identifier = frame.locator("input#identifier").first
|
||||
identifier.wait_for(state="attached", timeout=1_000)
|
||||
identifier.press("Enter", timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
script = """
|
||||
() => {
|
||||
const candidates = Array.from(document.querySelectorAll('body *')).filter((node) => {
|
||||
const style = window.getComputedStyle(node);
|
||||
const rect = node.getBoundingClientRect();
|
||||
return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
|
||||
});
|
||||
const label = candidates.find((node) => {
|
||||
const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
return text === '继续' || text === 'Continue' || text.includes('继续') || text.includes('Continue');
|
||||
});
|
||||
const target = label && (label.closest('button, input, a, [role="button"], .dbs-sims-button-primary, [onclick], form') || label);
|
||||
if (!target) return false;
|
||||
target.scrollIntoView({ block: 'center', inline: 'center' });
|
||||
if (target.tagName === 'FORM') {
|
||||
if (typeof target.requestSubmit === 'function') target.requestSubmit();
|
||||
else target.submit();
|
||||
return true;
|
||||
}
|
||||
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
|
||||
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
"""
|
||||
for frame in page.frames:
|
||||
try:
|
||||
if frame.evaluate(script):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_locator_can_edit(locator: Any) -> bool:
|
||||
try:
|
||||
if locator.is_editable(timeout=1_000):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return bool(
|
||||
locator.evaluate(
|
||||
"(node) => !node.disabled && !node.readOnly && node.getAttribute('aria-disabled') !== 'true'",
|
||||
timeout=1_000,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_username_has_value(locator: Any) -> bool:
|
||||
for _ in range(5):
|
||||
try:
|
||||
if locator.input_value(timeout=1_000).strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
|
||||
_DSV_MAYBE_LATER_SELECTORS: tuple[str, ...] = (
|
||||
'button.dbs-sims-button-secondary:has-text("也许以后")',
|
||||
'button.dbs-sims-button-secondary:has-text("Maybe later")',
|
||||
'button.dbs-sims-button-secondary:has-text("Maybe Later")',
|
||||
'button.dbs-sims-button-secondary:has-text("Not now")',
|
||||
'button.dbs-sims-button-secondary:has-text("Not Now")',
|
||||
'button:has-text("也许以后")',
|
||||
'a:has-text("也许以后")',
|
||||
'[role="button"]:has-text("也许以后")',
|
||||
'text=也许以后',
|
||||
'button:has-text("Maybe later")',
|
||||
'button:has-text("Maybe Later")',
|
||||
'a:has-text("Maybe later")',
|
||||
'a:has-text("Maybe Later")',
|
||||
'[role="button"]:has-text("Maybe later")',
|
||||
'[role="button"]:has-text("Maybe Later")',
|
||||
'text=Maybe later',
|
||||
'text=Maybe Later',
|
||||
'button:has-text("Not now")',
|
||||
'button:has-text("Not Now")',
|
||||
'a:has-text("Not now")',
|
||||
'a:has-text("Not Now")',
|
||||
'text=Not now',
|
||||
'text=Not Now',
|
||||
)
|
||||
|
||||
_DSV_PASSWORD_UPGRADE_PROMPT_MARKERS: tuple[str, ...] = (
|
||||
"使用密码升级登录",
|
||||
"升级登录",
|
||||
"password upgrade",
|
||||
"upgrade your sign-in",
|
||||
"sign in with a passkey",
|
||||
"passkey",
|
||||
)
|
||||
|
||||
|
||||
def _dsv_maybe_later_selector_candidates() -> tuple[str, ...]:
|
||||
"""返回“也许以后 / Maybe later”按钮候选选择器;支持 FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR 覆盖。"""
|
||||
selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR")
|
||||
return (selector,) if selector else _DSV_MAYBE_LATER_SELECTORS
|
||||
|
||||
|
||||
def _is_dsv_password_upgrade_redirect(page: Any) -> bool:
|
||||
"""
|
||||
判断是否处在点击登录后的密码升级提示地址。
|
||||
|
||||
核心逻辑:只有 `auth.dbschenker.com/.../resume/as/authorization.ping` 才需要点击
|
||||
“也许以后”;如果登录直接进入 s360 portal,则不做升级提示处理。
|
||||
"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
return "auth.dbschenker.com" in current_url and "/resume/as/authorization.ping" in current_url
|
||||
|
||||
|
||||
def _portal_home_nav_already_usable(page: Any) -> bool:
|
||||
"""
|
||||
判断 s360 portal 首页导航是否已可操作。
|
||||
|
||||
核心逻辑:仅在 Reports 顶栏已可用时,才跳过升级提示扫描,避免把“弹窗挡住的 portal 页”
|
||||
误判为“首页已稳定”。
|
||||
"""
|
||||
current_url = str(getattr(page, "url", "") or "").lower()
|
||||
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
|
||||
return False
|
||||
try:
|
||||
import dsv_session
|
||||
|
||||
return bool(dsv_session.has_dsv_report_nav_usable(page))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _try_click_dsv_maybe_later_via_js(root: Any) -> bool:
|
||||
"""
|
||||
通过 innerText 匹配点击“也许以后 / Maybe later”按钮。
|
||||
|
||||
核心逻辑:Playwright 选择器未命中时(class 变更、文本大小写差异),用 JS 兜底点击
|
||||
secondary 按钮,并显式跳过“立即启用 / Enable now”主按钮。
|
||||
"""
|
||||
script = """
|
||||
() => {
|
||||
const labels = ['也许以后', 'maybe later', 'not now'];
|
||||
const skipLabels = ['立即启用', 'enable now'];
|
||||
const isVisible = (node) => {
|
||||
if (!node) return false;
|
||||
const style = window.getComputedStyle(node);
|
||||
if (style.visibility === 'hidden' || style.display === 'none') return false;
|
||||
const rect = node.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
const nodes = Array.from(document.querySelectorAll('button, a, [role="button"], .dbs-sims-button-secondary, .dbs-sims-button'));
|
||||
for (const node of nodes) {
|
||||
if (!isVisible(node)) continue;
|
||||
const text = ((node.innerText || node.textContent || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
const lowered = text.toLowerCase();
|
||||
if (skipLabels.some((label) => lowered.includes(label))) continue;
|
||||
if (!labels.some((label) => lowered.includes(label))) continue;
|
||||
node.scrollIntoView({ block: 'center', inline: 'center' });
|
||||
if (typeof node.click === 'function') node.click();
|
||||
node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
"""
|
||||
try:
|
||||
return bool(root.evaluate(script, timeout=2_000))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _has_dsv_password_upgrade_prompt(page: Any, timeout_ms: int = 250) -> bool:
|
||||
"""
|
||||
快速判断 DSV 是否真的出现“也许以后 / Maybe later”升级提示。
|
||||
|
||||
核心逻辑:仅检查升级提示的强特征,不把 Verifying compliance 或普通 auth 跳转页
|
||||
误判成升级提示;portal 首页导航已可用时才跳过扫描,弹窗挡屏时仍会继续探测。
|
||||
"""
|
||||
if not _is_dsv_password_upgrade_redirect(page):
|
||||
return False
|
||||
if _portal_home_nav_already_usable(page):
|
||||
return False
|
||||
candidates = _dsv_maybe_later_selector_candidates()
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
for root in roots:
|
||||
for candidate in candidates:
|
||||
try:
|
||||
if root.locator(candidate).first.is_visible(timeout=timeout_ms):
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
body = root.locator("body").inner_text(timeout=timeout_ms).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
if any(marker.lower() in body for marker in _DSV_PASSWORD_UPGRADE_PROMPT_MARKERS):
|
||||
if any(label in body for label in ("也许以后", "maybe later", "not now")):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _debug_dsv_login_method_page(page: Any) -> str:
|
||||
snippets: list[str] = []
|
||||
for idx, frame in enumerate(page.frames):
|
||||
try:
|
||||
body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
|
||||
except Exception:
|
||||
body = ""
|
||||
try:
|
||||
candidates = frame.evaluate(
|
||||
"""
|
||||
() => Array.from(document.querySelectorAll('.device-type, .device-description, li, button, a, [role="button"]'))
|
||||
.map((node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 30)
|
||||
""",
|
||||
timeout=1_000,
|
||||
)
|
||||
except Exception:
|
||||
candidates = []
|
||||
if body or candidates:
|
||||
snippets.append(f"frame[{idx}] body={body!r} candidates={candidates!r}")
|
||||
return " | ".join(snippets)[:2000]
|
||||
|
||||
|
||||
def _fill_dsv_password_page_fields(page: Any, username: str, password: str) -> bool:
|
||||
filled_password = False
|
||||
for frame in page.frames:
|
||||
try:
|
||||
inputs = frame.locator("input").all()
|
||||
except Exception:
|
||||
inputs = []
|
||||
for input_locator in inputs:
|
||||
try:
|
||||
input_type = str(input_locator.get_attribute("type", timeout=500) or "").lower()
|
||||
input_name = str(input_locator.get_attribute("name", timeout=500) or "").lower()
|
||||
input_id = str(input_locator.get_attribute("id", timeout=500) or "").lower()
|
||||
if not input_locator.is_visible(timeout=500):
|
||||
continue
|
||||
if input_type == "password" or "password" in input_name or "password" in input_id:
|
||||
input_locator.fill(password, timeout=2_000)
|
||||
filled_password = True
|
||||
elif input_type in {"", "text", "email"} or "user" in input_name or "identifier" in input_name:
|
||||
current = str(input_locator.input_value(timeout=500) or "").strip()
|
||||
if not current:
|
||||
input_locator.fill(username, timeout=2_000)
|
||||
except Exception:
|
||||
pass
|
||||
return filled_password
|
||||
|
||||
|
||||
def _is_dsv_username_page(page: Any) -> bool:
|
||||
for frame in page.frames:
|
||||
try:
|
||||
text = frame.locator("body").inner_text(timeout=500)
|
||||
except Exception:
|
||||
text = ""
|
||||
lowered = text.lower()
|
||||
method_markers = ("选择登录方法", "choose a sign-on method", "输入您的密码并登录", "password")
|
||||
if any(marker in text or marker in lowered for marker in method_markers):
|
||||
continue
|
||||
if ("电子邮件或SIMS ID或手机号" in text or "e-mail or sims id" in lowered) and ("继续" in text or "continue" in lowered):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _submit_dsv_password_form(page: Any) -> bool:
|
||||
"""
|
||||
提交 DSV 密码登录页。
|
||||
|
||||
核心逻辑:优先直接点击可见登录按钮;如果页面使用 Vue/隐藏字段组合提交,
|
||||
则退回到 DOM 脚本里触发 `pf.ok` / form submit / Enter,避免“密码已填完但未真正登录”。
|
||||
"""
|
||||
selectors = (
|
||||
'button[name="login"]',
|
||||
'button[type="submit"]',
|
||||
'input[type="submit"]',
|
||||
'input[name="pf.ok"]',
|
||||
'button.btn.dbs-sims-button-primary',
|
||||
'button.dbs-sims-button-primary',
|
||||
)
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
for selector in selectors:
|
||||
for root in roots:
|
||||
try:
|
||||
button = root.locator(selector).first
|
||||
button.wait_for(state="visible", timeout=1_000)
|
||||
button.click(timeout=2_000, force=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
script = """
|
||||
() => {
|
||||
const visible = (node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
const style = window.getComputedStyle(node);
|
||||
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
const password = Array.from(document.querySelectorAll('input#userpassword, input[name="userpassword"], input#password[name="pf.pass"], input[name="pf.pass"], input[type="password"]'))
|
||||
.find((node) => !node.disabled);
|
||||
if (!password) return false;
|
||||
const form = password.closest('form');
|
||||
const scope = form || document;
|
||||
const submit = scope.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button.btn.dbs-sims-button-primary, button.dbs-sims-button-primary')
|
||||
|| Array.from(scope.querySelectorAll('button, input[type="submit"], input[name="pf.ok"], [role="button"], .btn.dbs-sims-button-primary, .dbs-sims-button-primary, .dbs-sims-button'))
|
||||
.find((node) => {
|
||||
const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
return text === '登录' || text === 'Login' || text === 'Log in' || text === 'Sign in';
|
||||
}) || (form ? form.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button:not([type]), .btn.dbs-sims-button-primary, .dbs-sims-button-primary') : null);
|
||||
if (submit) {
|
||||
if (visible(submit) && typeof submit.scrollIntoView === 'function') {
|
||||
submit.scrollIntoView({ block: 'center', inline: 'center' });
|
||||
}
|
||||
submit.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerType: 'mouse' }));
|
||||
submit.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
submit.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
submit.click();
|
||||
submit.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
return true;
|
||||
}
|
||||
if (form && typeof form.requestSubmit === 'function') {
|
||||
form.requestSubmit();
|
||||
return true;
|
||||
}
|
||||
if (form) {
|
||||
form.submit();
|
||||
return true;
|
||||
}
|
||||
password.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||||
return true;
|
||||
}
|
||||
"""
|
||||
for frame in roots:
|
||||
try:
|
||||
if frame.evaluate(script, timeout=2_000):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _looks_like_dsv_login_method_page(page: Any) -> bool:
|
||||
needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method")
|
||||
for frame in page.frames:
|
||||
try:
|
||||
text = frame.locator("body").inner_text(timeout=300)
|
||||
except Exception:
|
||||
text = ""
|
||||
lowered = text.lower()
|
||||
if "real person" in lowered and ("rabbit" in lowered or "scale" in lowered):
|
||||
continue
|
||||
if any(needle in text for needle in needles):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _has_dsv_human_check_prompt(page: Any) -> bool:
|
||||
"""快速判断当前页是否出现真人验证提示,避免在普通登录轮询里反复触发重等待。"""
|
||||
try:
|
||||
text = page.locator("body").inner_text(timeout=300)
|
||||
except Exception:
|
||||
text = ""
|
||||
lowered = text.lower()
|
||||
return "real person" in lowered or "rabbit" in lowered or "scale" in lowered or "真人" in text
|
||||
|
||||
|
||||
def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool:
|
||||
wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("FREIGHT_RPA_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000"))
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url:
|
||||
return True
|
||||
if _looks_like_dsv_login_method_page(page):
|
||||
return True
|
||||
if _has_dsv_human_check_prompt(page):
|
||||
_wait_for_dsv_human_check_if_present(page, timeout_ms=2_000)
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_dsv_human_check_if_present(page: Any, timeout_ms: int | None = None) -> None:
|
||||
wait_ms = timeout_ms if timeout_ms is not None else 300_000
|
||||
try:
|
||||
text = page.locator("body").inner_text(timeout=2_000)
|
||||
except Exception:
|
||||
text = ""
|
||||
lowered = text.lower()
|
||||
if "real person" not in lowered and "rabbit" not in lowered and "scale" not in lowered and "真人" not in text:
|
||||
return
|
||||
print("[dsv-login] human check detected; please click the requested object in the browser")
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
current = page.locator("body").inner_text(timeout=2_000)
|
||||
except Exception:
|
||||
current = ""
|
||||
lowered_current = current.lower()
|
||||
if "real person" not in lowered_current and "rabbit" not in lowered_current and "scale" not in lowered_current:
|
||||
print("[dsv-login] human check passed")
|
||||
return
|
||||
time.sleep(2)
|
||||
raise RuntimeError("DSV login human check was not completed in time")
|
||||
|
||||
|
||||
def _dsv_login_debug_value(page: Any) -> tuple[str, dict[str, Any]]:
|
||||
identifier_value = ""
|
||||
button_state: dict[str, Any] = {}
|
||||
for frame in page.frames:
|
||||
if not identifier_value:
|
||||
try:
|
||||
identifier_value = frame.locator("input#identifier").first.input_value(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
if not button_state:
|
||||
try:
|
||||
button_state = frame.locator("button[name='login']").first.evaluate(
|
||||
"(node) => ({ disabled: node.disabled, text: node.textContent, className: node.className })",
|
||||
timeout=1_000,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if identifier_value or button_state:
|
||||
break
|
||||
return identifier_value, button_state
|
||||
|
||||
|
||||
def _find_dsv_password_locator(page: Any, timeout_ms: int = 250):
|
||||
"""
|
||||
轻量探测 DSV 密码输入框。
|
||||
|
||||
核心逻辑:登录第二/第三步切换期间只需要快速知道“密码框是否已出现”,
|
||||
这里避免调用带长轮询的通用选择器等待,减少方法页阶段的有效阻塞。
|
||||
"""
|
||||
selectors = tuple(
|
||||
item
|
||||
for item in (
|
||||
_env("FREIGHT_RPA_DSV_PASSWORD_SELECTOR"),
|
||||
"input#userpassword",
|
||||
'input[name="userpassword"]',
|
||||
'input[name="password"]',
|
||||
'input[type="password"]',
|
||||
)
|
||||
if item
|
||||
)
|
||||
for frame in page.frames:
|
||||
for selector in selectors:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
if locator.is_visible(timeout=timeout_ms):
|
||||
return locator
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _is_dsv_oauth_handshake_url(url: str) -> bool:
|
||||
"""PingFederate OAuth 握手页:常见为空白 body,需等待 JS 跳转或 reload。"""
|
||||
current = str(url or "").lower()
|
||||
return "auth.dbschenker.com" in current and "authorization.oauth2" in current
|
||||
|
||||
|
||||
def _is_dsv_auth_ping_url(url: str) -> bool:
|
||||
"""PingFederate 密码阶段 authorization.ping:同样可能出现空白 body。"""
|
||||
current = str(url or "").lower()
|
||||
return "auth.dbschenker.com" in current and "authorization.ping" in current
|
||||
|
||||
|
||||
def _is_dsv_blank_auth_transition(page: Any) -> bool:
|
||||
"""auth 域 oauth2/ping 中间页中 body 为空。"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
if not (_is_dsv_oauth_handshake_url(current_url) or _is_dsv_auth_ping_url(current_url)):
|
||||
return False
|
||||
try:
|
||||
body = str(page.locator("body").inner_text(timeout=1_000) or "").strip()
|
||||
except Exception:
|
||||
body = ""
|
||||
return not body
|
||||
|
||||
|
||||
def _dsv_login_ready_timeout_ms() -> int:
|
||||
"""DSV 登录表单/跳转就绪的最大等待秒数。"""
|
||||
return max(60_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "120000") or "120000"))
|
||||
|
||||
|
||||
def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -> bool:
|
||||
"""
|
||||
等待 DSV auth 域完成 OAuth/Ping 握手并渲染登录表单或跳回 portal。
|
||||
|
||||
核心逻辑:authorization.oauth2 / authorization.ping 均可能空白;
|
||||
轮询用户名/密码框与 portal 导航,必要时 reload 一次触发 PingFederate 自动提交。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else _dsv_login_ready_timeout_ms()
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
started_at = time.monotonic()
|
||||
logged_waiting = False
|
||||
reload_attempted = False
|
||||
while time.monotonic() < deadline:
|
||||
current_url = str(page.url or "").lower()
|
||||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None:
|
||||
return True
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None:
|
||||
return True
|
||||
if _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_USERNAME_SELECTOR",
|
||||
_DSV_USERNAME_SELECTORS,
|
||||
timeout_ms=500,
|
||||
) is not None:
|
||||
return True
|
||||
if _find_dsv_password_locator(page, timeout_ms=200) is not None:
|
||||
return True
|
||||
if _wait_for_dsv_login_method_page(page, timeout_ms=200):
|
||||
return True
|
||||
if "auth.dbschenker.com" not in current_url:
|
||||
return True
|
||||
try:
|
||||
body = str(page.locator("body").inner_text(timeout=1_000) or "").strip()
|
||||
except Exception:
|
||||
body = ""
|
||||
if body and not _is_dsv_blank_auth_transition(page):
|
||||
return True
|
||||
if not logged_waiting:
|
||||
print(f"[dsv-login] waiting auth page render url={page.url!r}")
|
||||
logged_waiting = True
|
||||
try:
|
||||
page.wait_for_load_state("load", timeout=2_000)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=2_000)
|
||||
except Exception:
|
||||
pass
|
||||
if not reload_attempted and (time.monotonic() - started_at) >= 12:
|
||||
reload_attempted = True
|
||||
transition = "ping" if _is_dsv_auth_ping_url(current_url) else "oauth"
|
||||
print(f"[dsv-login] blank auth {transition} transition, reload once")
|
||||
try:
|
||||
page.reload(wait_until="commit", timeout=min(wait_ms, 45_000))
|
||||
except Exception as exc:
|
||||
print(f"[dsv-login] auth reload failed: {exc}", file=sys.stderr)
|
||||
time.sleep(0.35)
|
||||
print(f"[dsv-login] auth page wait finished url={page.url!r}")
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_dsv_oauth_handshake(page: Any, *, timeout_ms: int = 45_000) -> None:
|
||||
"""兼容旧调用:委托至 _wait_for_dsv_auth_page_ready。"""
|
||||
_wait_for_dsv_auth_page_ready(page, timeout_ms=timeout_ms)
|
||||
|
||||
|
||||
def _try_fill_dsv_username_locator(locator: Any, username: str) -> bool:
|
||||
try:
|
||||
locator.wait_for(state="visible", timeout=1_000)
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
if not locator.is_enabled(timeout=1_000):
|
||||
return False
|
||||
if not _dsv_locator_can_edit(locator):
|
||||
return False
|
||||
locator.click(timeout=2_000)
|
||||
try:
|
||||
locator.fill(username, timeout=3_000)
|
||||
except Exception:
|
||||
locator.press("Control+A")
|
||||
locator.press("Backspace")
|
||||
locator.type(username, delay=30)
|
||||
if _dsv_username_has_value(locator):
|
||||
return True
|
||||
locator.evaluate(
|
||||
"""
|
||||
(node, value) => {
|
||||
node.focus();
|
||||
node.value = value;
|
||||
node.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
node.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
""",
|
||||
username,
|
||||
)
|
||||
return _dsv_username_has_value(locator)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _fill_dsv_username(page: Any, username: str, preferred_locator: Any | None = None):
|
||||
"""
|
||||
在 DSV 第一步邮箱页填写账号。
|
||||
|
||||
核心逻辑:优先复用已经探测到的输入框,避免“探测到了邮箱框,但二次扫描更窄选择器后又找不到”的失配,
|
||||
若复用失败,再按完整候选选择器扫描各 frame。
|
||||
"""
|
||||
if preferred_locator is not None and _try_fill_dsv_username_locator(preferred_locator, username):
|
||||
return preferred_locator
|
||||
|
||||
timeout_ms = max(5_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "300000") or "300000"))
|
||||
deadline = time.monotonic() + (timeout_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for frame in page.frames:
|
||||
for selector in _DSV_USERNAME_SELECTORS:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
if _try_fill_dsv_username_locator(locator, username):
|
||||
return locator
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None:
|
||||
"""
|
||||
DSV 首次登录后可能提示升级密码登录;RPA 选择“也许以后”继续进入系统。
|
||||
"""
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point M:upgrade-prompt-entry
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:entry",
|
||||
"[DEBUG] checking dsv password upgrade prompt",
|
||||
{"url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
candidates = _dsv_maybe_later_selector_candidates()
|
||||
|
||||
def _prompt_visible() -> bool:
|
||||
return _has_dsv_password_upgrade_prompt(page, timeout_ms=250)
|
||||
|
||||
# [STEP 1] 先做轻量探测门;没看到升级提示强特征时,直接跳过,
|
||||
# 避免在 Verifying compliance / auth 跳转页里做大范围阻塞轮询。
|
||||
quick_detect_deadline = time.monotonic() + 5.0
|
||||
prompt_detected = _prompt_visible()
|
||||
while not prompt_detected and time.monotonic() < quick_detect_deadline:
|
||||
time.sleep(0.2)
|
||||
prompt_detected = _prompt_visible()
|
||||
if not prompt_detected:
|
||||
# #region debug-point M:upgrade-prompt-skip
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip",
|
||||
"[DEBUG] dsv password upgrade prompt not shown",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
for root in roots:
|
||||
for candidate in candidates:
|
||||
try:
|
||||
locator = root.locator(candidate).first
|
||||
locator.wait_for(state="attached", timeout=300)
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=1_500, force=True)
|
||||
except Exception:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
time.sleep(1)
|
||||
if not _prompt_visible():
|
||||
print("[dsv-login] password upgrade prompt dismissed")
|
||||
# #region debug-point M:upgrade-prompt-dismissed
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed",
|
||||
"[DEBUG] dsv password upgrade prompt dismissed",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "candidate": candidate, "url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
try:
|
||||
page.wait_for_load_state("domcontentloaded", timeout=10_000)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
except Exception:
|
||||
continue
|
||||
if _try_click_dsv_maybe_later_via_js(root):
|
||||
time.sleep(1)
|
||||
if not _prompt_visible():
|
||||
print("[dsv-login] password upgrade prompt dismissed via js fallback")
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed_js",
|
||||
"[DEBUG] dsv password upgrade prompt dismissed via js fallback",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
try:
|
||||
page.wait_for_load_state("domcontentloaded", timeout=10_000)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
if not _prompt_visible():
|
||||
# #region debug-point M:upgrade-prompt-skip
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip",
|
||||
"[DEBUG] dsv password upgrade prompt disappeared before click",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
_debug_dsv_stage(page, "password-upgrade-prompt-still-visible", target_text="Maybe later")
|
||||
time.sleep(0.4)
|
||||
# #region debug-point M:upgrade-prompt-timeout
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:timeout",
|
||||
"[DEBUG] dsv password upgrade prompt remained visible until timeout",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
|
||||
|
||||
def _dismiss_dsv_password_upgrade_prompt_after_login_redirect(page: Any) -> None:
|
||||
"""
|
||||
登录提交后的条件处理:仅在跳到密码升级 auth resume 页时点击“也许以后”。
|
||||
"""
|
||||
if not _is_dsv_password_upgrade_redirect(page):
|
||||
_report_debug_event(
|
||||
"M",
|
||||
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt_after_login_redirect:skip",
|
||||
"[DEBUG] skip password upgrade prompt because login did not redirect to upgrade URL",
|
||||
{"url": page.url},
|
||||
)
|
||||
return
|
||||
try:
|
||||
page.wait_for_load_state("domcontentloaded", timeout=10_000)
|
||||
except Exception:
|
||||
pass
|
||||
_dismiss_dsv_password_upgrade_prompt(page)
|
||||
|
||||
|
||||
_DSV_USERNAME_SELECTORS = (
|
||||
"input#identifier",
|
||||
'input[name="identifier"]',
|
||||
'input[name="username"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="email"]',
|
||||
'input[autocomplete="username"]',
|
||||
'input[placeholder="电子邮件或SIMS ID或手机号"]',
|
||||
'input[type="email"]',
|
||||
'input[type="text"]',
|
||||
)
|
||||
|
||||
# 公开 API
|
||||
DSV_USERNAME_SELECTORS = _DSV_USERNAME_SELECTORS
|
||||
click_dsv_continue = _click_dsv_continue
|
||||
click_dsv_password_method = _click_dsv_password_method
|
||||
debug_dsv_login_method_page = _debug_dsv_login_method_page
|
||||
dismiss_dsv_password_upgrade_prompt = _dismiss_dsv_password_upgrade_prompt
|
||||
dismiss_dsv_password_upgrade_prompt_after_login_redirect = _dismiss_dsv_password_upgrade_prompt_after_login_redirect
|
||||
dsv_locator_can_edit = _dsv_locator_can_edit
|
||||
dsv_login_debug_value = _dsv_login_debug_value
|
||||
dsv_login_ready_timeout_ms = _dsv_login_ready_timeout_ms
|
||||
dsv_username_has_value = _dsv_username_has_value
|
||||
fill_dsv_password_page_fields = _fill_dsv_password_page_fields
|
||||
fill_dsv_username = _fill_dsv_username
|
||||
find_dsv_password_locator = _find_dsv_password_locator
|
||||
has_dsv_human_check_prompt = _has_dsv_human_check_prompt
|
||||
has_dsv_password_upgrade_prompt = _has_dsv_password_upgrade_prompt
|
||||
is_dsv_auth_ping_url = _is_dsv_auth_ping_url
|
||||
is_dsv_blank_auth_transition = _is_dsv_blank_auth_transition
|
||||
is_dsv_oauth_handshake_url = _is_dsv_oauth_handshake_url
|
||||
is_dsv_username_page = _is_dsv_username_page
|
||||
looks_like_dsv_login_method_page = _looks_like_dsv_login_method_page
|
||||
submit_dsv_password_form = _submit_dsv_password_form
|
||||
submit_dsv_username_form = _submit_dsv_username_form
|
||||
try_fill_dsv_username_locator = _try_fill_dsv_username_locator
|
||||
wait_for_dsv_auth_page_ready = _wait_for_dsv_auth_page_ready
|
||||
wait_for_dsv_human_check_if_present = _wait_for_dsv_human_check_if_present
|
||||
wait_for_dsv_login_method_page = _wait_for_dsv_login_method_page
|
||||
wait_for_dsv_oauth_handshake = _wait_for_dsv_oauth_handshake
|
||||
|
||||
from dsv_auth_login_flow import maybe_auto_login_dsv as _maybe_auto_login_dsv
|
||||
maybe_auto_login_dsv = _maybe_auto_login_dsv
|
||||
@@ -0,0 +1,393 @@
|
||||
"""
|
||||
scripts/rpa/dsv_auth_login_flow.py
|
||||
|
||||
用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。
|
||||
依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。
|
||||
逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
from dsv_debug import (
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
debug_dsv_stage as _debug_dsv_stage,
|
||||
report_debug_event as _report_debug_event,
|
||||
report_dsv_chain_stage as _report_dsv_chain_stage,
|
||||
)
|
||||
|
||||
import dsv_auth
|
||||
|
||||
# 绑定私有符号,避免 dsv_auth 末尾 re-export 时的循环导入竞态。
|
||||
_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_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
|
||||
_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
|
||||
_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_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
|
||||
_wait_for_dsv_human_check_if_present = dsv_auth._wait_for_dsv_human_check_if_present
|
||||
_wait_for_dsv_login_method_page = dsv_auth._wait_for_dsv_login_method_page
|
||||
|
||||
|
||||
def _wait_for_dsv_home_ready_after_login(
|
||||
page: Any,
|
||||
*,
|
||||
timeout_ms: int | None = None,
|
||||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""登录完成后等待首页 ready;惰性导入 dsv_session 避免循环依赖。"""
|
||||
import dsv_session
|
||||
|
||||
dsv_session.wait_for_dsv_home_ready(
|
||||
page,
|
||||
timeout_ms=timeout_ms,
|
||||
on_portal_shell_seen=on_portal_shell_seen,
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_dsv_app_after_login(
|
||||
page: Any,
|
||||
timeout_ms: int | None = None,
|
||||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||||
) -> bool:
|
||||
"""登录轮询 portal 壳层;委托 dsv_session。"""
|
||||
import dsv_session
|
||||
|
||||
return dsv_session.wait_for_dsv_app_after_login(
|
||||
page,
|
||||
timeout_ms=timeout_ms,
|
||||
on_portal_shell_seen=on_portal_shell_seen,
|
||||
)
|
||||
|
||||
|
||||
def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
"""
|
||||
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
|
||||
"""
|
||||
username = _env("FREIGHT_RPA_DSV_USERNAME")
|
||||
password = _env("FREIGHT_RPA_DSV_PASSWORD")
|
||||
auto_login_started_at = time.monotonic()
|
||||
username_step_started_at = auto_login_started_at
|
||||
continue_to_method_started_at: float | None = None
|
||||
method_to_password_started_at: float | None = None
|
||||
submit_to_home_started_at: float | None = None
|
||||
portal_shell_seen_at: float | None = None
|
||||
|
||||
def _report_auto_login_substage(name: str, started_at: float | None) -> None:
|
||||
"""记录 auto_login 内部子阶段耗时,帮助定位认证链路具体卡点。"""
|
||||
if started_at is None:
|
||||
return
|
||||
_report_dsv_chain_stage(
|
||||
f"auto_login.{name}",
|
||||
"end",
|
||||
started_at=started_at,
|
||||
extra={"sinceAutoLoginMs": int((time.monotonic() - auto_login_started_at) * 1000)},
|
||||
)
|
||||
|
||||
def _report_portal_shell_seen() -> None:
|
||||
"""记录 portal 壳层首次可见时间,区分 auth 收尾和首页 ready 的等待。"""
|
||||
nonlocal portal_shell_seen_at
|
||||
if portal_shell_seen_at is not None:
|
||||
return
|
||||
portal_shell_seen_at = time.monotonic()
|
||||
_report_auto_login_substage("portal_shell_seen", submit_to_home_started_at)
|
||||
|
||||
if not username or not password:
|
||||
return
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=15_000) is not None:
|
||||
print("[dsv-login] existing session detected")
|
||||
# #region debug-point E:existing-session
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session",
|
||||
"[DEBUG] dsv existing session detected before login flow",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
|
||||
_wait_for_dsv_auth_page_ready(page)
|
||||
login_ready_ms = _dsv_login_ready_timeout_ms()
|
||||
print("[dsv-login] waiting username field")
|
||||
username_locator = _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_USERNAME_SELECTOR",
|
||||
_DSV_USERNAME_SELECTORS,
|
||||
timeout_ms=login_ready_ms,
|
||||
)
|
||||
if username_locator is not None:
|
||||
username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator)
|
||||
user_filled = username_locator is not None
|
||||
else:
|
||||
username_locator = None
|
||||
user_filled = _fill_first_visible_text_input(page, username)
|
||||
if not user_filled:
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=10_000) is not None:
|
||||
print("[dsv-login] existing session detected")
|
||||
# #region debug-point E:existing-session-late
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session_late",
|
||||
"[DEBUG] dsv existing session detected after username probe",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
if _is_dsv_oauth_handshake_url(page.url):
|
||||
print("[dsv-login] still on blank oauth handshake before giving up, reload once")
|
||||
try:
|
||||
page.reload(wait_until="domcontentloaded", timeout=45_000)
|
||||
except Exception as exc:
|
||||
print(f"[dsv-login] final oauth reload failed: {exc}", file=sys.stderr)
|
||||
if _wait_for_dsv_auth_page_ready(page, timeout_ms=30_000):
|
||||
username_locator = _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_USERNAME_SELECTOR",
|
||||
_DSV_USERNAME_SELECTORS,
|
||||
timeout_ms=15_000,
|
||||
)
|
||||
if username_locator is not None:
|
||||
username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator)
|
||||
if username_locator is not None:
|
||||
user_filled = True
|
||||
if not user_filled:
|
||||
try:
|
||||
text = page.locator("body").inner_text(timeout=3_000)
|
||||
except Exception:
|
||||
text = ""
|
||||
raise RuntimeError(
|
||||
"DSV login state is unknown "
|
||||
f"url={page.url} body={text[:300]!r} "
|
||||
"(oauth handshake page stayed blank; check network/VPN or complete login manually in browser)"
|
||||
)
|
||||
print("[dsv-login] username filled")
|
||||
_report_auto_login_substage("username_step", username_step_started_at)
|
||||
|
||||
continue_selector = _env("FREIGHT_RPA_DSV_CONTINUE_BUTTON_SELECTOR")
|
||||
if continue_selector:
|
||||
page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||||
clicked_continue = True
|
||||
else:
|
||||
clicked_continue = _click_dsv_continue(page, username_locator)
|
||||
if not clicked_continue:
|
||||
identifier_value, button_state = _dsv_login_debug_value(page)
|
||||
print(f"[dsv-login] continue missing identifier_value={identifier_value!r} button={button_state!r}")
|
||||
raise RuntimeError("DSV login email step detected but continue button was not found")
|
||||
print("[dsv-login] continue clicked")
|
||||
continue_to_method_started_at = time.monotonic()
|
||||
# #region debug-point E:continue-clicked
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked",
|
||||
"[DEBUG] dsv username step submitted",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
|
||||
print("[dsv-login] waiting password field")
|
||||
password_locator = None
|
||||
login_deadline = time.monotonic() + (
|
||||
max(60_000, int(_env("FREIGHT_RPA_DSV_PASSWORD_STAGE_TIMEOUT_MS", "120000") or "120000")) / 1000
|
||||
)
|
||||
password_method_clicked_at = 0.0
|
||||
username_retry_allowed_at = time.monotonic() + 6
|
||||
while time.monotonic() < login_deadline:
|
||||
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
|
||||
if password_locator is not None:
|
||||
break
|
||||
if _fill_dsv_password_page_fields(page, username, password):
|
||||
print("[dsv-login] password filled")
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
if not _submit_dsv_password_form(page):
|
||||
raise RuntimeError("DSV login password step detected but login button was not found")
|
||||
print("[dsv-login] login clicked")
|
||||
submit_to_home_started_at = time.monotonic()
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
_debug_dsv_stage(page, "after-login-click-inline-password", target_text="Reports")
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
|
||||
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
|
||||
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
|
||||
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
return
|
||||
if _has_dsv_human_check_prompt(page):
|
||||
_wait_for_dsv_human_check_if_present(page, timeout_ms=300_000)
|
||||
if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen):
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
# #region debug-point E:login-completed-direct
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_direct",
|
||||
"[DEBUG] dsv login completed directly after human check/app wait",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000)
|
||||
if method_ready:
|
||||
# #region debug-point E:password-method-page
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_page",
|
||||
"[DEBUG] dsv password method page detected",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2:
|
||||
time.sleep(1)
|
||||
continue
|
||||
password_method_selector = _env("FREIGHT_RPA_DSV_PASSWORD_METHOD_SELECTOR")
|
||||
if password_method_selector:
|
||||
page.locator(password_method_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||||
clicked_password_method = True
|
||||
else:
|
||||
clicked_password_method = _click_dsv_password_method(page)
|
||||
if not clicked_password_method:
|
||||
print(f"[dsv-login] password method debug {_debug_dsv_login_method_page(page)}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
password_method_clicked_at = time.monotonic()
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
continue_to_method_started_at = None
|
||||
method_to_password_started_at = password_method_clicked_at
|
||||
username_retry_allowed_at = max(username_retry_allowed_at, password_method_clicked_at + 4)
|
||||
print("[dsv-login] password method clicked")
|
||||
# #region debug-point E:password-method-clicked
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_clicked",
|
||||
"[DEBUG] dsv password method clicked",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
continue
|
||||
# [STEP 2] Continue 刚提交或刚点过“密码”时,先给 PingID 页面一点切换时间,
|
||||
# 避免方法页尚未稳定时又误判回邮箱页,造成来回重填账号。
|
||||
if time.monotonic() >= username_retry_allowed_at and _is_dsv_username_page(page):
|
||||
username_locator = _fill_dsv_username(page, username)
|
||||
if username_locator is None and not _fill_first_visible_text_input(page, username):
|
||||
print(f"[dsv-login] username retry failed {_debug_dsv_login_method_page(page)}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
if _click_dsv_continue(page, username_locator):
|
||||
print("[dsv-login] username page retried")
|
||||
username_retry_allowed_at = time.monotonic() + 6
|
||||
time.sleep(1)
|
||||
continue
|
||||
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
|
||||
if password_locator is not None:
|
||||
break
|
||||
if _is_dsv_blank_auth_transition(page):
|
||||
_wait_for_dsv_auth_page_ready(page, timeout_ms=5_000)
|
||||
password_locator = _find_dsv_password_locator(page, timeout_ms=500)
|
||||
if password_locator is not None:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
if password_locator is None:
|
||||
if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen):
|
||||
print("[dsv-login] login completed")
|
||||
# #region debug-point E:login-completed-late
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_late",
|
||||
"[DEBUG] dsv login completed after password wait fallback",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
try:
|
||||
text = page.locator("body").inner_text(timeout=3_000)
|
||||
except Exception:
|
||||
text = ""
|
||||
if not text.strip():
|
||||
print(f"[dsv-login] password page still loading url={page.url}")
|
||||
if _is_dsv_blank_auth_transition(page):
|
||||
_wait_for_dsv_auth_page_ready(page, timeout_ms=_dsv_login_ready_timeout_ms())
|
||||
password_locator = _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_DSV_PASSWORD_SELECTOR",
|
||||
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
|
||||
timeout_ms=_dsv_login_ready_timeout_ms(),
|
||||
)
|
||||
if password_locator is None:
|
||||
if not _fill_dsv_password_page_fields(page, username, password):
|
||||
raise RuntimeError("DSV login password field was not found")
|
||||
print("[dsv-login] password filled")
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
if not _submit_dsv_password_form(page):
|
||||
raise RuntimeError("DSV login password step detected but login button was not found")
|
||||
print("[dsv-login] login clicked")
|
||||
submit_to_home_started_at = time.monotonic()
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
_debug_dsv_stage(page, "after-login-click-late-password", target_text="Reports")
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
|
||||
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
|
||||
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
|
||||
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
return
|
||||
print(f"[dsv-login] password field missing url={page.url} body={text[:300]!r} method_debug={_debug_dsv_login_method_page(page)}")
|
||||
raise RuntimeError("DSV login password field was not found")
|
||||
|
||||
password_locator.fill(password, timeout=_browser_timeout_ms())
|
||||
print("[dsv-login] password filled")
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
if not _submit_dsv_password_form(page):
|
||||
raise RuntimeError("DSV login password step detected but login button was not found")
|
||||
print("[dsv-login] login clicked")
|
||||
submit_to_home_started_at = time.monotonic()
|
||||
# #region debug-point N:login-clicked
|
||||
_report_debug_event(
|
||||
"N",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_clicked",
|
||||
"[DEBUG] dsv login button submitted",
|
||||
{"url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
# #region debug-point N:after-domcontentloaded
|
||||
_report_debug_event(
|
||||
"N",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:after_domcontentloaded",
|
||||
"[DEBUG] dsv login flow reached domcontentloaded after submit",
|
||||
{"url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
_debug_dsv_stage(page, "after-login-click-password-locator", target_text="Reports")
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
|
||||
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
|
||||
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
|
||||
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
|
||||
|
||||
# 公开 API
|
||||
maybe_auto_login_dsv = _maybe_auto_login_dsv
|
||||
@@ -0,0 +1,346 @@
|
||||
"""
|
||||
scripts/rpa/dsv_debug.py
|
||||
|
||||
用途:DSV 360 RPA 调试探针与链路阶段日志。
|
||||
依赖:rpa_common。
|
||||
逻辑:供 dsv_session、dsv_navigation、dsv_report_export 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
|
||||
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
_payload = {
|
||||
"sessionId": "dsv-export-stall",
|
||||
"runId": run_id,
|
||||
"hypothesisId": hypothesis_id,
|
||||
"location": location,
|
||||
"msg": msg,
|
||||
"data": data or {},
|
||||
"ts": int(time.time() * 1000),
|
||||
}
|
||||
_url = "http://127.0.0.1:7778/event"
|
||||
_env_file = Path(".dbg/dsv-export-stall.env")
|
||||
try:
|
||||
if _env_file.is_file():
|
||||
_content = _env_file.read_text(encoding="utf-8")
|
||||
_url = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SERVER_URL=")), _url)
|
||||
_payload["sessionId"] = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SESSION_ID=")), _payload["sessionId"])
|
||||
urllib.request.urlopen(
|
||||
urllib.request.Request(
|
||||
_url,
|
||||
data=json.dumps(_payload, ensure_ascii=False).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
),
|
||||
timeout=1.5,
|
||||
).read()
|
||||
except Exception:
|
||||
pass
|
||||
def _debug_dsv_page_snapshot(page: Any, *, target_text: str = "") -> str:
|
||||
"""
|
||||
汇总 DSV 当前页面与各 frame 的可见文本快照,便于定位菜单/报表文案漂移。
|
||||
|
||||
核心逻辑:采集 page.url、顶层 body 文本、关键菜单容器是否存在,以及各 frame 中
|
||||
可见的链接/按钮/菜单项候选文本;当目标文案找不到时,日志里直接输出“页面上实际看到了什么”。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
target_text: 当前正在寻找的菜单/报表文案,可为空。
|
||||
|
||||
Returns:
|
||||
str: 截断后的页面快照字符串,适合直接输出到 worker 日志。
|
||||
"""
|
||||
focus = str(target_text or "").strip()
|
||||
try:
|
||||
page_url = page.url
|
||||
except Exception:
|
||||
page_url = ""
|
||||
snippets = [f"url={page_url!r}"]
|
||||
try:
|
||||
body = page.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
|
||||
except Exception:
|
||||
body = ""
|
||||
if body:
|
||||
snippets.append(f"page_body={body!r}")
|
||||
try:
|
||||
from dsv_session import has_dsv_report_nav_attached as _has_dsv_report_nav_attached
|
||||
|
||||
report_nav_exists = _has_dsv_report_nav_attached(page)
|
||||
except Exception:
|
||||
report_nav_exists = False
|
||||
snippets.append(f"report_nav_exists={report_nav_exists}")
|
||||
|
||||
candidate_script = """
|
||||
(focusText) => {
|
||||
const normalize = (value) => ((value || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
const isVisible = (node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
const style = window.getComputedStyle(node);
|
||||
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
const selectors = [
|
||||
'#report-mega-legacy',
|
||||
'#report-mega-legacy *',
|
||||
'.mega-dropdown-menu *',
|
||||
'.dropdown-menu *',
|
||||
'a',
|
||||
'button',
|
||||
'[role="button"]',
|
||||
'li',
|
||||
'.nav-link',
|
||||
'.dropdown-item',
|
||||
];
|
||||
const focus = normalize(focusText).toLowerCase();
|
||||
const values = Array.from(document.querySelectorAll(selectors.join(',')))
|
||||
.filter((node) => isVisible(node))
|
||||
.map((node) => normalize(node.innerText || node.textContent || node.value))
|
||||
.filter(Boolean);
|
||||
const deduped = Array.from(new Set(values));
|
||||
const matched = focus
|
||||
? deduped.filter((text) => text.toLowerCase().includes(focus)).slice(0, 20)
|
||||
: [];
|
||||
return {
|
||||
matched,
|
||||
candidates: deduped.slice(0, 40),
|
||||
};
|
||||
}
|
||||
"""
|
||||
for idx, frame in enumerate(page.frames):
|
||||
try:
|
||||
frame_url = frame.url
|
||||
except Exception:
|
||||
frame_url = ""
|
||||
try:
|
||||
frame_name = frame.name
|
||||
except Exception:
|
||||
frame_name = ""
|
||||
try:
|
||||
frame_body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:400]
|
||||
except Exception:
|
||||
frame_body = ""
|
||||
try:
|
||||
frame_data = frame.evaluate(candidate_script, focus, timeout=1_500)
|
||||
except Exception:
|
||||
frame_data = {"matched": [], "candidates": []}
|
||||
matched = list((frame_data or {}).get("matched") or [])
|
||||
candidates = list((frame_data or {}).get("candidates") or [])
|
||||
if frame_body or candidates or matched:
|
||||
snippets.append(
|
||||
f"frame[{idx}] name={frame_name!r} url={frame_url!r} body={frame_body!r} matched={matched!r} candidates={candidates!r}"
|
||||
)
|
||||
return " | ".join(snippets)[:5000]
|
||||
|
||||
|
||||
def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None:
|
||||
"""
|
||||
输出 DSV 关键阶段的运行时快照,用于排查“短暂到页后又跳走”或 DOM 未就绪的问题。
|
||||
|
||||
核心逻辑:在登录后等待首页、展开 Reports、选择 Program 等关键节点打印统一格式日志,
|
||||
让失败复现时可以按时间顺序观察 URL、标题、body、frame 候选文本是否发生变化。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
stage: 当前阶段名,例如 `after-login-click`、`wait-app-3s`。
|
||||
target_text: 当前关注的菜单或文案目标。
|
||||
"""
|
||||
try:
|
||||
title = page.title()
|
||||
except Exception:
|
||||
title = ""
|
||||
snapshot = _debug_dsv_page_snapshot(page, target_text=target_text)
|
||||
print(f"[dsv-stage] stage={stage} title={title!r} {snapshot}")
|
||||
|
||||
|
||||
# #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"
|
||||
url = "http://127.0.0.1:7778/event"
|
||||
session_id = "reports-menu-stuck"
|
||||
try:
|
||||
content = env_path.read_text(encoding="utf-8")
|
||||
for line in content.splitlines():
|
||||
if line.startswith("DEBUG_SERVER_URL="):
|
||||
url = line.split("=", 1)[1].strip() or url
|
||||
elif line.startswith("DEBUG_SESSION_ID="):
|
||||
session_id = line.split("=", 1)[1].strip() or session_id
|
||||
except Exception:
|
||||
pass
|
||||
return url, session_id
|
||||
|
||||
|
||||
def _report_debug_event(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
"""向 Debug Server 上报结构化运行时证据;失败时静默,不影响业务流程。"""
|
||||
try:
|
||||
url, session_id = _debug_server_config()
|
||||
payload = {
|
||||
"sessionId": session_id,
|
||||
"runId": "pre-fix",
|
||||
"hypothesisId": hypothesis_id,
|
||||
"location": location,
|
||||
"msg": msg,
|
||||
"data": data or {},
|
||||
"ts": int(time.time() * 1000),
|
||||
}
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=2):
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _report_dsv_chain_stage(stage: str, status: str, *, started_at: float | None = None, extra: dict[str, Any] | None = None) -> None:
|
||||
"""
|
||||
统一记录 DSV 主链路各阶段耗时。
|
||||
|
||||
核心逻辑:只在主编排链路输出 `start/end/error` 三类探针,不参与任何业务判断,
|
||||
让一次真实运行即可回放从登录到导出的完整阶段耗时分布。
|
||||
"""
|
||||
payload = dict(extra or {})
|
||||
if started_at is not None:
|
||||
payload["elapsedMs"] = int((time.monotonic() - started_at) * 1000)
|
||||
print(
|
||||
"[dsv-chain] "
|
||||
f"stage={stage} "
|
||||
f"status={status} "
|
||||
+ (
|
||||
" ".join(f"{key}={payload[key]!r}" for key in sorted(payload))
|
||||
if payload
|
||||
else ""
|
||||
)
|
||||
)
|
||||
_report_debug_event(
|
||||
"T",
|
||||
f"freight_rpa_worker.py:_download_dsv360_inventory:{stage}:{status}",
|
||||
"[DEBUG] dsv chain stage probe",
|
||||
{"stage": stage, "status": status, **payload},
|
||||
)
|
||||
|
||||
|
||||
def _collect_dsv_reports_probe(page: Any) -> dict[str, Any]:
|
||||
"""采集 Reports 导航的最小 DOM 证据,帮助判断是否点早、点错或被遮挡。"""
|
||||
try:
|
||||
probe = page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
const nav = document.querySelector('#report-mega-legacy');
|
||||
const link = nav?.querySelector('a.dropdown-toggle, a.nav-link, a');
|
||||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||||
const rectOf = (node) => {
|
||||
if (!node || !node.getBoundingClientRect) return null;
|
||||
const r = node.getBoundingClientRect();
|
||||
return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
|
||||
};
|
||||
const centerNode = (() => {
|
||||
const rect = rectOf(link);
|
||||
if (!rect || rect.width <= 0 || rect.height <= 0) return null;
|
||||
return document.elementFromPoint(rect.x + Math.max(Math.floor(rect.width / 2), 1), rect.y + Math.max(Math.floor(rect.height / 2), 1));
|
||||
})();
|
||||
return {
|
||||
navExists: !!nav,
|
||||
navClass: nav?.className || '',
|
||||
navAriaExpanded: nav?.getAttribute('aria-expanded') || '',
|
||||
linkText: textOf(link),
|
||||
linkClass: link?.className || '',
|
||||
linkAriaExpanded: link?.getAttribute('aria-expanded') || '',
|
||||
linkRect: rectOf(link),
|
||||
centerTag: centerNode?.tagName || '',
|
||||
centerText: textOf(centerNode).slice(0, 120),
|
||||
activeTag: document.activeElement?.tagName || '',
|
||||
activeText: textOf(document.activeElement).slice(0, 120),
|
||||
};
|
||||
}
|
||||
""",
|
||||
)
|
||||
except Exception as exc:
|
||||
probe = {"probe_error": str(exc)[:200]}
|
||||
try:
|
||||
probe["url"] = page.url
|
||||
except Exception:
|
||||
probe["url"] = ""
|
||||
try:
|
||||
from dsv_navigation import is_dsv_reports_menu_open as _is_dsv_reports_menu_open
|
||||
|
||||
probe["menuOpen"] = _is_dsv_reports_menu_open(page)
|
||||
except Exception as exc:
|
||||
probe["menuOpen"] = False
|
||||
probe["menuOpenError"] = str(exc)[:120]
|
||||
return probe
|
||||
# #endregion
|
||||
|
||||
|
||||
def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]:
|
||||
"""采集 Reports 级联菜单当前可见层级,帮助判断下拉是否真的推进到了下一层。"""
|
||||
target_text = str(target_text or "").strip()
|
||||
target_literal = json.dumps(target_text)
|
||||
try:
|
||||
probe = page.evaluate(
|
||||
f"""
|
||||
() => {{
|
||||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||||
const nodes = Array.from(document.querySelectorAll(
|
||||
'#report-mega-legacy a, .mega-dropdown-menu a, .dropdown-menu a, [role="menuitem"], .dropdown-item'
|
||||
));
|
||||
const visible = nodes
|
||||
.filter((node) => {{
|
||||
const rect = node.getBoundingClientRect ? node.getBoundingClientRect() : null;
|
||||
const style = window.getComputedStyle ? window.getComputedStyle(node) : null;
|
||||
return rect && rect.width > 0 && rect.height > 0 && style && style.visibility !== 'hidden' && style.display !== 'none';
|
||||
}})
|
||||
.map((node) => {{
|
||||
const rect = node.getBoundingClientRect();
|
||||
return {{
|
||||
text: textOf(node),
|
||||
className: node.className || '',
|
||||
ariaExpanded: node.getAttribute('aria-expanded') || '',
|
||||
x: Math.round(rect.x),
|
||||
y: Math.round(rect.y),
|
||||
}};
|
||||
}})
|
||||
.filter((item) => item.text)
|
||||
.slice(0, 40);
|
||||
const target = {target_literal};
|
||||
const matched = target
|
||||
? visible.filter((item) => item.text.toLowerCase().includes(target.toLowerCase())).slice(0, 10)
|
||||
: [];
|
||||
return {{
|
||||
visibleItems: visible,
|
||||
matchedItems: matched,
|
||||
bodySnippet: textOf(document.body).slice(0, 600),
|
||||
activeText: textOf(document.activeElement).slice(0, 120),
|
||||
}};
|
||||
}}
|
||||
""",
|
||||
)
|
||||
except Exception as exc:
|
||||
probe = {"probe_error": str(exc)[:200]}
|
||||
try:
|
||||
probe["url"] = page.url
|
||||
except Exception:
|
||||
probe["url"] = ""
|
||||
return probe
|
||||
|
||||
|
||||
# 公开 API
|
||||
emit_debug_event = _emit_debug_event
|
||||
debug_dsv_page_snapshot = _debug_dsv_page_snapshot
|
||||
debug_dsv_stage = _debug_dsv_stage
|
||||
debug_server_config = _debug_server_config
|
||||
report_debug_event = _report_debug_event
|
||||
report_dsv_chain_stage = _report_dsv_chain_stage
|
||||
collect_dsv_reports_probe = _collect_dsv_reports_probe
|
||||
collect_dsv_menu_probe = _collect_dsv_menu_probe
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
scripts/rpa/dsv_driver.py
|
||||
|
||||
用途:DSV 360 库存 RPA 对外编排入口(session → 导航 → 导出)。
|
||||
依赖:dsv_report_export。
|
||||
逻辑:freight_rpa_worker 在 source_type=dsv360 时仅调用本模块公开函数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from dsv_report_export import (
|
||||
ensure_dsv_session,
|
||||
export_dsv_inventory_source,
|
||||
prepare_dsv_batch_export_step,
|
||||
)
|
||||
|
||||
|
||||
def download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
"""
|
||||
单票 trigger 的 DSV 360 导出。
|
||||
核心逻辑:ensure session → 导航至参数页 → 填参并导出 Excel。
|
||||
"""
|
||||
entry_url = str(source.get("entry_url") or "").strip()
|
||||
if not entry_url:
|
||||
raise RuntimeError("DSV360 inventory source missing entry_url")
|
||||
ensure_dsv_session(page, entry_url)
|
||||
return export_dsv_inventory_source(page, trigger, source)
|
||||
@@ -62,7 +62,6 @@ def _with_warehouse(source: dict[str, Any], warehouse: str, *, keep_source_code:
|
||||
if not keep_source_code:
|
||||
cloned["source_code"] = f"DSV360_AWSBI_{wh}"
|
||||
cloned["warehouse_id"] = wh
|
||||
cloned["warehouse_code"] = wh
|
||||
query = dict(cloned.get("query") or {})
|
||||
query["warehouse_code"] = wh
|
||||
cloned["query"] = query
|
||||
@@ -115,7 +114,7 @@ def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]]
|
||||
previous_source: dict[str, Any] | None = None
|
||||
for index, source in enumerate(sources):
|
||||
code = str(source.get("source_code") or "")
|
||||
wh = str(source.get("warehouse_id") or source.get("warehouse_code") or "")
|
||||
wh = str(source.get("warehouse_id") or "")
|
||||
print(
|
||||
f"[batch-smoke] scenario={scenario} step={index + 1}/{len(sources)} "
|
||||
f"source_code={code} warehouse={wh}"
|
||||
|
||||
@@ -52,11 +52,11 @@ def _build_source_from_config(source_code: str) -> dict:
|
||||
|
||||
navigation = dict(raw.get("navigation") or {})
|
||||
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
|
||||
site = str(raw.get("site") or "dsv360").strip().lower()
|
||||
warehouse_id = str(raw.get("warehouse_id") or raw.get("warehouse_code") or "").strip()
|
||||
source_type = str(raw.get("source_type") or "dsv360").strip().lower()
|
||||
warehouse_id = str(raw.get("warehouse_id") or "").strip()
|
||||
|
||||
query: dict[str, object] = {}
|
||||
if site == "dsv360":
|
||||
if source_type == "dsv360":
|
||||
for key in ("program_group", "program_label", "report_group", "report_name"):
|
||||
if navigation.get(key):
|
||||
query[key] = navigation[key]
|
||||
@@ -88,12 +88,12 @@ def _build_source_from_config(source_code: str) -> dict:
|
||||
|
||||
return {
|
||||
"source_code": str(raw.get("source_code") or source_code).upper(),
|
||||
"source_type": "dsv360" if site == "dsv360" else site,
|
||||
"source_type": source_type,
|
||||
"site_id": str(raw.get("site_id") or "").strip().upper(),
|
||||
"display_name": str(raw.get("display_name") or source_code),
|
||||
"enabled": bool(raw.get("enabled", True)),
|
||||
"entry_url": str(raw.get("entry_url") or "https://s360.dbschenker.com/"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"warehouse_code": str(raw.get("warehouse_code") or warehouse_id),
|
||||
"navigation": navigation,
|
||||
"parameters": parameters,
|
||||
"query": query,
|
||||
|
||||
@@ -0,0 +1,849 @@
|
||||
"""
|
||||
scripts/rpa/dsv_navigation.py
|
||||
|
||||
用途:DSV 360 Reports 菜单导航至 SSRS 参数页。
|
||||
依赖:rpa_common、dsv_debug、dsv_session。
|
||||
逻辑:由 dsv_report_export 在填参导出前调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
import dsv_debug
|
||||
from dsv_debug import (
|
||||
collect_dsv_menu_probe as _collect_dsv_menu_probe,
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
debug_dsv_page_snapshot as _debug_dsv_page_snapshot,
|
||||
debug_dsv_stage as _debug_dsv_stage,
|
||||
report_debug_event as _report_debug_event,
|
||||
)
|
||||
import dsv_session
|
||||
from dsv_session import (
|
||||
DSV_REPORTS_NAV_SELECTORS as _DSV_REPORTS_NAV_SELECTORS,
|
||||
has_dsv_report_nav_attached as _has_dsv_report_nav_attached,
|
||||
has_dsv_report_nav_usable as _has_dsv_report_nav_usable,
|
||||
is_dsv_on_portal_home as _is_dsv_on_portal_home,
|
||||
has_dsv_portal_shell as _has_dsv_portal_shell,
|
||||
is_dsv_home_ready as _is_dsv_home_ready,
|
||||
dismiss_dsv_password_upgrade_prompt as _dismiss_dsv_password_upgrade_prompt,
|
||||
has_dsv_password_upgrade_prompt as _has_dsv_password_upgrade_prompt,
|
||||
wait_for_dsv_app_after_login as _wait_for_dsv_app_after_login,
|
||||
)
|
||||
|
||||
def _has_dsv_report_form_shell(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV 报表参数页的 shell 是否已经挂载完成。
|
||||
|
||||
核心逻辑:用户在菜单里选中目标报表后,`View Report` 按钮常常已经可以点击,
|
||||
但报表标题文本未必立刻出现在 frame 正文里;此时只要 portal reports 路由和
|
||||
SSRS 相关 frame 已出现,就可以认定表单页已基本就绪,避免额外等待标题文本刷出。
|
||||
"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if "/main/portal/frame/reports/" in current_url:
|
||||
return True
|
||||
for frame in getattr(page, "frames", []):
|
||||
try:
|
||||
frame_name = str(frame.name or "").strip().lower()
|
||||
except Exception:
|
||||
frame_name = ""
|
||||
try:
|
||||
frame_url = str(frame.url or "").strip().lower()
|
||||
except Exception:
|
||||
frame_url = ""
|
||||
if frame_name in {"myiframe", "report-frame"}:
|
||||
return True
|
||||
if "/s360reports/ssrs/" in frame_url or "/s360reports/reports/default.aspx" in frame_url:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_report_submission_started(frame: Any, locator: Any) -> bool:
|
||||
"""
|
||||
判断 View Report 点击后是否已开始提交。
|
||||
|
||||
核心逻辑:优先检测按钮是否变为 disabled/隐藏,其次检测 frame 文本里是否出现常见的加载提示,
|
||||
避免“程序化 submit 已调用,但页面其实没有开始处理”的误判。
|
||||
"""
|
||||
try:
|
||||
if not locator.is_visible(timeout=500):
|
||||
return True
|
||||
except Exception:
|
||||
return True
|
||||
try:
|
||||
state = locator.evaluate(
|
||||
"""
|
||||
(node) => ({
|
||||
disabled: Boolean(node.disabled),
|
||||
ariaDisabled: node.getAttribute('aria-disabled'),
|
||||
value: node.value || node.textContent || '',
|
||||
})
|
||||
"""
|
||||
)
|
||||
value = str((state or {}).get("value") or "").strip().lower()
|
||||
if (state or {}).get("disabled") or str((state or {}).get("ariaDisabled") or "").lower() == "true":
|
||||
return True
|
||||
if value and value != "view report":
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
body = frame.locator("body").inner_text(timeout=800).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
transition_markers = (
|
||||
"loading",
|
||||
"please wait",
|
||||
"generating",
|
||||
"processing",
|
||||
"export",
|
||||
"save",
|
||||
"excel",
|
||||
"no records",
|
||||
"no data",
|
||||
)
|
||||
return any(marker in body for marker in transition_markers)
|
||||
|
||||
|
||||
def _dsv_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool:
|
||||
"""
|
||||
判断当前 DSV 页面或 frame 中是否已经出现目标文案。
|
||||
|
||||
核心逻辑:同时扫描顶层页面与各 frame 的可见文本和常见菜单节点,
|
||||
用于级联菜单点击后的“下一层已展开”确认,避免只点到一级菜单就误判成功。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: 需要确认出现的目标文案。
|
||||
timeout_ms: 单次检查的等待时间,默认 1 秒。
|
||||
|
||||
Returns:
|
||||
bool: 找到目标文案时返回 True,否则返回 False。
|
||||
"""
|
||||
normalized = str(text or "").strip().lower()
|
||||
if not normalized:
|
||||
return False
|
||||
selectors = (
|
||||
f"text={text}",
|
||||
f"a:has-text({json.dumps(text)})",
|
||||
f".dropdown-item:has-text({json.dumps(text)})",
|
||||
f"button:has-text({json.dumps(text)})",
|
||||
)
|
||||
for root in (page, *page.frames):
|
||||
for selector in selectors:
|
||||
try:
|
||||
if root.locator(selector).first.is_visible(timeout=timeout_ms):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
body = root.locator("body").inner_text(timeout=timeout_ms).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
if normalized in body:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool:
|
||||
"""
|
||||
仅判断当前展开的 DSV 下拉菜单中是否出现目标文案。
|
||||
|
||||
核心逻辑:主页 `Recent Reports` 也会出现与报表菜单同名的文本;
|
||||
这里将确认范围收紧为 `Reports` 级联菜单容器内的可见项,避免把首页正文误判成下一级菜单已展开。
|
||||
"""
|
||||
normalized = str(text or "").strip().lower()
|
||||
if not normalized:
|
||||
return False
|
||||
selectors = (
|
||||
f"#report-mega-legacy a.dropdown-item:has-text({json.dumps(text)})",
|
||||
f".mega-dropdown-menu a.dropdown-item:has-text({json.dumps(text)})",
|
||||
f".dropdown-menu a.dropdown-item:has-text({json.dumps(text)})",
|
||||
f"#report-mega-legacy [role='menuitem']:has-text({json.dumps(text)})",
|
||||
f".mega-dropdown-menu [role='menuitem']:has-text({json.dumps(text)})",
|
||||
f".dropdown-menu [role='menuitem']:has-text({json.dumps(text)})",
|
||||
f"#report-mega-legacy a:has-text({json.dumps(text)})",
|
||||
f".mega-dropdown-menu a:has-text({json.dumps(text)})",
|
||||
f".dropdown-menu a:has-text({json.dumps(text)})",
|
||||
)
|
||||
for selector in selectors:
|
||||
try:
|
||||
if page.locator(selector).first.is_visible(timeout=timeout_ms):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
probe = _collect_dsv_menu_probe(page, text)
|
||||
for item in probe.get("matchedItems") or []:
|
||||
item_text = str((item or {}).get("text") or "").strip().lower()
|
||||
if item_text and normalized in item_text:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
|
||||
"""
|
||||
点击 DSV 级联菜单项,并在需要时确认下一级目标已经出现。
|
||||
|
||||
核心逻辑:对同一菜单项依次尝试 hover/click/force/evaluate/keyboard 等方式;
|
||||
若传入 next_text,则只有在页面上真正看到下一级菜单文本后才认为本次点击成功。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: 当前要点击的菜单文案。
|
||||
next_text: 预期因本次点击而出现的下一级菜单文案;为空时仅要求当前点击成功。
|
||||
"""
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
raise RuntimeError("DSV menu item text is empty")
|
||||
_report_debug_event(
|
||||
"F",
|
||||
"freight_rpa_worker.py:_click_dsv_menu_item:entry",
|
||||
"[DEBUG] entering dsv menu item selection",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"elapsedMs": 0,
|
||||
**_collect_dsv_menu_probe(page, text),
|
||||
},
|
||||
)
|
||||
text_literal = json.dumps(text)
|
||||
deadline = time.monotonic() + 30
|
||||
started_at = time.monotonic()
|
||||
while time.monotonic() < deadline:
|
||||
for selector in (
|
||||
f"#report-mega-legacy a.dropdown-item:has-text({text_literal})",
|
||||
f".mega-dropdown-menu a.dropdown-item:has-text({text_literal})",
|
||||
f".dropdown-menu a.dropdown-item:has-text({text_literal})",
|
||||
f"#report-mega-legacy [role='menuitem']:has-text({text_literal})",
|
||||
f".mega-dropdown-menu [role='menuitem']:has-text({text_literal})",
|
||||
f".dropdown-menu [role='menuitem']:has-text({text_literal})",
|
||||
f"#report-mega-legacy a:has-text({text_literal})",
|
||||
f".mega-dropdown-menu a:has-text({text_literal})",
|
||||
f".dropdown-menu a:has-text({text_literal})",
|
||||
):
|
||||
try:
|
||||
locator = page.locator(selector).first
|
||||
locator.wait_for(state="visible", timeout=2_000)
|
||||
for action in ("hover", "click", "force-click", "evaluate", "enter", "space"):
|
||||
try:
|
||||
if action == "hover":
|
||||
locator.hover(timeout=1_500)
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
elif action == "click":
|
||||
locator.click(timeout=1_500)
|
||||
elif action == "force-click":
|
||||
locator.click(timeout=1_500, force=True)
|
||||
elif action == "evaluate":
|
||||
locator.evaluate("(node) => node.click()")
|
||||
elif action == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
else:
|
||||
locator.press("Space", timeout=1_500)
|
||||
except Exception:
|
||||
continue
|
||||
_report_debug_event(
|
||||
"F",
|
||||
"freight_rpa_worker.py:_click_dsv_menu_item:attempt",
|
||||
"[DEBUG] dsv menu item attempt dispatched",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"selector": selector,
|
||||
"action": action,
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_menu_probe(page, next_text or text),
|
||||
},
|
||||
)
|
||||
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
|
||||
_report_debug_event(
|
||||
"F",
|
||||
"freight_rpa_worker.py:_click_dsv_menu_item:success",
|
||||
"[DEBUG] dsv menu item selection considered successful",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"selector": selector,
|
||||
"action": action,
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_menu_probe(page, next_text or text),
|
||||
},
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
_report_debug_event(
|
||||
"F",
|
||||
"freight_rpa_worker.py:_click_dsv_menu_item:failed",
|
||||
"[DEBUG] dsv menu item selection timed out",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_menu_probe(page, next_text or text),
|
||||
},
|
||||
)
|
||||
print(f"[dsv-debug] menu item missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}")
|
||||
raise RuntimeError(f"DSV menu item was not found: {text}")
|
||||
|
||||
|
||||
def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None:
|
||||
"""
|
||||
点击 DSV Report Group,并在需要时确认目标报表已经出现在菜单中。
|
||||
|
||||
核心逻辑:Report Group 往往位于 Program 的二级菜单下,单次 click 很容易因为 hover 丢失而失效;
|
||||
这里在每次尝试后立刻检查 next_text,确保真正进入到报表项层级。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: 当前 report group 文案。
|
||||
next_text: 预期出现的报表名称;为空时仅要求当前 group 点击成功。
|
||||
"""
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
raise RuntimeError("DSV report group text is empty")
|
||||
_report_debug_event(
|
||||
"G",
|
||||
"freight_rpa_worker.py:_click_dsv_report_group:entry",
|
||||
"[DEBUG] entering dsv report group selection",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"elapsedMs": 0,
|
||||
**_collect_dsv_menu_probe(page, text),
|
||||
},
|
||||
)
|
||||
text_literal = json.dumps(text)
|
||||
started_at = time.monotonic()
|
||||
for selector in (
|
||||
f"#report-mega-legacy :text-is({text_literal})",
|
||||
f".mega-dropdown-menu :text-is({text_literal})",
|
||||
f".dropdown-menu :text-is({text_literal})",
|
||||
):
|
||||
try:
|
||||
locator = page.locator(selector).first
|
||||
locator.wait_for(state="visible", timeout=10_000)
|
||||
for action in ("hover", "click", "force-click", "evaluate", "enter", "space"):
|
||||
try:
|
||||
if action == "hover":
|
||||
locator.hover(timeout=1_500)
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
elif action == "click":
|
||||
locator.click(timeout=1_500)
|
||||
elif action == "force-click":
|
||||
locator.click(timeout=1_500, force=True)
|
||||
elif action == "evaluate":
|
||||
locator.evaluate("(node) => node.click()")
|
||||
elif action == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
else:
|
||||
locator.press("Space", timeout=1_500)
|
||||
except Exception:
|
||||
continue
|
||||
_report_debug_event(
|
||||
"G",
|
||||
"freight_rpa_worker.py:_click_dsv_report_group:attempt",
|
||||
"[DEBUG] dsv report group attempt dispatched",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"selector": selector,
|
||||
"action": action,
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_menu_probe(page, next_text or text),
|
||||
},
|
||||
)
|
||||
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
|
||||
_report_debug_event(
|
||||
"G",
|
||||
"freight_rpa_worker.py:_click_dsv_report_group:success",
|
||||
"[DEBUG] dsv report group selection considered successful",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
"selector": selector,
|
||||
"action": action,
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_menu_probe(page, next_text or text),
|
||||
},
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
_report_debug_event(
|
||||
"G",
|
||||
"freight_rpa_worker.py:_click_dsv_report_group:failed",
|
||||
"[DEBUG] dsv report group selection timed out",
|
||||
{
|
||||
"targetText": text,
|
||||
"nextText": str(next_text or ""),
|
||||
**_collect_dsv_menu_probe(page, next_text or text),
|
||||
},
|
||||
)
|
||||
print(f"[dsv-debug] report group missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}")
|
||||
raise RuntimeError(f"DSV report group was not found: {text}")
|
||||
|
||||
|
||||
def _click_dsv_view_report(page: Any) -> None:
|
||||
"""
|
||||
点击 SSRS 参数页 View Report。
|
||||
核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。
|
||||
"""
|
||||
selectors = (
|
||||
"#ReportViewerMain_ctl08_ctl00",
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
)
|
||||
_debug_dsv_stage(page, "view-report-before-click", target_text="View Report")
|
||||
wait_ms = max(15_000, int(_env("FREIGHT_RPA_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000"))
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for frame in page.frames:
|
||||
for selector in selectors:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
|
||||
for attempt in click_attempts:
|
||||
try:
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif attempt == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
elif attempt == "space":
|
||||
locator.press("Space", timeout=1_500)
|
||||
elif attempt == "evaluate-click":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
else:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
if (target.form && typeof target.form.requestSubmit === 'function') {
|
||||
target.form.requestSubmit(target);
|
||||
} else if (target.form) {
|
||||
target.form.submit();
|
||||
} else {
|
||||
target.click();
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
submit_deadline = time.monotonic() + 4
|
||||
while time.monotonic() < submit_deadline:
|
||||
if _dsv_report_submission_started(frame, locator):
|
||||
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
|
||||
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
|
||||
raise RuntimeError("DSV View Report button was not found")
|
||||
|
||||
|
||||
def _is_dsv_reports_menu_open(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV Reports 下拉是否已真正展开,而不是仅仅点到了导航按钮。
|
||||
|
||||
核心逻辑:优先检查 `#report-mega-legacy` 上的 `show/open/aria-expanded` 状态,
|
||||
再兜底检查常见下拉容器里是否出现可见菜单项,避免“点击成功但菜单没开”的误判。
|
||||
"""
|
||||
for selector in (
|
||||
"#report-mega-legacy.show",
|
||||
"#report-mega-legacy.open",
|
||||
"#report-mega-legacy[aria-expanded='true']",
|
||||
"#report-mega-legacy .mega-dropdown-menu.show",
|
||||
"#report-mega-legacy .dropdown-menu.show",
|
||||
".mega-dropdown-menu.show",
|
||||
".dropdown-menu.show",
|
||||
):
|
||||
try:
|
||||
if page.locator(selector).first.is_visible(timeout=150):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for selector in (
|
||||
"#report-mega-legacy .dropdown-item",
|
||||
".mega-dropdown-menu a.dropdown-item",
|
||||
".dropdown-menu a.dropdown-item",
|
||||
):
|
||||
try:
|
||||
locator = page.locator(selector).first
|
||||
if locator.is_visible(timeout=150):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_dsv_reports_menu(page: Any) -> None:
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point B:reports-click-entry
|
||||
_report_debug_event(
|
||||
"B",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:entry",
|
||||
"[DEBUG] entering reports click flow",
|
||||
{"elapsedMs": 0, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
click_selectors = (
|
||||
"#report-mega-legacy > a.dropdown-toggle.nav-link",
|
||||
"#report-mega-legacy a.dropdown-toggle",
|
||||
"#report-mega-legacy a.nav-link",
|
||||
"nav a:has-text('Reports')",
|
||||
"a.nav-link:has-text('Reports')",
|
||||
)
|
||||
click_roots = [page, *list(getattr(page, "frames", []))]
|
||||
for selector in click_selectors:
|
||||
for root in click_roots:
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=5_000)
|
||||
except Exception:
|
||||
continue
|
||||
# [STEP 1] Reports 打开优先走真实 click,避免先 hover 白等一轮再退回 click。
|
||||
for action_name in ("click", "evaluate", "enter", "space", "hover"):
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=2_000)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if action_name == "hover":
|
||||
locator.hover(timeout=2_000)
|
||||
elif action_name == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif action_name == "evaluate":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
elif action_name == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
else:
|
||||
locator.press("Space", timeout=1_500)
|
||||
except Exception:
|
||||
continue
|
||||
# #region debug-point B:reports-click-attempt
|
||||
_report_debug_event(
|
||||
"B",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:attempt",
|
||||
"[DEBUG] reports click attempt dispatched",
|
||||
{
|
||||
"selector": selector,
|
||||
"action": action_name,
|
||||
**_collect_dsv_reports_probe(page),
|
||||
},
|
||||
)
|
||||
# #endregion
|
||||
post_action_wait_seconds = 0.6 if action_name == "hover" else 1.2
|
||||
action_deadline = time.monotonic() + post_action_wait_seconds
|
||||
while time.monotonic() < action_deadline:
|
||||
if _is_dsv_reports_menu_open(page):
|
||||
print(f"[dsv] reports expanded via {action_name} selector={selector!r}")
|
||||
_debug_dsv_stage(page, f"reports-expanded-{action_name}", target_text="Reports")
|
||||
# #region debug-point D:reports-expanded
|
||||
_report_debug_event(
|
||||
"D",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:expanded",
|
||||
"[DEBUG] reports menu expanded after click attempt",
|
||||
{
|
||||
"selector": selector,
|
||||
"action": action_name,
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_reports_probe(page),
|
||||
},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
time.sleep(0.2)
|
||||
print(f"[dsv-debug] reports menu missing {_debug_dsv_page_snapshot(page, target_text='Reports')}")
|
||||
# #region debug-point C:reports-click-failed
|
||||
_report_debug_event(
|
||||
"C",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:failed",
|
||||
"[DEBUG] reports menu click flow exhausted without expansion",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
raise RuntimeError("DSV Reports menu was not found")
|
||||
def _wait_for_dsv_reports_nav_stable(page: Any, *, timeout_ms: int | None = None) -> None:
|
||||
"""
|
||||
在首页 ready 之后,继续等待 Reports 导航进入可稳定交互态。
|
||||
|
||||
核心逻辑:首页首屏刚渲染完成时,Reports 虽然已经可见,但 hover/click 仍可能被吞掉;
|
||||
这里要求导航链接连续多次保持可见,降低“刚进首页就急着点”的误触发概率。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else 8_000
|
||||
selectors = (
|
||||
"#report-mega-legacy > a.dropdown-toggle.nav-link",
|
||||
"#report-mega-legacy a.dropdown-toggle",
|
||||
"#report-mega-legacy a.nav-link",
|
||||
)
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
stable_hits = 0
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point L:reports-nav-stable-entry
|
||||
_report_debug_event(
|
||||
"L",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:entry",
|
||||
"[DEBUG] waiting for dsv reports nav stable",
|
||||
{"timeoutMs": wait_ms, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
while time.monotonic() < deadline:
|
||||
visible = False
|
||||
click_roots = [page, *list(getattr(page, "frames", []))]
|
||||
for selector in selectors:
|
||||
for root in click_roots:
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.is_visible(timeout=200):
|
||||
visible = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if visible:
|
||||
break
|
||||
if visible:
|
||||
stable_hits += 1
|
||||
if stable_hits >= 3:
|
||||
# #region debug-point L:reports-nav-stable-success
|
||||
_report_debug_event(
|
||||
"L",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:success",
|
||||
"[DEBUG] dsv reports nav considered stable",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
else:
|
||||
stable_hits = 0
|
||||
time.sleep(0.4)
|
||||
# #region debug-point L:reports-nav-stable-timeout
|
||||
_report_debug_event(
|
||||
"L",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:timeout",
|
||||
"[DEBUG] dsv reports nav did not become stable in time",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
|
||||
|
||||
def _wait_for_dsv_reports_open(page: Any, *, timeout_ms: int | None = None) -> None:
|
||||
"""
|
||||
等待 Reports 下拉真正展开。
|
||||
|
||||
核心逻辑:菜单导航偶发存在 hover/click 已触发但 DOM 尚未展开的情况;
|
||||
这里统一以 `_is_dsv_reports_menu_open()` 为成功判据,避免“看起来点了,实际没开”。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else 15_000
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if _is_dsv_reports_menu_open(page):
|
||||
_debug_dsv_stage(page, "reports-open-confirmed", target_text="Reports")
|
||||
# #region debug-point D:reports-open-confirmed
|
||||
_report_debug_event(
|
||||
"D",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_open:confirmed",
|
||||
"[DEBUG] reports open confirmed",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
time.sleep(0.3)
|
||||
_debug_dsv_stage(page, "reports-open-timeout", target_text="Reports")
|
||||
# #region debug-point D:reports-open-timeout
|
||||
_report_debug_event(
|
||||
"D",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_open:timeout",
|
||||
"[DEBUG] reports open confirmation timed out",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
raise RuntimeError("DSV Reports menu did not expand")
|
||||
|
||||
|
||||
def _wait_for_dsv_report_form_ready(page: Any, report_name: str, *, timeout_ms: int | None = None) -> None:
|
||||
"""
|
||||
等待报表表单页稳定可操作。
|
||||
|
||||
核心逻辑:选择 Program / Group / Report 后,不立即假设已进入表单页;
|
||||
优先要求 `View Report` 按钮出现,同时满足“报表标题文本已出现”或“报表 shell/frame 已挂载”,
|
||||
这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else max(
|
||||
60_000, int(_env("FREIGHT_RPA_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000")
|
||||
)
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
started_at = time.monotonic()
|
||||
normalized_report = str(report_name or "").strip().lower()
|
||||
last_probe_signature: tuple[bool, bool, bool] | None = None
|
||||
last_probe_logged_at = 0.0
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:entry",
|
||||
"[DEBUG] waiting for dsv report form ready",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
while time.monotonic() < deadline:
|
||||
view_report_visible = False
|
||||
try:
|
||||
if _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
(
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
),
|
||||
timeout_ms=1_000,
|
||||
) is not None:
|
||||
view_report_visible = True
|
||||
except Exception:
|
||||
view_report_visible = False
|
||||
report_title_visible = False
|
||||
if normalized_report:
|
||||
for frame in page.frames:
|
||||
try:
|
||||
body = frame.locator("body").inner_text(timeout=500).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
if normalized_report in body:
|
||||
report_title_visible = True
|
||||
break
|
||||
form_shell_ready = _has_dsv_report_form_shell(page)
|
||||
probe_signature = (view_report_visible, report_title_visible, form_shell_ready)
|
||||
now = time.monotonic()
|
||||
if probe_signature != last_probe_signature or (now - last_probe_logged_at) >= 2.0:
|
||||
print(
|
||||
"[dsv-report-form-probe] "
|
||||
f"elapsedMs={int((now - started_at) * 1000)} "
|
||||
f"viewReportVisible={view_report_visible} "
|
||||
f"reportTitleVisible={report_title_visible} "
|
||||
f"formShellReady={form_shell_ready} "
|
||||
f"stateChanged={probe_signature != last_probe_signature}"
|
||||
)
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:probe",
|
||||
"[DEBUG] dsv report form probe state",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
"elapsedMs": int((now - started_at) * 1000),
|
||||
"viewReportVisible": view_report_visible,
|
||||
"reportTitleVisible": report_title_visible,
|
||||
"formShellReady": form_shell_ready,
|
||||
"stateChanged": probe_signature != last_probe_signature,
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
last_probe_signature = probe_signature
|
||||
last_probe_logged_at = now
|
||||
if form_shell_ready and report_title_visible and not view_report_visible:
|
||||
remaining_ms = max(0, int((deadline - time.monotonic()) * 1000))
|
||||
if remaining_ms > 0:
|
||||
if _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
(
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
),
|
||||
timeout_ms=min(remaining_ms, 45_000),
|
||||
) is not None:
|
||||
view_report_visible = True
|
||||
print(
|
||||
"[dsv-report-form-probe] viewReport appeared after shell+title "
|
||||
f"elapsedMs={int((time.monotonic() - started_at) * 1000)}"
|
||||
)
|
||||
if view_report_visible and (report_title_visible or form_shell_ready or not normalized_report):
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:success",
|
||||
"[DEBUG] dsv report form became ready",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
"viewReportVisible": view_report_visible,
|
||||
"reportTitleVisible": report_title_visible,
|
||||
"formShellReady": form_shell_ready,
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
_debug_dsv_stage(page, "report-form-ready", target_text=report_name or "View Report")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:timeout",
|
||||
"[DEBUG] dsv report form wait timed out",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
"viewReportVisible": view_report_visible,
|
||||
"reportTitleVisible": report_title_visible,
|
||||
"formShellReady": _has_dsv_report_form_shell(page),
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
_debug_dsv_stage(page, "report-form-timeout", target_text=report_name or "View Report")
|
||||
raise RuntimeError("DSV report form was not ready")
|
||||
|
||||
|
||||
|
||||
# 公开 API
|
||||
has_dsv_report_form_shell = _has_dsv_report_form_shell
|
||||
dsv_report_submission_started = _dsv_report_submission_started
|
||||
dsv_text_visible = _dsv_text_visible
|
||||
dsv_dropdown_text_visible = _dsv_dropdown_text_visible
|
||||
click_dsv_menu_item = _click_dsv_menu_item
|
||||
click_dsv_report_group = _click_dsv_report_group
|
||||
click_dsv_view_report = _click_dsv_view_report
|
||||
is_dsv_reports_menu_open = _is_dsv_reports_menu_open
|
||||
click_dsv_reports_menu = _click_dsv_reports_menu
|
||||
wait_for_dsv_reports_nav_stable = _wait_for_dsv_reports_nav_stable
|
||||
wait_for_dsv_reports_open = _wait_for_dsv_reports_open
|
||||
wait_for_dsv_report_form_ready = _wait_for_dsv_report_form_ready
|
||||
File diff suppressed because it is too large.
Load diff
@@ -195,20 +195,28 @@ def _fill_input_via_script(root: Any, selector: str, value: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, timeout_ms: int) -> bool:
|
||||
def _fill_multi_value_parameter(
|
||||
page: Any,
|
||||
label: str,
|
||||
values: list[str],
|
||||
*,
|
||||
timeout_ms: int,
|
||||
config_override: dict[str, str] | None = None,
|
||||
select_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。
|
||||
核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。
|
||||
"""
|
||||
config = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
|
||||
config = {**_DSV_REPORT_PARAM_DEFAULTS.get(label, {}), **(config_override or {})}
|
||||
if config.get("control") != "multi_value":
|
||||
return False
|
||||
cleaned = [str(item).strip() for item in values if str(item).strip()]
|
||||
if not cleaned:
|
||||
if not cleaned and not select_all:
|
||||
return False
|
||||
|
||||
_, text_locator = _find_locator(page, config["text"])
|
||||
if text_locator is not None:
|
||||
if text_locator is not None and not select_all:
|
||||
try:
|
||||
current = str(text_locator.input_value(timeout=2_000) or "").strip()
|
||||
if current and all(item in current for item in cleaned):
|
||||
@@ -233,15 +241,17 @@ def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, tim
|
||||
try:
|
||||
adjusted = root.evaluate(
|
||||
"""
|
||||
({ dropdownSelector, desiredValues, restrictToDesired }) => {
|
||||
({ dropdownSelector, desiredValues, restrictToDesired, selectAll }) => {
|
||||
const dropdown = document.querySelector(dropdownSelector);
|
||||
if (!dropdown) return false;
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
|
||||
const labels = Array.from(dropdown.querySelectorAll('label'));
|
||||
let changed = false;
|
||||
let selectAllClicked = false;
|
||||
const entries = [];
|
||||
for (const labelNode of labels) {
|
||||
const text = normalize(labelNode.textContent);
|
||||
if (!text || text === '(Select All)') continue;
|
||||
if (!text) continue;
|
||||
let checkbox = null;
|
||||
const htmlFor = labelNode.getAttribute('for');
|
||||
if (htmlFor) {
|
||||
@@ -251,14 +261,37 @@ def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, tim
|
||||
checkbox = labelNode.previousElementSibling;
|
||||
}
|
||||
if (!checkbox || checkbox.type !== 'checkbox') continue;
|
||||
const shouldCheck = desiredValues.includes(text.toLowerCase());
|
||||
if (restrictToDesired) {
|
||||
if (checkbox.checked !== shouldCheck) {
|
||||
const isSelectAll = text === '(Select All)' || text.toLowerCase().includes('select all');
|
||||
entries.push({ text, checkbox, isSelectAll });
|
||||
if (selectAll && isSelectAll) {
|
||||
if (!checkbox.checked) {
|
||||
checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
} else if (shouldCheck && !checkbox.checked) {
|
||||
checkbox.click();
|
||||
selectAllClicked = true;
|
||||
}
|
||||
}
|
||||
if (selectAll && !selectAllClicked) {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isSelectAll && !entry.checkbox.checked) {
|
||||
entry.checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (selectAll) {
|
||||
return changed || entries.length > 0;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.isSelectAll) continue;
|
||||
const shouldCheck = desiredValues.includes(text.toLowerCase());
|
||||
if (restrictToDesired) {
|
||||
if (entry.checkbox.checked !== shouldCheck) {
|
||||
entry.checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
} else if (shouldCheck && !entry.checkbox.checked) {
|
||||
entry.checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -269,10 +302,14 @@ def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, tim
|
||||
"dropdownSelector": config["dropdown"],
|
||||
"desiredValues": list(desired),
|
||||
"restrictToDesired": label == "PutawayZone",
|
||||
"selectAll": select_all,
|
||||
},
|
||||
)
|
||||
if adjusted:
|
||||
print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}")
|
||||
if select_all:
|
||||
print(f"[dsv-filter] {label} multi_value select_all")
|
||||
else:
|
||||
print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}")
|
||||
if toggle is not None:
|
||||
try:
|
||||
toggle.click(timeout=2_000, force=True)
|
||||
@@ -405,3 +442,35 @@ def fill_dsv_filter_if_needed(
|
||||
|
||||
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
|
||||
_debug(f"filter-failed-{label.lower()}", text)
|
||||
|
||||
|
||||
def fill_dsv_multi_select_parameter(
|
||||
page: Any,
|
||||
label: str,
|
||||
values: list[str],
|
||||
*,
|
||||
selectors: dict[str, str] | None = None,
|
||||
select_all: bool = False,
|
||||
browser_timeout_ms: Callable[[], int],
|
||||
) -> bool:
|
||||
"""
|
||||
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
|
||||
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
|
||||
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
|
||||
"""
|
||||
config_override = {"control": "multi_value"}
|
||||
if selectors:
|
||||
for key in ("text", "toggle", "dropdown"):
|
||||
value = str(selectors.get(key) or "").strip()
|
||||
if value:
|
||||
config_override[key] = value
|
||||
if not all(config_override.get(key) for key in ("text", "toggle", "dropdown")):
|
||||
return False
|
||||
return _fill_multi_value_parameter(
|
||||
page,
|
||||
label,
|
||||
values,
|
||||
timeout_ms=browser_timeout_ms(),
|
||||
config_override=config_override,
|
||||
select_all=select_all,
|
||||
)
|
||||
@@ -0,0 +1,349 @@
|
||||
"""
|
||||
scripts/rpa/dsv_session.py
|
||||
|
||||
用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。
|
||||
依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。
|
||||
逻辑:dsv_navigation / dsv_debug 探针;dsv_report_export 在 ensure 前检测 session。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
import dsv_debug
|
||||
from dsv_debug import (
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
debug_dsv_stage as _debug_dsv_stage,
|
||||
report_debug_event as _report_debug_event,
|
||||
)
|
||||
|
||||
|
||||
_DSV_REPORTS_NAV_SELECTORS: tuple[str, ...] = (
|
||||
"#report-mega-legacy",
|
||||
"#report-mega-legacy > a.dropdown-toggle.nav-link",
|
||||
"#report-mega-legacy a.dropdown-toggle",
|
||||
"#report-mega-legacy a.nav-link",
|
||||
"nav a:has-text('Reports')",
|
||||
"a.nav-link:has-text('Reports')",
|
||||
)
|
||||
|
||||
def _iter_dsv_report_nav_locators(page: Any):
|
||||
"""在所有 frame 与顶层 page 中查找 Reports 顶栏相关 locator。"""
|
||||
roots = [page, *list(getattr(page, "frames", []))]
|
||||
for root in roots:
|
||||
for selector in _DSV_REPORTS_NAV_SELECTORS:
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.count() > 0:
|
||||
yield root, selector, locator
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
def _has_dsv_report_nav_attached(page: Any) -> bool:
|
||||
"""Reports 顶栏 DOM 是否已挂载(跨 frame + 文本 fallback)。"""
|
||||
return next(_iter_dsv_report_nav_locators(page), None) is not None
|
||||
|
||||
def _has_dsv_report_nav_usable(page: Any) -> bool:
|
||||
"""
|
||||
Reports 导航是否已可用于后续点击。
|
||||
核心逻辑:用户肉眼看到首页时,顶栏 Reports 可能已 visible 但 #report-mega-legacy 计数仍为 0;
|
||||
因此同时接受 attached 与短超时 visible 探测。
|
||||
"""
|
||||
for _, _, locator in _iter_dsv_report_nav_locators(page):
|
||||
try:
|
||||
if locator.is_visible(timeout=200):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return _has_dsv_report_nav_attached(page)
|
||||
|
||||
def _is_dsv_on_portal_home(page: Any) -> bool:
|
||||
"""URL 已在 portal 且主页面已出现 Home/Favorites/Recent Reports 等内容。"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if "auth.dbschenker.com" in current_url:
|
||||
return False
|
||||
if "s360.dbschenker.com" not in current_url:
|
||||
return False
|
||||
try:
|
||||
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
return any(marker in body for marker in ("home favorites", "recent reports", "favorites"))
|
||||
|
||||
def _wait_for_dsv_app_after_login(
|
||||
page: Any,
|
||||
timeout_ms: int | None = None,
|
||||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
等待 DSV 从登录链路切回 portal 壳层。
|
||||
|
||||
核心逻辑:`Verifying compliance` 这类认证过渡页并不代表首页导航已经可操作;
|
||||
这里单独识别 auth/合规过渡态,避免在该阶段反复用长超时探测 `#report-mega-legacy`,
|
||||
从而把“认证收尾慢”和“Reports 菜单慢”混在一起。
|
||||
"""
|
||||
import dsv_auth
|
||||
|
||||
wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
last_debug_at = 0.0
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point J:wait-app-entry
|
||||
_report_debug_event(
|
||||
"J",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:entry",
|
||||
"[DEBUG] waiting for dsv app shell after login",
|
||||
{"timeoutMs": wait_ms, "url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
_debug_dsv_stage(page, "wait-app-start", target_text="Reports")
|
||||
last_portal_home_log_at = 0.0
|
||||
portal_shell_callback_fired = False
|
||||
while time.monotonic() < deadline:
|
||||
now = time.monotonic()
|
||||
current_url = str(page.url or "").lower()
|
||||
auth_transition = False
|
||||
try:
|
||||
current_title = str(page.title() or "").lower()
|
||||
except Exception:
|
||||
current_title = ""
|
||||
auth_transition = "auth.dbschenker.com" in current_url or "verifying compliance" in current_title
|
||||
if now - last_debug_at >= 3:
|
||||
elapsed = int((time.monotonic() - started_at) * 1000)
|
||||
_debug_dsv_stage(page, f"wait-app-{elapsed // 1000}s", target_text="Reports")
|
||||
last_debug_at = now
|
||||
if _has_dsv_report_nav_usable(page):
|
||||
if on_portal_shell_seen is not None:
|
||||
on_portal_shell_seen()
|
||||
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
|
||||
_report_debug_event(
|
||||
"J",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
|
||||
"[DEBUG] dsv reports nav usable after login",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
return True
|
||||
if not auth_transition and _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
_DSV_REPORTS_NAV_SELECTORS,
|
||||
timeout_ms=400,
|
||||
) is not None:
|
||||
if on_portal_shell_seen is not None:
|
||||
on_portal_shell_seen()
|
||||
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
|
||||
_report_debug_event(
|
||||
"J",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
|
||||
"[DEBUG] dsv reports nav visible after login",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
return True
|
||||
on_portal_home = _is_dsv_on_portal_home(page)
|
||||
if on_portal_home and not auth_transition:
|
||||
if on_portal_shell_seen is not None and not portal_shell_callback_fired:
|
||||
on_portal_shell_seen()
|
||||
portal_shell_callback_fired = True
|
||||
if now - last_portal_home_log_at >= 2.0:
|
||||
print(
|
||||
"[dsv-home] portal home visible, waiting Reports nav "
|
||||
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} "
|
||||
f"report_nav_attached={_has_dsv_report_nav_attached(page)} url={page.url!r}"
|
||||
)
|
||||
last_portal_home_log_at = now
|
||||
elif _has_dsv_portal_shell(page) and on_portal_shell_seen is not None and not portal_shell_callback_fired:
|
||||
on_portal_shell_seen()
|
||||
portal_shell_callback_fired = True
|
||||
if auth_transition:
|
||||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||||
continue
|
||||
# [STEP] 合规/认证过渡页仅用轻量短超时探测 Reports 导航,避免与首页长轮询混淆。
|
||||
_wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
_DSV_REPORTS_NAV_SELECTORS,
|
||||
timeout_ms=400,
|
||||
)
|
||||
time.sleep(0.25)
|
||||
continue
|
||||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||||
if not _has_dsv_report_nav_usable(page) and dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||||
continue
|
||||
try:
|
||||
page.wait_for_load_state("domcontentloaded", timeout=1_500)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
_debug_dsv_stage(page, "wait-app-timeout", target_text="Reports")
|
||||
# #region debug-point J:wait-app-timeout
|
||||
_report_debug_event(
|
||||
"J",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:timeout",
|
||||
"[DEBUG] dsv app shell wait timed out",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
return False
|
||||
|
||||
def _has_dsv_portal_shell(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV portal 内容壳层是否已出现。
|
||||
|
||||
核心逻辑:dashboard iframe 的欢迎语/Recent Reports 往往先于顶栏 `#report-mega-legacy`
|
||||
渲染完成;此函数用于记录 portal_shell_seen 时间点,但不应单独作为 home-ready 判据。
|
||||
"""
|
||||
if _has_dsv_report_nav_attached(page):
|
||||
return True
|
||||
portal_markers = ("home favorites", "recent reports", "360 — your contract logistics portal")
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
for root in roots:
|
||||
try:
|
||||
body = str(root.locator("body").inner_text(timeout=1_000) or "").lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
if any(marker in body for marker in portal_markers):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _is_dsv_home_ready(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV 是否已经稳定进入首页导航态。
|
||||
|
||||
核心逻辑:必须离开认证域名,且 Reports 导航已可用(跨 frame 探测);
|
||||
用户肉眼已在 portal 首页时,不再仅依赖顶层 #report-mega-legacy 计数。
|
||||
"""
|
||||
if "auth.dbschenker.com" in page.url:
|
||||
return False
|
||||
return _has_dsv_report_nav_usable(page)
|
||||
|
||||
def _wait_for_dsv_home_ready(
|
||||
page: Any,
|
||||
*,
|
||||
timeout_ms: int | None = None,
|
||||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
等待 DSV 首页真正稳定可操作。
|
||||
|
||||
核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现,
|
||||
失败则直接在“首页阶段”报错,避免主流程跳步到 Reports/View Report。
|
||||
"""
|
||||
import dsv_auth
|
||||
|
||||
wait_ms = timeout_ms if timeout_ms is not None else 60_000
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point K:home-wait-entry
|
||||
_report_debug_event(
|
||||
"K",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:entry",
|
||||
"[DEBUG] entering dsv home ready wait",
|
||||
{"timeoutMs": wait_ms, "url": page.url, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||||
if _is_dsv_home_ready(page):
|
||||
if on_portal_shell_seen is not None:
|
||||
on_portal_shell_seen()
|
||||
_debug_dsv_stage(page, "home-ready", target_text="Reports")
|
||||
# #region debug-point A:home-ready
|
||||
_report_debug_event(
|
||||
"A",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready",
|
||||
"[DEBUG] dsv home considered ready before wait loop",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
if _wait_for_dsv_app_after_login(page, timeout_ms=wait_ms, on_portal_shell_seen=on_portal_shell_seen):
|
||||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||||
if _is_dsv_home_ready(page):
|
||||
if on_portal_shell_seen is not None:
|
||||
on_portal_shell_seen()
|
||||
_debug_dsv_stage(page, "home-ready-after-wait", target_text="Reports")
|
||||
# #region debug-point A:home-ready-after-wait
|
||||
_report_debug_event(
|
||||
"A",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_wait",
|
||||
"[DEBUG] dsv home considered ready after app wait",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
_debug_dsv_stage(page, "home-not-ready", target_text="Reports")
|
||||
# #region debug-point A:home-not-ready
|
||||
_report_debug_event(
|
||||
"A",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:timeout",
|
||||
"[DEBUG] dsv home was not ready before reports click",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
raise RuntimeError("DSV home page was not ready after login")
|
||||
|
||||
def _goto_dsv_entry_url(page: Any, entry_url: str) -> None:
|
||||
"""
|
||||
打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。
|
||||
|
||||
核心逻辑:s360 -> auth 重定向链可能超过单次 goto 默认超时,不应因此中断 batch。
|
||||
"""
|
||||
try:
|
||||
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||||
except Exception as exc:
|
||||
message = str(exc).lower()
|
||||
if "timeout" not in message:
|
||||
raise
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if any(token in current_url for token in ("auth.dbschenker.com", "s360.dbschenker.com")):
|
||||
print(
|
||||
"[dsv] entry goto domcontentloaded timeout, continue auth redirect "
|
||||
f"url={page.url!r}"
|
||||
)
|
||||
return
|
||||
raise
|
||||
|
||||
|
||||
# 公开 API
|
||||
DSV_REPORTS_NAV_SELECTORS = _DSV_REPORTS_NAV_SELECTORS
|
||||
goto_dsv_entry_url = _goto_dsv_entry_url
|
||||
has_dsv_portal_shell = _has_dsv_portal_shell
|
||||
has_dsv_report_nav_attached = _has_dsv_report_nav_attached
|
||||
has_dsv_report_nav_usable = _has_dsv_report_nav_usable
|
||||
is_dsv_home_ready = _is_dsv_home_ready
|
||||
is_dsv_on_portal_home = _is_dsv_on_portal_home
|
||||
iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators
|
||||
wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login
|
||||
wait_for_dsv_home_ready = _wait_for_dsv_home_ready
|
||||
|
||||
# 向后兼容:登录 API 仍可从 dsv_session 引用
|
||||
from dsv_auth import ( # noqa: E402
|
||||
DSV_USERNAME_SELECTORS,
|
||||
click_dsv_continue,
|
||||
click_dsv_password_method,
|
||||
dismiss_dsv_password_upgrade_prompt,
|
||||
fill_dsv_password_page_fields,
|
||||
fill_dsv_username,
|
||||
find_dsv_password_locator,
|
||||
has_dsv_human_check_prompt,
|
||||
has_dsv_password_upgrade_prompt,
|
||||
is_dsv_username_page,
|
||||
looks_like_dsv_login_method_page,
|
||||
maybe_auto_login_dsv,
|
||||
submit_dsv_password_form,
|
||||
wait_for_dsv_human_check_if_present,
|
||||
wait_for_dsv_login_method_page,
|
||||
)
|
||||
+160
-3924
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,466 @@
|
||||
"""
|
||||
scripts/rpa/rpa_common.py
|
||||
|
||||
用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。
|
||||
依赖:标准库、Playwright(运行时)。
|
||||
逻辑:由 freight_rpa_worker、dsv_*、crane_* 导入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any, TextIO
|
||||
|
||||
|
||||
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
"""惰性委托 dsv_debug.emit_debug_event,避免 rpa_common ↔ dsv_debug 循环导入。"""
|
||||
try:
|
||||
from dsv_debug import emit_debug_event
|
||||
|
||||
emit_debug_event(run_id, hypothesis_id, location, msg, data)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def _env(name: str, default: str = "") -> str:
|
||||
"""
|
||||
读取 RPA 环境变量,并兼容 .env 中常见的外层单双引号写法。
|
||||
|
||||
核心逻辑:先读取原始环境变量并去除首尾空白;若值整体被同种引号包裹,
|
||||
再剥离最外层一对引号,避免账号密码把引号一并输入到第三方登录页。
|
||||
|
||||
Args:
|
||||
name: 环境变量名。
|
||||
default: 未设置时的默认值。
|
||||
|
||||
Returns:
|
||||
str: 去除空白与外层成对引号后的环境变量值。
|
||||
"""
|
||||
value = str(os.getenv(name) or default).strip()
|
||||
if len(value) >= 2 and (
|
||||
(value.startswith('"') and value.endswith('"'))
|
||||
or (value.startswith("'") and value.endswith("'"))
|
||||
):
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def _browser_timeout_ms() -> int:
|
||||
return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000"))
|
||||
|
||||
def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None:
|
||||
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
text_literal = json.dumps(text)
|
||||
for selector in (
|
||||
f"a.dropdown-item:has-text({text_literal})",
|
||||
f".dropdown-item:has-text({text_literal})",
|
||||
f"button:has-text({text_literal})",
|
||||
f'[role="button"]:has-text({text_literal})',
|
||||
f"a:has-text({text_literal})",
|
||||
f"li:has-text({text_literal})",
|
||||
f"div.device-type:has-text({text_literal})",
|
||||
):
|
||||
locator = page.locator(selector).first
|
||||
try:
|
||||
locator.click(timeout=3_000)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=3_000, force=True)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
for role in ("button", "link"):
|
||||
try:
|
||||
page.get_by_role(role, name=text, exact=exact).first.click(timeout=3_000)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator = page.get_by_text(text, exact=False).first
|
||||
try:
|
||||
locator.click(timeout=min(timeout, 3_000))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.click(timeout=min(timeout, 3_000), force=True)
|
||||
|
||||
|
||||
def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None:
|
||||
selector = _env(selector_env)
|
||||
if selector:
|
||||
page.locator(selector).first.click(timeout=_browser_timeout_ms())
|
||||
return
|
||||
if selector_env == "FREIGHT_RPA_DSV_VIEW_REPORT_SELECTOR":
|
||||
for view_selector in (
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
'.btn:has-text("View Report")',
|
||||
'input[value="View Report"]',
|
||||
'[role="button"]:has-text("View Report")',
|
||||
):
|
||||
try:
|
||||
locator = page.locator(view_selector).first
|
||||
locator.wait_for(state="visible", timeout=30_000)
|
||||
locator.evaluate("(node) => node.click()")
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
if fallback_text:
|
||||
_click_text(page, fallback_text, exact=True)
|
||||
return
|
||||
raise RuntimeError(f"Missing selector env: {selector_env}")
|
||||
|
||||
|
||||
def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label).first
|
||||
try:
|
||||
current = str(locator.input_value(timeout=3_000) or "").strip()
|
||||
if current == text:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.fill_dsv_filter_if_needed(
|
||||
page,
|
||||
selector_env,
|
||||
label,
|
||||
value,
|
||||
env=_env,
|
||||
browser_timeout_ms=_browser_timeout_ms,
|
||||
debug_stage=_debug_dsv_stage,
|
||||
)
|
||||
|
||||
|
||||
def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label)
|
||||
try:
|
||||
locator.select_option(label=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.select_option(value=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
for frame in page.frames:
|
||||
locator = frame.locator(selector).first
|
||||
try:
|
||||
return locator if locator.is_visible(timeout=1_000) else None
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _visible_locator_in_root(root: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
return locator if locator.is_visible(timeout=1_000) else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _click_text_in_root(root: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> bool:
|
||||
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
text_literal = json.dumps(text)
|
||||
for selector in (
|
||||
f'a.dropdown-item:has-text({text_literal})',
|
||||
f'.dropdown-item:has-text({text_literal})',
|
||||
f'button:has-text({text_literal})',
|
||||
f'[role="button"]:has-text({text_literal})',
|
||||
f'a:has-text({text_literal})',
|
||||
f'li:has-text({text_literal})',
|
||||
f'span:has-text({text_literal})',
|
||||
):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.click(timeout=min(timeout, 3_000), force=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for role in ("button", "link"):
|
||||
try:
|
||||
root.get_by_role(role, name=text, exact=exact).first.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000), force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _click_visible_selector_or_text_in_root(root: Any, selector: str | None, fallback_texts: tuple[str, ...]) -> bool:
|
||||
locator = _visible_locator_in_root(root, selector)
|
||||
if locator is not None:
|
||||
# #region debug-point H4:root-selector-click-attempt
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-attempt",
|
||||
"[DEBUG] attempting selector click in selected root",
|
||||
{"selector": selector or "", "fallbackTexts": list(fallback_texts)},
|
||||
)
|
||||
# #endregion
|
||||
try:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
# #region debug-point H4:root-selector-click-success
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-success",
|
||||
"[DEBUG] selector click succeeded in selected root",
|
||||
{"selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
return True
|
||||
except Exception as exc:
|
||||
# #region debug-point H4:root-selector-click-error
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-error",
|
||||
"[DEBUG] selector click failed in selected root",
|
||||
{"selector": selector or "", "error": str(exc)[:300]},
|
||||
)
|
||||
# #endregion
|
||||
for text in fallback_texts:
|
||||
# #region debug-point H4:root-text-click-attempt
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-attempt",
|
||||
"[DEBUG] attempting text click in selected root",
|
||||
{"text": text, "selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
clicked = _click_text_in_root(root, text, exact=True, timeout_ms=3_000)
|
||||
# #region debug-point H4:root-text-click-result
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-result",
|
||||
"[DEBUG] text click result in selected root",
|
||||
{"text": text, "clicked": clicked, "selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
if clicked:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool:
|
||||
value = _env(value_env)
|
||||
if not value:
|
||||
return False
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.fill(value, timeout=_browser_timeout_ms())
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_first_visible_text_input(page: Any, value: str) -> bool:
|
||||
for selector in (
|
||||
'input:not([type])',
|
||||
'input[type="text"]',
|
||||
'input[type="email"]',
|
||||
'input',
|
||||
):
|
||||
for frame in page.frames:
|
||||
try:
|
||||
inputs = frame.locator(selector).all()
|
||||
except Exception:
|
||||
inputs = []
|
||||
for locator in inputs:
|
||||
try:
|
||||
if not locator.is_visible(timeout=500) or not _dsv_locator_can_edit(locator):
|
||||
continue
|
||||
locator.fill(value, timeout=2_000)
|
||||
if locator.input_value(timeout=1_000).strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
page.get_by_role("button", name=text).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.get_by_text(text, exact=True).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_visible_selector_or_text(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
if any(text in {"登录", "Login", "Log in", "Sign in"} for text in fallback_texts):
|
||||
for submit_selector in (
|
||||
'button[type="submit"]',
|
||||
'input[type="submit"]',
|
||||
"#signOnButton",
|
||||
".btn-primary",
|
||||
):
|
||||
locator = _visible_locator(page, submit_selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.click(timeout=3_000, force=True)
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
_click_text(page, text, exact=True, timeout_ms=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
def _wait_for_visible_selector(
|
||||
page: Any,
|
||||
selector_env: str,
|
||||
fallback_selectors: tuple[str, ...],
|
||||
*,
|
||||
timeout_ms: int | None = None,
|
||||
):
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for selector in selectors:
|
||||
for frame in page.frames:
|
||||
locator = frame.locator(selector).first
|
||||
try:
|
||||
if locator.is_visible(timeout=1_000):
|
||||
return locator
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _maybe_auto_login(page: Any, prefix: str) -> None:
|
||||
"""
|
||||
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
|
||||
"""
|
||||
username_env = f"FREIGHT_RPA_{prefix}_USERNAME"
|
||||
password_env = f"FREIGHT_RPA_{prefix}_PASSWORD"
|
||||
if not _env(username_env) or not _env(password_env):
|
||||
return
|
||||
|
||||
user_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_{prefix}_USERNAME_SELECTOR",
|
||||
username_env,
|
||||
(
|
||||
'input[name="username"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="email"]',
|
||||
'input[type="email"]',
|
||||
'input[type="text"]',
|
||||
),
|
||||
)
|
||||
password_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_{prefix}_PASSWORD_SELECTOR",
|
||||
password_env,
|
||||
('input[name="password"]', 'input[type="password"]'),
|
||||
)
|
||||
if not user_filled and not password_filled:
|
||||
return
|
||||
if user_filled != password_filled:
|
||||
raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors")
|
||||
|
||||
if not _click_login_submit(
|
||||
page,
|
||||
f"FREIGHT_RPA_{prefix}_LOGIN_BUTTON_SELECTOR",
|
||||
("Sign in", "Login", "Log in", "登录"),
|
||||
):
|
||||
raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required")
|
||||
|
||||
|
||||
|
||||
# 公开 API
|
||||
env = _env
|
||||
browser_timeout_ms = _browser_timeout_ms
|
||||
click_text = _click_text
|
||||
click_selector_or_text = _click_selector_or_text
|
||||
fill_selector_or_label = _fill_selector_or_label
|
||||
fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed
|
||||
select_or_fill = _select_or_fill
|
||||
visible_locator = _visible_locator
|
||||
visible_locator_in_root = _visible_locator_in_root
|
||||
click_text_in_root = _click_text_in_root
|
||||
click_visible_selector_or_text_in_root = _click_visible_selector_or_text_in_root
|
||||
fill_login_field = _fill_login_field
|
||||
fill_first_visible_text_input = _fill_first_visible_text_input
|
||||
click_login_submit = _click_login_submit
|
||||
click_visible_selector_or_text = _click_visible_selector_or_text
|
||||
wait_for_visible_selector = _wait_for_visible_selector
|
||||
maybe_auto_login = _maybe_auto_login
|
||||
@@ -0,0 +1,216 @@
|
||||
"""
|
||||
scripts/rpa/run_inventory_batch_trigger.py
|
||||
|
||||
用途:用指定 inventory_export_batch_*.json 直接跑一次真实浏览器批量导出(不启动 worker 轮询)。
|
||||
依赖:Playwright、freight_rpa_worker、FREIGHT_RPA_* 凭据与 HXOPS_API_BASE/SHIPPING_NOTICE_TOOL_API_KEY。
|
||||
逻辑:委托 freight_rpa_worker._handle_inventory_batch_trigger 处理 trigger 并回调后端。
|
||||
|
||||
用法(仓库根目录):
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\run_inventory_batch_trigger.py backend\\data\\shipping_notice\\freight_rpa\\inventory_triggers\\inventory_export_batch_RUN2026070912002659A5.json
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_dotenv_dev() -> None:
|
||||
"""从 .env.dev 注入缺失的 SHIPPING_NOTICE / FREIGHT 目录变量(不覆盖已有 env)。"""
|
||||
env_path = _repo_root() / ".env.dev"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
key = key.strip()
|
||||
value = value.strip().strip('"').strip("'")
|
||||
if key and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
def _load_worker():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_runner", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _inventory_sources_config() -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
读取 shipping_inventory_sources.yaml,按 source_code 索引。
|
||||
核心逻辑:供 enrich 补全旧 trigger 缺失的 site_id / navigation 等字段。
|
||||
"""
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml"
|
||||
payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
indexed: dict[str, dict[str, Any]] = {}
|
||||
for item in payload.get("sources") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get("source_code") or "").strip().upper()
|
||||
if code:
|
||||
indexed[code] = item
|
||||
return indexed
|
||||
|
||||
|
||||
def _build_query_from_yaml(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""复用 dsv_export_smoke 口径,从 YAML 构造 worker 兼容 query。"""
|
||||
navigation = dict(raw.get("navigation") or {})
|
||||
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
|
||||
source_type = str(raw.get("source_type") or "dsv360").strip().lower()
|
||||
warehouse_id = str(raw.get("warehouse_id") or "").strip()
|
||||
query: dict[str, Any] = {}
|
||||
if source_type == "dsv360":
|
||||
for key in ("program_group", "program_label", "report_group", "report_name"):
|
||||
if navigation.get(key):
|
||||
query[key] = navigation[key]
|
||||
if warehouse_id:
|
||||
query["warehouse_code"] = warehouse_id
|
||||
for parameter in parameters:
|
||||
name = str(parameter.get("name") or "").strip()
|
||||
mode = str(parameter.get("mode") or "single").strip().lower()
|
||||
values = [str(v).strip() for v in (parameter.get("values") or []) if str(v).strip()]
|
||||
if not values:
|
||||
continue
|
||||
if mode == "multi_text":
|
||||
joined = str(parameter.get("joiner") or ",").join(values)
|
||||
if name.lower() == "owner":
|
||||
query["owner_code"] = joined
|
||||
elif name.lower() == "putawayzone":
|
||||
query["putaway_zone"] = joined
|
||||
elif name.lower() == "warehouse":
|
||||
query["warehouse_code"] = joined
|
||||
continue
|
||||
value = values[0]
|
||||
if name.lower() == "owner":
|
||||
query["owner_code"] = value
|
||||
elif name.lower() == "putawayzone":
|
||||
query["putaway_zone"] = value
|
||||
elif name.lower() == "warehouse":
|
||||
query["warehouse_code"] = value
|
||||
return query
|
||||
|
||||
|
||||
def _build_rpa_source_from_yaml(source_code: str) -> dict[str, Any] | None:
|
||||
"""从 YAML 构造完整 rpa_inventory_source;找不到 source_code 时返回 None。"""
|
||||
raw = _inventory_sources_config().get(source_code.strip().upper())
|
||||
if not raw:
|
||||
return None
|
||||
navigation = dict(raw.get("navigation") or {})
|
||||
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
|
||||
return {
|
||||
"source_code": str(raw.get("source_code") or source_code).upper(),
|
||||
"source_type": str(raw.get("source_type") or "dsv360").strip().lower(),
|
||||
"site_id": str(raw.get("site_id") or "").strip().upper() or None,
|
||||
"warehouse_id": str(raw.get("warehouse_id") or "").strip(),
|
||||
"entry_url": str(raw.get("entry_url") or ""),
|
||||
"navigation": navigation,
|
||||
"parameters": parameters,
|
||||
"query": _build_query_from_yaml(raw),
|
||||
}
|
||||
|
||||
|
||||
def _enrich_trigger_sources(trigger_path: Path) -> None:
|
||||
"""
|
||||
用 YAML 补全 trigger 中 inventory_sources 的缺失字段(如 site_id)。
|
||||
核心逻辑:旧排程 trigger 可能缺 site_id;以 YAML 为准 merge,保留 trigger 已有 query 覆盖。
|
||||
"""
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
sources = body.get("inventory_sources") or []
|
||||
if not isinstance(sources, list):
|
||||
return
|
||||
enriched: list[dict[str, Any]] = []
|
||||
changed = False
|
||||
for source in sources:
|
||||
if not isinstance(source, dict):
|
||||
continue
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
baseline = _build_rpa_source_from_yaml(code) if code else None
|
||||
if baseline:
|
||||
merged = {**baseline, **{k: v for k, v in source.items() if v not in (None, "", {}, [])}}
|
||||
if not merged.get("query") and baseline.get("query"):
|
||||
merged["query"] = baseline["query"]
|
||||
elif baseline.get("query"):
|
||||
merged["query"] = {**baseline["query"], **(source.get("query") or {})}
|
||||
if merged != source:
|
||||
changed = True
|
||||
enriched.append(merged)
|
||||
else:
|
||||
enriched.append(source)
|
||||
if not changed:
|
||||
return
|
||||
body["inventory_sources"] = enriched
|
||||
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f"[batch-run] 已从 YAML 补全 trigger 字段: {', '.join(str(s.get('source_code')) for s in enriched)}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 2:
|
||||
print("用法: python scripts/rpa/run_inventory_batch_trigger.py <trigger.json>")
|
||||
return 1
|
||||
|
||||
trigger_path = Path(sys.argv[1]).expanduser()
|
||||
if not trigger_path.is_file():
|
||||
trigger_path = _repo_root() / sys.argv[1]
|
||||
if not trigger_path.is_file():
|
||||
print(f"[batch-run] trigger 不存在: {sys.argv[1]}")
|
||||
return 1
|
||||
|
||||
_load_dotenv_dev()
|
||||
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
|
||||
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
|
||||
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
|
||||
os.environ.setdefault(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
|
||||
"backend/data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
|
||||
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
|
||||
os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052")
|
||||
|
||||
repo = _repo_root()
|
||||
drop_dir = Path(os.environ.get("FREIGHT_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_drop")
|
||||
if not drop_dir.is_absolute():
|
||||
drop_dir = repo / drop_dir
|
||||
processed_dir = trigger_path.parent / "processed"
|
||||
processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
worker = _load_worker()
|
||||
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
|
||||
print("[batch-run] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
|
||||
return 1
|
||||
if not worker._env("SHIPPING_NOTICE_TOOL_API_KEY"):
|
||||
print("[batch-run] 缺少 SHIPPING_NOTICE_TOOL_API_KEY(或 INTEGRATION_API_KEY)")
|
||||
return 1
|
||||
|
||||
_enrich_trigger_sources(trigger_path)
|
||||
|
||||
print(f"[batch-run] trigger={trigger_path}")
|
||||
print(f"[batch-run] drop_dir={drop_dir}")
|
||||
print(f"[batch-run] mock={worker._env('FREIGHT_RPA_MOCK', 'false')} headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}")
|
||||
crane_ready = bool(worker._env("FREIGHT_RPA_CRANE_USERNAME") and worker._env("FREIGHT_RPA_CRANE_PASSWORD"))
|
||||
if not crane_ready:
|
||||
print("[batch-run] 提示: 未配置 FREIGHT_RPA_CRANE_USERNAME/PASSWORD,Crane 源预计失败")
|
||||
print("[batch-run] 正在打开浏览器执行批量导出(DSV + Crane,预计 5~15 分钟)…")
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
print("[batch-run] 完成,请查看 inventory_drop 目录与 worker 日志。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user