- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
589 lines
25 KiB
Python
589 lines
25 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""增员 / 减员导入(HR「待增减人员 → 更多操作 → 增减员导入」的纯接口实现)。
|
||
|
||
**写操作**,默认 ``dry_run=True``:只做「取模板配置 + 文件格式校验 + 表头匹配」,
|
||
不提交、不写库。必须显式 ``apply=True`` 才真正导入。
|
||
|
||
链路(与前端弹窗一致,全为 multipart):
|
||
|
||
1. ``GET /hr/module/base/import/do/<importId>/toImpPage.mc`` 取模板配置(fieldJson 表头映射)
|
||
2. ``POST .../checkFileType.mc`` 文件格式校验(只读,返回 Excel 实际表头)
|
||
3. 同名列回填 ``excelColNum``(等价前端 ``setDefaultMatchTitle``)
|
||
4. ``POST .../uploadData.mc`` **唯一写库动作**(异步;不重试,防重复导入)
|
||
5. ``POST .../getImportResult.mc`` 轮询结果(前端用 WebSocket,这里轮询等价)
|
||
6. ``POST .../getFailPage.mc`` / ``getTmpDataPage.mc`` 失败明细分页
|
||
7. ``getImportFailurePageAjax.mc`` 当天失败批次核对
|
||
|
||
入库核对(哪些人真的入库了)由插件事后调 :func:`operated_staff` 拿数据自行判定。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import time
|
||
import uuid
|
||
from datetime import datetime, timedelta
|
||
from typing import Dict, List, Optional
|
||
from urllib.parse import quote
|
||
|
||
from .config import REDSEA, base_params
|
||
from .errors import ApiError, ConfigError, SessionExpiredError
|
||
from .query import encode, encode_raw
|
||
|
||
CONTEXT_PATH = "/RedseaPlatform"
|
||
#: 注意:REDSEA 已含 ``/RedseaPlatform``,这里只放其后的路径段
|
||
IMP_DO = "/hr/module/base/import/do"
|
||
TO_IMP_PAGE_URL = (f"{REDSEA}{IMP_DO}/"
|
||
"{import_id}/toImpPage.mc?pageType=1&importTitle={title}&struTreeCode=")
|
||
CHECK_FILE_TYPE_URL = f"{REDSEA}{IMP_DO}/checkFileType.mc"
|
||
UPLOAD_DATA_URL = f"{REDSEA}{IMP_DO}/uploadData.mc"
|
||
GET_IMPORT_RESULT_URL = f"{REDSEA}{IMP_DO}/getImportResult.mc"
|
||
GET_TMP_DATA_PAGE_URL = f"{REDSEA}{IMP_DO}/getTmpDataPage.mc"
|
||
IMP_BASE = "/hr/module/base/import"
|
||
GET_IMPORT_FAILURE_LIST_URL = f"{REDSEA}{IMP_BASE}/getImportFailurePageAjax.mc"
|
||
GET_FAIL_PAGE_URL = f"{REDSEA}{IMP_BASE}/getFailPage.mc"
|
||
|
||
#: 「待增减人员」台账(入库核对用;成功导入的人会带本次 ext_operate_time 留在列表)
|
||
PENDING_ROSTER_ID = "7984ae1a-16ec-11ed-bea9-822ff8ed5b28"
|
||
PENDING_LIST_URL = f"{REDSEA}/hrRoster/{PENDING_ROSTER_ID}/queryRealTimeData.mc"
|
||
PENDING_TABLE_ID = "assemble-hr_staff_base"
|
||
PENDING_ORG_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||
PENDING_ROLE_IDS = "POST_SYS_ADMIN,renshi"
|
||
PENDING_PAGE_SIZE = 100
|
||
PENDING_OPERATE_FIELD = "`si_add_cut_person_sp_cq37du.ext_operate_time`"
|
||
|
||
#: 两个导入模板的固定配置 id(取自「待增减人员」页按钮配置,勿改)
|
||
IMPORT_MENUS = {
|
||
"add": {"import_id": "12eecb13-78b0-4fac-a865-10c3043a33e1",
|
||
"title": "商业保险增员导入", "label": "增员导入"},
|
||
"sub": {"import_id": "22e180f9-476b-412d-b68b-bbed8393dba6",
|
||
"title": "商业保险减员导入", "label": "减员导入"},
|
||
}
|
||
|
||
#: 弹窗默认行号(列标题行 / 内容起始行)
|
||
TITLE_ROW_NUM = "2"
|
||
CONTENT_ROW_NUM = "4"
|
||
|
||
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||
TMP_PAGE_SIZE = 15 # getTmpDataPage/getFailPage 固定 15 条/页
|
||
FAIL_LIST_PAGE_SIZE = 50 # 失败批次列表每页条数
|
||
POLL_TIMEOUT_SECONDS = 300 # 导入结果轮询上限
|
||
POLL_INTERVAL_SECONDS = 2.0
|
||
|
||
_CONF_CACHE: Dict[str, dict] = {}
|
||
|
||
|
||
# ==================== 模板配置 ====================
|
||
|
||
def menu_info(menu: str) -> dict:
|
||
"""取导入菜单信息(``add`` / ``sub``)。"""
|
||
key = str(menu or "").strip().lower()
|
||
if key not in IMPORT_MENUS:
|
||
raise ConfigError(f"未知导入类型「{menu}」,可选:{' / '.join(IMPORT_MENUS)}")
|
||
return IMPORT_MENUS[key]
|
||
|
||
|
||
def load_conf(client, menu: str) -> dict:
|
||
"""取导入模板配置 ``hrModuleBaseImport``(含 importId / fieldJson / maxNum)。"""
|
||
menu_info(menu) # 校验 menu 合法
|
||
key = str(menu).strip().lower()
|
||
if key in _CONF_CACHE:
|
||
return _CONF_CACHE[key]
|
||
|
||
info = IMPORT_MENUS[key]
|
||
url = TO_IMP_PAGE_URL.format(import_id=info["import_id"],
|
||
title=quote(info["title"], safe=""))
|
||
resp = client.get(url, headers={"X-Requested-With": "XMLHttpRequest"}, timeout=30)
|
||
html = (resp.content or b"").decode("utf-8", "ignore")
|
||
if "j_username" in html[:5000] and "RedSea" not in html[:2000]:
|
||
raise SessionExpiredError(f"{info['label']}弹窗页被重定向到登录页(HR 登录态失效)")
|
||
|
||
idx = html.find("var hrModuleBaseImport =")
|
||
if idx < 0:
|
||
raise ApiError(f"{info['label']}弹窗页未找到模板配置(页面结构可能已变化)")
|
||
start = html.find("{", idx)
|
||
try:
|
||
conf, _ = json.JSONDecoder().raw_decode(html[start:])
|
||
except ValueError as exc:
|
||
raise ApiError(f"{info['label']}模板配置解析失败:{exc}") from None
|
||
if str(conf.get("id") or "") != info["import_id"]:
|
||
client.log(f"[WARN] {info['label']}页面 importId={conf.get('id')} 与预期不一致(沿用页面值)")
|
||
client.log(f"[INFO] {info['label']}模板:{conf.get('title') or info['title']}"
|
||
f"(最多 {conf.get('maxNum') or '-'} 行)")
|
||
_CONF_CACHE[key] = conf
|
||
return conf
|
||
|
||
|
||
def field_list(conf: dict) -> List[dict]:
|
||
"""解析 ``fieldJson`` → 表头映射数组(``columnName``/``columnDisplay``)。"""
|
||
raw = conf.get("fieldJson") or "[]"
|
||
try:
|
||
data = json.loads(str(raw).replace("\n", "\\n").replace("\r", "\\r"))
|
||
except ValueError:
|
||
try:
|
||
data = json.loads(raw)
|
||
except ValueError:
|
||
return []
|
||
return data if isinstance(data, list) else []
|
||
|
||
|
||
def match_titles(fields: List[dict], excel_titles: List[dict]):
|
||
"""同名列回填 ``excelColNum``(等价前端 ``setDefaultMatchTitle``)。
|
||
|
||
Returns:
|
||
``(title_list, matched)``:回填后的字段数组与匹配列数。
|
||
"""
|
||
by_name = {}
|
||
for item in excel_titles or []:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
name = str(item.get("excelColName") or "").strip()
|
||
if name:
|
||
by_name[name] = item.get("excelColNum")
|
||
title_list = [dict(f) for f in fields if isinstance(f, dict)]
|
||
matched = 0
|
||
for field in title_list:
|
||
display = str(field.get("columnDisplay") or "").strip()
|
||
if display in by_name and by_name[display] is not None:
|
||
field["excelColNum"] = by_name[display]
|
||
matched += 1
|
||
return title_list, matched
|
||
|
||
|
||
def _form_base(conf: dict, title_list: List[dict]) -> dict:
|
||
"""弹窗表单公共字段(与前端 FormData 一致)。"""
|
||
return {
|
||
"importId": conf["id"],
|
||
"titleRowNum": TITLE_ROW_NUM,
|
||
"contentRowNum": CONTENT_ROW_NUM,
|
||
"titleList": encode_raw(json.dumps(title_list, ensure_ascii=False,
|
||
separators=(",", ":"))),
|
||
"name": "test", # 前端为兼容 IE 固定附加,照传
|
||
}
|
||
|
||
|
||
# ==================== 校验(只读) ====================
|
||
|
||
def check_file(client, file_path: str, menu: str = "add", *,
|
||
conf: Optional[dict] = None) -> dict:
|
||
"""文件格式校验(**不写库**),返回 ``{conf, fields, title_list, matched, excel_titles}``。"""
|
||
_require_file(file_path)
|
||
menu_info(menu)
|
||
conf = conf or load_conf(client, menu)
|
||
fields = field_list(conf)
|
||
|
||
resp = client.post_files(
|
||
CHECK_FILE_TYPE_URL,
|
||
files={"file": (os.path.basename(file_path), _read_bytes(file_path), XLSX_MIME)},
|
||
data=_form_base(conf, fields), timeout=180)
|
||
data = client.as_json(resp, "文件格式校验")
|
||
client.check_state(data, "文件格式校验")
|
||
|
||
titles = data.get("result") or []
|
||
title_list, matched = match_titles(fields, titles)
|
||
client.log(f"[INFO] 表头校验通过:Excel {len(titles)} 列,"
|
||
f"匹配模板 {matched}/{len(fields)} 列")
|
||
return {"conf": conf, "fields": fields, "title_list": title_list,
|
||
"matched": matched, "excel_titles": titles}
|
||
|
||
|
||
# ==================== 导入(写) ====================
|
||
|
||
def upload(client, file_path: str, menu: str = "add", *, apply: bool = False,
|
||
poll_timeout: int = POLL_TIMEOUT_SECONDS,
|
||
fetch_exceptions: bool = True) -> dict:
|
||
"""校验(+ 可选)提交导入并回收结果。
|
||
|
||
Args:
|
||
client: :class:`hr_sdk.client.HrClient`
|
||
file_path: 导入 Excel(模板:列标题行=2、内容起始行=4)
|
||
menu: ``add``(增员)/ ``sub``(减员)
|
||
apply: **默认 False**,只校验不写库;True 才真正提交
|
||
poll_timeout: 结果轮询上限(秒)
|
||
fetch_exceptions: 失败时是否拉失败明细
|
||
|
||
Returns:
|
||
dict:``{menu, label, file, dry_run, matched, fields, max_num, applied, ok,
|
||
stage, business_id, is_success, success, check_fail, save_fail, other,
|
||
message, exceptions, batch_found, batch_total}``
|
||
|
||
Raises:
|
||
SessionExpiredError: 登录态失效(确定性失败,不重试、不建议继续提交)
|
||
ConfigError: 文件缺失 / menu 非法
|
||
"""
|
||
info = menu_info(menu)
|
||
key = str(menu).strip().lower()
|
||
out = {"menu": key, "label": info["label"], "file": os.path.abspath(file_path),
|
||
"dry_run": not apply, "matched": 0, "fields": 0, "max_num": 0,
|
||
"applied": False, "ok": False, "stage": "", "business_id": "",
|
||
"is_success": False, "success": 0, "check_fail": 0, "save_fail": 0,
|
||
"other": 0, "message": "", "exceptions": [],
|
||
"batch_found": False, "batch_total": 0}
|
||
|
||
checked = check_file(client, file_path, key)
|
||
conf, title_list = checked["conf"], checked["title_list"]
|
||
out.update({"matched": checked["matched"], "fields": len(checked["fields"]),
|
||
"max_num": int(conf.get("maxNum") or 0)})
|
||
if checked["matched"] <= 0:
|
||
out.update(stage="check",
|
||
message=f"导入文件表头与「{conf.get('title') or info['title']}」模板不匹配(0 列匹配)")
|
||
return out
|
||
if not apply:
|
||
out.update(ok=True, message="仅校验(dry_run):未提交、未写库")
|
||
return out
|
||
|
||
# ---- 以下为写操作 ----
|
||
business_id = str(uuid.uuid4()) # 必须 36 位带连字符(HR 用该串关联任务与失败记录)
|
||
out.update(business_id=business_id, applied=True)
|
||
form = _form_base(conf, title_list)
|
||
form["businessId"] = business_id
|
||
try:
|
||
resp = client.post_files(
|
||
UPLOAD_DATA_URL,
|
||
files={"file": (os.path.basename(file_path), _read_bytes(file_path), XLSX_MIME)},
|
||
data=form, timeout=180)
|
||
except Exception as exc: # noqa: BLE001 - 结果未知,转轮询判定
|
||
out.update(stage="upload", message=f"提交异常(结果未知,转轮询):{exc}")
|
||
client.log(f"[WARN] {info['label']}提交异常,转轮询判定:{exc}")
|
||
else:
|
||
try:
|
||
payload = resp.json()
|
||
except ValueError:
|
||
payload = None
|
||
if isinstance(payload, dict):
|
||
client.check_state(payload, f"{info['label']}提交") # 会话失效直接抛
|
||
if str(payload.get("state")) != "1":
|
||
detail = decode_error(payload.get("des")) or decode_error(payload.get("meg"))
|
||
out.update(stage="upload",
|
||
message=f"提交未被受理:{(detail or payload)[:500]}")
|
||
return out
|
||
client.log(f"[INFO] {info['label']}已提交(businessId={business_id},"
|
||
f"HTTP {resp.status_code})")
|
||
|
||
result = _poll_result(client, conf["id"], business_id, poll_timeout)
|
||
if result is None:
|
||
out.update(stage="result",
|
||
message=f"结果轮询超时({poll_timeout}s),结果待人工确认")
|
||
return out
|
||
|
||
out.update({
|
||
"is_success": str(result.get("isSuccess")) == "1",
|
||
"success": _int(result.get("success")),
|
||
"check_fail": _int(result.get("checkFail")),
|
||
"save_fail": _int(result.get("saveFail")),
|
||
"other": _int(result.get("other")),
|
||
"message": str(result.get("meg") or ""),
|
||
})
|
||
if fetch_exceptions and not out["is_success"]:
|
||
out["exceptions"] = fetch_failures(client, conf["id"], business_id)
|
||
_check_fail_batches(client, conf["id"], business_id, out, info["label"])
|
||
out["ok"] = True
|
||
return out
|
||
|
||
|
||
def decode_error(value) -> str:
|
||
"""解码服务端返回的加密文案(``des``/``meg``),失败返回原文。"""
|
||
from .query import decode_raw
|
||
|
||
text = str(value or "").strip()
|
||
return decode_raw(text) if text else ""
|
||
|
||
|
||
def _int(value) -> int:
|
||
try:
|
||
return int(value or 0)
|
||
except (TypeError, ValueError):
|
||
return 0
|
||
|
||
|
||
def _poll_result(client, import_id: str, business_id: str,
|
||
timeout: int) -> Optional[dict]:
|
||
"""轮询 ``getImportResult``:拿到含 isSuccess/success 的 result 即返回,超时 None。"""
|
||
deadline = time.time() + max(1, int(timeout))
|
||
waited = 0
|
||
while time.time() < deadline:
|
||
try:
|
||
resp = client.post_files(GET_IMPORT_RESULT_URL,
|
||
files={},
|
||
data={"importId": import_id,
|
||
"businessId": business_id}, timeout=30)
|
||
data = client.as_json(resp, "导入结果查询")
|
||
client.check_state(data, "导入结果查询")
|
||
res = data.get("result")
|
||
if str(data.get("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 += int(POLL_INTERVAL_SECONDS)
|
||
if waited % 30 == 0:
|
||
client.log(f"[INFO] 导入处理中:{meg}(已等待 {waited}s)")
|
||
except SessionExpiredError:
|
||
raise
|
||
except Exception as exc: # noqa: BLE001 - 轮询期间容忍抖动
|
||
client.log(f"[WARN] 导入结果查询失败(继续轮询):{exc}")
|
||
time.sleep(POLL_INTERVAL_SECONDS)
|
||
return None
|
||
|
||
|
||
# ==================== 失败明细 / 批次 ====================
|
||
|
||
def _page_failures(client, url: str, data_builder, label: str) -> List[dict]:
|
||
items: List[dict] = []
|
||
page_count, page_no = 1, 1
|
||
while page_no <= page_count:
|
||
try:
|
||
resp = client.post_files(url, files={}, data=data_builder(page_no), timeout=30)
|
||
result = client.as_json(resp, label)
|
||
client.check_state(result, label)
|
||
except SessionExpiredError:
|
||
raise
|
||
except Exception as exc: # noqa: BLE001
|
||
client.log(f"[WARN] {label}第 {page_no} 页失败:{exc}")
|
||
break
|
||
page_count = max(1, _int(result.get("pageCount") or 1))
|
||
items.extend(_parse_failure_rows(result.get("datas") or []))
|
||
page_no += 1
|
||
return items
|
||
|
||
|
||
def _parse_failure_rows(rows: List[dict]) -> List[dict]:
|
||
out = []
|
||
for item in rows or []:
|
||
item = item or {}
|
||
message = str(item.get("imp_fixed_msg", "") or "").strip()
|
||
if not message or "导入成功" in message: # 成功行固定文案,不计入异常
|
||
continue
|
||
out.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": message,
|
||
})
|
||
return out
|
||
|
||
|
||
def fetch_failures(client, import_id: str, business_id: str) -> List[dict]:
|
||
"""拉某批次失败明细(官方「失败数据」页优先,弹窗明细兜底)。"""
|
||
items = _page_failures(
|
||
client, GET_FAIL_PAGE_URL,
|
||
lambda page_no: {
|
||
"excelImpVersion": "2", "functionCode": import_id,
|
||
"businessId": business_id,
|
||
"start": str((page_no - 1) * TMP_PAGE_SIZE), "pageNo": str(page_no),
|
||
"pageSize": str(TMP_PAGE_SIZE), "commonQuery": "[]",
|
||
"sortType": "", "sortName": "",
|
||
}, "失败数据")
|
||
if items:
|
||
return items
|
||
return _page_failures(
|
||
client, GET_TMP_DATA_PAGE_URL,
|
||
lambda page_no: {
|
||
"importId": import_id, "imp_fixed_businessid": business_id,
|
||
"start": str((page_no - 1) * TMP_PAGE_SIZE), "pageNo": str(page_no),
|
||
"pageSize": str(TMP_PAGE_SIZE), "sortType": "", "sortName": "",
|
||
}, "导入明细")
|
||
|
||
|
||
def fail_batches(client, import_id: str, date_begin: str = "",
|
||
date_end: str = "") -> List[dict]:
|
||
"""查某模板在指定时间段内的失败批次(只有存在失败数据才生成批次)。"""
|
||
today = date_begin or time.strftime("%Y-%m-%d")
|
||
resp = client.post_files(GET_IMPORT_FAILURE_LIST_URL, files={}, data={
|
||
"root_id": "", "excelImpVersion": "2", "functionCode": import_id,
|
||
"date_begin": today, "date_end": date_end or f"{today} 23:59:59",
|
||
"start": "0", "sortType": "", "sortName": "", "pageNo": "1",
|
||
"pageSize": str(FAIL_LIST_PAGE_SIZE),
|
||
}, timeout=30)
|
||
data = client.as_json(resp, "导入失败批次列表")
|
||
if str(data.get("state")) != "1":
|
||
client.check_state(data, "导入失败批次列表")
|
||
return []
|
||
out = []
|
||
for item in data.get("datas") or []:
|
||
item = item or {}
|
||
bid = str(item.get("businessid") or "").strip()
|
||
if not bid:
|
||
continue
|
||
out.append({"business_id": bid,
|
||
"operator_time": str(item.get("operator_time") or ""),
|
||
"total": _int(item.get("total"))})
|
||
return out
|
||
|
||
|
||
def _check_fail_batches(client, import_id: str, business_id: str, out: dict,
|
||
label: str) -> None:
|
||
"""当天失败批次核对(只补观测字段,不影响主流程)。"""
|
||
try:
|
||
batches = fail_batches(client, import_id)
|
||
except SessionExpiredError:
|
||
raise
|
||
except Exception as exc: # noqa: BLE001
|
||
client.log(f"[WARN] {label}失败批次核对跳过:{exc}")
|
||
return
|
||
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:
|
||
client.log(f"[INFO] {label}失败批次已确认:{business_id}"
|
||
f"({hit['operator_time']},失败 {hit['total']} 条)")
|
||
if out["exceptions"] and len(out["exceptions"]) != hit["total"]:
|
||
client.log(f"[WARN] {label}明细条数({len(out['exceptions'])})"
|
||
f"与批次统计({hit['total']})不一致,请人工核对")
|
||
elif not out["is_success"]:
|
||
client.log(f"[WARN] {label}未在当天失败批次列表中找到本批次,请人工核对")
|
||
|
||
|
||
# ==================== 入库核对数据(只读) ====================
|
||
|
||
def _date_params() -> dict:
|
||
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 operated_staff(client, started_at: str, end_at: str = "",
|
||
max_pages: int = 80) -> List[dict]:
|
||
"""查「待增减人员」里商业保险操作时间 ∈ [started_at, end_at] 的人员。
|
||
|
||
返回 ``[{staff_code, staff_name, scheme, operate_time, add_date, cut_date}]``;
|
||
与导入文件工号做交集即可判断「到底哪些人入库了」——判定逻辑留插件。
|
||
"""
|
||
if not started_at:
|
||
raise ConfigError("started_at 不能为空(导入提交前的时间点,YYYY-MM-DD HH:MM:SS)")
|
||
end_at = end_at or time.strftime("%Y-%m-%d %H:%M:%S")
|
||
user = client.request_json("POST", f"{REDSEA}/PtUsers.mc?method=getCurUserInfo",
|
||
data={}, label="当前用户信息")
|
||
root = str(user.get("rootId") or "cq37du")
|
||
params = base_params("待增减人员", PENDING_TABLE_ID, PENDING_ROSTER_ID,
|
||
user={"userId": user.get("userId") or "",
|
||
"staffId": user.get("staffId") or "",
|
||
"roleIds": PENDING_ROLE_IDS})
|
||
params.update({
|
||
"_t": str(int(time.time() * 1000)),
|
||
"struTreeCode": root,
|
||
"struId": PENDING_ORG_STRU_ID,
|
||
"belongUnitStruId": PENDING_ORG_STRU_ID,
|
||
"rootId": root,
|
||
"currentUserRootId": root,
|
||
"pageSize": str(PENDING_PAGE_SIZE),
|
||
"commonQuery": encode([
|
||
{"queryField": PENDING_OPERATE_FIELD, "leftBracket": "(", "queryType": ">=",
|
||
"queryValue": started_at, "queryText": started_at, "rightBracket": "",
|
||
"logic": "AND", "inputType": "date"},
|
||
{"queryField": PENDING_OPERATE_FIELD, "leftBracket": "", "queryType": "<=",
|
||
"queryValue": end_at, "queryText": end_at, "rightBracket": ")",
|
||
"logic": "AND", "inputType": "date"},
|
||
]),
|
||
})
|
||
params.update(_date_params())
|
||
|
||
rows: List[dict] = []
|
||
for page_no in range(1, max(1, max_pages) + 1):
|
||
body = dict(params)
|
||
body["pageNo"] = str(page_no)
|
||
body["start"] = str((page_no - 1) * PENDING_PAGE_SIZE)
|
||
data = client.request_json("POST", PENDING_LIST_URL, data=body,
|
||
label=f"待增减人员第 {page_no} 页")
|
||
client.check_state(data, f"待增减人员第 {page_no} 页")
|
||
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 ""),
|
||
})
|
||
page_count = _int(data.get("pageCount") or 1) or 1
|
||
if page_no >= page_count or not datas:
|
||
break
|
||
client.log(f"[INFO] 待增减人员操作记录:{len(rows)} 条({started_at} 之后)")
|
||
return rows
|
||
|
||
|
||
def read_codes(file_path: str) -> List[str]:
|
||
"""读导入文件里的工号(第 4 行起、A 列序号非空视为有效行,取 B 列)。"""
|
||
_require_file(file_path)
|
||
from openpyxl import load_workbook
|
||
|
||
codes: List[str] = []
|
||
try:
|
||
wb = load_workbook(file_path, read_only=True, data_only=True)
|
||
except Exception as exc: # noqa: BLE001
|
||
raise ConfigError(f"读取导入文件失败:{exc}") from None
|
||
try:
|
||
ws = wb[wb.sheetnames[0]]
|
||
for row in ws.iter_rows(min_row=int(CONTENT_ROW_NUM), max_col=2,
|
||
values_only=True):
|
||
seq, code = (list(row) + [None, None])[:2]
|
||
if seq in (None, "") or code in (None, ""):
|
||
continue
|
||
codes.append(str(code).strip())
|
||
finally:
|
||
wb.close()
|
||
return codes
|
||
|
||
|
||
# ==================== 内部工具 ====================
|
||
|
||
def _require_file(path: str) -> None:
|
||
if not path or not os.path.isfile(path):
|
||
raise ConfigError(f"导入文件不存在:{path}")
|
||
|
||
|
||
def _read_bytes(path: str) -> bytes:
|
||
with open(path, "rb") as fp:
|
||
return fp.read() # 读成 bytes:重试/多次提交时可重发
|
||
|
||
|
||
__all__ = [
|
||
"CHECK_FILE_TYPE_URL",
|
||
"CONTENT_ROW_NUM",
|
||
"FAIL_LIST_PAGE_SIZE",
|
||
"GET_FAIL_PAGE_URL",
|
||
"GET_IMPORT_FAILURE_LIST_URL",
|
||
"GET_IMPORT_RESULT_URL",
|
||
"GET_TMP_DATA_PAGE_URL",
|
||
"IMPORT_MENUS",
|
||
"PENDING_LIST_URL",
|
||
"PENDING_OPERATE_FIELD",
|
||
"PENDING_ROSTER_ID",
|
||
"POLL_INTERVAL_SECONDS",
|
||
"POLL_TIMEOUT_SECONDS",
|
||
"TITLE_ROW_NUM",
|
||
"TMP_PAGE_SIZE",
|
||
"UPLOAD_DATA_URL",
|
||
"XLSX_MIME",
|
||
"check_file",
|
||
"decode_error",
|
||
"fail_batches",
|
||
"fetch_failures",
|
||
"field_list",
|
||
"load_conf",
|
||
"match_titles",
|
||
"menu_info",
|
||
"operated_staff",
|
||
"read_codes",
|
||
"upload",
|
||
]
|