feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 数据层:HR 接口数据导出与加载(封存数据 / 花名册 / 调动台账)。"""
|
||||
@@ -0,0 +1,483 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 员工花名册导出(由 workflows/share/roster_export_api.py 内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
|
||||
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 日志统一转发到 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
|
||||
|
||||
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 字段串,顺序与页面导出模板列一致) ----------
|
||||
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", # 用工类型
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数 ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_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 _save_df_lowmem(df, path: str) -> None:
|
||||
"""低内存写出 DataFrame:openpyxl write_only 逐行写入。
|
||||
|
||||
全集团花名册(在职+离职)数万行 × 30+ 列,pd.DataFrame.to_excel() 峰值内存
|
||||
(DataFrame 拷贝 + openpyxl 全量 cell + zip 压缩缓冲)可能触发 MemoryError;
|
||||
改以 write_only 流式逐行写出,内存占用与行数无关。
|
||||
"""
|
||||
from openpyxl import Workbook
|
||||
wb = Workbook(write_only=True)
|
||||
ws = wb.create_sheet(title="Sheet1")
|
||||
ws.append([str(c) for c in df.columns])
|
||||
for row in df.itertuples(index=False, name=None):
|
||||
ws.append([None if (isinstance(v, float) and pd.isna(v)) else v for v in row])
|
||||
wb.save(path)
|
||||
|
||||
|
||||
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)
|
||||
_save_df_lowmem(merged, output_path)
|
||||
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
|
||||
@@ -0,0 +1,570 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 封存数据导出与预处理(由影刀版 seal_data_export.py 移植)。
|
||||
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1~6 一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. HR 会话/用户 ID 由底座 RunContext 注入(config 全局钩子),不再自行读 cookies 构建;
|
||||
2. 登录态失效不再自动补登(插件无法自动登录),直接抛错提示重新登录;
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from collections import Counter
|
||||
from datetime import date, datetime
|
||||
from functools import lru_cache
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import (
|
||||
logger, require_session, require_user_id, set_roster_path, get_roster_path,
|
||||
get_seal_rows, set_seal_rows,
|
||||
CACHE_DIR, SESSIONS_DIR,
|
||||
HR_BASE_URL, GET_CUR_USER_INFO_URL, SEAL_URL, SEAL_SQL_ID, PAGE_MAX_SIZE,
|
||||
DEFAULT_SAVE_DIR, SEAL_UNIT_WHITELIST, SEAL_CODE_FIELDS,
|
||||
EXCLUDE_FIRST_DEPT, EXCLUDE_EMPTY_FIRST_DEPT,
|
||||
ROSTER_CODE_COL, ROSTER_UNIT_COL, ROSTER_DEPT_COLS,
|
||||
ROSTER_JOIN_COL, ROSTER_LEAVE_COL,
|
||||
)
|
||||
|
||||
# 花名册岗位列(异常名单岗位回填来源;「员工基础信息」模板含此列)
|
||||
ROSTER_POST_COL = "岗位"
|
||||
|
||||
# 所属单位白名单 / 剔除口径 / 花名册列定义统一取自 config
|
||||
|
||||
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
|
||||
CN_FIELD_MAP: Dict[str, str] = {
|
||||
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
|
||||
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
|
||||
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
|
||||
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
|
||||
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
|
||||
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
|
||||
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
|
||||
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
|
||||
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
|
||||
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
|
||||
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
|
||||
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
|
||||
"_年度福利假天": "kq_stat_leave_day_num24",
|
||||
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
|
||||
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
|
||||
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
|
||||
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
|
||||
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
|
||||
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
|
||||
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
|
||||
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
|
||||
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
|
||||
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
|
||||
"员工状态": "staff_status", "在职状态": "person_status_name",
|
||||
}
|
||||
|
||||
|
||||
# ==================== HR 登录态(底座注入) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _expired_error(label):
|
||||
return RuntimeError(
|
||||
f"{label}:HR 登录态已失效,无法自动补登。请在插件界面重新完成 HR 登录后重试。")
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(getPageAjaxList.mc + leave_wage_SelectV2) ====================
|
||||
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页考勤封存数据。
|
||||
|
||||
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
|
||||
"""
|
||||
params = {
|
||||
"tree_code": "cq37du",
|
||||
"user_id": user_id,
|
||||
"sqlId": SEAL_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"dept_org_name": "",
|
||||
"confirm_state": "",
|
||||
"person_status": "",
|
||||
"identity": "",
|
||||
"staff_status": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"post_type": "1",
|
||||
"custom_dept_ids": "",
|
||||
"custom_dept_names": "",
|
||||
"STAFF_ID": "",
|
||||
"sealOrgAlias": "",
|
||||
"seal_dept_stru_id": "",
|
||||
"kqDataOperatorName": "",
|
||||
"kqDataOperatorId": "",
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"yearmonth": yearmonth,
|
||||
"kq_data_state": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
|
||||
|
||||
|
||||
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
|
||||
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise _expired_error("考勤封存")
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤封存第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤封存无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
import time
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _text(v) -> str:
|
||||
return _clean(v)
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)[:10]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _fmt_date(v) -> str:
|
||||
"""日期格式化为 yyyy-mm-dd(如 2026-09-21 00:00:00 → 2026-09-21)。"""
|
||||
d = _parse_date(v)
|
||||
return d.isoformat() if d else _clean(v)[:10]
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _month_days(ym: str) -> int:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
return pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
|
||||
|
||||
def _seal_path(save_dir: str, ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(save_dir, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
# ==================== 预处理:所属单位白名单筛选 ====================
|
||||
def _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get("BELONG_UNIT_ORG_NAME")) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
def _rec_code(rec: dict) -> str:
|
||||
"""封存记录工号(base_code 优先,seal_base_code 兜底)。"""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
c = _clean(rec.get(f))
|
||||
if c:
|
||||
return c
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 花名册:剔除名单 & 工号→1-5级部门 缓存 ====================
|
||||
@lru_cache(maxsize=4)
|
||||
def _load_roster_maps(roster_path: str) -> Tuple[Dict[str, dict], Set[str]]:
|
||||
"""读取花名册(当日全量导出,在职+离职)→ (工号→所属单位/1-5级部门 映射, 剔除工号集合)。
|
||||
|
||||
剔除口径(不参与本检查):
|
||||
1) 一级部门 = EXCLUDE_FIRST_DEPT(职业技术培训学校);
|
||||
2) 一级部门为空 = 直属单位根节点的高管(未挂具体部门树),同样不参与检查。
|
||||
同一工号可能多行(在职/离职并存),后读取的行覆盖先前的行。
|
||||
花名册缺失时返回空映射与空集合,不影响检查主流程(仅部门回填为空、不剔除)。
|
||||
"""
|
||||
if not roster_path or not os.path.exists(roster_path):
|
||||
logger.warning("花名册不存在,跳过部门回填与学校剔除:%s", roster_path)
|
||||
return {}, set()
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
dept_map: Dict[str, dict] = {}
|
||||
excluded: Set[str] = set()
|
||||
school_n = exec_n = 0
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code:
|
||||
continue
|
||||
info = {
|
||||
"所属单位": _clean(row.get(ROSTER_UNIT_COL)),
|
||||
"岗位": _clean(row.get(ROSTER_POST_COL)),
|
||||
"入职时间": _clean(row.get(ROSTER_JOIN_COL)),
|
||||
"离职时间": _clean(row.get(ROSTER_LEAVE_COL)),
|
||||
**{c: _clean(row.get(c)) for c in ROSTER_DEPT_COLS},
|
||||
}
|
||||
dept_map[code] = info
|
||||
if _clean(row.get(ROSTER_DEPT_COLS[0])) == EXCLUDE_FIRST_DEPT:
|
||||
excluded.add(code)
|
||||
school_n += 1
|
||||
elif EXCLUDE_EMPTY_FIRST_DEPT and not _clean(row.get(ROSTER_DEPT_COLS[0])):
|
||||
excluded.add(code) # 部门树为空的高管,不参与检查
|
||||
exec_n += 1
|
||||
logger.info("花名册读取完成:%s(%d 人,剔除「%s」%d 人 + 高管 %d 人)",
|
||||
roster_path, len(dept_map), EXCLUDE_FIRST_DEPT, school_n, exec_n)
|
||||
return dept_map, excluded
|
||||
|
||||
|
||||
def load_roster_dept_map(roster_path: str = None) -> Dict[str, dict]:
|
||||
"""工号 → {所属单位, 一级部门~五级部门} 映射(进程内按路径缓存,一次读取)。"""
|
||||
dept_map, _ = _load_roster_maps(roster_path or get_roster_path())
|
||||
return dept_map
|
||||
|
||||
|
||||
def load_excluded_codes(roster_path: str = None) -> Set[str]:
|
||||
"""一级部门 = 职业技术培训学校 的剔除工号集合。"""
|
||||
_, excluded = _load_roster_maps(roster_path or get_roster_path())
|
||||
return set(excluded)
|
||||
|
||||
|
||||
DEPT_CN_ORDER = ("一", "二", "三", "四", "五")
|
||||
DEPT_ORG_FIELDS = ("DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE")
|
||||
|
||||
|
||||
def enrich_dept_fields(target: dict, code: str, rec: dict = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""异常名单行回填「所属单位 + 一级~五级部门 + 岗位 + 入职/离职时间」:
|
||||
优先花名册(按工号),兜底封存记录字段。
|
||||
|
||||
Args:
|
||||
target: 待回填的行 dict(就地修改并返回)。
|
||||
code: 37工号。
|
||||
rec: 封存记录行(兜底来源),可为 None。
|
||||
"""
|
||||
info = load_roster_dept_map(roster_path).get(code) or {}
|
||||
rec = rec or {}
|
||||
target["所属单位"] = info.get("所属单位") or _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
target["岗位"] = info.get("岗位") or _clean(rec.get("POST_ALIAS_NAME"))
|
||||
target["入职时间"] = _fmt_date(info.get("入职时间") or _clean(rec.get("join_date")))
|
||||
# 离职时间以封存记录为准(封存的是检查月当月实际状态):存在离职后又复职的员工,
|
||||
# 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底。
|
||||
# 优先取「封存快照」离职时间 seal_leaveOffice_date(保留检查月离职日期),
|
||||
# 其次当前离职时间 leaveOffice_date,最后花名册。
|
||||
target["离职时间"] = _fmt_date(
|
||||
_clean(rec.get("seal_leaveOffice_date"))
|
||||
or _clean(rec.get("leaveOffice_date"))
|
||||
or info.get("离职时间"))
|
||||
for chn, cn, f in zip(DEPT_CN_ORDER, ROSTER_DEPT_COLS, DEPT_ORG_FIELDS):
|
||||
target[cn] = info.get(cn) or _clean(rec.get(f))
|
||||
return target
|
||||
|
||||
|
||||
def _write_seal_rows_lowmem(rows: List[dict], path: str) -> None:
|
||||
"""低内存写出封存表:openpyxl write_only 逐行写入原始记录。
|
||||
|
||||
全集团封存数据可达数万行 × 数十列,pd.DataFrame(...).to_excel() 的峰值内存
|
||||
(DataFrame 拷贝 + openpyxl 全量 cell + zip 压缩缓冲)极易触发 MemoryError;
|
||||
改以 write_only 流式逐行写出,内存占用与行数无关。
|
||||
"""
|
||||
from openpyxl import Workbook
|
||||
wb = Workbook(write_only=True)
|
||||
ws = wb.create_sheet(title="封存数据")
|
||||
columns = list(rows[0].keys()) if rows else []
|
||||
rename = {en: cn for cn, en in CN_FIELD_MAP.items() if en in columns}
|
||||
ws.append([rename.get(c, c) for c in columns])
|
||||
for rec in rows:
|
||||
ws.append([rec.get(c, "") for c in columns])
|
||||
wb.save(path)
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
save_dir: 输出目录,默认 config.DEFAULT_SAVE_DIR。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = require_session()
|
||||
user_id = require_user_id()
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 2.1 花名册剔除:一级部门 = 职业技术培训学校 的不参与本检查
|
||||
excluded = load_excluded_codes()
|
||||
if excluded:
|
||||
before = len(filtered)
|
||||
filtered = [rec for rec in filtered if _rec_code(rec) not in excluded]
|
||||
logger.info("花名册剔除不参与人员(「%s」/高管):%d 人 → %d 人",
|
||||
EXCLUDE_FIRST_DEPT, before, len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
path = _seal_path(save_dir, ym)
|
||||
try:
|
||||
_write_seal_rows_lowmem(filtered, path)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None, save_dir: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
save_dir: 输出目录,默认 config.DEFAULT_SAVE_DIR。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
save_dir = save_dir or DEFAULT_SAVE_DIR
|
||||
# 进程内缓存:run() 预处理阶段已预读(含剔除),检查1~6 复用,避免各自重复读大文件
|
||||
cached = get_seal_rows()
|
||||
if cached is not None:
|
||||
return cached
|
||||
path = _seal_path(save_dir, ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先执行插件(封存导出步骤)导出并预处理当月封存数据后再检查。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
# 兜底剔除(防止历史封存表未做学校剔除):一级部门 = 职业技术培训学校 的工号
|
||||
excluded = load_excluded_codes()
|
||||
if excluded:
|
||||
before = len(rows)
|
||||
rows = [r for r in rows if _rec_code(r) not in excluded]
|
||||
if len(rows) != before:
|
||||
logger.warning("读取封存表后按花名册剔除不参与人员(「%s」/高管)%d 人:%d → %d",
|
||||
EXCLUDE_FIRST_DEPT, before - len(rows), before, len(rows))
|
||||
set_seal_rows(rows)
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 排班预处理(工号 → 检查月最早排班日期,与花名册映射一致供各检查复用) ====================
|
||||
SHIFT_SQL_ID = "kq_count_SelectBanci"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
|
||||
|
||||
def fetch_shift_page(session, user_id, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页全集团排班数据(base_code 留空 = 不过滤,返回全部员工当月排班)。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": SHIFT_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, begin_date, end_date) -> List[dict]:
|
||||
"""分页抓取全集团当月排班数据(登录态失效抛错提示重新登录)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(session, user_id, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise _expired_error("排班数据")
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def build_earliest_shift_map(shift_rows: List[dict]) -> Dict[str, date]:
|
||||
"""从全集团排班记录构建 工号 → 检查月最早排班日期 映射。
|
||||
|
||||
排班记录一条 = 一个员工当月逐日排班,字段为 {YYYY-MM-DD}_team_name;
|
||||
取首个非空且非「休息」的日期作为该员工当月最早排班日。
|
||||
供检查1「二次入职」识别:花名册入职日期晚于最早排班日期 = 入职前已有排班 = 二次入职。
|
||||
"""
|
||||
mapping: Dict[str, date] = {}
|
||||
for row in shift_rows:
|
||||
code = _clean(row.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
earliest: Optional[date] = None
|
||||
for key, val in row.items():
|
||||
if not (isinstance(key, str) and key.endswith("_team_name")):
|
||||
continue
|
||||
if not _clean(val) or _clean(val) == "休息":
|
||||
continue
|
||||
d = _parse_date(key[:10])
|
||||
if d and (earliest is None or d < earliest):
|
||||
earliest = d
|
||||
if earliest:
|
||||
mapping[code] = earliest
|
||||
return mapping
|
||||
|
||||
|
||||
def load_shift_data(ym: str) -> Tuple[Dict[str, date], Dict[str, str]]:
|
||||
"""预处理:一次拉取检查月全集团排班,产出两个映射(供检查1/2 直接消费,不再各自请求)。
|
||||
|
||||
Returns:
|
||||
(工号 → 检查月最早排班日期, 工号 → 当月出现最多的排班方案名)。
|
||||
失败(登录态失效等)时抛错,由调用方(run 预处理)决定降级策略。
|
||||
"""
|
||||
session = require_session()
|
||||
user_id = require_user_id()
|
||||
total_days = pd.Timestamp(year=int(ym[:4]), month=int(ym[5:7]), day=1).daysinmonth
|
||||
begin = f"{ym}-01"
|
||||
end = f"{ym}-{total_days:02d}"
|
||||
shift_rows = fetch_all_shift(session, user_id, begin, end)
|
||||
return build_earliest_shift_map(shift_rows), build_staff_team_map(shift_rows)
|
||||
|
||||
|
||||
def _shift_main_team(row: dict) -> str:
|
||||
"""统计单条排班记录内逐日 {日期}_team_name 出现最多的方案名(换方案口径:取当月出现最多的)。"""
|
||||
counter: Counter = Counter()
|
||||
for key, val in row.items():
|
||||
if isinstance(key, str) and key.endswith("_team_name"):
|
||||
name = _clean(val)
|
||||
if name and name != "休息":
|
||||
counter[name] += 1
|
||||
if not counter:
|
||||
return ""
|
||||
return counter.most_common(1)[0][0]
|
||||
|
||||
|
||||
def build_staff_team_map(shift_rows: List[dict]) -> Dict[str, str]:
|
||||
"""从全集团排班记录构建 工号 → 当月出现最多的排班方案名 映射(检查2 用)。"""
|
||||
mapping: Dict[str, str] = {}
|
||||
for row in shift_rows:
|
||||
code = _clean(row.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
team = _shift_main_team(row)
|
||||
if team:
|
||||
mapping[code] = team
|
||||
return mapping
|
||||
@@ -0,0 +1,341 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0011 考勤月报封存检查 插件 - 调动台账导出(由 workflows/share/transfer_roster_export_api.py 内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问调动台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(调动已生效 rosterId=10feec75,模板=排班异常识别导出,
|
||||
调动时间范围经 commonQuery 加密传入)-> 接收 "--end--|文件路径" 推送 -> 下载保存。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 调动台账查询/导出接口(浏览器抓包提取) ----------
|
||||
TRANSFER_ROSTER_ID = "10feec75-b094-11ea-b588-14187743d052"
|
||||
TRANSFER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{TRANSFER_ROSTER_ID}/getCustomCommonList.mc"
|
||||
TRANSFER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{TRANSFER_ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
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"
|
||||
|
||||
# 调动台账导出固定入参(浏览器抓包提取)
|
||||
TRANSFER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "调动台账",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_move_info",
|
||||
"rosterId": TRANSFER_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 字段串,「排班异常识别导出」模板,含原/现职位序列、调动时间) ----------
|
||||
TRANSFER_TEMPLATE_FILTERS = {
|
||||
"排班异常识别导出": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_move_info.CHANGE_TYPE", # 调动类型
|
||||
"hr_staff_move_info.PRE_ORG_NAME", # 原所属单位
|
||||
"hr_staff_move_info.PRE_DEPT_NAME", # 原部门
|
||||
"hr_staff_move_info.PRE_PARENT_ORG_NAME", # 原上级部门
|
||||
"hr_staff_move_info_ext.ext_pre_dept_one", # 原一级部门
|
||||
"hr_staff_move_info_ext.ext_pre_dept_five", # 原五级部门
|
||||
"hr_staff_move_info.PRE_POST_NAME", # 原岗位
|
||||
"hr_staff_move_info.pre_first_type_id", # 原职位序列
|
||||
"hr_staff_move_info.NOW_ORG_NAME", # 现所属单位
|
||||
"hr_staff_move_info.DEPT_NAME", # 现部门
|
||||
"hr_staff_move_info.NOW_PARENT_ORG_NAME", # 现上级部门
|
||||
"hr_staff_move_info_ext.ext_now_dept_one", # 现一级部门
|
||||
"hr_staff_move_info_ext.ext_now_dept_five", # 现五级部门
|
||||
"hr_staff_move_info.POST_NAME", # 现岗位
|
||||
"hr_staff_move_info.now_first_type_id", # 现职位序列
|
||||
"pt_structure1.dept_org_four", # 原四级部门
|
||||
"pt_structure.dept_org_four", # 现四级部门
|
||||
"hr_staff_move_info.MOVE_DATE", # 调动时间
|
||||
"hr_staff_move_info.OPERAT_TIME", # 操作时间
|
||||
]),
|
||||
}
|
||||
|
||||
DEFAULT_TEMPLATE = "排班异常识别导出"
|
||||
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_transfer_range(today: date = None, days: int = 30):
|
||||
"""计算调动日期筛选范围,返回 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_move_date_conditions(start, end):
|
||||
"""调动时间区间条件(与页面「更多搜索 -> 调动时间」抓包条件一致)。"""
|
||||
return [
|
||||
build_condition("`hr_staff_move_info.MOVE_DATE`", ">=", start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_move_info.MOVE_DATE`", "<=", end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出 ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问调动台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(TRANSFER_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_once(session, download_dir, template_name, start, end):
|
||||
"""单次异步导出:提交任务 -> 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 TRANSFER_QUERY_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = encode_common_query(_build_move_date_conditions(start, end))
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": TRANSFER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
ts = str(int(time.time() * 1000))
|
||||
params["_t"] = ts
|
||||
params["urlConditions"] = "#".join([
|
||||
f"_t:{ts}", "clickFlag:true", "treePermitType:permit",
|
||||
"useSealTreeData:0", "menuName:调动台账", f"_t:{ts}", ""])
|
||||
|
||||
resp = session.post(TRANSFER_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,模板:%s)", start, end, 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)
|
||||
save_path = os.path.join(download_dir, "调动台账.xlsx")
|
||||
with open(save_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已保存导出文件:%s(%d 字节)", save_path, len(dl.content))
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_transfer_roster(download_dir: str = None, template_name: str = DEFAULT_TEMPLATE,
|
||||
output_path: str = None, start: str = None, end: str = None,
|
||||
session=None) -> str:
|
||||
"""执行调动台账自定义导出(调动已生效,调动时间近30天),返回导出 xlsx 文件路径。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_transfer_roster 一致。
|
||||
"""
|
||||
output_path = os.path.abspath(output_path or "调动台账.xlsx")
|
||||
download_dir = os.path.dirname(output_path)
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("===== 开始调动台账导出(模板:%s,日期:%s ~ %s),保存路径:%s =====",
|
||||
template_name, start, end, output_path)
|
||||
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
sess = _build_session(session)
|
||||
save_path = _export_once(sess, download_dir, template_name, start, end)
|
||||
if os.path.abspath(save_path) != output_path:
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
shutil.move(save_path, output_path)
|
||||
logger.info("===== 调动台账导出完成:%s =====", output_path)
|
||||
return output_path
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("调动台账导出第 %d 次失败:%s,%.1f 秒后重试", attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("调动台账导出连续 %d 次失败,放弃", MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
Reference in New Issue
Block a user