1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性 2. 定义OALoginExpiredError统一标识登录态失效异常 3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验 4. 为重试装饰器添加不重试异常配置,登录失效直接上抛 5. 全流程增加登录态失效自动重登机制,最多重试2次 6. 新增通用钉钉机器人推送工具类
1762 lines
88 KiB
Python
1762 lines
88 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: overtime_approval_yingdao.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-06
|
||
@Description: 加班审批流程(影刀单文件版)- 合并自原项目 13 个模块
|
||
@Version: 1.0.0
|
||
|
||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install DrissionPage python-dotenv chinese_calendar pyautogui pywin32 pyperclip
|
||
|
||
环境变量(.env 文件或系统变量):
|
||
oa_login_url=登录页URL
|
||
oa_target_url_keyword=登录成功后URL关键字
|
||
oa_login_username=用户名
|
||
oa_login_password=密码
|
||
dingtalk_notify_enabled=true|false(默认 false,是否推送审批结果到钉钉)
|
||
dingtalk_notify_target=钉钉联系人姓名(如 夏一平)
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import functools
|
||
import json
|
||
import math
|
||
import os
|
||
import random
|
||
import re
|
||
import time
|
||
from collections import defaultdict
|
||
from datetime import datetime, timedelta
|
||
from typing import Any, Callable, Dict, List, Optional
|
||
from urllib.parse import urlencode, urlparse, parse_qs
|
||
|
||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||
try:
|
||
from DrissionPage import ChromiumPage, SessionPage
|
||
from dotenv import load_dotenv
|
||
import pyautogui
|
||
import win32gui
|
||
import win32con
|
||
import win32clipboard
|
||
import pyperclip
|
||
import chinese_calendar as cc
|
||
except ImportError as _import_err:
|
||
raise RuntimeError(
|
||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||
"请先执行安装:\n"
|
||
" pip install DrissionPage python-dotenv chinese_calendar pyautogui pywin32 pyperclip\n"
|
||
f"缺失依赖详情: {_import_err}"
|
||
)
|
||
|
||
# 模块加载时即读取 .env,避免复用已保存会话(跳过 oa_login)时环境变量未加载
|
||
load_dotenv()
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有(影刀版独立子目录)
|
||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation', 'OvertimeApproval')
|
||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||
|
||
# ---------- 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"
|
||
PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc"
|
||
KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc"
|
||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||
|
||
# ---------- 加班审批规则常量 ----------
|
||
WORK_START_TIME = "09:00"
|
||
WORK_END_TIME = "18:00"
|
||
FLEX_TRIGGER_TIME = "23:00"
|
||
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
|
||
|
||
# ---------- 分页 ----------
|
||
DEFAULT_PAGE_SIZE = 15
|
||
|
||
|
||
# ==================== 日志(影刀环境用 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()
|
||
|
||
|
||
# ==================== 重试装饰器 ====================
|
||
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.fdSubject": subject,
|
||
"orderby": "fdCreateTime",
|
||
"ordertype": "down",
|
||
"page.pageNo": page_no,
|
||
"page.pageSize": page_size,
|
||
"__seq": int(time.time() * 1000),
|
||
}
|
||
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'<span class="subjecthead"[^>]*>(.*?)</span>', 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
|
||
|
||
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_html(session, staff_id, year, month):
|
||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
||
data = {"type": "2", "staffId": staff_id, "year": str(year), "month": str(month)}
|
||
logger.info("获取排班: %s %d-%02d", staff_id, year, month)
|
||
|
||
session.post(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:
|
||
raise RuntimeError("排班接口返回非 JSON 数据")
|
||
|
||
if json_data.get("success") != "true":
|
||
raise RuntimeError(f"排班接口返回失败: {json_data}")
|
||
|
||
html = json_data.get("caleHtml")
|
||
if not html:
|
||
raise RuntimeError("排班接口未返回 caleHtml 字段")
|
||
return html
|
||
|
||
|
||
def get_attendance_records(session, staff_id, start_date, end_date):
|
||
params = {
|
||
"staff_id": staff_id,
|
||
"rootId": "",
|
||
"countId": "",
|
||
"bc_date": start_date,
|
||
"bc_date_end": end_date,
|
||
"begin": start_date,
|
||
"end": end_date,
|
||
}
|
||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date)
|
||
|
||
session.get(KQ_DATA_URL, params=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}")
|
||
|
||
records = json_data.get("jsonList", [])
|
||
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 parse_attendance_html(html):
|
||
"""
|
||
解析排班日历 HTML,返回 {日期: 班次} 字典。
|
||
|
||
实际 HTML 结构(属性用单引号):
|
||
<a class='cale_a' title='经营正班A' short_bc_name='经营A'
|
||
data-temp='2026-08-03' finalState='' onclick="...">正常</a>
|
||
|
||
- data-temp: 日期
|
||
- title: 班次全称(如 经营正班A、职能正班A、休息)
|
||
- 文本内容: 考勤状态(如 正常、异常、休息)
|
||
"""
|
||
if not html:
|
||
logger.warning("排班 HTML 为空")
|
||
return {}
|
||
|
||
result = {}
|
||
# 匹配含 data-temp 属性的 <a> 标签,兼容单引号和双引号
|
||
a_tag_pattern = r"""<a\b[^>]*\bdata-temp=['"]([^'"]+)['"][^>]*>([^<]*)</a>"""
|
||
|
||
for match in re.finditer(a_tag_pattern, html, re.DOTALL):
|
||
date_str = match.group(1).strip()
|
||
text_content = match.group(2).strip()
|
||
|
||
# 从完整标签中提取 title 属性(班次名称),同样兼容单/双引号
|
||
full_tag = match.group(0)
|
||
title_match = re.search(r"""\btitle=['"]([^'"]*)['"]""", full_tag)
|
||
shift_name = title_match.group(1).strip() if title_match else ""
|
||
|
||
# 优先使用 title(班次名称),休息日 title='休息'
|
||
if shift_name:
|
||
# 考勤异常时附加标注,便于报告展示
|
||
if text_content and text_content == "异常":
|
||
result[date_str] = f"{shift_name}(异常)"
|
||
else:
|
||
result[date_str] = shift_name
|
||
else:
|
||
result[date_str] = text_content
|
||
|
||
if not result:
|
||
logger.warning("排班 HTML 解析失败,未匹配到任何数据。HTML 片段(前500字符): %s", html[:500])
|
||
else:
|
||
logger.debug("排班解析: 共 %d 条", len(result))
|
||
|
||
return result
|
||
|
||
|
||
def get_work_days_in_range(attendance_dict, start_date, end_date):
|
||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||
work_days = []
|
||
current = start
|
||
while current <= end:
|
||
date_str = current.strftime("%Y-%m-%d")
|
||
shift = attendance_dict.get(date_str, "")
|
||
if shift != "休息" and shift != "":
|
||
work_days.append(date_str)
|
||
current += timedelta(days=1)
|
||
return work_days
|
||
|
||
|
||
def summarize_attendance_records(records):
|
||
time_format = "%Y-%m-%d %H:%M:%S"
|
||
group_map = defaultdict(list)
|
||
|
||
for item in records:
|
||
staff_id = item.get("staff_id", "")
|
||
bc_day = item.get("bc_date", "")
|
||
if not staff_id or not bc_day:
|
||
continue
|
||
try:
|
||
kq_dt = datetime.strptime(item["kq_time"], time_format)
|
||
except (KeyError, ValueError):
|
||
continue
|
||
group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt})
|
||
|
||
summary = []
|
||
for (sid, day), items in group_map.items():
|
||
items.sort(key=lambda x: x["_dt"])
|
||
base = items[0]
|
||
row = {
|
||
"staff_id": sid,
|
||
"staff_name": base.get("staff_name", ""),
|
||
"dept_name": base.get("DEPT_ORG_NAME", ""),
|
||
"post_name": base.get("POST_ALIAS_NAME", ""),
|
||
"attend_date": day,
|
||
"first_check_in": items[0]["kq_time"],
|
||
"last_check_out": items[-1]["kq_time"] if len(items) > 1 else None,
|
||
}
|
||
summary.append(row)
|
||
return summary
|
||
|
||
|
||
# ==================== 加班表单解析 ====================
|
||
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
|
||
|
||
|
||
# ==================== 会话管理 ====================
|
||
def init_session_from_page(browser_page, copy_headers=True):
|
||
session = SessionPage()
|
||
cookies_dict = browser_page.cookies(all_domains=True)
|
||
if cookies_dict:
|
||
session.set.cookies(cookies_dict)
|
||
logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict))
|
||
else:
|
||
logger.warning("未获取到 Cookies,请确认浏览器已登录")
|
||
|
||
if copy_headers:
|
||
headers = {"User-Agent": browser_page.run_js("return navigator.userAgent;")}
|
||
session.set.headers(headers)
|
||
logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50])
|
||
|
||
session.set.timeout(10)
|
||
return session
|
||
|
||
|
||
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 save_browser_cookies(browser_page, path=COOKIE_FILE):
|
||
cookies = browser_page.cookies(all_domains=True)
|
||
if not cookies:
|
||
logger.warning("未获取到 Cookies,跳过保存")
|
||
return
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
with open(path, 'w', encoding='utf-8') as f:
|
||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||
|
||
|
||
def load_cookies(path=COOKIE_FILE):
|
||
if not os.path.exists(path):
|
||
return None
|
||
with open(path, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
|
||
|
||
def load_saved_session(path=COOKIE_FILE):
|
||
cookies = load_cookies(path)
|
||
if not cookies:
|
||
return None
|
||
session = SessionPage()
|
||
session.set.cookies(cookies)
|
||
session.set.timeout(10)
|
||
return session
|
||
|
||
|
||
def create_browser_with_saved_cookies(path=COOKIE_FILE):
|
||
browser = ChromiumPage()
|
||
cookies = load_cookies(path)
|
||
if cookies:
|
||
browser.set.cookies(cookies)
|
||
return browser
|
||
|
||
|
||
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
|
||
|
||
|
||
# ==================== 登录 ====================
|
||
@retry(max_attempts=3)
|
||
def oa_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||
load_dotenv()
|
||
|
||
login_url = os.getenv('oa_login_url')
|
||
if not login_url:
|
||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||
if not target_url_keyword:
|
||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
||
|
||
final_username = username or os.getenv('oa_login_username')
|
||
final_password = password or os.getenv('oa_login_password')
|
||
if not final_username or not final_password:
|
||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
||
|
||
page = ChromiumPage()
|
||
|
||
try:
|
||
page.get(login_url)
|
||
time.sleep(wait_after_load)
|
||
|
||
username_input = page.ele('tag:input@name=j_username')
|
||
if not username_input:
|
||
raise RuntimeError("未找到用户名输入框")
|
||
username_input.input(final_username)
|
||
page.wait(0.5)
|
||
|
||
password_input = page.ele('tag:input@name=j_password')
|
||
if not password_input:
|
||
raise RuntimeError("未找到密码输入框")
|
||
password_input.input(final_password)
|
||
page.wait(0.5)
|
||
|
||
login_button = page.ele('.lui_login_button_div_c')
|
||
if not login_button:
|
||
raise RuntimeError("未找到登录按钮")
|
||
login_button.click()
|
||
page.wait(0.5)
|
||
|
||
start = time.time()
|
||
while time.time() - start < timeout:
|
||
if target_url_keyword in page.url:
|
||
logger.info("登录成功!当前 URL: %s", page.url)
|
||
return page
|
||
time.sleep(0.5)
|
||
|
||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||
if error_elem:
|
||
logger.warning("登录失败,提示: %s", error_elem.text)
|
||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||
|
||
except Exception as e:
|
||
page.quit()
|
||
raise RuntimeError(f"登录过程出错: {e}")
|
||
|
||
|
||
# ==================== 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}
|
||
|
||
|
||
# ==================== 审批引擎 ====================
|
||
def _get_browser_and_session(subject):
|
||
saved_session = load_saved_session()
|
||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||
logger.info("复用已保存的登录会话,跳过登录")
|
||
browser = create_browser_with_saved_cookies()
|
||
return browser, saved_session, False
|
||
|
||
browser = oa_login()
|
||
session = init_session_from_page(browser)
|
||
save_browser_cookies(browser)
|
||
return browser, session, True
|
||
|
||
|
||
@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 t="1786428964523" class="icon" viewBox="0 0 1300 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2092" width="200" height="200"><path d="M784.058182 99.258182l10.938182 18.385454-21.294546-2.56-14.196363 16.058182-4.072728-21.061818-19.781818-8.494545 18.734546-10.472728 2.094545-21.294545 15.709091 14.545454 20.945454-4.654545-9.076363 19.549091zM1067.287273 642.443636l-18.501818 10.821819 2.56-21.294546-16.058182-14.196364 21.061818-4.072727 8.494545-19.665454 10.472728 18.734545 21.294545 1.978182-14.661818 15.709091 4.770909 20.945454-19.432727-8.96z" fill="#13C463" p-id="2093"></path><path d="M1067.287273 642.443636l-18.501818 10.821819 2.56-21.294546-16.058182-14.196364 21.061818-4.072727 8.494545-19.665454 10.472728 18.734545 21.294545 1.978182-14.661818 15.709091 4.770909 20.945454-19.432727-8.96zM571.927273 100.072727l-17.454546-12.567272 20.596364-6.167273 6.516364-20.48 12.218181 17.570909 21.410909-0.116364-12.916363 17.105455 6.749091 20.363636-20.247273-6.981818-17.338182 12.683636 0.465455-21.410909zM991.418182 784.407273l-21.178182 3.490909 10.123636-18.967273-9.774545-18.967273 21.061818 3.723637 15.127273-15.243637 2.909091 21.294546 19.2 9.658182-19.316364 9.309091-3.258182 21.178181-14.894545-15.476363zM427.985455 156.741818L407.272727 151.505455l16.872728-13.265455-1.396364-21.410909 17.803636 11.985454 20.014546-7.912727-5.934546 20.596364 13.730909 16.523636-21.410909 0.814546-11.52 18.152727-7.447272-20.247273zM854.225455 896.465455l-20.712728-5.352728 16.872728-13.265454-1.396364-21.294546 17.803636 11.869091 20.014546-7.912727-5.934546 20.712727 13.730909 16.523637-21.527272 0.814545-11.403637 18.036364-7.447272-20.130909zM562.501818 923.694545l10.821818 18.385455-21.294545-2.56-14.196364 16.058182-4.072727-21.061818-19.665455-8.494546 18.734546-10.356363 1.978182-21.41091 15.709091 14.661819 20.945454-4.770909-8.96 19.54909zM242.734545 420.770909l-18.385454 10.938182 2.56-21.294546-16.058182-14.196363 21.061818-4.189091 8.494546-19.665455 10.356363 18.734546 21.410909 2.094545-14.545454 15.709091 4.654545 20.945455-19.549091-9.076364z" fill="#13C463" p-id="2094"></path><path d="M242.734545 420.770909l-18.385454 10.938182 2.56-21.294546-16.058182-14.196363 21.061818-4.189091 8.494546-19.665455 10.356363 18.734546 21.410909 2.094545-14.545454 15.709091 4.654545 20.945455-19.549091-9.076364zM700.858182 943.941818l-17.454546-12.450909 20.48-6.283636 6.516364-20.48 12.334545 17.687272 21.41091-0.116363-12.916364 17.105454 6.632727 20.363637-20.247273-7.098182-17.221818 12.683636 0.465455-21.410909zM303.592727 278.807273l-21.178182 3.490909 10.123637-18.967273-9.890909-18.967273 21.178182 3.723637 15.010909-15.243637 2.909091 21.294546 19.2 9.541818-19.316364 9.425455-3.258182 21.178181-14.778182-15.476363z" fill="#13C463" p-id="2095"></path><path d="M407.272727 90.647273a486.632727 486.632727 0 0 1 504.552728 11.636363l25.018181-14.429091A512 512 0 0 0 139.636364 546.909091l25.018181-14.429091A486.981818 486.981818 0 0 1 407.272727 90.647273zM893.323636 933.352727a486.749091 486.749091 0 0 1-504.669091-11.636363l-24.901818 14.429091A512 512 0 0 0 1161.192727 477.090909l-24.901818 13.963636a486.981818 486.981818 0 0 1-242.967273 442.298182z" fill="#13C463" p-id="2096"></path><path d="M814.545455 795.927273a327.447273 327.447273 0 0 1-258.21091 29.556363l-29.78909 17.105455A353.163636 353.163636 0 0 0 998.865455 570.181818l-29.789091 17.105455A326.865455 326.865455 0 0 1 814.545455 795.927273zM486.865455 228.072727A327.447273 327.447273 0 0 1 744.727273 198.516364l29.789091-17.105455A353.163636 353.163636 0 0 0 302.545455 453.818182l29.78909-17.105455A326.865455 326.865455 0 0 1 486.865455 228.072727zM1288.378182 374.690909a53.294545 53.294545 0 0 1-14.429091 11.636364L229.469091 989.090909a53.876364 53.876364 0 0 1-73.425455-19.665454L7.214545 710.632727a53.527273 53.527273 0 0 1 19.781819-73.309091L1071.476364 34.909091a53.876364 53.876364 0 0 1 73.425454 19.665454l148.829091 258.327273a53.061818 53.061818 0 0 1 5.352727 40.727273 55.272727 55.272727 0 0 1-10.705454 21.061818zM32.232727 665.716364A28.043636 28.043636 0 0 0 29.323636 698.181818l148.829091 257.978182a28.392727 28.392727 0 0 0 38.516364 10.356364l1044.48-601.949091a28.16 28.16 0 0 0 10.356364-38.516364L1122.676364 67.84a28.276364 28.276364 0 0 0-38.4-10.356364L39.68 659.432727a27.810909 27.810909 0 0 0-7.447273 6.283637z" fill="#13C463" p-id="2097"></path><path d="M356.770909 569.250909l22.341818 38.749091-15.476363 8.727273L349.090909 592.64l-153.483636 88.785455 14.778182 25.483636-15.476364 8.96-23.272727-39.912727L256 627.2c-6.283636-4.887273-11.636364-8.843636-16.174545-11.636364L256 602.647273c3.956364 3.141818 9.774545 8.261818 17.338182 15.127272z m-17.338182 199.447273l-49.221818 28.392727 7.563636 13.149091-15.476363 8.96-62.138182-107.52 64.814545-37.469091-12.8-22.574545 15.941819-9.192728 12.8 22.109091 65.396363-37.701818 61.672728 106.821818-15.476364 8.96-7.214546-12.450909-49.92 28.858182 26.065455 45.032727-16.058182 9.192728z m-46.545454-79.825455L244.363636 717.265455l14.778182 25.6 49.221818-28.509091zM267.636364 756.945455l14.778181 25.6 49.221819-28.509091-14.778182-25.483637z m106.938181-80.523637l-14.778181-25.483636-49.92 28.741818 14.778181 25.483636zM346.996364 744.727273l49.803636-28.741818-14.661818-25.483637-49.92 28.741818zM505.832727 609.978182c-4.654545 6.283636-10.123636 13.265455-16.523636 21.061818l35.84 62.021818a18.967273 18.967273 0 0 1-6.749091 29.672727l-19.316364 11.636364-12.450909-13.847273a170.123636 170.123636 0 0 0 17.803637-8.727272 8.494545 8.494545 0 0 0 2.909091-13.614546L477.090909 645.352727l-9.890909 10.472728-10.007273 10.24-12.683636-13.149091c9.309091-8.261818 17.221818-15.941818 23.272727-23.272728l-31.301818-54.341818-25.018182 14.545455-8.843636-15.36 25.018182-14.429091-23.272728-41.076364 15.476364-8.96 23.272727 41.076364L465.454545 538.763636l8.843637 15.36-22.109091 12.567273 28.509091 49.221818c5.469091-6.516364 10.938182-13.498182 16.407273-21.061818z m9.076364-45.730909L572.043636 663.272727a207.825455 207.825455 0 0 0 23.272728-27.461818l11.636363 13.149091a365.381818 365.381818 0 0 1-41.774545 45.498182l-12.567273-12.567273a11.636364 11.636364 0 0 0 1.745455-13.963636L453.818182 493.963636l15.709091-9.076363 36.887272 63.883636 31.301819-18.152727 8.96 15.592727z m129.745454 83.316363a20.596364 20.596364 0 0 1-31.418181-9.774545l-103.098182-178.618182 15.709091-9.192727 38.632727 67.025454a200.261818 200.261818 0 0 0 28.043636-41.076363l16.872728 7.68a303.243636 303.243636 0 0 1-35.723637 49.338182l53.410909 93.090909a9.192727 9.192727 0 0 0 13.963637 4.072727l10.821818-6.283636a14.312727 14.312727 0 0 0 8.029091-11.636364 103.447273 103.447273 0 0 0-15.243637-39.098182l17.338182-3.84c12.567273 25.134545 18.036364 41.658182 16.290909 49.803636A28.392727 28.392727 0 0 1 663.272727 636.741818zM860.276364 521.774545c-7.563636 4.421818-20.829091 11.636364-39.912728 22.574546a179.432727 179.432727 0 0 1-37.352727 16.174545 58.181818 58.181818 0 0 1-33.047273-1.978181 14.312727 14.312727 0 0 0-11.636363-0.581819c-5.352727 3.025455-8.261818 18.385455-8.727273 45.847273l-18.269091-3.956364c1.047273-25.483636 5.003636-42.821818 11.636364-52.014545l-38.865455-67.374545-31.534545 18.152727-8.378182-14.661818 46.545454-26.647273 47.825455 82.850909a55.505455 55.505455 0 0 1 8.494545 1.861818 59.694545 59.694545 0 0 0 25.367273 4.072727 101.701818 101.701818 0 0 0 33.512727-11.636363L849.454545 508.509091l31.418182-18.734546c11.636364-7.214545 19.898182-12.334545 24.087273-15.127272l5.469091 18.152727zM676.072727 413.207273L671.185455 430.545455a279.272727 279.272727 0 0 0-58.181819-13.265455l4.887273-16.64a307.781818 307.781818 0 0 1 58.181818 12.567273zM754.967273 372.363636a261.818182 261.818182 0 0 0 20.247272-38.516363l-98.443636 56.785454-7.796364-13.498182 119.97091-69.46909 6.632727 11.636363a281.134545 281.134545 0 0 1-25.949091 54.807273l5.236364 0.930909L818.734545 349.090909l57.25091 99.025455a18.385455 18.385455 0 0 1-8.843637 27.927272l-18.385454 10.589091-11.636364-11.636363 17.92-9.425455a7.796364 7.796364 0 0 0 3.607273-11.636364L849.454545 437.410909l-37.236363 21.527273 21.992727 38.050909-14.894545 8.610909-21.992728-38.167273L760.203636 488.727273l22.458182 38.749091-15.127273 8.727272L699.461818 418.909091l55.389091-32a306.269091 306.269091 0 0 0-39.330909-1.047273l4.305455-15.127273c13.265455-0.232727 24.901818 0.465455 35.141818 1.629091z m15.825454 49.454546l-11.636363-20.014546-37.003637 21.410909 11.636364 20.014546z m-29.44 34.909091l11.636364 19.549091 37.003636-21.410909-11.636363-19.549091z m81.454546-64.814546l-11.636364-19.898182-37.236364 21.527273 11.636364 19.898182z m-29.556364 34.909091l11.636364 19.432727 37.236363-21.527272-11.636363-19.432728zM1086.370909 391.214545l-19.898182 11.636364-10.589091 6.167273-10.938181 6.050909a186.181818 186.181818 0 0 1-38.749091 16.989091 60.16 60.16 0 0 1-33.978182-1.978182 14.312727 14.312727 0 0 0-11.636364 0c-5.585455 3.258182-8.610909 18.734545-8.96 46.545455l-18.036363-3.723637c0.814545-26.181818 4.770909-43.752727 11.636363-52.945454l-38.865454-67.141819-31.883637 18.385455-8.727272-15.010909 47.243636-27.345455 47.941818 83.2h4.189091a32.465455 32.465455 0 0 1 4.538182 1.163637 71.68 71.68 0 0 0 26.298182 3.490909 112.872727 112.872727 0 0 0 34.210909-13.265455c16.523636-9.192727 31.767273-17.803636 46.545454-25.949091l14.545455-8.727272 14.196363-8.727273c11.636364-6.865455 18.618182-11.636364 22.574546-14.196364l5.352727 18.385455zM896 286.021818l-4.770909 18.385455a296.378182 296.378182 0 0 0-58.181818-14.661818l4.770909-16.872728a311.156364 311.156364 0 0 1 58.181818 13.149091zM1031.098182 384l-12.334546-13.149091c11.636364-5.934545 21.76-11.636364 30.138182-15.941818a9.658182 9.658182 0 0 0 4.189091-14.661818l-54.341818-94.138182-83.781818 48.290909-9.076364-15.709091 83.781818-48.407273-20.712727-35.84 16.174545-9.425454 20.712728 36.072727 32.814545-18.967273 8.610909 15.243637-32.349091 18.850909 56.552728 97.978182a20.247273 20.247273 0 0 1-8.843637 31.185454z m-23.272727-59.345455L1000.727273 340.48a405.876364 405.876364 0 0 0-58.181818-25.6l7.796363-15.127273a393.890909 393.890909 0 0 1 57.716364 24.436364z" fill="#13C463" p-id="2098"></path></svg>''' # 审批通过 / 成功图标
|
||
svg_error = '''<svg t="1786429461597" class="icon" viewBox="0 0 1300 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2485" width="200" height="200"><path d="M784.073793 99.194344l10.92764 18.472914-21.302392-2.569296-14.179913 16.066232-4.130388-21.04221-19.708778-8.520957 18.765619-10.439798 2.01641-21.334915 15.708481 14.602708 20.944642-4.683274-9.041321 19.448596zM1067.216732 642.38908l-18.440391 10.927639 2.569296-21.302392-16.098754-14.179913 21.04221-4.130388 8.520957-19.676255 10.439798 18.733096 21.367437 2.01641-14.602708 15.708481 4.683274 20.944642-19.481119-9.04132z" fill="#F45151" p-id="2486"></path><path d="M1067.216732 642.38908l-18.440391 10.927639 2.569296-21.302392-16.098754-14.179913 21.04221-4.130388 8.520957-19.676255 10.439798 18.733096 21.367437 2.01641-14.602708 15.708481 4.683274 20.944642-19.481119-9.04132zM571.927987 100.007413l-17.399664-12.488731 20.521847-6.244365 6.504547-20.424278 12.261071 17.5948 21.432483-0.097568-12.944049 17.074436 6.732207 20.359233-20.261665-7.024911-17.269572 12.71639 0.422795-21.465006zM991.438758 784.415867l-21.172302 3.479933 10.114571-18.928232-9.821866-19.025801 21.107256 3.772638 15.090549-15.253164 2.927046 21.237347 19.155892 9.62673-19.318505 9.366548-3.219751 21.204823-14.86289-15.480822zM428.014881 156.79211l-20.749506-5.333729 16.8793-13.236753-1.365955-21.399961 17.82246 11.935844 19.936437-7.870502-5.854093 20.619415 13.659549 16.52155-21.432483 0.813068-11.513048 18.082641-7.382661-20.131573zM854.257857 896.456692l-20.749505-5.333728 16.8793-13.236754-1.365955-21.39996 17.822459 11.968367 19.936437-7.903025-5.854092 20.619415 13.659549 16.554072-21.432483 0.780546-11.513048 18.115164-7.382662-20.164097zM562.431348 923.6457l10.927639 18.440391-21.302392-2.569296-14.179912 16.098754-4.130388-21.04221-19.676255-8.520957 18.733096-10.439798 2.016409-21.367438 15.708482 14.602709 20.944642-4.683274-9.041321 19.481119zM242.7979 420.779157l-18.472914 10.895117 2.569296-21.302392-16.066232-14.179913 21.042211-4.130388 8.520956-19.676255 10.439799 18.733096 21.334914 2.01641-14.602708 15.708481 4.683274 20.944642-19.448596-9.008798z" fill="#F45151" p-id="2487"></path><path d="M242.7979 420.779157l-18.472914 10.895117 2.569296-21.302392-16.066232-14.179913 21.042211-4.130388 8.520956-19.676255 10.439799 18.733096 21.334914 2.01641-14.602708 15.708481 4.683274 20.944642-19.448596-9.008798zM700.815589 943.939887l-17.399663-12.521254 20.521846-6.211842 6.504547-20.424278 12.261072 17.5948 21.432483-0.130091-12.944049 17.106959 6.732206 20.359233-20.261664-7.024911-17.269573 12.683867 0.422795-21.432483zM303.55037 278.817415l-21.139778 3.479933 10.114571-18.928233-9.854389-19.058323 21.107256 3.80516 15.090549-15.253163 2.927046 21.237347 19.155892 9.626729-19.285983 9.366548-3.252273 21.172301-14.862891-15.448299z" fill="#F45151" p-id="2488"></path><path d="M407.655648 90.640865C569.911577-2.894523 764.202402 8.000593 912.213373 102.218959l25.009984-14.407572c-157.052292-105.991596-367.116643-120.334123-542.349144-19.351028-175.232501 100.983095-268.149958 289.907668-255.173386 478.962332l25.009984-14.407572C157.425718 357.685049 245.399719 184.143731 407.688171 90.640865zM893.285141 933.369998c-162.255929 93.502866-356.546754 82.607749-504.557725-11.610617l-25.009984 14.407572c157.052292 106.024119 367.116643 120.366646 542.349144 19.383551 175.232501-100.983095 268.149958-289.907668 255.173386-478.962332l-25.009984 14.407572c7.285093 175.330069-80.688908 348.871388-242.97736 442.374254z" fill="#F45151" p-id="2489"></path><path d="M814.059756 795.86387c-81.371885 46.897785-174.647092 54.735765-258.165478 29.563167l-29.790826 17.172005c95.421707 35.840055 205.511168 30.31119 300.737739-24.554666 95.194048-54.865855 155.198496-147.360516 172.045273-247.888293l-29.790826 17.172005c-20.099051 84.884341-73.663997 161.637997-155.035882 208.535782zM486.881033 228.11447c81.371885-46.897785 174.647092-54.735765 258.165477-29.563167l29.790826-17.172005c-95.421707-35.840055-205.511168-30.31119-300.737738 24.554666-95.194048 54.865855-155.198496 147.360516-172.045273 247.888293l29.790826-17.172005c20.099051-84.884341 73.663997-161.637997 155.035882-208.535782zM1288.338814 374.726963a53.925948 53.925948 0 0 1-14.342527 12.00089L229.431055 988.658649c-25.692961 14.797845-58.60597 5.951661-73.403815-19.741301l-148.824039-258.230523c-7.155002-12.423685-9.073843-26.928825-5.333729-40.783511 3.740115-13.854685 12.651344-25.465302 25.07503-32.620304L1071.509733 35.352214c25.692961-14.797845 58.60597-5.951661 73.403815 19.741301l148.82404 258.230523c7.155002 12.456208 9.073843 26.928825 5.333728 40.78351a53.272241 53.272241 0 0 1-10.732502 20.619415zM32.213185 665.740404c-2.601819 3.08966-4.52066 6.764729-5.626433 10.797548-1.951364 7.25257-0.975682 14.86289 2.796955 21.367438l148.824039 258.230523c7.740411 13.464413 25.009984 18.082641 38.441874 10.34223l1044.565232-601.930796c6.504547-3.772637 11.187821-9.821866 13.139185-17.074437 1.951364-7.25257 0.943159-14.86289-2.796955-21.367437l-148.82404-258.230523c-7.740411-13.464413-25.009984-18.082641-38.441873-10.34223L39.725937 659.430993c-2.894523 1.65866-5.431297 3.80516-7.512752 6.276888z" fill="#F45151" p-id="2490"></path><path d="M489.970693 669.513041c-14.472617 15.090549-31.38444 30.116053-50.735468 45.043989l-11.025208-14.472617c20.749506-15.545868 38.474397-30.733985 53.142151-45.564353l8.618525 14.960459z m-126.806148-95.45423l-8.748616-15.188117 75.420225-43.547944 42.149466 98.251186 17.172004-9.919435c29.368031 50.865559 43.938216 81.632067 43.74308 92.267002-0.292705 10.472321-8.098161 20.164096-23.41637 28.977758a287.527004 287.527004 0 0 1-18.66805 9.886911l-12.618822-12.065935c9.431593-4.260478 16.033709-7.480229 19.741301-9.62673 12.065935-6.959865 17.204527-14.50514 15.480822-22.635824-1.691182-8.748616-12.13098-29.790826-31.38444-63.094107l-61.793198 35.677441-34.766805-84.949386 16.131277-8.130684 27.319098 68.427836 27.676849-15.968663-34.506623-82.412613-58.898675 34.018782z m175.720342-124.366942c0.260182 16.911823-1.431 33.433373-4.975978 49.597173 18.603005 0.975682 37.140964 2.862001 55.613878 5.658956l-0.975682 18.407868c-19.838869-3.414887-39.677738-5.658956-59.484084-6.699683-8.423389 24.912416-21.75771 47.678331-40.002965 68.297745l-16.196322-8.488434c16.944345-18.733096 29.59569-38.897192 37.92151-60.557334-21.107256-0.487841-41.954329 0.325227-62.541222 2.471728l1.268387-17.399664c22.050415-2.01641 44.230921-2.73191 66.574041-2.146501 3.870206-14.927936 5.756524-31.091736 5.626433-48.458876l17.139482-0.682978z m47.54824 86.477955c7.024911 29.660735 9.138889 57.207492 6.341934 82.607749 22.278074 5.593911 45.271648 6.602115 68.980723 3.024615l-1.365955 19.806346c-25.302689 2.894523-48.849149 1.431-70.671905-4.423092-5.46382 23.188711-14.992981 43.938216-28.587485 62.313562l-17.985073-7.447707c14.14739-18.082641 23.871688-38.181692 29.172894-60.264629-23.546461-8.813661-46.084717-22.082938-67.614768-39.807829l9.008798-15.318209c19.481119 16.911823 40.002965 29.270462 61.565539 37.043396 2.504251-23.481415 0.227659-48.523922-6.829775-75.192565l17.985073-2.341637zM846.842674 279.012551l108.333233 187.656186-15.610913 9.008798-5.528865-9.594207-147.718267 85.274614 5.528865 9.594207-15.610913 9.008798-108.333233-187.656186 178.940093-103.324732z m-68.785587 258.06791l147.718267-85.274614-86.315341-149.474494-147.718267 85.274613 86.315341 149.474495z m-35.319691-132.822854l86.120205-49.727263 45.857057 79.420521-86.120204 49.727263-45.857058-79.420521z m108.951165 24.84737l-30.018485-51.971331-56.004151 32.327599 30.018485 51.971332 56.004151-32.3276z" fill="#F45151" p-id="2491"></path></svg>''' # 审批驳回 / 失败图标
|
||
# ==================================================
|
||
|
||
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)
|
||
|
||
|
||
|
||
# ==================== 钉钉推送(内联精简版,保持单文件自包含) ====================
|
||
DINGTALK_WINDOW_KEYWORD = "钉钉"
|
||
|
||
|
||
def _find_dingtalk_hwnd():
|
||
"""用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。"""
|
||
matches = []
|
||
|
||
def _enum(hwnd, _):
|
||
if not win32gui.IsWindowVisible(hwnd):
|
||
return
|
||
title = win32gui.GetWindowText(hwnd)
|
||
if title and DINGTALK_WINDOW_KEYWORD in title:
|
||
matches.append((hwnd, title))
|
||
|
||
win32gui.EnumWindows(_enum, None)
|
||
if not matches:
|
||
raise RuntimeError("未找到标题包含「钉钉」的可见窗口,请确认钉钉桌面端已启动并登录")
|
||
matches.sort(key=lambda x: len(x[1]))
|
||
return matches[0][0]
|
||
|
||
|
||
def _is_dingtalk_foreground():
|
||
title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
|
||
return DINGTALK_WINDOW_KEYWORD in title
|
||
|
||
|
||
def _activate_dingtalk():
|
||
"""激活钉钉窗口:Ctrl+D 唤起托盘中的钉钉 -> win32 置前 -> 点击确保焦点。"""
|
||
if _is_dingtalk_foreground():
|
||
logger.info("钉钉窗口已在前台,跳过激活")
|
||
return
|
||
|
||
# 先尝试找到已打开的钉钉窗口
|
||
hwnd = None
|
||
try:
|
||
hwnd = _find_dingtalk_hwnd()
|
||
except RuntimeError:
|
||
pass
|
||
|
||
if hwnd is None:
|
||
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
|
||
pyautogui.hotkey("ctrl", "d")
|
||
time.sleep(1.5)
|
||
try:
|
||
hwnd = _find_dingtalk_hwnd()
|
||
except RuntimeError:
|
||
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
|
||
|
||
# win32 置前台
|
||
if win32gui.IsIconic(hwnd):
|
||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||
time.sleep(0.3)
|
||
pyautogui.press("alt")
|
||
win32gui.SetForegroundWindow(hwnd)
|
||
time.sleep(1.0)
|
||
|
||
# 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点)
|
||
rect = win32gui.GetWindowRect(hwnd)
|
||
cx = (rect[0] + rect[2]) // 2
|
||
cy = (rect[1] + rect[3]) // 2
|
||
pyautogui.click(cx, cy)
|
||
time.sleep(0.5)
|
||
|
||
if _is_dingtalk_foreground():
|
||
logger.info("钉钉窗口已激活")
|
||
else:
|
||
raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录")
|
||
|
||
|
||
def _send_dingtalk_text(target, text):
|
||
"""搜索联系人并发送文本:激活 -> 搜索 -> 进会话 -> 点击输入框聚焦 -> 粘贴 -> 发送。"""
|
||
_activate_dingtalk()
|
||
# 搜索联系人
|
||
pyautogui.hotkey("ctrl", "shift", "f")
|
||
time.sleep(0.5)
|
||
pyperclip.copy(target)
|
||
pyautogui.hotkey("ctrl", "v")
|
||
time.sleep(1.0)
|
||
pyautogui.press("enter")
|
||
time.sleep(3.5) # 等待会话加载完成
|
||
logger.info("已搜索并进入会话: %s", target)
|
||
|
||
# 进入会话后钉钉可能失焦,重新确认前台并点击消息输入框区域
|
||
if not _is_dingtalk_foreground():
|
||
_activate_dingtalk()
|
||
try:
|
||
hwnd = _find_dingtalk_hwnd()
|
||
rect = win32gui.GetWindowRect(hwnd)
|
||
cx = (rect[0] + rect[2]) // 2
|
||
cy = rect[1] + int((rect[3] - rect[1]) * 0.85) # 窗口底部 15%,消息输入框区域
|
||
pyautogui.click(cx, cy)
|
||
time.sleep(0.5)
|
||
except Exception:
|
||
pass
|
||
|
||
# 粘贴文本并发送
|
||
pyperclip.copy(text)
|
||
pyautogui.hotkey("ctrl", "v")
|
||
time.sleep(0.3)
|
||
pyautogui.press("enter")
|
||
time.sleep(1.0)
|
||
logger.info("文本已发送: %s", text[:50] + ("..." if len(text) > 50 else ""))
|
||
|
||
|
||
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") == "超期"]
|
||
failed = [r for r in results if r.get("decision") == "失败"]
|
||
if not passed and not rejected and not review and not overdue:
|
||
return ""
|
||
|
||
def _item(r):
|
||
info = r.get("overtime_info", {}) or {}
|
||
title = r.get("title", "") or info.get("加班人员") or "未知"
|
||
vtype = info.get("加班类型") or ""
|
||
return f"{title}-{vtype}" if vtype else title
|
||
|
||
all_pass = (not rejected and not review and not overdue and not failed)
|
||
lines = []
|
||
if all_pass:
|
||
lines.append(f"【{subject}审批】本次审批 {len(passed)} 条{subject}申请,")
|
||
lines.append("分别是:")
|
||
for r in passed:
|
||
lines.append(_item(r))
|
||
lines.append("全部通过")
|
||
else:
|
||
lines.append(f"【{subject}审批】本次共审批 {len(results)} 条{subject}申请。")
|
||
if passed:
|
||
lines.append(f"通过 {len(passed)} 条,分别是:")
|
||
for r in passed:
|
||
lines.append(_item(r))
|
||
if rejected:
|
||
lines.append(f"自动驳回 {len(rejected)} 条,分别是:")
|
||
for r in rejected:
|
||
lines.append(_item(r))
|
||
lines.append(f"驳回原因:{r.get('note') or r.get('error') or '未知'}")
|
||
if review:
|
||
lines.append(f"需人工复核 {len(review)} 条,分别是:")
|
||
for r in review:
|
||
lines.append(_item(r))
|
||
lines.append(f"详情页:{r.get('detail_url') or '无'}")
|
||
if overdue:
|
||
lines.append(f"超期待人资处理 {len(overdue)} 条,分别是:")
|
||
for r in overdue:
|
||
lines.append(_item(r))
|
||
lines.append(f"处理原因:{r.get('note') or r.get('error') or '未知'}")
|
||
if failed:
|
||
lines.append(f"另有处理失败 {len(failed)} 条,请查看日志。")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def push_report(report, subject=""):
|
||
"""推送审批报告到钉钉联系人(env 控制,失败不影响主流程)。"""
|
||
load_dotenv()
|
||
if not report or not report.strip():
|
||
logger.info("[%s] 无推送内容(无通过项),跳过钉钉推送", subject)
|
||
return False
|
||
enabled = os.getenv("dingtalk_notify_enabled", "false").lower() == "true"
|
||
if not enabled:
|
||
logger.info("[%s] 钉钉推送未开启(dingtalk_notify_enabled!=true),跳过", subject)
|
||
return False
|
||
target = os.getenv("dingtalk_notify_target", "").strip()
|
||
if not target:
|
||
logger.warning("[%s] 未配置 dingtalk_notify_target,跳过钉钉推送", subject)
|
||
return False
|
||
try:
|
||
_send_dingtalk_text(target, report)
|
||
logger.info("[%s] 审批报告已推送至钉钉: %s", subject, target)
|
||
return True
|
||
except Exception as e:
|
||
logger.warning("[%s] 钉钉推送失败: %s", subject, e)
|
||
return False
|
||
|
||
|
||
# ==================== 真实审批提交 ====================
|
||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||
APPROVE_ENABLED = True
|
||
# 审批按钮:通过->同意(#chooseSubmit),驳回->退回申请人(#backApplySubmit)
|
||
_APPROVE_BUTTONS = {
|
||
"通过": ("#chooseSubmit", "同意"),
|
||
"驳回": ("#backApplySubmit", "退回申请人"),
|
||
}
|
||
|
||
|
||
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()
|
||
# 点击弹出的确认框"确定"按钮(同意/驳回共用同一确认框,仅标题不同)。
|
||
# 确认框由 rsMessageBox.confirm 点击后动态生成(modal 渐入动画),轮询等待其出现
|
||
confirm = None
|
||
for _ in range(10):
|
||
confirm = _find_button(page, "#custom-confirm-modal-ok", timeout=1)
|
||
if confirm:
|
||
break
|
||
time.sleep(0.5)
|
||
if confirm is None:
|
||
msg = "未找到确认框确定按钮 #custom-confirm-modal-ok,审批未提交"
|
||
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):
|
||
logger.info("%s审批流程开始", subject)
|
||
|
||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||
for login_attempt in range(2):
|
||
browser, session, _ = _get_browser_and_session(subject)
|
||
try:
|
||
docs = _fetch_documents(session, subject)
|
||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||
|
||
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") == "通过":
|
||
submit = submit_approval(browser, result.get("decision"))
|
||
result["审批动作"] = submit["action"]
|
||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||
else:
|
||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||
# 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示
|
||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||
try:
|
||
show_rpa_result_popup(
|
||
browser,
|
||
"success" if result.get("decision") == "通过" else "error",
|
||
2.5,
|
||
)
|
||
except Exception:
|
||
pass
|
||
results.append(result)
|
||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||
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)
|
||
|
||
# 先推送摘要到钉钉
|
||
push_report(build_push_summary(results, subject), subject)
|
||
|
||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||
if has_detail:
|
||
push_report(report, subject)
|
||
|
||
save_browser_cookies(browser)
|
||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||
return report
|
||
except OALoginExpiredError as e:
|
||
logger.warning("OA 登录态失效: %s", e)
|
||
if login_attempt == 0:
|
||
try:
|
||
if os.path.exists(COOKIE_FILE):
|
||
os.remove(COOKIE_FILE)
|
||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||
except Exception:
|
||
pass
|
||
continue
|
||
raise
|
||
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:
|
||
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 _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])
|
||
html = get_attendance_html(session, staff_id, year, month)
|
||
attendance = parse_attendance_html(html)
|
||
return any("职能" in (shift or "") for shift in attendance.values())
|
||
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 _check_punch_records(session, staff_id, ot_date):
|
||
if not ot_date or not staff_id:
|
||
return {"当日最早打卡": 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:
|
||
# 查询范围扩到前一天:提前到岗型加班(开始<=6点)的到岗打卡可能被系统归到前一天
|
||
records = get_attendance_records(session, staff_id, prev_day, next_day)
|
||
summary = summarize_attendance_records(records)
|
||
prev_summary = next((r for r in summary if r["attend_date"] == prev_day), None)
|
||
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 and not prev_summary:
|
||
return {"当日最早打卡": None, "当日最晚打卡": 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,
|
||
"前一天最晚打卡": prev_summary["last_check_out"] if prev_summary else None,
|
||
"打卡备注": "",
|
||
}
|
||
except Exception as e:
|
||
logger.warning("获取打卡明细失败: %s", str(e))
|
||
return {"当日最早打卡": 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
|
||
|
||
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, 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. 区间合规校验
|
||
work_start = datetime.strptime(f"{ot_date} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
|
||
work_end = datetime.strptime(f"{ot_date} {WORK_END_TIME}", "%Y-%m-%d %H:%M")
|
||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)。
|
||
# 常规"晚于18:00""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||
# - 开始<=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})早于规定下班时间({WORK_END_TIME})")
|
||
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:
|
||
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):
|
||
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:
|
||
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}小时"
|
||
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("当日最晚打卡"))
|
||
next_first = _parse_dt(punch.get("次日最早打卡"))
|
||
interval = None
|
||
if first is None or last is None:
|
||
# 跨天打卡处理:当天缺打卡时参考次日首条打卡,次日首条早于6点视为归属加班当天
|
||
if next_first is not None and next_first.hour < CROSS_DAY_BEFORE_HOUR:
|
||
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)
|
||
# 职能排班半天(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") == "超期"]
|
||
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 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 ""
|
||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 驳回原因: {reason}")
|
||
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("")
|
||
|
||
return "\n".join(lines)
|
||
|
||
|
||
# ==================== 主入口 ====================
|
||
def main():
|
||
"""加班审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||
run_flow(subject="加班", validate_doc=validate_doc, generate_report=generate_report)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|