Files
37duAutomation/app/service/hrbp/oa/work_overtime/validator.py
T
puddy 9927066abb feat: 新增考勤异常模块、银行卡校验、OCR附件检测等功能
1. 新增考勤异常查询与导出模块,支持当月异常拉取、Excel导出、钉钉推送提醒
2. 完善请假/加班流程解析与校验,新增附件下载、OCR核验能力
3. 新增银行卡信息校验模块,支持在职/离职员工工资卡数据核对与异常导出
4. 新增通用OCR工具模块,支持病假/婚假/产检假附件关键词检测与日期提取
5. 新增门店请休假异常名单、银行卡检查等需求文档
6. 重构部分现有模块代码,优化配置与接口调用逻辑
7. 新增测试文件与工具类,完善项目基础能力
2026-08-11 17:26:24 +08:00

506 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@Module: hrbp.oa.work_overtime.validator
@FileName: validator.py
@Author: 小布丁
@CreateTime: 2026-08-05 21:35
@Description: 加班流程校验模块(按 aa.md 审批规则:延时加班/休息日加班/法定假日加班,判定通过/驳回/超期)
@Version: 3.2.0
"""
import math
from datetime import datetime, timedelta
from typing import Any, Dict, Optional
from app.utils.logger import get_logger
logger = get_logger(__name__)
from app.service.hrbp.oa.work_overtime.parser import parse_overtime_form
from app.service.hrbp.oa.common.oa_api import (
get_attendance_html,
get_attendance_records,
get_leave_records,
)
from app.service.hrbp.oa.common.parser import parse_attendance_html, summarize_attendance_records
from app.service.hrbp.oa.common.config import (
WORK_START_TIME,
WORK_END_TIME,
FLEX_TRIGGER_TIME,
OT_MIN_HOURS,
CROSS_DAY_BEFORE_HOUR,
OT_REVIEW_DAYS,
MONTH_CUTOFF_DAY,
MONTH_CUTOFF_HOUR,
)
# ---------- 通用工具 ----------
def _parse_dt(value: Any) -> Optional[datetime]:
"""解析 "YYYY-MM-DD HH:MM[:SS]" 格式时间,失败返回 None"""
if not value:
return None
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
try:
return datetime.strptime(str(value), fmt)
except ValueError:
continue
return None
def _calc_delayed_hours(start: datetime, end: datetime) -> float:
"""
延时加班计时:1小时起算,超过1小时的部分按0.5小时累加,不足0.5小时舍去。
不足1小时返回0。
示例:1.0->1.0, 1.4->1.0, 1.5->1.5, 1.9->1.5, 2.0->2.0, 2.3->2.0, 2.5->2.5
"""
total = (end - start).total_seconds() / 3600
if total < 1:
return 0.0
return 1.0 + math.floor((total - 1) / 0.5) * 0.5
def _calc_flex_d(actual_checkout: datetime, flex_trigger: datetime) -> float:
"""
弹性额度 D 计算(基于实际下班打卡时间):
实际下班打卡 >= 23:00 时,D = 1 + floor((打卡-23:00)/0.5) * 0.5
"""
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
def _calc_day_ot_threshold(days: float) -> float:
"""
休息日/法定假日加班打卡间隔阈值:8 * days + int(days)。
0.5天->4h, 1天->9h, 1.5天->13h, 2天->18h, 2.5天->22h
"""
return 8.0 * days + int(days)
def _next_day(date_str: str) -> str:
"""日期字符串 +1 天"""
d = datetime.strptime(date_str, "%Y-%m-%d")
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
def _is_spring_festival(date_str: str) -> bool:
"""
判断日期是否为春节法定节假日(初一至初三)。
用 chinese_calendar 的 get_holiday_detail 判断 holiday_name == 'Spring Festival',
且 is_in_lieu=False(排除调休日),且非周末(排除正常周末)。
判定失败时按非春节处理(优雅降级)。
"""
try:
import chinese_calendar as cc
date = datetime.strptime(date_str, "%Y-%m-%d").date()
is_holiday, holiday_name = cc.get_holiday_detail(date)
return (is_holiday
and holiday_name == 'Spring Festival'
and not cc.is_in_lieu(date)
and date.weekday() < 5)
except Exception as e:
logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e))
return False
# ---------- 排班 / 打卡 / 请假查询 ----------
def _get_shift(session: Any, staff_id: str, date_str: str) -> str:
"""获取指定日期员工的排班班次(自动处理跨月)"""
if not date_str or not staff_id:
return "未知"
try:
year = int(date_str[:4])
month = int(date_str[5:7])
html = get_attendance_html(session, staff_id, year, month)
attendance = parse_attendance_html(html)
return attendance.get(date_str, "无排班")
except Exception as e:
logger.warning("获取排班失败(%s): %s", date_str, str(e))
return "获取失败"
def _check_attendance(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
"""查询员工在加班日期的排班班次"""
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
"""
查询员工在加班日及次日的打卡明细,按日汇总。
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日,因此查询
范围扩展到 ot_date 次日;次日最早打卡用于延时加班的弹性到岗兑换判定。
"""
if not ot_date or not staff_id:
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
"打卡备注": "缺少加班日期或员工ID"}
start = datetime.strptime(ot_date, "%Y-%m-%d")
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
try:
records = get_attendance_records(session, staff_id, ot_date, next_day)
summary = summarize_attendance_records(records)
day_summary = next((r for r in summary if r["attend_date"] == ot_date), None)
next_summary = next((r for r in summary if r["attend_date"] == next_day), None)
if not day_summary and not next_summary:
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
"打卡备注": "当天及次日无打卡记录"}
return {
"当日最早打卡": day_summary["first_check_in"] if day_summary else None,
"当日最晚打卡": day_summary["last_check_out"] if day_summary else None,
"次日最早打卡": next_summary["first_check_in"] if next_summary else None,
"打卡备注": "",
}
except Exception as e:
logger.warning("获取打卡明细失败: %s", str(e))
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
"打卡备注": f"获取失败: {e}"}
def _check_leave_covers_morning(session: Any, staff_id: str, date_str: str) -> bool:
"""
判断指定日期是否有请假覆盖早上上班时间(用于弹性兑换触发判定)。
只要任意请假区间覆盖了当日 WORK_START_TIME(如 09:00),即视为早上无需到岗,
不触发弹性兑换。查询范围向前一天扩展,确保能查到跨天请假。
"""
prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
try:
records = get_leave_records(session, staff_id, prev_day, date_str)
except Exception as e:
logger.warning("获取请假记录失败: %s", str(e))
return False
morning = datetime.strptime(f"{date_str} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
for r in records:
start = _parse_dt(r.get("start_time"))
end = _parse_dt(r.get("end_time"))
if start and end and start <= morning <= end:
return True
return False
# ---------- 规则一:延时加班 ----------
def _validate_delayed(
info: Dict[str, Any], punch: Dict[str, Any], session: Any, staff_id: str
) -> tuple:
"""
延时加班审批(按 aa.md 规则一):
(一)驳回门槛:
1. 日期匹配:加班开始时间所属日期 = 申请加班日期;
2. 时长达标:1小时起算,超1小时按0.5h累加,不足1h驳回;
3. 区间合规:开始时间 >= 规定下班时间(18:00),结束时间 <= 实际下班打卡时间。
(二)弹性到岗兑换(仅影响结算,校验驳回则驳回):
D 基于实际下班打卡时间计算,>= 23:00 时 D = 1 + floor((打卡-23:00)/0.5)*0.5。
次日休息/请假覆盖09:00/无打卡 -> 不触发兑换。
正常工作日按次日打卡 P 校验:P<=09:00 不扣;09:00<P<=09:00+D 扣 ceil(P-09:00);
P>09:00+D 扣 D。兑换校验:加班时长+晚到 <= 加班开始到次日打卡的总自然时长。
"""
ot_date = info.get("加班日期")
start = _parse_dt(info.get("加班开始时间"))
end = _parse_dt(info.get("加班结束时间"))
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
reasons = []
# 1. 日期校验
if start is None:
reasons.append("加班开始时间缺失")
elif start.strftime("%Y-%m-%d") != ot_date:
reasons.append(f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致")
# 2. 时长校验
hours = None
if end is None:
reasons.append("加班结束时间缺失")
elif start is not None:
hours = _calc_delayed_hours(start, end)
if hours < OT_MIN_HOURS:
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
# 3. 区间合规校验:开始 >= 规定下班时间,结束 <= 实际下班打卡时间
work_end = datetime.strptime(f"{ot_date} {WORK_END_TIME}", "%Y-%m-%d %H:%M")
if start is not None and start < work_end:
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})")
if end is not None:
if actual_checkout is None:
reasons.append("当日无下班打卡记录,无法校验区间合规")
elif end > actual_checkout:
reasons.append(
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})"
)
info["计算加班时长(小时)"] = hours
if reasons:
info["弹性扣减(小时)"] = 0
info["有效加班时长(小时)"] = hours
info["弹性额度D(小时)"] = 0
return "驳回", ";".join(reasons)
# 4. 弹性到岗兑换(仅影响结算时长)
deduction = 0.0
flex_note = ""
d_hours = 0.0
flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M")
if actual_checkout is not None and actual_checkout >= flex_trigger:
d_hours = _calc_flex_d(actual_checkout, flex_trigger)
next_day = _next_day(ot_date)
next_shift = _get_shift(session, staff_id, next_day)
if next_shift in ("休息", "无排班"):
flex_note = f"次日({next_day})为休息日,不触发弹性兑换"
elif next_shift in ("获取失败", "未知"):
flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换"
elif _check_leave_covers_morning(session, staff_id, next_day):
flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换"
else:
work_start = datetime.strptime(f"{next_day} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
p = _parse_dt(punch.get("次日最早打卡"))
if p is None:
flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换"
elif p <= work_start:
flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换"
else:
# 有晚到,校验:加班时长 + 晚到 <= 加班开始到次日打卡的总自然时长
total_natural = (p - start).total_seconds() / 3600
if p <= work_start + timedelta(hours=d_hours):
# 09:00 < P <= 09:00+D:晚到时长 = ceil(P-09:00),不足1h按1h
late_hours = max(1, math.ceil((p - work_start).total_seconds() / 3600))
if hours + late_hours > total_natural:
info["弹性扣减(小时)"] = 0
info["有效加班时长(小时)"] = hours
info["弹性额度D(小时)"] = d_hours
return "驳回", (
f"弹性兑换校验驳回:申请加班{hours:g}h + 晚到{late_hours}h "
f"> 总自然时长{total_natural:.1f}h"
)
deduction = float(late_hours)
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
else:
# P > 09:00+D:兑换额度最高按D,超出部分交考勤处理
if hours + d_hours > total_natural:
info["弹性扣减(小时)"] = 0
info["有效加班时长(小时)"] = hours
info["弹性额度D(小时)"] = d_hours
return "驳回", (
f"弹性兑换校验驳回:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
f"> 总自然时长{total_natural:.1f}h"
)
deduction = float(d_hours)
flex_note = (
f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h),"
f"按D兑换,超出部分交考勤处理"
)
else:
if actual_checkout is not None:
flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0"
effective = max(0.0, float(hours) - deduction)
info["弹性扣减(小时)"] = deduction
info["有效加班时长(小时)"] = effective
info["弹性额度D(小时)"] = d_hours
note = f"审批通过,有效加班时长{effective:g}小时"
if flex_note:
note += f"({flex_note})"
return "通过", note
# ---------- 规则二/三:休息日 / 法定假日加班 ----------
def _validate_day_ot(
info: Dict[str, Any],
punch: Dict[str, Any],
session: Any,
staff_id: str,
require_holiday: bool,
) -> tuple:
"""
休息日/法定假日加班审批(任一条件不满足即驳回):
- 排班显示为休息;
- 法定假日(仅春节):申请日期必须为春节法定节假日;
- 加班时长 > 0;
- 当天有上下班打卡(跨天打卡处理:当天无打卡时,若次日首条打卡早于6点,
视为归属加班当天的跨天有效打卡,不再因缺打卡驳回);
- 打卡时间间隔满足申报天数(0.5天>=4h, 1天>=9h, 1.5天>=13h, 2天>=18h...)。
"""
ot_date = info.get("加班日期")
reasons = []
# 排班须显示为休息;排班获取失败/未知时优雅降级
shift = info.get("加班当天班次", "")
if shift not in ("休息", "获取失败", "未知", "无排班"):
reasons.append(f"当天排班为'{shift}',非休息日")
if require_holiday and not _is_spring_festival(ot_date):
reasons.append(f"{ot_date}不在春节法定节假日列表中")
# 加班时长 > 0:休息日加班按天计,表单 ot_hour 常为 0(aa.md 中 ot_hours=0.0、ot_days=1.00),
# 此时用申报起止时间推算实际加班时长,避免误驳回
ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)")
try:
ot_hour = float(ot_hour)
except (TypeError, ValueError):
ot_hour = 0.0
if ot_hour <= 0:
start = _parse_dt(info.get("加班开始时间"))
end = _parse_dt(info.get("加班结束时间"))
if start and end and end > start:
ot_hour = (end - start).total_seconds() / 3600
if ot_hour <= 0:
reasons.append("加班时长为0或缺失")
# 当天有上下班打卡,且打卡时间间隔满足申报天数
# 跨天打卡处理:当天缺打卡时参考次日首条打卡,次日首条早于6点视为归属加班当天
first = _parse_dt(punch.get("当日最早打卡"))
last = _parse_dt(punch.get("当日最晚打卡"))
next_first = _parse_dt(punch.get("次日最早打卡"))
interval = None
if first is None or last is None:
if next_first is not None and next_first.hour < CROSS_DAY_BEFORE_HOUR:
# 次日首条早于6点 -> 加班当天跨天有效打卡,补全当天缺失的打卡
had_punch = (first is not None) or (last is not None)
first = first if first is not None else next_first
last = last if last is not None else next_first
info["跨天打卡"] = "是"
# 当天全无打卡时仅凭跨天记录,视为满足"至少一条打卡"要求,不计算间隔
if had_punch:
interval = (last - first).total_seconds() / 3600
else:
reasons.append("当天缺少上班或下班打卡")
else:
interval = (last - first).total_seconds() / 3600
apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)")
try:
apply_days = float(apply_days)
except (TypeError, ValueError):
apply_days = 0.0
if apply_days <= 0:
reasons.append("申报天数缺失或为0")
elif interval is not None:
threshold = _calc_day_ot_threshold(apply_days)
if interval < threshold:
reasons.append(
f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时"
)
info["打卡时间间隔(小时)"] = interval
info["申报天数(天)"] = apply_days
if reasons:
return "驳回", ";".join(reasons)
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
# ---------- 加班日期有效性前置校验 ----------
def check_review_period(ot_date: Optional[str], today: Optional[datetime] = None) -> tuple:
"""
加班日期有效性前置校验,返回 (是否可审核, 原因)。
规则:
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
2. 月度截止:每月 MONTH_CUTOFF_DAY 号 MONTH_CUTOFF_HOUR:00 之后,
不再审核上一个月的加班流程。
Args:
ot_date: 加班日期 "YYYY-MM-DD"
today: 当前时间(默认 datetime.now(),便于测试注入)
Returns:
(True, "") 可审核;否则 (False, 原因)
"""
if not ot_date:
return False, "加班日期缺失,无法校验审核周期"
try:
ot_day = datetime.strptime(ot_date, "%Y-%m-%d")
except (TypeError, ValueError):
return False, f"加班日期格式非法: {ot_date}"
today = today or datetime.now()
today_date = today.date()
# 规则1:8天审核周期
if (today_date - ot_day.date()).days > OT_REVIEW_DAYS:
return False, f"加班日期({ot_date})距今超过{OT_REVIEW_DAYS}天审核周期,不再审核"
# 规则2:每月2号12点之后不再审核上月加班
if ot_day.date() < today_date.replace(day=1):
if today.day > MONTH_CUTOFF_DAY or (today.day == MONTH_CUTOFF_DAY and today.hour >= MONTH_CUTOFF_HOUR):
return False, (f"加班日期({ot_date})属于上月或更早,已超过本月{MONTH_CUTOFF_DAY}号"
f"{MONTH_CUTOFF_HOUR}点,不再审核上月加班流程")
return True, ""
# ---------- 主入口 ----------
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
"""
校验单张加班单据,返回审批决策(通过 / 驳回)。
按加班类型分派规则:
ot_type=1 延时加班;
ot_type=3 休息日加班;
ot_type=2 法定假日加班(仅春节法定节假日走规则三,非春节按休息日规则执行)。
Args:
doc: 单据信息,含基本信息(title/creator/time/detail_url)
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
session: 已登录的 SessionPage 对象(用于调用排班/打卡/请假接口)
Returns:
校验结果,包含审批决策、原因说明及解析后的加班信息
"""
form_data = doc.get("formData", {}) or {}
overtime_info = parse_overtime_form(form_data)
# 前置校验:加班日期有效性(8天审核周期 + 每月2号12点后不再审核上月加班)
valid, period_reason = check_review_period(overtime_info.get("加班日期"))
if not valid:
return {
"title": doc.get("title", ""),
"creator": doc.get("creator", ""),
"time": doc.get("time", ""),
"detail_url": doc.get("detail_url", ""),
"decision": "超期",
"note": period_reason,
"overtime_info": overtime_info,
}
staff_id = overtime_info.get("加班人员ID")
ot_date = overtime_info.get("加班日期")
attendance_info = _check_attendance(session, staff_id, ot_date)
punch_info = _check_punch_records(session, staff_id, ot_date)
overtime_info.update(attendance_info)
overtime_info.update(punch_info)
ot_type_code = str(form_data.get("ot_type") or "")
if ot_type_code == "1":
decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id)
elif ot_type_code == "3":
decision, note = _validate_day_ot(
overtime_info, punch_info, session, staff_id, require_holiday=False
)
elif ot_type_code == "2":
# 法定假日加班:仅春节法定节假日适用规则三,非春节按休息日规则执行
require_holiday = _is_spring_festival(ot_date)
decision, note = _validate_day_ot(
overtime_info, punch_info, session, staff_id, require_holiday=require_holiday
)
else:
decision, note = "驳回", f"无法识别加班类型: {ot_type_code}"
return {
"title": doc.get("title", ""),
"creator": doc.get("creator", ""),
"time": doc.get("time", ""),
"detail_url": doc.get("detail_url", ""),
"decision": decision,
"note": note,
"overtime_info": overtime_info,
}