274 lines
11 KiB
Python
274 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0065 插件 - HR 花名册 / 合同台账导出(纯接口,异步导出 + WebSocket 收文件)。
|
||
|
||
实现来源:workflows/share/roster_export_api.py(影刀共享指令)的会话绑定 + WS 导出 + 下载逻辑,
|
||
按插件自包含要求 vendored 到本插件内(不 import 插件包外代码),并改为使用底座注入的 session。
|
||
|
||
流程:访问台账页面绑定会话 -> ws/bridge 注册 -> 订阅 HR_DEFINED_HMC_EXPORT ->
|
||
POST exportCommonListData 异步导出(服务端翻译字典字段)-> 收 "--end--|文件路径" ->
|
||
下载临时 Excel -> pandas 读取(第 2 行为表头)-> 删除临时文件。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
import urllib.parse
|
||
from datetime import datetime, timedelta
|
||
|
||
import pandas as pd
|
||
import websocket
|
||
|
||
from ..config import (
|
||
BRIDGE_URL, CONTRACT_EXPORT_FIELDS, CONTRACT_ROSTERS, CONTRACT_TABLE_ID,
|
||
EXPORT_TIMEOUT_SECONDS, HR_BASE_URL, MAX_REQUEST_RETRY, ROSTER_EXPORT_FIELDS,
|
||
ROSTER_ID, ROSTER_QUERY_BASE_PARAMS, ROSTER_TABLE_ID, USER_AGENT, WS_EXPORT_THEME,
|
||
WS_SERVICE_URL, XHR_HEADERS, logger,
|
||
)
|
||
|
||
# ==================== commonQuery 前端加密(与前端行为一致,已实测接口可用) ====================
|
||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||
_PAD_CHAR = "7"
|
||
_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 字符串。"""
|
||
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]
|
||
|
||
|
||
def _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 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",
|
||
}
|
||
|
||
|
||
class LoginRequiredError(Exception):
|
||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容 / bridge 注册失败)。"""
|
||
|
||
|
||
LOGIN_EXPIRED_MSG = "HR 登录态已过期,请先在壳子(工作台)重新登录 HR 平台后重试"
|
||
|
||
|
||
def _bind_session(session):
|
||
"""绑定会话:先访问台账页面,再调用 ws/bridge 把 HTTP 会话注册到 WS 容器。"""
|
||
page_url = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||
session.get(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"{LOGIN_EXPIRED_MSG}(ws/bridge 注册失败:{r.text[:100]})")
|
||
|
||
|
||
def _export_once(session, roster_id, table_id, export_name, export_fields,
|
||
download_dir, common_query=""):
|
||
"""单次异步导出:提交任务 -> WS 等 --end-- -> 下载临时 Excel,返回文件路径。
|
||
|
||
Raises:
|
||
LoginRequiredError: 登录态失效
|
||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||
"""
|
||
_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}",
|
||
f"Origin: {HR_BASE_URL}",
|
||
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]}")
|
||
|
||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||
params.update({
|
||
"rosterId": roster_id,
|
||
"tableId": table_id,
|
||
"commonQuery": common_query,
|
||
})
|
||
params.update(get_date_params())
|
||
params["exportConfig"] = json.dumps(
|
||
{"exportName": export_name, "exportFilters": ",".join(export_fields)},
|
||
ensure_ascii=False, separators=(",", ":"))
|
||
params["_t"] = str(int(time.time() * 1000))
|
||
|
||
url = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{roster_id}/exportCommonListData.mc"
|
||
resp = session.post(url, data=params, headers=XHR_HEADERS, timeout=30)
|
||
if resp.status_code != 200:
|
||
raise RuntimeError(f"提交导出任务失败({export_name}):HTTP {resp.status_code}")
|
||
text = (resp.text or "").lstrip()
|
||
if text and not text.startswith(("{", "[")):
|
||
raise LoginRequiredError(f"{LOGIN_EXPIRED_MSG}({export_name}:{text[:100]})")
|
||
logger.info("导出任务已提交:%s", export_name)
|
||
|
||
file_url = None
|
||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||
while time.time() < deadline:
|
||
msg = json.loads(ws.recv())
|
||
if msg.get("code") != "NORMAL_PUSH_TO":
|
||
continue
|
||
txt = msg.get("txt", "")
|
||
if txt.startswith("--end--"):
|
||
file_url = txt.split("|", 1)[1].strip()
|
||
break
|
||
finally:
|
||
ws.close()
|
||
|
||
if not file_url:
|
||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s):{export_name}")
|
||
dl_url = HR_BASE_URL + 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"下载导出文件失败({export_name}):HTTP {dl.status_code}")
|
||
os.makedirs(download_dir, exist_ok=True)
|
||
safe_name = export_name.replace("/", "_").replace("\\", "_")
|
||
temp_path = os.path.join(download_dir, f"{safe_name}_{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_with_retry(session, roster_id, table_id, export_name, export_fields,
|
||
download_dir, common_query=""):
|
||
"""项目级重试:最多 3 次,登录态失效不重试。"""
|
||
last_err = None
|
||
for attempt in range(1, MAX_REQUEST_RETRY + 1):
|
||
try:
|
||
return _export_once(session, roster_id, table_id, export_name,
|
||
export_fields, download_dir, common_query)
|
||
except LoginRequiredError:
|
||
raise
|
||
except Exception as e:
|
||
last_err = e
|
||
if attempt >= MAX_REQUEST_RETRY:
|
||
break
|
||
delay = 2.0 * attempt
|
||
logger.warning("「%s」第 %d 次导出失败:%s,%.0f 秒后重试",
|
||
export_name, attempt, e, delay)
|
||
time.sleep(delay)
|
||
raise RuntimeError(f"「{export_name}」连续 {MAX_REQUEST_RETRY} 次导出失败:{last_err}")
|
||
|
||
|
||
def _read_export(path, tag):
|
||
"""读取服务端导出的 Excel(第 1 行是标题,第 2 行才是表头),删除序号列。"""
|
||
df = pd.read_excel(path, header=1)
|
||
df = df.drop(columns=["序号"], errors="ignore")
|
||
logger.info("读取%s:%d 行 × %d 列", tag, len(df), len(df.columns))
|
||
return df
|
||
|
||
|
||
def export_roster(session, download_dir):
|
||
"""导出在职花名册(全字段),返回 DataFrame。"""
|
||
common_query = encode_common_query(_in_service_conditions())
|
||
path = _export_with_retry(session, ROSTER_ID, ROSTER_TABLE_ID, "XQ0065在职花名册",
|
||
ROSTER_EXPORT_FIELDS, download_dir, common_query)
|
||
try:
|
||
return _read_export(path, "在职花名册")
|
||
finally:
|
||
_remove_quietly(path)
|
||
|
||
|
||
def export_contracts(session, download_dir):
|
||
"""导出合同台账(生效中 + 待生效)并合并,追加「合同状态」列,返回 DataFrame。"""
|
||
frames = []
|
||
for tag, roster_id in CONTRACT_ROSTERS:
|
||
path = _export_with_retry(session, roster_id, CONTRACT_TABLE_ID,
|
||
f"XQ0065合同台账{tag}", CONTRACT_EXPORT_FIELDS, download_dir)
|
||
try:
|
||
df = _read_export(path, f"合同台账({tag})")
|
||
finally:
|
||
_remove_quietly(path)
|
||
df["合同状态"] = tag
|
||
frames.append(df)
|
||
merged = pd.concat(frames, ignore_index=True)
|
||
logger.info("合同台账合并完成:%d 条(生效中 %d / 待生效 %d)", len(merged),
|
||
(merged["合同状态"] == "生效中").sum(), (merged["合同状态"] == "待生效").sum())
|
||
return merged
|
||
|
||
|
||
def precheck(session):
|
||
"""登录态预检:bridge 注册一次,失效直接抛错,避免导出到一半才发现。"""
|
||
try:
|
||
_bind_session(session)
|
||
except LoginRequiredError:
|
||
raise RuntimeError(LOGIN_EXPIRED_MSG)
|
||
logger.info("HR 登录态校验通过")
|
||
|
||
|
||
def _remove_quietly(path):
|
||
try:
|
||
os.remove(path)
|
||
except OSError:
|
||
pass
|