feat: 新增EHR系统花名册检查插件及多个插件版本更新

This commit is contained in:
2026-10-30 16:38:18 +08:00
parent 210de5b68b
commit 62de24eb4d
93 changed files with 9195 additions and 2277 deletions
@@ -0,0 +1,447 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 - HR「待增减人员」增/减员导入(纯接口版,无浏览器)。
逆向来源(2026-10-30,全程只 GET 页面与前端 JS,未做任何写入探测):
待增减人员列表页按钮配置 + /RedseaPlatform/jsp/hr/custommodule/dataimport/js/
hr_module_base_import_do.js
链路(与前端 checkFileType / submit 完全一致,全为 multipart/form-data):
1. GET hr/module/base/import/do/<importId>/toImpPage.mc 取弹窗配置 hrModuleBaseImport
(importId、fieldJson 表头映射模板、maxNum 等)
2. POST .../checkFileType.mc 文件格式校验,返回 Excel 实际表头
(result[].excelColName / excelColNum),不写库
3. 同名匹配 columnDisplay == excelColName 回填 excelColNum(前端 setDefaultMatchTitle)
4. POST .../uploadData.mc 真正导入(异步,服务端后台跑,响应无业务结果)
5. POST .../getImportResult.mc 轮询取结果(前端靠 WebSocket 主题 EXCEL_COMMON_IMPORT
的 done 消息触发,接口版改为轮询,等价且不依赖 ws)
6. POST .../getTmpDataPage.mc 失败明细分页(固定 15 条/页)
关键事实(决定了不需要抓包、也没有一次性 token 门槛):
- importId 是导入模板的固定配置 id,写死在弹窗页 hidden input 中;
- businessId 由前端 guid() 生成、每次导入唯一,接口版自行 uuid4();
- titleList 是字段映射数组 JSON 的 base64,无签名;
- 写库只发生在 uploadData,checkFileType 纯校验(读文件比对表头)。
"""
import base64
import json
import os
import time
import uuid
from urllib.parse import quote
import requests
from ..config import logger, SESSIONS_DIR, get_session
# ==================== 常量 ====================
BASE_URL = "https://hr.37du.co"
CONTEXT_PATH = "/RedseaPlatform"
IMP_DO = CONTEXT_PATH + "/hr/module/base/import/do"
TO_IMP_PAGE_URL = IMP_DO + "/{import_id}/toImpPage.mc?pageType=1&importTitle={title}&struTreeCode="
CHECK_FILE_TYPE_URL = BASE_URL + IMP_DO + "/checkFileType.mc"
UPLOAD_DATA_URL = BASE_URL + IMP_DO + "/uploadData.mc"
GET_IMPORT_RESULT_URL = BASE_URL + IMP_DO + "/getImportResult.mc"
GET_TMP_DATA_PAGE_URL = BASE_URL + IMP_DO + "/getTmpDataPage.mc"
# 两个导入模板的固定配置 id(取自「待增减人员」页按钮配置,勿改)
IMPORT_MENUS = {
"add": {"import_id": "12eecb13-78b0-4fac-a865-10c3043a33e1",
"title": "商业保险增员导入", "label": "增员导入"},
"sub": {"import_id": "22e180f9-476b-412d-b68b-bbed8393dba6",
"title": "商业保险减员导入", "label": "减员导入"},
}
# 弹窗默认行号(页面 select 默认值:列标题行号=2、内容开始行号=4)
TITLE_ROW_NUM = "2"
CONTENT_ROW_NUM = "4"
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
RETRY_TIMES = 3 # 只读接口重试次数(项目级规范)
RETRY_INTERVAL = 1.0
PAGE_SIZE = 15 # getTmpDataPage 固定 15 条/页
POLL_TIMEOUT_SECONDS = 300 # 导入结果轮询上限(与前端"排队等候"提示口径一致)
POLL_INTERVAL_SECONDS = 2.0
# 弹窗配置缓存(importId -> hrModuleBaseImport dict,进程内复用)
_CONF_CACHE = {}
class LoginRequiredError(Exception):
"""HR 登录态缺失/失效(页面被重定向到登录页或 cookies 为空)。"""
# ==================== 会话 ====================
def _session_from_cookie_file():
"""兜底:用共享 cookies 文件构建 requests.Session(底座未注入会话时)。"""
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
return None
try:
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
cookies = json.load(f) or []
except Exception as e:
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
return None
s = requests.Session()
s.headers.update({"User-Agent": USER_AGENT})
for c in cookies:
if c.get("domain") and "37du.co" in str(c["domain"]):
try:
s.cookies.set(c["name"], c["value"], domain=c["domain"],
path=c.get("path", "/"))
except Exception:
continue
return s
def build_session():
"""取可用 HR 会话:底座注入 session 优先,缺失时兜底共享 cookies 文件。"""
session = get_session()
if session is not None:
return session
session = _session_from_cookie_file()
if session is None:
raise LoginRequiredError(
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
"请先在插件界面完成 HR 登录后再执行导入。")
return session
# ==================== HTTP 基础 ====================
def _parse_json(resp, desc):
"""解析接口响应;返回登录页等非 JSON 内容时判定登录态失效。"""
text = resp.text or ""
try:
return resp.json()
except Exception:
if "j_username" in text or "login" in text.lower()[:2000]:
raise LoginRequiredError(
f"{desc} 返回登录页,HR 登录态已失效,请在插件界面重新登录 HR。")
raise RuntimeError(f"{desc} 响应非 JSON(HTTP {resp.status_code}):{text[:200]}")
def _multipart_post(session, url, data, file_path=None, timeout=120):
"""以 multipart/form-data 提交(上传文件)。
底座注入的共享 session 默认带 Content-Type: application/x-www-form-urlencoded,
会让 requests 不再自动生成 multipart 边界头而被服务端拒绝;上传前临时清除、随后恢复
(同 XQ0008 oa_push.py 的处理)。
"""
saved_ct = session.headers.pop("Content-Type", None)
headers = {"X-Requested-With": "XMLHttpRequest", "Referer": BASE_URL + CONTEXT_PATH + "/"}
fh = None
try:
files = None
if file_path:
if not os.path.isfile(file_path):
raise FileNotFoundError(f"导入文件不存在:{file_path}")
fh = open(file_path, "rb")
files = {"file": (os.path.basename(file_path), fh, XLSX_MIME)}
return session.post(url, data=data, files=files, headers=headers, timeout=timeout)
finally:
if fh is not None:
fh.close()
if saved_ct is not None:
session.headers["Content-Type"] = saved_ct
def _get_text(session, url, desc, timeout=30):
"""GET 文本(只读,带重试)。"""
last = None
for attempt in range(RETRY_TIMES):
try:
resp = session.get(url, timeout=timeout,
headers={"X-Requested-With": "XMLHttpRequest"})
text = resp.content.decode("utf-8", "ignore")
if "j_username" in text[:5000] and "RedSea" not in text[:2000]:
raise LoginRequiredError(
f"{desc} 被重定向到登录页,HR 登录态已失效,请重新登录 HR。")
return text
except LoginRequiredError:
raise
except Exception as e:
last = e
logger.warning("%s 第 %s/%s 次失败:%s", desc, attempt + 1, RETRY_TIMES, e)
time.sleep(RETRY_INTERVAL)
raise RuntimeError(f"{desc} 请求失败(已重试 {RETRY_TIMES} 次):{last}")
def _post_json(session, url, data, desc, file_path=None, timeout=120):
"""POST 并解析 JSON(只读接口使用,带重试)。写接口请勿用本函数。"""
last = None
for attempt in range(RETRY_TIMES):
try:
resp = _multipart_post(session, url, data, file_path=file_path, timeout=timeout)
return _parse_json(resp, desc)
except LoginRequiredError:
raise
except Exception as e:
last = e
logger.warning("%s 第 %s/%s 次失败:%s", desc, attempt + 1, RETRY_TIMES, e)
time.sleep(RETRY_INTERVAL)
raise RuntimeError(f"{desc} 请求失败(已重试 {RETRY_TIMES} 次):{last}")
def _b64(value):
"""与前端 Base64.tranCode.encode 等价(标准 base64,UTF-8)。"""
return base64.b64encode(str(value).encode("utf-8")).decode("ascii")
# ==================== 1. 弹窗配置 ====================
def load_import_conf(session, menu):
"""取导入模板配置 hrModuleBaseImport(含 importId、fieldJson 表头映射模板)。"""
info = IMPORT_MENUS[menu]
if menu in _CONF_CACHE:
return _CONF_CACHE[menu]
url = BASE_URL + TO_IMP_PAGE_URL.format(
import_id=info["import_id"],
title=quote(info["title"], safe=""),
)
html = _get_text(session, url, f"{info['label']}弹窗页")
idx = html.find("var hrModuleBaseImport =")
if idx < 0:
raise RuntimeError(f"{info['label']}弹窗页未找到模板配置 hrModuleBaseImport(页面结构可能变化)")
start = html.find("{", idx)
try:
conf, _ = json.JSONDecoder().raw_decode(html[start:])
except Exception as e:
raise RuntimeError(f"{info['label']}弹窗页模板配置解析失败:{e}")
if str(conf.get("id") or "") != info["import_id"]:
logger.warning("%s弹窗页 importId=%s 与预期 %s 不一致(沿用页面返回值)",
info["label"], conf.get("id"), info["import_id"])
logger.info("%s模板:%s(最多 %s 行)", info["label"],
conf.get("title") or info["title"], conf.get("maxNum") or "-")
_CONF_CACHE[menu] = conf
return conf
def _field_list(conf):
"""解析 fieldJson 为表头映射数组(columnName 模板字段名 / columnDisplay 中文名)。"""
raw = conf.get("fieldJson") or "[]"
try:
data = json.loads(raw.replace("\n", "\\n").replace("\r", "\\r"))
except Exception:
data = json.loads(raw)
return data if isinstance(data, list) else []
def match_titles(field_list, excel_titles):
"""前端 setDefaultMatchTitle 等价实现:同名列 -> 回填 excelColNum。
Returns:
(title_list, matched):回填后的字段数组与成功匹配的列数。
"""
by_name = {}
for t in excel_titles or []:
if not isinstance(t, dict):
continue
name = str(t.get("excelColName") or "").strip()
if name:
by_name[name] = t.get("excelColNum")
title_list = [dict(f) for f in field_list if isinstance(f, dict)]
matched = 0
for f in title_list:
disp = str(f.get("columnDisplay") or "").strip()
if disp in by_name and by_name[disp] is not None:
f["excelColNum"] = by_name[disp]
matched += 1
return title_list, matched
# ==================== 2~5. 校验 / 导入 / 结果 ====================
def _form_base(conf, title_list):
"""构造弹窗表单公共字段(与前端 FormData 一致)。"""
return {
"importId": conf["id"],
"titleRowNum": TITLE_ROW_NUM,
"contentRowNum": CONTENT_ROW_NUM,
"titleList": _b64(json.dumps(title_list, ensure_ascii=False,
separators=(",", ":"))),
"name": "test", # 前端为兼容 IE 固定附加,照传
}
def check_file_type(session, conf, file_path, field_list):
"""第 1 步「下一步」:文件格式校验(不写库)。返回 Excel 实际表头列表。"""
data = _form_base(conf, field_list)
result = _post_json(session, CHECK_FILE_TYPE_URL, data, "文件格式校验",
file_path=file_path, timeout=180)
if str(result.get("state")) != "1":
raise RuntimeError(f"文件格式校验失败:{result.get('meg') or '未知原因'}")
titles = result.get("result") or []
logger.info("文件格式校验通过,Excel 表头 %d 列", len(titles) if isinstance(titles, list) else 0)
return titles
def submit_upload(session, conf, file_path, title_list, business_id):
"""第 2 步「下一步」:真正导入(异步,服务端后台执行)。
本步骤是唯一写库动作,**不做请求重试**:重试可能造成重复导入。
请求异常时结果未知,交由 get_import_result 轮询判定(服务端若已受理仍可查到结果)。
"""
data = _form_base(conf, title_list)
data["businessId"] = business_id
try:
resp = _multipart_post(session, UPLOAD_DATA_URL, data, file_path=file_path, timeout=180)
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
return True
except Exception as e:
logger.warning("导入请求提交异常(结果未知,转轮询判定):%s", e)
return False
def get_import_result(session, import_id, business_id):
"""轮询导入结果(替代前端 WebSocket 的 done 回调)。
Returns:
dict:{isSuccess, success, checkFail, saveFail, other, ...};超时返回 None。
"""
deadline = time.time() + POLL_TIMEOUT_SECONDS
waited = 0
while time.time() < deadline:
try:
resp = _multipart_post(session, GET_IMPORT_RESULT_URL,
{"importId": import_id, "businessId": business_id},
timeout=30)
data = _parse_json(resp, "导入结果查询")
state = str(data.get("state") or "").strip()
res = data.get("result")
if state == "1" and isinstance(res, dict) and (
"isSuccess" in res or "success" in res):
return res
meg = str(data.get("meg") or "").strip()
if meg:
waited += POLL_INTERVAL_SECONDS
if waited % 30 == 0:
logger.info("导入处理中:%s(已等待 %ss)", meg, waited)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("导入结果查询失败(继续轮询):%s", e)
time.sleep(POLL_INTERVAL_SECONDS)
return None
def fetch_exceptions(session, import_id, business_id):
"""分页拉取失败明细(getTmpDataPage.mc,15 条/页),返回异常行列表。"""
exceptions = []
page_no = 1
page_count = 1
while page_no <= page_count:
data = {
"importId": import_id,
"imp_fixed_businessid": business_id,
"start": str((page_no - 1) * PAGE_SIZE),
"pageNo": str(page_no),
"pageSize": str(PAGE_SIZE),
"sortType": "",
"sortName": "",
}
try:
result = _post_json(session, GET_TMP_DATA_PAGE_URL, data,
f"导入明细第 {page_no} 页", timeout=30)
except Exception as e:
logger.warning("导入明细第 %s 页拉取失败:%s", page_no, e)
break
if str(result.get("state")) != "1":
if page_no == 1:
logger.info("导入明细接口无结果(state=%s,多为全部成功)", result.get("state"))
break
try:
page_count = max(1, int(result.get("pageCount") or 1))
except (TypeError, ValueError):
page_count = 1
for item in result.get("datas") or []:
item = item or {}
msg = str(item.get("imp_fixed_msg", "") or "").strip()
if not msg:
continue
# 成功行返回「导入成功;」固定文案,不纳入异常
if "导入成功" in msg:
continue
exceptions.append({
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
"message": msg,
})
page_no += 1
return exceptions
def import_one_file(session, menu, file_path):
"""对单个导入文件执行完整接口导入(校验 -> 导入 -> 结果 -> 明细)。
Args:
session: HR 会话(build_session() 返回)
menu: "add"(增员)/ "sub"(减员)
file_path: 导入文件路径
Returns:
dict:{menu, ok, stage, state, meg, is_success, success, check_fail,
save_fail, other, exceptions, business_id, assumed_all_success}
stage 表示失败发生的环节:conf/check/upload/result/''(成功)
"""
info = IMPORT_MENUS[menu]
label = info["label"]
out = {"menu": menu, "ok": False, "stage": "", "state": "", "meg": "",
"is_success": False, "success": 0, "check_fail": 0, "save_fail": 0,
"other": 0, "exceptions": [], "business_id": "",
"assumed_all_success": False}
# 1) 模板配置 + 表头映射模板
try:
conf = load_import_conf(session, menu)
field_list = _field_list(conf)
except Exception as e:
out.update(stage="conf", meg=str(e))
return out
# 2) 格式校验(读文件比对表头,不写库)
try:
excel_titles = check_file_type(session, conf, file_path, field_list)
except Exception as e:
out.update(stage="check", meg=str(e))
return out
# 3) 表头同名匹配(前端 setDefaultMatchTitle)
title_list, matched = match_titles(field_list, excel_titles)
if matched <= 0:
out.update(stage="check",
meg=f"导入文件表头与「{conf.get('title') or info['title']}」模板不匹配(0 列匹配)")
return out
logger.info("%s表头匹配 %d/%d 列", label, matched, len(title_list))
# 4) 提交导入(唯一写操作,businessId 每次唯一)
business_id = uuid.uuid4().hex
out["business_id"] = business_id
submit_upload(session, conf, file_path, title_list, business_id)
# 5) 轮询结果
result = get_import_result(session, conf["id"], business_id)
if result is None:
out.update(stage="result",
meg=f"导入结果轮询超时({POLL_TIMEOUT_SECONDS}s),结果待人工确认")
return out
def _int(key):
try:
return int(result.get(key) or 0)
except (TypeError, ValueError):
return 0
out["is_success"] = str(result.get("isSuccess")) == "1"
out["success"] = _int("success")
out["check_fail"] = _int("checkFail")
out["save_fail"] = _int("saveFail")
out["other"] = _int("other")
out["meg"] = str(result.get("meg") or "")
# 6) 失败明细
if not out["is_success"]:
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
out["ok"] = True
return out