# -*- coding: utf-8 -*- """ @Module: hrbp.ehr.attendance @FileName: attendance_abnormal.py @Author: 小布丁 @CreateTime: 2026-08-10 @Description: 考勤异常查询与导出:通过员工基础信息接口(getCurUserInfo)校验 cookies 有效性, 再调用考勤异常接口分页拉取【当月】全部考勤异常数据,导出为 Excel; 并按规则(迟到/早退 >=30 分钟,或其他类型异常)向对应员工推送钉钉核实通知; 仅推送 first_type_name 含「职能」的人员,且按「姓名-工号」合并为一人一条,减少推送次数。 底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。 @Version: 2.0.0 使用说明: 1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json; 后续运行自动复用缓存,登录态过期会自动重新登录。 2. 直接运行本文件即可查询当月考勤异常并导出 Excel。 """ import os import sys from datetime import date, datetime from pathlib import Path from typing import Dict, List # ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ---- def _find_project_root() -> str: for parent in Path(__file__).resolve().parents: if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file(): return str(parent) return str(Path(__file__).resolve().parents[5]) _root = _find_project_root() if _root not in sys.path: sys.path.insert(0, _root) from app.utils.logger import get_logger, setup_logging # noqa: E402 # 底层复用:接口调用 / 会话管理 from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402 fetch_cur_user_info, fetch_all_attendance_abnormal, # adjust_abnormal, # 自动确认异常能力暂未启用,需要时取消注释 HRSessionExpiredError, ) from app.service.hrbp.common.hr_session import ( # noqa: E402 build_hr_session, refresh_hr_session, ) try: import pandas as pd except ImportError: pd = None logger = get_logger(__name__) # ===================== 配置区(自行修改) ===================== # 默认保存目录 SAVE_DIR = r"D:\资料\人资\考勤异常" # 英文字段 → 中文字段映射(aa.md 提供的考勤异常字段,其余字段保留原样) COL_MAP: Dict[str, str] = { "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" # ---------------------------------------------- # 1. 当月查询范围(每次默认查询当月) # ---------------------------------------------- def current_month_range(today: date = None) -> tuple: """返回当月的查询日期范围,返回 (开始日期, 结束日期)。 开始日期 = 当月 1 日,结束日期 = 今天。 """ today = today or date.today() begin = today.replace(day=1) return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d") # ---------------------------------------------- # 2. cookies 有效性校验(员工基础信息接口) # ---------------------------------------------- def _validate_session(session): """调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。 若登录态过期则重新登录并重建会话后重试。 """ try: info = fetch_cur_user_info(session) except HRSessionExpiredError: logger.warning("cookies 已失效,正在重新登录") session = refresh_hr_session() info = fetch_cur_user_info(session) 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 # ---------------------------------------------- # 3. 导出当月考勤异常 Excel # ---------------------------------------------- def export_excel(data: List[dict], save_dir: str, month_str: str) -> str: """将考勤异常数据映射为中文、调整列顺序并导出 .xlsx。""" if pd is None: raise RuntimeError("缺少 pandas 依赖,无法导出 Excel") 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) # 文件名加时间戳,避免同名文件被占用导致 PermissionError 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 # ---------------------------------------------- # 4. 筛选 + 钉钉推送(按姓名) # ---------------------------------------------- def classify_abnormal(item: dict) -> bool: """判断该条异常是否需要钉钉推送。 规则(需求): - 迟到/早退 且 异常时长 < 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: dict) -> bool: """判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。""" return "职能" in str(item.get("first_type_name", "") or "") def build_notify_text(items: List[dict]) -> str: """按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。 每条异常保留原确认行格式:按实际异常类型动态生成; 迟到/早退会在确认项前附上分钟数。 """ 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) def push_abnormal(items: List[dict]) -> int: """按「姓名-工号」分组生成钉钉通知文本(暂不实际发送,先供人工确认)。 同一人员多条异常合并为一条通知,大幅减少推送次数。 Returns: 生成通知的人员数(即推送次数) """ from app.utils.dingtalk_sender import send_to_person # noqa: F401 groups: Dict[tuple, List[dict]] = {} for it in items: name = it.get("STAFF_NAME", "") or "" if not name: logger.warning("异常记录缺少姓名,跳过:%s", it) continue key = (name, it.get("base_code", "") or "") groups.setdefault(key, []).append(it) for (_name, _code), group in groups.items(): text = build_notify_text(group) # 先注释掉实际推送,仅输出文本供确认 logger.info("【待推送通知】\n%s", text) # send_to_person(_name, text=text) # logger.info("已向 %s 推送考勤异常通知(%d 条合并)", _name, len(group)) return len(groups) # ---------------------------------------------- # 5. 内部抓取(供下载/处理共用) # ---------------------------------------------- def _fetch_abnormal_data(month: str = None) -> tuple: """校验会话、计算查询范围、拉取当月考勤异常数据。 Returns: (data, month_str):data 为异常明细列表,month_str 为查询月份 "YYYY-MM" """ session = build_hr_session() # 校验 cookies 有效性,并获取查询所需 user_id / treecode 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") logger.info("===== 查询考勤异常日期范围:%s ~ %s,调整状态:%s =====", begin, end, IS_ADJUSTED or "所有") data = fetch_all_attendance_abnormal( session, user_id, treecode, begin, end, IS_ADJUSTED ) return data, month_str # ---------------------------------------------- # 6. 对外便捷入口 # ---------------------------------------------- # ---- 自动确认异常能力暂未启用,需要时取消以下注释 ---- # def confirm_abnormal(abnormal_ids, type_code: int = 1, session=None): # """确认/调整考勤异常单据(按 abnormal_id 唯一编号)。 # # Args: # abnormal_ids: 异常单据 id,可为单个 id 或 id 列表 # type_code: 处理类型,1=自动确认异常(默认) # session: 已登录会话;为空时自动构建并校验 # # Returns: # 接口返回的 JSON 字典(state=1 表示处理成功) # """ # if session is None: # session = build_hr_session() # session, _, _ = _validate_session(session) # return adjust_abnormal(session, abnormal_ids, type_code) def download_attendance_abnormal(save_dir: str = None, month: str = None) -> str: """查询当月考勤异常并导出 Excel,返回导出文件路径。 Args: save_dir: 保存目录,默认 SAVE_DIR month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月, 不传则按「当月 1 日 至 今天」查询。 """ save_dir = save_dir or SAVE_DIR data, month_str = _fetch_abnormal_data(month) if not data: logger.info("当月无考勤异常数据") return None return export_excel(data, save_dir, month_str) def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str: """查询当月考勤异常,导出 Excel,并按要求向钉钉推送需核实的异常。 推送规则见 classify_abnormal:迟到/早退 >= 30 分钟,或其他类型异常; 且仅推送 first_type_name 含「职能」的人员,并按「姓名-工号」合并为一人一条推送。 Args: save_dir: 保存目录,默认 SAVE_DIR month: 查询月份 "YYYY-MM"(默认当月) Returns: 导出文件路径(无数据时返回 None) """ save_dir = save_dir or SAVE_DIR data, month_str = _fetch_abnormal_data(month) if not data: logger.info("当月无考勤异常数据,跳过导出与推送") return None path = export_excel(data, save_dir, month_str) push_list = [it for it in data if classify_abnormal(it)] handled_count = len(data) - len(push_list) logger.info("考勤异常共 %d 条:需推送 %d 条,轻微异常(迟到/早退<30分钟,直接处理) %d 条", len(data), len(push_list), handled_count) # 只推送「职能」序列(first_type_name 含「职能」),并按 姓名-工号 合并推送 func_list = [it for it in push_list if is_func_staff(it)] skipped_non_func = len(push_list) - len(func_list) if func_list: push_count = push_abnormal(func_list) else: push_count = 0 logger.info("无需推送的异常,跳过钉钉通知") # ---- 最终统计汇总 ---- logger.info("=" * 60) logger.info("【考勤异常处理汇总】") logger.info(" 考勤异常总数:%d 条", len(data)) logger.info(" 直接处理(轻微,无需通知):%d 条", handled_count) logger.info(" 非职能人员(first_type_name 不含「职能」,不推送):%d 条", skipped_non_func) logger.info(" 待通知(职能人员):%d 条,合并为 %d 条推送", len(func_list), push_count) logger.info(" 导出文件:%s", path) logger.info("=" * 60) return path def main() -> None: setup_logging() save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR month = 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("===== 考勤异常处理完成:当月无数据 =====") except Exception as e: if "正被占用" in str(e): # 文件被 Excel 占用:只提醒关闭后重试,不抛堆栈 logger.error("=========== 提醒 ===========") logger.error(str(e)) logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。") return logger.error("考勤异常处理失败:%s", e) raise if __name__ == "__main__": main()