新增内容包括: 1. 7个业务需求占位文档目录与README 2. 共享OA登录、钉钉机器人推送工具模块 3. 雇主险变更清单导出脚本 4. 考勤月报封存检查两个检查脚本 5. 重庆社保停保导入名单生成脚本
792 lines
32 KiB
Python
792 lines
32 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: social_change.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-07
|
||
@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——复用共享 OA 登录态导出参保/停保名单
|
||
-> 清洗去重 -> 复用共享 HR 登录态核对参保记录 -> 追加结果列
|
||
-> 写全局变量 messages(文本汇总+表文件,单文件直接推/多文件打包 zip,
|
||
由「37du钉钉单聊推送」指令发送)。
|
||
业务判定及规则见 docs/社保增减名单/需求文档.md。
|
||
@Version: 2.3.0
|
||
|
||
设计说明(避免维护 app/影刀两套版本):
|
||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||
- OA 登录态复用共享 oa_cookies.json(由「37duOA登录」指令写入),HR 登录态复用共享
|
||
hr_cookies.json(由「37duHR登录」指令写入);均只读,缺失/失效时友好提示先运行
|
||
对应登录指令,不自动补登。
|
||
- 结果推送写全局变量 messages(text 汇总 + file 附件),发送由「37du钉钉单聊推送」指令完成。
|
||
|
||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install DrissionPage python-dotenv requests xlrd openpyxl
|
||
|
||
环境变量(.env 文件或系统变量):
|
||
可选:social_change_query_date=查询起始日期(如 2026-08-01,默认当月1号)
|
||
social_change_output_dir=结果输出目录(默认 D:\资料\人资\员工社保增减名单)
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import functools
|
||
import json
|
||
import os
|
||
import random
|
||
import re
|
||
import sys
|
||
import time
|
||
import zipfile
|
||
from datetime import datetime
|
||
from urllib.parse import urljoin, urlparse, parse_qs
|
||
|
||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||
try:
|
||
from DrissionPage import ChromiumPage, SessionPage, ChromiumOptions
|
||
from dotenv import load_dotenv
|
||
import requests
|
||
import xlrd
|
||
from openpyxl import load_workbook as _load_workbook
|
||
from openpyxl import Workbook as _XlsxWorkbook
|
||
from openpyxl.styles import PatternFill, Font, Alignment
|
||
from openpyxl.utils import get_column_letter
|
||
except ImportError as _import_err:
|
||
raise RuntimeError(
|
||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||
"请先执行安装:\n"
|
||
" pip install DrissionPage python-dotenv requests xlrd openpyxl\n"
|
||
f"缺失依赖详情: {_import_err}"
|
||
)
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
# 共享登录态 cookies 统一由对应登录指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\
|
||
_SHARED_SESSIONS_DIR = os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||
'37duAutomation', '.sessions'
|
||
)
|
||
# OA 登录态 cookies:由「37duOA登录」指令写入(只读,缺失/失效提示先运行登录指令,不自动补登)
|
||
COOKIE_FILE_OA = os.path.join(_SHARED_SESSIONS_DIR, 'oa_cookies.json')
|
||
# HR 登录态 cookies:由「37duHR登录」指令写入(只读,缺失/失效提示先运行登录指令,不自动补登)
|
||
SHARED_HR_COOKIE_FILE = os.path.join(_SHARED_SESSIONS_DIR, 'hr_cookies.json')
|
||
|
||
# ---------- OA 系统 ----------
|
||
BASE_URL = "https://oa.37du.co"
|
||
HR_BASE_URL = "https://hr.37du.co"
|
||
HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619903d5"
|
||
LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp"
|
||
SEARCH_URL = f"{BASE_URL}/sys/search/search.do"
|
||
MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do"
|
||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||
|
||
DEFAULT_FIXED_PARAMS = {
|
||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||
"canClose": "false", "isNew": "true",
|
||
"j_aside": "false", "j_rIframe": "true", "j_iframe": "true",
|
||
}
|
||
DEFAULT_EXPORT_COLUMNS = (
|
||
"fd_38e9dd25e050e0;docCreator;fd_38d49cbc0ceeae;"
|
||
"fd_390c6988e241ea;fd_390c639f265c78;fd_38e77e5cd6e9fe;"
|
||
"fd_38d49cd67211e2;fd_38d49cd73eff02;fd_38deea220dc8c4;docStatus"
|
||
)
|
||
DEFAULT_EXPORT_COLUMNS_SUSPEND = (
|
||
"fd_38d32213b2e9cc;fd_38d322164f42f2;fd_38e6887c2b3690;"
|
||
"fd_3ec504d4c63e02;fd_38dad8035e33e4;fd_38e6887d6b0088;"
|
||
"fd_38d32227f7a496;fd_38dee9ae569d6a;fd_38e687e91f4fc6;"
|
||
"fd_38e687eb56dc4c;docStatus;docPublishTime"
|
||
)
|
||
MENU_NAME_PARTICIPATE = "员工参保申请"
|
||
MENU_NAME_SUSPEND = "员工停保申请"
|
||
FILTER_IDX_PARTICIPATE = "2"
|
||
FILTER_IDX_SUSPEND = "3"
|
||
|
||
# ---------- HR 参保记录核对(si_main 接口) ----------
|
||
SI_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||
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
|
||
|
||
# ---------- 打包推送(结果写全局变量 messages,由「37du钉钉单聊推送」指令发送) ----------
|
||
PUSH_RECEIVER_NAME = "周卫"
|
||
PUSH_RECEIVER_ID = "37001166"
|
||
|
||
|
||
# ==================== 日志(print 替代 logging) ====================
|
||
class _PrintLogger:
|
||
def debug(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def info(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def warning(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def error(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
|
||
logger = _PrintLogger()
|
||
|
||
|
||
# ==================== 重试装饰器 ====================
|
||
class RetryExhaustedError(Exception):
|
||
pass
|
||
|
||
|
||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||
if max_attempts < 1:
|
||
raise ValueError("max_attempts must be >= 1")
|
||
|
||
def decorator(func):
|
||
@functools.wraps(func)
|
||
def wrapper(*args, **kwargs):
|
||
last_exc = None
|
||
for attempt in range(1, max_attempts + 1):
|
||
try:
|
||
return func(*args, **kwargs)
|
||
except no_retry_on:
|
||
raise
|
||
except Exception as e:
|
||
last_exc = e
|
||
if attempt >= max_attempts:
|
||
logger.error("%s 连续 %d 次尝试失败: %s", func.__name__, max_attempts, e)
|
||
break
|
||
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||
time.sleep(delay)
|
||
raise RetryExhaustedError(
|
||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||
) from last_exc
|
||
return wrapper
|
||
return decorator
|
||
|
||
|
||
# ==================== Cookies 读取(共享登录态,只读) ====================
|
||
def _ensure_dir(path):
|
||
os.makedirs(path, exist_ok=True)
|
||
|
||
|
||
def load_cookies(path):
|
||
if not os.path.exists(path):
|
||
return None
|
||
with open(path, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
|
||
|
||
# ==================== OA 会话(复用共享登录态) ====================
|
||
def is_oa_session_valid(session):
|
||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需启动浏览器)。"""
|
||
try:
|
||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||
resp = session.response
|
||
if resp is None or resp.status_code != 200:
|
||
return False
|
||
# 会话有效时返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});失效会被重定向到登录页返回 HTML
|
||
text = resp.text
|
||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||
except Exception as e:
|
||
logger.info("OA 会话已失效: %s", e)
|
||
return False
|
||
|
||
|
||
def get_oa_session():
|
||
"""从共享 oa_cookies.json 构建 OA 会话(SessionPage + ChromiumPage)。
|
||
缺失/失效抛 LoginRequiredError,提示先运行「37duOA登录」指令。"""
|
||
cookies = load_cookies(COOKIE_FILE_OA)
|
||
if not cookies:
|
||
raise LoginRequiredError("未找到 OA 登录态 cookies,请先调用「37duOA登录」指令完成登录后再重试。")
|
||
session = SessionPage()
|
||
session.set.cookies(cookies)
|
||
session.set.timeout(10)
|
||
if hasattr(session, 'session'):
|
||
session.session.headers.update({
|
||
"Referer": LIST_URL,
|
||
"X-Requested-With": "XMLHttpRequest",
|
||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||
})
|
||
if not is_oa_session_valid(session):
|
||
raise LoginRequiredError("OA 登录态已失效,请先重新调用「37duOA登录」指令完成登录后再重试。")
|
||
browser = ChromiumPage()
|
||
browser.set.cookies(cookies)
|
||
return browser, session
|
||
|
||
|
||
# ==================== HR 登录态(共享 cookies,只读不补登) ====================
|
||
class LoginRequiredError(Exception):
|
||
"""HR 登录态 cookies 缺失或失效,需先调用「37duHR登录」指令。"""
|
||
|
||
|
||
def _load_shared_hr_cookies():
|
||
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
return None
|
||
|
||
|
||
def get_hr_session():
|
||
"""构建 HR requests.Session(只读共享 cookies,缺失/失效抛 LoginRequiredError)。"""
|
||
cookies = _load_shared_hr_cookies()
|
||
if not cookies:
|
||
raise LoginRequiredError(
|
||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in cookies)
|
||
if not has_hr:
|
||
raise LoginRequiredError(
|
||
"共享 cookies 中无 hr.37du.co 登录态,请先调用「37duHR登录」指令完成登录后再重试。")
|
||
logger.info("复用共享 HR 登录态(hr.37du.co,%d 个 cookies)", len(cookies))
|
||
return _build_hr_session(cookies)
|
||
|
||
|
||
def _build_hr_session(cookies=None):
|
||
cookies = cookies or _load_shared_hr_cookies()
|
||
if not cookies:
|
||
raise LoginRequiredError(
|
||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||
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:
|
||
if c.get("domain") and c["domain"].endswith("hr.37du.co"):
|
||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||
return session
|
||
|
||
|
||
# ==================== 导出(fdId / searchId / 总数 / 导出) ====================
|
||
def _check_response(resp, action):
|
||
if resp is None:
|
||
raise RuntimeError(f"{action}失败,未获取到响应")
|
||
if resp.status_code != 200:
|
||
raise RuntimeError(f"{action}失败,状态码: {resp.status_code}")
|
||
|
||
|
||
def _resolve_query_date(query_date=None):
|
||
return query_date or datetime.now().strftime("%Y-%m-01")
|
||
|
||
|
||
def _build_filter_params(filter_idx, query_date=None):
|
||
day = _resolve_query_date(query_date)
|
||
# ge=不早于(包含起始日当天):申请日期 >= 当月1号
|
||
return {f"v0_{filter_idx}": "ge", f"v1_{filter_idx}": day}
|
||
|
||
|
||
def _get_cookies_with_domain(session):
|
||
cookies = []
|
||
try:
|
||
raw = session.session.cookies
|
||
for c in raw:
|
||
cookies.append({"name": c.name, "value": c.value, "domain": c.domain, "path": c.path or "/"})
|
||
except Exception:
|
||
cookies = load_cookies(COOKIE_FILE_OA) or []
|
||
return cookies
|
||
|
||
|
||
def get_fd_id_by_listening(session, browser=None):
|
||
own_browser = browser is None
|
||
if own_browser:
|
||
cookies = _get_cookies_with_domain(session)
|
||
if not cookies:
|
||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||
browser = ChromiumPage(ChromiumOptions())
|
||
browser.set.cookies(cookies)
|
||
try:
|
||
browser.listen.start()
|
||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||
browser.get(HOME_URL)
|
||
time.sleep(5)
|
||
# 兜底:若浏览器 cookies 失效会停在登录页,快速失败避免空等,且异常含『登录』可触发主流程自动重登
|
||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||
deadline = time.time() + 10
|
||
target = None
|
||
while time.time() < deadline:
|
||
req = browser.listen.wait(timeout=1)
|
||
if req and 'sysPortalNav.do' in req.url:
|
||
target = req
|
||
break
|
||
if target is None:
|
||
raise RuntimeError("超时未监听到菜单请求,请检查网络或登录态")
|
||
qs = parse_qs(urlparse(target.url).query)
|
||
fd_id = qs.get('fdId', [None])[0]
|
||
if not fd_id:
|
||
raise RuntimeError("菜单请求中未包含 fdId")
|
||
logger.info("动态获取到 fdId: %s", fd_id)
|
||
return fd_id
|
||
finally:
|
||
browser.listen.stop()
|
||
if own_browser:
|
||
browser.quit()
|
||
|
||
|
||
def get_search_id_from_menu(session, fd_id, menu_name=MENU_NAME_PARTICIPATE):
|
||
params = {"method": "portlet", "fdId": fd_id, "f_s": "sourcejs", "t": str(int(time.time() * 1000))}
|
||
session.get(f"{BASE_URL}{MENU_API_PATH}", params=params)
|
||
_check_response(session.response, "获取菜单")
|
||
data = session.response.json()
|
||
|
||
def find_item(items):
|
||
for item in items:
|
||
if item.get("text") == menu_name:
|
||
return item
|
||
if "children" in item:
|
||
found = find_item(item["children"])
|
||
if found:
|
||
return found
|
||
return None
|
||
|
||
items = data if isinstance(data, list) else data.get("children", [])
|
||
item = find_item(items)
|
||
if not item:
|
||
raise RuntimeError(f"菜单中未找到 '{menu_name}'")
|
||
qs = parse_qs(urlparse(urljoin(BASE_URL, item["href"])).query)
|
||
search_id = qs.get("searchId", [None])[0]
|
||
if not search_id:
|
||
raise RuntimeError("菜单链接中未包含 searchId")
|
||
logger.info("从菜单获取到 searchId: %s", search_id)
|
||
return search_id
|
||
|
||
|
||
def get_total_count(session, base_params, search_id, timestamp):
|
||
params = {"method": "result", "searchId": search_id, "j_timestamp": timestamp, **base_params}
|
||
session.get(SEARCH_URL, params=params, headers={"Referer": LIST_URL})
|
||
_check_response(session.response, "查询总数")
|
||
html = session.response.text
|
||
for pat in (r'exportNum:\s*"(\d+)"', r'总记录数[::]\s*(\d+)', r'共\s*(\d+)\s*条'):
|
||
m = re.search(pat, html)
|
||
if m:
|
||
total = int(m.group(1))
|
||
logger.info("获取到总记录数: %d", total)
|
||
return total
|
||
logger.warning("未找到总条数,默认为 0")
|
||
return 0
|
||
|
||
|
||
def export_all_data(session, base_params, total, columns, search_id, timestamp):
|
||
data = {
|
||
"method": "exportResult", "searchId": search_id, "j_timestamp": timestamp, **base_params,
|
||
"fdColumns": columns, "fdNum": str(total), "fdNumStart": "1", "fdNumEnd": str(total),
|
||
"fdKeepRtfStyle": "true", "checkIdValues": "",
|
||
}
|
||
session.post(SEARCH_URL, data=data, headers={"Referer": LIST_URL})
|
||
_check_response(session.response, "导出数据")
|
||
return session.response.content
|
||
|
||
|
||
# ==================== 读取 + 清洗去重 ====================
|
||
def _normalize_date_key(value):
|
||
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:
|
||
try:
|
||
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||
return (datetime(y, mo, d) - datetime(1899, 12, 30)).days
|
||
except ValueError:
|
||
return 0.0
|
||
return 0.0
|
||
|
||
|
||
def _date_display(value, wb):
|
||
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):
|
||
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}")
|
||
|
||
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)
|
||
|
||
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
|
||
|
||
|
||
# ==================== HR 参保记录核对 ====================
|
||
class HRSessionExpiredError(Exception):
|
||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||
|
||
|
||
def _si_is_expired(text):
|
||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||
|
||
|
||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||
def _si_query_batch(session, codes_batch):
|
||
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 _si_is_expired(resp.text):
|
||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||
return resp.json()
|
||
|
||
|
||
def _si_found_codes(response_json):
|
||
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):
|
||
"""返回这一批中『能查到参保记录』的工号集合;查询失败上抛,由调用方决定重登或标注异常。"""
|
||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||
|
||
|
||
def _si_preflight(session):
|
||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期/异常抛 LoginRequiredError 提示先运行登录指令。"""
|
||
try:
|
||
_si_query_batch(session, ["0"])
|
||
except HRSessionExpiredError as e:
|
||
raise LoginRequiredError(
|
||
f"预检发现 HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试: {e}")
|
||
except Exception as e:
|
||
# 网络超时也可能由 cookies 过期(重定向到登录页后加载超时)引发,同样按登录态失效处理
|
||
raise LoginRequiredError(
|
||
f"预检查询异常(可能 HR 登录态已过期),请先重新调用「37duHR登录」指令完成登录后再重试: {e}")
|
||
return session
|
||
|
||
|
||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".", session=None):
|
||
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。
|
||
|
||
session 由调用方预检后传入(复用,避免重复探测);为 None 时内部自行预检。
|
||
"""
|
||
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)
|
||
|
||
if session is None:
|
||
session = _si_preflight(get_hr_session())
|
||
found = set()
|
||
failed_codes = set()
|
||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||
try:
|
||
found |= _si_check_batch(session, batch)
|
||
except HRSessionExpiredError:
|
||
# 登录态失效时不自动补登,上抛提示先重新运行「37duHR登录」指令(避免大批误标异常)
|
||
raise LoginRequiredError(
|
||
f"HR 登录态已过期(第 {min(i + SI_BATCH_SIZE, len(unique_codes))}/{len(unique_codes)} 批),"
|
||
f"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||
except Exception as e:
|
||
# 网络超时/其它异常:宁可标注查询异常,也不当作『无记录』避免误判
|
||
logger.warning("参保记录查询失败(该批标注查询异常,需人工复核): %s", e)
|
||
failed_codes |= set(batch)
|
||
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()
|
||
if code in failed_codes:
|
||
val = "异常:参保记录查询失败,需人工复核"
|
||
else:
|
||
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
|
||
|
||
ws = out_wb.active
|
||
ws.title = "核对明细"
|
||
ws.append(headers + [SI_RESULT_COL])
|
||
for c in range(1, len(headers) + 2):
|
||
cell = 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):
|
||
ws.append(row)
|
||
if str(row[-1]).startswith("异常"):
|
||
for c in range(1, len(row) + 1):
|
||
cell = ws.cell(idx, c)
|
||
cell.fill = red_fill
|
||
if c == len(row):
|
||
cell.font = red_font
|
||
ws.freeze_panes = "A2"
|
||
ws.auto_filter.ref = ws.dimensions
|
||
if get_column_letter:
|
||
for c in range(1, len(headers) + 2):
|
||
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 export_employee_change_list(menu_name, filter_idx, columns, output_dir, query_date=None):
|
||
logger.info("社保增减名单核对流程开始,菜单:%s", menu_name)
|
||
base_params = {**DEFAULT_FIXED_PARAMS, **_build_filter_params(filter_idx, query_date)}
|
||
|
||
# 预检 HR 登录态:缺失/失效抛 LoginRequiredError 提示先运行「37duHR登录」指令
|
||
hr_session = _si_preflight(get_hr_session())
|
||
|
||
# 获取 OA 会话:缺失/失效抛 LoginRequiredError 提示先运行「37duOA登录」指令
|
||
browser, session = get_oa_session()
|
||
try:
|
||
fd_id = get_fd_id_by_listening(session, browser)
|
||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||
timestamp = str(int(time.time() * 1000))
|
||
total = get_total_count(session, base_params, search_id, timestamp)
|
||
if total == 0:
|
||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||
return ""
|
||
|
||
logger.info("开始导出 %d 条记录...", total)
|
||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||
output_path = os.path.abspath(os.path.join(
|
||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||
with open(output_path, "wb") as f:
|
||
f.write(content)
|
||
logger.info("导出完成,文件保存为:%s", output_path)
|
||
|
||
headers, rows, emp_col = _read_and_clean(output_path)
|
||
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,
|
||
session=hr_session)
|
||
try:
|
||
os.remove(output_path)
|
||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||
except Exception:
|
||
pass
|
||
return final_path
|
||
except Exception as e:
|
||
logger.error("导出过程出错: %s", e)
|
||
# 登录态失效(OA/HR):直接上抛,提示先运行对应登录指令,不自动补登
|
||
raise
|
||
finally:
|
||
if browser is not None:
|
||
try:
|
||
browser.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def export_participation(output_dir=".", query_date=None):
|
||
return export_employee_change_list(
|
||
MENU_NAME_PARTICIPATE, FILTER_IDX_PARTICIPATE, DEFAULT_EXPORT_COLUMNS, output_dir, query_date)
|
||
|
||
|
||
def export_suspension(output_dir=".", query_date=None):
|
||
return export_employee_change_list(
|
||
MENU_NAME_SUSPEND, FILTER_IDX_SUSPEND, DEFAULT_EXPORT_COLUMNS_SUSPEND, output_dir, query_date)
|
||
|
||
|
||
# ==================== 结果推送(写全局变量 messages,由「37du钉钉单聊推送」指令发送) ====================
|
||
def _read_abnormal(xlsx_path, label):
|
||
"""读取标注表,返回 (总条数, 异常行列表)。异常行形如 [工号, 申请人/姓名, 结果] 说明文本。"""
|
||
if not os.path.exists(xlsx_path):
|
||
return 0, []
|
||
ws = _load_workbook(xlsx_path).active
|
||
rows = list(ws.iter_rows(values_only=True))
|
||
headers = [str(h) if h is not None else "" for h in rows[0]]
|
||
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
|
||
res_col = headers.index(SI_RESULT_COL)
|
||
name_candidates = ("参保人",) if label == "参保" else ("停保人姓名",)
|
||
name_col = next((i for i, h in enumerate(headers) if h in name_candidates), None)
|
||
abnormal = []
|
||
for r in rows[1:]:
|
||
val = r[res_col] if res_col < len(r) else ""
|
||
if val and str(val).startswith("异常"):
|
||
emp = str(r[emp_col]) if emp_col is not None and emp_col < len(r) else ""
|
||
name = str(r[name_col]) if name_col is not None and name_col < len(r) else ""
|
||
abnormal.append(f" · 工号{emp} {name} —— {val}")
|
||
return len(rows) - 1, abnormal
|
||
|
||
|
||
def build_push_text(part_path, susp_path):
|
||
p_total, p_abn = _read_abnormal(part_path, "参保")
|
||
s_total, s_abn = _read_abnormal(susp_path, "停保")
|
||
lines = ["【社保增减名单核对结果】"]
|
||
lines.append(f"参保表:共 {p_total} 条,异常 {len(p_abn)} 条")
|
||
if p_abn:
|
||
lines.extend(p_abn)
|
||
else:
|
||
lines.append(" 无异常")
|
||
lines.append("")
|
||
lines.append(f"停保表:共 {s_total} 条,异常 {len(s_abn)} 条")
|
||
if s_abn:
|
||
lines.extend(s_abn)
|
||
else:
|
||
lines.append(" 无异常")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _set_glv(name, value):
|
||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||
try:
|
||
glv[name] = value
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _package_files(paths, save_dir):
|
||
"""单文件直接返回原路径;多文件打包 zip(时间戳命名);无有效文件返回 None。"""
|
||
exist_files = [p for p in paths if p and os.path.exists(p)]
|
||
if not exist_files:
|
||
return None
|
||
if len(exist_files) == 1:
|
||
return exist_files[0]
|
||
_ensure_dir(save_dir)
|
||
zip_path = os.path.join(
|
||
save_dir,
|
||
f"社保增减名单_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip",
|
||
)
|
||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||
for fp in exist_files:
|
||
zf.write(fp, os.path.basename(fp))
|
||
logger.info("多文件已打包 %d 个到 %s", len(exist_files), zip_path)
|
||
return zip_path
|
||
|
||
|
||
def _build_push_messages(part_path, susp_path, save_dir):
|
||
"""构造 dws 单聊推送消息:先发文本汇总,再发表文件(单文件直接推,多文件打包 zip)。"""
|
||
messages = [{
|
||
"msg_type": "text",
|
||
"name": PUSH_RECEIVER_NAME,
|
||
"user_id": PUSH_RECEIVER_ID,
|
||
"content": build_push_text(part_path, susp_path),
|
||
"file_path": "",
|
||
}]
|
||
file_target = _package_files([part_path, susp_path], save_dir)
|
||
if file_target:
|
||
messages.append({
|
||
"msg_type": "file",
|
||
"name": PUSH_RECEIVER_NAME,
|
||
"user_id": PUSH_RECEIVER_ID,
|
||
"content": "",
|
||
"file_path": file_target,
|
||
})
|
||
return messages
|
||
|
||
|
||
# ==================== 主入口 ====================
|
||
def main():
|
||
load_dotenv()
|
||
args = sys.argv[1:]
|
||
output_dir = os.getenv("social_change_output_dir") or r"D:\资料\人资\员工社保增减名单"
|
||
os.makedirs(output_dir, exist_ok=True)
|
||
query_date = None
|
||
change_type = "全部"
|
||
for a in args:
|
||
if re.match(r"^\d{4}-\d{2}-\d{2}$", a):
|
||
query_date = a
|
||
elif a in ("参保", "participate"):
|
||
change_type = "参保"
|
||
elif a in ("停保", "suspend"):
|
||
change_type = "停保"
|
||
|
||
if query_date is None:
|
||
query_date = os.getenv("social_change_query_date") or None
|
||
|
||
part_path = ""
|
||
susp_path = ""
|
||
if change_type in ("参保", "全部"):
|
||
part_path = export_participation(output_dir=output_dir, query_date=query_date)
|
||
if change_type in ("停保", "全部"):
|
||
susp_path = export_suspension(output_dir=output_dir, query_date=query_date)
|
||
|
||
# 写全局变量 messages(dws 单聊推送:文本汇总 + 表文件,单文件直接推/多文件打包 zip)
|
||
if part_path or susp_path:
|
||
messages = _build_push_messages(part_path, susp_path, output_dir)
|
||
_set_glv("messages", messages)
|
||
logger.info("已写全局变量 messages(%d 条),交由「37du钉钉单聊推送」指令发送给 %s(%s)",
|
||
len(messages), PUSH_RECEIVER_NAME, PUSH_RECEIVER_ID)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|