876 lines
40 KiB
Python
876 lines
40 KiB
Python
# -*- 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() 生成(36 位带连字符)、每次导入唯一,接口版用 uuid4();
|
||
- titleList 是字段映射数组 JSON 经「前端 Base64.tranCode.encode」编码的结果:自定义字符表
|
||
Base64 + 固定盐 + 首尾重排(非标准 base64;编码错会让服务端 uploadDataSax 抛空指针、
|
||
任务根本不入队,后续只能查到全 0 的结果);
|
||
- 写库只发生在 uploadData,checkFileType 纯校验(读文件比对表头)。
|
||
"""
|
||
import json
|
||
import os
|
||
import time
|
||
import uuid
|
||
from datetime import datetime, timedelta
|
||
from urllib.parse import quote, unquote
|
||
|
||
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"
|
||
# 失败数据页(注意:这两个不在 /do 下,是导入模块的列表/明细接口)
|
||
IMP_BASE = CONTEXT_PATH + "/hr/module/base/import"
|
||
GET_IMPORT_FAILURE_LIST_URL = BASE_URL + IMP_BASE + "/getImportFailurePageAjax.mc"
|
||
GET_FAIL_PAGE_URL = BASE_URL + IMP_BASE + "/getFailPage.mc"
|
||
|
||
# 「待增减人员」列表(核对本次入库用:导入成功的人会带当天 ext_operate_time 留在列表里)
|
||
PENDING_ROSTER_ID = "7984ae1a-16ec-11ed-bea9-822ff8ed5b28"
|
||
PENDING_LIST_URL = (BASE_URL + CONTEXT_PATH + "/hrRoster/"
|
||
+ PENDING_ROSTER_ID + "/queryRealTimeData.mc")
|
||
GET_CUR_USER_INFO_URL = BASE_URL + CONTEXT_PATH + "/PtUsers.mc?method=getCurUserInfo"
|
||
PENDING_ORG_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28" # 集团节点(页面固定值)
|
||
PENDING_ROLE_IDS = "POST_SYS_ADMIN,renshi" # 与花名册查询口径一致
|
||
PENDING_PAGE_SIZE = 100
|
||
|
||
# 两个导入模板的固定配置 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 条/页
|
||
FAIL_LIST_PAGE_SIZE = 50 # 导入失败批次列表每页条数(同一天可能有多个批次)
|
||
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 基础 ====================
|
||
# HR 会话失效有两种表现:① 页面被重定向到登录页(HTML);② 接口返回 HTTP 200 +
|
||
# JSON {"state":"Nosession","meg":"会话过期,请重新登录!"}。后者不是 HTTP 错误,
|
||
# 不识别就会被当成"导入处理中/无结果"一直轮询到 POLL_TIMEOUT,最终误报"待人工确认"。
|
||
SESSION_EXPIRED_STATES = ("nosession", "no_session", "sessiontimeout", "session_timeout")
|
||
SESSION_EXPIRED_KEYWORDS = ("会话过期", "会话已失效", "重新登录", "登录已超时", "登录超时")
|
||
|
||
|
||
def _raise_if_session_expired(data, desc):
|
||
"""识别「会话失效」类响应并抛 LoginRequiredError(HTTP 200 也会出现,必须按业务字段判定)。"""
|
||
if not isinstance(data, dict):
|
||
return
|
||
state = str(data.get("state") or "").strip()
|
||
meg = str(data.get("meg") or "").strip()
|
||
expired = state.lower() in SESSION_EXPIRED_STATES \
|
||
or any(k in meg for k in SESSION_EXPIRED_KEYWORDS)
|
||
if expired:
|
||
raise LoginRequiredError(
|
||
f"{desc} 提示会话失效(state={state or '-'},meg={meg or '-'}),"
|
||
"HR 登录态已失效,请在插件界面重新登录 HR 后重试。")
|
||
|
||
|
||
def _parse_json(resp, desc):
|
||
"""解析接口响应;登录页 HTML 或会话失效 JSON 均判定为登录态失效。"""
|
||
text = resp.text or ""
|
||
try:
|
||
data = 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]}")
|
||
_raise_if_session_expired(data, desc)
|
||
return data
|
||
|
||
|
||
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}")
|
||
|
||
|
||
# titleList 提交前要用前端 Base64.tranCode.encode 编码:自定义字符表 Base64 + 固定盐 +
|
||
# 首尾重排(与 commonQuery 同源,仅少一步 URI 编码)。用标准 base64 会导致服务端解不出
|
||
# 字段映射(titleList 为 null),uploadDataSax 直接抛 NullPointerException、任务不入队。
|
||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||
_TITLE_SALT = "yyryrtweasdasd"
|
||
|
||
|
||
def _custom_base64_encode(data):
|
||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列,'7' 对应填充位)。"""
|
||
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 = 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 _custom_base64_decode(enc_str):
|
||
"""自定义字符表 Base64 解码('7' 为填充符),与 _custom_base64_encode 互逆。"""
|
||
index = {c: i for i, c in enumerate(_CUSTOM_CHARS)}
|
||
pad = enc_str.count("7")
|
||
enc_str = enc_str.replace("7", "")
|
||
data = bytearray()
|
||
for i in range(0, len(enc_str), 4):
|
||
chunk = enc_str[i:i + 4].ljust(4, "7")
|
||
n = ((index[chunk[0]] << 18) | (index[chunk[1]] << 12)
|
||
| (index[chunk[2]] << 6) | index[chunk[3]])
|
||
data.extend([(n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF])
|
||
if pad:
|
||
data = data[:-pad]
|
||
return bytes(data)
|
||
|
||
|
||
def _b64(value):
|
||
"""等价前端 Base64.tranCode.encode:自定义 Base64 + 盐值 + 首尾重排(titleList 专用)。"""
|
||
raw = str(value).encode("utf-8")
|
||
en_str = _custom_base64_encode(raw) + _TITLE_SALT
|
||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||
|
||
|
||
def _decode_hr_text(value):
|
||
"""解码 HR 接口返回的加密文案(uploadData 的 des / meg),失败返回原文。
|
||
|
||
入参/文件异常时 uploadData 返回 {"state":"0","meg":null,"des":"<加密串>"},
|
||
解密后才是真正的错误(如服务端异常堆栈),不解码只能看到一串乱码。
|
||
"""
|
||
text = str(value or "").strip()
|
||
if len(text) < 8:
|
||
return text
|
||
try:
|
||
en_str = text[:2] + text[5:] + text[2:5]
|
||
if en_str.endswith(_TITLE_SALT):
|
||
en_str = en_str[:-len(_TITLE_SALT)]
|
||
return unquote(_custom_base64_decode(en_str).decode("utf-8", errors="replace"))
|
||
except Exception:
|
||
return text
|
||
|
||
|
||
# ==================== 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)
|
||
except Exception as e:
|
||
logger.warning("导入请求提交异常(结果未知,转轮询判定):%s", e)
|
||
return False
|
||
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
|
||
# 会话失效时上传同样返回 HTTP 200 + state=Nosession(任务并未受理):
|
||
# 这里立即判定登录态,避免"其实没受理"却继续轮询到超时、误报待人工确认
|
||
try:
|
||
payload = resp.json()
|
||
except Exception:
|
||
payload = None
|
||
_raise_if_session_expired(payload, f"{conf.get('title') or ''}导入提交")
|
||
if isinstance(payload, dict) and str(payload.get("state")) != "1":
|
||
# 服务端受理失败(多为入参/文件让它抛异常):des/meg 是加密文案,解码后写日志,
|
||
# 否则后续只会轮询到全 0 结果、报"待人工确认",真正原因看不到
|
||
detail = _decode_hr_text(payload.get("des")) or _decode_hr_text(payload.get("meg"))
|
||
logger.error("导入提交未被受理(state=%s):%s", payload.get("state"),
|
||
detail.replace("\n", " ")[:500] if detail else "-")
|
||
return False
|
||
return True
|
||
|
||
|
||
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 LoginRequiredError:
|
||
raise # 登录态失效必须上报,不能当成"无异常行"吞掉
|
||
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 query_fail_batches(session, import_id, date_begin=None, date_end=None):
|
||
"""查某模板在指定时间段内的导入失败批次(「导入失败记录」列表接口)。
|
||
|
||
业务语义:导入提交后系统自动把校验通过的数据入库、把失败的返回明细;
|
||
只有存在失败数据时才会在此列表里生成批次(全成功的批次不会出现)。
|
||
|
||
Returns:
|
||
list[dict]:{business_id, operator_time, total}(total 为该批次失败条数);无记录返回 []。
|
||
"""
|
||
today = date_begin or time.strftime("%Y-%m-%d")
|
||
data = {
|
||
"root_id": "",
|
||
"excelImpVersion": "2",
|
||
"functionCode": import_id,
|
||
"date_begin": today,
|
||
"date_end": date_end or (today + " 23:59:59"),
|
||
"start": "0",
|
||
"sortType": "",
|
||
"sortName": "",
|
||
"pageNo": "1",
|
||
"pageSize": str(FAIL_LIST_PAGE_SIZE),
|
||
}
|
||
result = _post_json(session, GET_IMPORT_FAILURE_LIST_URL, data,
|
||
"导入失败批次列表", timeout=30)
|
||
if str(result.get("state")) != "1":
|
||
logger.info("导入失败批次列表无结果(state=%s)", result.get("state"))
|
||
return []
|
||
batches = []
|
||
for item in result.get("datas") or []:
|
||
item = item or {}
|
||
bid = str(item.get("businessid") or "").strip()
|
||
if not bid:
|
||
continue
|
||
try:
|
||
total = int(item.get("total") or 0)
|
||
except (TypeError, ValueError):
|
||
total = 0
|
||
batches.append({"business_id": bid,
|
||
"operator_time": str(item.get("operator_time") or ""),
|
||
"total": total})
|
||
return batches
|
||
|
||
|
||
def fetch_fail_page(session, import_id, business_id):
|
||
"""分页拉取某批次的失败明细(官方「失败数据」页接口 getFailPage.mc)。
|
||
|
||
字段口径与 getTmpDataPage 一致(imp_fixed_msg / 工号 / 姓名 / 方案),
|
||
「导入成功」行不计入异常。
|
||
"""
|
||
exceptions = []
|
||
page_no = 1
|
||
page_count = 1
|
||
while page_no <= page_count:
|
||
data = {
|
||
"excelImpVersion": "2",
|
||
"functionCode": import_id,
|
||
"businessId": business_id,
|
||
"start": str((page_no - 1) * PAGE_SIZE),
|
||
"pageNo": str(page_no),
|
||
"pageSize": str(PAGE_SIZE),
|
||
"commonQuery": "[]",
|
||
"sortType": "",
|
||
"sortName": "",
|
||
}
|
||
try:
|
||
result = _post_json(session, GET_FAIL_PAGE_URL, data,
|
||
f"失败数据第 {page_no} 页", timeout=30)
|
||
except LoginRequiredError:
|
||
raise
|
||
except Exception as e:
|
||
logger.warning("失败数据第 %s 页拉取失败:%s", page_no, e)
|
||
break
|
||
if str(result.get("state")) != "1":
|
||
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 or "导入成功" 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 item.get("sicut_o_rel_ext_insurance_name") or ""),
|
||
"message": msg,
|
||
})
|
||
page_no += 1
|
||
return exceptions
|
||
|
||
|
||
# ==================== 8. 入库核对(待增减人员列表 · 操作时间) ====================
|
||
def _date_params():
|
||
"""列表查询需要的动态日期参数(当月/上月/当年首月),与花名册查询口径一致。"""
|
||
now = datetime.now()
|
||
last = now.replace(day=1) - timedelta(days=1)
|
||
return {
|
||
"currentDate": now.strftime("%Y-%m-%d"),
|
||
"currentMonth": now.strftime("%Y%m"),
|
||
"currentMonthBar": now.strftime("%Y-%m"),
|
||
"lastMonth": last.strftime("%Y%m"),
|
||
"lastMonFirstDay": last.strftime("%Y-%m-01"),
|
||
"lastMonLastDay": last.strftime("%Y-%m-%d"),
|
||
"curYearFirstMon": f"{now.year}01",
|
||
"curYearFirstMonBar": f"{now.year}-01",
|
||
}
|
||
|
||
|
||
def _encode_common_query(conditions):
|
||
"""查询条件列表 -> commonQuery(JSON -> URI 编码 -> 自定义 Base64 + 盐 -> 首尾重排)。"""
|
||
json_str = json.dumps(conditions, ensure_ascii=False, separators=(",", ":"))
|
||
en_str = _custom_base64_encode(quote(json_str, safe="-_.~!*'()").encode("utf-8")) + _TITLE_SALT
|
||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||
|
||
|
||
def _current_user_id(session):
|
||
"""取当前登录用户 userId/staffId(列表查询参数用),失败返回空 dict。"""
|
||
try:
|
||
data = _post_json(session, GET_CUR_USER_INFO_URL, {}, "当前用户信息", timeout=30)
|
||
except LoginRequiredError:
|
||
raise
|
||
except Exception as e:
|
||
logger.warning("取当前用户信息失败(沿用内置参数):%s", e)
|
||
return {}
|
||
return data if isinstance(data, dict) else {}
|
||
|
||
|
||
def query_operated_staff(session, started_at, end_at=None, max_pages=80):
|
||
"""查「待增减人员」列表里商业保险操作时间落在 [started_at, end_at] 的人员。
|
||
|
||
业务含义:导入提交后系统自动把成功数据入库,这些人会带着本次的
|
||
si_add_cut_person_sp_cq37du.ext_operate_time 留在列表中;失败的人不会带上本次操作时间。
|
||
据此可与导入文件工号比对,确认"本次到底入库了哪些人"。
|
||
|
||
Args:
|
||
started_at: "YYYY-MM-DD HH:MM:SS"(导入提交前的时间点)
|
||
end_at: 结束时间,默认现在
|
||
|
||
Returns:
|
||
list[dict]:{staff_code, staff_name, scheme, operate_time, add_date, cut_date}
|
||
"""
|
||
end_at = end_at or time.strftime("%Y-%m-%d %H:%M:%S")
|
||
field = "`si_add_cut_person_sp_cq37du.ext_operate_time`"
|
||
conditions = [
|
||
{"queryField": field, "leftBracket": "(", "queryType": ">=", "queryValue": started_at,
|
||
"queryText": started_at, "rightBracket": "", "logic": "AND", "inputType": "date"},
|
||
{"queryField": field, "leftBracket": "", "queryType": "<=", "queryValue": end_at,
|
||
"queryText": end_at, "rightBracket": ")", "logic": "AND", "inputType": "date"},
|
||
]
|
||
info = _current_user_id(session)
|
||
root = info.get("rootId") or "cq37du"
|
||
params = {
|
||
"menuName": "待增减人员",
|
||
"_t": str(int(time.time() * 1000)),
|
||
"in_use": "1",
|
||
"commonQuery": _encode_common_query(conditions),
|
||
"newCondition": "",
|
||
"urlConditions": "",
|
||
"exportConfig": "",
|
||
"tableId": "assemble-hr_staff_base",
|
||
"rosterId": PENDING_ROSTER_ID,
|
||
"includeChildrenSetting": "",
|
||
"struTreeCode": root,
|
||
"djStruTreeCode": "", "djStruId": "", "djOrgName": "",
|
||
"struId": PENDING_ORG_STRU_ID,
|
||
"belongUnitStruId": PENDING_ORG_STRU_ID,
|
||
"rootId": root,
|
||
"isVirtual": "0",
|
||
"currentUserRootId": root,
|
||
"currentUserId": info.get("userId") or "",
|
||
"currentRoleIds": PENDING_ROLE_IDS,
|
||
"currentStaffId": info.get("staffId") or "",
|
||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||
"orgName": "集团", "belongUnitOrgName": "集团",
|
||
"throughParam": "",
|
||
"start": "0", "sortType": "", "sortName": "",
|
||
"pageNo": "1", "pageSize": str(PENDING_PAGE_SIZE),
|
||
}
|
||
params.update(_date_params())
|
||
|
||
rows = []
|
||
page_no = 1
|
||
while page_no <= max_pages:
|
||
params["pageNo"] = str(page_no)
|
||
params["start"] = str((page_no - 1) * PENDING_PAGE_SIZE)
|
||
data = _post_json(session, PENDING_LIST_URL, params,
|
||
f"待增减人员操作记录第 {page_no} 页", timeout=60)
|
||
if str(data.get("state")) != "1":
|
||
logger.info("待增减人员列表无结果(state=%s)", data.get("state"))
|
||
break
|
||
datas = data.get("datas") or []
|
||
for item in datas:
|
||
item = item or {}
|
||
code = str(item.get("a_sp_cq37du.base_code") or "").strip()
|
||
if not code:
|
||
continue
|
||
rows.append({
|
||
"staff_code": code,
|
||
"staff_name": str(item.get("hr_staff_base.staff_name") or ""),
|
||
"scheme": str(item.get("si_add_cut_person_sp_cq37du.ext_insurance_name") or ""),
|
||
"operate_time": str(item.get("si_add_cut_person_sp_cq37du.ext_operate_time") or ""),
|
||
"add_date": str(item.get("si_add_cut_person_sp_cq37du.ext_add_per_date") or ""),
|
||
"cut_date": str(item.get("si_add_cut_person_sp_cq37du.ext_cut_per_date") or ""),
|
||
})
|
||
try:
|
||
page_count = int(data.get("pageCount") or 1)
|
||
except (TypeError, ValueError):
|
||
page_count = 1
|
||
if page_no >= page_count or not datas:
|
||
break
|
||
page_no += 1
|
||
return rows
|
||
|
||
|
||
def _read_import_codes(file_path):
|
||
"""读导入文件里的工号集合(第 4 行起 A 列序号非空视为有效数据行,取 B 列)。"""
|
||
from openpyxl import load_workbook
|
||
codes = set()
|
||
try:
|
||
wb = load_workbook(file_path, read_only=True, data_only=True)
|
||
except Exception as e:
|
||
logger.warning("读取导入文件失败(跳过入库核对):%s", e)
|
||
return codes
|
||
try:
|
||
ws = wb[wb.sheetnames[0]]
|
||
for row in ws.iter_rows(min_row=4, max_col=2, values_only=True):
|
||
if not row:
|
||
continue
|
||
seq, code = (list(row) + [None, None])[:2]
|
||
if seq in (None, "") or code in (None, ""):
|
||
continue
|
||
codes.add(str(code).strip())
|
||
finally:
|
||
wb.close()
|
||
return codes
|
||
|
||
|
||
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 每次唯一)
|
||
# 必须与前端 guid() 同格式(36 位带连字符):HR 的失败记录/ws 消息 key 都按该字符串关联,
|
||
# 用 uuid4().hex(32 位无连字符)会导致服务端任务与查询对不上号
|
||
business_id = str(uuid.uuid4())
|
||
out["business_id"] = business_id
|
||
started_at = time.strftime("%Y-%m-%d %H:%M:%S") # 入库核对的时间起点(提交前)
|
||
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_fail_page(session, conf["id"], business_id)
|
||
if not out["exceptions"]:
|
||
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
|
||
|
||
# 7) 当天失败批次核对:列表里能看到本批次的失败条数(全成功的批次不会出现在这里),
|
||
# 既验证"这批确实被受理并处理过",也能和明细条数互校
|
||
try:
|
||
batches = query_fail_batches(session, conf["id"])
|
||
hit = next((b for b in batches if b["business_id"] == business_id), None)
|
||
out["batch_found"] = bool(hit)
|
||
out["batch_total"] = hit["total"] if hit else 0
|
||
if hit:
|
||
logger.info("%s当天失败批次已确认:%s(操作时间 %s,失败 %s 条)",
|
||
label, business_id, hit["operator_time"], hit["total"])
|
||
if out["exceptions"] and len(out["exceptions"]) != hit["total"]:
|
||
logger.warning("%s失败明细条数(%d)与批次统计(%d)不一致,请人工核对",
|
||
label, len(out["exceptions"]), hit["total"])
|
||
elif out["is_success"]:
|
||
logger.info("%s全部成功,当天失败批次列表无本批次记录(符合预期)", label)
|
||
else:
|
||
logger.warning("%s未在当天失败批次列表中找到本批次(%s),结果请人工核对",
|
||
label, business_id)
|
||
except LoginRequiredError:
|
||
raise
|
||
except Exception as e:
|
||
logger.warning("%s当天失败批次核对失败(不影响主流程):%s", label, e)
|
||
|
||
# 8) 入库核对:本次成功入库的人会带本次操作时间出现在「待增减人员」列表,
|
||
# 用导入文件工号做交集,确认"到底哪些人入库了"(失败的人不会带本次操作时间)
|
||
try:
|
||
codes = _read_import_codes(file_path)
|
||
if codes:
|
||
operated = query_operated_staff(session, started_at)
|
||
op_codes = {o["staff_code"] for o in operated}
|
||
if menu == "sub":
|
||
# 减员成功表现为"人员从待增减列表移除",因此仍在列表的人才是需要核对的;
|
||
# 例外:同一人也在本批增员文件里(换方案替换)→ 增员后会重新出现在列表,属正常
|
||
still = codes & op_codes
|
||
out["operated_count"] = len(codes) - len(still)
|
||
out["operated_missing"] = sorted(still)
|
||
logger.info("%s减员核对:文件 %d 人,已从待增减列表移除 %d 人(操作时间 ≥ %s)",
|
||
label, len(codes), len(codes) - len(still), started_at)
|
||
if still:
|
||
logger.info("%s仍在待增减列表 %d 人(同时在本批增员文件中的属正常替换,余者请核对):%s",
|
||
label, len(still), "、".join(sorted(still)[:20]))
|
||
else:
|
||
# 增员成功表现为"带本次操作时间出现在待增减列表"
|
||
hit = codes & op_codes
|
||
out["operated_count"] = len(hit)
|
||
out["operated_missing"] = sorted(codes - hit)
|
||
logger.info("%s入库核对:文件 %d 人,列表命中 %d 人(操作时间 ≥ %s)",
|
||
label, len(codes), len(hit), started_at)
|
||
if out["operated_missing"]:
|
||
logger.warning("%s未在列表命中 %d 人:%s", label,
|
||
len(out["operated_missing"]),
|
||
"、".join(out["operated_missing"][:20]))
|
||
if out["is_success"] and len(hit) < len(codes):
|
||
logger.warning("%s接口返回全部成功,但列表只命中 %d/%d 人,请人工核对",
|
||
label, len(hit), len(codes))
|
||
except LoginRequiredError:
|
||
raise
|
||
except Exception as e:
|
||
logger.warning("%s入库核对失败(不影响主流程):%s", label, e)
|
||
|
||
out["ok"] = True
|
||
return out
|