Files
37duAutomation/plugins/xq0020/data/hr_browser.py
T

191 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0020 EHR系统离职电子签流程审核 插件 - 浏览器审批层。
表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
提交结果依据监听的 sendWeTask 接口响应区分成功/失败(state="1" 成功,"0" 失败)。
"""
import json
import time
from ..config import logger, APPROVE_BUTTONS, SEND_WE_TASK_MARK
def _cookies_from_session(session):
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
cookies = []
if session is None:
return cookies
try:
jar = session.cookies
except Exception:
return cookies
for c in jar:
domain = str(c.domain or "")
if domain and "37du.co" not in domain:
continue
cookies.append({
"name": c.name,
"value": c.value,
"domain": domain or ".37du.co",
"path": c.path or "/",
})
return cookies
def build_browser(session):
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
from DrissionPage import ChromiumPage, ChromiumOptions
cookies = _cookies_from_session(session)
if not cookies:
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
page = ChromiumPage(ChromiumOptions())
page.set.cookies(cookies)
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
return page
def _find_button(page, selector, timeout=3.0):
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
try:
btn = page.ele(selector, timeout=timeout)
if btn:
return btn
except Exception:
pass
try:
frames = page.get_frames()
except Exception:
frames = []
for frame in frames:
try:
btn = frame.ele(selector, timeout=1)
if btn:
return btn
except Exception:
continue
return None
def _extract_json_response(req):
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
try:
return req.response.json()
except Exception:
body = getattr(req.response, "body", None)
if isinstance(body, (dict, list)):
return body
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def _wait_send_we_task_result(page, label, timeout=6.0):
"""等待并捕获 sendWeTask 提交接口响应,据此区分提交成功/失败。
判断规则(业务接口约定):
state="1" -> 提交成功
state="0" -> 提交失败(页面不关闭)
超时/监听异常未捕获到响应:提交成功后详情页会立即关闭/跳转,可能来不及监听,
默认按成功处理(失败不会关闭页面,因此不会漏判失败)。
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
remain = max(0.0, deadline - time.time())
req = page.listen.wait(timeout=min(0.5, remain))
except Exception as e:
logger.info("监听 sendWeTask 响应异常(页面可能已关闭),默认视为提交成功: %s", e)
return {"action": label, "ok": "true", "message": "未捕获到 sendWeTask 响应,默认视为提交成功"}
if req is None:
continue
if not hasattr(req, "url"):
logger.info("监听返回非请求对象(页面可能已关闭),默认视为提交成功: %r", req)
return {"action": label, "ok": "true", "message": "未捕获到 sendWeTask 响应,默认视为提交成功"}
if SEND_WE_TASK_MARK not in (req.url or ""):
continue
resp = _extract_json_response(req)
if not isinstance(resp, dict):
continue
state = str(resp.get("state", "")).strip()
if state == "1":
logger.info("审批提交成功(sendWeTask state=1)")
return {"action": label, "ok": "true", "message": "提交成功(sendWeTask state=1)"}
if state == "0":
fail_reason = str(resp.get("meg", "")).strip() or "提交失败"
logger.error("审批提交失败(sendWeTask state=0,原因:%s)", fail_reason)
return {"action": label, "ok": "false", "message": fail_reason}
return {"action": label, "ok": "true", "message": "未捕获到 sendWeTask 响应,默认视为提交成功"}
def submit_approval(page, decision):
"""按校验结论在流程详情页执行真实审批提交。
点击"同意"确认后监听 sendWeTask 提交接口响应区分成功/失败:
监听响应 state="1" -> 提交成功;
state="0" -> 提交失败(页面不关闭,必然能监听到);
页面已关闭/超时未捕获到响应 -> 默认视为提交成功(成功才关闭页面)。
Returns:
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
"""
if decision not in APPROVE_BUTTONS:
return {"action": "-", "ok": "true", "message": "无需提交"}
selector, label = APPROVE_BUTTONS[decision]
try:
page.listen.start(SEND_WE_TASK_MARK)
except Exception as e:
logger.warning("启动 sendWeTask 监听失败,将无法识别提交结果: %s", e)
try:
btn = _find_button(page, selector)
if btn is None:
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
logger.error(msg)
return {"action": label, "ok": "false", "message": msg}
logger.info("点击审批按钮: %s(%s)", selector, label)
btn.click()
def _visible(el):
try:
return el.states.is_displayed
except Exception:
return False
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
confirm = None
for _ in range(20):
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
if c1 is not None and _visible(c1):
confirm = c1
break
people = page.ele(".wf-select-people", timeout=0.2)
if people is not None and _visible(people):
try:
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
except Exception:
c2 = None
if c2 is not None and _visible(c2):
confirm = c2
break
time.sleep(0.2)
if confirm is None:
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
logger.error(msg)
return {"action": label, "ok": "false", "message": msg}
confirm.click()
logger.info("已点击确认框确定按钮")
# 依据监听到的 sendWeTask 响应返回提交结果(成功/失败/默认成功)
return _wait_send_we_task_result(page, label)
except Exception as e:
logger.error("审批提交失败[%s]: %s", label, str(e))
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
finally:
try:
page.listen.stop()
except Exception:
pass