统一优化多个HR、OA、雇主险相关脚本的文件注释: 1. 整理折叠冗长的业务描述,将具体规则指向对应docs目录下的需求文档 2. 简化登录、推送流程的说明文本,统一表述风格 3. 修正雇主险调度脚本的main函数传参类型,匹配实际调用逻辑
1786 lines
90 KiB
Python
1786 lines
90 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: leave_approval.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-06
|
||
@Description: 请假审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致。
|
||
具体业务逻辑见 docs/请假审批/需求文档.md、流程文档.md、开发文档.md。
|
||
@Version: 2.2.0
|
||
|
||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install DrissionPage python-dotenv Pillow numpy rapidocr-onnxruntime
|
||
|
||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
|
||
缺失/失效时先拖入「37duOA登录」指令再运行本流程。
|
||
|
||
推送(本脚本只生成待推送文本,不内联发送):
|
||
main() 将结果消息写入影刀全局变量 messages,由「37du钉钉群机器人推送」指令发送。
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import functools
|
||
import json
|
||
import math
|
||
import os
|
||
import random
|
||
import re
|
||
import sys
|
||
import time
|
||
from datetime import datetime, timedelta
|
||
from typing import Callable
|
||
from urllib.parse import urlencode, urlparse, parse_qs
|
||
|
||
# ==================== VC++ 运行库预加载(自包含,目标机免装运行库) ====================
|
||
# onnxruntime 强依赖新版 MSVC 运行库 DLL(msvcp140*.dll / vcruntime140*.dll),缺失会报
|
||
# "onnxruntime DLL 初始化例程失败(1114)"。这里把随包分发的运行库目录加入 DLL 搜索路径,
|
||
# 这样任何机型只要带了 vc_redist 目录即可运行,无需手动安装 VC++ 2015-2022 运行库。
|
||
def _load_vc_redist():
|
||
candidates = [
|
||
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vc_redist'), # 与脚本同目录
|
||
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'vc_redist')), # 项目根目录
|
||
os.path.join(
|
||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||
'37duAutomation', 'vc_redist'), # 影刀共享数据目录
|
||
]
|
||
for _dir in candidates:
|
||
if os.path.isdir(_dir):
|
||
try:
|
||
os.add_dll_directory(_dir)
|
||
except Exception:
|
||
pass
|
||
_load_vc_redist()
|
||
|
||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||
try:
|
||
import requests
|
||
from DrissionPage import ChromiumPage, SessionPage
|
||
from dotenv import load_dotenv
|
||
from PIL import Image, ImageEnhance
|
||
import numpy as np
|
||
from rapidocr_onnxruntime import RapidOCR
|
||
except ImportError as _import_err:
|
||
raise RuntimeError(
|
||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||
"请先执行安装:\n"
|
||
" pip install DrissionPage python-dotenv Pillow numpy rapidocr-onnxruntime requests\n"
|
||
f"缺失依赖详情: {_import_err}"
|
||
)
|
||
|
||
# ==================== OCR 附件内容检测(单文件自包含) ====================
|
||
# 影刀版不依赖项目目录,直接使用下方内置 OCR 实现(行为与原项目 app/utils/ocr.py 完全一致)。
|
||
# Pillow/numpy/rapidocr 已在上方启动校验中强制安装,不做懒加载。
|
||
|
||
|
||
# ==================== 路径 & 常量配置 ====================
|
||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有
|
||
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 yingdao/share/oa_login.py)
|
||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||
# HR 登录态:由「37duHR登录」共享指令(yingdao/share/hr_login.py)写入
|
||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_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"
|
||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||
# 当前登录用户信息(排班/考勤接口权限参数 user_id/rootId 的来源)
|
||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||
# 排班查询接口(逐日班次为动态列 "YYYY-MM-DD_bc_name/bc_time/...";
|
||
# bc_name 为班次名,"休息"或空串表示休息日;paiban_type 不可靠不可用来判定休息)
|
||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||
|
||
# ---------- 分页 ----------
|
||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
|
||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||
DEFAULT_PAGE_SIZE = 100
|
||
PAGE_MAX_SIZE = 500 # 排班查询单页最大条数
|
||
|
||
|
||
# ==================== 真实审批提交 ====================
|
||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||
APPROVE_ENABLED = False
|
||
# 审批按钮:仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||
_APPROVE_BUTTONS = {
|
||
"通过": ("#chooseSubmit", "同意"),
|
||
}
|
||
|
||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||
class _PrintLogger:
|
||
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
|
||
def debug(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def info(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def warning(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def error(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
|
||
logger = _PrintLogger()
|
||
|
||
|
||
def _set_glv(name, value):
|
||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||
try:
|
||
glv[name] = value
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ==================== 登录态(共享 cookies 文件) ====================
|
||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
|
||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||
# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
|
||
|
||
|
||
# ==================== 内置 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_check_leave_attachment_detail(file_path, leave_type="sick", debug=False):
|
||
"""检测附件是否命中关键词,返回 (是否命中, 命中关键词列表, OCR全文)。"""
|
||
if leave_type not in _OCR_VALID_TYPES:
|
||
return False, [], ""
|
||
if not os.path.isfile(file_path):
|
||
return False, [], ""
|
||
|
||
try:
|
||
full_text, raw_text = _ocr_read_text(file_path, debug=debug)
|
||
except Exception as e:
|
||
if debug:
|
||
print(f"[识别异常] {e}")
|
||
return False, [], ""
|
||
|
||
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]
|
||
return len(hit_words) > 0, hit_words, raw_text
|
||
|
||
|
||
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
|
||
check_leave_attachment_detail = _ocr_check_leave_attachment_detail
|
||
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.s_raq=<随机小数>,每次刷新
|
||
"q.s_raq": str(random.random()),
|
||
"q.fdSubject": subject,
|
||
# 分页参数必须用 pageno/rowsize/pagingtype:
|
||
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
|
||
"pageno": page_no,
|
||
"rowsize": page_size,
|
||
"pagingtype": "default",
|
||
"orderby": "fdCreateTime",
|
||
"ordertype": "down",
|
||
}
|
||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
||
logger.debug("请求第 %d 页: %s", page_no, url)
|
||
|
||
session.get(url)
|
||
resp = session.response
|
||
if not resp:
|
||
raise RuntimeError("请求失败,未获取到响应")
|
||
if resp.status_code != 200:
|
||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
||
try:
|
||
return resp.json()
|
||
except Exception:
|
||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||
if "login.jsp" in (resp.text or "") or "j_username" in (resp.text or ""):
|
||
raise OALoginExpiredError("待办接口返回登录页,OA 登录态已失效")
|
||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||
|
||
|
||
def parse_todo_list(data):
|
||
datas = data.get("datas", [])
|
||
if not datas:
|
||
return []
|
||
|
||
docs = []
|
||
for row in datas:
|
||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
||
title_raw = title_cell.get("value", "")
|
||
match = re.search(r'<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
|
||
|
||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:请假申请"):
|
||
# 链接指向协作模块 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
|
||
|
||
|
||
# ==================== HR 会话 & 排班查询(原排班接口 rf_p_kq_count_SelectBanci) ====================
|
||
# 原排班接口按工号(base_code)+日期范围查询排班,含未来日期,替代考勤逐日接口
|
||
# (rf_s_kq_count_leave_yc_day_all 仅返回当天及之前的排班,未来日期无数据)。
|
||
# 登录态复用「37duHR登录」写入的 hr_cookies.json,user_id 来自 getCurUserInfo(当前操作人)。
|
||
class HRSessionExpiredError(Exception):
|
||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||
|
||
|
||
def _load_shared_hr_cookies():
|
||
"""读取共享 HR 登录 cookies(由「37duHR登录」指令写入)。"""
|
||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||
return None
|
||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
|
||
|
||
def _ensure_hr_cookies():
|
||
"""确保存在 HR 登录态文件;缺失时提示先运行「37duHR登录」指令。"""
|
||
if _load_shared_hr_cookies():
|
||
return True
|
||
raise RuntimeError(
|
||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 "
|
||
"python yingdao/share/hr_login.py")
|
||
|
||
|
||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||
resp.raise_for_status()
|
||
text = resp.text
|
||
if not text or not text.lstrip().startswith(("{", "[")):
|
||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||
return resp.json()
|
||
|
||
|
||
def build_hr_session():
|
||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 37du.co 域)。"""
|
||
_ensure_hr_cookies()
|
||
cookies = _load_shared_hr_cookies()
|
||
if not cookies:
|
||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||
"Content-Type": "application/x-www-form-urlencoded",
|
||
})
|
||
for c in cookies:
|
||
if c.get("domain") and "37du.co" in c["domain"]:
|
||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||
return session
|
||
|
||
|
||
def fetch_cur_user_info(session):
|
||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||
|
||
|
||
# 模块级缓存:单次运行内复用 HR 会话与当前操作人 user_id
|
||
_HR_CTX = {"session": None, "user_id": None}
|
||
|
||
|
||
def _get_hr_context():
|
||
"""获取 (hr_session, user_id),带缓存;失效时清缓存重试一次。"""
|
||
if _HR_CTX["session"] is not None:
|
||
return _HR_CTX["session"], _HR_CTX["user_id"]
|
||
_ensure_hr_cookies()
|
||
session = build_hr_session()
|
||
info = fetch_cur_user_info(session)
|
||
user_id = info.get("userId", "")
|
||
if not user_id:
|
||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||
_HR_CTX.update(session=session, user_id=user_id)
|
||
return session, user_id
|
||
|
||
|
||
def ensure_hr_context():
|
||
"""校验 HR 登录态有效(hr_cookies + getCurUserInfo),供流程开头一次性调用。
|
||
|
||
失效时抛 SystemExit 友好提示(无堆栈),提醒先运行「37duHR登录」指令,
|
||
避免每张单据校验排班时才逐个失败。
|
||
"""
|
||
try:
|
||
_get_hr_context()
|
||
return True
|
||
except Exception as e:
|
||
logger.warning("HR 登录态校验失败: %s", e)
|
||
raise SystemExit(
|
||
"HR 登录态已失效(hr_cookies.json 过期或无效)。\n"
|
||
"请先在影刀流程开头调用「37duHR登录」指令完成登录,"
|
||
"或本地运行: python yingdao/share/hr_login.py\n"
|
||
"重新登录后再运行本流程。")
|
||
|
||
|
||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||
"""请求单页排班数据(按工号 base_code 查询)。"""
|
||
params = {
|
||
"treecode": treecode,
|
||
"user_id": user_id,
|
||
"sqlId": "kq_count_SelectBanci",
|
||
"commonQuery": "",
|
||
"commonQueryStr": "",
|
||
"staff_ids": "",
|
||
"person_status": "1,4",
|
||
"post_no": "",
|
||
"post_type": "1",
|
||
"post_level": "",
|
||
"identity": "",
|
||
"showType": "1",
|
||
"dateType": "1",
|
||
"begin": begin_date,
|
||
"end": end_date,
|
||
"bc_date": begin_date,
|
||
"base_code": base_code,
|
||
"staff_name": "",
|
||
"start": str((page_no - 1) * page_size),
|
||
"sortType": "",
|
||
"sortName": "",
|
||
"pageNo": page_no,
|
||
"pageSize": page_size,
|
||
}
|
||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||
|
||
|
||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date, treecode="cq37du"):
|
||
"""分页抓取指定工号、日期范围内的全部排班记录。"""
|
||
all_rows = []
|
||
page_no = 1
|
||
while True:
|
||
try:
|
||
data = fetch_shift_page(
|
||
session, user_id, base_code, begin_date, end_date,
|
||
treecode, page_no, PAGE_MAX_SIZE)
|
||
except HRSessionExpiredError:
|
||
logger.warning("排班 HR 登录态过期,重建会话后重试")
|
||
session, user_id = _get_hr_context()
|
||
data = fetch_shift_page(
|
||
session, user_id, base_code, begin_date, end_date,
|
||
treecode, page_no, PAGE_MAX_SIZE)
|
||
if data.get("state") != "1":
|
||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||
break
|
||
page_list = data.get("datas", []) or []
|
||
if not page_list:
|
||
logger.info("排班无更多数据")
|
||
break
|
||
all_rows.extend(page_list)
|
||
total_page = data.get("pageCount", 0)
|
||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||
if page_no >= total_page:
|
||
break
|
||
page_no += 1
|
||
time.sleep(0.2)
|
||
return all_rows
|
||
|
||
|
||
def _get_day_shift(shift_rows, date_str):
|
||
"""从排班记录中提取指定日期的班次信息(动态列 "YYYY-MM-DD_bc_name/bc_time/...")。"""
|
||
info = {"bc_name": "", "bc_time": ""}
|
||
for rec in shift_rows:
|
||
name = rec.get(f"{date_str}_bc_name")
|
||
time_ = rec.get(f"{date_str}_bc_time")
|
||
if name or time_:
|
||
info = {
|
||
"bc_name": str(name if name is not None else ""),
|
||
"bc_time": str(time_ if time_ is not None else ""),
|
||
}
|
||
break
|
||
return info
|
||
|
||
|
||
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_code"),
|
||
"请假人员": result.get("staff_name"),
|
||
"所属部门": result.get("dept_org_name"),
|
||
"假期类型": _resolve_vacation_type(result),
|
||
# 日期字段:其他假期一律用 begin_date/end_date(start_time/end_time 可能跨天,
|
||
# 不可用于取日期);仅小时特假等按小时请假需用 start_time/end_time 取当日排班
|
||
"开始日期": result.get("begin_date"),
|
||
"开始时间": result.get("start_time"),
|
||
"开始段": result.get("begin_other_name"),
|
||
"结束日期": result.get("end_date"),
|
||
"结束时间": result.get("end_time"),
|
||
"结束段": result.get("end_other_name"),
|
||
# 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 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 下载附件文件,兼容多附件(逗号分隔多个 fileId)。
|
||
|
||
下载地址: /RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob?fileId=<file_id>
|
||
通过 session(已带登录 Cookie)发起 GET,并按响应头保存为真实文件名。
|
||
多附件时 file 字段为逗号分隔的多个 fileId,逐个下载并返回逗号拼接的路径串。
|
||
返回保存路径(逗号拼接,多个);失败返回 None。
|
||
"""
|
||
if not file_id:
|
||
logger.warning("附件 fileId 为空,跳过下载")
|
||
return None
|
||
|
||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||
saved = []
|
||
for fid in ids:
|
||
path = _download_one(session, fid, save_dir)
|
||
if path:
|
||
saved.append(path)
|
||
if not saved:
|
||
return None
|
||
return ",".join(saved)
|
||
|
||
|
||
def _download_one(session, file_id, save_dir):
|
||
"""
|
||
下载单个附件 fileId,返回本地保存路径;失败返回 None。
|
||
"""
|
||
from urllib.parse import unquote
|
||
if not file_id:
|
||
return None
|
||
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)
|
||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||
counter = 1
|
||
base, ext = os.path.splitext(filename)
|
||
while os.path.exists(path):
|
||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||
counter += 1
|
||
with open(path, "wb") as f:
|
||
f.write(resp.content)
|
||
logger.info("附件已下载: %s", path)
|
||
return path
|
||
|
||
|
||
def _load_shared_oa_cookies():
|
||
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
|
||
if not os.path.exists(COOKIE_FILE):
|
||
return None
|
||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||
cookies = json.load(f)
|
||
return cookies or None
|
||
|
||
|
||
def _ensure_oa_cookies(force=False):
|
||
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入)。
|
||
|
||
本脚本为单文件自包含、不 import 共享登录模块,因此不做自动重登;
|
||
登录态缺失或失效时抛友好的 SystemExit 提示(无堆栈),直接提醒先运行登录流程。
|
||
"""
|
||
if not force and _load_shared_oa_cookies():
|
||
return True
|
||
if not os.path.exists(COOKIE_FILE):
|
||
raise SystemExit(
|
||
"未找到 OA 登录态文件(oa_cookies.json)。\n"
|
||
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
|
||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||
"登录完成后再运行本流程。")
|
||
raise SystemExit(
|
||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||
"请先重新运行「37duOA登录」指令完成登录,"
|
||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||
"重新登录后再运行本流程。")
|
||
|
||
|
||
def is_session_valid(session, subject="请假"):
|
||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||
try:
|
||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||
resp = session.response
|
||
if resp is None or resp.status_code != 200:
|
||
return False
|
||
# 会话有效时返回待办数统计 JSON;失效会被重定向到登录页返回 HTML
|
||
text = resp.text
|
||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||
except Exception as e:
|
||
logger.info("会话已失效,需重新登录: %s", e)
|
||
return False
|
||
|
||
|
||
def build_session(subject):
|
||
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
|
||
|
||
用于查待办、拉表单等纯接口操作;登录态失效时抛友好提示(SystemExit,无堆栈),
|
||
提醒先运行「37duOA登录」指令重新登录,而不是中途崩溃。
|
||
"""
|
||
_ensure_oa_cookies()
|
||
session = SessionPage()
|
||
session.set.timeout(10)
|
||
cookies = _load_shared_oa_cookies()
|
||
if cookies:
|
||
session.set.cookies(cookies)
|
||
if is_session_valid(session, subject):
|
||
return session
|
||
# 登录态已失效:单文件自包含、不做自动重登,直接友好提示先运行登录流程
|
||
_ensure_oa_cookies(force=True) # 恒抛 SystemExit 友好提示
|
||
|
||
|
||
def build_browser(subject):
|
||
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
|
||
_ensure_oa_cookies()
|
||
browser = ChromiumPage()
|
||
cookies = _load_shared_oa_cookies()
|
||
if cookies:
|
||
browser.set.cookies(cookies)
|
||
return browser
|
||
|
||
|
||
# ==================== 登录(共享) ====================
|
||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
|
||
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
|
||
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
|
||
|
||
|
||
# ==================== SSO 解析 ====================
|
||
def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||
|
||
browser.get(sso_url)
|
||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||
logger.info("重定向最终 URL: %s", browser.url)
|
||
|
||
params = parse_qs(urlparse(browser.url).query)
|
||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||
business_key = params.get("businessKey", [None])[0]
|
||
|
||
if not task_id or not business_key:
|
||
raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
|
||
|
||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
||
return {"taskId": task_id, "businessKey": business_key}
|
||
|
||
|
||
# ==================== 审批引擎 ====================
|
||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||
def _fetch_documents(session, subject):
|
||
return get_documents(session, subject=subject)
|
||
|
||
|
||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||
def _fetch_doc_detail(browser, session, doc):
|
||
detail_url = doc.get("detail_url", "")
|
||
if not detail_url:
|
||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||
|
||
sso_params = resolve_sso_params(browser, detail_url)
|
||
task_id = sso_params["taskId"]
|
||
business_key = sso_params["businessKey"]
|
||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||
|
||
refresh_session_cookies(session, browser)
|
||
|
||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||
form_id = extract_form_id(wf_activity_data)
|
||
|
||
form_data = get_business_data(session, business_key, form_id)
|
||
|
||
return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data}
|
||
|
||
|
||
def show_rpa_result_popup(page: ChromiumPage,
|
||
type_: str = "success",
|
||
stay_seconds: float = 2.5):
|
||
"""
|
||
纯图标弹窗(无背景卡片),图标放大居中
|
||
:param page: DrissionPage 页面对象
|
||
:param type_: success / error
|
||
:param stay_seconds: 显示秒数(阻塞等待,保证弹窗完整展示后再继续)
|
||
"""
|
||
# ========== 把两个 SVG 代码粘贴到下面的变量里 ==========
|
||
svg_success = '''<svg 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)
|
||
|
||
|
||
|
||
# ==================== 推送消息生成(不发送,交由消息推送模块) ====================
|
||
# 本脚本不发送任何消息:仅把审批结果拼成文本消息(群消息,只含 text),
|
||
# 经 main() 把纯文本写入影刀全局变量 messages。
|
||
|
||
|
||
def _build_push_messages(texts):
|
||
"""把推送内容列表转成推送消息列表(字典列表)。
|
||
|
||
texts 项可为:
|
||
- 纯文本:包成 {"text": ...}(单条消息)
|
||
- 块格式分组 dict(含 blocks):原样保留,交由钉钉机器人模块内部分批推送
|
||
仅生成群消息({"text": ...},钉钉群机器人 webhook 推送)。
|
||
"""
|
||
messages = []
|
||
for text in texts:
|
||
if isinstance(text, dict) and text.get("blocks") is not None:
|
||
msg = dict(text)
|
||
else:
|
||
msg = {"text": text}
|
||
messages.append(msg)
|
||
return messages
|
||
|
||
|
||
def _format_leave_block(r):
|
||
"""将单条请假审批结果格式化为块格式 Markdown。"""
|
||
info = r.get("leave_info", {}) or {}
|
||
name = info.get("请假人员") or r.get("creator") or "未知"
|
||
vtype = info.get("假期类型") or ""
|
||
lines = [f"**🔹 {name}‑{vtype}**"]
|
||
label_map = [
|
||
("请假人员", "请假人员"),
|
||
("工号", "工号"),
|
||
("所属部门", "所属部门"),
|
||
("假期类型", "假期类型"),
|
||
]
|
||
for key, label in label_map:
|
||
val = info.get(key)
|
||
if val is not None and val != "" and val != "无":
|
||
lines.append(f"> {label}:{val}")
|
||
start = info.get("开始日期")
|
||
start_seg = info.get("开始段")
|
||
if start:
|
||
if start_seg:
|
||
lines.append(f"> 开始日期:{start}|开始段:{start_seg}")
|
||
else:
|
||
lines.append(f"> 开始日期:{start}")
|
||
end = info.get("结束日期")
|
||
end_seg = info.get("结束段")
|
||
if end:
|
||
if end_seg:
|
||
lines.append(f"> 结束日期:{end}|结束段:{end_seg}")
|
||
else:
|
||
lines.append(f"> 结束日期:{end}")
|
||
for key, label in [("请假天数", "请假天数"), ("请假小时", "请假小时"),
|
||
("实际上班天数", "实际上班天数"), ("填报天数", "填报天数")]:
|
||
val = info.get(key)
|
||
if val is not None and val != "" and val != "无":
|
||
lines.append(f"> {label}:{val}")
|
||
note = r.get("note") or r.get("error") or ""
|
||
if note:
|
||
lines.append(f"> 备注:{note}")
|
||
url = r.get("detail_url") or ""
|
||
if url:
|
||
lines.append(f"> 详情页:{url}")
|
||
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
|
||
return '\n\n'.join(lines)
|
||
|
||
|
||
def build_push_summary(results, subject=""):
|
||
"""
|
||
按结果类型生成块格式 Markdown 推送分组。
|
||
|
||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]},
|
||
分批/推送由「37du钉钉群机器人推送」指令内部完成(调用方不关心批次)。
|
||
"""
|
||
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") == "人工复核"]
|
||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||
failed = [r for r in results if r.get("decision") == "失败"]
|
||
if not passed and not rejected and not review and not abnormal and not failed:
|
||
return []
|
||
|
||
messages = []
|
||
|
||
def _push_group(title_prefix, records):
|
||
if not records:
|
||
return
|
||
blocks = [_format_leave_block(r) for r in records]
|
||
messages.append({"title": title_prefix, "blocks": blocks})
|
||
|
||
_push_group(f"【{subject}审批】通过", passed)
|
||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||
_push_group(f"【{subject}审批】需人工复核", review)
|
||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||
_push_group(f"【{subject}审批】处理失败", failed)
|
||
|
||
# 汇总消息:本次审批各类别数量(一条,含 0 的类别)
|
||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||
for label, cnt in [("通过", len(passed)),
|
||
("校验不通过未处理", len(rejected)),
|
||
("需人工复核", len(review)),
|
||
("审批异常", len(abnormal)),
|
||
("处理失败", len(failed))]:
|
||
summary_lines.append(f"- {label}:{cnt} 条")
|
||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||
|
||
return messages
|
||
|
||
|
||
def _find_button(page, selector, timeout=3.0):
|
||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||
try:
|
||
btn = page.ele(selector, timeout=timeout)
|
||
if btn:
|
||
return btn
|
||
except Exception:
|
||
pass
|
||
try:
|
||
frames = page.get_frames()
|
||
except Exception:
|
||
frames = []
|
||
for frame in frames:
|
||
try:
|
||
btn = frame.ele(selector, timeout=1)
|
||
if btn:
|
||
return btn
|
||
except Exception:
|
||
continue
|
||
return None
|
||
|
||
|
||
def submit_approval(page, decision):
|
||
"""
|
||
按校验结论在流程详情页执行真实审批提交。
|
||
|
||
Args:
|
||
page: 停留在详情页的 ChromiumPage
|
||
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
|
||
|
||
Returns:
|
||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||
"""
|
||
if decision not in _APPROVE_BUTTONS:
|
||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||
selector, label = _APPROVE_BUTTONS[decision]
|
||
try:
|
||
btn = _find_button(page, selector)
|
||
if btn is None:
|
||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||
logger.error(msg)
|
||
return {"action": label, "ok": "false", "message": msg}
|
||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||
btn.click()
|
||
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
|
||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||
def _visible(el):
|
||
try:
|
||
return el.states.is_displayed
|
||
except Exception:
|
||
return False
|
||
|
||
confirm = None
|
||
for _ in range(20):
|
||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||
if c1 is not None and _visible(c1):
|
||
confirm = c1
|
||
break
|
||
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
|
||
people = page.ele(".wf-select-people", timeout=0.2)
|
||
if people is not None and _visible(people):
|
||
try:
|
||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||
except Exception:
|
||
c2 = None
|
||
if c2 is not None and _visible(c2):
|
||
confirm = c2
|
||
break
|
||
time.sleep(0.2)
|
||
if confirm is None:
|
||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||
logger.error(msg)
|
||
return {"action": label, "ok": "false", "message": msg}
|
||
confirm.click()
|
||
logger.info("已点击确认框确定按钮")
|
||
time.sleep(1.0)
|
||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||
except Exception as e:
|
||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||
|
||
|
||
def run_flow(subject, validate_doc, generate_report):
|
||
"""请假审批主流程;返回生成的推送消息列表(字典列表,群消息,本脚本不发送)。
|
||
"""
|
||
logger.info("%s审批流程开始", subject)
|
||
|
||
# 登录态失效(待办/表单接口返回登录页)时本脚本不做自动重登(单文件自包含),
|
||
# 直接抛友好提示(SystemExit 无堆栈)提醒先运行「37duOA登录」指令
|
||
for login_attempt in range(2):
|
||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||
session = build_session(subject)
|
||
browser = None
|
||
try:
|
||
docs = _fetch_documents(session, subject)
|
||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||
|
||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||
if not docs:
|
||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"])
|
||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||
return push_messages
|
||
|
||
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
|
||
browser = build_browser(subject)
|
||
refresh_session_cookies(session, browser)
|
||
|
||
# 排班校验依赖 HR 登录态(hr_cookies.json),提前一次性校验:
|
||
# 失效时友好提示先运行「37duHR登录」,避免每张单据校验排班时才逐个失败
|
||
ensure_hr_context()
|
||
|
||
results = []
|
||
for doc in docs:
|
||
try:
|
||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||
result = validate_doc(doc_detail, session)
|
||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行(默认关闭)
|
||
# 与加班共用同一开关(公共审批引擎亦如此),校验不通过未处理暂不自动处理(保留待人工复核),仅对"通过"提交真实审批
|
||
if APPROVE_ENABLED:
|
||
if result.get("decision") == "通过":
|
||
orig_decision = result.get("decision")
|
||
submit = submit_approval(browser, orig_decision)
|
||
result["审批动作"] = submit["action"]
|
||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过,
|
||
# 归为「异常」并附机器结论,交由人工跟进
|
||
if submit["ok"] == "false":
|
||
result["decision"] = "异常"
|
||
result["note"] = (
|
||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||
)
|
||
result["审批结果"] = f"{submit['message']}"
|
||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||
else:
|
||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||
results.append(result)
|
||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||
# 弹出结果提示:通过=绿勾,其余(校验不通过未处理/人工复核/失败)=红叉,停留便于演示
|
||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||
try:
|
||
show_rpa_result_popup(
|
||
browser,
|
||
"success" if result.get("decision") == "通过" else "error",
|
||
2.5,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||
results.append({
|
||
"creator": doc.get("creator", "未知"),
|
||
"title": doc.get("title", "未知"),
|
||
"decision": "失败",
|
||
"error": str(e),
|
||
})
|
||
|
||
report = generate_report(results)
|
||
print("\n" + report)
|
||
|
||
# 生成推送消息文本(本脚本不发送,交由流程/消息推送模块):
|
||
# 按结果类型分多条(通过/校验不通过/人工复核/失败 各一条,含单笔明细)
|
||
texts = build_push_summary(results, subject)
|
||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||
if not texts:
|
||
texts.append(f"暂无待审批的{subject}单据")
|
||
push_messages = _build_push_messages(texts)
|
||
|
||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||
return push_messages
|
||
except OALoginExpiredError as e:
|
||
logger.warning("OA 登录态失效: %s", e)
|
||
# 本脚本为单文件自包含、不自动重登:直接抛友好提示(SystemExit 无堆栈),
|
||
# 提醒先运行「37duOA登录」指令重新登录后再跑本流程
|
||
_ensure_oa_cookies(force=True)
|
||
finally:
|
||
if browser is not None:
|
||
try:
|
||
browser.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# ==================== 请假校验规则 ====================
|
||
# 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可
|
||
HOURLY_LEAVE_TYPES = {
|
||
"小时特假",
|
||
}
|
||
|
||
# Group 1:仅校验排班上班天数与填报天数一致
|
||
LEAVE_TYPE_GROUP_1 = {
|
||
"事假", "调休假", "半天休(仅限人资专用)",
|
||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||
"年度福利假",
|
||
}
|
||
|
||
# Group 2:校验天数一致 + 需上传附件
|
||
LEAVE_TYPE_GROUP_2 = {
|
||
"病假", "特别福利假", "特殊事假", "产假",
|
||
}
|
||
|
||
|
||
def _get_date_range(begin_date, end_date):
|
||
"""从请假表单的 begin_date/end_date 提取日期范围 (start_date, end_date)"""
|
||
start_date = begin_date[:10] if begin_date else None
|
||
end_date = end_date[:10] if end_date else None
|
||
return start_date, end_date
|
||
|
||
|
||
def _get_work_days_count(start_date, end_date, staff_code):
|
||
"""获取请假区间内实际上班天数(非休息日)。
|
||
|
||
数据源为排班接口(rf_p_kq_count_SelectBanci),按工号(base_code)+日期范围查询
|
||
(含未来日期排班),逐日班次存于动态列 "YYYY-MM-DD_bc_name/bc_time/paiban_type"。
|
||
注意:休息与否只能以 bc_name 为准("休息"或空串=休息日):
|
||
返回数据中休息日的 paiban_type 可能为 -2/0,而上班日(bc_name 为具体班次名)
|
||
的 paiban_type 也可能为 0/-3,故不能按 paiban_type 判断。
|
||
"""
|
||
session, user_id = _get_hr_context()
|
||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||
if not rows:
|
||
raise RuntimeError("未能获取到任何排班数据")
|
||
|
||
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")
|
||
info = _get_day_shift(rows, day)
|
||
bc_name = info["bc_name"]
|
||
if bc_name not in ("", "休息"):
|
||
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
|
||
|
||
# 多附件支持:download_attachment 对逗号分隔的多个 fileId 返回逗号拼接的路径串,
|
||
# 拆分后逐个做内容校验,任一命中即通过
|
||
paths = [p for p in path.split(",") if p]
|
||
if not paths:
|
||
return "人工复核", "附件下载失败,需人工核验", None
|
||
|
||
def _first_hit(checker):
|
||
return next((p for p in paths if checker(p)), None)
|
||
|
||
def _kw_hint(p, leave_type):
|
||
"""返回该附件 OCR 命中的关键词列表(顿号拼接),用于备注便于人工判断。"""
|
||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||
return "、".join(hits) if hits else ""
|
||
|
||
if vacation_type == "病假":
|
||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||
if hit:
|
||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||
|
||
if vacation_type == "特别福利假":
|
||
reason = reason or ""
|
||
if "婚" in reason:
|
||
hit = None
|
||
reg_kw = ""
|
||
for p in paths:
|
||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||
if ok:
|
||
hit = p
|
||
reg_kw = "、".join(hits)
|
||
break
|
||
if hit is None:
|
||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||
ok, reg_date = marriage_within_one_year(hit)
|
||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||
if ok:
|
||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||
if "产" in reason or "孕" in reason:
|
||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||
if hit:
|
||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||
if "丧" in reason:
|
||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||
|
||
# 特殊事假 / 产假:有附件即通过
|
||
return "通过", f"附件已上传({len(paths)}份)", 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")
|
||
staff_code = leave_info.get("工号")
|
||
vacation_type = leave_info.get("假期类型")
|
||
begin_date = leave_info.get("开始日期")
|
||
end_date = leave_info.get("结束日期")
|
||
leave_days = leave_info.get("请假天数")
|
||
attachment = leave_info.get("附件")
|
||
# 小时特假为按小时请假:start_time/end_time 为当日实际起止时间(可能 end_date 为空),
|
||
# 用它们取当天日期判断排班;其他假期不受影响,仍用 begin_date/end_date
|
||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||
if is_hourly:
|
||
begin_date = leave_info.get("开始时间")
|
||
end_date = 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
|
||
|
||
if not staff_code:
|
||
result["decision"] = "校验不通过未处理"
|
||
result["note"] = "请假人工号缺失"
|
||
return result
|
||
|
||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||
if not start_date or not end_date:
|
||
result["decision"] = "校验不通过未处理"
|
||
result["note"] = "请假起止日期缺失"
|
||
return result
|
||
|
||
try:
|
||
actual_work_days = _get_work_days_count(start_date, end_date, staff_code)
|
||
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") == "人工复核"]
|
||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||
failed = [r for r in results if r.get("decision") == "失败"]
|
||
|
||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||
if abnormal:
|
||
summary += f",审批异常 {len(abnormal)}"
|
||
if failed:
|
||
summary += f",处理失败 {len(failed)}"
|
||
|
||
lines = [
|
||
"请假审批报告",
|
||
"=" * 60,
|
||
summary,
|
||
"",
|
||
]
|
||
|
||
# ----- 明细清单(所有审批单的完整数据) -----
|
||
lines.append("【审批明细】")
|
||
for i, r in enumerate(results, 1):
|
||
info = r.get("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 ""
|
||
url = r.get("detail_url") or "无"
|
||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||
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 abnormal:
|
||
lines.append("《请假审批异常待人工确认清单》")
|
||
for i, r in enumerate(abnormal, 1):
|
||
url = r.get("detail_url") or "无"
|
||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 原因: {r.get('note') or r.get('error') or ''} | 详情页链接: {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 -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
|
||
|
||
仅生成群消息:写入全局变量 messages 为纯文本,直接交给钉钉群机器人 webhook 推送。
|
||
返回:推送消息列表(字典列表,本脚本不发送);同时把纯文本写入全局变量 messages。
|
||
"""
|
||
push_messages = run_flow(
|
||
subject="请假",
|
||
validate_doc=validate_doc,
|
||
generate_report=generate_report,
|
||
)
|
||
# 写入影刀全局变量 messages(块格式分组列表:{title, blocks}),
|
||
# 供「37du钉钉群机器人推送」指令读取后整体传入 main(),由模块内部分批逐条发送;
|
||
# 本地独立运行时静默跳过
|
||
_set_glv("messages", [m for m in push_messages if str(m.get("text", "") or m.get("blocks", "") or "").strip()])
|
||
return push_messages
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|