本次提交全面调整了排班数据的处理逻辑: 1. 移除所有对`paiban_type`字段的依赖,改为通过`bc_name == "休息"`作为休息日判定的唯一可靠依据 2. 从`_extract_day_shift`、`_get_day_shift`等工具函数中删除`paiban_type`相关的字段获取和判断逻辑 3. 更新所有相关接口注释、文档说明,明确说明`paiban_type`不可靠,休息也可能返回-2 4. 重构了连续未出勤段的计算逻辑,将休息日纳入未出勤集合,支持跨月追溯 5. 同时更新了影刀版本和服务端版本的实现代码,保持逻辑一致
606 lines
25 KiB
Python
606 lines
25 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@Module: hrbp.ehr.attendance
|
||
@FileName: abnormal_check.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-14
|
||
@Description: 月考勤异常三重复核:结合考勤异常 / 请假 / 加班 / 打卡四类接口,
|
||
对当月数据做三项检查并输出多 Sheet Excel 报告(独立于周考勤异常处理流程):
|
||
|
||
检查1:已确认异常(is_adjusted=2)的日期,是否存在请假流程?
|
||
—— 可能存在「提前确认后请假」导致仍为考勤异常的情况;
|
||
检查2:休息日加班(类型3)且加班天数为 0.5 天,当日打卡是否按考勤班段正常打卡(无漏打卡)?
|
||
检查3:员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)处于确认
|
||
—— 弹出提示「该员工XX日考勤状态存在异常」。
|
||
|
||
底层复用:接口调用(app.service.hrbp.ehr.common.hr_api)、会话管理(app.service.hrbp.common.hr_session)。
|
||
@Version: 1.0.0
|
||
|
||
使用说明:
|
||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到
|
||
AppData\\Local\\37duAutomation\\.sessions\\hr_cookies.json;
|
||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||
2. 直接运行本文件即可对当月做三查并导出 Excel 报告。
|
||
3. 加班/请假接口按「空工号=查询全部」调用,返回的记录自带工号,无需额外员工列表接口。
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
from datetime import date, datetime, timedelta
|
||
from pathlib import Path
|
||
from typing import Any, Dict, List, Optional, Tuple
|
||
|
||
# ---- 单文件运行支持:把项目根目录加入 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,
|
||
fetch_all_leave,
|
||
fetch_all_overtime,
|
||
fetch_all_kq_data,
|
||
fetch_all_shift,
|
||
HRSessionExpiredError,
|
||
)
|
||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||
build_hr_session,
|
||
refresh_hr_session,
|
||
)
|
||
from app.service.hrbp.common.config import VACATION_TYPE_MAP # noqa: E402
|
||
|
||
try:
|
||
import pandas as pd
|
||
except ImportError:
|
||
pd = None
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
# ===================== 配置区(自行修改) =====================
|
||
# 默认保存目录(与周考勤异常导出目录保持一致)
|
||
SAVE_DIR = r"D:\资料\人资\考勤异常"
|
||
|
||
# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||
IS_ADJUSTED_CONFIRMED = "2" # 已确认异常(检查1)
|
||
IS_ADJUSTED_OPEN = "0" # 未调整异常(检查3并集之一)
|
||
IS_ADJUSTED_ALL = "" # 全部状态
|
||
|
||
# 加班类型:空=全部、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
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 1. 工具函数
|
||
# ----------------------------------------------
|
||
def current_month_range(today: date = None) -> Tuple[str, str]:
|
||
"""返回当月的查询日期范围 (开始日期, 结束日期)。开始=当月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: Dict[str, Any], *keys: str, default: Any = "") -> Any:
|
||
"""从记录中取第一个存在的键的值(兼容字段大小写差异)。"""
|
||
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: Any) -> str:
|
||
"""将接口返回的日期/时间值归一化为 '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: Any, default: float = 0.0) -> float:
|
||
try:
|
||
return float(value)
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
def _is_half_day_ot(rec: Dict[str, Any]) -> bool:
|
||
"""判断加班记录是否为休息日半天(0.5 天)。
|
||
|
||
依次取 ot_days / sys_ot_days / plan_ot_days,任一 ≈ 0.5 即判定半天。
|
||
"""
|
||
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: Dict[str, Any]) -> str:
|
||
"""从请假记录中提取假期类型名称(兼容编码与名称两种输入)。"""
|
||
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: Dict[str, Any]) -> str:
|
||
"""兼容取员工姓名字段(不同接口命名不同)。"""
|
||
return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default=""))
|
||
|
||
|
||
def _punch_analysis(records: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||
"""对某日打卡流水做统计。
|
||
|
||
打卡记录无法可靠区分上下班(time_order 多为空),按时间最早=上班、最晚=下班汇总。
|
||
|
||
Returns:
|
||
{count, first, last}:count 打卡次数,first/last 最早/最晚打卡时间(含时分)
|
||
"""
|
||
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: Any) -> Optional[int]:
|
||
"""将 "HH:MM[:SS]" 时间串转为当日分钟数;解析失败返回 None。"""
|
||
if value is None:
|
||
return None
|
||
s = str(value).strip()
|
||
if not s:
|
||
return None
|
||
# 兼容 "09:00" / "09:00:00" / "2026-08-03 09:00:00"(取最后的时间段)
|
||
import re
|
||
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: str) -> Tuple[Optional[int], Optional[int]]:
|
||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
|
||
if not bc_time:
|
||
return None, None
|
||
import re
|
||
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: List[Dict[str, Any]], date_str: str) -> Dict[str, Any]:
|
||
"""从某员工排班记录中提取指定日期的班段信息。
|
||
|
||
排班接口 datas 为动态列(key 为 "YYYY-MM-DD_bc_name/bc_time/..."):
|
||
- bc_name:班次名(休息日为「休息」,是休息与否的可靠判定依据)
|
||
- bc_time:班段时间,如 "09:00 ~ 18:00"(休息日为空串)
|
||
注意:paiban_type 不可靠(休息也可能为 -2 / 0),不可用来判定休息。
|
||
|
||
Returns:
|
||
{"bc_name": 班次名, "bc_time": 班段时间}
|
||
"""
|
||
info = {"bc_name": "", "bc_time": ""}
|
||
for rec in shift_rows:
|
||
name = _get(rec, f"{date_str}_bc_name", default="")
|
||
time_ = _get(rec, f"{date_str}_bc_time", default="")
|
||
if name or time_:
|
||
info = {"bc_name": str(name), "bc_time": str(time_)}
|
||
break
|
||
return info
|
||
|
||
|
||
def _judge_punch_by_shift(p: Dict[str, Any], shift_info: Dict[str, Any]) -> str:
|
||
"""结合班段时间判断当日打卡是否正常。
|
||
|
||
规则:
|
||
- 排班有班段时间(如 "09:00 ~ 12:00"):最早打卡应覆盖班段开始(前后容差内),
|
||
最晚打卡应覆盖班段结束,且打卡次数 >= 2 → 正常;
|
||
- 排班为休息日(无班段时间):退化为打卡次数判断(>=2 正常)。
|
||
"""
|
||
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 "漏打卡(打卡未按班段覆盖上下班)"
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 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. 数据获取(全量拉取,返回记录自带工号)
|
||
# ----------------------------------------------
|
||
def _fetch_all_data(session, user_id: str, treecode: str, begin: str, end: str) -> Dict[str, list]:
|
||
"""一次性拉取三项检查所需的基础数据。
|
||
|
||
- abnormal_confirmed: 已确认异常(is_adjusted=2)
|
||
- abnormal_open: 未调整异常(is_adjusted=0)
|
||
- leaves: 全部请假记录(空工号=全量,检查1/检查3共用)
|
||
- rest_overtime: 全部休息日加班(类型3,空工号=全量,检查2用)
|
||
|
||
Returns:
|
||
以名称为键的列表字典
|
||
"""
|
||
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: List[Dict[str, Any]], need_full_day: bool = False) -> Dict[Tuple[str, str], Dict]:
|
||
"""把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。
|
||
|
||
need_full_day=True 时只保留整日请假(leave_days>=1)的每一天;
|
||
否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。
|
||
"""
|
||
index: Dict[Tuple[str, str], Dict] = {}
|
||
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
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 4. 检查1:已确认异常日期 × 请假流程
|
||
# ----------------------------------------------
|
||
def check_leave_after_confirm(abnormal_confirmed: List[Dict[str, Any]],
|
||
leave_index: Dict[Tuple[str, str], Dict]) -> List[Dict[str, Any]]:
|
||
"""已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。
|
||
|
||
若存在,说明可能是「提前确认后请假」导致仍为考勤异常,需人工复核。
|
||
"""
|
||
rows: List[Dict[str, Any]] = []
|
||
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
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 5. 检查2:休息日半天加班 × 打卡校验(结合排班班段)
|
||
# ----------------------------------------------
|
||
def check_rest_day_half_day_punch(session, user_id: str, treecode: str,
|
||
rest_overtime: List[Dict[str, Any]],
|
||
begin: str, end: str) -> List[Dict[str, Any]]:
|
||
"""休息日加班(类型3)且加班天数为 0.5 天时,校验当日打卡是否按考勤班段正常打卡。
|
||
|
||
步骤:
|
||
1. 按工号拉取排班(fetch_all_shift),取加班日期的班段时间(bc_time);
|
||
2. 拉取该员工当日打卡流水(fetch_all_kq_data);
|
||
3. 结合班段判定:最早打卡覆盖班段开始、最晚打卡覆盖班段结束且次数>=2 → 正常,
|
||
否则漏打卡;休息日排班(无班段)则退化为按打卡次数判断。
|
||
"""
|
||
rows: List[Dict[str, Any]] = []
|
||
half_ots = [ot for ot in rest_overtime if _is_half_day_ot(ot)]
|
||
logger.info("休息日半天加班 %d 条,逐一校验打卡(结合排班班段)", len(half_ots))
|
||
|
||
# 按工号缓存排班记录,避免重复请求
|
||
shift_cache: Dict[str, List[Dict[str, Any]]] = {}
|
||
|
||
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
|
||
try:
|
||
kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode)
|
||
except HRSessionExpiredError:
|
||
# fetch_all_kq_data 内部已处理重登;此处兜底
|
||
raise
|
||
|
||
# 拉取该员工排班(缓存),取加班日的班段
|
||
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
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 6. 检查3:整日请假 × 考勤异常 → 提示
|
||
# ----------------------------------------------
|
||
def check_full_day_leave_abnormal(abnormal_confirmed: List[Dict[str, Any]],
|
||
abnormal_open: List[Dict[str, Any]],
|
||
leaves: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。
|
||
|
||
异常并集 = 未调整(is_adjusted=0) + 已确认(is_adjusted=2)。
|
||
"""
|
||
rows: List[Dict[str, Any]] = []
|
||
|
||
# 整日请假日期索引 {(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
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 7. 导出多 Sheet Excel 报告
|
||
# ----------------------------------------------
|
||
def export_report(results: Dict[str, List[Dict[str, Any]]], save_dir: str, month_str: str) -> str:
|
||
"""将三项检查结果导出为多 Sheet Excel 报告。
|
||
|
||
Sheet 顺序:汇总 -> 检查1 -> 检查2 -> 检查3(无数据的 Sheet 也保留表头便于对照)。
|
||
"""
|
||
if pd is None:
|
||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||
|
||
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
|
||
|
||
|
||
# ----------------------------------------------
|
||
# 8. 对外便捷入口
|
||
# ----------------------------------------------
|
||
def handle_abnormal_check(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
|
||
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() -> 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_abnormal_check(save_dir, month)
|
||
logger.info("===== 月考勤异常三查完成,导出:%s =====", out)
|
||
except Exception as e:
|
||
if "正被占用" in str(e):
|
||
logger.error("=========== 提醒 ===========")
|
||
logger.error(str(e))
|
||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||
return
|
||
logger.error("月考勤异常三查失败:%s", e)
|
||
raise
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|