feat: 新增社保参保核对工具链,补全依赖并清理废弃文件
- 新增社保参保/停保状态核对核心逻辑,支持调用HR接口校验工号参保记录 - 新增滑块验证码改进版登录工具,支持缓存会话免重复登录 - 新增HR通用API封装模块 - 新增员工异动名单清洗、导出、核对全流程功能 - 新增依赖库xlrd、openpyxl、opencv等 - 删除旧的钉钉消息推送文档、测试用Excel、aa.md脚本文件 - 优化员工异动导出流程,自动完成去重和参保核对
This commit is contained in:
@@ -48,6 +48,27 @@ except ImportError:
|
||||
SessionPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
try:
|
||||
import xlrd
|
||||
except ImportError:
|
||||
xlrd = None
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
requests = None
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
from openpyxl.styles import PatternFill, Font, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError:
|
||||
_XlsxWorkbook = None
|
||||
PatternFill = None
|
||||
Font = None
|
||||
Alignment = None
|
||||
get_column_letter = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 常量 ----------
|
||||
@@ -87,6 +108,35 @@ MENU_NAME_SUSPEND = "员工停保申请"
|
||||
FILTER_IDX_PARTICIPATE = "2"
|
||||
FILTER_IDX_SUSPEND = "3"
|
||||
|
||||
# ---------- HR 参保记录核对(si_main 接口,对应 aa.md) ----------
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
# HR cookies 持久化文件(ehr/common/login.py 保存)
|
||||
HR_COOKIE_FILE = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), '..', '..', '..', '.sessions', 'hr_cookies.json')
|
||||
)
|
||||
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": "",
|
||||
}
|
||||
SI_RESULT_COL = "社保记录查询结果"
|
||||
SI_BATCH_SIZE = 15
|
||||
|
||||
|
||||
def _resolve_query_date(query_date: Optional[str] = None) -> str:
|
||||
"""返回查询起始日期:手动传入则用传入值,否则用当前月份第一天。"""
|
||||
@@ -167,16 +217,19 @@ def _get_cookies_with_domain(session: SessionPage) -> list:
|
||||
return cookies
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session: SessionPage) -> str:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||||
def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage] = None) -> str:
|
||||
# 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景)
|
||||
own_browser = browser is None
|
||||
if own_browser:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||||
|
||||
co = ChromiumOptions()
|
||||
# 如需 Edge 浏览器,请取消注释并设置路径
|
||||
# co.set_browser_path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
|
||||
browser = ChromiumPage(co)
|
||||
browser.set.cookies(cookies)
|
||||
co = ChromiumOptions()
|
||||
# 如需 Edge 浏览器,请取消注释并设置路径
|
||||
# co.set_browser_path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
|
||||
browser = ChromiumPage(co)
|
||||
browser.set.cookies(cookies)
|
||||
|
||||
try:
|
||||
browser.listen.start()
|
||||
@@ -204,7 +257,8 @@ def get_fd_id_by_listening(session: SessionPage) -> str:
|
||||
return fd_id
|
||||
finally:
|
||||
browser.listen.stop()
|
||||
browser.quit()
|
||||
if own_browser:
|
||||
browser.quit()
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
@@ -311,6 +365,248 @@ def export_all_data(session: SessionPage, base_params: Dict, total: int, columns
|
||||
return session.response.content
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5.5 按工号去重清洗(去掉『废弃』,每工号保留最新申请日期)
|
||||
# ----------------------------------------------
|
||||
def _normalize_date_key(value) -> float:
|
||||
"""将『申请日期』单元格归一化为可比较的数值键(Excel 序列号或日期天数)。"""
|
||||
if value is None:
|
||||
return 0.0
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
if isinstance(value, str):
|
||||
m = re.match(r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})", value.strip())
|
||||
if m:
|
||||
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
try:
|
||||
return (datetime(y, mo, d) - datetime(1899, 12, 30)).days
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _date_display(value, wb):
|
||||
"""把 Excel 日期序列号转成可读字符串:整天只显示日期,带时间则显示到秒。"""
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
dt = xlrd.xldate_as_datetime(float(value), wb.datemode)
|
||||
except Exception:
|
||||
return value
|
||||
if float(value).is_integer():
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return value
|
||||
|
||||
|
||||
def _read_and_clean(xls_path: str):
|
||||
"""读取 .xls:去掉『废弃』,按工号去重(每工号保留最新申请日期)。
|
||||
|
||||
返回 (headers, rows, emp_col),rows 中工号已统一为字符串、申请日期已格式化为文本。
|
||||
"""
|
||||
if xlrd is None:
|
||||
raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls")
|
||||
|
||||
wb = xlrd.open_workbook(xls_path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
|
||||
def find_col(keyword):
|
||||
for i, h in enumerate(headers):
|
||||
if keyword in h:
|
||||
return i
|
||||
return None
|
||||
|
||||
emp_col = find_col("工号")
|
||||
date_col = find_col("申请日期")
|
||||
status_col = find_col("文档状态")
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
# 1) 过滤:去掉『废弃』,且工号非空;所有日期列统一转成可读文本
|
||||
rows = []
|
||||
for r in range(1, sh.nrows):
|
||||
row = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if sh.cell_type(r, c) == xlrd.XL_CELL_DATE:
|
||||
v = _date_display(v, wb)
|
||||
row.append(v)
|
||||
emp = str(row[emp_col]).strip()
|
||||
if not emp:
|
||||
continue
|
||||
if status_col is not None and str(row[status_col]).strip() == "废弃":
|
||||
continue
|
||||
row[emp_col] = emp
|
||||
rows.append(row)
|
||||
|
||||
# 2) 去重:按工号保留申请日期最新的一条,保持首次出现顺序
|
||||
latest = {}
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
key = _normalize_date_key(row[date_col]) if date_col is not None else 0.0
|
||||
if emp not in latest or key > latest[emp][0]:
|
||||
latest[emp] = (key, row)
|
||||
|
||||
ordered = []
|
||||
seen = set()
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
if emp not in seen:
|
||||
seen.add(emp)
|
||||
ordered.append(latest[emp][1])
|
||||
|
||||
logger.info("清洗完成:去掉废弃后 %d 条,去重后 %d 条", len(rows), len(ordered))
|
||||
return headers, ordered, emp_col
|
||||
|
||||
|
||||
def clean_employee_change_file(xls_path: str, output_dir: str = ".") -> str:
|
||||
"""按工号去重清洗导出的名单,写出清洗后的 .xlsx(兼容旧入口)。"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法执行去重清洗,请先安装")
|
||||
headers, rows, _ = _read_and_clean(xls_path)
|
||||
out_name = f"{os.path.splitext(os.path.basename(xls_path))[0]}_去重.xlsx"
|
||||
out_path = os.path.abspath(os.path.join(output_dir, out_name))
|
||||
out_wb = _XlsxWorkbook()
|
||||
ws = out_wb.active
|
||||
ws.append(headers)
|
||||
for row in rows:
|
||||
ws.append(row)
|
||||
out_wb.save(out_path)
|
||||
logger.info("清洗结果保存为:%s", out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5.6 HR 参保记录核对(调用 si_main 接口,追加结果列)
|
||||
# ----------------------------------------------
|
||||
def _build_hr_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
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _si_query_batch(session, codes_batch):
|
||||
"""查询一批工号(≤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 _si_found_codes(response_json):
|
||||
"""从返回 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 _si_check_batch(session, codes_batch) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;请求失败返回空集合并告警。"""
|
||||
try:
|
||||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||||
except Exception as e:
|
||||
logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") -> str:
|
||||
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
|
||||
|
||||
# 按工号去重(保持首次出现顺序),再逐批查询
|
||||
unique_codes, seen = [], set()
|
||||
for row in rows:
|
||||
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), SI_BATCH_SIZE):
|
||||
found |= _si_check_batch(session, unique_codes[i:i + SI_BATCH_SIZE])
|
||||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3)
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in rows:
|
||||
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"{base_name}_参保核对.xlsx"))
|
||||
out_wb = _XlsxWorkbook()
|
||||
|
||||
# 异常行标红 + 结果列加粗红字(便于数据多时一眼定位)
|
||||
red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") if PatternFill else None
|
||||
red_font = Font(color="9C0006", bold=True) if Font else None
|
||||
head_fill = PatternFill(start_color="DDEBF7", end_color="DDEBF7", fill_type="solid") if PatternFill else None
|
||||
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = "核对明细"
|
||||
out_ws.append(headers + [SI_RESULT_COL])
|
||||
for c in range(1, len(headers) + 2):
|
||||
cell = out_ws.cell(1, c)
|
||||
cell.fill = head_fill
|
||||
cell.font = Font(bold=True) if Font else None
|
||||
cell.alignment = Alignment(horizontal="center") if Alignment else None
|
||||
for idx, row in enumerate(new_rows, start=2):
|
||||
out_ws.append(row)
|
||||
if str(row[-1]).startswith("异常"):
|
||||
for c in range(1, len(row) + 1):
|
||||
cell = out_ws.cell(idx, c)
|
||||
cell.fill = red_fill
|
||||
if c == len(row):
|
||||
cell.font = red_font
|
||||
out_ws.freeze_panes = "A2"
|
||||
out_ws.auto_filter.ref = out_ws.dimensions
|
||||
if get_column_letter:
|
||||
for c in range(1, len(headers) + 2):
|
||||
out_ws.column_dimensions[get_column_letter(c)].width = 20
|
||||
|
||||
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
|
||||
|
||||
|
||||
def annotate_si_result(xls_path: str, mode: str, output_dir: str = ".") -> str:
|
||||
"""读取原始 .xls → 清洗去重 → 查 HR 参保记录 → 追加结果列,导出一份最终文件(无中间表)。
|
||||
|
||||
mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常)
|
||||
"""
|
||||
headers, rows, emp_col = _read_and_clean(xls_path)
|
||||
return _write_annotated(headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(xls_path))[0], output_dir)
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 主流程(精简版)
|
||||
# ----------------------------------------------
|
||||
@@ -333,8 +629,8 @@ def export_employee_change_list(
|
||||
browser, session = get_session()
|
||||
|
||||
try:
|
||||
# 1. 动态获取 fdId
|
||||
fd_id = get_fd_id_by_listening(session)
|
||||
# 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭)
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
|
||||
# 2. 从菜单获取 searchId
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
@@ -360,9 +656,25 @@ def export_employee_change_list(
|
||||
f.write(file_content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
# 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
|
||||
# 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
|
||||
# 8. 清理中间原始导出文件,只保留最终标注表
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return output_path
|
||||
return final_path
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
# -*- 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()
|
||||
Reference in New Issue
Block a user