refactor(rpa): 重构 scripts/rpa 目录结构与命名
按 common/connectors/inventory/receipt 分层并重命名 - common/: rpa_common, rpa_heartbeat, download_artifact_fallback, new_rpa_worker_secret - connectors/dsv|crane/: 登录网站连接器,库存与收料共用 - inventory/: inventory_rpa_worker, run_inventory_batch_trigger, start_inventory_worker, register_inventory_worker_tasks - receipt/: receipt_rpa_worker, receipt_crane/dbs_export, start_receipt_worker 保留裸 import + sys.path 引导;修正懒加载路径; 按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks; 同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。
This commit is contained in:
1 parent
09deada712
commit
f3050164d0
40 files changed
+384
-172
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,448 @@
|
||||
"""
|
||||
scripts/rpa/dsv_auth_login_flow.py
|
||||
|
||||
用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。
|
||||
依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。
|
||||
逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
from dsv_debug import (
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
debug_dsv_stage as _debug_dsv_stage,
|
||||
report_debug_event as _report_debug_event,
|
||||
report_dsv_chain_stage as _report_dsv_chain_stage,
|
||||
)
|
||||
|
||||
import dsv_auth
|
||||
|
||||
# 绑定私有符号,避免 dsv_auth 末尾 re-export 时的循环导入竞态。
|
||||
_DSV_USERNAME_SELECTORS = dsv_auth._DSV_USERNAME_SELECTORS
|
||||
_click_dsv_continue = dsv_auth._click_dsv_continue
|
||||
_click_dsv_password_method = dsv_auth._click_dsv_password_method
|
||||
_debug_dsv_login_method_page = dsv_auth._debug_dsv_login_method_page
|
||||
_dismiss_dsv_password_upgrade_prompt = dsv_auth._dismiss_dsv_password_upgrade_prompt
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect = dsv_auth._dismiss_dsv_password_upgrade_prompt_after_login_redirect
|
||||
_dsv_login_debug_value = dsv_auth._dsv_login_debug_value
|
||||
_dsv_login_ready_timeout_ms = dsv_auth._dsv_login_ready_timeout_ms
|
||||
_fill_dsv_password_page_fields = dsv_auth._fill_dsv_password_page_fields
|
||||
_fill_dsv_username = dsv_auth._fill_dsv_username
|
||||
_find_dsv_password_locator = dsv_auth._find_dsv_password_locator
|
||||
_has_dsv_human_check_prompt = dsv_auth._has_dsv_human_check_prompt
|
||||
_has_dsv_password_upgrade_prompt = dsv_auth._has_dsv_password_upgrade_prompt
|
||||
_is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition
|
||||
_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url
|
||||
_is_dsv_password_upgrade_redirect = dsv_auth._is_dsv_password_upgrade_redirect
|
||||
_is_dsv_username_page = dsv_auth._is_dsv_username_page
|
||||
_submit_dsv_password_form = dsv_auth._submit_dsv_password_form
|
||||
_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready
|
||||
_wait_for_dsv_human_check_if_present = dsv_auth._wait_for_dsv_human_check_if_present
|
||||
_wait_for_dsv_login_method_page = dsv_auth._wait_for_dsv_login_method_page
|
||||
|
||||
|
||||
def _wait_for_dsv_home_ready_after_login(
|
||||
page: Any,
|
||||
*,
|
||||
timeout_ms: int | None = None,
|
||||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""登录完成后等待首页 ready;惰性导入 dsv_session 避免循环依赖。"""
|
||||
import dsv_session
|
||||
|
||||
dsv_session.wait_for_dsv_home_ready(
|
||||
page,
|
||||
timeout_ms=timeout_ms,
|
||||
on_portal_shell_seen=on_portal_shell_seen,
|
||||
)
|
||||
|
||||
|
||||
def _wait_for_dsv_app_after_login(
|
||||
page: Any,
|
||||
timeout_ms: int | None = None,
|
||||
on_portal_shell_seen: Callable[[], None] | None = None,
|
||||
) -> bool:
|
||||
"""登录轮询 portal 壳层;委托 dsv_session。"""
|
||||
import dsv_session
|
||||
|
||||
return dsv_session.wait_for_dsv_app_after_login(
|
||||
page,
|
||||
timeout_ms=timeout_ms,
|
||||
on_portal_shell_seen=on_portal_shell_seen,
|
||||
)
|
||||
|
||||
|
||||
def _has_existing_dsv_portal_session(page: Any) -> bool:
|
||||
"""
|
||||
轻量判断当前页面是否已是有效 DSV Portal 首页。
|
||||
|
||||
核心逻辑:持久化 Browser Profile 恢复时,Portal 首页可能已可见,但旧登录流程仍先
|
||||
等待用户名控件和认证页渲染。仅当已离开 auth 域且首页业务标记出现时短路;Reports
|
||||
菜单是否可点击仍由后续首页就绪校验负责,避免把认证中转页误判为已登录。
|
||||
"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
|
||||
return False
|
||||
try:
|
||||
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
return any(marker in body for marker in ("home favorites", "recent reports", "favorites"))
|
||||
|
||||
|
||||
def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
"""
|
||||
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
|
||||
"""
|
||||
username = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME")
|
||||
password = _env("SHIPPING_NOTICE_RPA_WORKER_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
|
||||
# [STEP 1] Profile 会话恢复优先于任何登录页等待。否则已在 Portal 首页时会白等
|
||||
# username selector 的长超时,随后才迟到地发现 existing session。
|
||||
if _has_existing_dsv_portal_session(page):
|
||||
print("[dsv-login] existing portal session detected before auth probe")
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_portal_session",
|
||||
"[DEBUG] dsv portal session detected before auth flow",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
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,
|
||||
"SHIPPING_NOTICE_RPA_WORKER_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,
|
||||
"SHIPPING_NOTICE_RPA_WORKER_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("SHIPPING_NOTICE_RPA_WORKER_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("SHIPPING_NOTICE_RPA_WORKER_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:
|
||||
# [STEP 1] DSV 在密码阶段前(authorization.ping)也会弹出“使用密码升级登录!”
|
||||
# 引导弹窗(也许以后/立即启用),会遮挡密码表单和登录按钮;先点“也许以后”关闭再探测。
|
||||
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
|
||||
_dismiss_dsv_password_upgrade_prompt(page)
|
||||
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
|
||||
if password_locator is not None:
|
||||
break
|
||||
if _fill_dsv_password_page_fields(page, username, password):
|
||||
print("[dsv-login] password filled")
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
if not _submit_dsv_password_form(page):
|
||||
raise RuntimeError("DSV login password step detected but login button was not found")
|
||||
print("[dsv-login] login clicked")
|
||||
submit_to_home_started_at = time.monotonic()
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
_debug_dsv_stage(page, "after-login-click-inline-password", target_text="Reports")
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
|
||||
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
|
||||
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
|
||||
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
return
|
||||
if _has_dsv_human_check_prompt(page):
|
||||
_wait_for_dsv_human_check_if_present(page, timeout_ms=300_000)
|
||||
if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen):
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
# #region debug-point E:login-completed-direct
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_direct",
|
||||
"[DEBUG] dsv login completed directly after human check/app wait",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000)
|
||||
if method_ready:
|
||||
# #region debug-point E:password-method-page
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_page",
|
||||
"[DEBUG] dsv password method page detected",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2:
|
||||
time.sleep(1)
|
||||
continue
|
||||
password_method_selector = _env("SHIPPING_NOTICE_RPA_WORKER_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,
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR",
|
||||
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
|
||||
timeout_ms=_dsv_login_ready_timeout_ms(),
|
||||
)
|
||||
if password_locator is None:
|
||||
if not _fill_dsv_password_page_fields(page, username, password):
|
||||
raise RuntimeError("DSV login password field was not found")
|
||||
print("[dsv-login] password filled")
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
if not _submit_dsv_password_form(page):
|
||||
raise RuntimeError("DSV login password step detected but login button was not found")
|
||||
print("[dsv-login] login clicked")
|
||||
submit_to_home_started_at = time.monotonic()
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
_debug_dsv_stage(page, "after-login-click-late-password", target_text="Reports")
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
|
||||
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
|
||||
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
|
||||
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
return
|
||||
print(f"[dsv-login] password field missing url={page.url} body={text[:300]!r} method_debug={_debug_dsv_login_method_page(page)}")
|
||||
raise RuntimeError("DSV login password field was not found")
|
||||
|
||||
password_locator.fill(password, timeout=_browser_timeout_ms())
|
||||
print("[dsv-login] password filled")
|
||||
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
|
||||
_report_auto_login_substage("method_to_password", method_to_password_started_at)
|
||||
if not _submit_dsv_password_form(page):
|
||||
raise RuntimeError("DSV login password step detected but login button was not found")
|
||||
print("[dsv-login] login clicked")
|
||||
submit_to_home_started_at = time.monotonic()
|
||||
# #region debug-point N:login-clicked
|
||||
_report_debug_event(
|
||||
"N",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_clicked",
|
||||
"[DEBUG] dsv login button submitted",
|
||||
{"url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
# #region debug-point N:after-domcontentloaded
|
||||
_report_debug_event(
|
||||
"N",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:after_domcontentloaded",
|
||||
"[DEBUG] dsv login flow reached domcontentloaded after submit",
|
||||
{"url": page.url},
|
||||
)
|
||||
# #endregion
|
||||
_debug_dsv_stage(page, "after-login-click-password-locator", target_text="Reports")
|
||||
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
|
||||
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
|
||||
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
|
||||
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
|
||||
print("[dsv-login] login completed")
|
||||
|
||||
|
||||
# 公开 API
|
||||
maybe_auto_login_dsv = _maybe_auto_login_dsv
|
||||
has_existing_dsv_portal_session = _has_existing_dsv_portal_session
|
||||
@@ -0,0 +1,364 @@
|
||||
"""
|
||||
scripts/rpa/dsv_debug.py
|
||||
|
||||
用途:DSV 360 RPA 调试探针与链路阶段日志。
|
||||
依赖:rpa_common。
|
||||
逻辑:供 dsv_session、dsv_navigation、dsv_report_export 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
|
||||
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
_payload = {
|
||||
"sessionId": "dsv-export-stall",
|
||||
"runId": run_id,
|
||||
"hypothesisId": hypothesis_id,
|
||||
"location": location,
|
||||
"msg": msg,
|
||||
"data": data or {},
|
||||
"ts": int(time.time() * 1000),
|
||||
}
|
||||
_url = "http://127.0.0.1:7778/event"
|
||||
_env_file = Path(".dbg/dsv-export-stall.env")
|
||||
try:
|
||||
if _env_file.is_file():
|
||||
_content = _env_file.read_text(encoding="utf-8")
|
||||
_url = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SERVER_URL=")), _url)
|
||||
_payload["sessionId"] = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SESSION_ID=")), _payload["sessionId"])
|
||||
urllib.request.urlopen(
|
||||
urllib.request.Request(
|
||||
_url,
|
||||
data=json.dumps(_payload, ensure_ascii=False).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
),
|
||||
timeout=1.5,
|
||||
).read()
|
||||
except Exception:
|
||||
pass
|
||||
def _debug_dsv_page_snapshot(page: Any, *, target_text: str = "") -> str:
|
||||
"""
|
||||
汇总 DSV 当前页面与各 frame 的可见文本快照,便于定位菜单/报表文案漂移。
|
||||
|
||||
核心逻辑:采集 page.url、顶层 body 文本、关键菜单容器是否存在,以及各 frame 中
|
||||
可见的链接/按钮/菜单项候选文本;当目标文案找不到时,日志里直接输出“页面上实际看到了什么”。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
target_text: 当前正在寻找的菜单/报表文案,可为空。
|
||||
|
||||
Returns:
|
||||
str: 截断后的页面快照字符串,适合直接输出到 worker 日志。
|
||||
"""
|
||||
focus = str(target_text or "").strip()
|
||||
try:
|
||||
page_url = page.url
|
||||
except Exception:
|
||||
page_url = ""
|
||||
snippets = [f"url={page_url!r}"]
|
||||
try:
|
||||
body = page.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
|
||||
except Exception:
|
||||
body = ""
|
||||
if body:
|
||||
snippets.append(f"page_body={body!r}")
|
||||
try:
|
||||
from dsv_session import has_dsv_report_nav_attached as _has_dsv_report_nav_attached
|
||||
|
||||
report_nav_exists = _has_dsv_report_nav_attached(page)
|
||||
except Exception:
|
||||
report_nav_exists = False
|
||||
snippets.append(f"report_nav_exists={report_nav_exists}")
|
||||
|
||||
candidate_script = """
|
||||
(focusText) => {
|
||||
const normalize = (value) => ((value || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
const isVisible = (node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
const style = window.getComputedStyle(node);
|
||||
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
const selectors = [
|
||||
'#report-mega-legacy',
|
||||
'#report-mega-legacy *',
|
||||
'.mega-dropdown-menu *',
|
||||
'.dropdown-menu *',
|
||||
'a',
|
||||
'button',
|
||||
'[role="button"]',
|
||||
'li',
|
||||
'.nav-link',
|
||||
'.dropdown-item',
|
||||
];
|
||||
const focus = normalize(focusText).toLowerCase();
|
||||
const values = Array.from(document.querySelectorAll(selectors.join(',')))
|
||||
.filter((node) => isVisible(node))
|
||||
.map((node) => normalize(node.innerText || node.textContent || node.value))
|
||||
.filter(Boolean);
|
||||
const deduped = Array.from(new Set(values));
|
||||
const matched = focus
|
||||
? deduped.filter((text) => text.toLowerCase().includes(focus)).slice(0, 20)
|
||||
: [];
|
||||
return {
|
||||
matched,
|
||||
candidates: deduped.slice(0, 40),
|
||||
};
|
||||
}
|
||||
"""
|
||||
for idx, frame in enumerate(page.frames):
|
||||
try:
|
||||
frame_url = frame.url
|
||||
except Exception:
|
||||
frame_url = ""
|
||||
try:
|
||||
frame_name = frame.name
|
||||
except Exception:
|
||||
frame_name = ""
|
||||
try:
|
||||
frame_body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:400]
|
||||
except Exception:
|
||||
frame_body = ""
|
||||
try:
|
||||
frame_data = frame.evaluate(candidate_script, focus, timeout=1_500)
|
||||
except Exception:
|
||||
frame_data = {"matched": [], "candidates": []}
|
||||
matched = list((frame_data or {}).get("matched") or [])
|
||||
candidates = list((frame_data or {}).get("candidates") or [])
|
||||
if frame_body or candidates or matched:
|
||||
snippets.append(
|
||||
f"frame[{idx}] name={frame_name!r} url={frame_url!r} body={frame_body!r} matched={matched!r} candidates={candidates!r}"
|
||||
)
|
||||
return " | ".join(snippets)[:5000]
|
||||
|
||||
|
||||
def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None:
|
||||
"""
|
||||
输出 DSV 关键阶段的运行时快照,用于排查“短暂到页后又跳走”或 DOM 未就绪的问题。
|
||||
|
||||
核心逻辑:在登录后等待首页、展开 Reports、选择 Program 等关键节点打印统一格式日志,
|
||||
让失败复现时可以按时间顺序观察 URL、标题、body、frame 候选文本是否发生变化。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
stage: 当前阶段名,例如 `after-login-click`、`wait-app-3s`。
|
||||
target_text: 当前关注的菜单或文案目标。
|
||||
"""
|
||||
try:
|
||||
title = page.title()
|
||||
except Exception:
|
||||
title = ""
|
||||
snapshot = _debug_dsv_page_snapshot(page, target_text=target_text)
|
||||
print(f"[dsv-stage] stage={stage} title={title!r} {snapshot}")
|
||||
|
||||
|
||||
# #region debug-point A:reports-debug-server
|
||||
def _debug_server_config() -> tuple[str, str]:
|
||||
"""读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。"""
|
||||
env_path = _RPA_ROOT.parents[1] / ".dbg" / "reports-menu-stuck.env"
|
||||
url = "http://127.0.0.1:7778/event"
|
||||
session_id = "reports-menu-stuck"
|
||||
try:
|
||||
content = env_path.read_text(encoding="utf-8")
|
||||
for line in content.splitlines():
|
||||
if line.startswith("DEBUG_SERVER_URL="):
|
||||
url = line.split("=", 1)[1].strip() or url
|
||||
elif line.startswith("DEBUG_SESSION_ID="):
|
||||
session_id = line.split("=", 1)[1].strip() or session_id
|
||||
except Exception:
|
||||
pass
|
||||
return url, session_id
|
||||
|
||||
|
||||
def _report_debug_event(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
"""向 Debug Server 上报结构化运行时证据;失败时静默,不影响业务流程。"""
|
||||
try:
|
||||
url, session_id = _debug_server_config()
|
||||
payload = {
|
||||
"sessionId": session_id,
|
||||
"runId": "pre-fix",
|
||||
"hypothesisId": hypothesis_id,
|
||||
"location": location,
|
||||
"msg": msg,
|
||||
"data": data or {},
|
||||
"ts": int(time.time() * 1000),
|
||||
}
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=2):
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _report_dsv_chain_stage(stage: str, status: str, *, started_at: float | None = None, extra: dict[str, Any] | None = None) -> None:
|
||||
"""
|
||||
统一记录 DSV 主链路各阶段耗时。
|
||||
|
||||
核心逻辑:只在主编排链路输出 `start/end/error` 三类探针,不参与任何业务判断,
|
||||
让一次真实运行即可回放从登录到导出的完整阶段耗时分布。
|
||||
"""
|
||||
payload = dict(extra or {})
|
||||
if started_at is not None:
|
||||
payload["elapsedMs"] = int((time.monotonic() - started_at) * 1000)
|
||||
print(
|
||||
"[dsv-chain] "
|
||||
f"stage={stage} "
|
||||
f"status={status} "
|
||||
+ (
|
||||
" ".join(f"{key}={payload[key]!r}" for key in sorted(payload))
|
||||
if payload
|
||||
else ""
|
||||
)
|
||||
)
|
||||
_report_debug_event(
|
||||
"T",
|
||||
f"freight_rpa_worker.py:_download_dsv360_inventory:{stage}:{status}",
|
||||
"[DEBUG] dsv chain stage probe",
|
||||
{"stage": stage, "status": status, **payload},
|
||||
)
|
||||
|
||||
|
||||
def _collect_dsv_reports_probe(page: Any) -> dict[str, Any]:
|
||||
"""采集 Reports 导航的最小 DOM 证据,帮助判断是否点早、点错或被遮挡。"""
|
||||
try:
|
||||
probe = page.evaluate(
|
||||
"""
|
||||
() => {
|
||||
const nav = document.querySelector('#report-mega-legacy');
|
||||
const link = nav?.querySelector('a.dropdown-toggle, a.nav-link, a');
|
||||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||||
const rectOf = (node) => {
|
||||
if (!node || !node.getBoundingClientRect) return null;
|
||||
const r = node.getBoundingClientRect();
|
||||
return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
|
||||
};
|
||||
const centerNode = (() => {
|
||||
const rect = rectOf(link);
|
||||
if (!rect || rect.width <= 0 || rect.height <= 0) return null;
|
||||
return document.elementFromPoint(rect.x + Math.max(Math.floor(rect.width / 2), 1), rect.y + Math.max(Math.floor(rect.height / 2), 1));
|
||||
})();
|
||||
return {
|
||||
navExists: !!nav,
|
||||
navClass: nav?.className || '',
|
||||
navAriaExpanded: nav?.getAttribute('aria-expanded') || '',
|
||||
linkText: textOf(link),
|
||||
linkClass: link?.className || '',
|
||||
linkAriaExpanded: link?.getAttribute('aria-expanded') || '',
|
||||
linkRect: rectOf(link),
|
||||
centerTag: centerNode?.tagName || '',
|
||||
centerText: textOf(centerNode).slice(0, 120),
|
||||
activeTag: document.activeElement?.tagName || '',
|
||||
activeText: textOf(document.activeElement).slice(0, 120),
|
||||
};
|
||||
}
|
||||
""",
|
||||
)
|
||||
except Exception as exc:
|
||||
probe = {"probe_error": str(exc)[:200]}
|
||||
try:
|
||||
probe["url"] = page.url
|
||||
except Exception:
|
||||
probe["url"] = ""
|
||||
try:
|
||||
from dsv_navigation import is_dsv_reports_menu_open as _is_dsv_reports_menu_open
|
||||
|
||||
probe["menuOpen"] = _is_dsv_reports_menu_open(page)
|
||||
except Exception as exc:
|
||||
probe["menuOpen"] = False
|
||||
probe["menuOpenError"] = str(exc)[:120]
|
||||
return probe
|
||||
# #endregion
|
||||
|
||||
|
||||
def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]:
|
||||
"""采集 Reports 级联菜单当前可见层级,帮助判断下拉是否真的推进到了下一层。"""
|
||||
target_text = str(target_text or "").strip()
|
||||
target_literal = json.dumps(target_text)
|
||||
try:
|
||||
probe = page.evaluate(
|
||||
f"""
|
||||
() => {{
|
||||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||||
const nodes = Array.from(document.querySelectorAll(
|
||||
'#report-mega-legacy a, #report-mega-legacy button, #report-mega-legacy [role="menuitem"], #report-mega-legacy [data-program], #report-mega-legacy [data-report], #report-mega-legacy .dropdown-item, #report-mega-legacy .menu-item, #report-mega-legacy div, #report-mega-legacy span, .mega-dropdown-menu a, .mega-dropdown-menu button, .mega-dropdown-menu [role="menuitem"], .mega-dropdown-menu [data-program], .mega-dropdown-menu [data-report], .mega-dropdown-menu .dropdown-item, .mega-dropdown-menu .menu-item, .mega-dropdown-menu div, .mega-dropdown-menu span, .dropdown-menu a, .dropdown-menu button, .dropdown-menu [role="menuitem"], .dropdown-menu [data-program], .dropdown-menu [data-report], .dropdown-menu .dropdown-item, .dropdown-menu .menu-item, .dropdown-menu div, .dropdown-menu span'
|
||||
));
|
||||
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') || '',
|
||||
tagName: node.tagName || '',
|
||||
dataProgram: node.getAttribute('data-program') || '',
|
||||
dataReport: node.getAttribute('data-report') || '',
|
||||
x: Math.round(rect.x),
|
||||
y: Math.round(rect.y),
|
||||
}};
|
||||
}})
|
||||
.filter((item) => item.text)
|
||||
.slice(0, 40);
|
||||
const target = {target_literal};
|
||||
const matched = target
|
||||
? visible.filter((item) => item.text.toLowerCase().includes(target.toLowerCase())).slice(0, 10)
|
||||
: [];
|
||||
return {{
|
||||
visibleItems: visible,
|
||||
matchedItems: matched,
|
||||
bodySnippet: textOf(document.body).slice(0, 600),
|
||||
activeText: textOf(document.activeElement).slice(0, 120),
|
||||
}};
|
||||
}}
|
||||
""",
|
||||
)
|
||||
except Exception as exc:
|
||||
probe = {"probe_error": str(exc)[:200]}
|
||||
try:
|
||||
probe["url"] = page.url
|
||||
except Exception:
|
||||
probe["url"] = ""
|
||||
return probe
|
||||
|
||||
|
||||
# 公开 API
|
||||
emit_debug_event = _emit_debug_event
|
||||
debug_dsv_page_snapshot = _debug_dsv_page_snapshot
|
||||
debug_dsv_stage = _debug_dsv_stage
|
||||
debug_server_config = _debug_server_config
|
||||
report_debug_event = _report_debug_event
|
||||
report_dsv_chain_stage = _report_dsv_chain_stage
|
||||
collect_dsv_reports_probe = _collect_dsv_reports_probe
|
||||
collect_dsv_menu_probe = _collect_dsv_menu_probe
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
scripts/rpa/dsv_driver.py
|
||||
|
||||
用途:DSV 360 库存 RPA 对外编排入口(session → 导航 → 导出)。
|
||||
依赖:dsv_report_export。
|
||||
逻辑:freight_rpa_worker 在 connector_type=dsv360 时仅调用本模块公开函数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
from typing import Any
|
||||
|
||||
from dsv_report_export import (
|
||||
ensure_dsv_session,
|
||||
export_dsv_inventory_source,
|
||||
prepare_dsv_batch_export_step,
|
||||
)
|
||||
|
||||
|
||||
def download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
|
||||
"""
|
||||
单票 trigger 的 DSV 360 导出。
|
||||
核心逻辑:ensure session → 导航至参数页 → 填参并导出 Excel。
|
||||
"""
|
||||
entry_url = str(source.get("entry_url") or "").strip()
|
||||
if not entry_url:
|
||||
raise RuntimeError("DSV360 inventory source missing entry_url")
|
||||
ensure_dsv_session(page, entry_url)
|
||||
return export_dsv_inventory_source(page, trigger, source)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
scripts/rpa/dsv_export_timeout_diagnostics.py
|
||||
|
||||
用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。
|
||||
依赖:json、标准库。
|
||||
逻辑:由 dsv_report_export 在 `page.expect_download(...)` 超时时调用;不参与任何业务判断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
def build_download_timeout_log(
|
||||
*,
|
||||
report_name: str,
|
||||
error_type: str,
|
||||
error_message: str,
|
||||
selected_frame_index: int | None,
|
||||
selected_frame_name: str,
|
||||
selected_frame_url: str,
|
||||
report_state: dict[str, Any] | None,
|
||||
export_controls: dict[str, Any] | None,
|
||||
page_snapshot: str,
|
||||
) -> str:
|
||||
"""
|
||||
生成 DSV 导出等待超时诊断日志。
|
||||
|
||||
核心逻辑:把当前报表、选中结果 frame、导出控件探针和页面快照压成一条 JSON,
|
||||
便于在不接 Debug Server 的情况下,直接从 worker.log 反推出导出按钮是否真实可见。
|
||||
|
||||
Returns:
|
||||
str: 以 `[dsv-download-timeout]` 开头的单行日志。
|
||||
"""
|
||||
payload = {
|
||||
"report_name": str(report_name or ""),
|
||||
"error_type": str(error_type or ""),
|
||||
"error_message": str(error_message or "")[:500],
|
||||
"selected_frame_index": selected_frame_index,
|
||||
"selected_frame_name": str(selected_frame_name or "")[:120],
|
||||
"selected_frame_url": str(selected_frame_url or "")[:300],
|
||||
"report_state": report_state or {},
|
||||
"export_controls": export_controls or {},
|
||||
"page_snapshot": str(page_snapshot or "")[:2500],
|
||||
}
|
||||
return "[dsv-download-timeout] " + json.dumps(payload, ensure_ascii=False, default=str)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
scripts/rpa/dsv_login_smoke.py
|
||||
|
||||
用途:本地手动验证 DSV 360 自动登录(含密码方式第二步、首页 ready)。
|
||||
依赖:Playwright、SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD。
|
||||
逻辑:打开可见浏览器 → _ensure_dsv_session → 保持窗口供人工观察,按 Enter 关闭。
|
||||
|
||||
用法(仓库根目录):
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_login_smoke.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _load_worker():
|
||||
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
|
||||
module_path = repo_root / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_smoke", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def main() -> int:
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
os.environ.setdefault(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"backend/data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
# Playwright 自带 Chromium 未安装时,回退到本机 Edge(Windows 开发机常见情况)。
|
||||
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"):
|
||||
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
|
||||
worker = _load_worker()
|
||||
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME")
|
||||
password = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD")
|
||||
if not username or not password:
|
||||
print("[smoke] 缺少 SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD,请先配置环境变量。")
|
||||
return 1
|
||||
|
||||
drop_dir = Path(tempfile.mkdtemp(prefix="dsv_smoke_drop_"))
|
||||
playwright = context = runtime_profile_dir = None
|
||||
entry_url = "https://s360.dbschenker.com/"
|
||||
|
||||
print(f"[smoke] headless={worker._env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false')}")
|
||||
print(f"[smoke] user={username[:3]}*** entry={entry_url}")
|
||||
print("[smoke] 正在打开浏览器并执行 DSV 自动登录…")
|
||||
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
|
||||
worker._ensure_dsv_session(page, entry_url)
|
||||
print(f"[smoke] SUCCESS — DSV session ready, url={page.url}")
|
||||
print("[smoke] 请在浏览器中确认 Reports 导航可见。按 Enter 关闭浏览器…")
|
||||
try:
|
||||
input()
|
||||
except EOFError:
|
||||
import time
|
||||
|
||||
print("[smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
|
||||
time.sleep(300)
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[smoke] FAILED — {exc}")
|
||||
traceback.print_exc()
|
||||
print("[smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
|
||||
try:
|
||||
input()
|
||||
except EOFError:
|
||||
import time
|
||||
|
||||
time.sleep(120)
|
||||
return 2
|
||||
finally:
|
||||
if context is not None:
|
||||
try:
|
||||
context.close()
|
||||
except Exception:
|
||||
pass
|
||||
if playwright is not None:
|
||||
try:
|
||||
playwright.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
shutil.rmtree(drop_dir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,975 @@
|
||||
"""
|
||||
scripts/rpa/dsv_navigation.py
|
||||
|
||||
用途:DSV 360 Reports 菜单导航至 SSRS 参数页。
|
||||
依赖:rpa_common、dsv_debug、dsv_session。
|
||||
逻辑:由 dsv_report_export 在填参导出前调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
import dsv_debug
|
||||
from dsv_debug import (
|
||||
collect_dsv_menu_probe as _collect_dsv_menu_probe,
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
debug_dsv_page_snapshot as _debug_dsv_page_snapshot,
|
||||
debug_dsv_stage as _debug_dsv_stage,
|
||||
report_debug_event as _report_debug_event,
|
||||
)
|
||||
import dsv_session
|
||||
from dsv_session import (
|
||||
DSV_REPORTS_NAV_SELECTORS as _DSV_REPORTS_NAV_SELECTORS,
|
||||
has_dsv_report_nav_attached as _has_dsv_report_nav_attached,
|
||||
has_dsv_report_nav_usable as _has_dsv_report_nav_usable,
|
||||
is_dsv_on_portal_home as _is_dsv_on_portal_home,
|
||||
has_dsv_portal_shell as _has_dsv_portal_shell,
|
||||
is_dsv_home_ready as _is_dsv_home_ready,
|
||||
dismiss_dsv_password_upgrade_prompt as _dismiss_dsv_password_upgrade_prompt,
|
||||
has_dsv_password_upgrade_prompt as _has_dsv_password_upgrade_prompt,
|
||||
wait_for_dsv_app_after_login as _wait_for_dsv_app_after_login,
|
||||
)
|
||||
|
||||
def _has_dsv_report_form_shell(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV 报表参数页的 shell 是否已经挂载完成。
|
||||
|
||||
核心逻辑:用户在菜单里选中目标报表后,`View Report` 按钮常常已经可以点击,
|
||||
但报表标题文本未必立刻出现在 frame 正文里;此时只要 portal reports 路由和
|
||||
SSRS 相关 frame 已出现,就可以认定表单页已基本就绪,避免额外等待标题文本刷出。
|
||||
"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if "/main/portal/frame/reports/" in current_url:
|
||||
return True
|
||||
for frame in getattr(page, "frames", []):
|
||||
try:
|
||||
frame_name = str(frame.name or "").strip().lower()
|
||||
except Exception:
|
||||
frame_name = ""
|
||||
try:
|
||||
frame_url = str(frame.url or "").strip().lower()
|
||||
except Exception:
|
||||
frame_url = ""
|
||||
if frame_name in {"myiframe", "report-frame"}:
|
||||
return True
|
||||
if "/s360reports/ssrs/" in frame_url or "/s360reports/reports/default.aspx" in frame_url:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_report_submission_started(frame: Any, locator: Any) -> bool:
|
||||
"""
|
||||
判断 View Report 点击后是否已开始提交。
|
||||
|
||||
核心逻辑:优先检测按钮是否变为 disabled/隐藏,其次检测 frame 文本里是否出现常见的加载提示,
|
||||
避免“程序化 submit 已调用,但页面其实没有开始处理”的误判。
|
||||
"""
|
||||
try:
|
||||
if not locator.is_visible(timeout=500):
|
||||
return True
|
||||
except Exception:
|
||||
return True
|
||||
try:
|
||||
state = locator.evaluate(
|
||||
"""
|
||||
(node) => ({
|
||||
disabled: Boolean(node.disabled),
|
||||
ariaDisabled: node.getAttribute('aria-disabled'),
|
||||
value: node.value || node.textContent || '',
|
||||
})
|
||||
"""
|
||||
)
|
||||
value = str((state or {}).get("value") or "").strip().lower()
|
||||
if (state or {}).get("disabled") or str((state or {}).get("ariaDisabled") or "").lower() == "true":
|
||||
return True
|
||||
if value and value != "view report":
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
body = frame.locator("body").inner_text(timeout=800).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
transition_markers = (
|
||||
"loading",
|
||||
"please wait",
|
||||
"generating",
|
||||
"processing",
|
||||
"export",
|
||||
"save",
|
||||
"excel",
|
||||
"no records",
|
||||
"no data",
|
||||
)
|
||||
return any(marker in body for marker in transition_markers)
|
||||
|
||||
|
||||
def _dsv_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool:
|
||||
"""
|
||||
判断当前 DSV 页面或 frame 中是否已经出现目标文案。
|
||||
|
||||
核心逻辑:同时扫描顶层页面与各 frame 的可见文本和常见菜单节点,
|
||||
用于级联菜单点击后的“下一层已展开”确认,避免只点到一级菜单就误判成功。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: 需要确认出现的目标文案。
|
||||
timeout_ms: 单次检查的等待时间,默认 1 秒。
|
||||
|
||||
Returns:
|
||||
bool: 找到目标文案时返回 True,否则返回 False。
|
||||
"""
|
||||
normalized = str(text or "").strip().lower()
|
||||
if not normalized:
|
||||
return False
|
||||
selectors = (
|
||||
f"text={text}",
|
||||
f"a:has-text({json.dumps(text)})",
|
||||
f".dropdown-item:has-text({json.dumps(text)})",
|
||||
f"button:has-text({json.dumps(text)})",
|
||||
)
|
||||
for root in (page, *page.frames):
|
||||
for selector in selectors:
|
||||
try:
|
||||
if root.locator(selector).first.is_visible(timeout=timeout_ms):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
body = root.locator("body").inner_text(timeout=timeout_ms).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
if normalized in body:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool:
|
||||
"""
|
||||
仅判断当前展开的 DSV 下拉菜单中是否出现目标文案。
|
||||
|
||||
核心逻辑:主页 `Recent Reports` 也会出现与报表菜单同名的文本;
|
||||
这里将确认范围收紧为 `Reports` 级联菜单容器内的可见项,避免把首页正文误判成下一级菜单已展开。
|
||||
"""
|
||||
normalized = str(text or "").strip().lower()
|
||||
if not normalized:
|
||||
return False
|
||||
selectors = (
|
||||
f"#report-mega-legacy a.dropdown-item:has-text({json.dumps(text)})",
|
||||
f".mega-dropdown-menu a.dropdown-item:has-text({json.dumps(text)})",
|
||||
f".dropdown-menu a.dropdown-item:has-text({json.dumps(text)})",
|
||||
f"#report-mega-legacy [role='menuitem']:has-text({json.dumps(text)})",
|
||||
f".mega-dropdown-menu [role='menuitem']:has-text({json.dumps(text)})",
|
||||
f".dropdown-menu [role='menuitem']:has-text({json.dumps(text)})",
|
||||
f"#report-mega-legacy a:has-text({json.dumps(text)})",
|
||||
f".mega-dropdown-menu a:has-text({json.dumps(text)})",
|
||||
f".dropdown-menu a:has-text({json.dumps(text)})",
|
||||
)
|
||||
for selector in selectors:
|
||||
try:
|
||||
if page.locator(selector).first.is_visible(timeout=timeout_ms):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
# DSV 的部分 Program(例如 Salt Lake City/AWSSL)由自定义 div/span 渲染,
|
||||
# 不一定带 dropdown-item、a 或 role=menuitem;精确文本定位可命中其嵌套节点。
|
||||
try:
|
||||
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
|
||||
if page.locator(container).get_by_text(text, exact=True).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 _try_dsv_menu_item_fast_path(page: Any, text: str, *, next_text: str = "") -> bool:
|
||||
"""
|
||||
尝试一次 DSV 菜单标准点击,并确认预期下级已展开。
|
||||
|
||||
核心逻辑:真实页面已验证的菜单通常可由精确文本一次 hover/click 打开;
|
||||
仅在明确看到 next_text 后才返回成功,避免把点击事件已发送误当作层级已切换。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: 当前菜单文本。
|
||||
next_text: 点击后应出现的下级文本;为空时只确认点击本身完成。
|
||||
|
||||
Returns:
|
||||
bool: 下一级已确认出现或无需确认时为 True;其余情况为 False。
|
||||
"""
|
||||
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
|
||||
try:
|
||||
locator = page.locator(container).get_by_text(text, exact=True).first
|
||||
locator.wait_for(state="visible", timeout=1_500)
|
||||
locator.hover(timeout=1_000)
|
||||
locator.click(timeout=1_500)
|
||||
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _try_dsv_report_group_fast_path(page: Any, text: str, *, next_text: str = "") -> bool:
|
||||
"""
|
||||
尝试一次 Report Group 标准点击,并确认目标报表已展开。
|
||||
|
||||
核心逻辑:Report Group 使用精确文本,避免旧逻辑对多个宽泛 selector
|
||||
分别等待十秒;失败时由兼容路径继续处理 hover 丢失等旧页面结构。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: Report Group 文本。
|
||||
next_text: 点击后应出现的报表名称。
|
||||
|
||||
Returns:
|
||||
bool: 报表文本确认出现时为 True,否则为 False。
|
||||
"""
|
||||
return _try_dsv_menu_item_fast_path(page, text, next_text=next_text)
|
||||
|
||||
|
||||
def _click_dsv_menu_item_compat(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:
|
||||
locator_candidates = [
|
||||
(page.locator(selector).first, selector)
|
||||
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})",
|
||||
)
|
||||
]
|
||||
# 兼容自定义菜单节点及嵌套 span 文本(AWSSL 使用该类结构)。
|
||||
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
|
||||
try:
|
||||
locator_candidates.append(
|
||||
(page.locator(container).get_by_text(text, exact=True).first, f"{container} >> text={text!r}")
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
for locator, selector in locator_candidates:
|
||||
try:
|
||||
locator.wait_for(state="visible", timeout=2_000)
|
||||
for action in ("hover", "click", "force-click", "evaluate", "enter", "space"):
|
||||
try:
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
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_compat(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_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
|
||||
"""
|
||||
点击 DSV 级联菜单,并在标准路径失败后回退全部兼容动作。
|
||||
|
||||
核心逻辑:先走一次精确文本 hover/click 快速路径;只有下一级没有被确认时,
|
||||
才调用原有多 selector、多输入方式的兼容逻辑,兼顾性能和历史页面兼容性。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: 当前菜单文案。
|
||||
next_text: 预期出现的下一级菜单文案。
|
||||
"""
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
raise RuntimeError("DSV menu item text is empty")
|
||||
if _try_dsv_menu_item_fast_path(page, text, next_text=next_text):
|
||||
print(f"[dsv-navigation] fast-path menu item selected target={text!r}")
|
||||
return
|
||||
_click_dsv_menu_item_compat(page, text, next_text=next_text)
|
||||
|
||||
|
||||
def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None:
|
||||
"""
|
||||
点击 DSV Report Group,并在标准路径失败后回退完整兼容链。
|
||||
|
||||
核心逻辑:快速路径确认报表名称已出现才结束;否则保留历史多动作策略,
|
||||
防止旧页面的 hover 状态不稳定时降低导出成功率。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
text: Report Group 文案。
|
||||
next_text: 预期出现的报表名称。
|
||||
"""
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
raise RuntimeError("DSV report group text is empty")
|
||||
if _try_dsv_report_group_fast_path(page, text, next_text=next_text):
|
||||
print(f"[dsv-navigation] fast-path report group selected target={text!r}")
|
||||
return
|
||||
_click_dsv_report_group_compat(page, text, next_text=next_text)
|
||||
|
||||
|
||||
def _click_dsv_view_report(page: Any) -> None:
|
||||
"""
|
||||
点击 SSRS 参数页 View Report。
|
||||
核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。
|
||||
"""
|
||||
selectors = (
|
||||
"#ReportViewerMain_ctl08_ctl00",
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
)
|
||||
_debug_dsv_stage(page, "view-report-before-click", target_text="View Report")
|
||||
wait_ms = max(15_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000"))
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for frame in page.frames:
|
||||
for selector in selectors:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
|
||||
for attempt in click_attempts:
|
||||
try:
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif attempt == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
elif attempt == "space":
|
||||
locator.press("Space", timeout=1_500)
|
||||
elif attempt == "evaluate-click":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
else:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
if (target.form && typeof target.form.requestSubmit === 'function') {
|
||||
target.form.requestSubmit(target);
|
||||
} else if (target.form) {
|
||||
target.form.submit();
|
||||
} else {
|
||||
target.click();
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
submit_deadline = time.monotonic() + 4
|
||||
while time.monotonic() < submit_deadline:
|
||||
if _dsv_report_submission_started(frame, locator):
|
||||
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
|
||||
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
|
||||
raise RuntimeError("DSV View Report button was not found")
|
||||
|
||||
|
||||
def _is_dsv_reports_menu_open(page: Any) -> bool:
|
||||
"""
|
||||
判断 DSV Reports 下拉是否已真正展开,而不是仅仅点到了导航按钮。
|
||||
|
||||
核心逻辑:优先检查 `#report-mega-legacy` 上的 `show/open/aria-expanded` 状态,
|
||||
再兜底检查常见下拉容器里是否出现可见菜单项,避免“点击成功但菜单没开”的误判。
|
||||
"""
|
||||
for selector in (
|
||||
"#report-mega-legacy.show",
|
||||
"#report-mega-legacy.open",
|
||||
"#report-mega-legacy[aria-expanded='true']",
|
||||
"#report-mega-legacy .mega-dropdown-menu.show",
|
||||
"#report-mega-legacy .dropdown-menu.show",
|
||||
".mega-dropdown-menu.show",
|
||||
".dropdown-menu.show",
|
||||
):
|
||||
try:
|
||||
if page.locator(selector).first.is_visible(timeout=150):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for selector in (
|
||||
"#report-mega-legacy .dropdown-item",
|
||||
".mega-dropdown-menu a.dropdown-item",
|
||||
".dropdown-menu a.dropdown-item",
|
||||
):
|
||||
try:
|
||||
locator = page.locator(selector).first
|
||||
if locator.is_visible(timeout=150):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_dsv_reports_menu(page: Any) -> None:
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point B:reports-click-entry
|
||||
_report_debug_event(
|
||||
"B",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:entry",
|
||||
"[DEBUG] entering reports click flow",
|
||||
{"elapsedMs": 0, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
click_selectors = (
|
||||
"#report-mega-legacy > a.dropdown-toggle.nav-link",
|
||||
"#report-mega-legacy a.dropdown-toggle",
|
||||
"#report-mega-legacy a.nav-link",
|
||||
"nav a:has-text('Reports')",
|
||||
"a.nav-link:has-text('Reports')",
|
||||
)
|
||||
click_roots = [page, *list(getattr(page, "frames", []))]
|
||||
for selector in click_selectors:
|
||||
for root in click_roots:
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=5_000)
|
||||
except Exception:
|
||||
continue
|
||||
# [STEP 1] Reports 打开优先走真实 click,避免先 hover 白等一轮再退回 click。
|
||||
for action_name in ("click", "evaluate", "enter", "space", "hover"):
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=2_000)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if action_name == "hover":
|
||||
locator.hover(timeout=2_000)
|
||||
elif action_name == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif action_name == "evaluate":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
elif action_name == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
else:
|
||||
locator.press("Space", timeout=1_500)
|
||||
except Exception:
|
||||
continue
|
||||
# #region debug-point B:reports-click-attempt
|
||||
_report_debug_event(
|
||||
"B",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:attempt",
|
||||
"[DEBUG] reports click attempt dispatched",
|
||||
{
|
||||
"selector": selector,
|
||||
"action": action_name,
|
||||
**_collect_dsv_reports_probe(page),
|
||||
},
|
||||
)
|
||||
# #endregion
|
||||
post_action_wait_seconds = 0.6 if action_name == "hover" else 1.2
|
||||
action_deadline = time.monotonic() + post_action_wait_seconds
|
||||
while time.monotonic() < action_deadline:
|
||||
if _is_dsv_reports_menu_open(page):
|
||||
print(f"[dsv] reports expanded via {action_name} selector={selector!r}")
|
||||
_debug_dsv_stage(page, f"reports-expanded-{action_name}", target_text="Reports")
|
||||
# #region debug-point D:reports-expanded
|
||||
_report_debug_event(
|
||||
"D",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:expanded",
|
||||
"[DEBUG] reports menu expanded after click attempt",
|
||||
{
|
||||
"selector": selector,
|
||||
"action": action_name,
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
**_collect_dsv_reports_probe(page),
|
||||
},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
time.sleep(0.2)
|
||||
print(f"[dsv-debug] reports menu missing {_debug_dsv_page_snapshot(page, target_text='Reports')}")
|
||||
# #region debug-point C:reports-click-failed
|
||||
_report_debug_event(
|
||||
"C",
|
||||
"freight_rpa_worker.py:_click_dsv_reports_menu:failed",
|
||||
"[DEBUG] reports menu click flow exhausted without expansion",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
raise RuntimeError("DSV Reports menu was not found")
|
||||
def _wait_for_dsv_reports_nav_stable(page: Any, *, timeout_ms: int | None = None) -> None:
|
||||
"""
|
||||
在首页 ready 之后,继续等待 Reports 导航进入可稳定交互态。
|
||||
|
||||
核心逻辑:首页首屏刚渲染完成时,Reports 虽然已经可见,但 hover/click 仍可能被吞掉;
|
||||
这里要求导航链接连续多次保持可见,降低“刚进首页就急着点”的误触发概率。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else 8_000
|
||||
selectors = (
|
||||
"#report-mega-legacy > a.dropdown-toggle.nav-link",
|
||||
"#report-mega-legacy a.dropdown-toggle",
|
||||
"#report-mega-legacy a.nav-link",
|
||||
)
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
stable_hits = 0
|
||||
started_at = time.monotonic()
|
||||
# #region debug-point L:reports-nav-stable-entry
|
||||
_report_debug_event(
|
||||
"L",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:entry",
|
||||
"[DEBUG] waiting for dsv reports nav stable",
|
||||
{"timeoutMs": wait_ms, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
while time.monotonic() < deadline:
|
||||
visible = False
|
||||
click_roots = [page, *list(getattr(page, "frames", []))]
|
||||
for selector in selectors:
|
||||
for root in click_roots:
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.is_visible(timeout=200):
|
||||
visible = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if visible:
|
||||
break
|
||||
if visible:
|
||||
stable_hits += 1
|
||||
if stable_hits >= 3:
|
||||
# #region debug-point L:reports-nav-stable-success
|
||||
_report_debug_event(
|
||||
"L",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:success",
|
||||
"[DEBUG] dsv reports nav considered stable",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
else:
|
||||
stable_hits = 0
|
||||
time.sleep(0.4)
|
||||
# #region debug-point L:reports-nav-stable-timeout
|
||||
_report_debug_event(
|
||||
"L",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:timeout",
|
||||
"[DEBUG] dsv reports nav did not become stable in time",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)},
|
||||
)
|
||||
# #endregion
|
||||
|
||||
|
||||
def _wait_for_dsv_reports_open(page: Any, *, timeout_ms: int | None = None) -> None:
|
||||
"""
|
||||
等待 Reports 下拉真正展开。
|
||||
|
||||
核心逻辑:菜单导航偶发存在 hover/click 已触发但 DOM 尚未展开的情况;
|
||||
这里统一以 `_is_dsv_reports_menu_open()` 为成功判据,避免“看起来点了,实际没开”。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else 15_000
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if _is_dsv_reports_menu_open(page):
|
||||
_debug_dsv_stage(page, "reports-open-confirmed", target_text="Reports")
|
||||
# #region debug-point D:reports-open-confirmed
|
||||
_report_debug_event(
|
||||
"D",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_open:confirmed",
|
||||
"[DEBUG] reports open confirmed",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
return
|
||||
time.sleep(0.3)
|
||||
_debug_dsv_stage(page, "reports-open-timeout", target_text="Reports")
|
||||
# #region debug-point D:reports-open-timeout
|
||||
_report_debug_event(
|
||||
"D",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_reports_open:timeout",
|
||||
"[DEBUG] reports open confirmation timed out",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
raise RuntimeError("DSV Reports menu did not expand")
|
||||
|
||||
|
||||
def _wait_for_dsv_report_form_ready(page: Any, report_name: str, *, timeout_ms: int | None = None) -> None:
|
||||
"""
|
||||
等待报表表单页稳定可操作。
|
||||
|
||||
核心逻辑:选择 Program / Group / Report 后,不立即假设已进入表单页;
|
||||
优先要求 `View Report` 按钮出现,同时满足“报表标题文本已出现”或“报表 shell/frame 已挂载”,
|
||||
这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。
|
||||
"""
|
||||
wait_ms = timeout_ms if timeout_ms is not None else max(
|
||||
60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000")
|
||||
)
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
started_at = time.monotonic()
|
||||
normalized_report = str(report_name or "").strip().lower()
|
||||
last_probe_signature: tuple[bool, bool, bool] | None = None
|
||||
last_probe_logged_at = 0.0
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:entry",
|
||||
"[DEBUG] waiting for dsv report form ready",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
while time.monotonic() < deadline:
|
||||
view_report_visible = False
|
||||
try:
|
||||
if _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
(
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
),
|
||||
timeout_ms=1_000,
|
||||
) is not None:
|
||||
view_report_visible = True
|
||||
except Exception:
|
||||
view_report_visible = False
|
||||
report_title_visible = False
|
||||
if normalized_report:
|
||||
for frame in page.frames:
|
||||
try:
|
||||
body = frame.locator("body").inner_text(timeout=500).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
if normalized_report in body:
|
||||
report_title_visible = True
|
||||
break
|
||||
form_shell_ready = _has_dsv_report_form_shell(page)
|
||||
probe_signature = (view_report_visible, report_title_visible, form_shell_ready)
|
||||
now = time.monotonic()
|
||||
if probe_signature != last_probe_signature or (now - last_probe_logged_at) >= 2.0:
|
||||
print(
|
||||
"[dsv-report-form-probe] "
|
||||
f"elapsedMs={int((now - started_at) * 1000)} "
|
||||
f"viewReportVisible={view_report_visible} "
|
||||
f"reportTitleVisible={report_title_visible} "
|
||||
f"formShellReady={form_shell_ready} "
|
||||
f"stateChanged={probe_signature != last_probe_signature}"
|
||||
)
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:probe",
|
||||
"[DEBUG] dsv report form probe state",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
"elapsedMs": int((now - started_at) * 1000),
|
||||
"viewReportVisible": view_report_visible,
|
||||
"reportTitleVisible": report_title_visible,
|
||||
"formShellReady": form_shell_ready,
|
||||
"stateChanged": probe_signature != last_probe_signature,
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
last_probe_signature = probe_signature
|
||||
last_probe_logged_at = now
|
||||
if form_shell_ready and report_title_visible and not view_report_visible:
|
||||
remaining_ms = max(0, int((deadline - time.monotonic()) * 1000))
|
||||
if remaining_ms > 0:
|
||||
if _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
(
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
),
|
||||
timeout_ms=min(remaining_ms, 45_000),
|
||||
) is not None:
|
||||
view_report_visible = True
|
||||
print(
|
||||
"[dsv-report-form-probe] viewReport appeared after shell+title "
|
||||
f"elapsedMs={int((time.monotonic() - started_at) * 1000)}"
|
||||
)
|
||||
if view_report_visible and (report_title_visible or form_shell_ready or not normalized_report):
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:success",
|
||||
"[DEBUG] dsv report form became ready",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
"viewReportVisible": view_report_visible,
|
||||
"reportTitleVisible": report_title_visible,
|
||||
"formShellReady": form_shell_ready,
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
_debug_dsv_stage(page, "report-form-ready", target_text=report_name or "View Report")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
_report_debug_event(
|
||||
"H",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:timeout",
|
||||
"[DEBUG] dsv report form wait timed out",
|
||||
{
|
||||
"reportName": str(report_name or ""),
|
||||
"elapsedMs": int((time.monotonic() - started_at) * 1000),
|
||||
"viewReportVisible": view_report_visible,
|
||||
"reportTitleVisible": report_title_visible,
|
||||
"formShellReady": _has_dsv_report_form_shell(page),
|
||||
**_collect_dsv_menu_probe(page, report_name or "View Report"),
|
||||
},
|
||||
)
|
||||
_debug_dsv_stage(page, "report-form-timeout", target_text=report_name or "View Report")
|
||||
raise RuntimeError("DSV report form was not ready")
|
||||
|
||||
|
||||
|
||||
# 公开 API
|
||||
has_dsv_report_form_shell = _has_dsv_report_form_shell
|
||||
dsv_report_submission_started = _dsv_report_submission_started
|
||||
dsv_text_visible = _dsv_text_visible
|
||||
dsv_dropdown_text_visible = _dsv_dropdown_text_visible
|
||||
click_dsv_menu_item = _click_dsv_menu_item
|
||||
click_dsv_report_group = _click_dsv_report_group
|
||||
click_dsv_view_report = _click_dsv_view_report
|
||||
is_dsv_reports_menu_open = _is_dsv_reports_menu_open
|
||||
click_dsv_reports_menu = _click_dsv_reports_menu
|
||||
wait_for_dsv_reports_nav_stable = _wait_for_dsv_reports_nav_stable
|
||||
wait_for_dsv_reports_open = _wait_for_dsv_reports_open
|
||||
wait_for_dsv_report_form_ready = _wait_for_dsv_report_form_ready
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,588 @@
|
||||
"""
|
||||
scripts/rpa/dsv_report_parameters.py
|
||||
|
||||
用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。
|
||||
依赖:Playwright Page/Frame;由 freight_rpa_worker._fill_dsv_filter_if_needed 委托调用。
|
||||
逻辑:识别 multi-value checkbox 与 ValidValue select,在 report iframe 内操作并等待控件启用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
# BYAWSATL01 等 3lv 报表在 SSRS 中的默认控件 ID(与页面源码一致)。
|
||||
_DSV_REPORT_PARAM_DEFAULTS: dict[str, dict[str, str]] = {
|
||||
"Owner": {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl03_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl03_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl03_divDropDown",
|
||||
},
|
||||
"PutawayZone": {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl07_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl07_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl07_divDropDown",
|
||||
},
|
||||
"Warehouse": {
|
||||
"control": "select",
|
||||
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _normalize_report_name(report_name: str) -> str:
|
||||
"""报表名归一化:去首尾空白并折叠连续空白、统一小写,用于模板精确匹配。"""
|
||||
return " ".join(str(report_name or "").strip().lower().split())
|
||||
|
||||
|
||||
# 报表名 → 参数控件模板。同名的 SSRS 参数在不同报表里的控件长相不同:
|
||||
# - 3lv 版(On Hand Inventory By Location 3lv,Bison/AWSBI):Warehouse 是原生 select(ddValue);
|
||||
# - JDA 版(On Hand Inventory by Location,Moerdijk 等):Warehouse 是 txtValue + toggle + divDropDown
|
||||
# 组成的多选框下拉(multi_value),历史 YAML 为该源配置的 selectors 即源于此。
|
||||
# 模板按"归一化报表名"精确匹配;未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
|
||||
_DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
|
||||
"on hand inventory by location 3lv": {
|
||||
"Warehouse": {
|
||||
"control": "select",
|
||||
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
|
||||
},
|
||||
},
|
||||
"on hand inventory by location": {
|
||||
"Warehouse": {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def resolve_parameter_controls(report_name: str | None, label: str) -> dict[str, str]:
|
||||
"""
|
||||
按(报表名, 参数名)解析 SSRS 控件配置;报表模板优先,未命中返回空 dict。
|
||||
|
||||
Args:
|
||||
report_name: 当前报表名(如 navigation.report_name),允许为空。
|
||||
label: 参数名(Owner / PutawayZone / Warehouse)。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: 控件配置(control/selector 或 control/text/toggle/dropdown);
|
||||
报表未登记时为空 dict,由调用方回退参数名默认值。
|
||||
"""
|
||||
key = _normalize_report_name(report_name)
|
||||
template = _DSV_REPORT_PARAM_TEMPLATES.get(key) or {}
|
||||
return dict(template.get(str(label or "").strip()) or {})
|
||||
|
||||
|
||||
def _iter_dsv_report_roots(page: Any) -> list[Any]:
|
||||
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
|
||||
matched: list[Any] = []
|
||||
for frame in getattr(page, "frames", []):
|
||||
try:
|
||||
if frame.locator("#ReportViewerMain").count() > 0:
|
||||
matched.append(frame)
|
||||
except Exception:
|
||||
continue
|
||||
if matched:
|
||||
return matched
|
||||
return [page, *list(getattr(page, "frames", []))]
|
||||
|
||||
|
||||
def _find_locator(page: Any, selector: str) -> tuple[Any | None, Any | None]:
|
||||
"""在 report roots 中查找 selector 对应的 locator。"""
|
||||
for root in _iter_dsv_report_roots(page):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
return root, locator
|
||||
except Exception:
|
||||
continue
|
||||
return None, None
|
||||
|
||||
|
||||
def _warehouse_select_state(locator: Any, value: str) -> dict[str, Any]:
|
||||
"""探测 Warehouse select 是否已有目标 option、是否已解除 disabled。"""
|
||||
try:
|
||||
result = locator.evaluate(
|
||||
"""
|
||||
(select, target) => {
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim().toLowerCase();
|
||||
const wanted = normalize(target);
|
||||
const options = Array.from(select.options || []);
|
||||
const hasTarget = options.some((item) => normalize(item.textContent) === wanted);
|
||||
const realOptions = options.filter((item) => {
|
||||
const label = normalize(item.textContent);
|
||||
return label && label !== '<select a value>' && !label.includes('select a value');
|
||||
}).length;
|
||||
return {
|
||||
hasTarget,
|
||||
enabled: !select.disabled && !select.classList.contains('aspNetDisabled'),
|
||||
optionCount: options.length,
|
||||
realOptionCount: realOptions,
|
||||
};
|
||||
}
|
||||
""",
|
||||
value,
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
return result
|
||||
except Exception:
|
||||
pass
|
||||
return {"hasTarget": False, "enabled": False, "optionCount": 0, "realOptionCount": 0}
|
||||
|
||||
|
||||
def _apply_select_value_via_script(locator: Any, value: str) -> bool:
|
||||
"""通过脚本写入 select 值;SSRS 常在 option 已加载但仍保持 aspNetDisabled。"""
|
||||
try:
|
||||
return bool(
|
||||
locator.evaluate(
|
||||
"""
|
||||
(select, target) => {
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
|
||||
const wanted = normalize(target).toLowerCase();
|
||||
const option = Array.from(select.options).find(
|
||||
(item) => normalize(item.textContent).toLowerCase() === wanted
|
||||
);
|
||||
if (!option) return false;
|
||||
select.disabled = false;
|
||||
select.classList.remove('aspNetDisabled');
|
||||
select.removeAttribute('disabled');
|
||||
select.value = option.value;
|
||||
select.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
select.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return true;
|
||||
}
|
||||
""",
|
||||
value,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_warehouse_select_ready(locator: Any, value: str, *, timeout_ms: int) -> tuple[bool, int, dict[str, Any]]:
|
||||
"""
|
||||
等待 Warehouse 下拉出现目标 option。
|
||||
|
||||
核心逻辑:SSRS 报表参数页会先渲染 Owner/PutawayZone 默认值,Warehouse 的 option 列表
|
||||
由 ReportViewer 异步拉取;此期间 select 长期保持 aspNetDisabled,肉眼像“卡住不能选”。
|
||||
"""
|
||||
started_at = time.monotonic()
|
||||
deadline = started_at + (timeout_ms / 1000)
|
||||
last_log_at = 0.0
|
||||
last_state: dict[str, Any] = {}
|
||||
while time.monotonic() < deadline:
|
||||
last_state = _warehouse_select_state(locator, value)
|
||||
if last_state.get("hasTarget"):
|
||||
elapsed_ms = int((time.monotonic() - started_at) * 1000)
|
||||
return True, elapsed_ms, last_state
|
||||
now = time.monotonic()
|
||||
if now - last_log_at >= 2.0:
|
||||
print(
|
||||
"[dsv-filter] waiting warehouse options "
|
||||
f"target={value!r} optionCount={last_state.get('optionCount')} "
|
||||
f"realOptionCount={last_state.get('realOptionCount')} enabled={last_state.get('enabled')}"
|
||||
)
|
||||
last_log_at = now
|
||||
time.sleep(0.2)
|
||||
elapsed_ms = int((time.monotonic() - started_at) * 1000)
|
||||
return False, elapsed_ms, last_state
|
||||
|
||||
|
||||
def _wait_until_enabled(locator: Any, *, timeout_ms: int = 15_000) -> bool:
|
||||
"""等待 SSRS 控件从 aspNetDisabled 变为可操作。"""
|
||||
deadline = time.monotonic() + (timeout_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
disabled = locator.evaluate(
|
||||
"(node) => Boolean(node.disabled || node.classList.contains('aspNetDisabled'))"
|
||||
)
|
||||
if not disabled:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.25)
|
||||
return False
|
||||
|
||||
|
||||
def _fill_input_via_script(root: Any, selector: str, value: str) -> bool:
|
||||
"""
|
||||
通过脚本解除 disabled 并写入文本框(Owner/PutawayZone 兜底)。
|
||||
核心逻辑:ReportViewer 初始常把参数控件设为 aspNetDisabled,需先启用再赋值。
|
||||
"""
|
||||
try:
|
||||
return bool(
|
||||
root.evaluate(
|
||||
"""
|
||||
({ selector, value }) => {
|
||||
const node = document.querySelector(selector);
|
||||
if (!node) return false;
|
||||
node.disabled = false;
|
||||
node.removeAttribute('disabled');
|
||||
node.classList.remove('aspNetDisabled');
|
||||
node.readOnly = false;
|
||||
node.removeAttribute('readonly');
|
||||
node.value = value;
|
||||
node.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
node.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return true;
|
||||
}
|
||||
""",
|
||||
{"selector": selector, "value": value},
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _fill_multi_value_parameter(
|
||||
page: Any,
|
||||
label: str,
|
||||
values: list[str],
|
||||
*,
|
||||
timeout_ms: int,
|
||||
config_override: dict[str, str] | None = None,
|
||||
select_all: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。
|
||||
核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。
|
||||
"""
|
||||
config = {**_DSV_REPORT_PARAM_DEFAULTS.get(label, {}), **(config_override or {})}
|
||||
if config.get("control") != "multi_value":
|
||||
return False
|
||||
cleaned = [str(item).strip() for item in values if str(item).strip()]
|
||||
if not cleaned and not select_all:
|
||||
return False
|
||||
|
||||
_, text_locator = _find_locator(page, config["text"])
|
||||
if text_locator is not None and not select_all:
|
||||
try:
|
||||
current = str(text_locator.input_value(timeout=2_000) or "").strip()
|
||||
if current and all(item in current for item in cleaned):
|
||||
print(f"[dsv-filter] {label} already set text={current!r}")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
root, toggle = _find_locator(page, config["toggle"])
|
||||
if root is not None and toggle is not None:
|
||||
try:
|
||||
toggle.click(timeout=timeout_ms, force=True)
|
||||
time.sleep(0.4)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
root, _ = _find_locator(page, config["dropdown"])
|
||||
if root is None:
|
||||
return False
|
||||
|
||||
desired = {item.casefold() for item in cleaned}
|
||||
try:
|
||||
adjusted = root.evaluate(
|
||||
"""
|
||||
({ dropdownSelector, desiredValues, restrictToDesired, selectAll }) => {
|
||||
const dropdown = document.querySelector(dropdownSelector);
|
||||
if (!dropdown) return false;
|
||||
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
|
||||
const labels = Array.from(dropdown.querySelectorAll('label'));
|
||||
let changed = false;
|
||||
let selectAllClicked = false;
|
||||
const entries = [];
|
||||
for (const labelNode of labels) {
|
||||
const text = normalize(labelNode.textContent);
|
||||
if (!text) continue;
|
||||
let checkbox = null;
|
||||
const htmlFor = labelNode.getAttribute('for');
|
||||
if (htmlFor) {
|
||||
checkbox = document.getElementById(htmlFor);
|
||||
}
|
||||
if (!checkbox) {
|
||||
checkbox = labelNode.previousElementSibling;
|
||||
}
|
||||
if (!checkbox || checkbox.type !== 'checkbox') continue;
|
||||
const isSelectAll = text === '(Select All)' || text.toLowerCase().includes('select all');
|
||||
entries.push({ text, checkbox, isSelectAll });
|
||||
if (selectAll && isSelectAll) {
|
||||
if (!checkbox.checked) {
|
||||
checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
selectAllClicked = true;
|
||||
}
|
||||
}
|
||||
if (selectAll && !selectAllClicked) {
|
||||
for (const entry of entries) {
|
||||
if (!entry.isSelectAll && !entry.checkbox.checked) {
|
||||
entry.checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (selectAll) {
|
||||
return changed || entries.length > 0;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.isSelectAll) continue;
|
||||
const shouldCheck = desiredValues.includes(text.toLowerCase());
|
||||
if (restrictToDesired) {
|
||||
if (entry.checkbox.checked !== shouldCheck) {
|
||||
entry.checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
} else if (shouldCheck && !entry.checkbox.checked) {
|
||||
entry.checkbox.click();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed || labels.length > 0;
|
||||
}
|
||||
""",
|
||||
{
|
||||
"dropdownSelector": config["dropdown"],
|
||||
"desiredValues": list(desired),
|
||||
"restrictToDesired": label == "PutawayZone",
|
||||
"selectAll": select_all,
|
||||
},
|
||||
)
|
||||
if adjusted:
|
||||
if select_all:
|
||||
print(f"[dsv-filter] {label} multi_value select_all")
|
||||
else:
|
||||
print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}")
|
||||
if toggle is not None:
|
||||
try:
|
||||
toggle.click(timeout=2_000, force=True)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
except Exception as exc:
|
||||
print(f"[dsv-filter] {label} multi_value checkbox failed: {exc}", file=sys.stderr)
|
||||
|
||||
joined = ", ".join(cleaned)
|
||||
for root in _iter_dsv_report_roots(page):
|
||||
if _fill_input_via_script(root, config["text"], joined):
|
||||
print(f"[dsv-filter] {label} multi_value script text={joined!r}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_select_parameter(page: Any, label: str, value: str, selector: str, *, timeout_ms: int) -> bool:
|
||||
"""
|
||||
填充 SSRS ValidValueParameterInputControl(Warehouse 等原生 select)。
|
||||
核心逻辑:目标 option 出现在 DOM 后即用脚本赋值,不必等 Playwright 可见的 enabled 状态。
|
||||
"""
|
||||
_, locator = _find_locator(page, selector)
|
||||
if locator is None:
|
||||
return False
|
||||
|
||||
wait_cap_ms = min(timeout_ms, 45_000) if label == "Warehouse" else timeout_ms
|
||||
ready, waited_ms, state = _wait_for_warehouse_select_ready(locator, value, timeout_ms=wait_cap_ms)
|
||||
if ready and _apply_select_value_via_script(locator, value):
|
||||
mode = "script-after-options" if not state.get("enabled") else "script-after-enabled"
|
||||
print(
|
||||
f"[dsv-filter] {label} select {mode} value={value!r} "
|
||||
f"waitedMs={waited_ms} selector={selector!r}"
|
||||
)
|
||||
return True
|
||||
|
||||
if waited_ms >= 500:
|
||||
print(
|
||||
f"[dsv-filter] {label} warehouse options not ready after {waited_ms}ms; "
|
||||
f"fallback enabled-wait state={state!r}"
|
||||
)
|
||||
|
||||
enable_started = time.monotonic()
|
||||
_wait_until_enabled(locator, timeout_ms=min(wait_cap_ms, 15_000))
|
||||
enable_wait_ms = int((time.monotonic() - enable_started) * 1000)
|
||||
if enable_wait_ms >= 500:
|
||||
print(f"[dsv-filter] {label} enabled-waitMs={enable_wait_ms}")
|
||||
|
||||
try:
|
||||
locator.select_option(label=value, timeout=min(timeout_ms, 10_000))
|
||||
print(f"[dsv-filter] {label} select_option label={value!r} selector={selector!r}")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
if _apply_select_value_via_script(locator, value):
|
||||
print(f"[dsv-filter] {label} select script fallback value={value!r} selector={selector!r}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _probe_report_parameter_controls(page: Any) -> dict[str, Any]:
|
||||
"""
|
||||
枚举报表参数区(ReportViewerMain_ctl08)的实际控件,用于填参失败时定位控件类型漂移。
|
||||
|
||||
核心逻辑:SSRS 对同一参数名在不同报表里可能渲染成原生 select、文本框或多选框下拉;
|
||||
失败日志带上本探针后,无需人工开浏览器即可判断目标控件是否存在、option 数是否为空。
|
||||
"""
|
||||
roots = _iter_dsv_report_roots(page)
|
||||
probe: dict[str, Any] = {"roots": len(roots), "controls": []}
|
||||
for root in roots:
|
||||
try:
|
||||
items = root.evaluate(
|
||||
"""
|
||||
() => {
|
||||
const normalize = (text) => ((text || '') + '').replace(/\\s+/g, ' ').trim();
|
||||
const nodes = Array.from(document.querySelectorAll(
|
||||
'#ReportViewerMain_ctl08 select, #ReportViewerMain_ctl08 input, ' +
|
||||
'#ReportViewerMain_ctl08 [id$="_divDropDown"]'
|
||||
));
|
||||
return nodes.slice(0, 60).map((node) => {
|
||||
const table = node.tagName.toLowerCase() === 'select'
|
||||
? Array.from(node.options || []).map((item) => normalize(item.textContent)).filter(Boolean)
|
||||
: [];
|
||||
const dropdown = node.getAttribute('id') || '';
|
||||
return {
|
||||
id: dropdown,
|
||||
tag: node.tagName.toLowerCase(),
|
||||
type: node.getAttribute('type') || '',
|
||||
hidden: node.getAttribute('type') === 'hidden',
|
||||
optionCount: table.length,
|
||||
firstOptions: table.slice(0, 12),
|
||||
labelText: normalize(
|
||||
(node.closest('td') || {}).innerText || ''
|
||||
).slice(0, 120),
|
||||
};
|
||||
});
|
||||
}
|
||||
""",
|
||||
)
|
||||
if isinstance(items, list):
|
||||
probe["controls"].extend(items)
|
||||
except Exception as exc:
|
||||
probe["controls"].append({"probe_error": str(exc)[:120]})
|
||||
return probe
|
||||
|
||||
|
||||
def fill_dsv_filter_if_needed(
|
||||
page: Any,
|
||||
selector_env: str,
|
||||
label: str,
|
||||
value: str | None,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: Callable[[], int],
|
||||
debug_stage: Callable[..., None] | None = None,
|
||||
report_name: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
按 ReportViewer 控件类型填充 DSV 报表参数。
|
||||
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
|
||||
报表模板(_DSV_REPORT_PARAM_TEMPLATES)登记了同类报表的控件差异:传入 report_name 时,
|
||||
先按模板选择 multi_value/select;未命中的报表回退参数名默认值(旧行为)。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
|
||||
def _debug(stage: str, target: str) -> None:
|
||||
if debug_stage is not None:
|
||||
debug_stage(page, stage, target_text=target)
|
||||
|
||||
try:
|
||||
if page.get_by_text(text, exact=False).first.is_visible(timeout=1_500):
|
||||
print(f"[dsv-filter] {label} already visible text={text!r}")
|
||||
_debug(f"filter-skip-{label.lower()}", text)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
timeout_ms = browser_timeout_ms()
|
||||
defaults = dict(_DSV_REPORT_PARAM_DEFAULTS.get(label, {}))
|
||||
# 报表模板优先:同一参数名在不同报表的控件长相不同(3lv select vs JDA multi_value)。
|
||||
template_controls = resolve_parameter_controls(report_name, label)
|
||||
if template_controls:
|
||||
defaults.update(template_controls)
|
||||
custom_selector = str(env(selector_env) or "").strip()
|
||||
selector = custom_selector or defaults.get("selector") or defaults.get("text")
|
||||
|
||||
if not selector and not defaults:
|
||||
print(f"[dsv] skip {label} filter; no selector configured")
|
||||
_debug(f"filter-no-selector-{label.lower()}", text)
|
||||
return
|
||||
|
||||
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
|
||||
|
||||
# [STEP 1] 模板登记为 multi_value(或 Owner/PutawayZone 固有多选)时,优先走 checkbox 下拉填充。
|
||||
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
|
||||
if _fill_multi_value_parameter(
|
||||
page, label, values, timeout_ms=timeout_ms, config_override=defaults,
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
|
||||
# [STEP 2] 原生 select 路径:模板为 select 或未登记时继续旧行为(ddValue + 选项等待/脚本赋值)。
|
||||
select_selector = custom_selector or defaults.get("selector", "")
|
||||
if select_selector and (defaults.get("control") == "select" or select_selector.endswith("ddValue")):
|
||||
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
|
||||
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
|
||||
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
|
||||
for root in _iter_dsv_report_roots(page):
|
||||
if _fill_input_via_script(root, selector, text):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
|
||||
# 最后回退:Playwright fill(适用于普通文本参数)
|
||||
_, locator = _find_locator(page, selector)
|
||||
if locator is not None:
|
||||
_wait_until_enabled(locator, timeout_ms=timeout_ms)
|
||||
try:
|
||||
locator.fill(text, timeout=timeout_ms)
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
except Exception as exc:
|
||||
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
|
||||
|
||||
# 全部路径失败:输出参数区控件探针,便于下轮直接定位控件 ID/类型漂移。
|
||||
print(
|
||||
f"[dsv-filter] {label} control probe: "
|
||||
f"{json.dumps(_probe_report_parameter_controls(page), ensure_ascii=False)[:1500]}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
|
||||
_debug(f"filter-failed-{label.lower()}", text)
|
||||
|
||||
|
||||
def fill_dsv_multi_select_parameter(
|
||||
page: Any,
|
||||
label: str,
|
||||
values: list[str],
|
||||
*,
|
||||
selectors: dict[str, str] | None = None,
|
||||
select_all: bool = False,
|
||||
browser_timeout_ms: Callable[[], int],
|
||||
report_name: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
|
||||
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
|
||||
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
|
||||
核心逻辑:selectors 缺省时按报表模板(report_name)解析控件;两者都没有则返回 False。
|
||||
"""
|
||||
config_override = {"control": "multi_value"}
|
||||
effective_selectors = selectors or (resolve_parameter_controls(report_name, label) or None)
|
||||
if effective_selectors:
|
||||
for key in ("text", "toggle", "dropdown"):
|
||||
value = str(effective_selectors.get(key) or "").strip()
|
||||
if value:
|
||||
config_override[key] = value
|
||||
if not all(config_override.get(key) for key in ("text", "toggle", "dropdown")):
|
||||
return False
|
||||
return _fill_multi_value_parameter(
|
||||
page,
|
||||
label,
|
||||
values,
|
||||
timeout_ms=browser_timeout_ms(),
|
||||
config_override=config_override,
|
||||
select_all=select_all,
|
||||
)
|
||||
@@ -0,0 +1,503 @@
|
||||
"""
|
||||
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 as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
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,
|
||||
)
|
||||
Reference in new issue
Block a user