Files
37duAutomation/app/service/hrbp/oa/social_change/si_insurance_check.py
T
puddy a41e150f85 feat: 新增社保参保核对工具链,补全依赖并清理废弃文件
- 新增社保参保/停保状态核对核心逻辑,支持调用HR接口校验工号参保记录
- 新增滑块验证码改进版登录工具,支持缓存会话免重复登录
- 新增HR通用API封装模块
- 新增员工异动名单清洗、导出、核对全流程功能
- 新增依赖库xlrd、openpyxl、opencv等
- 删除旧的钉钉消息推送文档、测试用Excel、aa.md脚本文件
- 优化员工异动导出流程,自动完成去重和参保核对
2026-08-07 23:12:09 +08:00

277 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.0.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
try:
import requests
except ImportError:
requests = None
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"
# HR cookies 持久化文件(login.py 保存)
HR_COOKIE_FILE = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..', '.sessions', 'hr_cookies.json')
)
# 接口基础参数(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. HR 会话(复用登录缓存 cookies)
# ----------------------------------------------
def build_hr_session() -> "requests.Session":
"""用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。"""
if requests is None:
raise RuntimeError("缺少 requests 依赖,请先安装")
if not os.path.exists(HR_COOKIE_FILE):
raise RuntimeError(f"未找到 HR cookies 缓存文件:{HR_COOKIE_FILE},请先执行 HR 登录")
import json
with open(HR_COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies or []:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
return session
# ----------------------------------------------
# 2. 查询参保记录接口
# ----------------------------------------------
@retry(max_attempts=3)
def query_batch(session, codes_batch: List[str]):
"""查询一批工号(≤15个),返回响应 JSON。"""
params = SI_BASE_PARAMS.copy()
params["base_codes"] = ",".join(codes_batch)
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
resp.raise_for_status()
return resp.json()
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 Exception as e:
logger.warning("批量查询失败 %s:%s", codes_batch, e)
return set()
# ----------------------------------------------
# 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 = build_hr_session()
found = set()
for i in range(0, len(unique_codes), BATCH_SIZE):
found |= check_codes(session, unique_codes[i:i + BATCH_SIZE])
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()