新增内容包括: 1. 7个业务需求占位文档目录与README 2. 共享OA登录、钉钉机器人推送工具模块 3. 雇主险变更清单导出脚本 4. 考勤月报封存检查两个检查脚本 5. 重庆社保停保导入名单生成脚本
662 lines
31 KiB
Python
662 lines
31 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: roster_export_api.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-09-05
|
||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——纯接口版。
|
||
与浏览器版 roster_export.py 的 main(...) 调用签名完全一致:
|
||
main(statuses, leave_start, leave_end, template, output_path, download_dir)
|
||
底层改为:访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||
接收 "--end--|文件路径" 推送 -> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||
无需 DrissionPage/浏览器,字典翻译(星级/参保类型/职衔/职级等)由服务端完成。
|
||
@Version: 1.0.0
|
||
|
||
运行方式:
|
||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||
statuses 在职状态,str "在职" / "在职,离职" 或 list(默认 在职+离职)
|
||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||
template 自定义导出模板名(默认 员工基础信息)
|
||
output_path 合并后 Excel 保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||
download_dir 单状态临时文件目录(默认 D:\\资料\\人资\\花名册\\download,合并后自动清理)
|
||
2. 命令行:python roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||
3. 业务脚本:懒加载本模块调用 main(...) / export_roster(...)
|
||
|
||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install requests pandas openpyxl websocket-client
|
||
|
||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import json
|
||
import os
|
||
import time
|
||
import urllib.parse
|
||
from datetime import date, datetime, timedelta
|
||
|
||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||
try:
|
||
import requests
|
||
import pandas as pd
|
||
import websocket # websocket-client
|
||
except ImportError as _import_err:
|
||
raise RuntimeError(
|
||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||
"请先执行安装:\n"
|
||
" pip install requests pandas openpyxl websocket-client\n"
|
||
f"缺失依赖详情: {_import_err}"
|
||
)
|
||
|
||
|
||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||
class _PrintLogger:
|
||
def debug(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def info(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def warning(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def error(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
|
||
logger = _PrintLogger()
|
||
|
||
|
||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||
_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 + 盐值 + 首尾重排)。"""
|
||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||
_APP_DATA_DIR = os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||
'37duAutomation'
|
||
)
|
||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
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"
|
||
# 自定义导出模板定义(页面「自定义导出」弹窗同款接口:列表拿 id -> 详情拿 exportField)
|
||
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"
|
||
|
||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||
# commonQuery 在导出时按「在职/离职」条件动态加密生成
|
||
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 字段串,顺序与页面导出模板列一致) ----------
|
||
ROSTER_TEMPLATE_FILTERS = {
|
||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||
"员工基础信息": ",".join([
|
||
"hr_staff_base.staff_name", # 姓名
|
||
"hr_staff_base.base_code", # 工号
|
||
"hr_staff_base.idCard", # 证件号
|
||
"hr_staff_base.join_date", # 入职时间
|
||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||
"hr_staff_base_ext.ext_star_level", # 星级
|
||
"pt_staff_stru.first_type_id", # 职位序列
|
||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||
"pt_post_level.ext_grade_name", # 职等
|
||
"hr_staff_base.mobile_phone", # 手机号码
|
||
"hr_staff_base.person_status", # 在职状态
|
||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||
"hr_staff_base.nation", # 民族
|
||
"hr_staff_base.sex", # 性别
|
||
"hr_staff_base.age", # 年龄
|
||
"hr_staff_base.period", # 试用期限(月)
|
||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||
"hr_staff_base.identity", # 用工类型
|
||
]),
|
||
# 「雇主险增减员导出模板」(14 列,无三级/五级部门,顺序按模板)
|
||
"雇主险增减员导出模板": ",".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_export.py 保持一致) ----------
|
||
DEFAULT_TEMPLATE = "员工基础信息"
|
||
DEFAULT_STATUSES = ["在职", "离职"]
|
||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||
|
||
# 异步导出等待超时(秒,服务端逐条生成 7000+ 条约需 10~20 秒,留足余量)
|
||
EXPORT_TIMEOUT_SECONDS = 300
|
||
|
||
# ---------- 项目级重试次数(单状态导出失败最大尝试次数,含首次) ----------
|
||
MAX_ATTEMPTS = 3
|
||
|
||
|
||
class LoginRequiredError(Exception):
|
||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||
|
||
|
||
# ==================== 登录态(共享 cookies 文件) ====================
|
||
def _build_session():
|
||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||
|
||
Raises:
|
||
LoginRequiredError: 共享 cookies 文件不存在
|
||
"""
|
||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||
raise LoginRequiredError(
|
||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||
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 _is_expired(text) -> bool:
|
||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||
|
||
|
||
# ==================== 动态日期参数 ====================
|
||
def get_date_params():
|
||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||
now = datetime.now()
|
||
year, month, day = now.year, now.month, now.day
|
||
|
||
# 上月(本月 1 号减一天即上月最后一天)
|
||
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():
|
||
"""在职人员条件:主职 in (1) + 在职状态 in (1),等价页面默认抓包条件。"""
|
||
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):
|
||
"""离职人员条件:主职 in (1) + 在职状态 in (2) + 离职时间区间,等价页面离职筛选抓包串。"""
|
||
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, user_id=None):
|
||
"""按模板名动态解析 exportFilters 字段串(与页面「自定义导出」弹窗逻辑一致)。
|
||
|
||
两步:模板列表(redmagicapi select,拿 id + ext1 名称)-> 模板详情
|
||
(getPtusersexportdefine,拿 exportField JSON)-> 按 exportField 顺序拼接字段串。
|
||
|
||
Args:
|
||
session: 已登录的 requests.Session 对象
|
||
template_name: 模板名(对应模板列表的 ext1)
|
||
user_id: 当前登录用户 id(缺省用 ROSTER_QUERY_BASE_PARAMS 里的 currentUserId)
|
||
|
||
Returns:
|
||
exportFilters 字段串(逗号分隔,顺序与模板一致);解析失败返回 None(调用方回退内置模板)
|
||
"""
|
||
user_id = user_id or ROSTER_QUERY_BASE_PARAMS["currentUserId"]
|
||
try:
|
||
# 1. 模板列表 -> 按名称匹配拿 id
|
||
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」(可选:%s),回退内置模板",
|
||
template_name, [t.get("ext1") for t in templates])
|
||
return None
|
||
|
||
# 2. 模板详情 -> exportField JSON -> 按顺序拼字段串
|
||
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 容器。
|
||
|
||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||
"""
|
||
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]}。"
|
||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||
|
||
|
||
def _export_one_status_once(session, status, download_dir, template_name,
|
||
leave_start=None, leave_end=None, export_filters=None):
|
||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。
|
||
|
||
Returns:
|
||
临时 Excel 文件路径
|
||
|
||
Raises:
|
||
LoginRequiredError: 登录态失效
|
||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||
"""
|
||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||
_bind_session(session)
|
||
|
||
# 2. WebSocket 连接并订阅主题
|
||
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)
|
||
|
||
# 3. 提交异步导出任务(按状态构造 commonQuery,服务端翻译全部字典字段)
|
||
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)
|
||
|
||
# 4. 接收进度推送,直到 --end--|文件路径
|
||
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()
|
||
|
||
# 5. 下载文件到临时目录
|
||
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行标题(源表第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):
|
||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||
|
||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出),
|
||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||
不同模板导出到不同路径,不会互相复用。纯接口实现,无需浏览器。
|
||
|
||
Args:
|
||
download_dir: 单状态临时文件目录(默认 DEFAULT_DOWNLOAD_DIR)
|
||
output_path: 合并后保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||
template_name: 自定义导出模板名(默认 DEFAULT_TEMPLATE)
|
||
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
|
||
(默认 DEFAULT_STATUSES)
|
||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
|
||
ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
|
||
|
||
Returns:
|
||
合并后的花名册文件路径
|
||
|
||
Raises:
|
||
LoginRequiredError: HR 登录态缺失或失效
|
||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||
"""
|
||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||
template_name = template_name or DEFAULT_TEMPLATE
|
||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||
if ttl is None: # 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),临时目录:%s =====",
|
||
template_name, statuses, leave_desc, download_dir)
|
||
|
||
session = _build_session()
|
||
# 模板动态解析(列表 -> 详情 -> exportField),失败回退内置模板字段串
|
||
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
|
||
|
||
|
||
def main(statuses=None, leave_start=None, leave_end=None,
|
||
template=None, output_path=None, download_dir=None):
|
||
"""影刀自定义指令入口「37du花名册导出」(与浏览器版 roster_export.py 签名一致)。
|
||
|
||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||
statuses: 在职状态,str "在职" 或 "在职,离职",或 list ["在职","离职"]
|
||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||
template: 自定义导出模板名
|
||
output_path / download_dir: 保存路径与临时下载目录
|
||
|
||
Returns:
|
||
{"success": bool, "save_path": str, "statuses": [...], "template": str}
|
||
save_path 即调用方传入的 output_path(合并后的花名册文件路径)。
|
||
"""
|
||
# 在职状态:兼容 str / list / 逗号分隔
|
||
if isinstance(statuses, str):
|
||
statuses = [s.strip() for s in statuses.replace(",", ",").split(",") if s.strip()]
|
||
elif statuses:
|
||
statuses = [str(s) for s in statuses]
|
||
else:
|
||
statuses = list(DEFAULT_STATUSES)
|
||
|
||
template = template or DEFAULT_TEMPLATE
|
||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||
|
||
try:
|
||
save_path = export_roster(
|
||
download_dir=download_dir, output_path=output_path,
|
||
template_name=template, statuses=statuses,
|
||
leave_start=leave_start, leave_end=leave_end)
|
||
return {"success": True, "save_path": save_path, "statuses": statuses, "template": template}
|
||
except Exception as e:
|
||
logger.error("花名册导出失败:%s", e)
|
||
return {"success": False, "error": str(e), "statuses": statuses, "template": template}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
statuses = ["在职"]
|
||
leave_start = ""
|
||
leave_end = ""
|
||
template = "员工基础信息"
|
||
output_path = r"D:\资料\人资\排班异常识别\员工花名册.xlsx"
|
||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||
template=template, output_path=output_path)
|