refactor: 重构审批流程与依赖,新增社保异动模块
1. 新增社保增减名单模块,支持参保/停保名单导出 2. 重构钉钉推送逻辑,先推摘要再按需推送完整报告 3. 优化假期/加班校验的天数比对逻辑,适配半天请假场景 4. 重写排班HTML解析器,兼容新的页面结构并提取班次全称 5. 重构审批报告生成逻辑,新增全量明细展示 6. 重构影刀脚本的日志与依赖管理,新增UI自动化聚焦输入框 7. 更新依赖包,新增uiautomation库支持
This commit is contained in:
@@ -21,13 +21,10 @@
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import logging.handlers
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
@@ -72,7 +69,6 @@ except ImportError:
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), 'OvertimeApproval')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
_LOG_DIR = os.path.join(_APP_DATA_DIR, 'logs')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
@@ -95,67 +91,23 @@ OT_MIN_HOURS = 1
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
|
||||
|
||||
# ==================== 日志配置 ====================
|
||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
_initialized = False
|
||||
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)
|
||||
|
||||
|
||||
class _ColoredFormatter(logging.Formatter):
|
||||
_colors = {
|
||||
logging.DEBUG: "\033[36m",
|
||||
logging.INFO: "\033[32m",
|
||||
logging.WARNING: "\033[33m",
|
||||
logging.ERROR: "\033[31m",
|
||||
logging.CRITICAL: "\033[35m",
|
||||
}
|
||||
_reset = "\033[0m"
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self._colors.get(record.levelno, "")
|
||||
orig_levelname = record.levelname
|
||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||||
result = super().format(record)
|
||||
record.levelname = orig_levelname
|
||||
return result
|
||||
|
||||
|
||||
def setup_logging(level: int = logging.INFO, log_dir: str = None, log_file: bool = True) -> None:
|
||||
global _initialized
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(level)
|
||||
logger.handlers.clear()
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
if log_file:
|
||||
if log_dir is None:
|
||||
log_dir = _LOG_DIR
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
return logging.getLogger(name)
|
||||
|
||||
|
||||
logger = get_logger("overtime_approval")
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
@@ -187,7 +139,9 @@ def retry(max_attempts: int = 3) -> Callable:
|
||||
logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
|
||||
raise RetryExhaustedError(f"{func.__name__} failed after {max_attempts} attempts") from last_exc
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
@@ -451,11 +405,49 @@ def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT
|
||||
|
||||
# ==================== 排班/打卡解析 ====================
|
||||
def parse_attendance_html(html):
|
||||
pattern = r'<a[^>]*data-temp="([^"]+)"[^>]*>([^<]+)</a>'
|
||||
matches = re.findall(pattern, html)
|
||||
"""
|
||||
解析排班日历 HTML,返回 {日期: 班次} 字典。
|
||||
|
||||
实际 HTML 结构(属性用单引号):
|
||||
<a class='cale_a' title='经营正班A' short_bc_name='经营A'
|
||||
data-temp='2026-08-03' finalState='' onclick="...">正常</a>
|
||||
|
||||
- data-temp: 日期
|
||||
- title: 班次全称(如 经营正班A、职能正班A、休息)
|
||||
- 文本内容: 考勤状态(如 正常、异常、休息)
|
||||
"""
|
||||
if not html:
|
||||
logger.warning("排班 HTML 为空")
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
for date, shift in matches:
|
||||
result[date.strip()] = shift.strip()
|
||||
# 匹配含 data-temp 属性的 <a> 标签,兼容单引号和双引号
|
||||
a_tag_pattern = r"""<a\b[^>]*\bdata-temp=['"]([^'"]+)['"][^>]*>([^<]*)</a>"""
|
||||
|
||||
for match in re.finditer(a_tag_pattern, html, re.DOTALL):
|
||||
date_str = match.group(1).strip()
|
||||
text_content = match.group(2).strip()
|
||||
|
||||
# 从完整标签中提取 title 属性(班次名称),同样兼容单/双引号
|
||||
full_tag = match.group(0)
|
||||
title_match = re.search(r"""\btitle=['"]([^'"]*)['"]""", full_tag)
|
||||
shift_name = title_match.group(1).strip() if title_match else ""
|
||||
|
||||
# 优先使用 title(班次名称),休息日 title='休息'
|
||||
if shift_name:
|
||||
# 考勤异常时附加标注,便于报告展示
|
||||
if text_content and text_content == "异常":
|
||||
result[date_str] = f"{shift_name}(异常)"
|
||||
else:
|
||||
result[date_str] = shift_name
|
||||
else:
|
||||
result[date_str] = text_content
|
||||
|
||||
if not result:
|
||||
logger.warning("排班 HTML 解析失败,未匹配到任何数据。HTML 片段(前500字符): %s", html[:500])
|
||||
else:
|
||||
logger.debug("排班解析: 共 %d 条", len(result))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@@ -692,7 +684,14 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
def _check_browser_deps():
|
||||
"""检查浏览器自动化依赖是否就绪,缺失时给出清晰提示。"""
|
||||
if ChromiumPage is None or SessionPage is None:
|
||||
raise RuntimeError("DrissionPage 未安装,请运行: pip install DrissionPage")
|
||||
|
||||
|
||||
def _get_browser_and_session(subject):
|
||||
_check_browser_deps()
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
@@ -772,29 +771,50 @@ def _is_dingtalk_foreground():
|
||||
|
||||
|
||||
def _activate_dingtalk():
|
||||
"""激活钉钉窗口:Ctrl+D 优先,失败回退 win32。已在前台则跳过(Ctrl+D 是 toggle)。"""
|
||||
"""激活钉钉窗口:Ctrl+D 唤起托盘中的钉钉 -> win32 置前 -> 点击确保焦点。"""
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已在前台,跳过激活")
|
||||
return
|
||||
|
||||
# 先尝试找到已打开的钉钉窗口
|
||||
hwnd = None
|
||||
try:
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.0)
|
||||
if not _is_dingtalk_foreground():
|
||||
raise RuntimeError("Ctrl+D 未能激活")
|
||||
logger.info("通过 Ctrl+D 激活钉钉窗口")
|
||||
except Exception as e:
|
||||
logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e)
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
if hwnd is None:
|
||||
# 钉钉在系统托盘,用 Ctrl+D 全局热键唤起
|
||||
pyautogui.hotkey("ctrl", "d")
|
||||
time.sleep(1.5)
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
except RuntimeError:
|
||||
raise RuntimeError("Ctrl+D 未能唤起钉钉窗口,请确认钉钉已启动并配置了 Ctrl+D 热键")
|
||||
|
||||
# win32 置前台
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
pyautogui.press("alt")
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
time.sleep(1.0)
|
||||
|
||||
# 点击窗口中心确保键盘焦点落在钉钉上(SetForegroundWindow 只切前台,不保证键盘焦点)
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = (rect[1] + rect[3]) // 2
|
||||
pyautogui.click(cx, cy)
|
||||
time.sleep(0.5)
|
||||
|
||||
if _is_dingtalk_foreground():
|
||||
logger.info("钉钉窗口已激活")
|
||||
else:
|
||||
raise RuntimeError("无法激活钉钉窗口,请确认钉钉桌面端已启动并登录")
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""搜索联系人并发送文本:激活 → Ctrl+Shift+F 搜索 → 回车进会话 → 粘贴 → 回车发送。"""
|
||||
"""搜索联系人并发送文本:激活 -> 搜索 -> 进会话 -> 点击输入框聚焦 -> 粘贴 -> 发送。"""
|
||||
_check_dingtalk_deps()
|
||||
_activate_dingtalk()
|
||||
# 搜索联系人
|
||||
@@ -804,9 +824,22 @@ def _send_dingtalk_text(target, text):
|
||||
pyautogui.hotkey("ctrl", "v")
|
||||
time.sleep(1.0)
|
||||
pyautogui.press("enter")
|
||||
time.sleep(1.0)
|
||||
time.sleep(2.5) # 焦点稳定到消息输入框
|
||||
time.sleep(3.5) # 等待会话加载完成
|
||||
logger.info("已搜索并进入会话: %s", target)
|
||||
|
||||
# 进入会话后钉钉可能失焦,重新确认前台并点击消息输入框区域
|
||||
if not _is_dingtalk_foreground():
|
||||
_activate_dingtalk()
|
||||
try:
|
||||
hwnd = _find_dingtalk_hwnd()
|
||||
rect = win32gui.GetWindowRect(hwnd)
|
||||
cx = (rect[0] + rect[2]) // 2
|
||||
cy = rect[1] + int((rect[3] - rect[1]) * 0.85) # 窗口底部 15%,消息输入框区域
|
||||
pyautogui.click(cx, cy)
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 粘贴文本并发送
|
||||
pyperclip.copy(text)
|
||||
pyautogui.hotkey("ctrl", "v")
|
||||
@@ -889,7 +922,6 @@ def push_report(report, subject=""):
|
||||
|
||||
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
@@ -916,9 +948,14 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 推送「通过项汇总」到钉钉(env 控制;无通过项或失败均不影响主流程)
|
||||
# 先推送摘要到钉钉
|
||||
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
|
||||
@@ -1231,13 +1268,49 @@ def _otype(r):
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
生成加班审批报告:汇总行 + 每条明细 + 驳回清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
输出两份清单:
|
||||
《加班审批自动驳回人员明细清单》:员工姓名、加班类型、驳回原因
|
||||
《附件人工复核待办清单》:员工姓名、加班类型、详情页链接(供人工打开查看附件)
|
||||
输出:
|
||||
- 每条审批的完整明细(含加班日期、时长、打卡、排班等)
|
||||
- 《加班审批自动驳回人员明细清单》:员工姓名、加班类型、驳回原因
|
||||
- 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "驳回"]
|
||||
@@ -1255,11 +1328,21 @@ def generate_report(results):
|
||||
"",
|
||||
]
|
||||
|
||||
if passed:
|
||||
names = "、".join(_name(r) for r in passed)
|
||||
lines.append(f"【通过】{len(passed)} 条:{names}")
|
||||
lines.append("")
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 驳回清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批自动驳回人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
@@ -1267,6 +1350,7 @@ def generate_report(results):
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 驳回原因: {reason}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
@@ -1274,6 +1358,7 @@ def generate_report(results):
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
|
||||
Reference in New Issue
Block a user