refactor: 重构雇主险业务,适配多类别拆分与影刀脚本整合
1. 重构ehr/common/config.py与employer_insurance/config.py,新增多类别配置与工具函数 2. 重写employer_insurance.py,支持按类别调度处理 3. 新增影刀共享模块与业务脚本,统一RPA开发规范 4. 移除旧版冗余的影刀脚本文件
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,525 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal.py
|
||||
@Description: 周考勤异常处理(影刀单文件版)- 独立自 app/service/hrbp/ehr/attendance/attendance_abnormal.py,
|
||||
业务逻辑完全一致:HR 登录态(共享登录)→ 分页拉取当月未调整考勤异常 → 导出 Excel 底稿
|
||||
→ 分级分类(轻微直接处理 / 其余钉钉核实)→ 按「姓名-工号」合并推送当事人
|
||||
→ 生成处理汇总报表 → 推送给 人资专用号 留痕。
|
||||
@Version: 1.1.0
|
||||
|
||||
登录(共享登录态,本脚本为单文件自包含):
|
||||
- 登录态统一由「37duHR登录」影刀自定义指令写入共享 cookies:
|
||||
%LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json
|
||||
- 本脚本仅读取该 cookies 文件,不 import 任何共享模块;缺失/失效时
|
||||
报错提示先运行登录指令(影刀流程开头请先拖入「37duHR登录」指令)。
|
||||
|
||||
钉钉推送(消息生成与发送解耦,本脚本不内联发送):
|
||||
- 本脚本不内联任何发送逻辑,也不 import 共享推送模块;
|
||||
- 运行后会同步把待推送的 messages(字典列表)写入影刀全局变量
|
||||
glv['messages'](无数据时置为空列表),由流程拖「37du钉钉推送」指令
|
||||
完成发送(含 target 走 OCR 单聊,不含 target 走群机器人);
|
||||
- 处理汇总报表文本写入全局变量 glv['report'],由流程推送给 人资专用号。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
|
||||
dingtalk_push_enabled=true|false(默认 false,是否启用钉钉推送,总开关)
|
||||
dingtalk_notify_target=人资专用号钉钉联系人姓名(处理汇总报表推送对象,如 夏一平)
|
||||
attendance_save_dir=(可选)Excel 导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
"(钉钉推送相关依赖 pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/"
|
||||
"rapidocr-onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一,见 app/common/app_paths.py) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 默认保存目录(可用环境变量覆盖)
|
||||
SAVE_DIR = os.getenv("attendance_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供的考勤异常字段,其余字段保留原样)
|
||||
COL_MAP = {
|
||||
"abnormal_id": "异常ID",
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"base_code": "工号",
|
||||
"first_type_name": "职位序列",
|
||||
"work_day": "考勤日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"abnormal_minute": "异常时长(分钟)",
|
||||
}
|
||||
|
||||
SHOW_ORDER = [
|
||||
"异常ID", "员工姓名", "工号", "职位序列", "考勤日期", "班次", "异常类型", "异常时长(分钟)",
|
||||
]
|
||||
|
||||
# 考勤异常调整状态过滤(本次只查询「未调整」);0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有
|
||||
IS_ADJUSTED = "0"
|
||||
# 钉钉推送总开关(默认关闭仅生成报表打印)
|
||||
DINGTALK_PUSH_ENABLED = "true"
|
||||
# 人资专用号:处理汇总报表推送对象;未配置则跳过汇总推送
|
||||
DINGTALK_NOTIFY_TARGET = "夏一平"
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件(由「37duHR登录」指令写入);缺失时提示先运行登录指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
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 "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
# ==================== HR 接口 ====================
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": abnormal_type,
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 业务规则(与 app 版一致) ====================
|
||||
def current_month_range(today=None):
|
||||
"""返回当月查询范围:(当月1日, 今天)。"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def classify_abnormal(item):
|
||||
"""判断该条异常是否需要钉钉推送。
|
||||
迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常,直接处理);
|
||||
迟到/早退 >= 30 分钟 或 其他类型(旷工/工时不足/漏打卡等)→ 推送。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item):
|
||||
"""判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
|
||||
|
||||
def build_notify_text(items):
|
||||
"""按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。"""
|
||||
first = items[0]
|
||||
lines = [
|
||||
"【考勤异常核实通知】",
|
||||
f"姓名:{first.get('STAFF_NAME', '')}",
|
||||
f"工号:{first.get('base_code', '')}",
|
||||
f"共 {len(items)} 条考勤异常,请逐条确认:",
|
||||
]
|
||||
for idx, item in enumerate(items, 1):
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute")
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute not in ("", None):
|
||||
confirm_item = f"{abnormal}{minute}分钟"
|
||||
else:
|
||||
confirm_item = abnormal
|
||||
lines.append(
|
||||
f"{idx}. 考勤日期:{item.get('work_day', '')}|班次:{item.get('bc_name', '')}"
|
||||
f"|异常类型:{abnormal}|异常时长:{minute}分钟"
|
||||
)
|
||||
lines.append(f" 请确认本次{confirm_item}真实情况:{abnormal}/漏打卡/外出/其他")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ==================== 导出 Excel ====================
|
||||
def export_excel(data, save_dir, month_str):
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤异常_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("考勤异常数据:%d 条", len(data))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 钉钉推送(总开关控制) ====================
|
||||
def push_abnormal(items):
|
||||
"""按「工号-姓名」分组,合并为 messages 字典列表,写入影刀全局变量 messages,
|
||||
由流程拖「37du钉钉推送」指令发送(本脚本不内联发送,保持单文件自包含)。
|
||||
推送目标(target)使用工号作为钉钉搜索关键字,避免同名人员误发;
|
||||
会话标题校验名(display_name)传姓名(钉钉标题显示姓名而非工号)。
|
||||
返回 (待推送条数, 失败数=0)。
|
||||
"""
|
||||
groups = {}
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
key = (it.get("base_code", "") or "", name)
|
||||
groups.setdefault(key, []).append(it)
|
||||
|
||||
messages = [
|
||||
{"target": _code or _name, "display_name": _name, "text": build_notify_text(group)}
|
||||
for (_code, _name), group in groups.items()
|
||||
]
|
||||
# 写入影刀全局变量,供流程「37du钉钉推送」指令读取(无数据也置空,避免 NameError)
|
||||
_set_glv('messages', messages)
|
||||
logger.info("当事人消息已生成并写入全局变量 messages:共 %d 条(由流程推送)", len(messages))
|
||||
return len(messages), 0
|
||||
|
||||
|
||||
def push_report(report):
|
||||
"""生成处理汇总报表文本并写入全局变量 report(未配置目标则跳过)。
|
||||
由流程拖「37du钉钉推送」指令推送给 人资专用号(本脚本不内联发送)。
|
||||
"""
|
||||
if not DINGTALK_NOTIFY_TARGET:
|
||||
logger.warning("未配置 dingtalk_notify_target,跳过汇总报表推送")
|
||||
return False
|
||||
_set_glv('report', report)
|
||||
logger.info("汇总报表已生成并写入全局变量 report(目标:%s,由流程推送)", DINGTALK_NOTIFY_TARGET)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 处理汇总报表(推送前生成最终结果) ====================
|
||||
def generate_report(data, handled_list, func_list, non_func_list, save_path, begin, end):
|
||||
lines = []
|
||||
lines.append("=" * 60)
|
||||
lines.append("周考勤异常处理报表")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"查询范围:{begin} ~ {end}")
|
||||
lines.append(f"考勤异常总数:{len(data)} 条")
|
||||
lines.append(f"直接处理(轻微,迟到/早退<30分钟):{len(handled_list)} 条")
|
||||
lines.append(f"非职能人员(不推送):{len(non_func_list)} 条")
|
||||
lines.append(f"待通知(职能人员):{len(func_list)} 条")
|
||||
lines.append(f"导出文件:{save_path}")
|
||||
lines.append(f"钉钉推送:{'已启用' if DINGTALK_PUSH_ENABLED else '未启用'}")
|
||||
lines.append("-" * 60)
|
||||
lines.append("【待通知明细(职能人员,需钉钉核实)】")
|
||||
if func_list:
|
||||
for i, it in enumerate(func_list, 1):
|
||||
lines.append(
|
||||
f"{i}. {it.get('STAFF_NAME','')}({it.get('base_code','')})"
|
||||
f" | {it.get('work_day','')} | 班次:{it.get('bc_name','')}"
|
||||
f" | 异常:{it.get('abnormal','')} | {it.get('abnormal_minute','')}分钟")
|
||||
else:
|
||||
lines.append(" 无")
|
||||
lines.append("【直接处理明细(轻微异常)】")
|
||||
if handled_list:
|
||||
for i, it in enumerate(handled_list, 1):
|
||||
lines.append(
|
||||
f"{i}. {it.get('STAFF_NAME','')}({it.get('base_code','')})"
|
||||
f" | {it.get('work_day','')} | 异常:{it.get('abnormal','')}"
|
||||
f" | {it.get('abnormal_minute','')}分钟")
|
||||
else:
|
||||
lines.append(" 无")
|
||||
lines.append("=" * 60)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_attendance_abnormal(save_dir=None, month=None):
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
|
||||
# 1. 会话:复用共享登录态,必要时补登
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,自动补登")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
info = {"userId": user_id, "rootId": treecode}
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
|
||||
# 2. 查询范围:默认当月
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s,调整状态:%s =====", begin, end, IS_ADJUSTED or "所有")
|
||||
|
||||
# 3. 拉取数据
|
||||
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end, IS_ADJUSTED)
|
||||
if not data:
|
||||
logger.info("当月无考勤异常数据,跳过导出与推送")
|
||||
return None
|
||||
|
||||
# 4. 导出 Excel 底稿
|
||||
month_str = month or date.today().strftime("%Y-%m")
|
||||
path = export_excel(data, save_dir, month_str)
|
||||
|
||||
# 5. 分级分类
|
||||
push_list = [it for it in data if classify_abnormal(it)]
|
||||
handled_list = [it for it in data if not classify_abnormal(it)]
|
||||
func_list = [it for it in push_list if is_func_staff(it)]
|
||||
non_func_list = [it for it in push_list if not is_func_staff(it)]
|
||||
|
||||
# 6. 生成处理汇总报表(最终结果,推送前形成)
|
||||
report = generate_report(data, handled_list, func_list, non_func_list, path, begin, end)
|
||||
print("\n" + report + "\n")
|
||||
|
||||
# 7. 钉钉推送(总开关控制)
|
||||
push_count, fail_count = 0, 0
|
||||
if DINGTALK_PUSH_ENABLED:
|
||||
if func_list:
|
||||
push_count, fail_count = push_abnormal(func_list)
|
||||
else:
|
||||
logger.info("无需推送的异常,跳过当事人钉钉通知")
|
||||
logger.info("当事人推送完成:成功 %d 条,失败 %d 条", push_count, fail_count)
|
||||
push_report(report)
|
||||
else:
|
||||
logger.info("钉钉推送未启用(dingtalk_push_enabled!=true),仅生成报表,未发送任何钉钉消息")
|
||||
|
||||
# 8. 汇总日志
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤异常处理汇总】")
|
||||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||||
logger.info(" 直接处理(轻微,无需通知):%d 条", len(handled_list))
|
||||
logger.info(" 非职能人员(不推送):%d 条", len(non_func_list))
|
||||
logger.info(" 待通知(职能人员):%d 条,合并为 %d 条推送", len(func_list), push_count)
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
return path
|
||||
|
||||
|
||||
def main(args=None):
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段 save_dir(导出目录)、month("YYYY-MM",默认当月)
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
# 始终定义影刀全局变量 messages(默认空列表),避免后续流程步骤引用时 NameError
|
||||
_set_glv('messages', [])
|
||||
save_dir = args.get("save_dir") or (sys.argv[1] if len(sys.argv) > 1 else None)
|
||||
month = args.get("month") or (sys.argv[2] if len(sys.argv) > 2 else None)
|
||||
try:
|
||||
out = handle_attendance_abnormal(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:当月无数据 =====")
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("考勤异常处理失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,996 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal_monthly.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-18
|
||||
@Description: EHR 系统月考勤异常处理(影刀版,单文件自包含)——复刻 app 版
|
||||
abnormal_check.py 业务逻辑:对上月考勤异常做三重复核(结合 考勤异常/请假/加班/
|
||||
打卡/排班 五类接口),输出多 Sheet Excel 报告。独立于周考勤异常处理流程。
|
||||
|
||||
检查1:已确认异常(is_adjusted=2)的日期,是否存在请假流程?
|
||||
—— 可能存在「提前确认后请假」导致仍为考勤异常的情况;
|
||||
检查2:休息日加班(类型3)且加班天数为 0.5 天,当日打卡是否按考勤班段正常打卡(无漏打卡)?
|
||||
检查3:员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)。
|
||||
|
||||
场景定位(月度定时任务,每月 1 号 14:00-17:00 由影刀调度触发,传上月月份参数):
|
||||
- 登录:登录态统一由「37duHR登录」指令写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
本脚本为单文件自包含,仅读取该 cookies 文件,不 import 任何共享模块。
|
||||
- 本模块不涉及花名册/浏览器页面操作,纯接口调用 + 数据校验 + 导出报告。
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 内联 HR 接口(getCurUserInfo / 考勤异常 / 请假 / 加班 / 打卡 / 排班),不依赖 app 包。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
|
||||
attendance_check_save_dir=(可选)报告导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
attendance_check_month=(可选)查询月份 "YYYY-MM",默认当月
|
||||
|
||||
运行:
|
||||
- 影刀「调用模块」:main({"save_dir": ..., "month": "2026-08"})
|
||||
- 直接运行:python attendance_abnormal_monthly.py [save_dir] [month]
|
||||
例:python attendance_abnormal_monthly.py "D:\\资料\\人资\\考勤异常" "2026-08"
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令(yingdao/share/hr_login.py)写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
KQ_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 输出配置(与 app 版一致) ----------
|
||||
# 默认保存目录(与周考勤异常导出目录保持一致)
|
||||
SAVE_DIR = os.getenv("attendance_check_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
IS_ADJUSTED_CONFIRMED = "2" # 已确认异常(检查1)
|
||||
IS_ADJUSTED_OPEN = "0" # 未调整异常(检查3并集之一)
|
||||
|
||||
# 加班类型:空=全部、1=延时加班、2=法定假日加班、3=休息日加班
|
||||
WORK_OVERTIME_TYPE_REST = "3"
|
||||
|
||||
# 休息日半天加班判定阈值(ot_days / sys_ot_days / plan_ot_days ≈ 0.5)
|
||||
HALF_DAY = 0.5
|
||||
EPS = 1e-6
|
||||
|
||||
# 打卡与班段边界匹配容差(分钟):上班打卡在班段开始前后、下班打卡在班段结束前后
|
||||
PUNCH_TOLERANCE_MIN = 60
|
||||
|
||||
# 假期类型编码 → 名称(与 app 版 common/config.VACATION_TYPE_MAP 一致)
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
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 _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 "
|
||||
"python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== HR 接口(内联,与 app 版 hr_api 一致) ====================
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
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 "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE, is_adjusted=""):
|
||||
"""请求单页考勤异常数据。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": "",
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页请假记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"begin_date": "",
|
||||
"end_date": "",
|
||||
"sqlId": "select_kqLeave_record",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"post_no": "",
|
||||
"source": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"processing_date": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "operat_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "请假查询")
|
||||
|
||||
|
||||
def fetch_all_leave(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部请假记录(空工号=全量)。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("请假查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("请假查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("请假查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_overtime_page(session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type="", treecode="cq37du",
|
||||
page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页加班记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_overtime_detail_select",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"BPM_STATUS": "",
|
||||
"post_no": "",
|
||||
"postName": "",
|
||||
"source": "",
|
||||
"IS_SUBSIDY": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"WORK_OVERTIME_TYPE": work_overtime_type,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "OPERATE_TIME",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "加班查询")
|
||||
|
||||
|
||||
def fetch_all_overtime(session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type="", treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部加班记录(空工号=全量)。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("加班查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("加班查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("加班查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_kq_data_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页打卡记录数据。"""
|
||||
params = {
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_data_query",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"kqStaffIds": "",
|
||||
"staff_id": "",
|
||||
"staff_name": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"kq_type": "",
|
||||
"post_type": "",
|
||||
"person_status": "",
|
||||
"dkstatus": "",
|
||||
"addr_status": " ",
|
||||
"struTreeCode": treecode,
|
||||
"belongUnitStruId": "",
|
||||
"work_day_begin": start_time,
|
||||
"work_day_end": end_time,
|
||||
"base_code": base_code,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "打卡查询")
|
||||
|
||||
|
||||
def fetch_all_kq_data(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部打卡记录。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("打卡查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("打卡查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("打卡查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("打卡查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部排班数据。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 工具函数(与 app 版 abnormal_check 一致) ====================
|
||||
def current_month_range(today=None):
|
||||
"""返回当月的查询日期范围 (开始日期, 结束日期)。开始=当月1日,结束=今天。"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _get(rec, *keys, default=""):
|
||||
"""从记录中取第一个存在的键的值(兼容字段大小写差异)。"""
|
||||
for k in keys:
|
||||
if rec.get(k) is not None and rec.get(k) != "":
|
||||
return rec[k]
|
||||
return default
|
||||
|
||||
|
||||
def _to_date_str(value):
|
||||
"""将接口返回的日期/时间值归一化为 'YYYY-MM-DD'(取前10位)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
return s[:10] if len(s) >= 10 else s
|
||||
|
||||
|
||||
def _float(value, default=0.0):
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _is_half_day_ot(rec):
|
||||
"""判断加班记录是否为休息日半天(0.5 天)。依次取 ot_days / sys_ot_days / plan_ot_days。"""
|
||||
for key in ("ot_days", "sys_ot_days", "plan_ot_days"):
|
||||
val = rec.get(key)
|
||||
if val is not None and val != "":
|
||||
if abs(_float(val) - HALF_DAY) <= EPS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _leave_type_name(rec):
|
||||
"""从请假记录中提取假期类型名称(兼容编码与名称两种输入)。"""
|
||||
raw = _get(rec, "leave_type", "vacation_type", "sub_type", "LEAVE_TYPE")
|
||||
raw = str(raw).strip()
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def _staff_name(rec):
|
||||
"""兼容取员工姓名字段(不同接口命名不同)。"""
|
||||
return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default=""))
|
||||
|
||||
|
||||
def _punch_analysis(records):
|
||||
"""对某日打卡流水做统计(打卡记录无法可靠区分上下班,按最早=上班、最晚=下班)。"""
|
||||
times = []
|
||||
for rec in records:
|
||||
t = _get(rec, "kq_time", "kqTime", "punch_time")
|
||||
if t:
|
||||
times.append(str(t))
|
||||
times.sort()
|
||||
if not times:
|
||||
return {"count": 0, "first": "", "last": ""}
|
||||
return {"count": len(times), "first": times[0], "last": times[-1]}
|
||||
|
||||
|
||||
def _to_minutes(value):
|
||||
"""将 "HH:MM[:SS]" 时间串转为当日分钟数;解析失败返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})(?::(\d{2}))?$", s)
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2))
|
||||
|
||||
|
||||
def _parse_shift_time(bc_time):
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
|
||||
if not bc_time:
|
||||
return None, None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None, None
|
||||
start = int(m.group(1)) * 60 + int(m.group(2))
|
||||
end = int(m.group(3)) * 60 + int(m.group(4))
|
||||
return start, end
|
||||
|
||||
|
||||
def _extract_day_shift(shift_rows, date_str):
|
||||
"""从某员工排班记录中提取指定日期的班段信息(动态列 key 为 "YYYY-MM-DD_bc_name/bc_time/paiban_type")。"""
|
||||
info = {"bc_name": "", "bc_time": "", "paiban_type": ""}
|
||||
for rec in shift_rows:
|
||||
name = _get(rec, f"{date_str}_bc_name", default="")
|
||||
time_ = _get(rec, f"{date_str}_bc_time", default="")
|
||||
paiban = _get(rec, f"{date_str}_paiban_type", default="")
|
||||
if name or time_ or paiban:
|
||||
info = {"bc_name": str(name), "bc_time": str(time_), "paiban_type": str(paiban)}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
def _judge_punch_by_shift(p, shift_info):
|
||||
"""结合班段时间判断当日打卡是否正常(容差 PUNCH_TOLERANCE_MIN 分钟)。"""
|
||||
start_min, end_min = _parse_shift_time(shift_info.get("bc_time", ""))
|
||||
count = p["count"]
|
||||
tol = PUNCH_TOLERANCE_MIN
|
||||
|
||||
# 无班段(休息日排班):按打卡次数判断
|
||||
if start_min is None or end_min is None:
|
||||
if count >= 2:
|
||||
return "正常(有上班+下班打卡)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
|
||||
# 有班段:最早打卡覆盖班段开始、最晚打卡覆盖班段结束
|
||||
first_min = _to_minutes(p["first"])
|
||||
last_min = _to_minutes(p["last"])
|
||||
first_ok = first_min is not None and first_min <= start_min + tol
|
||||
last_ok = last_min is not None and last_min >= end_min - tol
|
||||
if count >= 2 and first_ok and last_ok:
|
||||
return "正常(按班段上班/下班打卡齐全)"
|
||||
if count == 0:
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(打卡未按班段覆盖上下班)"
|
||||
|
||||
|
||||
# ==================== 会话校验 & 数据获取(与 app 版一致) ====================
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
return session, user_id, treecode
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return session, user_id, treecode
|
||||
|
||||
|
||||
def _fetch_all_data(session, user_id, treecode, begin, end):
|
||||
"""一次性拉取三项检查所需的基础数据(考勤异常 / 请假 / 休息日加班)。"""
|
||||
logger.info("===== 月考勤异常三查,日期范围:%s ~ %s =====", begin, end)
|
||||
|
||||
abnormal_confirmed = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_CONFIRMED
|
||||
)
|
||||
abnormal_open = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_OPEN
|
||||
)
|
||||
logger.info("已确认异常 %d 条,未调整异常 %d 条", len(abnormal_confirmed), len(abnormal_open))
|
||||
|
||||
# 请假:空工号 = 查询全部员工(返回记录自带 base_code)
|
||||
leaves = fetch_all_leave(session, user_id, "", begin, end)
|
||||
logger.info("请假记录(全部员工)%d 条", len(leaves))
|
||||
|
||||
# 休息日加班:空工号 = 查询全部员工
|
||||
rest_overtime = fetch_all_overtime(
|
||||
session, user_id, "", begin, end, WORK_OVERTIME_TYPE_REST
|
||||
)
|
||||
logger.info("休息日加班记录(全部员工)%d 条", len(rest_overtime))
|
||||
|
||||
return {
|
||||
"abnormal_confirmed": abnormal_confirmed,
|
||||
"abnormal_open": abnormal_open,
|
||||
"leaves": leaves,
|
||||
"rest_overtime": rest_overtime,
|
||||
}
|
||||
|
||||
|
||||
def _build_leave_set(leaves, need_full_day=False):
|
||||
"""把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。
|
||||
|
||||
need_full_day=True 时只保留整日请假(leave_days>=1)的每一天;
|
||||
否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。
|
||||
"""
|
||||
index = {}
|
||||
for rec in leaves:
|
||||
code = str(_get(rec, "base_code")).strip()
|
||||
start = _to_date_str(_get(rec, "start_time", "begin_date"))
|
||||
end = _to_date_str(_get(rec, "end_time", "end_date"))
|
||||
leave_days = _float(rec.get("leave_days"))
|
||||
if not code or not start or not end:
|
||||
continue
|
||||
if need_full_day and leave_days < 1:
|
||||
continue
|
||||
try:
|
||||
cur = datetime.strptime(start, "%Y-%m-%d").date()
|
||||
end_d = datetime.strptime(end, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
continue
|
||||
if end_d < cur:
|
||||
continue
|
||||
step = timedelta(days=1)
|
||||
while cur <= end_d:
|
||||
index[(code, cur.strftime("%Y-%m-%d"))] = rec
|
||||
cur += step
|
||||
return index
|
||||
|
||||
|
||||
# ==================== 检查1:已确认异常 × 请假流程 ====================
|
||||
def check_leave_after_confirm(abnormal_confirmed, leave_index):
|
||||
"""已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。"""
|
||||
rows = []
|
||||
for ab in abnormal_confirmed:
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = leave_index.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"考勤日期": work_day,
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假起止": f"{_to_date_str(_get(leave_rec, 'start_time', 'begin_date'))} ~ "
|
||||
f"{_to_date_str(_get(leave_rec, 'end_time', 'end_date'))}",
|
||||
"问题说明": "该日期已确认考勤异常,但同时存在请假流程,可能为「提前确认后请假」仍为异常",
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查2:休息日半天加班 × 打卡校验(结合排班班段) ====================
|
||||
def check_rest_day_half_day_punch(session, user_id, treecode, rest_overtime, begin, end):
|
||||
"""休息日加班(类型3)且加班天数为 0.5 天时,校验当日打卡是否按考勤班段正常打卡。"""
|
||||
rows = []
|
||||
half_ots = [ot for ot in rest_overtime if _is_half_day_ot(ot)]
|
||||
logger.info("休息日半天加班 %d 条,逐一校验打卡(结合排班班段)", len(half_ots))
|
||||
|
||||
# 按工号缓存排班记录,避免重复请求
|
||||
shift_cache = {}
|
||||
|
||||
for ot in half_ots:
|
||||
code = str(_get(ot, "base_code")).strip()
|
||||
ot_date = _to_date_str(_get(ot, "OT_DATE", "ot_date"))
|
||||
if not code or not ot_date:
|
||||
continue
|
||||
kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode)
|
||||
|
||||
# 拉取该员工排班(缓存),取加班日的班段
|
||||
if code not in shift_cache:
|
||||
shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode)
|
||||
shift_info = _extract_day_shift(shift_cache.get(code, []), ot_date)
|
||||
|
||||
p = _punch_analysis(kq)
|
||||
judge = _judge_punch_by_shift(p, shift_info)
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ot),
|
||||
"工号": code,
|
||||
"加班日期": ot_date,
|
||||
"加班天数": _get(ot, "ot_days", "sys_ot_days", "plan_ot_days", default="0.5"),
|
||||
"排班班次": shift_info["bc_name"],
|
||||
"排班班段时间": shift_info["bc_time"],
|
||||
"计划时段": f"{_get(ot, 'PLAN_START_TIME') or _get(ot, 'FINAL_START_TIME')} ~ "
|
||||
f"{_get(ot, 'PLAN_END_TIME') or _get(ot, 'FINAL_END_TIME')}",
|
||||
"上班打卡": p["first"],
|
||||
"下班打卡": p["last"],
|
||||
"打卡次数": p["count"],
|
||||
"判定": judge,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查3:整日请假 × 考勤异常 → 提示 ====================
|
||||
def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
|
||||
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。"""
|
||||
rows = []
|
||||
|
||||
# 整日请假日期索引 {(code, date): leave_rec}
|
||||
full_day_leave = _build_leave_set(leaves, need_full_day=True)
|
||||
if not full_day_leave:
|
||||
logger.info("无整日请假记录,检查3跳过")
|
||||
return rows
|
||||
|
||||
# 异常并集(同一员工同一日期可能同时有未调整/已确认,各自输出一条便于核查)
|
||||
for ab in list(abnormal_open) + list(abnormal_confirmed):
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = full_day_leave.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
is_adjusted = str(ab.get("is_adjusted", ""))
|
||||
status = "确认异常" if is_adjusted == "2" else ("未调整" if is_adjusted == "0" else "异常")
|
||||
hint = f"该员工{work_day}考勤状态存在异常"
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"请假日期": work_day,
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假天数": _get(leave_rec, "leave_days"),
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"异常状态": status,
|
||||
"提示": hint,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出多 Sheet Excel 报告 ====================
|
||||
def export_report(results, save_dir, month_str):
|
||||
"""将三项检查结果导出为多 Sheet Excel 报告(无数据的 Sheet 也保留表头便于对照)。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"月考勤异常三查_{month_str}_{ts}.xlsx"))
|
||||
|
||||
sheet_cfg = [
|
||||
("检查1_确认异常有请假", "check1", [
|
||||
"员工姓名", "工号", "考勤日期", "异常类型", "请假类型", "请假起止", "问题说明"]),
|
||||
("检查2_休息日半天打卡", "check2", [
|
||||
"员工姓名", "工号", "加班日期", "加班天数", "排班班次", "排班班段时间", "计划时段",
|
||||
"上班打卡", "下班打卡", "打卡次数", "判定"]),
|
||||
("检查3_整日请假有异常", "check3", [
|
||||
"员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "异常状态", "提示"]),
|
||||
]
|
||||
|
||||
c1 = results.get("check1", [])
|
||||
c2 = results.get("check2", [])
|
||||
c3 = results.get("check3", [])
|
||||
|
||||
# 汇总行
|
||||
summary = [
|
||||
{"检查项": "检查1:确认异常日期存在请假流程", "条数": len(c1)},
|
||||
{"检查项": "检查2:休息日半天加班打卡校验", "条数": len(c2)},
|
||||
{"检查项": "检查3:整日请假当日仍有考勤异常", "条数": len(c3)},
|
||||
]
|
||||
summary[1]["备注"] = "「判定」列中 漏打卡 需人工复核"
|
||||
summary[0]["备注"] = "可能为「提前确认后请假」仍为异常"
|
||||
|
||||
try:
|
||||
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
for sheet_name, key, cols in sheet_cfg:
|
||||
data = results.get(key, [])
|
||||
df = pd.DataFrame(data, columns=cols)
|
||||
df.to_excel(writer, sheet_name=sheet_name, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("月考勤异常三查完成:检查1=%d 条,检查2=%d 条,检查3=%d 条",
|
||||
len(c1), len(c2), len(c3))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_abnormal_check(save_dir=None, month=None):
|
||||
"""执行月考勤异常三项检查并导出 Excel 报告,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月,
|
||||
不传则按「当月 1 日 至 今天」查询。
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = build_hr_session()
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
month_str = month
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
month_str = date.today().strftime("%Y-%m")
|
||||
|
||||
data = _fetch_all_data(session, user_id, treecode, begin, end)
|
||||
|
||||
# 请假索引(全部请假,供检查1判断日期是否有请假流程)
|
||||
leave_index = _build_leave_set(data["leaves"], need_full_day=False)
|
||||
|
||||
# 检查1
|
||||
c1 = check_leave_after_confirm(data["abnormal_confirmed"], leave_index)
|
||||
logger.info("检查1(确认异常有请假):命中 %d 条", len(c1))
|
||||
for r in c1:
|
||||
logger.warning("【检查1】%s %s 考勤日期 %s,异常:%s,请假:%s",
|
||||
r["员工姓名"], r["工号"], r["考勤日期"], r["异常类型"], r["请假类型"])
|
||||
|
||||
# 检查2
|
||||
c2 = check_rest_day_half_day_punch(session, user_id, treecode,
|
||||
data["rest_overtime"], begin, end)
|
||||
logger.info("检查2(休息日半天打卡):校验 %d 条", len(c2))
|
||||
for r in c2:
|
||||
if "漏打卡" in r["判定"]:
|
||||
logger.warning("【检查2】%s %s %s 加班半天,%s",
|
||||
r["员工姓名"], r["工号"], r["加班日期"], r["判定"])
|
||||
|
||||
# 检查3
|
||||
c3 = check_full_day_leave_abnormal(
|
||||
data["abnormal_confirmed"], data["abnormal_open"], data["leaves"])
|
||||
logger.info("检查3(整日请假有异常):命中 %d 条", len(c3))
|
||||
for r in c3:
|
||||
logger.warning("【检查3】%s %s %s:%s(异常:%s / %s)",
|
||||
r["员工姓名"], r["工号"], r["请假日期"], r["提示"],
|
||||
r["异常类型"], r["异常状态"])
|
||||
|
||||
return export_report({"check1": c1, "check2": c2, "check3": c3}, save_dir, month_str)
|
||||
|
||||
|
||||
def main(args=None):
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段 save_dir(导出目录)、month("YYYY-MM",默认当月;月度调度传上月)
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
save_dir = args.get("save_dir") or (sys.argv[1] if len(sys.argv) > 1 else None)
|
||||
month = args.get("month") or os.getenv("attendance_check_month") or (sys.argv[2] if len(sys.argv) > 2 else None)
|
||||
try:
|
||||
out = handle_abnormal_check(save_dir, month)
|
||||
_set_glv('attendance_check_save_path', out)
|
||||
logger.info("===== 月考勤异常三查完成,导出:%s =====", out)
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("月考勤异常三查失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,985 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查(单文件版,app 与影刀共用)——HR 登录(滑块验证码)
|
||||
-> 调用工资卡接口下载在职+离职工资卡数据 -> 核对身份证/姓名/银行卡号
|
||||
-> 导出核对结果 + 异常名单到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 1.0.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 内含 HR 登录(滑块验证码识别),保证工资卡查询所需的 hr.37du.co 登录态。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python numpy Pillow
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
HR 登录:hr_login_url / hr_target_url_keyword / hr_login_username / hr_login_password
|
||||
可选:wage_card_output_dir=结果输出目录(默认 D:\\资料\\人资\\银行卡检查)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
import cv2
|
||||
import numpy as np
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python "
|
||||
"numpy Pillow\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(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()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation\BankCardCheck(影刀版独立子目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', 'BankCardCheck'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE_HR = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
HR_LOGIN_URL = f"{HR_BASE_URL}/RedseaPlatform/"
|
||||
HR_SUCCESS_KEYWORD = f"{HR_BASE_URL}/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
|
||||
# ---------- 工资卡接口 ----------
|
||||
WAGE_CARD_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
|
||||
BANK_DICT_URL = f"{HR_BASE_URL}/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
BANK_DICT_LIST_FILE = os.path.join(_APP_DATA_DIR, "bank_dict_list.json")
|
||||
BANK_DICT_MAP_FILE = os.path.join(_APP_DATA_DIR, "bank_dict_map.json")
|
||||
|
||||
# ---------- 输出 ----------
|
||||
OUTPUT_DIR = os.getenv("wage_card_output_dir") or r"D:\资料\人资\银行卡检查"
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
|
||||
# ---------- HR 登录配置 ----------
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT_HR = "@id=j_username"
|
||||
PASSWORD_INPUT_HR = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
HR_RETRY_MAX = 5
|
||||
HR_TIMEOUT = 10
|
||||
HR_HEADLESS = False
|
||||
|
||||
# ---------- 工资卡字段映射 ----------
|
||||
COL_MAP = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# ---------- 核对相关列名 ----------
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
# ---------- 银行卡校验规则 ----------
|
||||
# 16 位银联卡 BIN(按银行归类,经实际工资卡数据比对核验)
|
||||
BIN_16 = {
|
||||
# 招商银行
|
||||
"621483", "621485", "621486", "622588", "622609",
|
||||
# 民生银行
|
||||
"621691", "622615", "622617", "622619", "622620", "622622",
|
||||
# 民生银行信用卡(16 位贷记卡)
|
||||
"622601",
|
||||
# 重庆农村商业银行
|
||||
"621258", "621465", "621528", "622867",
|
||||
# 浦东发展银行
|
||||
"621792", "621793", "622521",
|
||||
# 其他银行
|
||||
"621499", # 建设银行理财金卡
|
||||
"621755", # 重庆三峡银行
|
||||
"623020", # 华夏银行
|
||||
}
|
||||
# 18 位银联储蓄卡 BIN
|
||||
BIN_18 = {"622908"} # 兴业银行
|
||||
# 非 62 开头但合法的老版储蓄卡 BIN(历史卡仍在使用,标准均为 19 位)
|
||||
NON62_BIN = {
|
||||
"436742", # 建设银行龙卡储蓄卡
|
||||
"601382", # 中国银行长城电子借记卡
|
||||
"955882", # 工商银行牡丹灵通卡
|
||||
}
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
def retry(max_attempts=3):
|
||||
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 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 last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== Cookies 持久化 ====================
|
||||
def _ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def save_browser_cookies(browser_page, path):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
logger.warning("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ==================== HR 登录(滑块验证码) ====================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("拖拽异常:%s", e)
|
||||
return False
|
||||
|
||||
|
||||
def handle_hr_captcha(page):
|
||||
for retry_no in range(HR_RETRY_MAX):
|
||||
logger.info("--- HR 第 %d 次尝试验证 ---", retry_no + 1)
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=HR_TIMEOUT)
|
||||
if not container:
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
logger.info("匹配距离 %dpx -> CSS %.1fpx", distance_phys, distance_css)
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
logger.warning("验证异常:%s", e)
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def hr_login(username=None, password=None):
|
||||
load_dotenv()
|
||||
final_username = username or os.getenv('hr_login_username')
|
||||
final_password = password or os.getenv('hr_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("HR 用户名或密码未提供,请设置环境变量 hr_login_username / hr_login_password")
|
||||
|
||||
co = ChromiumOptions()
|
||||
if HR_HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
|
||||
saved = load_cookies(COOKIE_FILE_HR)
|
||||
if saved:
|
||||
try:
|
||||
page.set.cookies(saved)
|
||||
page.get(HR_LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
logger.info("已通过缓存的 HR Cookies 登录")
|
||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||||
page.quit()
|
||||
return
|
||||
except Exception as e:
|
||||
logger.warning("复用 HR Cookies 失败:%s", e)
|
||||
else:
|
||||
page.get(HR_LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
logger.info("HR 已登录")
|
||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||||
page.quit()
|
||||
return
|
||||
|
||||
try:
|
||||
account = page.ele(ACCOUNT_INPUT_HR)
|
||||
if not account:
|
||||
raise RuntimeError("找不到 HR 账号输入框")
|
||||
account.clear(); account.input(final_username); time.sleep(0.5)
|
||||
pwd = page.ele(PASSWORD_INPUT_HR)
|
||||
if not pwd:
|
||||
raise RuntimeError("找不到 HR 密码输入框")
|
||||
pwd.clear(); pwd.input(final_password); time.sleep(0.5)
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
raise RuntimeError("找不到登录按钮")
|
||||
login_btn.click(); time.sleep(3)
|
||||
|
||||
if HR_SUCCESS_KEYWORD in page.url:
|
||||
logger.info("HR 登录成功(无滑块)")
|
||||
elif handle_hr_captcha(page):
|
||||
logger.info("HR 登录成功(验证通过)")
|
||||
else:
|
||||
raise RuntimeError("HR 登录失败(滑块验证未通过)")
|
||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
"""确保存在有效的 hr.37du.co cookies;必要时触发 HR 登录。"""
|
||||
hr_cookies = load_cookies(COOKIE_FILE_HR)
|
||||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in (hr_cookies or []))
|
||||
if not has_hr:
|
||||
logger.info("无 hr.37du.co 登录态,执行 HR 登录")
|
||||
hr_login()
|
||||
else:
|
||||
logger.info("复用已保存的 HR 登录态(hr.37du.co)")
|
||||
return _build_hr_session()
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
cookies = load_cookies(COOKIE_FILE_HR)
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
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
|
||||
|
||||
|
||||
# ==================== 银行字典接口(aa.md 提供) ====================
|
||||
def _fetch_bank_dict(session=None):
|
||||
"""远程调用接口获取银行字典,并写入本地缓存。
|
||||
|
||||
返回 (list[dict], dict[code->name])。
|
||||
"""
|
||||
if session is None:
|
||||
session = get_hr_session()
|
||||
payload = {
|
||||
"codeType": BANK_DICT_CODE_TYPE,
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
|
||||
resp.raise_for_status()
|
||||
resp_json = resp.json()
|
||||
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
|
||||
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
|
||||
for item in raw_list]
|
||||
result_map = {item["code"]: item["name"] for item in result_list}
|
||||
|
||||
_ensure_dir(_APP_DATA_DIR)
|
||||
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_list, f, ensure_ascii=False, indent=2)
|
||||
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_map, f, ensure_ascii=False, indent=2)
|
||||
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
|
||||
return result_list, result_map
|
||||
|
||||
|
||||
def _load_bank_dict_cache():
|
||||
"""读取本地银行字典缓存,失败返回 (None, None)。"""
|
||||
try:
|
||||
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
|
||||
lst = json.load(f)
|
||||
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
|
||||
mp = json.load(f)
|
||||
return lst, mp
|
||||
except Exception as e:
|
||||
logger.warning("银行字典本地缓存读取失败:%s", e)
|
||||
return None, None
|
||||
|
||||
|
||||
def get_bank_dict(session=None, force_refresh=False):
|
||||
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
|
||||
|
||||
:param session: 可选的 HR requests.Session;未提供时自动构建
|
||||
:param force_refresh: True 强制重新调用接口
|
||||
:return: (list版本, map版本)
|
||||
"""
|
||||
need_refresh = force_refresh
|
||||
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
|
||||
need_refresh = True
|
||||
else:
|
||||
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
|
||||
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
|
||||
need_refresh = True
|
||||
|
||||
if need_refresh:
|
||||
try:
|
||||
return _fetch_bank_dict(session)
|
||||
except Exception as e:
|
||||
logger.error("银行字典远程拉取失败:%s", e)
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is not None:
|
||||
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
return [], {}
|
||||
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is None:
|
||||
# 缓存异常时重新拉取
|
||||
return _fetch_bank_dict(session)
|
||||
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
|
||||
|
||||
def _bank_type_to_name(bank_type, bank_map):
|
||||
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
|
||||
if bank_type is None:
|
||||
return ""
|
||||
if isinstance(bank_type, float):
|
||||
if bank_type != bank_type: # NaN
|
||||
return ""
|
||||
bank_type = str(int(bank_type))
|
||||
elif isinstance(bank_type, int):
|
||||
bank_type = str(bank_type)
|
||||
else:
|
||||
bank_type = str(bank_type).strip()
|
||||
return bank_map.get(bank_type, "")
|
||||
|
||||
|
||||
# ==================== 工资卡接口 ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch_wage_card_page(session, status, page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
leave_start=None, leave_end=None):
|
||||
params = {
|
||||
"start": (page_no - 1) * page_size,
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ftl_list_STRU_TREE_CODE": "cq37du",
|
||||
"sortName": "hr_staff_wage_card.STAFF_NAME",
|
||||
"sortType": "asc",
|
||||
"commonQuery": "[]",
|
||||
"person_status": status,
|
||||
}
|
||||
if status == 1:
|
||||
params["leaveOffice_date"] = ""
|
||||
elif leave_start and leave_end:
|
||||
params["leaveOffice_date[0]"] = leave_start
|
||||
params["leaveOffice_date[1]"] = leave_end
|
||||
params["leaveOffice_date_start"] = leave_start
|
||||
params["leaveOffice_date_end"] = leave_end
|
||||
|
||||
resp = session.post(WAGE_CARD_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("工资卡请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if text and not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = text[:200]
|
||||
raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_wage_card(session, status, status_name, leave_start=None, leave_end=None):
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name)
|
||||
hr_login()
|
||||
session = _build_hr_session()
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("【%s】无更多数据", status_name)
|
||||
break
|
||||
|
||||
for item in page_list:
|
||||
item["人员类型"] = status_name
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total = data.get("count", 0)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
|
||||
status_name, page_no, total_page, len(all_rows), total)
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 离职时间范围 ====================
|
||||
def get_leave_range(today=None):
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 工资卡导出 Excel ====================
|
||||
def export_excel(data_on_job, data_leave, save_dir):
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: _bank_type_to_name(c, bank_map))
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
_ensure_dir(save_dir)
|
||||
save_path = os.path.join(save_dir, SAVE_NAME)
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 银行卡校验 ====================
|
||||
def check_bank_card(card_raw):
|
||||
card = str(card_raw).strip()
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw:
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
bin6 = card[:6]
|
||||
if not (card.startswith("62") or bin6 in NON62_BIN):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ==================== 核对分类 ====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account):
|
||||
"""按 4 类异常对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, id_inconsistent, bank_info)
|
||||
issues: 4 类异常标签(写入核对结果)
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
"""
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if _is_empty(bank_account):
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 身份证不一致(开户人身份证非空且与员工不一致) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
if id_inconsistent:
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
|
||||
# ---- 3. 姓名不一致(仅身份证一致时比对) ----
|
||||
if (not id_inconsistent and not _is_empty(card_idcard)
|
||||
and not _is_empty(card_name) and staff_name != card_name):
|
||||
issues.append("员工姓名与开户人姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 4. 银行卡信息异常(银行卡非空但格式/位数错误) ----
|
||||
if not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
issues.append("银行卡信息异常")
|
||||
basis.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
|
||||
return issues, basis, id_inconsistent, bank_info
|
||||
|
||||
|
||||
# ==================== 核对辅助 ====================
|
||||
def _is_empty(val):
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val:
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val):
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val:
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
# ==================== 核对主逻辑 ====================
|
||||
def check_wage_card(input_path, output_path=None):
|
||||
"""读取工资卡汇总表,执行核对并保存结果 + 异常名单。
|
||||
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
"""
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: _bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"] if bk else ""
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"] if bk else ""
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存核对结果
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
# 保存核对结果
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
# 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录)
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_rows))
|
||||
abnormal = df[mask]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = os.path.join(os.path.dirname(base), f"工资卡异常名单{ext}")
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def download_wage_card(save_dir=None):
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel。"""
|
||||
save_dir = save_dir or OUTPUT_DIR
|
||||
# get_hr_session 会检查 cookies,不存在时自动触发 HR 登录
|
||||
session = get_hr_session()
|
||||
|
||||
# 预检登录态
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
hr_login()
|
||||
session = _build_hr_session()
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
load_dotenv()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user