1. 更新需求文档版本与查询范围规则,将默认查询改为整月(1号查上月),钉钉推送仅覆盖上周 2. 新增query_month、in_last_week工具函数重构日期逻辑 3. 调整自动确认开关默认值为启用,分级处理轻微异常整月自动确认、严重异常仅上周推送 4. 更新日志与汇总消息格式,补充本月非上周异常的统计项 5. 同步修改影刀脚本与业务服务端代码逻辑
455 lines
19 KiB
Python
455 lines
19 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@Module: hrbp.ehr.attendance
|
||
@FileName: attendance_abnormal.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-10
|
||
@Description: 考勤异常查询与导出:通过员工基础信息接口(getCurUserInfo)校验 cookies 有效性,
|
||
再调用考勤异常接口分页拉取【本月(1 号查上月,否则当月)】全部考勤异常数据,导出为 Excel;
|
||
并按规则分级处理:轻微异常(迟到/早退 <30 分钟)整月自动确认;需推送的(迟到/早退 >=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. 直接运行本文件即可查询本月(1 号查上月,否则当月)考勤异常并导出 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, "推送记录")
|
||
# 自动确认总开关(默认启用:整月轻微异常直接批量确认;置 "false" 关闭仅统计不执行)
|
||
AUTO_CONFIRM_ENABLED = "true"
|
||
|
||
# 英文字段 → 中文字段映射(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. 查询范围(默认整月: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")
|
||
|
||
|
||
def query_month(today: date = None) -> str:
|
||
"""本次查询月份:1 号(2 号之前,不含 2 号)查上月,否则查当月。
|
||
|
||
当月数据过少(仅 1 天)时补处理上月整月;2 号及以后按当月处理。
|
||
"""
|
||
today = today or date.today()
|
||
if today.day < 2:
|
||
first_of_this_month = today.replace(day=1)
|
||
return (first_of_this_month - timedelta(days=1)).strftime("%Y-%m")
|
||
return today.strftime("%Y-%m")
|
||
|
||
|
||
def in_last_week(item: dict, push_begin: str, push_end: str) -> bool:
|
||
"""判断异常记录(按 work_day)是否落在上周范围内;work_day 缺失时返回 False。"""
|
||
work_day = str(item.get("work_day") or "")[:10]
|
||
return bool(work_day) and push_begin <= work_day <= push_end
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 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)
|
||
|
||
# 计算查询范围:默认整月(1 号查上月,否则当月)
|
||
month = month or query_month()
|
||
begin = f"{month}-01"
|
||
end = f"{month}-31"
|
||
month_str = month
|
||
logger.info("===== 查询考勤异常日期范围:%s ~ %s(%s 整月),调整状态:%s =====",
|
||
begin, end, month, 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,
|
||
other_count: int, month: str, begin: str, end: str) -> str:
|
||
"""生成考勤异常处理条数汇总消息(与汇总日志格式一致)。"""
|
||
return (
|
||
"【考勤异常处理汇总】\n"
|
||
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n"
|
||
f"考勤异常总数:{total_count} 条\n"
|
||
f"直接处理(轻微,整月自动确认):{mild_count} 条,确认成功 {confirmed_count} 条\n"
|
||
f"待通知(职能,上周):{func_count} 条,合并为 {push_count} 条推送\n"
|
||
f"上周非职能(不推送):{non_func_count} 条\n"
|
||
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
|
||
)
|
||
|
||
|
||
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("本月(%s)无考勤异常数据", month_str)
|
||
return None
|
||
return export_excel(data, save_dir, month_str)
|
||
|
||
|
||
def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||
"""查询当月考勤异常,导出 Excel,并按要求向钉钉推送需核实的异常。
|
||
|
||
规则:轻微异常(迟到/早退 < 30 分钟)整月自动确认;需推送的仅上周(周一~周日)
|
||
严重异常,且仅推送 first_type_name 含「职能」的人员,按「姓名-工号」合并为一人一条。
|
||
|
||
Args:
|
||
save_dir: 保存目录,默认 SAVE_DIR
|
||
month: 查询月份 "YYYY-MM";默认本月(1 号查上月,否则当月)
|
||
|
||
Returns:
|
||
导出文件路径(无数据时返回 None)
|
||
"""
|
||
save_dir = save_dir or SAVE_DIR
|
||
data, month_str = _fetch_abnormal_data(month)
|
||
if not data:
|
||
logger.info("本月(%s)无考勤异常数据,跳过导出与推送", month_str)
|
||
return None
|
||
|
||
path = export_excel(data, save_dir, month_str)
|
||
|
||
# 分级分类:轻微异常整月自动确认;需推送的仅上周(周一~周日)严重异常
|
||
mild_list = [it for it in data if not classify_abnormal(it)]
|
||
push_begin, push_end = last_week_range()
|
||
push_list = [it for it in data if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
|
||
other_list = [it for it in data if classify_abnormal(it) and not in_last_week(it, push_begin, push_end)]
|
||
logger.info("考勤异常共 %d 条:轻微整月自动确认 %d 条,上周需推送 %d 条,其他严重仅留痕 %d 条",
|
||
len(data), len(mild_list), len(push_list), len(other_list))
|
||
|
||
# 自动确认轻微异常(整月,迟到/早退<30分钟,不分职能序列)——总开关 AUTO_CONFIRM_ENABLED 控制
|
||
# 统计不受开关影响:始终按数据计算实际条数(开关只决定是否真正调用确认接口)
|
||
mild_count = len([it for it in mild_list if it.get("abnormal_id")])
|
||
if AUTO_CONFIRM_ENABLED:
|
||
confirmed_count = auto_confirm_mild(mild_list)
|
||
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)]
|
||
non_func_list = [it for it in push_list if not is_func_staff(it)]
|
||
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, len(non_func_list),
|
||
len(func_list), push_count, len(other_list), month_str,
|
||
push_begin, push_end))
|
||
|
||
# ---- 最终统计汇总 ----
|
||
logger.info("=" * 60)
|
||
logger.info("【考勤异常处理汇总】")
|
||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||
logger.info(" 直接处理(轻微,整月自动确认):%d 条,确认成功 %d 条", mild_count, confirmed_count)
|
||
logger.info(" 待通知(职能,上周):%d 条,合并为 %d 条推送", len(func_list), push_count)
|
||
logger.info(" 上周非职能(不推送):%d 条", len(non_func_list))
|
||
logger.info(" 本月其他严重异常(非上周,仅导出留痕):%d 条", len(other_list))
|
||
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()
|