4536 lines
187 KiB
Python
4536 lines
187 KiB
Python
"""
|
||
Freight RPA worker (PoC).
|
||
|
||
Polls trigger JSON files written by hxops and reports results back via Tool API callbacks.
|
||
Set FREIGHT_RPA_MOCK=true to simulate export/upload without a real freight UI.
|
||
|
||
Usage:
|
||
python scripts/rpa/freight_rpa_worker.py
|
||
|
||
Required env (same as backend):
|
||
HXOPS_API_BASE e.g. http://127.0.0.1:5052
|
||
SHIPPING_NOTICE_TOOL_API_KEY
|
||
FREIGHT_INVENTORY_DROP_DIR
|
||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR
|
||
FREIGHT_UPLOAD_QUEUE_DIR
|
||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR
|
||
Optional:
|
||
FREIGHT_RPA_MOCK=false
|
||
FREIGHT_RPA_POLL_SECONDS=3
|
||
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
|
||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||
FREIGHT_RPA_HEADLESS=false
|
||
FREIGHT_RPA_BROWSER_CHANNEL=msedge
|
||
FREIGHT_RPA_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
|
||
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
|
||
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any, Callable
|
||
|
||
try:
|
||
from openpyxl import Workbook
|
||
except ImportError:
|
||
Workbook = None # type: ignore
|
||
|
||
|
||
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 _backend_dir() -> Path:
|
||
"""
|
||
返回仓库内 backend 根目录。
|
||
|
||
核心逻辑:RPA worker 通常从仓库根目录启动,但也可能由计划任务从其他 cwd
|
||
启动;统一从脚本路径反推 backend,避免相对路径写到错误目录。
|
||
|
||
Returns:
|
||
Path: backend 目录的绝对路径。
|
||
"""
|
||
return Path(__file__).resolve().parents[2] / "backend"
|
||
|
||
|
||
def _resolve_backend_relative_path(value: str, *, default: Path | None = None) -> Path:
|
||
"""
|
||
将 RPA 环境变量路径解析为 backend 根目录下的绝对路径。
|
||
|
||
核心逻辑:兼容 `data/...` 与历史 `backend/data/...` 两种写法;绝对路径保持不变。
|
||
|
||
Args:
|
||
value: 环境变量中的路径值。
|
||
default: value 为空时使用的默认路径。
|
||
|
||
Returns:
|
||
Path: 解析后的绝对路径。
|
||
|
||
Raises:
|
||
ValueError: value 与 default 同时为空。
|
||
"""
|
||
raw = str(value or "").strip()
|
||
if not raw:
|
||
if default is None:
|
||
raise ValueError("path is required when no default is provided")
|
||
return default.resolve()
|
||
|
||
path = Path(raw)
|
||
if path.is_absolute():
|
||
return path.resolve()
|
||
|
||
normalized = raw.replace("\\", "/")
|
||
backend_dir = _backend_dir()
|
||
if normalized.startswith("backend/"):
|
||
return (backend_dir / normalized[len("backend/") :]).resolve()
|
||
return (backend_dir / raw).resolve()
|
||
|
||
|
||
def _require_path(name: str) -> Path:
|
||
"""
|
||
读取必填目录环境变量,并确保目录存在。
|
||
|
||
核心逻辑:复用 backend 相对路径解析,保持 worker 与 Flask 配置的目录语义一致。
|
||
|
||
Args:
|
||
name: 必填目录环境变量名。
|
||
|
||
Returns:
|
||
Path: 已创建的绝对目录路径。
|
||
|
||
Raises:
|
||
SystemExit: 环境变量未配置时退出 worker。
|
||
"""
|
||
value = _env(name)
|
||
if not value:
|
||
raise SystemExit(f"Missing env: {name}")
|
||
path = _resolve_backend_relative_path(value)
|
||
path.mkdir(parents=True, exist_ok=True)
|
||
return path
|
||
|
||
|
||
def _browser_profile_root() -> Path:
|
||
"""
|
||
解析 Playwright 运行时 profile 根目录。
|
||
|
||
核心逻辑:默认落到 `backend/data/shipping_notice/freight_rpa/browser_profile`;
|
||
若本机残留旧的 `data/freight_rpa/browser_profile` 配置,强制迁到 shipping_notice
|
||
命名空间,避免库存导出继续污染旧目录。
|
||
|
||
Returns:
|
||
Path: 已解析但未创建的 profile 根目录。
|
||
"""
|
||
default = _backend_dir() / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||
legacy_default = _backend_dir() / "data" / "freight_rpa" / "browser_profile"
|
||
profile = _env("FREIGHT_RPA_BROWSER_PROFILE_DIR")
|
||
normalized = profile.replace("\\", "/").strip("/")
|
||
if normalized in {
|
||
"data/freight_rpa/browser_profile",
|
||
"backend/data/freight_rpa/browser_profile",
|
||
} or (Path(profile).is_absolute() and Path(profile).resolve() == legacy_default.resolve()):
|
||
print(
|
||
"[warn] FREIGHT_RPA_BROWSER_PROFILE_DIR points to legacy data/freight_rpa; "
|
||
f"using {default} instead"
|
||
)
|
||
return default.resolve()
|
||
return _resolve_backend_relative_path(profile, default=default)
|
||
|
||
|
||
def _post_callback(path: str, payload: dict) -> None:
|
||
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
|
||
key = (
|
||
_env("SHIPPING_NOTICE_TOOL_API_KEY")
|
||
or _env("INTEGRATION_API_KEY")
|
||
or _env("HXOPS_TOOLS_API_KEY")
|
||
)
|
||
if not key:
|
||
raise SystemExit("Missing SHIPPING_NOTICE_TOOL_API_KEY, INTEGRATION_API_KEY, or HXOPS_TOOLS_API_KEY")
|
||
try:
|
||
key.encode("latin-1")
|
||
except UnicodeEncodeError as exc:
|
||
raise RuntimeError(
|
||
"SHIPPING_NOTICE_TOOL_API_KEY/INTEGRATION_API_KEY must be an ASCII token, "
|
||
"not a Chinese placeholder or description"
|
||
) from exc
|
||
|
||
url = f"{base}{path}"
|
||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||
req = urllib.request.Request(
|
||
url,
|
||
data=data,
|
||
headers={
|
||
"Content-Type": "application/json",
|
||
"X-Integration-Key": key,
|
||
"X-Shipping-Tool-Key": key,
|
||
},
|
||
method="POST",
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||
body = resp.read().decode("utf-8")
|
||
print(f"[callback] {path} -> {resp.status} {body[:200]}")
|
||
except urllib.error.HTTPError as exc:
|
||
err = exc.read().decode("utf-8", errors="replace")
|
||
raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc
|
||
|
||
|
||
def _move_trigger(trigger_path: Path, target_dir: Path, reason: str) -> None:
|
||
target_dir.mkdir(parents=True, exist_ok=True)
|
||
done = target_dir / trigger_path.name
|
||
trigger_path.replace(done)
|
||
print(f"[trigger] {reason}: {trigger_path.name} -> {target_dir.name}")
|
||
|
||
|
||
def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exception) -> None:
|
||
print(f"[callback-error] {trigger_path.name}: {exc}", file=sys.stderr)
|
||
if trigger_path.exists():
|
||
_move_trigger(trigger_path, failed_dir, "callback failed")
|
||
|
||
|
||
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
|
||
sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY")
|
||
if sample and Path(sample).is_file():
|
||
dest = drop_dir / Path(sample).name
|
||
shutil.copy2(sample, dest)
|
||
return dest
|
||
|
||
if Workbook is None:
|
||
raise RuntimeError("openpyxl required to generate mock inventory")
|
||
|
||
dest = drop_dir / f"inventory_{task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "Inventory"
|
||
ws.append(["料号", "可用数量"])
|
||
ws.append(["A001", 100])
|
||
ws.append(["A002", 50])
|
||
wb.save(dest)
|
||
return dest
|
||
|
||
|
||
def _download_name(task_no: str, source_code: str, suffix: str = ".xlsx") -> str:
|
||
safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN"
|
||
stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
|
||
return f"inventory_{task_no}_{safe_source}_{stamp}{suffix}"
|
||
|
||
|
||
def _require_playwright():
|
||
try:
|
||
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
|
||
from playwright.sync_api import sync_playwright
|
||
except ImportError as exc:
|
||
raise RuntimeError(
|
||
"Playwright is required for real RPA. Install it on the RPA terminal with: "
|
||
"pip install playwright && python -m playwright install chromium"
|
||
) from exc
|
||
return sync_playwright, PlaywrightTimeoutError
|
||
|
||
|
||
def _browser_timeout_ms() -> int:
|
||
return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000"))
|
||
|
||
|
||
# #region debug-point H1:debug-reporter
|
||
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
|
||
|
||
|
||
# #endregion
|
||
|
||
|
||
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 _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:
|
||
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:
|
||
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
|
||
|
||
|
||
def _click_dsv_export_excel(page: Any) -> None:
|
||
"""
|
||
触发 DSV SSRS ReportViewer 的 Excel 导出。
|
||
|
||
核心逻辑:结果页经常已经渲染出数据,但顶层页面并不会立即出现稳定的 `Export/Save`
|
||
文案;因此优先在承载报表结果的 frame 内直接调用 ReportViewer 原生
|
||
`exportReport('EXCELOPENXML')`,失败后只在选中的结果 frame 内退回到菜单点击式导出,
|
||
避免误点到 portal 顶层或报表标题 frame 的同名元素。
|
||
"""
|
||
# #region debug-point H2:export-click-entry
|
||
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_click_dsv_export_excel:entry", "[DEBUG] enter export click path", {"frameCount": len(page.frames)})
|
||
# #endregion
|
||
try:
|
||
_wait_for_dsv_report_result_ready(page, min(_browser_timeout_ms(), 20_000))
|
||
except TypeError:
|
||
_wait_for_dsv_report_result_ready(page)
|
||
# #region debug-point H2:export-click-after-wait
|
||
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_click_dsv_export_excel:after-wait", "[DEBUG] export path passed wait_for_dsv_report_result_ready", {"frameCount": len(page.frames)})
|
||
# #endregion
|
||
|
||
selected_frame = _find_dsv_report_result_frame(page)
|
||
# #region debug-point H4:selected-report-frame
|
||
if selected_frame is not None:
|
||
try:
|
||
_selected_name = str(selected_frame[1].name or "")
|
||
except Exception:
|
||
_selected_name = ""
|
||
try:
|
||
_selected_url = str(selected_frame[1].url or "")
|
||
except Exception:
|
||
_selected_url = ""
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:selected-frame",
|
||
"[DEBUG] selected report frame before export fallback",
|
||
{
|
||
"frameIndex": selected_frame[0],
|
||
"frameName": _selected_name,
|
||
"frameUrl": _selected_url[:300],
|
||
"state": selected_frame[2],
|
||
},
|
||
)
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:control-probe",
|
||
"[DEBUG] sampled export-related controls in selected report frame",
|
||
_probe_dsv_report_export_controls(selected_frame[1]),
|
||
)
|
||
else:
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:selected-frame",
|
||
"[DEBUG] no report frame selected before export fallback",
|
||
{"frameCount": len(page.frames)},
|
||
)
|
||
# #endregion
|
||
frame_order: list[tuple[int, Any]] = (
|
||
[(selected_frame[0], selected_frame[1])]
|
||
if selected_frame is not None
|
||
else list(enumerate(page.frames))
|
||
)
|
||
|
||
for frame_index, frame in frame_order:
|
||
try:
|
||
direct_exported = bool(
|
||
frame.evaluate(
|
||
"""
|
||
() => {
|
||
const visible = (node) => {
|
||
if (!node) return false;
|
||
const style = window.getComputedStyle(node);
|
||
const rect = node.getBoundingClientRect();
|
||
return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
|
||
};
|
||
if (typeof exportReport === 'function') {
|
||
exportReport('EXCELOPENXML');
|
||
return true;
|
||
}
|
||
const win = window;
|
||
if (win && typeof win.exportReport === 'function') {
|
||
win.exportReport('EXCELOPENXML');
|
||
return true;
|
||
}
|
||
const excelLink = Array.from(document.querySelectorAll('a[onclick], button[onclick], input[onclick], [role="button"][onclick]'))
|
||
.find((node) => String(node.getAttribute('onclick') || '').includes("EXCELOPENXML") && visible(node));
|
||
if (excelLink) {
|
||
excelLink.click();
|
||
return true;
|
||
}
|
||
const exportSelect = Array.from(document.querySelectorAll('select'))
|
||
.find((node) => Array.from(node.options || []).some((option) => {
|
||
const text = String(option.text || '').toUpperCase();
|
||
const value = String(option.value || '').toUpperCase();
|
||
return text.includes('EXCEL') || value.includes('EXCELOPENXML');
|
||
}));
|
||
if (exportSelect) {
|
||
const option = Array.from(exportSelect.options || []).find((item) => {
|
||
const text = String(item.text || '').toUpperCase();
|
||
const value = String(item.value || '').toUpperCase();
|
||
return text.includes('EXCEL') || value.includes('EXCELOPENXML');
|
||
});
|
||
if (option) {
|
||
exportSelect.value = option.value;
|
||
exportSelect.dispatchEvent(new Event('change', { bubbles: true }));
|
||
exportSelect.dispatchEvent(new Event('input', { bubbles: true }));
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
"""
|
||
)
|
||
)
|
||
# #region debug-point H3:direct-export-attempt
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H3",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:direct-export-attempt",
|
||
"[DEBUG] direct export attempt finished",
|
||
{"frameIndex": frame_index, "directExported": direct_exported},
|
||
)
|
||
# #endregion
|
||
if direct_exported:
|
||
return
|
||
except Exception:
|
||
# #region debug-point H3:direct-export-exception
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H3",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:direct-export-exception",
|
||
"[DEBUG] direct export attempt raised exception",
|
||
{"frameIndex": frame_index},
|
||
)
|
||
# #endregion
|
||
pass
|
||
|
||
# #region debug-point H4:direct-export-fallback
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:fallback",
|
||
"[DEBUG] direct export not available; fallback to export menu",
|
||
{"frameCount": len(page.frames), "selectedFrameIndex": selected_frame[0] if selected_frame else None},
|
||
)
|
||
# #endregion
|
||
frame_root = selected_frame[1] if selected_frame else page
|
||
export_menu_selector = _env("FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR") or ",".join(
|
||
(
|
||
'a[title="Export drop down menu"]',
|
||
'button[title="Export drop down menu"]',
|
||
'[id$="_ctl04_ctl00_ButtonLink"]',
|
||
'[aria-label="Export drop down menu"]',
|
||
)
|
||
)
|
||
excel_export_selector = _env("FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR") or ",".join(
|
||
(
|
||
'a[title="Excel"]',
|
||
'button[title="Excel"]',
|
||
'a[onclick*="EXCELOPENXML"]',
|
||
'button[onclick*="EXCELOPENXML"]',
|
||
'a[href*="EXCELOPENXML"]',
|
||
)
|
||
)
|
||
legacy_selector = _env("FREIGHT_RPA_DSV_EXPORT_SELECTOR")
|
||
if legacy_selector:
|
||
locator = _visible_locator_in_root(frame_root, legacy_selector)
|
||
if locator is not None:
|
||
locator.click(timeout=_browser_timeout_ms())
|
||
else:
|
||
page.locator(legacy_selector).first.click(timeout=_browser_timeout_ms())
|
||
else:
|
||
export_menu_clicked = _click_visible_selector_or_text_in_root(
|
||
frame_root,
|
||
export_menu_selector,
|
||
("file_download", "Save", "Export"),
|
||
) or (
|
||
selected_frame is None
|
||
and _click_visible_selector_or_text(
|
||
page,
|
||
"FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR",
|
||
("file_download", "Save", "Export"),
|
||
)
|
||
)
|
||
# #region debug-point H4:export-menu-result
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:export-menu-result",
|
||
"[DEBUG] export menu click result",
|
||
{
|
||
"clicked": export_menu_clicked,
|
||
"selectedFrameIndex": selected_frame[0] if selected_frame else None,
|
||
},
|
||
)
|
||
# #endregion
|
||
if not export_menu_clicked:
|
||
snapshot = _debug_dsv_page_snapshot(page, target_text="Export")
|
||
# #region debug-point H4:export-menu-missing
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:export-menu-missing",
|
||
"[DEBUG] export menu not found in selected frame",
|
||
{"selectedFrameIndex": selected_frame[0] if selected_frame else None, "snapshot": snapshot[:2000]},
|
||
)
|
||
# #endregion
|
||
print(f"[dsv-debug] export menu missing {snapshot}")
|
||
raise RuntimeError("DSV report export menu was not found")
|
||
time.sleep(0.5)
|
||
|
||
excel_option_clicked = _click_visible_selector_or_text_in_root(
|
||
frame_root,
|
||
excel_export_selector,
|
||
("Excel", "EXCELOPENXML"),
|
||
) or (
|
||
selected_frame is None
|
||
and _click_visible_selector_or_text(
|
||
page,
|
||
"FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR",
|
||
("Excel", "EXCELOPENXML"),
|
||
)
|
||
)
|
||
if not excel_option_clicked:
|
||
forced_menu_opened = _force_open_dsv_export_menu(frame_root, export_menu_selector)
|
||
# #region debug-point H4:export-menu-force-open
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:export-menu-force-open",
|
||
"[DEBUG] forced export menu open attempt finished",
|
||
{
|
||
"opened": forced_menu_opened,
|
||
"selectedFrameIndex": selected_frame[0] if selected_frame else None,
|
||
},
|
||
)
|
||
# #endregion
|
||
if forced_menu_opened:
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:post-force-control-probe",
|
||
"[DEBUG] sampled controls after forced export menu open",
|
||
_probe_dsv_report_export_controls(frame_root),
|
||
)
|
||
excel_option_clicked = _click_visible_selector_or_text_in_root(
|
||
frame_root,
|
||
excel_export_selector,
|
||
("Excel", "EXCELOPENXML"),
|
||
)
|
||
if excel_option_clicked:
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result",
|
||
"[DEBUG] excel option click result",
|
||
{"clicked": True, "selector": "post-force-open", "selectedFrameIndex": selected_frame[0] if selected_frame else None},
|
||
)
|
||
return
|
||
for excel_selector in (
|
||
'a.ActiveLink[title="Excel"]',
|
||
'a[title="Excel"]',
|
||
'a[onclick*="EXCELOPENXML"]',
|
||
):
|
||
locator = _visible_locator_in_root(frame_root, excel_selector)
|
||
if locator is None and selected_frame is None:
|
||
locator = _visible_locator(page, excel_selector)
|
||
if locator is not None:
|
||
locator.click(timeout=3_000, force=True)
|
||
# #region debug-point H4:excel-option-result
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result",
|
||
"[DEBUG] excel option click result",
|
||
{"clicked": True, "selector": excel_selector, "selectedFrameIndex": selected_frame[0] if selected_frame else None},
|
||
)
|
||
# #endregion
|
||
return
|
||
snapshot = _debug_dsv_page_snapshot(page, target_text="Excel")
|
||
# #region debug-point H4:excel-option-missing
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:excel-option-missing",
|
||
"[DEBUG] excel option not found after export menu",
|
||
{"selectedFrameIndex": selected_frame[0] if selected_frame else None, "snapshot": snapshot[:2000]},
|
||
)
|
||
# #endregion
|
||
print(f"[dsv-debug] excel export option missing {snapshot}")
|
||
raise RuntimeError("DSV Excel export option was not found")
|
||
# #region debug-point H4:excel-option-result
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H4",
|
||
"freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result",
|
||
"[DEBUG] excel option click result",
|
||
{"clicked": True, "selector": "fallback-text-or-selector", "selectedFrameIndex": selected_frame[0] if selected_frame else None},
|
||
)
|
||
# #endregion
|
||
|
||
|
||
def _get_dsv_report_result_state(frame: Any) -> dict[str, bool]:
|
||
"""
|
||
读取 DSV SSRS 结果 frame 的当前状态。
|
||
|
||
核心逻辑:真实页面里“结果表头已出现”与“报表真正渲染完成”并不同步,
|
||
这里统一抽象为 `asyncWait / exportReady / excelReady / bodyReady / directExportReady`
|
||
五个布尔量,供等待逻辑和导出逻辑复用。
|
||
"""
|
||
try:
|
||
state = frame.evaluate(
|
||
"""
|
||
() => {
|
||
const visible = (node) => {
|
||
if (!node) return false;
|
||
const style = window.getComputedStyle(node);
|
||
const rect = node.getBoundingClientRect();
|
||
return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
|
||
};
|
||
const body = String(document.body?.innerText || '');
|
||
const normalizedBody = body.toLowerCase();
|
||
const hasVisible = (selectors) => selectors.some((selector) =>
|
||
Array.from(document.querySelectorAll(selector)).some((node) => visible(node))
|
||
);
|
||
const exportReady = hasVisible([
|
||
'a[title="Export"]',
|
||
'button[title="Export"]',
|
||
'[aria-label="Export"]',
|
||
'a[title="Save"]',
|
||
'button[title="Save"]',
|
||
'a[onclick*="ShowExport"]',
|
||
'button[onclick*="ShowExport"]',
|
||
'a[onclick*="export"]',
|
||
'button[onclick*="export"]',
|
||
]);
|
||
const excelReady = hasVisible([
|
||
'a[title="Excel"]',
|
||
'button[title="Excel"]',
|
||
'a[onclick*="EXCELOPENXML"]',
|
||
'button[onclick*="EXCELOPENXML"]',
|
||
]);
|
||
const bodyMarkers = [
|
||
'on hand inventory by location',
|
||
'supplier id',
|
||
'sku description',
|
||
'page width',
|
||
'whole page',
|
||
'carton id',
|
||
'location (%)',
|
||
'pallet id',
|
||
'warehouse',
|
||
];
|
||
const bodyScore = bodyMarkers.filter((token) => normalizedBody.includes(token)).length;
|
||
const bodyReady = bodyScore > 0;
|
||
const asyncWait = [
|
||
'loading',
|
||
'please wait',
|
||
'generating',
|
||
'processing',
|
||
'retrieving',
|
||
].some((token) => normalizedBody.includes(token));
|
||
const directExportReady = typeof exportReport === 'function' ||
|
||
(window && typeof window.exportReport === 'function');
|
||
return { asyncWait, exportReady, excelReady, bodyReady, bodyScore, directExportReady };
|
||
}
|
||
"""
|
||
)
|
||
except Exception:
|
||
state = {}
|
||
return {
|
||
"asyncWait": bool((state or {}).get("asyncWait")),
|
||
"exportReady": bool((state or {}).get("exportReady")),
|
||
"excelReady": bool((state or {}).get("excelReady")),
|
||
"bodyReady": bool((state or {}).get("bodyReady")),
|
||
"bodyScore": int((state or {}).get("bodyScore") or (3 if (state or {}).get("bodyReady") else 0)),
|
||
"directExportReady": bool((state or {}).get("directExportReady")),
|
||
}
|
||
|
||
|
||
def _probe_dsv_report_export_controls(frame: Any) -> dict[str, Any]:
|
||
"""
|
||
采集 DSV SSRS 结果 frame 内的导出相关控件特征。
|
||
|
||
核心逻辑:真实页面的导出入口未必直接显示为 Export/Save 文案,因此在运行时
|
||
抽样可见 a/button/input/select/option,记录 title/aria-label/value/onclick 等属性,
|
||
用于后续基于真实 DOM 证据收敛选择器。
|
||
"""
|
||
try:
|
||
return frame.evaluate(
|
||
"""
|
||
() => {
|
||
const visible = (node) => {
|
||
if (!node) return false;
|
||
const style = window.getComputedStyle(node);
|
||
const rect = node.getBoundingClientRect();
|
||
return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
|
||
};
|
||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||
const pick = (node) => ({
|
||
tag: String(node.tagName || '').toLowerCase(),
|
||
id: String(node.id || ''),
|
||
name: String(node.getAttribute('name') || ''),
|
||
title: String(node.getAttribute('title') || ''),
|
||
ariaLabel: String(node.getAttribute('aria-label') || ''),
|
||
value: String(node.getAttribute('value') || ''),
|
||
text: textOf(node).slice(0, 120),
|
||
onclick: String(node.getAttribute('onclick') || '').slice(0, 200),
|
||
href: String(node.getAttribute('href') || '').slice(0, 200),
|
||
});
|
||
const controls = Array.from(document.querySelectorAll('a, button, input, select, option, img, span[title], div[title]'))
|
||
.filter((node) => visible(node) || node.tagName === 'OPTION')
|
||
.map((node) => pick(node))
|
||
.filter((item) => item.text || item.title || item.ariaLabel || item.value || item.onclick || item.href || item.id || item.name)
|
||
.slice(0, 80);
|
||
const exportHints = controls.filter((item) => {
|
||
const haystack = [item.text, item.title, item.ariaLabel, item.value, item.onclick, item.href, item.id, item.name]
|
||
.join(' ')
|
||
.toLowerCase();
|
||
return ['export', 'excel', 'openxml', 'save', 'csv', 'download', 'page width', 'whole page', 'find', 'next'].some((token) => haystack.includes(token));
|
||
}).slice(0, 40);
|
||
const windowKeys = Object.keys(window || {})
|
||
.filter((key) => /export|reportviewer|rv|excel/i.test(key))
|
||
.slice(0, 40);
|
||
return {
|
||
exportHints,
|
||
windowKeys,
|
||
bodySnippet: textOf(document.body).slice(0, 600),
|
||
};
|
||
}
|
||
"""
|
||
)
|
||
except Exception as exc:
|
||
return {"probeError": str(exc)[:300]}
|
||
|
||
|
||
def _force_open_dsv_export_menu(root: Any, export_menu_selector: str) -> bool:
|
||
"""
|
||
在 SSRS ReportViewer 中强制展开导出下拉菜单。
|
||
|
||
核心逻辑:真实 DSV 页面里 `Export drop down menu` 按钮即便 locator.click 成功,
|
||
也可能没有真正把下拉层渲染出来;这里补一轮 force click + JS mouse 事件 + 键盘事件,
|
||
尽量把 ReportViewer 的导出菜单显式展开。
|
||
"""
|
||
locator = _visible_locator_in_root(root, export_menu_selector)
|
||
if locator is None:
|
||
return False
|
||
try:
|
||
locator.click(timeout=2_000, force=True)
|
||
time.sleep(0.3)
|
||
return True
|
||
except Exception:
|
||
pass
|
||
try:
|
||
locator.evaluate(
|
||
"""
|
||
(node) => {
|
||
const fire = (type) => node.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
|
||
fire('mouseover');
|
||
fire('mouseenter');
|
||
fire('mousedown');
|
||
fire('mouseup');
|
||
fire('click');
|
||
}
|
||
"""
|
||
)
|
||
time.sleep(0.3)
|
||
return True
|
||
except Exception:
|
||
pass
|
||
for key in ("Enter", " ", "ArrowDown"):
|
||
try:
|
||
locator.press(key, timeout=1_500)
|
||
time.sleep(0.2)
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _find_dsv_report_result_frame(page: Any) -> tuple[int, Any, dict[str, Any]] | None:
|
||
"""
|
||
选择真正承载 SSRS 报表结果表格的 frame。
|
||
|
||
核心逻辑:首页/最近报表等 frame 也可能包含报表名文本,因此不能只看 `bodyReady`;
|
||
这里先按 frame 身份硬匹配 `report-frame` / `.../S360Reports/Reports/Default.aspx`,
|
||
命中后即使正文仍在 loading,也要持续盯住它等待;只有完全识别不到目标 frame 时,
|
||
才退回到 `bodyScore` 启发式排序。
|
||
"""
|
||
hard_matches: list[tuple[int, Any, dict[str, Any], tuple[int, int, int, int, int]]] = []
|
||
heuristic_matches: list[tuple[int, Any, dict[str, Any], tuple[int, int, int, int]]] = []
|
||
for frame_index, frame in enumerate(page.frames):
|
||
state = _get_dsv_report_result_state(frame)
|
||
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 = ""
|
||
|
||
identity_rank = 0
|
||
if frame_name == "report-frame":
|
||
identity_rank = 2
|
||
elif "/s360reports/reports/default.aspx" in frame_url:
|
||
identity_rank = 1
|
||
|
||
if identity_rank > 0:
|
||
hard_matches.append(
|
||
(
|
||
frame_index,
|
||
frame,
|
||
state,
|
||
(
|
||
identity_rank,
|
||
1 if state["bodyReady"] else 0,
|
||
int(state["bodyScore"]),
|
||
1 if state["excelReady"] else 0,
|
||
1 if state["exportReady"] else 0,
|
||
),
|
||
)
|
||
)
|
||
continue
|
||
|
||
if not state["bodyReady"]:
|
||
continue
|
||
heuristic_matches.append(
|
||
(
|
||
frame_index,
|
||
frame,
|
||
state,
|
||
(
|
||
int(state["bodyScore"]),
|
||
1 if state["excelReady"] else 0,
|
||
1 if state["exportReady"] else 0,
|
||
1 if state["directExportReady"] else 0,
|
||
),
|
||
)
|
||
)
|
||
|
||
if hard_matches:
|
||
best_hard = max(hard_matches, key=lambda item: item[3])
|
||
return (best_hard[0], best_hard[1], best_hard[2])
|
||
|
||
if heuristic_matches:
|
||
best_heuristic = max(heuristic_matches, key=lambda item: item[3])
|
||
return (best_heuristic[0], best_heuristic[1], best_heuristic[2])
|
||
|
||
return None
|
||
|
||
|
||
def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None:
|
||
"""
|
||
等待 DSV 报表结果区进入“可导出”状态。
|
||
|
||
核心逻辑:DSV 报表页点击 View Report 后,真实结果和导出工具栏都渲染在 frame 里,
|
||
顶层页面未必能立即看到 `Export` 文案;因此这里改为轮询读取 frame 状态。
|
||
只要“目标结果 frame 的异步加载已结束 + 报表正文已出现”就允许继续尝试导出,因为真实站点上
|
||
导出能力有时直到点击工具栏/调用原生导出函数时才真正显式出现。
|
||
"""
|
||
deadline = time.monotonic() + max(timeout_ms / 1000, 1)
|
||
last_stage_second = -1
|
||
# #region debug-point H2:wait-report-entry
|
||
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:entry", "[DEBUG] start wait_for_dsv_report_result_ready", {"timeoutMs": timeout_ms, "frameCount": len(page.frames)})
|
||
# #endregion
|
||
while time.monotonic() < deadline:
|
||
selected = _find_dsv_report_result_frame(page)
|
||
if selected is not None:
|
||
frame_index, _frame, state = selected
|
||
if state["bodyReady"] and not state["asyncWait"]:
|
||
# #region debug-point H2:wait-report-ready
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H2",
|
||
"freight_rpa_worker.py:_wait_for_dsv_report_result_ready:ready",
|
||
"[DEBUG] report result considered ready",
|
||
{"frameIndex": frame_index, **state},
|
||
)
|
||
# #endregion
|
||
_debug_dsv_stage(page, "wait-report-ready-state", target_text="Export")
|
||
return
|
||
elapsed_second = int(deadline - time.monotonic())
|
||
if elapsed_second != last_stage_second and elapsed_second % 3 == 0:
|
||
# #region debug-point H2:wait-report-poll
|
||
_emit_debug_event(
|
||
"pre-fix",
|
||
"H2",
|
||
"freight_rpa_worker.py:_wait_for_dsv_report_result_ready:poll",
|
||
"[DEBUG] report result still waiting",
|
||
{"secondsRemaining": elapsed_second, "frameCount": len(page.frames)},
|
||
)
|
||
# #endregion
|
||
_debug_dsv_stage(page, "wait-report-polling", target_text="Export")
|
||
last_stage_second = elapsed_second
|
||
time.sleep(1)
|
||
# #region debug-point H2:wait-report-timeout
|
||
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:timeout", "[DEBUG] report result wait timed out", {"timeoutMs": timeout_ms, "frameCount": len(page.frames)})
|
||
# #endregion
|
||
_debug_dsv_stage(page, "wait-report-timeout", target_text="Export")
|
||
raise RuntimeError("DSV report result did not become exportable before timeout")
|
||
|
||
|
||
def _wait_dsv_report_ready(page: Any, *, timeout_ms: int) -> None:
|
||
"""
|
||
向后兼容的包装器。
|
||
|
||
核心逻辑:历史调用点仍使用 `_wait_dsv_report_ready`;
|
||
实际实现统一委托给 `_wait_for_dsv_report_result_ready`,避免测试和主流程再次分叉。
|
||
"""
|
||
_wait_for_dsv_report_result_ready(page, timeout_ms)
|
||
|
||
|
||
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。
|
||
核心逻辑:report-frame 挂载后按钮可能延迟渲染,先短轮询再尝试多种点击方式。
|
||
"""
|
||
selectors = (
|
||
'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"))
|
||
if _wait_for_visible_selector(page, "", selectors, timeout_ms=wait_ms) is None:
|
||
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")
|
||
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
|
||
deadline = time.monotonic() + 4
|
||
while time.monotonic() < 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
|
||
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 _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_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 菜单慢”混在一起。
|
||
"""
|
||
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
|
||
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 _has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||
_dismiss_dsv_password_upgrade_prompt(page)
|
||
continue
|
||
time.sleep(0.25)
|
||
continue
|
||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||
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。
|
||
"""
|
||
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 _has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||
_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 _has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||
_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 _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")
|
||
|
||
|
||
def _has_dsv_password_upgrade_prompt(page: Any, timeout_ms: int = 250) -> bool:
|
||
"""
|
||
快速判断 DSV 是否真的出现“也许以后 / Maybe later”升级提示。
|
||
|
||
核心逻辑:仅检查升级提示的强特征,不把 Verifying compliance 或普通 auth 跳转页
|
||
误判成升级提示,避免触发长时间的无效轮询。
|
||
"""
|
||
current_url = str(getattr(page, "url", "") or "").lower()
|
||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||
return False
|
||
selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR")
|
||
candidates = (selector,) if selector else (
|
||
'button.dbs-sims-button-secondary:has-text("也许以后")',
|
||
'button.dbs-sims-button-secondary:has-text("Maybe later")',
|
||
'button.dbs-sims-button-secondary:has-text("Not now")',
|
||
'button:has-text("也许以后")',
|
||
'a:has-text("也许以后")',
|
||
'text=也许以后',
|
||
'button:has-text("Maybe later")',
|
||
'a:has-text("Maybe later")',
|
||
'text=Maybe later',
|
||
'button:has-text("Not now")',
|
||
'a:has-text("Not now")',
|
||
'text=Not now',
|
||
)
|
||
prompt_markers = (
|
||
"使用密码升级登录",
|
||
"升级登录",
|
||
"password upgrade",
|
||
"upgrade your sign-in",
|
||
)
|
||
roots = [page, *getattr(page, "frames", [])]
|
||
for root in roots:
|
||
try:
|
||
body = root.locator("body").inner_text(timeout=timeout_ms).lower()
|
||
except Exception:
|
||
body = ""
|
||
if any(marker.lower() in body for marker in prompt_markers):
|
||
return True
|
||
for candidate in candidates:
|
||
try:
|
||
if root.locator(candidate).first.is_visible(timeout=timeout_ms):
|
||
return True
|
||
except Exception:
|
||
continue
|
||
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
|
||
|
||
|
||
_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"]',
|
||
)
|
||
|
||
|
||
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 _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
|
||
|
||
|
||
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 _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")
|
||
|
||
|
||
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(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(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(page)
|
||
_wait_for_dsv_home_ready(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(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(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")
|
||
|
||
|
||
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
|
||
selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR")
|
||
if selector:
|
||
candidates = (selector,)
|
||
else:
|
||
candidates = (
|
||
'button.dbs-sims-button-secondary:has-text("也许以后")',
|
||
'button.dbs-sims-button-secondary:has-text("Maybe later")',
|
||
'button.dbs-sims-button-secondary:has-text("Not now")',
|
||
'button:has-text("也许以后")',
|
||
'a:has-text("也许以后")',
|
||
'text=也许以后',
|
||
'button:has-text("Maybe later")',
|
||
'a:has-text("Maybe later")',
|
||
'text=Maybe later',
|
||
'button:has-text("Not now")',
|
||
'a:has-text("Not now")',
|
||
'text=Not now',
|
||
)
|
||
def _prompt_visible() -> bool:
|
||
return _has_dsv_password_upgrade_prompt(page, timeout_ms=250)
|
||
|
||
# [STEP 1] 先做一次轻量探测门;没看到升级提示强特征时,直接跳过,
|
||
# 避免在 Verifying compliance / auth 跳转页里做大范围阻塞轮询。
|
||
quick_detect_deadline = time.monotonic() + 2.5
|
||
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() + 8
|
||
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 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},
|
||
)
|
||
# #endregion
|
||
|
||
|
||
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
|
||
suggested = str(download.suggested_filename or "")
|
||
suffix = Path(suggested).suffix or ".xlsx"
|
||
dest = drop_dir / _download_name(task_no, source_code, suffix=suffix)
|
||
download.save_as(str(dest))
|
||
return dest
|
||
|
||
|
||
def _batch_download_name(run_no: str, source_code: str, warehouse_id: str, suffix: str = ".xlsx") -> str:
|
||
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
|
||
safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN"
|
||
safe_wh = "".join(ch for ch in warehouse_id if ch.isalnum() or ch in {"-", "_"}) or "WH"
|
||
stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
|
||
return f"inventory_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}"
|
||
|
||
|
||
def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dict[str, Any]) -> Path:
|
||
suggested = str(download.suggested_filename or "")
|
||
suffix = Path(suggested).suffix or ".xlsx"
|
||
source_code = str(source.get("source_code") or "UNKNOWN")
|
||
warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "WH")
|
||
dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix)
|
||
download.save_as(str(dest))
|
||
return dest
|
||
|
||
|
||
def _fill_dsv_multi_select(page: Any, selector_env: str, label: str, values: list[str]) -> None:
|
||
"""
|
||
填充 DSV 报表多选控件(multi_select)。
|
||
核心逻辑:优先 select_option 多值;失败则展开控件后逐条点击 option/checkbox。
|
||
"""
|
||
cleaned = [str(item).strip() for item in values if str(item).strip()]
|
||
if not cleaned:
|
||
return
|
||
selector = _env(selector_env)
|
||
if selector:
|
||
locator = page.locator(selector).first
|
||
try:
|
||
locator.select_option(label=cleaned, timeout=_browser_timeout_ms())
|
||
print(f"[dsv-filter] {label} multi_select via select_option labels={cleaned!r}")
|
||
return
|
||
except Exception:
|
||
pass
|
||
try:
|
||
locator.select_option(value=cleaned, timeout=_browser_timeout_ms())
|
||
print(f"[dsv-filter] {label} multi_select via select_option values={cleaned!r}")
|
||
return
|
||
except Exception:
|
||
pass
|
||
try:
|
||
locator.click(timeout=_browser_timeout_ms())
|
||
for value in cleaned:
|
||
option = page.get_by_role("option", name=value).first
|
||
if option.is_visible(timeout=2_000):
|
||
option.click(timeout=_browser_timeout_ms())
|
||
continue
|
||
page.get_by_text(value, exact=False).first.click(timeout=_browser_timeout_ms())
|
||
print(f"[dsv-filter] {label} multi_select via click options={cleaned!r}")
|
||
return
|
||
except Exception as exc:
|
||
print(f"[dsv-filter] {label} multi_select click fallback failed: {exc}", file=sys.stderr)
|
||
for value in cleaned:
|
||
_fill_dsv_filter_if_needed(page, selector_env, label, value)
|
||
|
||
|
||
def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
|
||
"""按 JSON parameters 配置填充 DSV 报表参数(single / multi_text / multi_select)。"""
|
||
if not isinstance(parameter, dict):
|
||
return
|
||
name = str(parameter.get("name") or "").strip()
|
||
mode = str(parameter.get("mode") or "single").strip().lower()
|
||
selector_env = str(parameter.get("selector_env") or "").strip()
|
||
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
|
||
if not name or not values:
|
||
return
|
||
if mode == "multi_text":
|
||
joiner = str(parameter.get("joiner") or ",")
|
||
_fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values))
|
||
return
|
||
if mode == "multi_select":
|
||
_fill_dsv_multi_select(page, selector_env, name, values)
|
||
return
|
||
_fill_dsv_filter_if_needed(page, selector_env, name, values[0])
|
||
|
||
|
||
def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None:
|
||
"""填充 source.parameters;无 parameters 时回退 query 字段。"""
|
||
parameters = source.get("parameters")
|
||
if isinstance(parameters, list) and parameters:
|
||
for item in parameters:
|
||
_fill_report_parameter(page, item)
|
||
return
|
||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"))
|
||
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"))
|
||
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"))
|
||
|
||
|
||
def _dsv_entry_url_host(entry_url: str) -> str:
|
||
"""从 entry_url 提取 host,用于判断当前 page 是否仍在同一 DSV 站点。"""
|
||
from urllib.parse import urlparse
|
||
|
||
parsed = urlparse(str(entry_url or "").strip())
|
||
return (parsed.netloc or "").lower()
|
||
|
||
|
||
def _is_dsv_on_entry_site(page: Any, entry_url: str) -> bool:
|
||
"""当前 tab 是否已在目标 entry_url 对应 portal 域(非 auth 跳转页)。"""
|
||
host = _dsv_entry_url_host(entry_url)
|
||
if not host:
|
||
return False
|
||
try:
|
||
current_url = str(page.url or "").lower()
|
||
except Exception:
|
||
return False
|
||
if "auth.dbschenker.com" in current_url:
|
||
return False
|
||
return host in current_url
|
||
|
||
|
||
def _is_dsv_session_active(page: Any, entry_url: str) -> bool:
|
||
"""
|
||
判定浏览器是否已在同一 entry_url 站点维持有效登录态。
|
||
|
||
核心逻辑:batch 内 source_code 不同但 entry_url 一致时,后续步骤不应重复 OAuth;
|
||
首页、portal 壳层、或 SSRS 参数页均视为 session 仍有效。
|
||
"""
|
||
if not _is_dsv_on_entry_site(page, entry_url):
|
||
return False
|
||
if _is_dsv_home_ready(page) or _has_dsv_portal_shell(page):
|
||
return True
|
||
for frame in page.frames:
|
||
try:
|
||
frame_url = str(frame.url or "").lower()
|
||
except Exception:
|
||
frame_url = ""
|
||
if "/s360reports/reports/default.aspx" in frame_url:
|
||
return True
|
||
try:
|
||
if frame.locator("#ReportViewerMain").count() > 0:
|
||
return True
|
||
except Exception:
|
||
continue
|
||
return False
|
||
|
||
|
||
def _ensure_dsv_session(page: Any, entry_url: str) -> None:
|
||
"""DSV 360 一次登录并等待首页/Reports 导航就绪。"""
|
||
if _is_dsv_session_active(page, entry_url):
|
||
print("[dsv] session already active on entry site, skip login")
|
||
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
|
||
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
|
||
return
|
||
_goto_dsv_entry_url(page, entry_url)
|
||
_maybe_auto_login_dsv(page)
|
||
_wait_for_dsv_home_ready(page, timeout_ms=60_000)
|
||
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
|
||
|
||
|
||
def _reset_dsv_export_entry(page: Any, entry_url: str) -> None:
|
||
"""
|
||
批量导出中 navigation 变化时回到 portal 首页。
|
||
核心逻辑:同 entry_url 且 session 仍有效时不重复登录,仅回首页待命;
|
||
同 navigation 连续导出请改用 _return_to_dsv_report_parameters。
|
||
"""
|
||
print("[dsv] reset export entry before next source")
|
||
if _is_dsv_session_active(page, entry_url):
|
||
print("[dsv] same entry_url session active, skip re-login")
|
||
if not _is_dsv_home_ready(page):
|
||
_goto_dsv_entry_url(page, entry_url)
|
||
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
|
||
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
|
||
return
|
||
_goto_dsv_entry_url(page, entry_url)
|
||
_maybe_auto_login_dsv(page)
|
||
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
|
||
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
|
||
|
||
|
||
def _dsv_navigation_signature(source: dict[str, Any]) -> tuple[str, str, str, str]:
|
||
"""提取 DSV 报表 navigation 四元组,用于判断批量导出是否可复用参数页。"""
|
||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||
return (
|
||
str(query.get("program_group") or navigation.get("program_group") or "").strip(),
|
||
str(query.get("program_label") or navigation.get("program_label") or "").strip(),
|
||
str(query.get("report_group") or navigation.get("report_group") or "").strip(),
|
||
str(query.get("report_name") or navigation.get("report_name") or "").strip(),
|
||
)
|
||
|
||
|
||
def _dsv_sources_share_navigation(previous: dict[str, Any] | None, current: dict[str, Any]) -> bool:
|
||
"""连续 source 的 program/report 导航一致时,可跳过 portal 首页重进。"""
|
||
if not previous:
|
||
return False
|
||
prev_sig = _dsv_navigation_signature(previous)
|
||
curr_sig = _dsv_navigation_signature(current)
|
||
return bool(prev_sig == curr_sig and all(prev_sig))
|
||
|
||
|
||
def _dsv_report_name(source: dict[str, Any]) -> str:
|
||
"""从 source 解析报表名称。"""
|
||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||
return str(query.get("report_name") or navigation.get("report_name") or "On Hand Inventory by Location")
|
||
|
||
|
||
def _find_dsv_report_parameter_frame(page: Any) -> Any | None:
|
||
"""定位承载 SSRS ReportViewer 参数区的 report-frame。"""
|
||
for frame in page.frames:
|
||
try:
|
||
frame_url = str(frame.url or "").lower()
|
||
except Exception:
|
||
frame_url = ""
|
||
if "/s360reports/reports/default.aspx" in frame_url:
|
||
return frame
|
||
try:
|
||
if frame.locator("#ReportViewerMain").count() > 0:
|
||
return frame
|
||
except Exception:
|
||
continue
|
||
return None
|
||
|
||
|
||
def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None:
|
||
"""
|
||
导出完成后回到同一报表的参数页,仅改 Warehouse 后再次 View Report。
|
||
核心逻辑:reload report-frame 的 Default.aspx URL,避免 batch 同 navigation 时回 portal 首页。
|
||
"""
|
||
frame = _find_dsv_report_parameter_frame(page)
|
||
if frame is None:
|
||
raise RuntimeError("DSV report parameter frame not found for reuse")
|
||
try:
|
||
report_url = str(frame.url or "").strip()
|
||
except Exception:
|
||
report_url = ""
|
||
if not report_url:
|
||
raise RuntimeError("DSV report parameter frame has empty url")
|
||
print("[dsv] reuse report parameter form via report-frame reload")
|
||
frame.goto(report_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||
try:
|
||
page.wait_for_load_state("networkidle", timeout=min(_browser_timeout_ms(), 8_000))
|
||
except Exception:
|
||
pass
|
||
_wait_for_dsv_report_form_ready(page, report_name)
|
||
|
||
|
||
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
|
||
"""从 portal 首页导航至目标报表参数页。"""
|
||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||
report_name = _dsv_report_name(source)
|
||
|
||
reports_selector = _env("FREIGHT_RPA_DSV_REPORTS_SELECTOR")
|
||
if reports_selector:
|
||
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||
else:
|
||
_click_dsv_reports_menu(page)
|
||
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
|
||
|
||
program_selector = _env("FREIGHT_RPA_DSV_PROGRAM_SELECTOR")
|
||
program_label = str(query.get("program_label") or navigation.get("program_label") or "")
|
||
if program_selector:
|
||
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
|
||
else:
|
||
_click_dsv_menu_item(page, program_label, next_text=str(query.get("report_group") or navigation.get("report_group") or "Inventory"))
|
||
|
||
report_group_selector = _env("FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR")
|
||
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
|
||
if report_group_selector:
|
||
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
|
||
else:
|
||
_click_dsv_report_group(page, report_group, next_text=report_name)
|
||
|
||
report_name_selector = _env("FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR")
|
||
if report_name_selector:
|
||
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
|
||
else:
|
||
_click_dsv_menu_item(page, report_name)
|
||
|
||
_wait_for_dsv_report_form_ready(page, report_name)
|
||
return report_name
|
||
|
||
|
||
def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any:
|
||
"""参数页已就绪后:填参 → View Report → 等结果 → 导出 Excel。"""
|
||
_fill_report_parameters(page, source)
|
||
_click_dsv_view_report(page)
|
||
try:
|
||
page.wait_for_load_state("networkidle", timeout=min(_browser_timeout_ms(), 10_000))
|
||
except Exception:
|
||
pass
|
||
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
|
||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||
_click_dsv_export_excel(page)
|
||
return download_info.value
|
||
|
||
|
||
def _prepare_dsv_batch_export_step(
|
||
page: Any,
|
||
entry_url: str,
|
||
previous_source: dict[str, Any] | None,
|
||
source: dict[str, Any],
|
||
*,
|
||
index: int,
|
||
) -> bool:
|
||
"""
|
||
批量导出单步前置:首条登录;同 navigation 复用参数页;否则回首页重导航。
|
||
同 entry_url 的 batch 内仅 index=0 可能触发完整登录,后续步骤 session 有效则跳过 OAuth。
|
||
|
||
Returns:
|
||
True 表示参数页已就绪且可 skip 完整菜单导航。
|
||
"""
|
||
if index == 0:
|
||
_ensure_dsv_session(page, entry_url)
|
||
return False
|
||
if _dsv_sources_share_navigation(previous_source, source):
|
||
report_name = _dsv_report_name(source)
|
||
try:
|
||
_return_to_dsv_report_parameters(page, report_name)
|
||
print(
|
||
"[dsv-batch] reuse parameter form "
|
||
f"navigation={_dsv_navigation_signature(source)!r}"
|
||
)
|
||
return True
|
||
except Exception as exc:
|
||
print(f"[dsv-batch] parameter reuse failed, fallback home reset: {exc}", file=sys.stderr)
|
||
_reset_dsv_export_entry(page, entry_url)
|
||
return False
|
||
|
||
|
||
def _export_dsv_inventory_source(
|
||
page: Any,
|
||
trigger: dict[str, Any],
|
||
source: dict[str, Any],
|
||
*,
|
||
skip_navigation: bool = False,
|
||
) -> Any:
|
||
"""在已登录 DSV session 上导出单个 Warehouse 库存。"""
|
||
if not skip_navigation:
|
||
_navigate_dsv_to_report_form(page, source)
|
||
return _run_dsv_inventory_export_from_form(page, source)
|
||
|
||
|
||
def _ensure_crane_session(page: Any, entry_url: str) -> None:
|
||
"""Crane FootPrint 一次登录。"""
|
||
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||
_maybe_auto_login(page, "CRANE")
|
||
|
||
|
||
def _reset_crane_export_entry(page: Any, entry_url: str) -> None:
|
||
"""批量导出中每个 Crane source 前回到报表表单入口。"""
|
||
print("[crane] reset export entry before next source")
|
||
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||
_maybe_auto_login(page, "CRANE")
|
||
|
||
|
||
def _fill_crane_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
|
||
"""按 JSON parameters 填充 Crane 报表参数。"""
|
||
if not isinstance(parameter, dict):
|
||
return
|
||
name = str(parameter.get("name") or "").strip().lower()
|
||
mode = str(parameter.get("mode") or "single").strip().lower()
|
||
selector_env = str(parameter.get("selector_env") or "").strip()
|
||
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
|
||
if not values:
|
||
return
|
||
label_map = {
|
||
"owner": "Select Owner...",
|
||
"project": "Select Project...",
|
||
"warehouse": "Choose Warehouse ..",
|
||
}
|
||
label = label_map.get(name, name)
|
||
if mode == "multi_select":
|
||
for value in values:
|
||
_select_or_fill(page, selector_env, label, value)
|
||
return
|
||
if mode == "multi_text":
|
||
joiner = str(parameter.get("joiner") or ",")
|
||
_select_or_fill(page, selector_env, label, joiner.join(values))
|
||
return
|
||
_select_or_fill(page, selector_env, label, values[0])
|
||
|
||
|
||
def _fill_crane_report_parameters(page: Any, source: dict[str, Any]) -> None:
|
||
"""填充 Crane source.parameters;无 parameters 时回退 query。"""
|
||
parameters = source.get("parameters")
|
||
if isinstance(parameters, list) and parameters:
|
||
for item in parameters:
|
||
_fill_crane_report_parameter(page, item)
|
||
return
|
||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||
_select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
|
||
_select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
|
||
_select_or_fill(page, "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", "Choose Warehouse ..", query.get("warehouse_code"))
|
||
|
||
|
||
def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||
"""在已登录 Crane session 上导出单个 Warehouse 库存。"""
|
||
_fill_crane_report_parameters(page, source)
|
||
_click_selector_or_text(page, "FREIGHT_RPA_CRANE_RUN_SELECTOR", "Run Report")
|
||
export_selector = _env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR")
|
||
export_text = _env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download")
|
||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||
if export_selector:
|
||
page.locator(export_selector).first.click(timeout=_browser_timeout_ms())
|
||
else:
|
||
_click_text(page, export_text, exact=True)
|
||
return download_info.value
|
||
|
||
|
||
def _open_browser(download_dir: Path):
|
||
"""
|
||
打开用于库存 RPA 导出的浏览器上下文。
|
||
|
||
核心逻辑:无论正式执行还是测试执行,都基于 `FREIGHT_RPA_BROWSER_PROFILE_DIR`
|
||
创建一次性的运行时 profile 子目录,再交给 Playwright 的 persistent context。
|
||
这样既能保留 Chrome/Edge 可执行文件与下载目录配置,又能避免复用任何已有登录态。
|
||
|
||
Args:
|
||
download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。
|
||
|
||
Returns:
|
||
tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir`
|
||
为本次执行独占的临时 profile 目录,调用方负责在关闭浏览器后清理。
|
||
"""
|
||
sync_playwright, _timeout = _require_playwright()
|
||
playwright = sync_playwright().start()
|
||
profile_root = _browser_profile_root()
|
||
profile_root.mkdir(parents=True, exist_ok=True)
|
||
runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
|
||
headless = _env("FREIGHT_RPA_HEADLESS", "false").lower() == "true"
|
||
channel = _env("FREIGHT_RPA_BROWSER_CHANNEL")
|
||
executable_path = _env("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH")
|
||
launch_options: dict[str, Any] = {
|
||
"headless": headless,
|
||
"accept_downloads": True,
|
||
"downloads_path": str(download_dir),
|
||
}
|
||
if executable_path:
|
||
launch_options["executable_path"] = executable_path
|
||
elif channel:
|
||
launch_options["channel"] = channel
|
||
context = playwright.chromium.launch_persistent_context(
|
||
str(runtime_profile_dir),
|
||
**launch_options,
|
||
)
|
||
page = context.pages[0] if context.pages else context.new_page()
|
||
page.set_default_timeout(_browser_timeout_ms())
|
||
return playwright, context, page, runtime_profile_dir
|
||
|
||
|
||
def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||
"""
|
||
单票 trigger 的 DSV 360 导出。
|
||
核心逻辑:与批量导出共用 _ensure_dsv_session + _export_dsv_inventory_source,确保 parameters/Warehouse 一致。
|
||
"""
|
||
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)
|
||
|
||
|
||
def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||
"""单票 trigger 的 Crane 导出;与批量共用 session + export 函数。"""
|
||
entry_url = str(source.get("entry_url") or "").strip()
|
||
if not entry_url:
|
||
raise RuntimeError("Crane inventory source missing entry_url")
|
||
_ensure_crane_session(page, entry_url)
|
||
return _export_crane_inventory_source(page, trigger, source)
|
||
|
||
|
||
def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> Path:
|
||
task_no = str(trigger.get("task_no") or "").strip()
|
||
source = trigger.get("rpa_inventory_source")
|
||
if not isinstance(source, dict):
|
||
raise RuntimeError("inventory trigger missing rpa_inventory_source")
|
||
source_type = str(source.get("source_type") or "").strip()
|
||
source_code = str(source.get("source_code") or "").strip() or source_type or "UNKNOWN"
|
||
if not source_type:
|
||
raise RuntimeError("inventory source missing source_type")
|
||
|
||
playwright = context = runtime_profile_dir = None
|
||
keep_open_on_error = _env("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
|
||
failed = False
|
||
try:
|
||
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
|
||
if source_type == "dsv360":
|
||
download = _download_dsv360_inventory(page, trigger, source)
|
||
elif source_type == "crane_footprint":
|
||
download = _download_crane_inventory(page, trigger, source)
|
||
else:
|
||
raise RuntimeError(f"unsupported inventory source_type: {source_type}")
|
||
return _save_download(download, drop_dir, task_no, source_code)
|
||
except Exception:
|
||
failed = True
|
||
raise
|
||
finally:
|
||
if failed and keep_open_on_error:
|
||
print("[browser] keeping browser open after error because FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true")
|
||
while True:
|
||
time.sleep(3600)
|
||
if context is not None:
|
||
context.close()
|
||
if playwright is not None:
|
||
playwright.stop()
|
||
if runtime_profile_dir is not None:
|
||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||
|
||
|
||
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||
run_no = str(body.get("run_no") or trigger_path.stem).strip()
|
||
task_no = str(body.get("task_no") or "").strip()
|
||
sources = body.get("inventory_sources") or []
|
||
failed_dir = trigger_path.parent / "failed"
|
||
if not isinstance(sources, list) or not sources:
|
||
trigger_path.unlink(missing_ok=True)
|
||
return
|
||
|
||
mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true"
|
||
mode = "mock" if mock else "browser"
|
||
results: list[dict[str, Any]] = []
|
||
|
||
if mock:
|
||
for source in sources:
|
||
if not isinstance(source, dict):
|
||
continue
|
||
task_stub = run_no
|
||
out_file = _write_sample_inventory(drop_dir, task_stub)
|
||
results.append({
|
||
"source_code": source.get("source_code"),
|
||
"warehouse_id": source.get("warehouse_id"),
|
||
"success": True,
|
||
"file_path": str(out_file),
|
||
"task_no": task_no or None,
|
||
})
|
||
else:
|
||
grouped: dict[str, list[dict[str, Any]]] = {}
|
||
for source in sources:
|
||
if not isinstance(source, dict):
|
||
continue
|
||
site = str(source.get("source_type") or "").strip() or "dsv360"
|
||
grouped.setdefault(site, []).append(source)
|
||
|
||
for site, site_sources in grouped.items():
|
||
entry_url = str((site_sources[0] or {}).get("entry_url") or "").strip()
|
||
playwright = context = runtime_profile_dir = None
|
||
try:
|
||
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
|
||
if site == "dsv360":
|
||
export_fn = _export_dsv_inventory_source
|
||
elif site == "crane_footprint":
|
||
export_fn = _export_crane_inventory_source
|
||
else:
|
||
for source in site_sources:
|
||
results.append({
|
||
"source_code": source.get("source_code"),
|
||
"warehouse_id": source.get("warehouse_id"),
|
||
"success": False,
|
||
"error_message": f"unsupported source_type: {site}",
|
||
})
|
||
continue
|
||
|
||
for index, source in enumerate(site_sources):
|
||
code = str(source.get("source_code") or "")
|
||
wh = str(source.get("warehouse_id") or "")
|
||
try:
|
||
skip_navigation = False
|
||
if site == "dsv360":
|
||
skip_navigation = _prepare_dsv_batch_export_step(
|
||
page,
|
||
entry_url,
|
||
site_sources[index - 1] if index > 0 else None,
|
||
source,
|
||
index=index,
|
||
)
|
||
elif site == "crane_footprint":
|
||
if index == 0:
|
||
_ensure_crane_session(page, entry_url)
|
||
else:
|
||
_reset_crane_export_entry(page, entry_url)
|
||
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
|
||
out_file = _save_batch_download(download, drop_dir, run_no, source)
|
||
results.append({
|
||
"source_code": code,
|
||
"warehouse_id": wh,
|
||
"success": True,
|
||
"file_path": str(out_file),
|
||
"task_no": task_no or None,
|
||
})
|
||
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||
except Exception as exc:
|
||
results.append({
|
||
"source_code": code,
|
||
"warehouse_id": wh,
|
||
"success": False,
|
||
"error_message": str(exc),
|
||
})
|
||
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
|
||
finally:
|
||
if context is not None:
|
||
context.close()
|
||
if playwright is not None:
|
||
playwright.stop()
|
||
if runtime_profile_dir is not None:
|
||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||
|
||
try:
|
||
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
|
||
"run_no": run_no,
|
||
"success": any(item.get("success") for item in results),
|
||
"rpa_mode": mode,
|
||
"trigger_type": body.get("trigger_type"),
|
||
"schedule_run_id": body.get("schedule_run_id"),
|
||
"results": results,
|
||
})
|
||
_move_trigger(trigger_path, processed_dir, "processed")
|
||
print(f"[inventory-batch] callback done run={run_no} success={sum(1 for r in results if r.get('success'))}/{len(results)}")
|
||
except Exception as callback_exc:
|
||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||
|
||
|
||
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||
action = str(body.get("action") or "inventory_export").strip()
|
||
if action == "inventory_export_batch":
|
||
_handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||
return
|
||
task_no = str(body.get("task_no") or "").strip()
|
||
failed_dir = trigger_path.parent / "failed"
|
||
if not task_no:
|
||
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
|
||
trigger_path.unlink(missing_ok=True)
|
||
return
|
||
|
||
mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true"
|
||
mode = "mock" if mock else "browser"
|
||
try:
|
||
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
|
||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||
"task_no": task_no,
|
||
"success": True,
|
||
"file_path": str(out_file),
|
||
"rpa_mode": mode,
|
||
"source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None),
|
||
})
|
||
_move_trigger(trigger_path, processed_dir, "processed")
|
||
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
|
||
except Exception as exc:
|
||
try:
|
||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||
"task_no": task_no,
|
||
"success": False,
|
||
"rpa_mode": mode,
|
||
"error_message": str(exc),
|
||
})
|
||
if trigger_path.exists():
|
||
trigger_path.unlink(missing_ok=True)
|
||
except Exception as callback_exc:
|
||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||
|
||
|
||
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
|
||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||
task_no = str(body.get("task_no") or "").strip()
|
||
file_path = str(body.get("file_path") or "").strip()
|
||
failed_dir = trigger_path.parent / "failed"
|
||
if not task_no:
|
||
trigger_path.unlink(missing_ok=True)
|
||
return
|
||
|
||
mock = _env("FREIGHT_RPA_MOCK", "false").lower() == "true"
|
||
if not mock:
|
||
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
|
||
return
|
||
|
||
if file_path and not Path(file_path).is_file():
|
||
try:
|
||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||
"task_no": task_no,
|
||
"success": False,
|
||
"error_message": f"queue file missing: {file_path}",
|
||
})
|
||
trigger_path.unlink(missing_ok=True)
|
||
except Exception as callback_exc:
|
||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||
return
|
||
|
||
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
|
||
try:
|
||
_post_callback("/api/shipping-notice/rpa/upload-complete", {
|
||
"task_no": task_no,
|
||
"success": True,
|
||
"freight_ref_no": ref,
|
||
})
|
||
_move_trigger(trigger_path, processed_dir, "processed")
|
||
print(f"[upload] mock upload done for {task_no} ref={ref}")
|
||
except Exception as callback_exc:
|
||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||
|
||
|
||
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||
if not trigger_dir.is_dir():
|
||
return
|
||
for path in sorted(trigger_dir.glob("*.json")):
|
||
if not path.is_file():
|
||
continue
|
||
try:
|
||
handler(path, *extra_args)
|
||
except Exception as exc:
|
||
print(f"[error] {path.name}: {exc}", file=sys.stderr)
|
||
|
||
|
||
def main() -> None:
|
||
drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR")
|
||
inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
|
||
upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR")
|
||
upload_trigger_dir = _require_path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
|
||
poll = max(1, int(_env("FREIGHT_RPA_POLL_SECONDS", "3") or "3"))
|
||
|
||
inv_processed = inv_trigger_dir / "processed"
|
||
upload_processed = upload_trigger_dir / "processed"
|
||
|
||
print("[freight_rpa_worker] started")
|
||
print(f" mock={_env('FREIGHT_RPA_MOCK', 'false')}")
|
||
print(f" inventory_triggers={inv_trigger_dir}")
|
||
print(f" upload_triggers={upload_trigger_dir}")
|
||
print(f" drop={drop_dir}")
|
||
print(f" queue={upload_queue_dir}")
|
||
|
||
while True:
|
||
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
|
||
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
|
||
time.sleep(poll)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|