1. **依赖与导入路径修正
- 移除所有本地sys.path插入,统一使用绝对包导入
- 修复logger导入路径,统一从app.utils导入
- 重构intelligent_retry.py移除冗余导入
- 统一hrbp各模块的导入路径
2. **项目配置与构建
- 新增pyproject.toml配置文件,规范项目元数据与依赖声明
- 更新requirements.txt新增pyautogui、pywin32、pyperclip依赖
3. **业务模块重构
- 重构请假/加班审批模块的导入路径与内部逻辑
- 重命名审批结果描述(将"不通过"改为"驳回")
- 统一代码中的箭头符号(将→改为->)
- 新增请假表单解析模块、钉钉通知模块
- 重构加班/请假校验模块的报告生成逻辑,统一报告格式与推送流程
4. **测试与文档
- 新增端到端测试脚本与统一测试运行器
- 完善README.md文档,补充项目结构、功能说明与使用方法
- 新增钉钉消息推送工具文档
- 新增测试用例与辅助工具
5. **其他优化
- 修复common/parser.py中的正则表达式兼容单引号的HTML属性
- 新增session_manager.py移除冗余导入与路径修正
- 新增OA审批报告生成逻辑优化,支持分组统计与详细清单输出
1171 lines
41 KiB
Python
1171 lines
41 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: leave_approval_yingdao.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-06
|
||
@Description: 请假审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致
|
||
@Version: 1.0.0
|
||
|
||
依赖安装:
|
||
pip install DrissionPage python-dotenv 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 logging
|
||
import logging.handlers
|
||
import os
|
||
import random
|
||
import re
|
||
import sys
|
||
import time
|
||
from collections import defaultdict
|
||
from datetime import datetime, timedelta
|
||
from typing import Any, Callable, Dict, List, Tuple
|
||
from urllib.parse import urlencode, urlparse, parse_qs
|
||
|
||
# ==================== 第三方库导入 ====================
|
||
try:
|
||
from DrissionPage import ChromiumPage, SessionPage
|
||
except ImportError:
|
||
ChromiumPage = None
|
||
SessionPage = None
|
||
|
||
try:
|
||
from dotenv import load_dotenv
|
||
except ImportError:
|
||
load_dotenv = lambda *args, **kwargs: None
|
||
|
||
# 钉钉推送依赖(懒加载,缺失时给出清晰提示)
|
||
try:
|
||
import pyautogui
|
||
except ImportError:
|
||
pyautogui = None
|
||
|
||
try:
|
||
import win32gui
|
||
import win32con
|
||
import win32clipboard
|
||
except ImportError:
|
||
win32gui = None
|
||
win32con = None
|
||
win32clipboard = None
|
||
|
||
try:
|
||
import pyperclip
|
||
except ImportError:
|
||
pyperclip = None
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
# 数据目录固定放在 AppData,不依赖脚本位置,每台电脑都有
|
||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), 'LeaveApproval')
|
||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||
_LOG_DIR = os.path.join(_APP_DATA_DIR, 'logs')
|
||
|
||
# ---------- 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"
|
||
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"
|
||
|
||
# ---------- 分页 ----------
|
||
DEFAULT_PAGE_SIZE = 15
|
||
|
||
|
||
# ==================== 日志配置 ====================
|
||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||
|
||
_initialized = False
|
||
|
||
|
||
class _ColoredFormatter(logging.Formatter):
|
||
_colors = {
|
||
logging.DEBUG: "\033[36m",
|
||
logging.INFO: "\033[32m",
|
||
logging.WARNING: "\033[33m",
|
||
logging.ERROR: "\033[31m",
|
||
logging.CRITICAL: "\033[35m",
|
||
}
|
||
_reset = "\033[0m"
|
||
|
||
def format(self, record: logging.LogRecord) -> str:
|
||
color = self._colors.get(record.levelno, "")
|
||
orig_levelname = record.levelname
|
||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||
result = super().format(record)
|
||
record.levelname = orig_levelname
|
||
return result
|
||
|
||
|
||
def setup_logging(level: int = logging.INFO, log_dir: str = None, log_file: bool = True) -> None:
|
||
global _initialized
|
||
if _initialized:
|
||
return
|
||
|
||
logger = logging.getLogger()
|
||
logger.setLevel(level)
|
||
logger.handlers.clear()
|
||
|
||
console_handler = logging.StreamHandler(sys.stdout)
|
||
console_handler.setLevel(level)
|
||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||
logger.addHandler(console_handler)
|
||
|
||
if log_file:
|
||
if log_dir is None:
|
||
log_dir = _LOG_DIR
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||
file_handler = logging.handlers.RotatingFileHandler(
|
||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||
)
|
||
file_handler.setLevel(logging.DEBUG)
|
||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||
logger.addHandler(file_handler)
|
||
|
||
_initialized = True
|
||
|
||
|
||
def get_logger(name: str) -> logging.Logger:
|
||
return logging.getLogger(name)
|
||
|
||
|
||
logger = get_logger("leave_approval")
|
||
|
||
|
||
# ==================== 重试装饰器 ====================
|
||
class RetryExhaustedError(Exception):
|
||
pass
|
||
|
||
|
||
def retry(max_attempts: int = 3) -> 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 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") 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:
|
||
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))
|
||
|
||
return all_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 中 data-temp 用单引号(data-temp='2026-08-04'),需同时兼容单/双引号
|
||
pattern = r'<a[^>]*data-temp=["\']([^"\']+)["\'][^>]*>([^<]+)</a>'
|
||
matches = re.findall(pattern, html)
|
||
result = {}
|
||
for date, shift in matches:
|
||
result[date.strip()] = shift.strip()
|
||
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
|
||
|
||
|
||
# ==================== 请假表单解析 ====================
|
||
VACATION_TYPE_MAP = {
|
||
"04": "病假",
|
||
"05": "产假",
|
||
"09": "事假",
|
||
"11": "调休假",
|
||
"15": "普通事假",
|
||
"17": "特殊事假",
|
||
"18": "小时特假",
|
||
"19": "普通事假(晚/高峰)",
|
||
"20": "普通事假(早/中)",
|
||
"22": "半天休(仅限人资专用)",
|
||
"23": "特别福利假",
|
||
"24": "年度福利假",
|
||
}
|
||
|
||
|
||
def _first_non_null(result, *keys):
|
||
"""返回 result 中第一个值非 None 的字段(不能用 or 链:0 / 0.0 / "" 是合法值但为 falsy)。"""
|
||
for k in keys:
|
||
v = result.get(k)
|
||
if v is not None:
|
||
return v
|
||
return None
|
||
|
||
|
||
def _resolve_vacation_type(result):
|
||
raw = _first_non_null(result, "vacation_type", "leave_type", "sub_type")
|
||
raw = str(raw).strip() if raw is not None else ""
|
||
if raw in VACATION_TYPE_MAP:
|
||
return VACATION_TYPE_MAP[raw]
|
||
return raw
|
||
|
||
|
||
def _parse_leave_form(result):
|
||
return {
|
||
"请假人员ID": result.get("staff_id"),
|
||
"请假人员": result.get("staff_name"),
|
||
"所属部门": result.get("dept_org_name"),
|
||
"假期类型": _resolve_vacation_type(result),
|
||
"开始时间": result.get("start_time"),
|
||
"结束时间": result.get("end_time"),
|
||
# leave_days 可能为 0.0(小时假),不能用 or 链(会被 falsy 短路成 None)
|
||
"请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"),
|
||
"请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"),
|
||
"附件": result.get("file"),
|
||
}
|
||
|
||
|
||
# ==================== 会话管理 ====================
|
||
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="请假"):
|
||
try:
|
||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
||
return True
|
||
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)
|
||
def _fetch_documents(session, subject):
|
||
return get_documents(session, subject=subject)
|
||
|
||
|
||
@retry(max_attempts=3)
|
||
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}
|
||
|
||
|
||
# ==================== 钉钉推送(内联精简版,保持单文件自包含) ====================
|
||
DINGTALK_WINDOW_KEYWORD = "钉钉"
|
||
|
||
|
||
def _check_dingtalk_deps():
|
||
"""检查钉钉推送必需的第三方依赖,缺失时抛出带安装提示的 RuntimeError。"""
|
||
missing = []
|
||
if pyautogui is None:
|
||
missing.append("pyautogui")
|
||
if win32gui is None:
|
||
missing.append("pywin32")
|
||
if pyperclip is None:
|
||
missing.append("pyperclip")
|
||
if missing:
|
||
raise RuntimeError(f"缺少依赖: {', '.join(missing)},请运行: pip install {' '.join(missing)}")
|
||
|
||
|
||
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。已在前台则跳过(Ctrl+D 是 toggle)。"""
|
||
if _is_dingtalk_foreground():
|
||
logger.info("钉钉窗口已在前台,跳过激活")
|
||
return
|
||
try:
|
||
pyautogui.hotkey("ctrl", "d")
|
||
time.sleep(1.0)
|
||
if not _is_dingtalk_foreground():
|
||
raise RuntimeError("Ctrl+D 未能激活")
|
||
logger.info("通过 Ctrl+D 激活钉钉窗口")
|
||
except Exception as e:
|
||
logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e)
|
||
hwnd = _find_dingtalk_hwnd()
|
||
if win32gui.IsIconic(hwnd):
|
||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||
time.sleep(0.3)
|
||
pyautogui.press("alt")
|
||
win32gui.SetForegroundWindow(hwnd)
|
||
time.sleep(1.0)
|
||
|
||
|
||
def _send_dingtalk_text(target, text):
|
||
"""搜索联系人并发送文本:激活 → Ctrl+Shift+F 搜索 → 回车进会话 → 粘贴 → 回车发送。"""
|
||
_check_dingtalk_deps()
|
||
_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(1.0)
|
||
time.sleep(2.5) # 焦点稳定到消息输入框
|
||
logger.info("已搜索并进入会话: %s", target)
|
||
# 粘贴文本并发送
|
||
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") == "人工复核"]
|
||
failed = [r for r in results if r.get("decision") == "失败"]
|
||
if not passed and not rejected and not review:
|
||
return ""
|
||
|
||
def _item(r):
|
||
info = r.get("leave_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 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 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
|
||
|
||
|
||
def run_flow(subject, validate_doc, generate_report):
|
||
setup_logging()
|
||
logger.info("%s审批流程开始", subject)
|
||
|
||
browser, session, _ = _get_browser_and_session(subject)
|
||
|
||
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)
|
||
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)
|
||
|
||
# 推送「通过项汇总」到钉钉(env 控制;无通过项或失败均不影响主流程)
|
||
push_report(build_push_summary(results, subject), subject)
|
||
|
||
save_browser_cookies(browser)
|
||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||
return report
|
||
|
||
|
||
# ==================== 请假校验规则 ====================
|
||
# 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可
|
||
HOURLY_LEAVE_TYPES = {
|
||
"小时特假",
|
||
}
|
||
|
||
# Group 1:仅校验排班上班天数与填报天数一致
|
||
LEAVE_TYPE_GROUP_1 = {
|
||
"事假", "调休假", "半天休(仅限人资专用)",
|
||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||
"年度福利假",
|
||
}
|
||
|
||
# Group 2:校验天数一致 + 需上传附件
|
||
LEAVE_TYPE_GROUP_2 = {
|
||
"病假", "特别福利假", "特殊事假", "产假",
|
||
}
|
||
|
||
|
||
def _get_date_range(start_time, end_time):
|
||
"""从请假起止时间中提取日期范围 (start_date, end_date)"""
|
||
start_date = start_time[:10] if start_time else None
|
||
end_date = end_time[:10] if end_time else None
|
||
return start_date, end_date
|
||
|
||
|
||
def _get_months_in_range(start_date, end_date):
|
||
"""获取日期范围内所有 (year, month) 元组列表,跨月按月份分段"""
|
||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||
months = []
|
||
current = start.replace(day=1)
|
||
while current <= end:
|
||
months.append((current.year, current.month))
|
||
if current.month == 12:
|
||
current = current.replace(year=current.year + 1, month=1)
|
||
else:
|
||
current = current.replace(month=current.month + 1)
|
||
return months
|
||
|
||
|
||
def _get_work_days_count(session, staff_id, start_date, end_date):
|
||
"""获取请假区间内实际上班天数(非休息日),跨月按月份分段请求"""
|
||
months = _get_months_in_range(start_date, end_date)
|
||
attendance = {}
|
||
for year, month in months:
|
||
try:
|
||
html = get_attendance_html(session, staff_id, year, month)
|
||
monthly = parse_attendance_html(html)
|
||
attendance.update(monthly)
|
||
logger.info("排班数据已获取: %d-%02d, 共 %d 天", year, month, len(monthly))
|
||
except Exception as e:
|
||
logger.warning("获取排班失败(%d-%02d): %s", year, month, str(e))
|
||
|
||
if not attendance:
|
||
raise RuntimeError("未能获取到任何排班数据")
|
||
|
||
work_days = get_work_days_in_range(attendance, start_date, end_date)
|
||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||
return len(work_days)
|
||
|
||
|
||
def validate_doc(doc, session):
|
||
"""
|
||
校验单张请假单据,返回审批决策。
|
||
|
||
Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过
|
||
Group 2(病假/产假等):天数一致 + 有附件 -> 通过
|
||
"""
|
||
form_data = doc.get("formData", {}) or {}
|
||
leave_info = _parse_leave_form(form_data)
|
||
|
||
staff_id = leave_info.get("请假人员ID")
|
||
vacation_type = leave_info.get("假期类型")
|
||
start_time = leave_info.get("开始时间")
|
||
end_time = leave_info.get("结束时间")
|
||
leave_days = leave_info.get("请假天数")
|
||
attachment = leave_info.get("附件")
|
||
|
||
result = {
|
||
"title": doc.get("title", ""),
|
||
"creator": doc.get("creator", ""),
|
||
"time": doc.get("time", ""),
|
||
"detail_url": doc.get("detail_url", ""),
|
||
"decision": "通过",
|
||
"note": "",
|
||
"leave_info": leave_info,
|
||
}
|
||
|
||
if not vacation_type:
|
||
result["decision"] = "驳回"
|
||
result["note"] = "无法识别假期类型"
|
||
return result
|
||
|
||
if not staff_id:
|
||
result["decision"] = "驳回"
|
||
result["note"] = "请假人员ID缺失"
|
||
return result
|
||
|
||
start_date, end_date = _get_date_range(start_time, end_time)
|
||
if not start_date or not end_date:
|
||
result["decision"] = "驳回"
|
||
result["note"] = "请假起止时间缺失"
|
||
return result
|
||
|
||
try:
|
||
actual_work_days = _get_work_days_count(session, staff_id, start_date, end_date)
|
||
except Exception as e:
|
||
logger.warning("计算上班天数失败: %s", str(e))
|
||
result["decision"] = "驳回"
|
||
result["note"] = f"获取排班数据失败: {e}"
|
||
return result
|
||
|
||
try:
|
||
fill_days = float(leave_days) if leave_days else 0
|
||
except (TypeError, ValueError):
|
||
fill_days = 0
|
||
|
||
leave_info["实际上班天数"] = actual_work_days
|
||
leave_info["填报天数"] = fill_days
|
||
|
||
days_mismatch = abs(actual_work_days - fill_days) > 0.01
|
||
|
||
if vacation_type in HOURLY_LEAVE_TYPES:
|
||
# 按小时请假(如小时特假):不比对天数,只要请假当天落在排班上班日即可
|
||
leave_hours = leave_info.get("请假小时")
|
||
if actual_work_days < 1:
|
||
result["decision"] = "驳回"
|
||
result["note"] = f"请假当天非排班上班日(实际上班天数: {actual_work_days})"
|
||
else:
|
||
result["decision"] = "通过"
|
||
result["note"] = (
|
||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||
f"当天为上班日)"
|
||
)
|
||
|
||
elif vacation_type in LEAVE_TYPE_GROUP_1:
|
||
if days_mismatch:
|
||
result["decision"] = "驳回"
|
||
result["note"] = f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||
else:
|
||
result["decision"] = "通过"
|
||
result["note"] = (
|
||
f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||
f"填报天数: {fill_days})"
|
||
)
|
||
|
||
elif vacation_type in LEAVE_TYPE_GROUP_2:
|
||
# 需附件的假期:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);否则驳回
|
||
reasons = []
|
||
if days_mismatch:
|
||
reasons.append(f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致")
|
||
if not attachment:
|
||
reasons.append("未上传附件")
|
||
|
||
if reasons:
|
||
result["decision"] = "驳回"
|
||
result["note"] = ";".join(reasons)
|
||
else:
|
||
result["decision"] = "人工复核"
|
||
result["note"] = (
|
||
f"需人工复核附件(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||
f"填报天数: {fill_days},附件: 已上传)"
|
||
)
|
||
else:
|
||
result["decision"] = "驳回"
|
||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||
|
||
return result
|
||
|
||
|
||
# ==================== 报告生成 ====================
|
||
def _name(r):
|
||
info = r.get("leave_info", {}) or {}
|
||
return info.get("请假人员") or r.get("creator") or "未知"
|
||
|
||
|
||
def _vtype(r):
|
||
info = r.get("leave_info", {}) or {}
|
||
return info.get("假期类型") or "未知"
|
||
|
||
|
||
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") == "人工复核"]
|
||
failed = [r for r in results if r.get("decision") == "失败"]
|
||
|
||
summary = f"共 {len(results)} 单:通过 {len(passed)},驳回 {len(rejected)},人工复核 {len(review)}"
|
||
if failed:
|
||
summary += f",处理失败 {len(failed)}"
|
||
|
||
lines = [
|
||
"请假审批报告",
|
||
"=" * 60,
|
||
summary,
|
||
"",
|
||
]
|
||
|
||
if passed:
|
||
names = "、".join(_name(r) for r in passed)
|
||
lines.append(f"【通过】{len(passed)} 条:{names}")
|
||
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)} | 假期类型: {_vtype(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)} | 假期类型: {_vtype(r)} | 详情页链接: {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()
|