Files
37duAutomation/plugins/xq0002/data/roster_export_api.py
T
puddy bf4f72cb01 feat(xq0002): 新增HR自动导入功能,优化花名册源表新鲜度校验
```

或者更贴合中文项目习惯的表述:
```msg
feat(xq0002): 新增HR自动导入,优化花名册源表新鲜度校验
2026-09-29 13:54:32 +08:00

454 lines
20 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 -*-
"""XQ0002 插件 - 员工花名册导出(接口版,由 xq0011 插件同模块内嵌移植)。
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
插件化改造点:
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
2. 内置「雇主险增减员导出模板」(B~O 共 14 列:所属单位→证件号,与 app 版 roster_template 一致);
3. 日志统一转发到 config.logger。
"""
import json
import os
import time
import urllib.parse
from datetime import date, datetime, timedelta
import requests
import pandas as pd
import websocket # websocket-client
from ..config import logger, SESSIONS_DIR, EXPORT_TEMPLATE, EXPORT_STATUSES
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
"rf_pt_users_export_define_select/getExecuteResult.mc")
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
# 花名册查询固定入参(从浏览器抓包提取)
ROSTER_QUERY_BASE_PARAMS = {
"menuName": "员工花名册",
"useSealTreeData": "0",
"treePermitType": "permit",
"cancelNodeClick": "1",
"clickFlag": "true",
"in_use": "1",
"commonQuery": "",
"newCondition": "",
"urlConditions": "",
"exportConfig": "",
"tableId": "assemble-hr_staff_base",
"rosterId": ROSTER_ID,
"includeChildrenSetting": "",
"struTreeCode": "cq37du",
"djStruTreeCode": "",
"djStruId": "",
"djOrgName": "",
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"rootId": "cq37du",
"isVirtual": "0",
"currentUserRootId": "cq37du",
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
"currentRoleIds": "POST_SYS_ADMIN,renshi",
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
"qrCodeUrl": "jspresumepage-01.jsp",
"orgName": "集团",
"belongUnitOrgName": "集团",
"throughParam": "",
"start": "0",
"sortType": "",
"sortName": "",
"pageNo": "1",
"pageSize": "15",
"dataIds": "",
"hideCols": "",
}
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
# 「雇主险增减员导出模板」(14 列 + 序号,B~O:所属单位→证件号,与 app 版 roster_template 一致)
ROSTER_TEMPLATE_FILTERS_EMPLOYER = ",".join([
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
"hr_staff_base.base_code", # 工号
"hr_staff_base.age", # 年龄
"hr_staff_base.sex", # 性别
"pt_staff_stru.POST_ORG_NAME", # 岗位
"pt_staff_stru.first_type_id", # 职位序列
"hr_staff_base_ext.ext_insurance_type", # 参保类型
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
"hr_staff_base.join_date", # 入职时间
"hr_staff_base.staff_name", # 姓名
"hr_staff_base.idCard", # 证件号
])
ROSTER_TEMPLATE_FILTERS = {
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
}
# ---------- 默认导出参数 ----------
DEFAULT_TEMPLATE = EXPORT_TEMPLATE # 雇主险增减员导出模板
DEFAULT_STATUSES = list(EXPORT_STATUSES) # ["在职"]
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
MAX_ATTEMPTS = 3 # 项目级重试次数
class LoginRequiredError(Exception):
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
_SALT = "yyryrtweasdasd" # 固定盐值
def _custom_base64_encode(data):
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
result = []
for i in range(0, len(data), 3):
chunk = data[i:i + 3]
b1 = chunk[0] if len(chunk) > 0 else 0
b2 = chunk[1] if len(chunk) > 1 else 0
b3 = chunk[2] if len(chunk) > 2 else 0
enc1 = (b1 >> 2) & 0x3F
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
enc4 = b3 & 0x3F
if len(chunk) == 1:
enc3 = 64
enc4 = 64
elif len(chunk) == 2:
enc4 = 64
result.append(_CUSTOM_CHARS[enc1])
result.append(_CUSTOM_CHARS[enc2])
result.append(_CUSTOM_CHARS[enc3])
result.append(_CUSTOM_CHARS[enc4])
return ''.join(result)
def build_condition(query_field, query_type, query_value, query_text="",
left_bracket="", right_bracket="", logic="AND", input_type="text"):
"""构造一个符合前端格式的单条查询条件字典。"""
return {
"queryField": query_field,
"leftBracket": left_bracket,
"queryType": query_type,
"queryValue": query_value,
"queryText": query_text,
"rightBracket": right_bracket,
"logic": logic,
"inputType": input_type,
}
def encode_common_query(query_list):
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
def _build_session(session=None):
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
if session is not None:
return session
if not os.path.exists(SHARED_HR_COOKIE_FILE):
raise LoginRequiredError(
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
session = requests.Session()
session.headers.update({
"User-Agent": USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies or []:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
return session
# ==================== 动态日期参数 ====================
def get_date_params():
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
now = datetime.now()
year, month, day = now.year, now.month, now.day
last_month_date = datetime(year, month, 1) - timedelta(days=1)
return {
"currentDate": f"{year}-{month:02d}-{day:02d}",
"currentMonth": f"{year}{month:02d}",
"currentMonthBar": f"{year}-{month:02d}",
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
"curYearFirstMon": f"{year}01",
"curYearFirstMonBar": f"{year}-01",
}
def _get_leave_range(today=None):
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
today = today or date.today()
last_month_end = today.replace(day=1) - timedelta(days=1)
start = last_month_end.replace(day=1)
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
# ==================== 查询条件构造 ====================
def _build_in_service_conditions():
return [
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
query_text="1", left_bracket="(", right_bracket=")",
input_type="select"),
build_condition("`hr_staff_base.person_status`", "in", "1",
query_text="1", left_bracket="(", right_bracket=")",
input_type="multipleSelect"),
]
def _build_leave_conditions(leave_start, leave_end):
return [
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
query_text="1", left_bracket="(", right_bracket=")",
input_type="select"),
build_condition("`hr_staff_base.person_status`", "in", "2",
query_text="2", left_bracket="(", right_bracket=")",
input_type="multipleSelect"),
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
left_bracket="(", input_type="date"),
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
right_bracket=")", input_type="date"),
]
# ==================== 自定义导出模板动态解析 ====================
def resolve_template_filters(session, template_name):
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
try:
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
templates = r.get("jsonList") or []
target = next((t for t in templates if t.get("ext1") == template_name), None)
if not target:
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
return None
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
export_field = (r2.get("result") or {}).get("exportField") or ""
fields = json.loads(export_field)
if not fields:
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
return None
filters = ",".join(f["tableCode"] for f in fields)
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
return filters
except Exception as e:
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
return None
# ==================== WebSocket 异步导出(单状态) ====================
def _bind_session(session):
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
"useSealTreeData": "0"}, timeout=30)
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
if "成功" not in r.text and r.text.strip() != "1":
raise LoginRequiredError(
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
"请先在插件界面重新完成 HR 登录后再重试。")
def _export_one_status_once(session, status, download_dir, template_name,
leave_start=None, leave_end=None, export_filters=None):
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
_bind_session(session)
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
if "hr.37du.co" in (c.domain or ""))
ws = websocket.WebSocket()
ws.connect(WS_SERVICE_URL, header=[
f"Cookie: {cookie_hdr}",
"Origin: https://hr.37du.co",
f"User-Agent: {USER_AGENT}",
], timeout=10)
try:
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
ack = json.loads(ws.recv())
if ack.get("code") != "SUBCRIBE_THEME_ACK":
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
if status == "离职":
ls = leave_start or ""
le = leave_end or ""
if not ls or not le:
ls, le = _get_leave_range()
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
logger.info("离职时间范围:%s ~ %s", ls, le)
else:
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
params.update(get_date_params())
params["exportConfig"] = json.dumps(
{"exportName": template_name,
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
ensure_ascii=False, separators=(",", ":"))
params["_t"] = str(int(time.time() * 1000))
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
if resp.status_code != 200:
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
file_url = None
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
while time.time() < deadline:
msg = json.loads(ws.recv())
txt, code = msg.get("txt", ""), msg.get("code", "")
if code != "NORMAL_PUSH_TO":
continue
if txt.startswith("--end--"):
file_url = txt.split("|", 1)[1].strip()
break
if txt.startswith(("开始下载", "正在生成")):
logger.info(" 进度:%s", txt)
if not file_url:
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
logger.info("导出完成,文件地址:%s", file_url)
finally:
ws.close()
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
dl = session.get(dl_url, timeout=120)
if dl.status_code != 200 or not dl.content:
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
os.makedirs(download_dir, exist_ok=True)
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
with open(temp_path, "wb") as f:
f.write(dl.content)
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
return temp_path
def _export_one_status(session, status, download_dir, template_name,
leave_start=None, leave_end=None, export_filters=None):
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
last_exc = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return _export_one_status_once(session, status, download_dir, template_name,
leave_start, leave_end, export_filters)
except LoginRequiredError:
raise # 确定性失败,不重试
except Exception as e:
last_exc = e
if attempt >= MAX_ATTEMPTS:
break
delay = 2.0 * attempt
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
status, attempt, e, delay)
time.sleep(delay)
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
raise last_exc
# ==================== 合并输出 ====================
def _normalize_and_save(files_with_status, output_path):
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
单 sheet,表头在第1行,数据第2行起。
"""
dfs = []
for status, path in files_with_status:
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
df["类型"] = status
dfs.append(df)
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
merged = pd.concat(dfs, ignore_index=True)
out_dir = os.path.dirname(output_path)
if out_dir:
os.makedirs(out_dir, exist_ok=True)
merged.to_excel(output_path, index=False)
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
for _, path in files_with_status:
try:
os.remove(path)
except Exception:
pass
return output_path
# ==================== 导出主流程 ====================
def export_roster(download_dir=None, output_path=None, template_name=None,
statuses=None, leave_start=None, leave_end=None,
ttl=DEFAULT_TTL_SECONDS, session=None):
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
Args:
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
其余参数与影刀版 export_roster 一致。
Returns:
合并后的花名册文件路径
"""
download_dir = download_dir or os.path.dirname(output_path or "") or "."
output_path = output_path or "花名册.xlsx"
template_name = template_name or DEFAULT_TEMPLATE
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
if ttl is None:
ttl = DEFAULT_TTL_SECONDS
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
if ttl > 0 and os.path.exists(output_path) \
and os.path.getsize(output_path) > 0 \
and time.time() - os.path.getmtime(output_path) <= ttl:
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
return output_path
leave_desc = ""
if "离职" in statuses:
ls, le = leave_start or "", leave_end or ""
if not ls or not le:
ls, le = _get_leave_range()
leave_desc = f",离职时间 {ls} ~ {le}"
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
template_name, statuses, leave_desc)
session = _build_session(session)
export_filters = resolve_template_filters(session, template_name)
files_with_status = []
for status in statuses:
logger.info("===== 开始导出在职状态:%s =====", status)
path = _export_one_status(session, status, download_dir, template_name,
leave_start, leave_end, export_filters)
files_with_status.append((status, path))
result = _normalize_and_save(files_with_status, output_path)
logger.info("===== 花名册导出并合并完成:%s =====", result)
return result