Files
37duAutomation/plugins/XQ0001-0100/XQ0004 EHR系统加班流程审核/logic/overtime_rules.py
T

637 lines
29 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 -*-
"""XQ0004 EHR系统加班流程审核 插件 - 加班校验规则层。
迁移自 workflows/XQ0001-0100/XQ0004 EHR系统加班流程审核/overtime_approval.py:
- 登录态改造:SessionPage → 底座注入 requests.Session(data.hr_api.get_* 接口)
- 日志改造:print 输出与进程退出提示 → config.logger
- 规则逻辑(时长取整/弹性兑换/休息日法定假日加班/审核周期)原样保留
"""
import calendar
import math
from datetime import datetime, timedelta
from chinese_calendar import get_holiday_detail, is_in_lieu
from ..config import (
logger,
WORK_START_TIME,
WORK_END_TIME,
FLEX_TRIGGER_TIME,
FLEX_LATE_LUNCH_TRIGGER_TIME,
LUNCH_BREAK_HOURS,
OT_MIN_HOURS,
CROSS_DAY_BEFORE_HOUR,
OT_REVIEW_DAYS,
OT_REVIEW_EXEMPT_POST_KEYWORDS,
MONTH_CUTOFF_DAY,
MONTH_CUTOFF_HOUR,
ZHINENG_HALF_MORNING_HOURS,
ZHINENG_HALF_AFTERNOON_HOURS,
ZHINENG_HALF_CUTOFF_HOUR,
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES,
OT_TYPE_MAP,
SUBSIDY_TYPE_MAP,
)
from ..data.hr_api import get_attendance_daily, get_leave_records, get_punch_records
# ==================== 加班表单解析 ====================
def parse_overtime_form(result):
ot_type_code = result.get("ot_type")
subsidy_type_code = result.get("subsidy_type")
overtime_info = {
"加班人员ID": result.get("staff_id"),
"加班人员": result.get("staff_name"),
"组织全路径": result.get("org_full_path"),
"岗位": result.get("post_name"),
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
"加班日期": result.get("ot_date"),
"加班开始时间": result.get("start_time"),
"加班结束时间": result.get("end_time"),
"加班时长(小时)": result.get("ot_hour") or result.get("expect_hour"),
"加班天数(天)": result.get("ot_day"),
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
"系统判断加班天数(天)": result.get("judge_ot_day"),
"附件": result.get("file"),
}
judge_start = result.get("judge_start_time")
judge_end = result.get("judge_end_time")
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
if (judge_start and judge_end
and "无" not in str(judge_start) and "无" not in str(judge_end)):
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
else:
overtime_info["系统判定加班时间"] = None
return overtime_info
# ==================== 加班校验规则 ====================
def _parse_dt(value):
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, end):
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, flex_trigger):
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
def _calc_day_ot_threshold(days):
return 8.0 * days + int(days)
def _next_day(date_str):
d = datetime.strptime(date_str, "%Y-%m-%d")
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
def _is_within_arrival_window(punch_str, start_dt,
before_hours=OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
after_minutes=OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES):
"""提前到岗型加班:判断打卡时间是否落在加班开始时间附近的到岗证据窗口内。"""
p = _parse_dt(punch_str)
if p is None:
return False
return (start_dt - timedelta(hours=before_hours)) <= p <= (start_dt + timedelta(minutes=after_minutes))
def _is_spring_festival(date_str):
try:
date = datetime.strptime(date_str, "%Y-%m-%d").date()
is_holiday, holiday_name = get_holiday_detail(date)
return (is_holiday and holiday_name == 'Spring Festival'
and not 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, staff_id, date_str):
if not date_str or not staff_id:
return "未知"
try:
records = get_attendance_daily(session, staff_id, date_str, date_str)
for r in records:
if str(r.get("work_day", "")) == date_str:
bc = r.get("bc_name")
if bc:
return str(bc)
# 休息日记录 bc_name 为空,以异常状态标识判断(abnormal_name/kq_status_name1);
# 用前缀"休息"匹配,兼容"休息"/"休息(调)"/"休息(补)"等变体
if str(r.get("abnormal_name") or r.get("kq_status_name1") or "").startswith("休息"):
return "休息"
return "无排班"
return "无排班"
except Exception as e:
logger.warning("获取排班失败(%s): %s", date_str, str(e))
return "获取失败"
def _is_zhineng_schedule(session, staff_id, date_str):
"""
判断员工是否为职能排班(休息日/节假日加班半天规则专用)。
不看加班当天(当天排班通常显示'休息'),而是查看当月每日考勤中的其他天:
只要任一天班次包含'职能'(如 职能正班A),即按职能排班处理。
排班获取失败时优雅降级返回 False,沿用默认半天4小时规则。
"""
if not date_str or not staff_id:
return False
try:
year = int(date_str[:4])
month = int(date_str[5:7])
first_day = f"{year:04d}-{month:02d}-01"
last_day = f"{year:04d}-{month:02d}-{calendar.monthrange(year, month)[1]:02d}"
records = get_attendance_daily(session, staff_id, first_day, last_day)
return any("职能" in (r.get("bc_name") or "") for r in records)
except Exception as e:
logger.warning("获取排班判断职能失败(%s): %s", date_str, str(e))
return False
def _check_attendance(session, staff_id, ot_date):
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
def _extract_shift_times(daily_records, date_str):
"""从每日考勤记录中提取指定日期的班次起止时间("HH:MM"),无则返回 (None, None)。
数据源为 rf_s_kq_count_leave_yc_day_all 接口返回的每日记录
(字段 work_day + bc_begin_time/bc_end_time),据此可拿到员工当天实际排班的
下班时间(如维护早班 08:00-17:00),避免延时加班校验错误使用默认 18:00。
"""
for r in daily_records:
if str(r.get("work_day", "")) != date_str:
continue
b = r.get("bc_begin_time")
e = r.get("bc_end_time")
return (str(b).strip()[:5] if b else None,
str(e).strip()[:5] if e else None)
return None, None
def _check_punch_records(session, staff_id, ot_date):
if not ot_date or not staff_id:
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
"次日班次开始时间": None, "打卡备注": "缺少加班日期或员工ID"}
start = datetime.strptime(ot_date, "%Y-%m-%d")
prev_day = (start - timedelta(days=1)).strftime("%Y-%m-%d")
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
try:
# 打卡明细接口返回 kq_time=真实打卡时间 与 bc_date=考勤归属日,
# 跨天打卡(次日0点~6点)由系统归入加班当天,无需人工拼接/修正日期;
# 范围扩到前一天是为了兼容提前到岗型加班(开始<=6点)到岗打卡被归到前一天的情况。
punches = get_punch_records(session, staff_id, prev_day, next_day)
if not punches:
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
"次日班次开始时间": None, "打卡备注": "当天及次日无打卡记录"}
# 按考勤归属日 bc_date 分组;time_order:1=上班打卡、2=下班打卡
arrivals = {}
checkouts = {}
all_by_date = {}
for r in punches:
bd = str(r.get("bc_date", "")).strip()
t = str(r.get("kq_time", "")).strip()
if not bd or not t:
continue
all_by_date.setdefault(bd, []).append(t)
if str(r.get("time_order", "")).strip() == "1":
arrivals.setdefault(bd, []).append(t)
elif str(r.get("time_order", "")).strip() == "2":
checkouts.setdefault(bd, []).append(t)
# 班次起止时间仍由考勤逐日接口提供;未获取到时由上层回退默认 09:00/18:00
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
# 次日班次开始时间:弹性到岗兑换计算晚到时长时,次日上班时间优先取排班开始时间
next_shift_begin, _ = _extract_shift_times(daily, next_day)
def _sorted(date_str):
return sorted(all_by_date.get(date_str, []))
# 当日最早/最晚打卡:优先按上下班类型取,缺该类型时回退取当天全部打卡
day_all = _sorted(ot_date)
day_arrivals = sorted(arrivals.get(ot_date, []))
day_checkouts = sorted(checkouts.get(ot_date, []))
day_first = day_arrivals[0] if day_arrivals else (day_all[0] if day_all else None)
day_last = day_checkouts[-1] if day_checkouts else (day_all[-1] if day_all else None)
# 次日最早打卡(弹性兑换用)
next_arrivals = sorted(arrivals.get(next_day, []))
next_all = _sorted(next_day)
next_first = next_arrivals[0] if next_arrivals else (next_all[0] if next_all else None)
# 前一天最晚打卡(提前到岗型加班用)
prev_all = _sorted(prev_day)
prev_last = prev_all[-1] if prev_all else None
return {
"当日最早打卡": day_first,
"当日最晚打卡": day_last,
"次日最早打卡": next_first,
"前一天最晚打卡": prev_last,
"班次开始时间": shift_begin,
"班次结束时间": shift_end,
"次日班次开始时间": next_shift_begin,
"打卡备注": "",
}
except Exception as e:
logger.warning("获取打卡明细失败: %s", str(e))
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
"次日班次开始时间": None, "打卡备注": f"获取失败: {e}"}
def _check_leave_covers_morning(session, staff_id, date_str):
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
# 上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
shift_begin = None
try:
daily = get_attendance_daily(session, staff_id, date_str, date_str)
shift_begin, _ = _extract_shift_times(daily, date_str)
except Exception as e:
logger.warning("获取排班时段失败(%s): %s", date_str, str(e))
morning_time = shift_begin or WORK_START_TIME
morning = datetime.strptime(f"{date_str} {morning_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, punch, session, staff_id):
ot_date = info.get("加班日期")
start = _parse_dt(info.get("加班开始时间"))
end = _parse_dt(info.get("加班结束时间"))
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
reasons = []
# 申请结束时间晚于实际下班打卡、但实际在岗时长(按系统取整)仍满足申请时长时,用于附加到通过备注
end_checkout_note = ""
# 1. 日期校验:加班开始日期与申请加班日期不一致时直接校验不通过未处理,
# 无需再校验后续的时长、区间合规等内容
if start is None:
reasons.append("加班开始时间缺失")
elif start.strftime("%Y-%m-%d") != ot_date:
reason = f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致"
info["计算加班时长(小时)"] = None
info["弹性扣减(小时)"] = 0
info["有效加班时长(小时)"] = 0
info["弹性额度D(小时)"] = 0
return "校验不通过未处理", reason
# 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. 区间合规校验
# 班次起止时间优先用打卡明细携带的班次时段(bc_begin_time/bc_end_time),
# 未获取到时回退默认 09:00/18:00(常规班次),避免非18点下班班次被误判。
shift_begin = punch.get("班次开始时间") or WORK_START_TIME
shift_end = punch.get("班次结束时间") or WORK_END_TIME
work_start = datetime.strptime(f"{ot_date} {shift_begin}", "%Y-%m-%d %H:%M")
work_end = datetime.strptime(f"{ot_date} {shift_end}", "%Y-%m-%d %H:%M")
# 提前到岗型延时加班:加班开始时间早于当天班次开始时间。
# 常规"晚于规定下班时间""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
# - 开始<=6点时,到岗打卡可能被系统归到前一天(跨天打卡),需回看前一天记录;
# - 6点~9点开始的,到岗打卡归属当天,只看当天记录。
is_pre_shift = start is not None and start < work_start
if is_pre_shift:
candidates = [punch.get("当日最早打卡")]
cross_cutoff = start.replace(hour=CROSS_DAY_BEFORE_HOUR, minute=0, second=0, microsecond=0)
if start <= cross_cutoff:
candidates.append(punch.get("前一天最晚打卡"))
arrival_punch = next(
(c for c in candidates if _is_within_arrival_window(c, start)),
None,
)
if arrival_punch is None:
reasons.append(f"提前到岗型加班,未找到加班开始时间({start:%H:%M})附近的到岗打卡")
else:
info["到岗打卡"] = arrival_punch
else:
if start is not None and start < work_end:
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({shift_end})")
if end is not None:
if actual_checkout is None:
reasons.append("当日无下班打卡记录,无法校验区间合规")
elif start is not None and hours is not None:
# 核心原则:申请的加班时长必须与打卡可支撑的实际在岗时长相符。
# 按系统取整规则(_calc_delayed_hours),用实际打卡区间(申请开始->实际下班打卡)
# 计算实际在岗时长,>= 申请时长即通过(申请结束时间比打卡晚几分钟也属正常)。
# 例:申请 18:00-23:05(取整5h),实际打卡23:00:45,实际在岗取整后也是5h,应通过
actual_hours = _calc_delayed_hours(start, actual_checkout)
if actual_hours >= hours:
if end > actual_checkout:
end_checkout_note = (
f"申请结束时间({end:%H:%M})晚于实际下班打卡({actual_checkout:%H:%M:%S}),"
f"实际在岗时长按系统取整为{actual_hours:g}小时,满足申请时长"
)
else:
reasons.append(
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S}),"
f"实际在岗时长按取整仅{actual_hours:g}小时,不足申请{hours:g}小时"
)
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:
# 次日上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
next_shift_begin = punch.get("次日班次开始时间") or WORK_START_TIME
work_start = datetime.strptime(f"{next_day} {next_shift_begin}", "%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:
# 有晚到,校验:加班时长 + 晚到 <= 实际在岗时长(按系统取整)
# 实际在岗时长 = 加班开始->实际下班打卡 按延时取整(1h起算0.5h累加)
actual_work = _calc_delayed_hours(start, actual_checkout)
lunch_trigger = datetime.strptime(
f"{next_day} {FLEX_LATE_LUNCH_TRIGGER_TIME}", "%Y-%m-%d %H:%M"
)
if p <= work_start + timedelta(hours=d_hours):
# T < P <= T+D:晚到时长 = P-T,次日打卡超过13:00时
# 再扣1小时午餐,按1小时起算向上取整(不足1小时不扣)
late_raw = (p - work_start).total_seconds() / 3600
if p > lunch_trigger:
late_raw -= LUNCH_BREAK_HOURS
late_hours = math.ceil(late_raw) if late_raw >= OT_MIN_HOURS else 0
if late_hours < 1:
flex_note = f"次日打卡({p:%H:%M})晚到不足1小时,不触发弹性兑换"
else:
if hours + late_hours > actual_work:
info["弹性扣减(小时)"] = 0
info["有效加班时长(小时)"] = hours
info["弹性额度D(小时)"] = d_hours
return "校验不通过未处理", (
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 晚到{late_hours}h "
f"> 实际在岗时长{actual_work:g}h"
)
deduction = float(late_hours)
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
else:
if hours + d_hours > actual_work:
info["弹性扣减(小时)"] = 0
info["有效加班时长(小时)"] = hours
info["弹性额度D(小时)"] = d_hours
return "校验不通过未处理", (
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
f"> 实际在岗时长{actual_work:g}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}小时"
extra_parts = [end_checkout_note, flex_note]
extra = ";".join(p for p in extra_parts if p)
if extra:
note += f"({extra})"
return "通过", note
def _validate_day_ot(info, punch, session, staff_id, require_holiday):
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或缺失")
first = _parse_dt(punch.get("当日最早打卡"))
last = _parse_dt(punch.get("当日最晚打卡"))
interval = None
# 打卡明细接口已按考勤归属日 bc_date 分组,跨天打卡(次日0点~6点)归入加班当天,
# 因此当日最早/最晚打卡已包含跨天下班打卡,无需再参考次日打卡补全。
if first is None or last is None:
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)
# 职能排班半天(0.5天)加班:上午3.5小时、下午4.5小时,不再统一按4小时半天处理;
# 上/下午按申请加班开始时间判定(早于12:00视为上午半天)
if abs(apply_days - 0.5) < 1e-9 and _is_zhineng_schedule(session, staff_id, ot_date):
start = _parse_dt(info.get("加班开始时间"))
if start is not None and start.hour < ZHINENG_HALF_CUTOFF_HOUR:
threshold = ZHINENG_HALF_MORNING_HOURS
else:
threshold = ZHINENG_HALF_AFTERNOON_HOURS
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 _is_review_period_exempt(post_name):
"""岗位名包含豁免关键字(如「门店店长」)时不受审核周期天数限制。"""
name = str(post_name or "").strip()
return bool(name) and any(kw in name for kw in OT_REVIEW_EXEMPT_POST_KEYWORDS)
def _is_same_day_ot(ot_date, today=None):
"""加班日期是否为当天。
当天发起当天加班时下班卡还没打,打卡校验必然不通过,本次直接跳过不审核,
等次日打卡齐全后再由后续运行审核。
"""
if not ot_date:
return False
try:
ot_day = datetime.strptime(str(ot_date).strip()[:10], "%Y-%m-%d").date()
except (TypeError, ValueError):
return False
return ot_day == (today or datetime.now()).date()
def check_review_period(ot_date, post_name=None, today=None):
"""
加班日期有效性前置校验,返回 (是否可审核, 原因)。
规则:
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
(岗位命中 OT_REVIEW_EXEMPT_POST_KEYWORDS,如门店店长,则不受该天数限制)
2. 月度截止:每月 MONTH_CUTOFF_DAY 号 MONTH_CUTOFF_HOUR:00 之后,
不再审核上一个月的加班流程。
"""
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 not _is_review_period_exempt(post_name) \
and (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, session):
form_data = doc.get("formData", {}) or {}
overtime_info = parse_overtime_form(form_data)
# 前置校验:加班日期有效性(8天审核周期 + 每月2号12点后不再审核上月加班)
# 门店店长岗位不受 8 天审核周期限制,仍受月度截止约束
valid, period_reason = check_review_period(overtime_info.get("加班日期"), 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("加班日期")
# 当天发起当天的加班:下班卡尚未打,打卡校验必然不通过;
# 本次直接跳过不审核(不提交、不推送),等次日打卡齐全后再由后续运行审核
if _is_same_day_ot(ot_date):
return {
"title": doc.get("title", ""),
"creator": doc.get("creator", ""),
"time": doc.get("time", ""),
"detail_url": doc.get("detail_url", ""),
"decision": "跳过",
"note": f"加班日期({ot_date})为当天,本次跳过审核,待打卡完成后再次审核",
"overtime_info": overtime_info,
}
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,
}