""" scripts/rpa/crane_login_smoke.py 用途:本地手动验证 Crane FootPrint Portal 自动登录。 依赖:Playwright、FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD。 逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。 用法(仓库根目录): $env:FREIGHT_RPA_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 = Path(__file__).resolve().parents[2] module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py" spec = importlib.util.spec_from_file_location("freight_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("FREIGHT_RPA_HEADLESS", "false") os.environ.setdefault("FREIGHT_RPA_MOCK", "false") os.environ.setdefault( "FREIGHT_RPA_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile", ) if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"): os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge") worker = _load_worker() username = worker._env("FREIGHT_RPA_CRANE_USERNAME") password = worker._env("FREIGHT_RPA_CRANE_PASSWORD") if not username or not password: print("[crane-smoke] 缺少 FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_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('FREIGHT_RPA_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())