# -*- coding: utf-8 -*-
"""
@FileName: overtime_approval.py
@Author: 小布丁
@CreateTime: 2026-08-06
@Description: 加班审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致
@Version: 2.0.0
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
pip install DrissionPage python-dotenv chinese_calendar
登录(共享登录态,本脚本为单文件自包含):
- 登录态统一由「37duOA登录」影刀自定义指令写入共享 cookies:
%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json
- 本脚本仅读取该 cookies 文件,不 import 任何共享模块;缺失/失效时
报错提示先运行登录指令(影刀流程开头请先拖入「37duOA登录」指令)。
推送消息(本脚本不发送任何消息,只负责生成文本):
- 本脚本不内联任何消息推送逻辑;仅生成待推送的文本消息,经 main() 写入影刀全局变量
messages(列表,每项一条消息,按结果类型分组:通过/校验不通过/人工复核/超期/失败 各一条),
由「37du钉钉群机器人推送」指令读取后逐条发送;本地独立运行时静默跳过写全局变量;
- main(push_type, target):
push_type="group"(默认)群消息:全局变量 messages 为文本列表,逐条交钉钉群机器人 webhook 推送;
push_type="person" 单聊:main 返回值仍为 {target, text} 列表,可交给「37du钉钉推送」指令走 OCR 单聊。
"""
# ==================== 标准库导入 ====================
import calendar
import functools
import json
import math
import os
import random
import re
import time
from datetime import datetime, timedelta
from typing import Callable
from urllib.parse import urlencode, urlparse, parse_qs
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
try:
from DrissionPage import ChromiumPage, SessionPage
from dotenv import load_dotenv
import chinese_calendar as cc
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install DrissionPage python-dotenv chinese_calendar\n"
f"缺失依赖详情: {_import_err}"
)
# ==================== 路径 & 常量配置 ====================
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有;
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 yingdao/share/oa_login.py)
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
# ---------- OA 系统 ----------
BASE_URL = "https://oa.37du.co"
HR_BASE_URL = "https://hr.37du.co"
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
FD_TYPE = "13"
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
# 考勤逐日接口(按员工+日期范围返回每日班次名/班次起止/上下班打卡,data 数组)
# 加班校验统一使用该接口获取排班与打卡,替代原 caleHtml 排班接口与打卡流水接口
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
# 打卡明细接口(按员工+日期范围返回真实打卡明细)
# kq_time=真实打卡时间、bc_date=考勤归属日(跨天打卡次日0点~6点归入前一天)、
# time_order=上下班类型(1=上班、2=下班)。加班校验用其替代考勤逐日接口的打卡字段,
# 避免人工拼接日期导致跨天打卡归属错误。
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
# ---------- 加班审批规则常量 ----------
WORK_START_TIME = "09:00"
WORK_END_TIME = "18:00"
FLEX_TRIGGER_TIME = "23:00"
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
# 次日弹性上班扣减时扣除的中午休息时长(小时)
LUNCH_BREAK_HOURS = 1
OT_MIN_HOURS = 1
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
CROSS_DAY_BEFORE_HOUR = 6
# 加班审核周期:加班日期距今天不超过该天数才允许审核
OT_REVIEW_DAYS = 8
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
MONTH_CUTOFF_DAY = 2
MONTH_CUTOFF_HOUR = 12
# 职能排班半天加班时长:上午3.5小时、下午4.5小时
# (休息日/节假日加班,不再统一按4小时半天处理,整天仍为9小时)
ZHINENG_HALF_MORNING_HOURS = 3.5
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
ZHINENG_HALF_CUTOFF_HOUR = 12
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
# 提前到岗型员工只会提前到、不会晚到:打卡须不晚于加班开始时间(晚到则无法证明开始时刻已到岗)。
# 到岗打卡证据窗口:加班开始时间前1小时内(含开始时刻)的打卡视为到岗
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
# ---------- 分页 ----------
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
DEFAULT_PAGE_SIZE = 100
# ==================== 日志(影刀环境用 print 替代 logging) ====================
class _PrintLogger:
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
def debug(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def info(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def warning(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def error(self, msg, *args, **kwargs):
print(msg % args if args else msg)
logger = _PrintLogger()
def _set_glv(name, value):
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
# ==================== 重试装饰器 ====================
class RetryExhaustedError(Exception):
pass
class OALoginExpiredError(Exception):
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
if max_attempts < 1:
raise ValueError("max_attempts must be >= 1")
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_exc = None
base_delay = 1.0
backoff = 2.0
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except no_retry_on:
raise
except Exception as e:
last_exc = e
if attempt >= max_attempts:
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s", func.__name__, max_attempts, e)
break
delay = base_delay * (backoff ** (attempt - 1))
delay *= random.uniform(0.5, 1.5)
logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
time.sleep(delay)
raise RetryExhaustedError(
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
) from last_exc
return wrapper
return decorator
# ==================== OA/HR API 接口 ====================
def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
params = {
"method": "list",
"dataType": "todo",
"fdType": FD_TYPE,
"fdCateId": "",
# 防缓存随机数:前端请求带 q.s_raq=<随机小数>,每次刷新
"q.s_raq": str(random.random()),
"q.fdSubject": subject,
# 分页参数必须用 pageno/rowsize/pagingtype:
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
"pageno": page_no,
"rowsize": page_size,
"pagingtype": "default",
"orderby": "fdCreateTime",
"ordertype": "down",
}
url = f"{TODO_LIST_URL}?{urlencode(params)}"
logger.debug("请求第 %d 页: %s", page_no, url)
session.get(url)
resp = session.response
if not resp:
raise RuntimeError("请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
try:
return resp.json()
except Exception:
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
def parse_todo_list(data):
datas = data.get("datas", [])
if not datas:
return []
docs = []
for row in datas:
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
title_raw = title_cell.get("value", "")
match = re.search(r']*>(.*?)', title_raw, re.DOTALL)
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
creator = creator_cell.get("value", "")
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
time_str = time_cell.get("value", "")
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
detail_url = href_cell.get("value", "")
if detail_url and not detail_url.startswith(("http://", "https://")):
detail_url = BASE_URL + detail_url
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:加班申请"):
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
if "kmCollaborateMain.do" in detail_url:
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
continue
docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url})
return docs
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
all_docs = []
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
total = int(data.get("page", {}).get("totalSize", 0))
logger.info("总待办[%s]条数: %d", subject, total)
docs = parse_todo_list(data)
all_docs.extend(docs)
logger.info("第 1 页获取 %d 条", len(docs))
if total > page_size:
total_pages = (total + page_size - 1) // page_size
for p in range(2, total_pages + 1):
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
docs = parse_todo_list(data)
all_docs.extend(docs)
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
# 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现),
# 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送
seen = set()
unique_docs = []
for doc in all_docs:
key = doc.get("detail_url") or doc.get("title")
if key in seen:
continue
seen.add(key)
unique_docs.append(doc)
if len(unique_docs) != len(all_docs):
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
return unique_docs
def get_wf_activity_by_task_id(session, task_id):
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
data = {"taskId": task_id}
logger.info("获取 formId: taskId=%s", task_id)
session.post(url, data=data)
resp = session.response
if not resp:
raise RuntimeError("WfActivity 请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}")
try:
json_data = resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
logger.debug("WfActivity 返回: %s", json_data)
return json_data
def extract_form_id(wf_activity_data):
form_id = (
wf_activity_data.get("formId")
or wf_activity_data.get("FormId")
or wf_activity_data.get("form_id")
)
if not form_id:
for key in ("data", "result"):
data_obj = wf_activity_data.get(key, {})
if isinstance(data_obj, dict):
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
if form_id:
break
if not form_id:
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
logger.info("提取到 formId: %s", form_id)
return form_id
def get_business_data(session, business_key, form_id):
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
data = {"businessKey": business_key, "formId": form_id}
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
session.post(url, data=data)
resp = session.response
if not resp:
raise RuntimeError("WorkformEngine 请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}")
try:
json_data = resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
result = json_data.get("result")
if json_data.get("state") != "1" or not isinstance(result, dict):
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
logger.info("WorkformEngine 返回成功")
return result
def get_attendance_daily(session, staff_id, start_date, end_date):
"""按员工+日期范围查询每日考勤(含班次起止时间与上下班打卡)。
接口: rf_s_kq_count_leave_yc_day_all/redApiExec.mc
kq_status_total 按考勤状态分类返回记录(来源为前端 JS 扒取的请求构造):
- 0=休息日、1=正常班、9=未打卡、11=异常(如上班漏打卡)
因此需按这四种状态各查一次,再按 work_day 合并去重,才能同时拿到
班次名/班次时段与休息日、异常班当天的上下班打卡(休息日/异常班加班校验依赖当天打卡)。
"""
by_day = {}
for status in ("0", "1", "9", "11"):
params = {
"staff_id": staff_id,
"begin_date": start_date,
"end_date": end_date,
"kq_status_total": status,
}
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
status, staff_id, start_date, end_date)
session.post(ATTENDANCE_DAILY_URL, data=params)
resp = session.response
if not resp:
raise RuntimeError("考勤逐日请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"考勤逐日接口状态码异常: {resp.status_code}")
try:
json_data = resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"考勤逐日接口返回非 JSON 数据: {body}")
for r in json_data.get("data", []) or []:
by_day.setdefault(str(r.get("work_day", "")), r)
records = [by_day[k] for k in sorted(by_day)]
logger.info("考勤逐日合并返回 %d 天", len(records))
return records
def fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
data = {
"sub_type": sub_type,
"staff_id": staff_id,
"begin_date": begin_date,
"end_date": end_date,
"start": str((page_no - 1) * page_size),
"pageSize": str(page_size),
"sortType": "",
"sortName": "",
"pageNo": str(page_no),
}
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
session.post(LEAVE_RECORD_URL, data=data)
resp = session.response
if not resp:
raise RuntimeError("请假记录请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}")
try:
json_data = resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}")
if json_data.get("success") is not True or json_data.get("code") != 200:
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
page_info = json_data.get("data")
if not isinstance(page_info, dict):
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
return page_info
def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
all_records = []
page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=page_size, sub_type=sub_type)
total = int(page_info.get("total", 0))
page_total = int(page_info.get("pageCount", 1))
records = page_info.get("list", []) or []
all_records.extend(records)
logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records))
if page_total > 1:
for p in range(2, page_total + 1):
page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=p, page_size=page_size, sub_type=sub_type)
records = page_info.get("list", []) or []
all_records.extend(records)
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
return all_records
def fetch_punch_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
"""请求单页员工打卡明细。
接口: rf_s_kq_data_queryByStaffId/redApiExec.mc
返回 data = {total, pageCount, list},list 每条含 kq_time(真实打卡时间)、
bc_date(考勤归属日)、time_order(1=上班、2=下班) 等字段。
"""
data = {
"start": str((page_no - 1) * page_size),
"sortType": "",
"sortName": "",
"pageNo": str(page_no),
"pageSize": str(page_size),
"staff_id": staff_id,
"rootId": "",
"countId": "",
"bc_date": begin_date,
"bc_date_end": end_date,
"begin": begin_date,
"end": end_date,
"sub_type": sub_type,
}
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
session.post(PUNCH_RECORD_URL, data=data)
resp = session.response
if not resp:
raise RuntimeError("打卡明细请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"打卡明细接口状态码异常: {resp.status_code}")
try:
json_data = resp.json()
except Exception:
body = (resp.text or "")[:200]
raise RuntimeError(f"打卡明细接口返回非 JSON 数据: {body}")
if json_data.get("success") is not True or json_data.get("code") != 200:
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
page_info = json_data.get("data")
if not isinstance(page_info, dict):
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
return page_info
def get_punch_records(session, staff_id, begin_date, end_date, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
"""查询员工某时间段内的全部打卡明细(自动分页)。
返回列表,每条含 kq_time(真实打卡时间 "YYYY-MM-DD HH:MM:SS")、
bc_date(考勤归属日)、time_order(1=上班、2=下班)、status、address 等。
"""
all_records = []
page_info = fetch_punch_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=page_size, sub_type=sub_type)
total = int(page_info.get("total", 0))
page_total = int(page_info.get("pageCount", 1))
records = page_info.get("list", []) or []
all_records.extend(records)
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
if page_total > 1:
for p in range(2, page_total + 1):
page_info = fetch_punch_record_page(session, staff_id, begin_date, end_date, page_no=p, page_size=page_size, sub_type=sub_type)
records = page_info.get("list", []) or []
all_records.extend(records)
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
return all_records
# ==================== 加班表单解析 ====================
OT_TYPE_MAP = {"1": "延时加班", "2": "法定假日加班", "3": "休息日加班"}
SUBSIDY_TYPE_MAP = {"1": "转调休", "2": "转补贴"}
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("dept_org_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
# ==================== 登录态(共享 cookies 文件) ====================
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
def _load_shared_oa_cookies():
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
def _ensure_oa_cookies(force=False):
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入)。
本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
登录态缺失或失效时抛友好的 SystemExit 提示(无堆栈),直接提醒先运行登录流程。
"""
if not force and _load_shared_oa_cookies():
return True
if not os.path.exists(COOKIE_FILE):
raise SystemExit(
"未找到 OA 登录态文件(oa_cookies.json)。\n"
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
"或本地运行: python yingdao/share/oa_login.py\n"
"登录完成后再运行本流程。")
raise SystemExit(
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
"请先重新运行「37duOA登录」指令完成登录,"
"或本地运行: python yingdao/share/oa_login.py\n"
"重新登录后再运行本流程。")
def is_session_valid(session, subject="加班"):
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
try:
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
resp = session.response
if resp is None or resp.status_code != 200:
return False
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
text = resp.text
return bool(text) and text.lstrip().startswith(("{", "["))
except Exception as e:
logger.info("会话已失效,需重新登录: %s", e)
return False
def refresh_session_cookies(session, browser_page):
cookies = browser_page.cookies(all_domains=True)
if cookies:
session.set.cookies(cookies)
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
else:
logger.warning("未获取到 Cookies,请确认浏览器登录态")
def build_session(subject):
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
用于查待办、拉表单等纯接口操作;登录态失效时抛友好提示(SystemExit,无堆栈),
提醒先运行「37duOA登录」指令重新登录,而不是中途崩溃。
"""
_ensure_oa_cookies()
session = SessionPage()
session.set.timeout(10)
cookies = _load_shared_oa_cookies()
if cookies:
session.set.cookies(cookies)
if is_session_valid(session, subject):
return session
# 登录态已失效:单文件自包含、不做自动重登,直接友好提示先运行登录流程
_ensure_oa_cookies(force=True) # 恒抛 SystemExit 友好提示
def build_browser(subject):
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
_ensure_oa_cookies()
browser = ChromiumPage()
cookies = _load_shared_oa_cookies()
if cookies:
browser.set.cookies(cookies)
return browser
# ==================== 登录(共享) ====================
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
# ==================== SSO 解析 ====================
def resolve_sso_params(browser, sso_url, wait_timeout=20):
logger.info("解析 SSO 重定向: %s", sso_url)
browser.get(sso_url)
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
logger.info("重定向最终 URL: %s", browser.url)
params = parse_qs(urlparse(browser.url).query)
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
business_key = params.get("businessKey", [None])[0]
if not task_id or not business_key:
raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
return {"taskId": task_id, "businessKey": business_key}
# ==================== 审批引擎 ====================
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
def _fetch_documents(session, subject):
return get_documents(session, subject=subject)
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
def _fetch_doc_detail(browser, session, doc):
detail_url = doc.get("detail_url", "")
if not detail_url:
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
sso_params = resolve_sso_params(browser, detail_url)
task_id = sso_params["taskId"]
business_key = sso_params["businessKey"]
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
refresh_session_cookies(session, browser)
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
form_id = extract_form_id(wf_activity_data)
form_data = get_business_data(session, business_key, form_id)
return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data}
def show_rpa_result_popup(page: ChromiumPage,
type_: str = "success",
stay_seconds: float = 2.5):
"""
纯图标弹窗(无背景卡片),图标放大居中
:param page: DrissionPage 页面对象
:param type_: success / error
:param stay_seconds: 显示秒数(阻塞等待,保证弹窗完整展示后再继续)
"""
# ========== 把两个 SVG 代码粘贴到下面的变量里 ==========
svg_success = '''''' # 审批通过 / 成功图标
svg_error = '''''' # 审批校验不通过未处理 / 失败图标
# ==================================================
svg_icon = svg_success if type_ == "success" else svg_error
accent_color = "#13C463" if type_ == "success" else "#F5222D"
js_script = f'''
(function() {{
const old = document.getElementById("rpa_apple_pop");
if (old) old.remove();
const mask = document.createElement('div');
mask.id = "rpa_apple_pop";
mask.style.cssText = `
position: fixed; inset: 0;
z-index: 999999;
display: flex; align-items: center; justify-content: center;
opacity: 0;
transition: opacity 0.25s ease;
`;
// 放大图标容器,无背景
const iconWrap = document.createElement('div');
iconWrap.style.cssText = `
position: relative;
width: 180px; height: 180px;
display: flex; align-items: center; justify-content: center;
transform: scale(0);
transition: transform 0.6s cubic-bezier(0.17, 0.89, 0.32, 1.27);
`;
iconWrap.innerHTML = `{svg_icon}`;
const svg = iconWrap.querySelector('svg');
if (svg) {{
svg.style.width = '100%';
svg.style.height = '100%';
}}
mask.appendChild(iconWrap);
document.body.appendChild(mask);
// 直接应用样式(不依赖 requestAnimationFrame,后台/未激活标签页也能正常显示)
mask.style.opacity = '1';
iconWrap.style.transform = 'scale(1)';
setTimeout(() => {{
mask.style.opacity = '0';
iconWrap.style.transform = 'scale(0.8)';
setTimeout(() => mask.remove(), 300);
}}, {int(stay_seconds * 1000)});
}})();
'''
page.run_js(js_script)
# 阻塞等待弹窗展示完成:弹窗稍后会被下一步打开单据的页面跳转清除,
# 若不等待,弹窗会"一闪而过"看不清审批结果
time.sleep(stay_seconds)
# ==================== 推送消息生成(不发送,交由推送指令) ====================
# 本脚本不发送任何消息:仅把审批结果按类型拼成多条文本消息(默认群消息,只含 text;
# 传 push_type="person" 时生成含 target 的单聊消息),经 main() 把列表写入影刀全局变量 messages。
def _build_push_messages(texts, push_type="group", target=None):
"""把文本列表转成推送消息列表(字典列表)。
push_type 推送类型:"group" 群消息(仅 text,钉钉群机器人 webhook 推送);
"person" 单聊(含 target,钉钉联系人 OCR 推送)。
"""
messages = []
for text in texts:
msg = {"text": text}
if push_type == "person":
msg["target"] = target
messages.append(msg)
return messages
def build_push_summary(results, subject=""):
"""
按结果类型生成多条推送消息文本(每条一类,含该类的单笔明细)。
返回:字符串列表,每项是一条独立完整消息,供推送指令逐条发送
(通过 / 校验不通过未处理 / 人工复核 / 超期待人资处理 / 处理失败 各一条)。
无业务结果时返回空列表。
"""
if not results:
return []
passed = [r for r in results if r.get("decision") == "通过"]
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
review = [r for r in results if r.get("decision") == "人工复核"]
overdue = [r for r in results if r.get("decision") == "超期"]
abnormal = [r for r in results if r.get("decision") == "异常"]
failed = [r for r in results if r.get("decision") == "失败"]
if not passed and not rejected and not review and not overdue and not abnormal and not failed:
return []
def _detail(r):
info = r.get("overtime_info", {}) or {}
name = info.get("加班人员") or r.get("title") or "未知"
vtype = info.get("加班类型") or ""
head = f"{name}-{vtype}" if vtype else name
extra = _format_detail(info)
return f"{head} {extra}" if extra else head
messages = []
if passed:
lines = [f"【{subject}审批】通过 {len(passed)} 条:"]
lines += [f" {_detail(r)}" for r in passed]
lines.append(f"以上 {len(passed)} 条{subject}申请已审批通过")
messages.append("\n".join(lines))
if rejected:
lines = [f"【{subject}审批】校验不通过未处理 {len(rejected)} 条:"]
for r in rejected:
lines.append(f" {_detail(r)}")
lines.append(f" 校验不通过原因:{r.get('note') or r.get('error') or '未知'}")
messages.append("\n".join(lines))
if review:
lines = [f"【{subject}审批】需人工复核 {len(review)} 条:"]
for r in review:
lines.append(f" {_detail(r)}")
lines.append(f" 详情页:{r.get('detail_url') or '无'}")
messages.append("\n".join(lines))
if overdue:
lines = [f"【{subject}审批】超期待人资处理 {len(overdue)} 条:"]
for r in overdue:
lines.append(f" {_detail(r)}")
lines.append(f" 处理原因:{r.get('note') or r.get('error') or '未知'}")
messages.append("\n".join(lines))
if abnormal:
lines = [f"【{subject}审批】审批异常 {len(abnormal)} 条(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进):"]
for r in abnormal:
lines.append(f" {_detail(r)}")
lines.append(f" 详情页:{r.get('detail_url') or '无'}")
messages.append("\n".join(lines))
if failed:
lines = [f"【{subject}审批】处理失败 {len(failed)} 条:"]
for r in failed:
lines.append(f" {r.get('title') or '未知'}:{r.get('error') or '未知'}")
messages.append("\n".join(lines))
return messages
# ==================== 真实审批提交 ====================
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
APPROVE_ENABLED = True
# 审批按钮:仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
_APPROVE_BUTTONS = {
"通过": ("#chooseSubmit", "同意"),
}
def _find_button(page, selector, timeout=3.0):
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
try:
btn = page.ele(selector, timeout=timeout)
if btn:
return btn
except Exception:
pass
try:
frames = page.get_frames()
except Exception:
frames = []
for frame in frames:
try:
btn = frame.ele(selector, timeout=1)
if btn:
return btn
except Exception:
continue
return None
def submit_approval(page, decision):
"""
按校验结论在流程详情页执行真实审批提交。
Args:
page: 停留在详情页的 ChromiumPage
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
Returns:
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
"""
if decision not in _APPROVE_BUTTONS:
return {"action": "-", "ok": "true", "message": "无需提交"}
selector, label = _APPROVE_BUTTONS[decision]
try:
btn = _find_button(page, selector)
if btn is None:
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
logger.error(msg)
return {"action": label, "ok": "false", "message": msg}
logger.info("点击审批按钮: %s(%s)", selector, label)
btn.click()
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
def _visible(el):
try:
return el.states.is_displayed
except Exception:
return False
confirm = None
for _ in range(20):
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
if c1 is not None and _visible(c1):
confirm = c1
break
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
people = page.ele(".wf-select-people", timeout=0.2)
if people is not None and _visible(people):
try:
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
except Exception:
c2 = None
if c2 is not None and _visible(c2):
confirm = c2
break
time.sleep(0.2)
if confirm is None:
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
logger.error(msg)
return {"action": label, "ok": "false", "message": msg}
confirm.click()
logger.info("已点击确认框确定按钮")
time.sleep(1.0)
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
except Exception as e:
logger.error("审批提交失败[%s]: %s", label, str(e))
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
def run_flow(subject, validate_doc, generate_report, push_type="group", target=None):
"""加班审批主流程;返回生成的推送消息列表(字典列表,本脚本不发送)。
push_type 推送类型:"group" 群消息(钉钉群机器人 webhook);"person" 单聊(钉钉联系人 OCR 推送)。
target 单聊推送目标(联系人),仅 push_type="person" 时使用。
"""
logger.info("%s审批流程开始", subject)
# 登录态失效(待办/表单接口返回登录页)时本脚本不做自动重登(单文件自包含),
# 直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duOA登录」指令
for login_attempt in range(2):
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
session = build_session(subject)
browser = None
try:
docs = _fetch_documents(session, subject)
logger.info("共获取%s待办 %d 条", subject, len(docs))
# 无待办单据:不开浏览器,直接生成提示消息返回
if not docs:
logger.info("%s无待审批单据,跳过浏览器操作", subject)
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"], push_type, target)
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
return push_messages
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
browser = build_browser(subject)
refresh_session_cookies(session, browser)
results = []
for doc in docs:
try:
doc_detail = _fetch_doc_detail(browser, session, doc)
result = validate_doc(doc_detail, session)
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
if APPROVE_ENABLED:
# 校验不通过未处理暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
if result.get("decision") == "通过":
orig_decision = result.get("decision")
submit = submit_approval(browser, orig_decision)
result["审批动作"] = submit["action"]
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过,
# 归为「异常」并附机器结论,交由人工跟进
if submit["ok"] == "false":
result["decision"] = "异常"
result["note"] = (
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
)
result["审批结果"] = f"{submit['message']}"
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
else:
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
results.append(result)
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
# 弹出结果提示:通过=绿勾,其余(校验不通过未处理/人工复核/失败)=红叉,停留便于演示
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
try:
show_rpa_result_popup(
browser,
"success" if result.get("decision") == "通过" else "error",
2.5,
)
except Exception:
pass
except Exception as e:
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
results.append({
"creator": doc.get("creator", "未知"),
"title": doc.get("title", "未知"),
"decision": "失败",
"error": str(e),
})
report = generate_report(results)
print("\n" + report)
# 生成推送消息文本(本脚本不发送,交由流程/推送指令):
# 按结果类型分多条(通过/校验不通过/人工复核/超期/失败 各一条,含单笔明细)
texts = build_push_summary(results, subject)
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
if not texts:
texts.append(f"暂无待审批的{subject}单据")
push_messages = _build_push_messages(texts, push_type, target)
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
return push_messages
except OALoginExpiredError as e:
logger.warning("OA 登录态失效: %s", e)
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
# 提醒先运行「37duOA登录」指令重新登录后再跑本流程
_ensure_oa_cookies(force=True)
finally:
if browser is not None:
try:
browser.quit()
except Exception:
pass
# ==================== 加班校验规则 ====================
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 = 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, 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 "") == "休息":
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 check_review_period(ot_date, today=None):
"""
加班日期有效性前置校验,返回 (是否可审核, 原因)。
规则:
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
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 (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点后不再审核上月加班)
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,
}
# ==================== 报告生成 ====================
def _name(r):
"""员工姓名:优先取表单里的加班人员,缺失时回退到发起人。"""
info = r.get("overtime_info", {}) or {}
return info.get("加班人员") or r.get("creator") or "未知"
def _otype(r):
"""加班类型。"""
info = r.get("overtime_info", {}) or {}
return info.get("加班类型") or "未知"
def _format_detail(info):
"""将 overtime_info 字典格式化为易读的明细行。"""
fields = [
("加班人员", "加班人员"),
("所属部门", "所属部门"),
("加班类型", "加班类型"),
("补贴类型", "补贴类型"),
("加班日期", "加班日期"),
("加班开始时间", "加班开始时间"),
("加班结束时间", "加班结束时间"),
("加班时长(小时)", "加班时长"),
("加班天数(天)", "加班天数"),
("系统判断加班时长(小时)", "系统判定时长"),
("系统判断加班天数(天)", "系统判定天数"),
("系统判定加班时间", "系统判定时间"),
("加班当天班次", "当天班次"),
("当日最早打卡", "最早打卡"),
("当日最晚打卡", "最晚打卡"),
("次日最早打卡", "次日最早打卡"),
("前一天最晚打卡", "前一天最晚打卡"),
("到岗打卡", "到岗打卡"),
("计算加班时长(小时)", "计算时长"),
("弹性扣减(小时)", "弹性扣减"),
("有效加班时长(小时)", "有效时长"),
("弹性额度D(小时)", "弹性额度D"),
("打卡时间间隔(小时)", "打卡间隔"),
("申报天数(天)", "申报天数"),
("打卡备注", "打卡备注"),
]
parts = []
for key, label in fields:
val = info.get(key)
if val is not None and val != "" and val != "无":
parts.append(f"{label}={val}")
return " | ".join(parts)
def generate_report(results):
"""
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
输出:
- 每条审批的完整明细(含加班日期、时长、打卡、排班等)
- 《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因
- 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接
- 《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
"""
passed = [r for r in results if r.get("decision") == "通过"]
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
review = [r for r in results if r.get("decision") == "人工复核"]
overdue = [r for r in results if r.get("decision") == "超期"]
abnormal = [r for r in results if r.get("decision") == "异常"]
failed = [r for r in results if r.get("decision") == "失败"]
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
if overdue:
summary += f",超期待人资处理 {len(overdue)}"
if abnormal:
summary += f",审批异常 {len(abnormal)}"
if failed:
summary += f",处理失败 {len(failed)}"
lines = [
"加班审批报告",
"=" * 60,
summary,
"",
]
# ----- 明细清单(所有审批单的完整数据) -----
lines.append("【审批明细】")
for i, r in enumerate(results, 1):
info = r.get("overtime_info", {}) or {}
decision = r.get("decision", "未知")
note = r.get("note") or r.get("error") or ""
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
detail = _format_detail(info)
if detail:
lines.append(f" {detail}")
if note:
lines.append(f" 备注: {note}")
if r.get("审批动作"):
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
lines.append("")
# ----- 校验不通过未处理清单 -----
if rejected:
lines.append("《加班审批校验不通过未处理人员明细清单》")
for i, r in enumerate(rejected, 1):
reason = r.get("note") or r.get("error") or ""
url = r.get("detail_url") or "无"
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
lines.append("")
# ----- 人工复核清单 -----
if review:
lines.append("《附件人工复核待办清单》")
for i, r in enumerate(review, 1):
url = r.get("detail_url") or "无"
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
lines.append("")
# ----- 超期待人资处理清单 -----
if overdue:
lines.append("《超期加班待人资处理清单》")
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
for i, r in enumerate(overdue, 1):
reason = r.get("note") or r.get("error") or ""
url = r.get("detail_url") or "无"
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {url}")
lines.append("")
# ----- 处理失败 -----
if failed:
lines.append("【处理失败】")
for i, r in enumerate(failed, 1):
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
lines.append("")
# ----- 审批异常(审批提交失败,需人工跟进) -----
if abnormal:
lines.append("《加班审批异常待人工确认清单》")
lines.append("(机器已出结论但审批提交未成功,OA 中单据状态未变,需人工跟进)")
for i, r in enumerate(abnormal, 1):
reason = r.get("note") or r.get("error") or "未知"
url = r.get("detail_url") or "无"
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 原因: {reason} | 详情页链接: {url}")
lines.append("")
return "\n".join(lines)
# ==================== 主入口 ====================
def main(push_type="group", target=None):
"""加班审批:查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。...
本脚本不发送任何消息:仅生成待推送消息(返回列表并写入影刀全局变量 messages),
由「37du钉钉群机器人推送」/「37du钉钉推送」指令消费。
Args:
push_type: 推送类型 "group"(默认,群消息,全局变量 messages 为纯文本直接发送)
/ "person"(单聊,返回列表含 target,交由 OCR 单聊推送指令)
target: 单聊推送目标(联系人),仅 push_type="person" 时使用
"""
push_type = str(push_type or "group").lower()
if push_type == "person" and not target:
logger.warning("push_type=person 但未提供 target,已按群消息(group)处理")
push_type = "group"
push_messages = run_flow(
subject="加班",
validate_doc=validate_doc,
generate_report=generate_report,
push_type=push_type,
target=target,
)
# 写入影刀全局变量 messages(列表,每项一条消息,按结果类型分组),
# 供「37du钉钉群机器人推送」指令读取后逐条发送;本地独立运行时静默跳过
_set_glv("messages", [
str(m.get("text", "") or "").strip()
for m in push_messages if str(m.get("text", "") or "").strip()
])
return push_messages
if __name__ == "__main__":
main()