# -*- 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, timedelta 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:\资料\人资\考勤异常" # 推送记录保存目录(按场景传入,不写死;空串=不记录) PUSH_RECORD_DIR = os.path.join(SAVE_DIR, "推送记录") # 自动确认总开关(默认关闭:置 "true" 才批量确认轻微异常,避免误确认真实记录,便于测试时关闭) AUTO_CONFIRM_ENABLED = "false" # 英文字段 → 中文字段映射(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 last_week_range(today: date = None) -> tuple: """返回上周(周一~周日)的查询日期范围,返回 (开始日期, 结束日期)。 上周定义:本周一往前推 7 天为上周一,上周一 + 6 天为上周日。 """ today = today or date.today() this_monday = today - timedelta(days=today.weekday()) # 本周一 last_monday = this_monday - timedelta(days=7) last_sunday = this_monday - timedelta(days=1) return last_monday.strftime("%Y-%m-%d"), last_sunday.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["处理方式"] = df.apply( lambda r: "自动确认" if not classify_abnormal(r) else "钉钉推送", axis=1 ) # 替换英文列为中文 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: """按「姓名-工号」分组生成钉钉通知文本并直接推送(app 版主脚本直接调用,无需全局变量)。 同一人员多条异常合并为一条通知,大幅减少推送次数。 Returns: 成功推送的人员数(即推送次数) """ from app.utils.dingtalk_sender import send_to_person 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) send_to_person(_name, text=text, keyword=_code, record_dir=PUSH_RECORD_DIR) 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 = last_week_range() month_str = end[:7] # 文件名月份标识取上周日所在月 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 is_mild_abnormal(item: dict) -> bool: """轻微异常:迟到/早退 且 异常时长 < 30 分钟(自动确认范围,不分职能序列)。""" return not classify_abnormal(item) def auto_confirm_mild(data, session=None) -> int: """自动确认轻微异常(迟到/早退 < 30 分钟,不分职能序列)。 Args: data: 未调整考勤异常记录列表 session: 已登录会话;为空时自动构建并校验 Returns: 确认成功的条数 """ mild = [it for it in data if is_mild_abnormal(it) and it.get("abnormal_id")] if not mild: logger.info("无轻微异常(迟到/早退<30分钟),跳过自动确认") return 0 ids = [it["abnormal_id"] for it in mild] logger.info("自动确认轻微异常 %d 条(不分职能序列)", len(ids)) result = confirm_abnormal(ids, session=session) if result.get("state") == "1": logger.info("自动确认接口返回处理成功,共 %d 条", len(ids)) return len(ids) logger.error("自动确认失败:%s", result.get("meg") or result) return 0 def build_group_summary(total_count: int, mild_count: int, confirmed_count: int, non_func_count: int, func_count: int, push_count: int, begin: str, end: str) -> str: """生成考勤异常处理条数汇总消息(与汇总日志格式一致)。""" return ( "【考勤异常处理汇总】\n" f"查询范围:{begin} ~ {end}\n" f"考勤异常总数:{total_count} 条\n" f"直接处理(轻微,自动确认):{mild_count} 条,确认成功 {confirmed_count} 条\n" f"非职能人员(不推送):{non_func_count} 条\n" f"待通知(职能人员):{func_count} 条,合并为 {push_count} 条推送" ) def download_attendance_abnormal(save_dir: str = None, month: str = None) -> str: """查询当月考勤异常并导出 Excel,返回导出文件路径。 Args: save_dir: 保存目录,默认 SAVE_DIR month: 查询月份 "YYYY-MM"(默认上周)。传该参数时查询整个月, 不传则按「上周一 至 上周日」查询。 """ 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_list = [it for it in data if not classify_abnormal(it)] logger.info("考勤异常共 %d 条:需推送 %d 条,轻微异常(迟到/早退<30分钟,自动确认) %d 条", len(data), len(push_list), len(handled_list)) # 自动确认轻微异常(迟到/早退<30分钟,不分职能序列)——总开关 AUTO_CONFIRM_ENABLED 控制 # 统计不受开关影响:始终按数据计算实际条数(开关只决定是否真正调用确认接口) if month: confirm_begin, confirm_end = f"{month}-01", f"{month}-31" else: confirm_begin, confirm_end = last_week_range() mild_count = len([it for it in handled_list if it.get("abnormal_id")]) if AUTO_CONFIRM_ENABLED: confirmed_count = auto_confirm_mild(handled_list, session=session) else: confirmed_count = 0 logger.info("自动确认未启用(AUTO_CONFIRM_ENABLED!=true),仅统计待自动确认 %d 条,未执行确认", mild_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("处理条数汇总:%s", build_group_summary(len(data), mild_count, confirmed_count, skipped_non_func, len(func_list), push_count, confirm_begin, confirm_end)) # ---- 最终统计汇总 ---- logger.info("=" * 60) logger.info("【考勤异常处理汇总】") logger.info(" 考勤异常总数:%d 条", len(data)) logger.info(" 直接处理(轻微,自动确认):%d 条,确认成功 %d 条", mild_count, confirmed_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()