""" scripts/rpa/crane_navigation.py 用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。 依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。 逻辑:优先点击首页 Queries 区 On Hand Details 卡片;失败再走顶部 Queries 下拉菜单;最后 goto entry_url。 """ from __future__ import annotations import sys import time from typing import Any, Callable from urllib.parse import urlparse _ON_HAND_DETAILS_LABEL = "On Hand Details" _ON_HAND_DETAILS_ROUTE = "on-hand-details-query" # 首页 Queries 区大卡片:Vue hash 路由常见 href="#/on-hand-details-query"(非 "/on-hand-details-query") _CRANE_DASHBOARD_REPORT_TILE_SELECTORS: tuple[str, ...] = ( 'a[href*="on-hand-details-query"]', 'a.box[href*="on-hand-details-query"]', 'a.box.has-text-centered[href*="on-hand-details-query"]', 'a.box:has-text("On Hand Details")', 'a:has-text("On Hand Details")', '.box:has-text("On Hand Details")', ) # 顶部导航 Queries 下拉(第二张图) _CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = ( 'a.navbar-link:has-text("Queries")', '.navbar-item.has-dropdown > a.navbar-link', ) _CRANE_NAV_ON_HAND_DETAILS_SELECTORS: tuple[str, ...] = ( '.navbar-dropdown a.navbar-item:has-text("On Hand Details")', 'a.navbar-item:has-text("On Hand Details")', ) # 报表表单就绪信号:必须出现 Run Report 或报表参数字段;首页 Queries 区标题不算 ready _CRANE_REPORT_FORM_READY_SELECTORS: tuple[str, ...] = ( 'button:has-text("Run Report")', '[role="button"]:has-text("Run Report")', 'text=Choose Warehouse', 'text=Select Owner', ) def _visible_locator(page: Any, selector: str) -> Any | None: """在 page 与各 frame 中查找首个可见 locator。""" for root in (page, *list(getattr(page, "frames", []))): try: locator = root.locator(selector).first if locator.is_visible(timeout=500): return locator except Exception: continue return None def _report_route_from_entry_url(entry_url: str) -> str: """从 entry_url hash 提取报表路由片段,默认 on-hand-details-query。""" parsed = urlparse(str(entry_url or "").strip()) fragment = (parsed.fragment or "").strip().lstrip("/").lower() if fragment: return fragment return _ON_HAND_DETAILS_ROUTE def _current_url_fragment(page: Any) -> str: """读取当前页 URL hash 片段(不含 #/ 前缀)。""" try: current_url = str(page.url or "") except Exception: return "" parsed = urlparse(current_url) return (parsed.fragment or "").strip().lstrip("/").lower() def is_crane_on_homepage(page: Any) -> bool: """ 判定是否停在 Crane 登录后首页(/#/ 或空 hash)。 核心逻辑:首页 Queries 区有 On Hand Details 卡片,但报表表单尚未打开,不能视为 ready。 """ fragment = _current_url_fragment(page) if not fragment or fragment in {"home", "dashboard", "index"}: return True return False def is_crane_on_report_route(page: Any, entry_url: str) -> bool: """当前 URL hash 是否已落在目标报表路由。""" target_route = _report_route_from_entry_url(entry_url) fragment = _current_url_fragment(page) if not fragment: return False return target_route in fragment def _has_report_form_controls(page: Any) -> bool: """Run Report 或报表参数字段是否可见。""" for selector in _CRANE_REPORT_FORM_READY_SELECTORS: if _visible_locator(page, selector) is not None: return True return False def is_crane_report_form_ready(page: Any, entry_url: str) -> bool: """ 判定 On Hand Details Query 报表表单是否已就绪。 核心逻辑:首页 /#/ 不算 ready;必须 hash 落在报表路由且出现 Run Report / 参数字段。 """ if is_crane_on_homepage(page): return False if not is_crane_on_report_route(page, entry_url): return False return _has_report_form_controls(page) def _click_visible_locator(locator: Any, *, browser_timeout_ms: int) -> bool: try: locator.click(timeout=browser_timeout_ms) return True except Exception: pass try: locator.click(timeout=browser_timeout_ms, force=True) return True except Exception: return False def _wait_for_crane_homepage_ready(page: Any, *, browser_timeout_ms: int) -> bool: """ 登录后等待首页 Queries 区渲染完成。 核心逻辑:On Hand Details 卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。 """ deadline = time.monotonic() + (min(browser_timeout_ms, 20_000) / 1000) while time.monotonic() < deadline: for selector in ( 'text=On Hand Details', 'text=Queries', 'a[href*="on-hand-details-query"]', '.box:has-text("On Hand Details")', ): if _visible_locator(page, selector) is not None: print("[crane-nav] homepage shell ready") return True time.sleep(0.25) print("[crane-nav] homepage shell not detected before timeout", file=sys.stderr) return False def _click_by_role_link(page: Any, name: str, *, browser_timeout_ms: int) -> bool: for root in (page, *list(getattr(page, "frames", []))): try: locator = root.get_by_role("link", name=name, exact=False).first if locator.is_visible(timeout=500): return _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms) except Exception: pass return False def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool: """ 通过文本语义点击首页 Queries 区的 On Hand Details 卡片。 核心逻辑:hash 路由下 tile 可能是 a[href*=#/on-hand-details-query] 或 .box 包裹的 router-link。 """ tile_selectors = ( '.columns .box:has-text("On Hand Details")', 'section:has-text("Queries") .box:has-text("On Hand Details")', '.box:has-text("On Hand Details")', 'a[href*="on-hand-details-query"]', '[class*="box"]:has-text("On Hand Details")', ) for selector in tile_selectors: locator = _visible_locator(page, selector) if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): print(f"[crane-nav] clicked On Hand Details tile selector={selector!r}") return True for root in (page, *list(getattr(page, "frames", []))): try: locator = root.get_by_role("link", name=_ON_HAND_DETAILS_LABEL, exact=False).first if locator.is_visible(timeout=500) and _click_visible_locator( locator, browser_timeout_ms=browser_timeout_ms ): print("[crane-nav] clicked On Hand Details tile via link role") return True except Exception: pass for root in (page, *list(getattr(page, "frames", []))): try: locator = root.get_by_text(_ON_HAND_DETAILS_LABEL, exact=False).first if not locator.is_visible(timeout=500): continue for candidate in ( locator.locator("xpath=ancestor-or-self::a[1]"), locator.locator("xpath=ancestor-or-self::*[contains(@class,'box')][1]"), locator, ): try: target = candidate.first if target.is_visible(timeout=300) and _click_visible_locator( target, browser_timeout_ms=browser_timeout_ms ): print("[crane-nav] clicked On Hand Details tile via text locator") return True except Exception: continue except Exception: pass return False def _click_dashboard_on_hand_details( page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int, ) -> bool: """ 点击首页 Queries 区域的 On Hand Details 卡片(优先策略)。 核心逻辑:先文本语义定位 tile,再匹配 href*=on-hand-details-query 的 hash 路由链接。 """ if _click_on_hand_details_tile(page, browser_timeout_ms=browser_timeout_ms): return True selectors = tuple( item for item in (env("FREIGHT_RPA_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS) if item ) for selector in selectors: locator = _visible_locator(page, selector) if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): print(f"[crane-nav] clicked dashboard tile selector={selector!r}") return True if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms): print("[crane-nav] clicked dashboard tile via link role") return True return False def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool: """展开顶部 Queries 下拉菜单。""" selectors = tuple( item for item in (env("FREIGHT_RPA_CRANE_NAV_QUERIES_SELECTOR"), *_CRANE_NAV_QUERIES_MENU_SELECTORS) if item ) for selector in selectors: locator = _visible_locator(page, selector) if locator is None: continue try: locator.hover(timeout=min(browser_timeout_ms, 5_000)) except Exception: pass if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): print(f"[crane-nav] opened Queries menu selector={selector!r}") return True for root in (page, *list(getattr(page, "frames", []))): try: locator = root.get_by_role("link", name="Queries", exact=False).first if not locator.is_visible(timeout=500): continue try: locator.hover(timeout=3_000) except Exception: pass if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): print("[crane-nav] opened Queries menu via link role") return True except Exception: pass return False def _click_navbar_on_hand_details( page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int, ) -> bool: """ 通过顶部 Queries 下拉进入 On Hand Details(回退策略)。 核心逻辑:先展开 Queries navbar-dropdown,再点 a.navbar-item On Hand Details。 """ if not _open_queries_nav_menu(page, env=env, browser_timeout_ms=browser_timeout_ms): print("[crane-nav] Queries navbar menu not opened", file=sys.stderr) return False time.sleep(0.35) selectors = tuple( item for item in (env("FREIGHT_RPA_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item ) for selector in selectors: locator = _visible_locator(page, selector) if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): print(f"[crane-nav] clicked navbar item selector={selector!r}") return True if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms): print("[crane-nav] clicked navbar On Hand Details via link role") return True return False def _wait_for_report_navigation( page: Any, entry_url: str, *, browser_timeout_ms: int, ) -> bool: """点击导航后短等待目标路由或表单控件出现。""" deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000) while time.monotonic() < deadline: if is_crane_report_form_ready(page, entry_url): return True time.sleep(0.25) return False def _navigate_hash_route(page: Any, entry_url: str, *, browser_timeout_ms: int) -> None: """ 通过 goto + hash 赋值进入 SPA 报表路由。 核心逻辑:登录后常落在 /#/ 首页,仅 goto 完整 entry_url 时 Vue 路由可能不切换。 """ target = str(entry_url or "").strip() if not target: raise RuntimeError("Crane report navigation failed: entry_url is empty") route = _report_route_from_entry_url(entry_url) parsed = urlparse(target) base_url = f"{parsed.scheme}://{parsed.netloc}/" print(f"[crane-nav] fallback direct goto entry_url={target!r}") page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms) if is_crane_on_report_route(page, entry_url) and _has_report_form_controls(page): return print(f"[crane-nav] assigning hash route via SPA base={base_url!r} route={route!r}") try: page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms) page.evaluate( """ (route) => { const hash = route.startsWith('/') ? route : `/${route}`; if (window.location.hash !== `#${hash}`) { window.location.hash = hash; } } """, route, ) page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms) try: page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000)) except Exception: pass except Exception as exc: print(f"[crane-nav] hash route assignment failed: {exc}", file=sys.stderr) def navigate_to_crane_report( page: Any, entry_url: str, *, env: Callable[[str, str], str], browser_timeout_ms: int, ) -> str: """ 导航至 On Hand Details Query 报表页。 核心逻辑:[STEP 1] 首页卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] 直接 goto entry_url。 Returns: 使用的导航模式:`already_ready` | `dashboard_tile` | `navbar_menu` | `direct_goto`。 Raises: RuntimeError: 三种方式均未能进入报表表单。 """ if is_crane_report_form_ready(page, entry_url): print("[crane-nav] report form already ready, skip navigation") return "already_ready" _wait_for_crane_homepage_ready(page, browser_timeout_ms=browser_timeout_ms) # [STEP 1] 首页 Queries 区 On Hand Details 卡片 if _click_dashboard_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms): if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms): return "dashboard_tile" print("[crane-nav] dashboard tile click did not reach report form, trying navbar", file=sys.stderr) # [STEP 2] 顶部 Queries → On Hand Details if _click_navbar_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms): if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms): return "navbar_menu" print("[crane-nav] navbar navigation did not reach report form, trying direct goto", file=sys.stderr) # [STEP 3] 直接打开配置的 entry_url(hash 路由) _navigate_hash_route(page, entry_url, browser_timeout_ms=browser_timeout_ms) if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms): return "direct_goto" raise RuntimeError( "Crane report navigation failed: dashboard tile, navbar menu, and direct goto did not reach report form" )