feat(xq0007): 新增 OA 社保增减名单梳理插件(v1.0.1)
从 OA 导出员工参保/停保申请名单(申请日期筛选、去废弃、同工号取最新),清洗后按 15 个/批与 HR 参保记录逐工号核对,输出标红核对表;支持单文件直传/多文件打包 zip、按份数留档、钉钉摘要推送。
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""OA 名单导出(登录态由底座注入的 requests.Session 提供)。
|
||||
|
||||
影刀版 social_change.py 的 OA 部分移植要点:
|
||||
- 原版用 DrissionPage SessionPage 承载共享 oa_cookies.json;插件版直接用
|
||||
`ctx.get_session("oa")` 注入的 requests.Session,不读 cookies 文件;
|
||||
- 原版「监听首页菜单请求取 fdId」需真实浏览器(门户菜单是首页 JS 异步拉取),
|
||||
插件版仅在取 fdId 这一步启动 DrissionPage 浏览器,拿到即关,其余全部走 HTTP。
|
||||
|
||||
流程:会话校验 → 取门户 fdId → 按菜单名取 searchId → 查总数 → 导出 xls 落盘。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from urllib.parse import urljoin, urlparse, parse_qs
|
||||
|
||||
from .. import config
|
||||
|
||||
# 首页加载后等待菜单异步请求的窗口(秒),与影刀版一致
|
||||
_HOME_SETTLE_SECONDS = 5
|
||||
_LISTEN_WINDOW_SECONDS = 10
|
||||
|
||||
|
||||
# ==================== 会话校验 ====================
|
||||
def is_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需启动浏览器)。"""
|
||||
try:
|
||||
resp = session.get(config.TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON(如 {"type_2":"39"});失效会被重定向到登录页返回 HTML
|
||||
text = (resp.text or "").strip()
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
config.logger.info("OA 会话校验异常:%s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== fdId(门户菜单监听) ====================
|
||||
def _cookies_from_session(session):
|
||||
"""把 requests.Session 的 cookies 转成 DrissionPage set.cookies 需要的结构。"""
|
||||
cookies = []
|
||||
try:
|
||||
for c in session.cookies:
|
||||
cookies.append({"name": c.name, "value": c.value,
|
||||
"domain": c.domain, "path": c.path or "/"})
|
||||
except Exception as e:
|
||||
config.logger.warning("读取 OA 会话 cookies 失败:%s", e)
|
||||
return cookies
|
||||
|
||||
|
||||
def fetch_nav_fd_id(session):
|
||||
"""启动浏览器打开 OA 首页,监听菜单请求(sysPortalNav.do)取出 fdId。
|
||||
|
||||
fdId 用于调用菜单接口取各查询方案的 searchId(参保/停保两个菜单同属一个门户,
|
||||
同一次运行只需取一次)。浏览器仅此一步使用,取到立即关闭。
|
||||
"""
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions # 懒加载:未装依赖只影响本步
|
||||
except ImportError as e:
|
||||
raise RuntimeError(f"缺少 DrissionPage 依赖,无法获取 OA 菜单标识({e});"
|
||||
f"请让执行机同步插件依赖后重试")
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("OA 会话中无 cookies,请先在壳子(工作台)重新登录 OA 平台")
|
||||
|
||||
co = ChromiumOptions()
|
||||
co.auto_port(True) # 独立端口 + 临时用户目录,不与人工浏览器互相影响
|
||||
try:
|
||||
browser = ChromiumPage(co)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"启动浏览器失败(取 OA 菜单标识需要本机安装 Chrome):{e}")
|
||||
listening = False
|
||||
try:
|
||||
browser.set.cookies(cookies)
|
||||
browser.listen.start()
|
||||
listening = True
|
||||
config.logger.info("正在访问 OA 首页获取菜单标识:%s", config.HOME_URL)
|
||||
browser.get(config.HOME_URL)
|
||||
time.sleep(_HOME_SETTLE_SECONDS)
|
||||
|
||||
# 兜底:浏览器 cookies 失效会停在登录页,快速失败,避免空等监听窗口
|
||||
if "login.jsp" in browser.url or browser.ele("tag:input@name=j_username", timeout=2):
|
||||
raise RuntimeError("OA 登录态已失效(浏览器停留在登录页),请重新登录 OA 后重试")
|
||||
|
||||
deadline = time.time() + _LISTEN_WINDOW_SECONDS
|
||||
while time.time() < deadline:
|
||||
req = browser.listen.wait(timeout=1)
|
||||
if req and config.NAV_REQUEST_KEY in (req.url or ""):
|
||||
qs = parse_qs(urlparse(req.url).query)
|
||||
fd_id = qs.get("fdId", [None])[0]
|
||||
if not fd_id:
|
||||
raise RuntimeError("菜单请求中未包含 fdId,OA 门户结构可能已调整")
|
||||
config.logger.info("动态获取到菜单 fdId:%s", fd_id)
|
||||
return fd_id
|
||||
raise RuntimeError("超时未监听到 OA 菜单请求,请检查网络或登录态")
|
||||
finally:
|
||||
if listening:
|
||||
try:
|
||||
browser.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== searchId / 总数 / 导出 ====================
|
||||
def _check_response(resp, action):
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{action}失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{action}失败,状态码:{resp.status_code}")
|
||||
|
||||
|
||||
def get_search_id(session, fd_id, menu_name):
|
||||
"""按菜单名(员工参保申请 / 员工停保申请)从菜单接口取 searchId。"""
|
||||
params = {"method": "portlet", "fdId": fd_id, "f_s": "sourcejs",
|
||||
"t": str(int(time.time() * 1000))}
|
||||
resp = session.get(f"{config.OA_BASE_URL}{config.MENU_API_PATH}", params=params, timeout=30)
|
||||
_check_response(resp, "获取菜单")
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
raise RuntimeError("获取菜单失败:OA 登录态可能已失效,请重新登录 OA 后重试")
|
||||
|
||||
def find_item(items):
|
||||
for item in items or []:
|
||||
if item.get("text") == menu_name:
|
||||
return item
|
||||
if "children" in item:
|
||||
found = find_item(item["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
items = data if isinstance(data, list) else (data or {}).get("children", [])
|
||||
item = find_item(items)
|
||||
if not item:
|
||||
raise RuntimeError(f"OA 菜单中未找到「{menu_name}」,请确认菜单权限")
|
||||
qs = parse_qs(urlparse(urljoin(config.OA_BASE_URL, item.get("href", ""))).query)
|
||||
search_id = qs.get("searchId", [None])[0]
|
||||
if not search_id:
|
||||
raise RuntimeError(f"菜单「{menu_name}」链接中未包含 searchId")
|
||||
config.logger.info("菜单「%s」searchId:%s", menu_name, search_id)
|
||||
return search_id
|
||||
|
||||
|
||||
def get_total_count(session, base_params, search_id, timestamp):
|
||||
"""查结果总数(结果页里的 exportNum)。"""
|
||||
params = {"method": "result", "searchId": search_id, "j_timestamp": timestamp, **base_params}
|
||||
resp = session.get(config.SEARCH_URL, params=params,
|
||||
headers={"Referer": config.LIST_URL}, timeout=60)
|
||||
_check_response(resp, "查询总数")
|
||||
html = resp.text or ""
|
||||
for pat in (r'exportNum:\s*"(\d+)"', r"总记录数[::]\s*(\d+)", r"共\s*(\d+)\s*条"):
|
||||
m = re.search(pat, html)
|
||||
if m:
|
||||
total = int(m.group(1))
|
||||
config.logger.info("获取到总记录数:%d", total)
|
||||
return total
|
||||
if "login.jsp" in html or "j_username" in html:
|
||||
raise RuntimeError("查询总数失败:OA 登录态可能已失效,请重新登录 OA 后重试")
|
||||
config.logger.warning("未找到总条数,按 0 条处理")
|
||||
return 0
|
||||
|
||||
|
||||
def export_all_data(session, base_params, total, columns, search_id, timestamp):
|
||||
"""导出全部结果(OA 返回 xls 二进制内容)。"""
|
||||
data = {
|
||||
"method": "exportResult", "searchId": search_id, "j_timestamp": timestamp, **base_params,
|
||||
"fdColumns": columns, "fdNum": str(total), "fdNumStart": "1", "fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true", "checkIdValues": "",
|
||||
}
|
||||
resp = session.post(config.SEARCH_URL, data=data,
|
||||
headers={"Referer": config.LIST_URL}, timeout=180)
|
||||
_check_response(resp, "导出数据")
|
||||
content = resp.content or b""
|
||||
if not content:
|
||||
raise RuntimeError("导出数据失败:返回内容为空,请稍后重试或确认 OA 登录态")
|
||||
return content
|
||||
|
||||
|
||||
def export_menu_xls(session, search_id, base_params, columns, out_path):
|
||||
"""导出指定菜单名单到本地 xls,返回导出条数(0 = 无数据,不落盘)。"""
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total <= 0:
|
||||
return 0
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(content)
|
||||
config.logger.info("导出完成(%d 条):%s", total, out_path)
|
||||
return total
|
||||
Reference in New Issue
Block a user