#!/usr/bin/env python3 """使用真实 Chrome 登录系统并生成 HTML 使用手册所需截图。 依赖本机 Google Chrome;通过 Chrome DevTools Protocol 操作页面,不额外安装 浏览器自动化包。运行前先启动 ``uvicorn app.main:app --port 8000``。 """ from __future__ import annotations import json import shutil import subprocess import tempfile import time import urllib.request from pathlib import Path from websockets.sync.client import connect ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "web" / "public" / "help" / "assets" BASE = "http://127.0.0.1:8000" CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" PORT = 9227 def api_login(username: str, password: str) -> dict: body = json.dumps({"username": username, "password": password}).encode() req = urllib.request.Request( f"{BASE}/api/v1/auth/login", data=body, headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=20) as resp: return json.load(resp) class CDP: def __init__(self, ws_url: str) -> None: self.ws = connect(ws_url, max_size=64 * 1024 * 1024, legacy=True) self.seq = 0 def call(self, method: str, params: dict | None = None) -> dict: self.seq += 1 current = self.seq self.ws.send(json.dumps({"id": current, "method": method, "params": params or {}})) while True: msg = json.loads(self.ws.recv(timeout=30)) if msg.get("id") == current: if "error" in msg: raise RuntimeError(f"{method}: {msg['error']}") return msg.get("result", {}) def eval(self, expression: str): result = self.call( "Runtime.evaluate", {"expression": expression, "returnByValue": True, "awaitPromise": True}, ) return result.get("result", {}).get("value") def wait_text(self, text: str, timeout: float = 25) -> None: deadline = time.time() + timeout expression = f"document.body && document.body.innerText.includes({json.dumps(text)})" while time.time() < deadline: if self.eval(expression): time.sleep(0.7) return time.sleep(0.25) raise TimeoutError(f"页面未出现文字:{text}") def navigate(self, path: str, text: str | None = None) -> None: self.call("Page.navigate", {"url": f"{BASE}{path}"}) time.sleep(0.5) if text: self.wait_text(text) def screenshot(self, name: str) -> None: result = self.call( "Page.captureScreenshot", {"format": "png", "fromSurface": True, "captureBeyondViewport": False}, ) import base64 (OUT / name).write_bytes(base64.b64decode(result["data"])) print(f"captured {name}") def wait_debug_port() -> dict: deadline = time.time() + 20 while time.time() < deadline: try: with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/version", timeout=1) as resp: return json.load(resp) except Exception: time.sleep(0.2) raise RuntimeError("Chrome 调试端口未就绪") def page_target() -> dict: with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/json/list", timeout=3) as resp: targets = json.load(resp) page = next((item for item in targets if item.get("type") == "page"), None) if page is None: raise RuntimeError("Chrome 中没有可用页面") return page def main() -> None: OUT.mkdir(parents=True, exist_ok=True) profile = Path(tempfile.mkdtemp(prefix="unis-hrms-chrome-")) chrome = subprocess.Popen( [ CHROME, "--headless=new", f"--remote-debugging-port={PORT}", f"--user-data-dir={profile}", "--no-first-run", "--no-default-browser-check", "--disable-gpu", "--hide-scrollbars", "--window-size=1600,1080", "about:blank", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: wait_debug_port() cdp = CDP(page_target()["webSocketDebuggerUrl"]) cdp.call("Page.enable") cdp.call("Runtime.enable") cdp.call("Emulation.setDeviceMetricsOverride", { "width": 1600, "height": 1080, "deviceScaleFactor": 1, "mobile": False, }) cdp.navigate("/login", "登录工作台") cdp.screenshot("01-login.png") plans = [ ("admin", "admin123", "/dashboard", "今日组织概览", "02-dashboard.png"), ("admin", "admin123", "/employees", "员工档案", "03-employees.png"), ("admin", "admin123", "/org/job-levels", "职级职等", "04-job-levels.png"), ("admin", "admin123", "/payroll/batches", "月度算薪", "06-payroll.png"), ("admin", "admin123", "/benefits/enrollments", "参保登记", "07-benefits.png"), ("admin", "admin123", "/system/roles", "角色权限", "08-roles.png"), ] token_for = {} for username, password, path, text, name in plans: pair = token_for.get(username) if pair is None: pair = api_login(username, password) token_for[username] = pair cdp.navigate("/login") cdp.eval( "localStorage.setItem('unis-hrms-auth', " + json.dumps(json.dumps({ "state": {"token": pair["access_token"], "refresh": pair["refresh_token"]}, "version": 0, })) + ")" ) cdp.navigate(path, text) cdp.screenshot(name) # 职级行内打开“报销标准”抽屉,展示多项目配置。 cdp.navigate("/org/job-levels", "职级职等") clicked = cdp.eval( "(() => { const b=[...document.querySelectorAll('button')]" ".find(x => x.innerText.includes('报销标准')); if (!b) return false; b.click(); return true })()" ) if not clicked: raise RuntimeError("未找到报销标准按钮") cdp.wait_text("可配置多个报销项目") cdp.screenshot("05-expense-standards.png") # 普通员工 Web 自助:导航直接呈现与 H5 同名的 5 项。 pair = api_login("emp", "emp123456") token_for["emp"] = pair cdp.navigate("/login") cdp.eval( "localStorage.setItem('unis-hrms-auth', " + json.dumps(json.dumps({ "state": {"token": pair["access_token"], "refresh": pair["refresh_token"]}, "version": 0, })) + ")" ) cdp.navigate("/dashboard", "常用自助入口") cdp.screenshot("09-web-self-home.png") cdp.navigate("/self/profile", "我的信息") cdp.screenshot("10-web-self-profile.png") cdp.eval( "(() => { const b=[...document.querySelectorAll('span,a,button')]" ".find(x => x.innerText.trim()==='修改资料'); if (!b) return false; b.click(); return true })()" ) cdp.wait_text("提交审核") cdp.screenshot("11-profile-audit.png") # H5 自动识别由单独的手机视口验证。 cdp.call("Emulation.setDeviceMetricsOverride", { "width": 390, "height": 844, "deviceScaleFactor": 2, "mobile": True, }) cdp.call("Emulation.setUserAgentOverride", { "userAgent": ( "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1" ), }) cdp.navigate("/m", "最新实发工资") cdp.screenshot("12-h5-home.png") cdp.navigate("/m/profile", "我的信息") cdp.screenshot("13-h5-profile.png") # 审批中心使用 HR 账号(拥有审批权且有员工档案)。 pair = token_for.get("hr") or api_login("hr", "hr123456") cdp.navigate("/login") cdp.eval( "localStorage.setItem('unis-hrms-auth', " + json.dumps(json.dumps({ "state": {"token": pair["access_token"], "refresh": pair["refresh_token"]}, "version": 0, })) + ")" ) cdp.navigate("/m/approvals", "审批中心") cdp.screenshot("14-approvals.png") cdp.ws.close() finally: chrome.terminate() try: chrome.wait(timeout=5) except subprocess.TimeoutExpired: chrome.kill() shutil.rmtree(profile, ignore_errors=True) if __name__ == "__main__": main()