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
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
scripts/rpa/crane_login_smoke.py
|
||||
|
||||
用途:本地手动验证 Crane FootPrint Portal 自动登录。
|
||||
依赖:Playwright、SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD。
|
||||
逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。
|
||||
|
||||
用法(仓库根目录):
|
||||
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_login_smoke.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _load_worker():
|
||||
repo_root = 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_crane_smoke", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def main() -> int:
|
||||
os.environ.setdefault("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",
|
||||
)
|
||||
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_CRANE_USERNAME")
|
||||
password = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD")
|
||||
if not username or not password:
|
||||
print("[crane-smoke] 缺少 SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD,请先配置环境变量。")
|
||||
return 1
|
||||
|
||||
entry_url = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
drop_dir = Path(tempfile.mkdtemp(prefix="crane_smoke_drop_"))
|
||||
playwright = context = runtime_profile_dir = None
|
||||
|
||||
print(f"[crane-smoke] headless={worker._env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false')}")
|
||||
print(f"[crane-smoke] user={username[:3]}*** entry={entry_url}")
|
||||
print("[crane-smoke] 正在打开浏览器并执行 Crane 自动登录…")
|
||||
|
||||
try:
|
||||
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
|
||||
worker._ensure_crane_session(page, entry_url)
|
||||
print(f"[crane-smoke] SUCCESS — Crane session ready, url={page.url}")
|
||||
print("[crane-smoke] 请在浏览器中确认 On Hand Details Query 表单可见。按 Enter 关闭浏览器…")
|
||||
try:
|
||||
input()
|
||||
except EOFError:
|
||||
import time
|
||||
|
||||
print("[crane-smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
|
||||
time.sleep(300)
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[crane-smoke] FAILED — {exc}")
|
||||
traceback.print_exc()
|
||||
print("[crane-smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
|
||||
try:
|
||||
input()
|
||||
except EOFError:
|
||||
import time
|
||||
|
||||
time.sleep(120)
|
||||
return 2
|
||||
finally:
|
||||
if context is not None:
|
||||
try:
|
||||
context.close()
|
||||
except Exception:
|
||||
pass
|
||||
if playwright is not None:
|
||||
try:
|
||||
playwright.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if runtime_profile_dir is not None:
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
shutil.rmtree(drop_dir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,410 @@
|
||||
"""
|
||||
scripts/rpa/crane_navigation.py
|
||||
|
||||
用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。
|
||||
依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。
|
||||
逻辑:优先点击首页 Queries 区 On Hand Details 卡片;失败再走顶部 Queries 下拉菜单;最后 goto entry_url。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
_ON_HAND_DETAILS_LABEL = "On Hand Details"
|
||||
_ON_HAND_DETAILS_ROUTE = "on-hand-details-query"
|
||||
|
||||
# 首页 Queries 区大卡片:Vue hash 路由常见 href="#/on-hand-details-query"(非 "/on-hand-details-query")
|
||||
_CRANE_DASHBOARD_REPORT_TILE_SELECTORS: tuple[str, ...] = (
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'a.box[href*="on-hand-details-query"]',
|
||||
'a.box.has-text-centered[href*="on-hand-details-query"]',
|
||||
'a.box:has-text("On Hand Details")',
|
||||
'a:has-text("On Hand Details")',
|
||||
'.box:has-text("On Hand Details")',
|
||||
)
|
||||
|
||||
# 顶部导航 Queries 下拉(第二张图)
|
||||
_CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = (
|
||||
'a.navbar-link:has-text("Queries")',
|
||||
'.navbar-item.has-dropdown > a.navbar-link',
|
||||
)
|
||||
|
||||
_CRANE_NAV_ON_HAND_DETAILS_SELECTORS: tuple[str, ...] = (
|
||||
'.navbar-dropdown a.navbar-item:has-text("On Hand Details")',
|
||||
'a.navbar-item:has-text("On Hand Details")',
|
||||
)
|
||||
|
||||
# 报表表单就绪信号:必须出现 Run Report 或报表参数字段;首页 Queries 区标题不算 ready
|
||||
_CRANE_REPORT_FORM_READY_SELECTORS: tuple[str, ...] = (
|
||||
'button:has-text("Run Report")',
|
||||
'[role="button"]:has-text("Run Report")',
|
||||
'text=Choose Warehouse',
|
||||
'text=Select Owner',
|
||||
)
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str) -> Any | None:
|
||||
"""在 page 与各 frame 中查找首个可见 locator。"""
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.is_visible(timeout=500):
|
||||
return locator
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _report_route_from_entry_url(entry_url: str) -> str:
|
||||
"""从 entry_url hash 提取报表路由片段,默认 on-hand-details-query。"""
|
||||
parsed = urlparse(str(entry_url or "").strip())
|
||||
fragment = (parsed.fragment or "").strip().lstrip("/").lower()
|
||||
if fragment:
|
||||
return fragment
|
||||
return _ON_HAND_DETAILS_ROUTE
|
||||
|
||||
|
||||
def _current_url_fragment(page: Any) -> str:
|
||||
"""读取当前页 URL hash 片段(不含 #/ 前缀)。"""
|
||||
try:
|
||||
current_url = str(page.url or "")
|
||||
except Exception:
|
||||
return ""
|
||||
parsed = urlparse(current_url)
|
||||
return (parsed.fragment or "").strip().lstrip("/").lower()
|
||||
|
||||
|
||||
def is_crane_on_homepage(page: Any) -> bool:
|
||||
"""
|
||||
判定是否停在 Crane 登录后首页(/#/ 或空 hash)。
|
||||
核心逻辑:首页 Queries 区有 On Hand Details 卡片,但报表表单尚未打开,不能视为 ready。
|
||||
"""
|
||||
fragment = _current_url_fragment(page)
|
||||
if not fragment or fragment in {"home", "dashboard", "index"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def is_crane_on_report_route(page: Any, entry_url: str) -> bool:
|
||||
"""当前 URL hash 是否已落在目标报表路由。"""
|
||||
target_route = _report_route_from_entry_url(entry_url)
|
||||
fragment = _current_url_fragment(page)
|
||||
if not fragment:
|
||||
return False
|
||||
return target_route in fragment
|
||||
|
||||
|
||||
def _has_report_form_controls(page: Any) -> bool:
|
||||
"""Run Report 或报表参数字段是否可见。"""
|
||||
for selector in _CRANE_REPORT_FORM_READY_SELECTORS:
|
||||
if _visible_locator(page, selector) is not None:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def is_crane_report_form_ready(page: Any, entry_url: str) -> bool:
|
||||
"""
|
||||
判定 On Hand Details Query 报表表单是否已就绪。
|
||||
核心逻辑:首页 /#/ 不算 ready;必须 hash 落在报表路由且出现 Run Report / 参数字段。
|
||||
"""
|
||||
if is_crane_on_homepage(page):
|
||||
return False
|
||||
if not is_crane_on_report_route(page, entry_url):
|
||||
return False
|
||||
return _has_report_form_controls(page)
|
||||
|
||||
|
||||
def _click_visible_locator(locator: Any, *, browser_timeout_ms: int) -> bool:
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms, force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_crane_homepage_ready(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
"""
|
||||
登录后等待首页 Queries 区渲染完成。
|
||||
核心逻辑:On Hand Details 卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。
|
||||
"""
|
||||
deadline = time.monotonic() + (min(browser_timeout_ms, 20_000) / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for selector in (
|
||||
'text=On Hand Details',
|
||||
'text=Queries',
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'.box:has-text("On Hand Details")',
|
||||
):
|
||||
if _visible_locator(page, selector) is not None:
|
||||
print("[crane-nav] homepage shell ready")
|
||||
return True
|
||||
time.sleep(0.25)
|
||||
print("[crane-nav] homepage shell not detected before timeout", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def _click_by_role_link(page: Any, name: str, *, browser_timeout_ms: int) -> bool:
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_role("link", name=name, exact=False).first
|
||||
if locator.is_visible(timeout=500):
|
||||
return _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool:
|
||||
"""
|
||||
通过文本语义点击首页 Queries 区的 On Hand Details 卡片。
|
||||
核心逻辑:hash 路由下 tile 可能是 a[href*=#/on-hand-details-query] 或 .box 包裹的 router-link。
|
||||
"""
|
||||
tile_selectors = (
|
||||
'.columns .box:has-text("On Hand Details")',
|
||||
'section:has-text("Queries") .box:has-text("On Hand Details")',
|
||||
'.box:has-text("On Hand Details")',
|
||||
'a[href*="on-hand-details-query"]',
|
||||
'[class*="box"]:has-text("On Hand Details")',
|
||||
)
|
||||
for selector in tile_selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked On Hand Details tile selector={selector!r}")
|
||||
return True
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_role("link", name=_ON_HAND_DETAILS_LABEL, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _click_visible_locator(
|
||||
locator, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print("[crane-nav] clicked On Hand Details tile via link role")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.get_by_text(_ON_HAND_DETAILS_LABEL, exact=False).first
|
||||
if not locator.is_visible(timeout=500):
|
||||
continue
|
||||
for candidate in (
|
||||
locator.locator("xpath=ancestor-or-self::a[1]"),
|
||||
locator.locator("xpath=ancestor-or-self::*[contains(@class,'box')][1]"),
|
||||
locator,
|
||||
):
|
||||
try:
|
||||
target = candidate.first
|
||||
if target.is_visible(timeout=300) and _click_visible_locator(
|
||||
target, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print("[crane-nav] clicked On Hand Details tile via text locator")
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_dashboard_on_hand_details(
|
||||
page: Any,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
点击首页 Queries 区域的 On Hand Details 卡片(优先策略)。
|
||||
核心逻辑:先文本语义定位 tile,再匹配 href*=on-hand-details-query 的 hash 路由链接。
|
||||
"""
|
||||
if _click_on_hand_details_tile(page, browser_timeout_ms=browser_timeout_ms):
|
||||
return True
|
||||
|
||||
selectors = tuple(
|
||||
item
|
||||
for item in (env("SHIPPING_NOTICE_RPA_WORKER_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("SHIPPING_NOTICE_RPA_WORKER_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("SHIPPING_NOTICE_RPA_WORKER_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item
|
||||
)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-nav] clicked navbar item selector={selector!r}")
|
||||
return True
|
||||
|
||||
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
|
||||
print("[crane-nav] clicked navbar On Hand Details via link role")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _wait_for_report_navigation(
|
||||
page: Any,
|
||||
entry_url: str,
|
||||
*,
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""点击导航后短等待目标路由或表单控件出现。"""
|
||||
deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if is_crane_report_form_ready(page, entry_url):
|
||||
return True
|
||||
time.sleep(0.25)
|
||||
return False
|
||||
|
||||
|
||||
def _navigate_hash_route(page: Any, entry_url: str, *, browser_timeout_ms: int) -> None:
|
||||
"""
|
||||
通过 goto + hash 赋值进入 SPA 报表路由。
|
||||
核心逻辑:登录后常落在 /#/ 首页,仅 goto 完整 entry_url 时 Vue 路由可能不切换。
|
||||
"""
|
||||
target = str(entry_url or "").strip()
|
||||
if not target:
|
||||
raise RuntimeError("Crane report navigation failed: entry_url is empty")
|
||||
|
||||
route = _report_route_from_entry_url(entry_url)
|
||||
parsed = urlparse(target)
|
||||
base_url = f"{parsed.scheme}://{parsed.netloc}/"
|
||||
|
||||
print(f"[crane-nav] fallback direct goto entry_url={target!r}")
|
||||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
if is_crane_on_report_route(page, entry_url) and _has_report_form_controls(page):
|
||||
return
|
||||
|
||||
print(f"[crane-nav] assigning hash route via SPA base={base_url!r} route={route!r}")
|
||||
try:
|
||||
page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||||
page.evaluate(
|
||||
"""
|
||||
(route) => {
|
||||
const hash = route.startsWith('/') ? route : `/${route}`;
|
||||
if (window.location.hash !== `#${hash}`) {
|
||||
window.location.hash = hash;
|
||||
}
|
||||
}
|
||||
""",
|
||||
route,
|
||||
)
|
||||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as exc:
|
||||
print(f"[crane-nav] hash route assignment failed: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
def navigate_to_crane_report(
|
||||
page: Any,
|
||||
entry_url: str,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> str:
|
||||
"""
|
||||
导航至 On Hand Details Query 报表页。
|
||||
核心逻辑:[STEP 1] 首页卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] 直接 goto entry_url。
|
||||
|
||||
Returns:
|
||||
使用的导航模式:`already_ready` | `dashboard_tile` | `navbar_menu` | `direct_goto`。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 三种方式均未能进入报表表单。
|
||||
"""
|
||||
if is_crane_report_form_ready(page, entry_url):
|
||||
print("[crane-nav] report form already ready, skip navigation")
|
||||
return "already_ready"
|
||||
|
||||
_wait_for_crane_homepage_ready(page, browser_timeout_ms=browser_timeout_ms)
|
||||
|
||||
# [STEP 1] 首页 Queries 区 On Hand Details 卡片
|
||||
if _click_dashboard_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "dashboard_tile"
|
||||
print("[crane-nav] dashboard tile click did not reach report form, trying navbar", file=sys.stderr)
|
||||
|
||||
# [STEP 2] 顶部 Queries → On Hand Details
|
||||
if _click_navbar_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "navbar_menu"
|
||||
print("[crane-nav] navbar navigation did not reach report form, trying direct goto", file=sys.stderr)
|
||||
|
||||
# [STEP 3] 直接打开配置的 entry_url(hash 路由)
|
||||
_navigate_hash_route(page, entry_url, browser_timeout_ms=browser_timeout_ms)
|
||||
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
|
||||
return "direct_goto"
|
||||
|
||||
raise RuntimeError(
|
||||
"Crane report navigation failed: dashboard tile, navbar menu, and direct goto did not reach report form"
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,382 @@
|
||||
"""
|
||||
scripts/rpa/crane_session.py
|
||||
|
||||
用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。
|
||||
依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。
|
||||
逻辑:识别登录页并自动填写;登录后委托 navigate_to_crane_report 进入 On Hand Details Query。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# Crane FootPrint 登录页(Bulma 表单)实测控件;用户名无 name 属性,靠 placeholder/label 定位。
|
||||
_CRANE_USERNAME_SELECTORS: tuple[str, ...] = (
|
||||
'input[placeholder="Enter user name..."]',
|
||||
'input[placeholder*="user name" i]',
|
||||
'form input.input[type="text"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="username"]',
|
||||
)
|
||||
|
||||
_CRANE_PASSWORD_SELECTORS: tuple[str, ...] = (
|
||||
'input[placeholder="Enter password..."]',
|
||||
'input.input.is-small.p-2.mt-1[type="password"]',
|
||||
'input[placeholder*="password" i]',
|
||||
'form input.input[type="password"]',
|
||||
'input[type="password"]',
|
||||
)
|
||||
|
||||
_CRANE_LOGIN_SUBMIT_SELECTORS: tuple[str, ...] = (
|
||||
'button.button.is-primary:has-text("Sign in")',
|
||||
'form button.button.is-primary',
|
||||
'button.button.is-primary',
|
||||
)
|
||||
|
||||
_CRANE_LOGIN_SUBMIT_TEXTS: tuple[str, ...] = ("Sign in", "Login", "Log in", "登录")
|
||||
|
||||
|
||||
def _load_crane_navigation_module() -> Any:
|
||||
"""运行时加载 crane_navigation,避免与 crane_session 循环 import。"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
module_path = Path(__file__).resolve().parent / "crane_navigation.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_navigation_runtime", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str) -> Any | None:
|
||||
"""在 page 与各 frame 中查找首个可见 locator。"""
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
if locator.is_visible(timeout=500):
|
||||
return locator
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _dispatch_input_events(locator: Any) -> None:
|
||||
"""触发 input/change 事件,驱动 Vue 表单解除 Sign in 按钮 disabled。"""
|
||||
try:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
node.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
node.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _fill_visible_locator(locator: Any, value: str, *, browser_timeout_ms: int) -> bool:
|
||||
"""向已定位控件写入文本,并触发前端校验以启用 Sign in。"""
|
||||
try:
|
||||
locator.fill(value, timeout=browser_timeout_ms)
|
||||
_dispatch_input_events(locator)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=3_000)
|
||||
locator.press("Control+A")
|
||||
locator.press("Backspace")
|
||||
locator.type(value, delay=30)
|
||||
_dispatch_input_events(locator)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_crane_button_enabled(locator: Any) -> bool:
|
||||
"""Sign in 初始为 disabled,需等用户名/密码填写后解除。"""
|
||||
try:
|
||||
return bool(
|
||||
locator.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
if (!node) return false;
|
||||
const disabled = Boolean(node.disabled);
|
||||
const ariaDisabled = String(node.getAttribute('aria-disabled') || '').toLowerCase() === 'true';
|
||||
const classDisabled = node.classList && node.classList.contains('is-disabled');
|
||||
return !disabled && !ariaDisabled && !classDisabled;
|
||||
}
|
||||
"""
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
return locator.is_enabled(timeout=500)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_crane_sign_in_button(
|
||||
page: Any,
|
||||
*,
|
||||
selector_env: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> Any | None:
|
||||
"""
|
||||
查找已启用的 Sign in 按钮。
|
||||
核心逻辑:页面按钮 class 为 button is-primary,填写凭据前带 disabled 属性。
|
||||
"""
|
||||
selectors = tuple(
|
||||
item
|
||||
for item in (env(selector_env), *_CRANE_LOGIN_SUBMIT_SELECTORS, 'button[type="submit"]')
|
||||
if item
|
||||
)
|
||||
deadline = time.monotonic() + (browser_timeout_ms / 1000)
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _is_crane_button_enabled(locator):
|
||||
return locator
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
for text in _CRANE_LOGIN_SUBMIT_TEXTS:
|
||||
try:
|
||||
locator = root.get_by_role("button", name=text, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _is_crane_button_enabled(locator):
|
||||
return locator
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.25)
|
||||
|
||||
# 最后再试一次可见按钮(部分环境 disabled 属性更新滞后,但 click 仍有效)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
return locator
|
||||
return None
|
||||
|
||||
|
||||
def _fill_crane_field(
|
||||
page: Any,
|
||||
*,
|
||||
selector_env: str,
|
||||
value: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
fallback_selectors: tuple[str, ...],
|
||||
label: str | None = None,
|
||||
placeholder: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
填写 Crane 登录字段。
|
||||
核心逻辑:优先环境变量 selector,再试页面实测 fallback,最后用 label/placeholder 语义定位。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
|
||||
selectors = tuple(item for item in (env(selector_env), *fallback_selectors) if item)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None and _fill_visible_locator(locator, text, browser_timeout_ms=browser_timeout_ms):
|
||||
print(f"[crane-login] filled field via selector={selector!r}")
|
||||
return True
|
||||
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
if label:
|
||||
try:
|
||||
locator = root.get_by_label(label, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _fill_visible_locator(
|
||||
locator, text, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print(f"[crane-login] filled field via label={label!r}")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
if placeholder:
|
||||
try:
|
||||
locator = root.get_by_placeholder(placeholder, exact=False).first
|
||||
if locator.is_visible(timeout=500) and _fill_visible_locator(
|
||||
locator, text, browser_timeout_ms=browser_timeout_ms
|
||||
):
|
||||
print(f"[crane-login] filled field via placeholder={placeholder!r}")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_crane_login_submit(
|
||||
page: Any,
|
||||
*,
|
||||
selector_env: str,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> bool:
|
||||
"""
|
||||
点击 Crane Sign in 按钮。
|
||||
核心逻辑:等待 button.button.is-primary 解除 disabled 后再点击。
|
||||
"""
|
||||
locator = _find_crane_sign_in_button(
|
||||
page,
|
||||
selector_env=selector_env,
|
||||
env=env,
|
||||
browser_timeout_ms=min(browser_timeout_ms, 15_000),
|
||||
)
|
||||
if locator is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=browser_timeout_ms, force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def is_crane_login_page(page: Any) -> bool:
|
||||
"""当前页是否为 Crane FootPrint 登录表单。"""
|
||||
for selector in (
|
||||
'input[placeholder="Enter user name..."]',
|
||||
'input[placeholder="Enter password..."]',
|
||||
):
|
||||
if _visible_locator(page, selector) is not None:
|
||||
return True
|
||||
for root in (page, *list(getattr(page, "frames", []))):
|
||||
try:
|
||||
if root.get_by_label("User Name", exact=False).first.is_visible(timeout=500):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _crane_entry_host(entry_url: str) -> str:
|
||||
"""从 entry_url 提取 host。"""
|
||||
parsed = urlparse(str(entry_url or "").strip())
|
||||
return (parsed.netloc or "").lower()
|
||||
|
||||
|
||||
def is_crane_session_active(page: Any, entry_url: str) -> bool:
|
||||
"""
|
||||
判定浏览器是否已在 Crane portal 维持有效登录态。
|
||||
核心逻辑:仍在 craneww 域且不再显示登录表单,即视为 session 有效。
|
||||
"""
|
||||
host = _crane_entry_host(entry_url)
|
||||
if not host:
|
||||
return False
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
if host not in current_url:
|
||||
return False
|
||||
if is_crane_login_page(page):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def wait_for_crane_app_ready(
|
||||
page: Any,
|
||||
entry_url: str,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> None:
|
||||
"""
|
||||
登录后导航并等待 Crane 报表表单就绪。
|
||||
核心逻辑:先 navigate_to_crane_report(首页卡片 → 顶部菜单 → goto),再轮询表单控件。
|
||||
"""
|
||||
navigation = _load_crane_navigation_module()
|
||||
mode = navigation.navigate_to_crane_report(
|
||||
page,
|
||||
entry_url,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
)
|
||||
print(f"[crane-nav] navigation mode={mode!r}")
|
||||
|
||||
deadline = time.monotonic() + (browser_timeout_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if navigation.is_crane_report_form_ready(page, entry_url):
|
||||
print("[crane-login] report form ready")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
|
||||
raise RuntimeError("Crane report form did not become ready after navigation; check selectors or permissions")
|
||||
|
||||
|
||||
def maybe_auto_login_crane(
|
||||
page: Any,
|
||||
*,
|
||||
env: Callable[[str, str], str],
|
||||
browser_timeout_ms: int,
|
||||
) -> None:
|
||||
"""
|
||||
Crane FootPrint 自动登录:User Name → Password → Sign in。
|
||||
核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。
|
||||
"""
|
||||
username = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME")
|
||||
password = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD")
|
||||
if not username or not password:
|
||||
return
|
||||
|
||||
if not is_crane_login_page(page):
|
||||
print("[crane-login] no login form detected, skip auto login")
|
||||
return
|
||||
|
||||
user_filled = _fill_crane_field(
|
||||
page,
|
||||
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR",
|
||||
value=username,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
fallback_selectors=_CRANE_USERNAME_SELECTORS,
|
||||
label="User Name",
|
||||
placeholder="Enter user name...",
|
||||
)
|
||||
password_filled = _fill_crane_field(
|
||||
page,
|
||||
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR",
|
||||
value=password,
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
fallback_selectors=_CRANE_PASSWORD_SELECTORS,
|
||||
label="Password",
|
||||
placeholder="Enter password...",
|
||||
)
|
||||
if not user_filled and not password_filled:
|
||||
print("[crane-login] login form visible but fields not filled", file=sys.stderr)
|
||||
return
|
||||
if user_filled != password_filled:
|
||||
raise RuntimeError("CRANE login form partially detected; please configure login selectors")
|
||||
|
||||
if not _click_crane_login_submit(
|
||||
page,
|
||||
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
env=env,
|
||||
browser_timeout_ms=browser_timeout_ms,
|
||||
):
|
||||
raise RuntimeError("CRANE login fields detected but Sign in button was not found")
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||||
if is_crane_login_page(page):
|
||||
raise RuntimeError("CRANE login did not complete; MFA/SSO/manual verification may be required")
|
||||
|
||||
# [STEP] 登录后 Crane 常先落到 /#/ 首页,等待 SPA 壳层渲染再进入报表导航
|
||||
try:
|
||||
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 15_000))
|
||||
except Exception:
|
||||
pass
|
||||
Reference in new issue
Block a user