489 lines
20 KiB
Python
489 lines
20 KiB
Python
"""
|
||
scripts/rpa/dsv_session.py
|
||
|
||
用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。
|
||
依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。
|
||
逻辑:dsv_navigation / dsv_debug 探针;dsv_report_export 在 ensure 前检测 session。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
import time
|
||
from typing import Any, Callable
|
||
|
||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||
from rpa_common import env as _env
|
||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||
import dsv_debug
|
||
from dsv_debug import (
|
||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||
debug_dsv_stage as _debug_dsv_stage,
|
||
report_debug_event as _report_debug_event,
|
||
)
|
||
|
||
|
||
_DSV_REPORTS_NAV_SELECTORS: tuple[str, ...] = (
|
||
"#report-mega-legacy",
|
||
"#report-mega-legacy > a.dropdown-toggle.nav-link",
|
||
"#report-mega-legacy a.dropdown-toggle",
|
||
"#report-mega-legacy a.nav-link",
|
||
"nav a:has-text('Reports')",
|
||
"a.nav-link:has-text('Reports')",
|
||
)
|
||
|
||
def _iter_dsv_report_nav_locators(page: Any):
|
||
"""在所有 frame 与顶层 page 中查找 Reports 顶栏相关 locator。"""
|
||
roots = [page, *list(getattr(page, "frames", []))]
|
||
for root in roots:
|
||
for selector in _DSV_REPORTS_NAV_SELECTORS:
|
||
try:
|
||
locator = root.locator(selector).first
|
||
if locator.count() > 0:
|
||
yield root, selector, locator
|
||
except Exception:
|
||
continue
|
||
|
||
def _has_dsv_report_nav_attached(page: Any) -> bool:
|
||
"""Reports 顶栏 DOM 是否已挂载(跨 frame + 文本 fallback)。"""
|
||
return next(_iter_dsv_report_nav_locators(page), None) is not None
|
||
|
||
def _has_dsv_report_nav_usable(page: Any) -> bool:
|
||
"""
|
||
Reports 导航是否已可用于后续点击。
|
||
核心逻辑:用户肉眼看到首页时,顶栏 Reports 可能已 visible 但 #report-mega-legacy 计数仍为 0;
|
||
因此同时接受 attached 与短超时 visible 探测。
|
||
"""
|
||
for _, _, locator in _iter_dsv_report_nav_locators(page):
|
||
try:
|
||
if locator.is_visible(timeout=200):
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return _has_dsv_report_nav_attached(page)
|
||
|
||
def _is_dsv_in_report_navigation_context(page: Any) -> bool:
|
||
"""
|
||
判断当前是否仍处于报表 iframe / SSRS 上下文,而非 portal 首页。
|
||
|
||
核心逻辑:报表 frame URL 与 portal 首页一样会渲染 Home/Favorites 侧栏与 Reports 顶栏;
|
||
仅探测 Reports 导航不足以区分,必须结合顶层 URL 与 report-frame 是否仍挂载。
|
||
"""
|
||
try:
|
||
current_url = str(page.url or "").lower()
|
||
except Exception:
|
||
current_url = ""
|
||
if "/main/portal/frame/reports/" in current_url:
|
||
return True
|
||
if "/s360reports/" in current_url:
|
||
return True
|
||
for frame in getattr(page, "frames", []):
|
||
try:
|
||
frame_url = str(frame.url or "").lower()
|
||
except Exception:
|
||
frame_url = ""
|
||
if "/s360reports/reports/default.aspx" in frame_url:
|
||
return True
|
||
if "/s360reports/ssrs/" in frame_url:
|
||
return True
|
||
try:
|
||
if frame.locator("#ReportViewerMain").count() > 0:
|
||
return True
|
||
except Exception:
|
||
continue
|
||
return False
|
||
|
||
|
||
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
|
||
if _is_dsv_in_report_navigation_context(page):
|
||
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 _dsv_sso_return_timeout_ms() -> int:
|
||
"""读取登录提交后 SSO 回跳的独立上限,避免混入首页菜单等待。"""
|
||
return max(30_000, int(
|
||
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS", "90000") or "90000"
|
||
))
|
||
|
||
|
||
def _dsv_sso_reload_after_ms() -> int:
|
||
"""读取空白授权中转页的一次性刷新阈值,默认等待 12 秒。"""
|
||
return max(5_000, int(
|
||
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS", "12000") or "12000"
|
||
))
|
||
|
||
|
||
def _wait_for_dsv_app_after_login(
|
||
page: Any,
|
||
timeout_ms: int | None = None,
|
||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||
) -> bool:
|
||
"""
|
||
等待 DSV 从登录链路切回 portal 壳层。
|
||
|
||
核心逻辑:`Verifying compliance` 这类认证过渡页并不代表首页导航已经可操作;
|
||
这里单独识别 auth/合规过渡态,避免在该阶段反复用长超时探测 `#report-mega-legacy`,
|
||
从而把“认证收尾慢”和“Reports 菜单慢”混在一起。
|
||
"""
|
||
import dsv_auth
|
||
|
||
requested_wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||
sso_wait_ms = _dsv_sso_return_timeout_ms()
|
||
# SSO 回跳和 Portal 菜单加载各有独立时间预算,不能互相吞掉。
|
||
wait_ms = sso_wait_ms + requested_wait_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
|
||
sso_started_at: float | None = None
|
||
sso_reload_attempted = False
|
||
last_sso_log_at = 0.0
|
||
while time.monotonic() < deadline:
|
||
now = time.monotonic()
|
||
current_url = str(page.url or "").lower()
|
||
auth_transition = False
|
||
try:
|
||
current_title = str(page.title() or "").lower()
|
||
except Exception:
|
||
current_title = ""
|
||
auth_transition = "auth.dbschenker.com" in current_url or "verifying compliance" in current_title
|
||
if now - last_debug_at >= 3:
|
||
elapsed = int((time.monotonic() - started_at) * 1000)
|
||
_debug_dsv_stage(page, f"wait-app-{elapsed // 1000}s", target_text="Reports")
|
||
last_debug_at = now
|
||
if _has_dsv_report_nav_usable(page):
|
||
if on_portal_shell_seen is not None:
|
||
on_portal_shell_seen()
|
||
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
|
||
_report_debug_event(
|
||
"J",
|
||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
|
||
"[DEBUG] dsv reports nav usable after login",
|
||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||
)
|
||
return True
|
||
if auth_transition:
|
||
if sso_started_at is None:
|
||
sso_started_at = now
|
||
print(f"[dsv-sso] authorization return started url={page.url!r}")
|
||
sso_elapsed_ms = int((now - sso_started_at) * 1000)
|
||
if now - last_sso_log_at >= 10.0:
|
||
print(
|
||
"[dsv-sso] waiting authorization return "
|
||
f"elapsedMs={sso_elapsed_ms} reloaded={sso_reload_attempted} url={page.url!r}"
|
||
)
|
||
last_sso_log_at = now
|
||
is_blank_transition = dsv_auth.is_dsv_blank_auth_transition(page)
|
||
if (
|
||
is_blank_transition
|
||
and not sso_reload_attempted
|
||
and sso_elapsed_ms >= _dsv_sso_reload_after_ms()
|
||
):
|
||
sso_reload_attempted = True
|
||
print("[dsv-sso] blank authorization transition persisted; reload once")
|
||
try:
|
||
page.reload(wait_until="commit", timeout=15_000)
|
||
except Exception as exc:
|
||
print(f"[dsv-sso] authorization refresh failed: {exc}", file=sys.stderr)
|
||
continue
|
||
if sso_elapsed_ms >= sso_wait_ms:
|
||
raise RuntimeError(
|
||
"DSV SSO authorization return timed out "
|
||
f"after {sso_elapsed_ms}ms; portal did not return after login"
|
||
)
|
||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||
continue
|
||
time.sleep(0.25)
|
||
continue
|
||
if not auth_transition and _wait_for_visible_selector(
|
||
page,
|
||
"",
|
||
_DSV_REPORTS_NAV_SELECTORS,
|
||
timeout_ms=400,
|
||
) is not None:
|
||
if on_portal_shell_seen is not None:
|
||
on_portal_shell_seen()
|
||
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
|
||
_report_debug_event(
|
||
"J",
|
||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
|
||
"[DEBUG] dsv reports nav visible after login",
|
||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||
)
|
||
return True
|
||
# Portal 壳层已出现后,只轮询 Reports 定位器,不再反复读取整页和 iframe 文本。
|
||
on_portal_home = portal_shell_callback_fired or _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 sso_started_at is not None:
|
||
print(
|
||
"[dsv-sso] authorization return completed "
|
||
f"elapsedMs={int((now - sso_started_at) * 1000)}"
|
||
)
|
||
print("[dsv-portal] portal shell visible; waiting Reports navigation")
|
||
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 "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||
if not _has_dsv_report_nav_usable(page) and dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||
continue
|
||
try:
|
||
page.wait_for_load_state("domcontentloaded", timeout=1_500)
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.5)
|
||
_debug_dsv_stage(page, "wait-app-timeout", target_text="Reports")
|
||
# #region debug-point J:wait-app-timeout
|
||
_report_debug_event(
|
||
"J",
|
||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:timeout",
|
||
"[DEBUG] dsv app shell wait timed out",
|
||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||
)
|
||
# #endregion
|
||
return False
|
||
|
||
def _has_dsv_portal_shell(page: Any) -> bool:
|
||
"""
|
||
判断 DSV portal 内容壳层是否已出现。
|
||
|
||
核心逻辑:dashboard iframe 的欢迎语/Recent Reports 往往先于顶栏 `#report-mega-legacy`
|
||
渲染完成;此函数用于记录 portal_shell_seen 时间点,但不应单独作为 home-ready 判据。
|
||
"""
|
||
if _has_dsv_report_nav_attached(page):
|
||
return True
|
||
portal_markers = ("home favorites", "recent reports", "360 — your contract logistics portal")
|
||
roots = [page, *getattr(page, "frames", [])]
|
||
for root in roots:
|
||
try:
|
||
body = str(root.locator("body").inner_text(timeout=1_000) or "").lower()
|
||
except Exception:
|
||
body = ""
|
||
if any(marker in body for marker in portal_markers):
|
||
return True
|
||
return False
|
||
|
||
def _is_dsv_home_ready(page: Any) -> bool:
|
||
"""
|
||
判断 DSV 是否已经稳定进入首页导航态。
|
||
|
||
核心逻辑:必须离开认证域名与报表 iframe 上下文,且 Reports 导航已可用;
|
||
停留在 `/main/portal/frame/reports/` 时即使顶栏可见,也不应视为 home-ready。
|
||
"""
|
||
if "auth.dbschenker.com" in page.url:
|
||
return False
|
||
if _is_dsv_in_report_navigation_context(page):
|
||
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 首页真正稳定可操作。
|
||
|
||
核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现。
|
||
app wait 超时但 portal 壳层已可见时,追加 grace wait;仍失败则在首页阶段报错。
|
||
"""
|
||
import dsv_auth
|
||
|
||
wait_ms = timeout_ms if timeout_ms is not None else 60_000
|
||
started_at = time.monotonic()
|
||
# #region debug-point K:home-wait-entry
|
||
_report_debug_event(
|
||
"K",
|
||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:entry",
|
||
"[DEBUG] entering dsv home ready wait",
|
||
{"timeoutMs": wait_ms, "url": page.url, **_collect_dsv_reports_probe(page)},
|
||
)
|
||
# #endregion
|
||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||
if _is_dsv_home_ready(page):
|
||
if on_portal_shell_seen is not None:
|
||
on_portal_shell_seen()
|
||
_debug_dsv_stage(page, "home-ready", target_text="Reports")
|
||
# #region debug-point A:home-ready
|
||
_report_debug_event(
|
||
"A",
|
||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready",
|
||
"[DEBUG] dsv home considered ready before wait loop",
|
||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||
)
|
||
# #endregion
|
||
return
|
||
if _wait_for_dsv_app_after_login(page, timeout_ms=wait_ms, on_portal_shell_seen=on_portal_shell_seen):
|
||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||
if _is_dsv_home_ready(page):
|
||
if on_portal_shell_seen is not None:
|
||
on_portal_shell_seen()
|
||
_debug_dsv_stage(page, "home-ready-after-wait", target_text="Reports")
|
||
# #region debug-point A:home-ready-after-wait
|
||
_report_debug_event(
|
||
"A",
|
||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_wait",
|
||
"[DEBUG] dsv home considered ready after app wait",
|
||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||
)
|
||
# #endregion
|
||
return
|
||
if _wait_for_dsv_report_nav_grace(
|
||
page,
|
||
timeout_ms=30_000,
|
||
on_portal_shell_seen=on_portal_shell_seen,
|
||
):
|
||
# #region debug-point A:home-ready-after-grace
|
||
_report_debug_event(
|
||
"A",
|
||
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_grace",
|
||
"[DEBUG] dsv home became ready during portal grace 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_report_nav_grace(
|
||
page: Any,
|
||
*,
|
||
timeout_ms: int = 30_000,
|
||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||
) -> bool:
|
||
"""
|
||
Portal 首屏已出现但 Reports 导航尚未 visible 时的额外等待。
|
||
|
||
核心逻辑:SSO/合规页较慢时,portal 壳层(Home/Favorites)常先于顶栏 Reports 可点击;
|
||
在判定 home-not-ready 前给导航一次 grace 窗口,降低首条 batch 误失败概率。
|
||
|
||
Returns:
|
||
bool: grace 窗口内首页变为 ready 则 True,否则 False。
|
||
"""
|
||
import dsv_auth
|
||
|
||
if not _is_dsv_on_portal_home(page):
|
||
return False
|
||
print(
|
||
"[dsv-home] portal shell visible, grace wait for Reports nav "
|
||
f"timeoutMs={timeout_ms} report_nav_attached={_has_dsv_report_nav_attached(page)} "
|
||
f"url={page.url!r}"
|
||
)
|
||
deadline = time.monotonic() + (timeout_ms / 1000)
|
||
while time.monotonic() < deadline:
|
||
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
|
||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||
if _is_dsv_home_ready(page):
|
||
if on_portal_shell_seen is not None:
|
||
on_portal_shell_seen()
|
||
_debug_dsv_stage(page, "home-ready-after-grace", target_text="Reports")
|
||
return True
|
||
time.sleep(0.5)
|
||
return False
|
||
|
||
|
||
def _goto_dsv_entry_url(page: Any, entry_url: str) -> None:
|
||
"""
|
||
打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。
|
||
|
||
核心逻辑:s360 -> auth 重定向链可能超过单次 goto 默认超时,不应因此中断 batch。
|
||
"""
|
||
try:
|
||
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
|
||
except Exception as exc:
|
||
message = str(exc).lower()
|
||
if "timeout" not in message:
|
||
raise
|
||
try:
|
||
current_url = str(page.url or "").lower()
|
||
except Exception:
|
||
current_url = ""
|
||
if any(token in current_url for token in ("auth.dbschenker.com", "s360.dbschenker.com")):
|
||
print(
|
||
"[dsv] entry goto domcontentloaded timeout, continue auth redirect "
|
||
f"url={page.url!r}"
|
||
)
|
||
return
|
||
raise
|
||
|
||
|
||
# 公开 API
|
||
DSV_REPORTS_NAV_SELECTORS = _DSV_REPORTS_NAV_SELECTORS
|
||
goto_dsv_entry_url = _goto_dsv_entry_url
|
||
has_dsv_portal_shell = _has_dsv_portal_shell
|
||
has_dsv_report_nav_attached = _has_dsv_report_nav_attached
|
||
has_dsv_report_nav_usable = _has_dsv_report_nav_usable
|
||
is_dsv_home_ready = _is_dsv_home_ready
|
||
is_dsv_in_report_navigation_context = _is_dsv_in_report_navigation_context
|
||
is_dsv_on_portal_home = _is_dsv_on_portal_home
|
||
iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators
|
||
wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login
|
||
wait_for_dsv_home_ready = _wait_for_dsv_home_ready
|
||
wait_for_dsv_report_nav_grace = _wait_for_dsv_report_nav_grace
|
||
|
||
# 向后兼容:登录 API 仍可从 dsv_session 引用
|
||
from dsv_auth import ( # noqa: E402
|
||
DSV_USERNAME_SELECTORS,
|
||
click_dsv_continue,
|
||
click_dsv_password_method,
|
||
dismiss_dsv_password_upgrade_prompt,
|
||
fill_dsv_password_page_fields,
|
||
fill_dsv_username,
|
||
find_dsv_password_locator,
|
||
has_dsv_human_check_prompt,
|
||
has_dsv_password_upgrade_prompt,
|
||
is_dsv_username_page,
|
||
looks_like_dsv_login_method_page,
|
||
maybe_auto_login_dsv,
|
||
submit_dsv_password_form,
|
||
wait_for_dsv_human_check_if_present,
|
||
wait_for_dsv_login_method_page,
|
||
)
|