1. 重构重试装饰器,新增no_retry_on参数支持指定异常不重试 2. 为社保核对模块添加登录态过期检测与自动刷新逻辑 3. 统一两处社保业务代码的异常处理与会话重建流程 4. 更新版本号与默认输出目录配置
315 lines
12 KiB
Python
315 lines
12 KiB
Python
# -*- 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
|
||
|
||
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
|
||
|
||
|
||
class HRSessionExpiredError(Exception):
|
||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||
|
||
|
||
def _is_expired(text) -> bool:
|
||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||
|
||
|
||
def _refresh_hr_session() -> "requests.Session":
|
||
"""HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。"""
|
||
from app.service.hrbp.ehr.common.login import login as hr_login
|
||
if not hr_login():
|
||
raise RuntimeError("HR 登录态过期后重新登录失败")
|
||
return build_hr_session()
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 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, 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)
|
||
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
|
||
resp.raise_for_status()
|
||
if _is_expired(resp.text):
|
||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||
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 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())
|
||
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()
|