# -*- coding: utf-8 -*- """ @FileName: leave_approval_yingdao.py @Author: 小布丁 @CreateTime: 2026-08-06 @Description: 请假审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致 @Version: 2.0.0 依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载): pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip Pillow numpy rapidocr-onnxruntime psutil 环境变量(.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 datetime import datetime, timedelta from typing import Callable from urllib.parse import urlencode, urlparse, parse_qs # ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ==================== # 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库 try: from DrissionPage import ChromiumPage, SessionPage from dotenv import load_dotenv import pyautogui import win32gui import win32con import win32clipboard import win32process import win32api import pyperclip import psutil from PIL import Image, ImageEnhance, ImageGrab import numpy as np from rapidocr_onnxruntime import RapidOCR except ImportError as _import_err: raise RuntimeError( "缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n" "请先执行安装:\n" " pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip " "Pillow numpy rapidocr-onnxruntime psutil\n" f"缺失依赖详情: {_import_err}" ) # ==================== OCR 附件内容检测(单文件自包含) ==================== # 影刀版不依赖项目目录,直接使用下方内置 OCR 实现(行为与原项目 app/utils/ocr.py 完全一致)。 # Pillow/numpy/rapidocr 已在上方启动校验中强制安装,不做懒加载。 # ==================== 路径 & 常量配置 ==================== # 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有(影刀版独立子目录) _APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation', 'LeaveApproval') _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" # 考勤逐日接口(按员工+日期范围返回每日班次名/班次起止/上下班打卡,data 数组) # 请假/加班校验统一使用该接口获取排班信息,替代原排班日历接口与打卡流水接口 ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc" LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc" # ---------- 分页 ---------- 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() # ==================== 内置 OCR 兜底实现 ==================== # 内置 OCR 实现(单文件自包含),行为与原项目 app/utils/ocr.py 完全一致: # 病假/婚假/产检假按关键词命中检测,结婚证按最大日期识别登记日期并判断 1 年内。 _OCR_LEAVE_KEYWORDS = { # 病假/医疗类:对应医院诊断证明、病历、检验单等 "sick": { "医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情", "检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单", }, # 婚假类:对应结婚证、婚姻登记证明 "marriage": { "结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关", "婚姻证", "中华人民共和国结婚证", }, # 产检假类:对应产检报告、B超单、妊娠诊断证明 "maternity": { "产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期", "超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心", }, } _OCR_CONFIDENCE_THRESHOLD = 0.5 _OCR_VALID_TYPES = set(_OCR_LEAVE_KEYWORDS.keys()) | {"all"} _ocr_engine = None # 前向声明,稍后在模块加载时统一初始化(不做懒加载) def _ocr_read_text(file_path, debug=False): """OCR 识别图片,返回 (清洗后拼接文本, 原始拼接文本)。""" if _ocr_engine is None: raise RuntimeError("OCR 引擎未初始化(rapidocr-onnxruntime 缺失或初始化失败)") with Image.open(file_path) as img: gray_img = img.convert("L") enhancer = ImageEnhance.Contrast(gray_img) enhanced_img = enhancer.enhance(2.0) img_array = np.array(enhanced_img) ocr_result, _ = _ocr_engine(img_array) if debug: print("=" * 60) print("【OCR原始识别片段(含置信度)】") for idx, (box, txt, score) in enumerate(ocr_result or []): print(f" [{idx:02d}] 置信度:{score:.3f} | 文本: {txt}") print("=" * 60 + "\n") raw_text = "" full_text = "" for box, text, score in ocr_result or []: if score < _OCR_CONFIDENCE_THRESHOLD: continue raw_text += text clean_text = text.replace(" ", "").replace("\u3000", "") full_text += clean_text # 过滤乱码特殊符号,保留常用字符 clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]') full_text = clean_pattern.sub('', full_text) return full_text, raw_text def _ocr_check_leave_attachment(file_path, leave_type="sick", debug=False): """检测附件图片是否包含对应假期关键词;文件异常/识别失败/未命中均返回 False。""" if leave_type not in _OCR_VALID_TYPES: return False if not os.path.isfile(file_path): return False try: full_text, _ = _ocr_read_text(file_path, debug=debug) except Exception as e: if debug: print(f"[识别异常] {e}") return False if debug: print("【清洗后匹配文本】") print(full_text) print("=" * 60 + "\n") if leave_type == "all": target_keywords = set() for kw_set in _OCR_LEAVE_KEYWORDS.values(): target_keywords.update(kw_set) else: target_keywords = _OCR_LEAVE_KEYWORDS[leave_type] hit_words = [kw for kw in target_keywords if kw in full_text] if debug: print(f"【命中关键词】: {hit_words}") return len(hit_words) > 0 def _ocr_extract_dates(text): """从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。""" dates = [] patterns = [ r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?', r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', ] for pat in patterns: for m in re.finditer(pat, text): try: dates.append(datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()) except ValueError: continue return dates def _ocr_marriage_within_one_year(file_path, today=None, debug=False): """识别结婚证登记日期(取最大日期)并判断是否在当前日期 1 年内。""" if today is None: today = datetime.now().date() if not os.path.isfile(file_path): return False, None try: full_text, _ = _ocr_read_text(file_path, debug=debug) except Exception as e: if debug: print(f"[识别异常] {e}") return False, None dates = _ocr_extract_dates(full_text) if not dates: if debug: print("【未识别到任何日期】") return False, None reg_date = max(dates) ok = reg_date <= today and (today - reg_date).days <= 365 if debug: print(f"【识别日期】: {dates}") print(f"【登记日期】: {reg_date},1年内: {ok}") return ok, reg_date # 单文件自包含:直接使用内置 OCR 实现(启动即初始化引擎,不做懒加载) check_leave_attachment = _ocr_check_leave_attachment marriage_within_one_year = _ocr_marriage_within_one_year _ocr_engine = RapidOCR() # 首次运行自动下载模型,缺库/失败立即暴露 # ==================== 重试装饰器 ==================== 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']*>(.*?)', title_raw, re.DOTALL) title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip() creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {}) creator = creator_cell.get("value", "") time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {}) time_str = time_cell.get("value", "") href_cell = next((c for c in row if c["col"] == "tr_href"), {}) detail_url = href_cell.get("value", "") if detail_url and not detail_url.startswith(("http://", "https://")): detail_url = BASE_URL + detail_url # 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:请假申请"): # 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到 # unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试 if "kmCollaborateMain.do" in detail_url: logger.warning("跳过非审批待办(工作沟通/协作): %s", title) continue docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url}) return docs def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE): all_docs = [] data = fetch_todo_page(session, subject, page_no=1, page_size=page_size) total = int(data.get("page", {}).get("totalSize", 0)) logger.info("总待办[%s]条数: %d", subject, total) docs = parse_todo_list(data) all_docs.extend(docs) logger.info("第 1 页获取 %d 条", len(docs)) if total > page_size: total_pages = (total + page_size - 1) // page_size for p in range(2, total_pages + 1): data = fetch_todo_page(session, subject, page_no=p, page_size=page_size) docs = parse_todo_list(data) all_docs.extend(docs) logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs)) # 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现), # 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送 seen = set() unique_docs = [] for doc in all_docs: key = doc.get("detail_url") or doc.get("title") if key in seen: continue seen.add(key) unique_docs.append(doc) if len(unique_docs) != len(all_docs): logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)", len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs)) return unique_docs def get_wf_activity_by_task_id(session, task_id): url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId" data = {"taskId": task_id} logger.info("获取 formId: taskId=%s", task_id) session.post(url, data=data) resp = session.response if not resp: raise RuntimeError("WfActivity 请求失败,未获取到响应") if resp.status_code != 200: raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}") try: json_data = resp.json() except Exception: body = (resp.text or "")[:200] raise RuntimeError(f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") logger.debug("WfActivity 返回: %s", json_data) return json_data def extract_form_id(wf_activity_data): form_id = ( wf_activity_data.get("formId") or wf_activity_data.get("FormId") or wf_activity_data.get("form_id") ) if not form_id: for key in ("data", "result"): data_obj = wf_activity_data.get(key, {}) if isinstance(data_obj, dict): form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id") if form_id: break if not form_id: raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}") logger.info("提取到 formId: %s", form_id) return form_id def get_business_data(session, business_key, form_id): url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate" data = {"businessKey": business_key, "formId": form_id} logger.info("获取请假表单: businessKey=%s, formId=%s", business_key, form_id) session.post(url, data=data) resp = session.response if not resp: raise RuntimeError("WorkformEngine 请求失败,未获取到响应") if resp.status_code != 200: raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}") try: json_data = resp.json() except Exception: body = (resp.text or "")[:200] raise RuntimeError(f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") result = json_data.get("result") if json_data.get("state") != "1" or not isinstance(result, dict): raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}") logger.info("WorkformEngine 返回成功") return result def get_attendance_daily(session, staff_id, start_date, end_date): """按员工+日期范围查询每日考勤(含班次名/班次起止时间/上下班打卡)。 接口: rf_s_kq_count_leave_yc_day_all/redApiExec.mc kq_status_total 按考勤状态分类返回记录(来源为前端 JS 扒取的请求构造): - 0=休息日、1=正常班、9=未打卡、11=异常(如上班漏打卡) 因此需按这四种状态各查一次,再按 work_day 合并去重,才能同时拿到 班次名/班次时段与休息日、异常班当天的上下班打卡。 """ by_day = {} for status in ("0", "1", "9", "11"): params = { "staff_id": staff_id, "begin_date": start_date, "end_date": end_date, "kq_status_total": status, } logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s", status, staff_id, start_date, end_date) session.post(ATTENDANCE_DAILY_URL, data=params) resp = session.response if not resp: raise RuntimeError("考勤逐日请求失败,未获取到响应") if resp.status_code != 200: raise RuntimeError(f"考勤逐日接口状态码异常: {resp.status_code}") try: json_data = resp.json() except Exception: body = (resp.text or "")[:200] raise RuntimeError(f"考勤逐日接口返回非 JSON 数据: {body}") for r in json_data.get("data", []) or []: by_day.setdefault(str(r.get("work_day", "")), r) records = [by_day[k] for k in sorted(by_day)] logger.info("考勤逐日合并返回 %d 天", len(records)) return records def fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"): data = { "sub_type": sub_type, "staff_id": staff_id, "begin_date": begin_date, "end_date": end_date, "start": str((page_no - 1) * page_size), "pageSize": str(page_size), "sortType": "", "sortName": "", "pageNo": str(page_no), } logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no) session.post(LEAVE_RECORD_URL, data=data) resp = session.response if not resp: raise RuntimeError("请假记录请求失败,未获取到响应") if resp.status_code != 200: raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}") try: json_data = resp.json() except Exception: body = (resp.text or "")[:200] raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}") if json_data.get("success") is not True or json_data.get("code") != 200: raise RuntimeError(f"请假记录接口返回失败: {json_data}") page_info = json_data.get("data") if not isinstance(page_info, dict): raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}") return page_info def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"): all_records = [] page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=page_size, sub_type=sub_type) total = int(page_info.get("total", 0)) page_total = int(page_info.get("pageCount", 1)) records = page_info.get("list", []) or [] all_records.extend(records) logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records)) if page_total > 1: for p in range(2, page_total + 1): page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=p, page_size=page_size, sub_type=sub_type) records = page_info.get("list", []) or [] all_records.extend(records) logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records)) return all_records # ==================== 请假表单解析 ==================== 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("leave_reason"), "附件": 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 download_attachment(session, file_id, save_dir=r"D:\资料\人资\请假流程审批\附件"): """ 根据附件 fileId 从 OA 下载附件文件。 下载地址: /RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob?fileId= 通过 session(已带登录 Cookie)发起 GET,并按响应头保存为真实文件名。 返回保存路径;失败返回 None。 """ if not file_id: logger.warning("附件 fileId 为空,跳过下载") return None from urllib.parse import unquote os.makedirs(save_dir, exist_ok=True) download_url = ( "https://hr.37du.co/RedseaPlatform/corePlatformOutUser/" f"fjkFileDownload.mob?fileId={file_id}" ) try: session.get(download_url) resp = session.response except Exception as e: logger.warning("附件请求失败(fileId=%s): %s", file_id, e) return None if not resp or resp.status_code != 200: logger.warning("附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id) return None # 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码) filename = None cd = resp.headers.get("Content-Disposition", "") if "filename=" in cd: raw = cd.split("filename=")[-1].strip().strip('"') if raw.startswith("UTF-8''"): raw = unquote(raw.split("UTF-8''", 1)[1]) if raw: filename = raw # 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名 if not filename: filename = file_id ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower() ext_map = { "image/png": ".png", "image/jpeg": ".jpg", "application/pdf": ".pdf", "application/octet-stream": ".bin", } filename += ext_map.get(ct, ".bin") # 清理非法字符,防止路径注入 filename = "".join(c for c in filename if c not in '\\/:*?"<>|') path = os.path.join(save_dir, filename) with open(path, "wb") as f: f.write(resp.content) logger.info("附件已下载: %s", path) return path 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_error = '''''' # 审批驳回 / 失败图标 # ================================================== svg_icon = svg_success if type_ == "success" else svg_error accent_color = "#13C463" if type_ == "success" else "#F5222D" js_script = f''' (function() {{ const old = document.getElementById("rpa_apple_pop"); if (old) old.remove(); const mask = document.createElement('div'); mask.id = "rpa_apple_pop"; mask.style.cssText = ` position: fixed; inset: 0; z-index: 999999; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.25s ease; `; // 放大图标容器,无背景 const iconWrap = document.createElement('div'); iconWrap.style.cssText = ` position: relative; width: 180px; height: 180px; display: flex; align-items: center; justify-content: center; transform: scale(0); transition: transform 0.6s cubic-bezier(0.17, 0.89, 0.32, 1.27); `; iconWrap.innerHTML = `{svg_icon}`; const svg = iconWrap.querySelector('svg'); if (svg) {{ svg.style.width = '100%'; svg.style.height = '100%'; }} mask.appendChild(iconWrap); document.body.appendChild(mask); // 直接应用样式(不依赖 requestAnimationFrame,后台/未激活标签页也能正常显示) mask.style.opacity = '1'; iconWrap.style.transform = 'scale(1)'; setTimeout(() => {{ mask.style.opacity = '0'; iconWrap.style.transform = 'scale(0.8)'; setTimeout(() => mask.remove(), 300); }}, {int(stay_seconds * 1000)}); }})(); ''' page.run_js(js_script) # 阻塞等待弹窗展示完成:弹窗稍后会被下一步打开单据的页面跳转清除, # 若不等待,弹窗会"一闪而过"看不清审批结果 time.sleep(stay_seconds) # ==================== 钉钉推送(OCR 视觉方案内联,保持单文件自包含) ==================== # 内联自 app/utils/dingtalk_sender.py(视觉方案),相比旧固定坐标模拟大幅提升稳定性: # 窗口查找排除 0 尺寸阴影/辅助窗口,只认主窗口;多策略激活(快捷键→Win32 API→组合); # 搜索框/标签/输入框全部通过 OCR 校验后再操作。 _DT_TIMEOUT = 8 _DT_SEARCH_RETRY = 3 _DT_RETRY_TIMES = 3 _DT_TOP_HEIGHT_RATIO = 0.18 _dt_ocr = None def _dt_get_ocr(): """获取 RapidOCR 实例(单例;若模块已初始化 _ocr_engine 则复用,避免重复加载模型)。""" global _dt_ocr # 用 globals().get 而非直接读 _dt_ocr:避免个别运行环境/旧 pyc 下模块级 _dt_ocr 未定义时抛 NameError _dt_ocr = globals().get("_dt_ocr") if _dt_ocr is None: _dt_ocr = globals().get("_ocr_engine") or RapidOCR() return _dt_ocr def _dt_get_process_name_by_pid(pid): """根据进程 ID 获取进程名称,失败返回 None""" try: return psutil.Process(pid).name() except Exception: return None def _dt_find_dingtalk_window(include_hidden=True): """查找钉钉“主窗口”句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。""" def has_valid_rect(hwnd): try: left, top, right, bottom = win32gui.GetWindowRect(hwnd) return (right - left) > 0 and (bottom - top) > 0 except Exception: return False def is_main_title(hwnd): return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk') candidates = [] def enum_callback(hwnd, _): if not include_hidden and not win32gui.IsWindowVisible(hwnd): return True title = win32gui.GetWindowText(hwnd) if title == '钉钉' or title == 'DingTalk': candidates.append(hwnd) return True try: _, pid = win32process.GetWindowThreadProcessId(hwnd) proc_name = _dt_get_process_name_by_pid(pid) if proc_name and proc_name.lower() == 'dingtalk.exe': candidates.append(hwnd) return True except Exception: pass return True win32gui.EnumWindows(enum_callback, None) valid = [h for h in candidates if has_valid_rect(h)] if not valid: return None for h in valid: if is_main_title(h) and win32gui.IsWindowVisible(h): return h for h in valid: if is_main_title(h): return h for h in valid: if win32gui.IsWindowVisible(h): return h return valid[0] def _dt_activate_window(hwnd): """强制激活窗口(最小化、隐藏、托盘均可恢复)""" if win32gui.IsIconic(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) time.sleep(0.3) if not win32gui.IsWindowVisible(hwnd): win32gui.ShowWindow(hwnd, win32con.SW_SHOW) time.sleep(0.3) win32gui.SetForegroundWindow(hwnd) win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.3) def _dt_get_window_rect(hwnd): """获取窗口矩形 (left, top, right, bottom)""" return win32gui.GetWindowRect(hwnd) def _dt_is_dingtalk_main_visible(): """钉钉主窗口当前是否可见""" hwnd = _dt_find_dingtalk_window(include_hidden=True) return bool(hwnd) and win32gui.IsWindowVisible(hwnd) def _dt_is_dingtalk_foreground(): """钉钉主窗口是否已处于最前""" fg = win32gui.GetForegroundWindow() if not fg: return False title = win32gui.GetWindowText(fg) or "" return '钉钉' in title or 'DingTalk' in title def _dt_capture_region(x, y, w, h): """截取屏幕指定区域,若区域无效则返回 None""" if w <= 0 or h <= 0: logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h) return None img = ImageGrab.grab(bbox=(x, y, x + w, y + h)) if img is None or img.size[0] == 0 or img.size[1] == 0: logger.warning("抓取图像为空") return None return img def _dt_ocr_image(img): """对图像进行 OCR 识别,返回 (text, (x1,y1,x2,y2)) 列表""" if img is None: return [] img_np = np.array(img) result, _ = _dt_get_ocr()(img_np) ocr_data = [] if result is not None: for box, text, score in result: xs = [p[0] for p in box] ys = [p[1] for p in box] x1, y1 = min(xs), min(ys) x2, y2 = max(xs), max(ys) ocr_data.append((text, (x1, y1, x2, y2))) return ocr_data def _dt_find_text_center(ocr_data, target_text): """在 OCR 结果中查找包含 target_text 的文本框,返回中心坐标 (x, y)""" for text, (x1, y1, x2, y2) in ocr_data: if target_text in text: return (x1 + x2) // 2, (y1 + y2) // 2 return None def _dt_wait_for_tab(hwnd, expected_tab, timeout=_DT_TIMEOUT): """循环检测窗口顶部是否出现 expected_tab 标签(如“联系人”或“群组”)。""" left, top, right, bottom = _dt_get_window_rect(hwnd) width = right - left height = bottom - top top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO)) start = time.time() while time.time() - start < timeout: img = _dt_capture_region(left, top, width, top_height) ocr_data = _dt_ocr_image(img) if _dt_find_text_center(ocr_data, expected_tab): logger.info("检测到'%s'标签", expected_tab) return True time.sleep(0.5) logger.warning("未检测到'%s'标签", expected_tab) return False def _dt_is_chat_opened(hwnd, target_name): """截取窗口顶部区域,OCR识别是否有目标名称""" left, top, right, bottom = _dt_get_window_rect(hwnd) width = right - left height = bottom - top top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO)) img = _dt_capture_region(left, top, width, top_height) ocr_data = _dt_ocr_image(img) for text, _ in ocr_data: if target_name in text: logger.debug("标题识别到: '%s'", text) return True return False def _dt_search_and_open(hwnd, target_name, chat_type="联系人"): """搜索并打开指定的联系人或群组会话。""" _dt_activate_window(hwnd) for attempt in range(_DT_SEARCH_RETRY): pyautogui.hotkey('ctrl', 'shift', 'f') time.sleep(0.8) pyautogui.hotkey('ctrl', 'a') pyautogui.press('delete') pyperclip.copy(target_name) pyautogui.hotkey('ctrl', 'v') time.sleep(0.5) pyautogui.press('enter') logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1) time.sleep(0.8) if _dt_wait_for_tab(hwnd, chat_type, timeout=3): break else: pyautogui.press('esc') time.sleep(0.5) else: logger.error("搜索框未正常打开") return False left, top, right, bottom = _dt_get_window_rect(hwnd) width = right - left height = bottom - top top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO)) img = _dt_capture_region(left, top, width, top_height) ocr_data = _dt_ocr_image(img) pos = _dt_find_text_center(ocr_data, chat_type) if pos: cx, cy = pos pyautogui.click(left + cx, top + cy) logger.info("点击'%s'标签", chat_type) else: logger.warning("未识别'%s'标签", chat_type) time.sleep(0.5) pyautogui.press('enter') logger.info("打开第一个匹配项") time.sleep(1.5) start = time.time() while time.time() - start < _DT_TIMEOUT: if _dt_is_chat_opened(hwnd, target_name): logger.info("成功进入会话 '%s'", target_name) return True _dt_activate_window(hwnd) time.sleep(0.5) logger.warning("未检测到会话名 '%s'", target_name) return False def _dt_find_input_box_by_ocr(hwnd): """通过OCR识别“请输入消息”等提示文字,返回屏幕坐标""" left, top, right, bottom = _dt_get_window_rect(hwnd) width = right - left height = bottom - top bottom_region_top = top + int(height * 0.6) bottom_region_height = int(height * 0.4) img = _dt_capture_region(left, bottom_region_top, width, bottom_region_height) ocr_data = _dt_ocr_image(img) keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"] for keyword in keywords: pos = _dt_find_text_center(ocr_data, keyword) if pos: cx, cy = pos screen_x = left + cx screen_y = bottom_region_top + cy logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y) return screen_x, screen_y logger.warning("未识别到输入框提示") return None def _dt_focus_input_box(hwnd): """定位并点击输入框,使其获得焦点""" input_pos = _dt_find_input_box_by_ocr(hwnd) if input_pos: pyautogui.click(input_pos[0], input_pos[1]) return True left, top, right, bottom = _dt_get_window_rect(hwnd) width = right - left height = bottom - top pyautogui.click(left + width // 2, top + height - 60) logger.warning("使用固定坐标点击输入框") return False def _dt_send_hotkey_to_activate(): """模拟按下全局快捷键 Ctrl+Alt+D 以激活钉钉窗口""" logger.info("尝试快捷键 Ctrl+Alt+D 激活") pyautogui.hotkey('ctrl', 'alt', 'd') time.sleep(0.8) def _dt_is_dingtalk_activated(hwnd, target_name=None): """通过 OCR 检测钉钉窗口是否已激活到前台(主界面可见)。""" try: left, top, right, bottom = _dt_get_window_rect(hwnd) width = right - left height = bottom - top if width <= 0 or height <= 0: return False top_height = max(50, int(height * 0.18)) img = _dt_capture_region(left, top, width, top_height) if img is None: return False ocr_data = _dt_ocr_image(img) if target_name: for text, _ in ocr_data: if target_name in text: return True main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"] for kw in main_keywords: for text, _ in ocr_data: if kw in text: return True return False except Exception as e: logger.warning("激活检测异常: %s", e) return False def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10): """多策略确保钉钉窗口激活到前台(快捷键→Win32 API→组合)。""" def wait_for_valid_rect(hwnd, max_wait=1.5): end = time.time() + max_wait while time.time() < end: left, top, right, bottom = _dt_get_window_rect(hwnd) if (right - left) > 0 and (bottom - top) > 0: return True time.sleep(0.2) return False def find_current(): return _dt_find_dingtalk_window(include_hidden=True) or hwnd def verify(hwnd): start = time.time() while time.time() - start < timeout: if _dt_is_dingtalk_activated(hwnd, target_name=None): return True time.sleep(0.5) return False if _dt_is_dingtalk_foreground(): logger.info("钉钉已在最前,跳过激活") return True if not _dt_is_dingtalk_main_visible(): _dt_send_hotkey_to_activate() cur = find_current() if cur and wait_for_valid_rect(cur) and verify(cur): logger.info("快捷键激活成功") win32gui.SetForegroundWindow(cur) return True logger.warning("快捷键后窗口尺寸无效") else: logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)") logger.info("尝试 Win32 API 激活") cur = find_current() if cur: _dt_activate_window(cur) if wait_for_valid_rect(cur) and verify(cur): logger.info("API激活成功") return True logger.warning("API后窗口尺寸无效") logger.info("组合激活") if not _dt_is_dingtalk_main_visible(): _dt_send_hotkey_to_activate() time.sleep(0.5) cur = find_current() if cur: _dt_activate_window(cur) time.sleep(1) if wait_for_valid_rect(cur) and verify(cur): logger.info("组合激活成功") return True raise RuntimeError("所有激活策略失败") def _dt_find_hwnd_or_raise(): """查找钉钉窗口,失败时给出可读的错误信息。""" hwnd = _dt_find_dingtalk_window(include_hidden=True) if not hwnd: dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter()) if not dingtalk_running: raise RuntimeError("钉钉进程未运行,请手动启动并登录") else: raise RuntimeError("找到进程但无窗口,请手动激活") return hwnd def _dt_send_text_to_person(name, text): """向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。""" if not text or not text.strip(): raise ValueError("text 不能为空") for attempt in range(_DT_RETRY_TIMES): try: hwnd = _dt_find_hwnd_or_raise() _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10) hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd if not _dt_search_and_open(hwnd, name, "联系人"): raise RuntimeError("打开联系人会话失败") _dt_focus_input_box(hwnd) time.sleep(0.3) pyperclip.copy(text) pyautogui.hotkey('ctrl', 'v') time.sleep(0.2) pyautogui.press('enter') logger.info("发送成功:%s...", text[:30]) return True except RuntimeError as e: logger.error(str(e)) raise except Exception as e: logger.error("第%d次尝试失败:%s", attempt + 1, e) time.sleep(2) raise RuntimeError(f"重试 {_DT_RETRY_TIMES} 次后失败") def _send_dingtalk_text(target, text): """推送文本到钉钉联系人(OCR 视觉方案,与 app/utils/dingtalk_sender.py 行为一致)。""" _dt_send_text_to_person(target, text) 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 # ==================== 真实审批提交 ==================== # 影刀环境无 .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")) results.append(result) logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"]) # 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示 # 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截 try: show_rpa_result_popup( browser, "success" if result.get("decision") == "通过" else "error", 2.5, ) except Exception: pass except Exception as e: logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e)) results.append({ "creator": doc.get("creator", "未知"), "title": doc.get("title", "未知"), "decision": "失败", "error": str(e), }) report = generate_report(results) print("\n" + report) # 先推送摘要到钉钉 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 # ==================== 请假校验规则 ==================== # 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可 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_work_days_count(session, staff_id, start_date, end_date): """获取请假区间内实际上班天数(非休息日)。 数据源为考勤逐日接口,按日期范围一次查询,返回区间内每天的班次名 (bc_name,休息日为"休息"),据此统计非休息的天数。 """ try: records = get_attendance_daily(session, staff_id, start_date, end_date) logger.info("排班数据已获取: %s ~ %s, 共 %d 天", start_date, end_date, len(records)) except Exception as e: logger.warning("获取排班失败(%s~%s): %s", start_date, end_date, str(e)) records = [] if not records: raise RuntimeError("未能获取到任何排班数据") attendance = {str(r.get("work_day", "")): r.get("bc_name", "") for r in records} work_days = [] current = datetime.strptime(start_date, "%Y-%m-%d") end_dt = datetime.strptime(end_date, "%Y-%m-%d") while current <= end_dt: day = current.strftime("%Y-%m-%d") if attendance.get(day) not in (None, "", "休息"): work_days.append(day) current += timedelta(days=1) logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days)) return len(work_days) def _verify_attachment(session, vacation_type, reason, file_id): """ 根据假期类型校验附件内容,返回 (decision, note, attachment_path)。 - 病假:OCR 病假关键词,命中通过,未命中人工复核 - 特别福利假:按请假理由细分 - 婚假:OCR 结婚证关键词 + 登记日期 1 年内 - 产检假:OCR 产检关键词 - 丧假:有附件即通过 - 特殊事假 / 产假:有附件即通过 """ path = download_attachment(session, file_id) if not path: return "人工复核", "附件下载失败,需人工核验", None if vacation_type == "病假": if check_leave_attachment(path, "sick"): return "通过", "附件OCR检测通过(病假)", path return "人工复核", "附件OCR未命中病假关键词,需人工核验", path if vacation_type == "特别福利假": reason = reason or "" if "婚" in reason: if not check_leave_attachment(path, "marriage"): return "人工复核", "附件OCR未命中结婚证关键词,需人工核验", path ok, reg_date = marriage_within_one_year(path) if ok: return "通过", f"结婚证OCR检测通过(登记日期{reg_date}在1年内)", path return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内,需人工核验", path if "产" in reason or "孕" in reason: if check_leave_attachment(path, "maternity"): return "通过", "产检附件OCR检测通过", path return "人工复核", "附件OCR未命中产检关键词,需人工核验", path if "丧" in reason: return "通过", "丧假附件已上传", path return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path # 特殊事假 / 产假:有附件即通过 return "通过", "附件已上传", path 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 # 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对: # 0.5天->1个工作日,1.0天->1个工作日,1.5天->2个工作日 days_mismatch = actual_work_days != math.ceil(round(fill_days, 2)) 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})" elif not attachment: result["decision"] = "驳回" result["note"] = "未上传附件" else: result["decision"] = "通过" result["附件路径"] = download_attachment(session, attachment) 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: # 需附件的假期:天数一致 + 附件内容校验(OCR/仅附件);无法确认 -> 人工复核 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"], result["附件路径"] = _verify_attachment( session, vacation_type, leave_info.get("请假原因"), attachment ) 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 _format_detail(info): """将 leave_info 字典格式化为易读的明细行。""" fields = [ ("请假人员", "请假人员"), ("所属部门", "所属部门"), ("假期类型", "假期类型"), ("开始时间", "开始时间"), ("结束时间", "结束时间"), ("请假天数", "请假天数"), ("请假小时", "请假小时"), ("实际上班天数", "实际上班天数"), ("填报天数", "填报天数"), ("附件", "附件"), ] 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") == "人工复核"] 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, "", ] # ----- 明细清单(所有审批单的完整数据) ----- lines.append("【审批明细】") for i, r in enumerate(results, 1): info = r.get("leave_info", {}) or {} decision = r.get("decision", "未知") note = r.get("note") or r.get("error") or "" lines.append(f" #{i} {_name(r)}({_vtype(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)} | 假期类型: {_vtype(r)} | 驳回原因: {reason}") lines.append("") # ----- 人工复核清单 ----- if review: lines.append("《附件人工复核待办清单》") for i, r in enumerate(review, 1): url = r.get("detail_url") or "无" path = r.get("附件路径") or "下载失败" lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}") 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()