Files
37duAutomation/app/service/hrbp/oa/social_change/si_insurance_check.py
T

266 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@Module: hrbp.oa.social_change.si_insurance_check
@FileName: si_insurance_check.py
@Author: 小布丁
@CreateTime: 2026-08-07 15:20
@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口,
判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。
@Version: 2.1.0
业务判定(对应 aa.md):
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
- 停保申请表:某工号在 HR 参保记录中「无返回数据」→ 已停保,属异常。
"""
import os
import sys
import time
from pathlib import Path
from typing import List, Tuple
# ---- 单文件运行支持 ----
def _find_project_root() -> str:
for parent in Path(__file__).resolve().parents:
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
return str(parent)
return str(Path(__file__).resolve().parents[5])
_root = _find_project_root()
if _root not in sys.path:
sys.path.insert(0, _root)
from app.utils.logger import get_logger, setup_logging
from app.utils.intelligent_retry import retry
# HR 平台会话/请求封装(共享层,避免反向依赖 ehr)
from app.service.hrbp.common.hr_session import (
build_hr_session,
refresh_hr_session,
HRSessionExpiredError,
hr_request_json,
)
try:
import xlrd
except ImportError:
xlrd = None
try:
from openpyxl import load_workbook as _load_workbook
from openpyxl import Workbook as _XlsxWorkbook
except ImportError:
_load_workbook = None
_XlsxWorkbook = None
logger = get_logger(__name__)
# ---------- 常量 ----------
# HR 参保记录查询接口(aa.md 提供的 si_main 接口)
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
# 接口基础参数(aa.md 基础参数模板,base_codes 动态替换)
SI_BASE_PARAMS = {
"start": "0", "pageNo": "1", "pageSize": "15",
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"STRU_TREE_CODE": "cq37du",
"queryTempPersonType": "queryForList",
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
"postStruId": "1", "regist_property": "", "identity": "",
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
"siName": "", "belongUnitId": "", "belongUnitName": "",
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
"operator": "",
"joinDate_begin": "", "joinDate_end": "",
"leaveDate_begin": "", "leaveDate_end": "",
"siBeginDate_begin": "", "siBeginDate_end": "",
"siEndDate_begin": "", "siEndDate_end": "",
}
RESULT_COL = "社保记录查询结果"
BATCH_SIZE = 15
# ----------------------------------------------
# 1. 查询参保记录接口
# ----------------------------------------------
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
def query_batch(session, codes_batch: List[str]):
"""查询一批工号(≤15个),返回响应 JSON。"""
params = SI_BASE_PARAMS.copy()
params["base_codes"] = ",".join(codes_batch)
return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15)
def extract_found_codes(response_json) -> set:
"""从返回 JSON 中提取所有 base_Code 工号。"""
datas = response_json.get("datas") or []
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
def check_codes(session, codes_batch: List[str]) -> set:
"""返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。"""
try:
return extract_found_codes(query_batch(session, codes_batch))
except HRSessionExpiredError:
raise
except Exception as e:
logger.warning("批量查询失败 %s:%s", codes_batch, e)
return set()
def preflight(session) -> "requests.Session":
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
try:
query_batch(session, ["0"])
except HRSessionExpiredError:
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
return refresh_hr_session()
return session
# ----------------------------------------------
# 3. 读取表格(支持 .xlsx / .xls)
# ----------------------------------------------
def read_table(path: str) -> Tuple[List[str], List[list]]:
"""读取表格,返回 (表头, 数据行)。"""
ext = os.path.splitext(path)[1].lower()
if ext == ".xlsx":
if _load_workbook is None:
raise RuntimeError("缺少 openpyxl 依赖,无法读取 .xlsx")
ws = _load_workbook(path).active
rows = list(ws.iter_rows(values_only=True))
headers = [str(h) if h is not None else "" for h in rows[0]]
data = [list(r) for r in rows[1:]]
elif ext == ".xls":
if xlrd is None:
raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls")
sh = xlrd.open_workbook(path).sheet_by_index(0)
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
data = [[sh.cell_value(r, c) for c in range(sh.ncols)] for r in range(1, sh.nrows)]
else:
raise ValueError(f"不支持的文件格式:{ext},请提供 .xlsx 或 .xls")
return headers, data
# ----------------------------------------------
# 4. 核对并追加结果列
# ----------------------------------------------
def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str:
"""读表 → 按工号去重 → 逐批查接口 → 追加结果列 → 导出 .xlsx。
mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常)
"""
if _XlsxWorkbook is None:
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
headers, data = read_table(table_path)
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
if emp_col is None:
raise ValueError(f"未找到『工号』列,表头: {headers}")
# 按工号去重(保持首次出现顺序),再逐批查询
unique_codes = []
seen = set()
for row in data:
code = str(row[emp_col]).strip()
if code and code not in seen:
seen.add(code)
unique_codes.append(code)
session = preflight(build_hr_session(auto_login=False))
found = set()
for i in range(0, len(unique_codes), BATCH_SIZE):
batch = unique_codes[i:i + BATCH_SIZE]
try:
found |= check_codes(session, batch)
except HRSessionExpiredError:
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
session = refresh_hr_session()
found |= check_codes(session, batch)
logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
time.sleep(0.3) # 轻微限速,避免触发风控
is_participate = (mode == "participation")
new_rows = []
for row in data:
code = str(row[emp_col]).strip()
has_record = code in found
if is_participate:
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
else:
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
new_rows.append(row + [val])
out_path = os.path.abspath(os.path.join(
output_dir,
f"{os.path.splitext(os.path.basename(table_path))[0]}_参保核对.xlsx",
))
out_wb = _XlsxWorkbook()
ws = out_wb.active
ws.append(headers + [RESULT_COL])
for row in new_rows:
ws.append(row)
out_wb.save(out_path)
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
logger.info("完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
len(unique_codes), len(found), len(abnormal), out_path)
return out_path
# ----------------------------------------------
# 5. 对外便捷入口
# ----------------------------------------------
def check_participation(table_path: str, output_dir: str = ".") -> str:
return check_and_annotate(table_path, "participation", output_dir)
def check_suspension(table_path: str, output_dir: str = ".") -> str:
return check_and_annotate(table_path, "suspension", output_dir)
def _latest_cleaned(project: str, keyword: str) -> str:
"""在项目目录里找最新(按修改时间)的、文件名含关键字且以 _去重.xlsx 结尾的表。"""
matches = [
p for p in Path(project).glob("*.xlsx")
if keyword in p.name and p.name.endswith("_去重.xlsx")
]
if not matches:
return ""
return str(max(matches, key=lambda p: p.stat().st_mtime))
def main() -> None:
setup_logging()
args = sys.argv[1:]
project = _root
def pick(keyword):
# 优先命令行显式指定,否则自动找最新清洗表
for a in args:
if keyword in Path(a).name:
return a
return _latest_cleaned(project, keyword)
participate = pick("参保")
suspend = pick("停保")
if participate and os.path.exists(participate):
check_participation(participate, project)
else:
logger.warning("未找到参保清洗表(*参保*_去重.xlsx)")
if suspend and os.path.exists(suspend):
check_suspension(suspend, project)
else:
logger.warning("未找到停保清洗表(*停保*_去重.xlsx)")
if __name__ == "__main__":
main()