From 8c97d4838294c062fa58ec08b468bc0c0da6c3fd Mon Sep 17 00:00:00 2001 From: spudding <1115683088@qq.com> Date: Fri, 7 Aug 2026 00:18:49 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E4=BB=A3=E7=A0=81=E7=BB=93=E6=9E=84=E4=B8=8E=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. **依赖与导入路径修正 - 移除所有本地sys.path插入,统一使用绝对包导入 - 修复logger导入路径,统一从app.utils导入 - 重构intelligent_retry.py移除冗余导入 - 统一hrbp各模块的导入路径 2. **项目配置与构建 - 新增pyproject.toml配置文件,规范项目元数据与依赖声明 - 更新requirements.txt新增pyautogui、pywin32、pyperclip依赖 3. **业务模块重构 - 重构请假/加班审批模块的导入路径与内部逻辑 - 重命名审批结果描述(将"不通过"改为"驳回") - 统一代码中的箭头符号(将→改为->) - 新增请假表单解析模块、钉钉通知模块 - 重构加班/请假校验模块的报告生成逻辑,统一报告格式与推送流程 4. **测试与文档 - 新增端到端测试脚本与统一测试运行器 - 完善README.md文档,补充项目结构、功能说明与使用方法 - 新增钉钉消息推送工具文档 - 新增测试用例与辅助工具 5. **其他优化 - 修复common/parser.py中的正则表达式兼容单引号的HTML属性 - 新增session_manager.py移除冗余导入与路径修正 - 新增OA审批报告生成逻辑优化,支持分组统计与详细清单输出 --- .trae/documents/dingtalk-message-sender.md | 119 ++ README.md | 127 ++ aa.md | 51 +- app/service/hrbp/__init__.py | 2 +- app/service/hrbp/oa/common/approval_flow.py | 68 +- app/service/hrbp/oa/common/login.py | 7 +- app/service/hrbp/oa/common/notify.py | 147 ++ app/service/hrbp/oa/common/oa_api.py | 11 +- app/service/hrbp/oa/common/parser.py | 20 +- app/service/hrbp/oa/common/session_manager.py | 15 +- app/service/hrbp/oa/common/sso.py | 8 +- app/service/hrbp/oa/leave/leave_approval.py | 19 +- app/service/hrbp/oa/leave/parser.py | 79 + app/service/hrbp/oa/leave/reporter.py | 75 +- app/service/hrbp/oa/leave/validator.py | 216 ++- .../oa/work_overtime/overtime_approval.py | 19 +- app/service/hrbp/oa/work_overtime/parser.py | 8 +- app/service/hrbp/oa/work_overtime/reporter.py | 82 +- .../hrbp/oa/work_overtime/validator.py | 72 +- app/utils/dingtalk_sender.py | 385 +++++ app/utils/intelligent_retry.py | 8 +- pyproject.toml | 20 + requirements.txt | 5 +- tests/hrbp/_helpers.py | 12 +- tests/hrbp/test_05_leave_validator.py | 502 +++++++ tests/hrbp/test_06_leave_online.py | 158 ++ tests/run_all_tests.py | 132 ++ tests/test.py | 38 + yingdao/leave_approval_yingdao.py | 1170 +++++++++++++++ yingdao/overtime_approval_yingdao.py | 1293 +++++++++++++++++ 30 files changed, 4580 insertions(+), 288 deletions(-) create mode 100644 .trae/documents/dingtalk-message-sender.md create mode 100644 app/service/hrbp/oa/common/notify.py create mode 100644 app/service/hrbp/oa/leave/parser.py create mode 100644 app/utils/dingtalk_sender.py create mode 100644 pyproject.toml create mode 100644 tests/hrbp/test_05_leave_validator.py create mode 100644 tests/hrbp/test_06_leave_online.py create mode 100644 tests/run_all_tests.py create mode 100644 tests/test.py create mode 100644 yingdao/leave_approval_yingdao.py create mode 100644 yingdao/overtime_approval_yingdao.py diff --git a/.trae/documents/dingtalk-message-sender.md b/.trae/documents/dingtalk-message-sender.md new file mode 100644 index 0000000..8f8a790 --- /dev/null +++ b/.trae/documents/dingtalk-message-sender.md @@ -0,0 +1,119 @@ +# 钉钉消息推送工具 实现计划 + +## Context(背景) + +项目目前只有基于 DrissionPage 的 **浏览器** 自动化(OA 审批),通用工具统一放在 `app/utils/`(见 [logger.py](file:///d:/work/code/Process-Automation/app/utils/logger.py)、[intelligent_retry.py](file:///d:/work/code/Process-Automation/app/utils/intelligent_retry.py))。 + +新需求:写一个 **钉钉桌面客户端** 消息推送工具——通过模拟键盘快捷键 + 剪贴板,向指定 **群名/人名** 发送 **文本和文档**。钉钉是桌面客户端(非浏览器),走不了 DrissionPage,需要引入桌面自动化依赖。 + +用户描述的操作链路:`Ctrl+D 激活钉钉 → Ctrl+Shift+F 搜索 → 回车确认 → 粘贴文本/文档 → 回车发送`。 + +## 已确认的决策 + +1. **窗口激活**:两者都支持,默认发 `Ctrl+D` 全局热键;失败自动回退到 win32 按标题查窗口置前。 +2. **文本+文件**:钉钉无法一条消息同时贴文本和文件 → 先发文本、再发文件(两条消息)。 + +## 依赖 + +新增到 [requirements.txt](file:///d:/work/code/Process-Automation/requirements.txt) 和 [pyproject.toml](file:///d:/work/code/Process-Automation/pyproject.toml): + +- `pyautogui` —— 发送键盘快捷键(`hotkey` / `press`) +- `pywin32` —— 窗口查找激活(`win32gui`)+ 文件剪贴板(`win32clipboard` 的 `CF_HDROP`) +- `pyperclip` —— 文本剪贴板(`pyautogui` 会自动带上,显式声明便于理解) + +## 文件改动 + +### 1. 新增 `app/utils/dingtalk_sender.py`(核心) + +遵循项目风格:文件头注释块(`@Module/@FileName/@Author/@CreateTime/@Description/@Version`)、复用 [get_logger](file:///d:/work/code/Process-Automation/app/utils/logger.py) 做日志、复用 [retry](file:///d:/work/code/Process-Automation/app/utils/intelligent_retry.py) 装饰关键步骤。 + +**模块结构**: + +``` +日志 & 常量 +├─ logger = get_logger(__name__) +├─ 默认等待时间常量(搜索结果、发送、激活) + +窗口激活 +├─ _find_dingtalk_hwnd() # win32gui.EnumWindows 按标题"钉钉"查找 +├─ _activate_by_win32() # ShowWindow(SW_RESTORE) + SetForegroundWindow(含 Alt trick 绕过前台锁) +└─ _activate_by_hotkey() # pyautogui.hotkey('ctrl','d') + +剪贴板 +├─ _set_text_to_clipboard(text) # pyperclip.copy +└─ _set_file_to_clipboard(path) # win32clipboard + struct 打包 DROPFILES(CF_HDROP, fWide=1, utf-16-le) + +搜索定位 +└─ _search_and_open(target) # Ctrl+Shift+F → 粘贴 target → 回车 → 等待 + +发送 +├─ _send_text(text) # 剪贴板文本 → Ctrl+V → 回车 +└─ _send_file(path) # 剪贴板文件 → Ctrl+V → 等待预览框 → 回车 + +高层 API +├─ class DingTalkSender # 封装可调参数(各步骤等待时间、激活方式) +│ └─ send(target, text, file_path, is_group) +├─ send_dingtalk_message(target, text, file_path, is_group, ...) # 一次性便捷函数 +├─ send_to_group(group_name, text, file_path) # 群消息快捷封装 +└─ send_to_person(name, text, file_path) # 个人消息快捷封装 +``` + +**主流程 `DingTalkSender.send`**: + +1. 激活钉钉窗口(默认 Ctrl+D,失败回退 win32) +2. `Ctrl+Shift+F` 打开搜索 → 粘贴 `target` → 回车 → 等待 `wait_search` 秒 +3. 若有 `text`:粘贴文本 → 回车发送 → 等待 `wait_send` 秒 +4. 若有 `file_path`:文件入剪贴板 → `Ctrl+V` → 等待 `wait_file_preview` 秒(预览框) → 回车发送 +5. 全程 logger.info 记录每步,失败抛 RuntimeError 含清晰提示 + +**关键实现细节**: + +- **中文输入**:一律走剪贴板 `Ctrl+V`,不用 `pyautogui.write`(不支持中文且受输入法干扰)。 +- **文件剪贴板**:`DROPFILES` 结构(20 字节:`pFiles=20, pt=(0,0), fNC=0, fWide=1`)+ 文件绝对路径 `utf-16-le` 编码 + 双 `\0` 结尾,用 `win32clipboard.SetClipboardData(CF_HDROP, data)`。路径必须 `os.path.abspath` 转绝对路径。 +- **窗口置前 trick**:`SetForegroundWindow` 会被 Windows 前台锁拦截,先 `pyautogui.press('alt')` 或 `win32gui.SendMessage(shell_hwnd, WM_SYSCOMMAND, SC_RESTORE, 0)` 再置前。 +- **搜索回车**:钉钉搜索框回车默认选中第一条结果并进入会话,焦点自动转到消息输入框。 +- **参数校验**:`target` 必填;`text` 和 `file_path` 至少传一个;`file_path` 不存在则提前报错。 +- **`@retry` 包裹**:激活、搜索两个易受环境影响的关键步骤用 `@retry(max_attempts=2)`,发送步骤不重试(避免重复发消息)。 + +**对外 API 签名**: + +```python +def send_dingtalk_message( + target: str, + text: str = "", + file_path: str = "", + is_group: bool = False, + activate_method: str = "auto", # "auto"(默认Ctrl+D回退win32) | "hotkey" | "win32" + wait_search: float = 1.5, + wait_send: float = 1.0, + wait_file_preview: float = 1.5, +) -> None: ... +``` + +### 2. 更新 `requirements.txt` + +追加三行:`pyautogui`、`pywin32`、`pyperclip`。 + +### 3. 更新 `pyproject.toml` `[project].dependencies` + +同步追加同样三项。 + +## 不改动的部分 + +- 不动 `app/utils/__init__.py`(现有内容只是注释头,保持原样,符合项目不集中导出的习惯)。 +- 不动任何 OA 业务模块(钉钉工具独立,暂不接入审批流程回调)。 + +## 验证方式 + +1. **依赖安装**:`.venv\Scripts\python.exe -m pip install pyautogui pywin32 pyperclip` +2. **导入自检**:`.venv\Scripts\python.exe -c "from app.utils.dingtalk_sender import send_to_group, send_to_person"` +3. **剪贴板单测(不发消息)**:调用 `_set_file_to_clipboard(r"C:\test.txt")` 后在资源管理器 `Ctrl+V` 验证能粘贴出文件。 +4. **端到端实测**(需钉钉已登录): + ```python + from app.utils.dingtalk_sender import send_to_person + send_to_person("张三", text="测试消息") # 文本 + send_to_person("张三", file_path=r"C:\report\月报.xlsx") # 文件 + send_to_person("张三", text="请查收", file_path=r"C:\report\月报.xlsx") # 先文本后文件 + ``` + 观察钉钉窗口是否被激活、搜索是否命中目标、消息是否发出。 +5. **日志检查**:`app/logs/app_YYYYMMDD.log` 应有完整步骤记录。 diff --git a/README.md b/README.md index c2db3fa..8e03306 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,129 @@ # Process-Automation +HRBP OA 流程自动化审批系统,实现请假、加班等审批流程的自动化处理。 + +## 项目简介 + +本项目是一个基于 Python 的 HRBP OA 系统自动化审批工具,通过集成 DrissionPage 浏览器自动化框架,实现与 OA 系统的交互,自动完成请假、加班等审批流程的处理。 + +## 项目结构 + +``` +Process-Automation/ +├── app/ # 主应用目录 +│ ├── service/hrbp/oa/ # HRBP OA 服务模块 +│ │ ├── common/ # 公共模块 +│ │ │ ├── approval_flow.py # 审批流程引擎 +│ │ │ ├── config.py # 配置常量 +│ │ │ ├── login.py # 自动登录模块 +│ │ │ ├── session_manager.py # 会话管理 +│ │ │ ├── sso.py # SSO 单点登录 +│ │ │ ├── oa_api.py # OA 系统 API 接口 +│ │ │ └── parser.py # 通用解析模块 +│ │ ├── leave/ # 请假审批模块 +│ │ │ ├── leave_approval.py # 请假审批入口 +│ │ │ └── parser.py # 请假数据解析 +│ │ └── work_overtime/ # 加班审批模块 +│ │ ├── overtime_approval.py # 加班审批入口 +│ │ └── parser.py # 加班数据解析 +│ └── utils/ # 工具模块 +│ ├── intelligent_retry.py # 智能重试装饰器 +│ └── logger.py # 日志模块 +└── yingdao/ # 影刀 RPA 单文件版本 + ├── leave_approval_yingdao.py # 请假审批影刀版 + └── overtime_approval_yingdao.py # 加班审批影刀版 +``` + +## 核心功能 + +### 1. 自动登录 +- 通过 DrissionPage 实现浏览器自动化登录 +- 支持 SSO 单点登录 +- 自动处理登录失败和重试 + +### 2. 审批流程引擎 +- 统一的审批流程处理框架 +- 自动获取待办列表 +- 表单数据解析和校验 +- 审批结果提交 + +### 3. 请假审批 +- 自动获取请假待办 +- 解析请假申请信息 +- 根据规则自动审批 +- 生成审批报告 + +### 4. 加班审批 +- 自动获取加班待办 +- 解析加班申请信息 +- 根据规则自动审批 +- 生成审批报告 + +### 5. 智能重试 +- 指数退避重试机制 +- 随机抖动避免并发冲突 +- 可配置重试次数和延迟 + +### 6. 日志系统 +- 控制台彩色输出 +- 文件持久化日志 +- 支持不同日志级别 + +## 安装依赖 + +```bash +pip install -r requirements.txt +``` + +主要依赖: +- `DrissionPage`: 浏览器自动化框架 +- `python-dotenv`: 环境变量管理 +- `chinese_calendar`: 中国节假日计算 + +## 使用方法 + +### 标准版本 + +1. 配置环境变量(创建 `.env` 文件): +```env +OA_USERNAME=your_username +OA_PASSWORD=your_password +``` + +2. 运行请假审批: +```bash +python app/service/hrbp/oa/leave/leave_approval.py +``` + +3. 运行加班审批: +```bash +python app/service/hrbp/oa/work_overtime/overtime_approval.py +``` + +### 影刀 RPA 版本 + +影刀版本将所有功能合并到单个文件中,便于在影刀 RPA 平台部署: + +```bash +python yingdao/leave_approval_yingdao.py +python yingdao/overtime_approval_yingdao.py +``` + +## 项目特点 + +- **自动化**: 全自动处理审批流程,减少人工操作 +- **智能重试**: 内置智能重试机制,提高稳定性 +- **灵活配置**: 支持环境变量配置,易于部署 +- **双版本支持**: 提供标准版和影刀 RPA 版本 +- **详细日志**: 完整的日志记录,便于问题追踪 + +## 注意事项 + +1. 确保已安装浏览器(Chrome/Edge) +2. 配置正确的 OA 系统账号密码 +3. 首次运行需要手动登录一次以保存会话 +4. 建议在稳定的网络环境下运行 + +## 许可证 + +本项目仅供学习和内部使用,请勿用于商业用途。 diff --git a/aa.md b/aa.md index 44205a0..1ffc6ca 100644 --- a/aa.md +++ b/aa.md @@ -1,47 +1,4 @@ -一、延时加班 -(一)驳回门槛(任一不满足直接驳回) -1. 日期匹配规则:加班开始时间所属日期 = 加班申请日期。当日开始、次日结束的跨天加班,按开始时间判定日期,视为符合要求。 -2. 时长达标规则:以「申请结束时间 - 申请开始时间」计算申请加班总时长,统一执行以下计时标准: - ◦ 不足1小时的,直接驳回; - ◦ 满1小时及以上的,超出1小时的部分按0.5小时为单位向下取整累加,不足0.5小时的部分不计入有效时长。 - ◦ 跨天延时加班的总时长统一套用上述取整规则,不按日期分段计算。 -3. 区间合规校验:申请开始时间 ≥ 当日规定下班时间,且申请结束时间 ≤ 当日实际下班打卡时间;超出该区间的申请直接驳回。 -(二)弹性到岗兑换规则(仅影响结算时长,不影响审批通过与否) -员工可使用当日加班时长等额兑换次日晚到时长,兑换额度、校验规则如下: -1. 弹性额度D计算规则 - ◦ 计算基准:以当日实际下班打卡时间为准,与申请结束时间无关。 - ◦ 触发条件:实际下班打卡时间 < 23:00 时,弹性额度 D=0,不可兑换次日晚到。 - ◦ 额度计算公式:实际下班打卡时间 ≥ 23:00 时,基础兑换额度1小时;超出23:00的部分,按0.5小时为单位向下取整,每满0.5小时累加0.5小时额度。 -公式:D = 1 + FLOOR( (实际下班打卡时间 - 23:00) / 0.5小时 ) × 0.5小时 -2. 次日场景分支校验 -对申请日的次日进行判断,符合以下任一情形的,不触发弹性兑换校验,仅校验当日申请与打卡、请假数据匹配(次日为休息且存在加班申请的,同步核实上班打卡记录): -① 次日排班为“休息”或无排班; -② 次日排班数据获取失败; -③ 次日有请假时段覆盖09:00(任意假期类型)。 -不属于以上情形的正常工作日,按次日实际打卡时间P进行校验: -① 无次日打卡记录:不触发弹性兑换校验,仅校验当日数据; -② P ≤ 09:00:无晚到,无需兑换,直接通过; -③ 09:00 < P ≤ 09:00+D:实际晚到时长 = P - 09:00,不足1小时按1小时计算; -校验规则:申请加班时长 + 实际晚到时长 ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回; -④ P > 09:00+D:可兑换的晚到时长最高按D计算,超出D的晚到部分按考勤迟到规则处理,不影响本次加班审批; -校验规则:申请加班时长 + D ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回。 ---- -二、休息日加班 -(一)适用范围 -1. 周末休息日加班; -2. 除春节外的其余法定节假日加班,统一按本规则执行。 -(二)审批条件(全部满足则通过,任一不满足即驳回) -1. 申请有效:申请加班时长 > 0; -2. 打卡完整:申请对应时段内有完整的上班打卡、下班打卡记录;跨次日0点的连续加班,下班打卡可在次日,只要时段连续、覆盖申请时段,即视为打卡完整; -3. 排班匹配:申请当日排班显示为休息; -4. 时长达标:上下班打卡的自然时间间隔(含午休、用餐等自然时长)满足申报档位要求: - ◦ 申报0.5天:打卡间隔 ≥ 4小时 - ◦ 申报1天:打卡间隔 ≥ 9小时 - ◦ 申报1.5天:打卡间隔 ≥ 13小时 - ◦ 申报2天:打卡间隔 ≥ 18小时 -以此类推,每增加0.5天,对应时长要求增加4小时。 ---- -三、法定假日加班(仅春节法定节假日适用) -1. 基础审批规则与休息日加班完全一致; -2. 额外校验:申请日期必须为春节法定节假日;春节假期内的调休休息日,不适用本规则,按休息日加班规则执行。 ---- \ No newline at end of file +{ + "success": "true", + "caleHtml": "
| 2026 年 8 月 |
总自然时长{total_natural:.1f}h" ) deduction = float(late_hours) @@ -303,8 +284,8 @@ def _validate_delayed( info["弹性扣减(小时)"] = 0 info["有效加班时长(小时)"] = hours info["弹性额度D(小时)"] = d_hours - return "不通过", ( - f"弹性兑换校验不通过:申请加班{hours:g}h + 兑换额度{d_hours:g}h " + return "驳回", ( + f"弹性兑换校验驳回:申请加班{hours:g}h + 兑换额度{d_hours:g}h " f"> 总自然时长{total_natural:.1f}h" ) deduction = float(d_hours) @@ -335,7 +316,7 @@ def _validate_day_ot( require_holiday: bool, ) -> tuple: """ - 休息日/法定假日加班审批(任一条件不满足即不通过): + 休息日/法定假日加班审批(任一条件不满足即驳回): - 排班显示为休息; - 法定假日(仅春节):申请日期必须为春节法定节假日; - 加班时长 > 0; @@ -388,14 +369,14 @@ def _validate_day_ot( info["打卡时间间隔(小时)"] = interval info["申报天数(天)"] = apply_days if reasons: - return "不通过", ";".join(reasons) + return "驳回", ";".join(reasons) return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)" # ---------- 主入口 ---------- def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]: """ - 校验单张加班单据,返回审批决策(通过 / 不通过)。 + 校验单张加班单据,返回审批决策(通过 / 驳回)。 按加班类型分派规则: ot_type=1 延时加班; @@ -435,12 +416,13 @@ def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]: overtime_info, punch_info, session, staff_id, require_holiday=require_holiday ) else: - decision, note = "不通过", f"无法识别加班类型: {ot_type_code}" + decision, note = "驳回", f"无法识别加班类型: {ot_type_code}" return { "title": doc.get("title", ""), "creator": doc.get("creator", ""), "time": doc.get("time", ""), + "detail_url": doc.get("detail_url", ""), "decision": decision, "note": note, "overtime_info": overtime_info, diff --git a/app/utils/dingtalk_sender.py b/app/utils/dingtalk_sender.py new file mode 100644 index 0000000..e0abfba --- /dev/null +++ b/app/utils/dingtalk_sender.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +""" +@Module: utils.dingtalk_sender +@FileName: dingtalk_sender.py +@Author: 小布丁 +@CreateTime: 2026-08-06 +@Description: 钉钉桌面客户端消息推送工具 + 通过模拟键盘快捷键 + 剪贴板,向指定群/联系人发送文本和文件 + 操作链路:Ctrl+D 激活钉钉 → Ctrl+Shift+F 搜索 → 回车确认 → 粘贴文本/文件 → 回车发送 +@Version: 1.0.0 + +依赖安装: + pip install pyautogui pywin32 pyperclip + +使用前提: + 1. Windows 系统 + 2. 钉钉桌面客户端已启动并登录 + 3. (可选)钉钉已配置 Ctrl+D 全局热键用于唤起主面板;未配置时自动回退到 win32 查窗口激活 + +使用示例: + from app.utils.dingtalk_sender import send_to_group, send_to_person + + # 发送文本到群 + send_to_group("测试群", text="你好,这是一条测试消息") + + # 发送文件到个人 + send_to_person("张三", file_path=r"C:\\report\\月报.xlsx") + + # 同时发送文本和文件(先发文本,再发文件,分两条消息) + send_to_person("张三", text="请查收月报", file_path=r"C:\\report\\月报.xlsx") +""" + +import os +import struct +import time + +from app.utils.logger import get_logger, setup_logging +from app.utils.intelligent_retry import retry + +logger = get_logger(__name__) + +# ==================== 第三方依赖(懒加载,缺失时给出清晰提示) ==================== +try: + import pyautogui +except ImportError: + pyautogui = None + +try: + import win32gui + import win32con + import win32clipboard +except ImportError: + win32gui = None + win32con = None + win32clipboard = None + +try: + import pyperclip +except ImportError: + pyperclip = None + + +# ==================== 默认参数 ==================== +DEFAULT_ACTIVATE_METHOD = "auto" # auto | hotkey | win32 +DEFAULT_WAIT_AFTER_ACTIVATE = 1.0 # 激活后等待窗口就绪 +DEFAULT_WAIT_SEARCH_BOX = 0.5 # Ctrl+Shift+F 后等待搜索框打开 +DEFAULT_WAIT_SEARCH_RESULT = 1.0 # 粘贴关键词后等待搜索结果加载 +DEFAULT_WAIT_CONVERSATION_LOAD = 1.0 # 回车后等待会话开始加载 +DEFAULT_WAIT_SEARCH = 2.5 # 会话加载完成、焦点稳定到消息输入框 +DEFAULT_WAIT_SEND = 1.0 # 文本发送后等待 +DEFAULT_WAIT_FILE_PREVIEW = 1.5 # 文件粘贴后预览框加载 + +DINGTALK_WINDOW_KEYWORD = "钉钉" + + +def _check_deps(): + """检查必需的第三方依赖是否就绪,缺失时抛出带安装提示的 RuntimeError。""" + missing = [] + if pyautogui is None: + missing.append("pyautogui") + if win32gui is None: + missing.append("pywin32") + if pyperclip is None: + missing.append("pyperclip") + if missing: + raise RuntimeError( + f"缺少依赖: {', '.join(missing)},请运行: pip install {' '.join(missing)}" + ) + + +# ==================== 窗口激活 ==================== +def _find_dingtalk_hwnd(): + """用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。""" + matches = [] + + def _enum(hwnd, _): + if not win32gui.IsWindowVisible(hwnd): + return + title = win32gui.GetWindowText(hwnd) + if title and DINGTALK_WINDOW_KEYWORD in title: + matches.append((hwnd, title)) + + win32gui.EnumWindows(_enum, None) + if not matches: + raise RuntimeError( + "未找到标题包含「钉钉」的可见窗口,请确认钉钉桌面端已启动并登录" + ) + # 标题最短的通常是主窗口("钉钉"),优先返回 + matches.sort(key=lambda x: len(x[1])) + hwnd, title = matches[0] + logger.debug("定位到钉钉窗口: hwnd=%s, title=%s", hwnd, title) + return hwnd + + +def _activate_by_win32(): + """win32 方式激活:还原最小化 + SetForegroundWindow(含 Alt trick 绕过前台锁)。""" + hwnd = _find_dingtalk_hwnd() + if win32gui.IsIconic(hwnd): + win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) + time.sleep(0.3) + # SetForegroundWindow 受 Windows 前台锁限制,先发一次 Alt 可放开 + pyautogui.press("alt") + win32gui.SetForegroundWindow(hwnd) + time.sleep(DEFAULT_WAIT_AFTER_ACTIVATE) + fg_title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) + if DINGTALK_WINDOW_KEYWORD not in fg_title: + raise RuntimeError(f"win32 激活后前台窗口仍非钉钉: {fg_title!r}") + + +def _activate_by_hotkey(): + """热键方式激活:发送 Ctrl+D 全局热键(需钉钉已配置该热键)。""" + pyautogui.hotkey("ctrl", "d") + time.sleep(DEFAULT_WAIT_AFTER_ACTIVATE) + fg_title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) + if DINGTALK_WINDOW_KEYWORD not in fg_title: + raise RuntimeError( + f"Ctrl+D 未能激活钉钉窗口,当前前台: {fg_title!r};" + "请在钉钉设置中确认主面板快捷键,或改用 activate_method='win32'" + ) + + +def _is_dingtalk_foreground(): + """检查钉钉窗口是否已处于最前。""" + hwnd = win32gui.GetForegroundWindow() + title = win32gui.GetWindowText(hwnd) + return DINGTALK_WINDOW_KEYWORD in title + + +def _activate(method=DEFAULT_ACTIVATE_METHOD): + """按指定方式激活钉钉窗口。auto = 先 Ctrl+D,失败回退 win32。 + + 若钉钉已在前台则直接返回——Ctrl+D 是 toggle 热键,窗口已显示时再按会把它隐藏, + 导致后续发送失败。连续发送时第二次起会命中此分支。 + """ + if _is_dingtalk_foreground(): + logger.info("钉钉窗口已在前台,跳过激活") + return + + if method == "hotkey": + _activate_by_hotkey() + elif method == "win32": + _activate_by_win32() + elif method == "auto": + try: + _activate_by_hotkey() + logger.info("通过 Ctrl+D 激活钉钉窗口") + except Exception as e: + logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e) + _activate_by_win32() + logger.info("通过 win32 激活钉钉窗口") + else: + raise ValueError(f"不支持的 activate_method: {method!r},可选: auto/hotkey/win32") + + +# ==================== 剪贴板 ==================== +def _set_text_to_clipboard(text): + """文本写入剪贴板(pyperclip,自动处理中文)。""" + pyperclip.copy(text) + + +def _set_file_to_clipboard(file_path): + """ + 将文件放入剪贴板(CF_HDROP 格式),供 Ctrl+V 粘贴发送。 + 构造 DROPFILES 结构 + UTF-16-LE 编码的绝对路径(以双 \\0 结尾)。 + """ + abspath = os.path.abspath(file_path) + if not os.path.exists(abspath): + raise FileNotFoundError(f"文件不存在: {abspath}") + + # 文件列表:单路径 + 双 \0 结尾 + files = abspath + "\0\0" + file_bytes = files.encode("utf-16-le") + + # DROPFILES: pFiles=20, pt.x=0, pt.y=0, fNC=0, fWide=1(5 个 unsigned int = 20 字节) + dropfiles = struct.pack("IIIII", 20, 0, 0, 0, 1) + data = dropfiles + file_bytes + + win32clipboard.OpenClipboard() + try: + win32clipboard.EmptyClipboard() + win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, data) + finally: + win32clipboard.CloseClipboard() + logger.debug("文件已放入剪贴板: %s", abspath) + + +# ==================== 搜索 & 发送 ==================== +def _search_and_open(target, wait_search=DEFAULT_WAIT_SEARCH): + """Ctrl+Shift+F 打开搜索 → 粘贴目标名 → 回车进入会话。 + + 时序很关键:搜索结果加载、会话跳转都需要时间,等待不足会把消息内容 + 误贴到搜索框。这里分段等待,确保回车后会话已加载、焦点已落到消息输入框。 + """ + pyautogui.hotkey("ctrl", "shift", "f") + time.sleep(DEFAULT_WAIT_SEARCH_BOX) # 搜索框打开 + _set_text_to_clipboard(target) + pyautogui.hotkey("ctrl", "v") + time.sleep(DEFAULT_WAIT_SEARCH_RESULT) # 搜索结果加载 + pyautogui.press("enter") + time.sleep(DEFAULT_WAIT_CONVERSATION_LOAD) # 会话开始加载 + time.sleep(wait_search) # 焦点稳定到消息输入框 + logger.info("已搜索并进入会话: %s", target) + + +def _send_text(text, wait_send=DEFAULT_WAIT_SEND): + """粘贴文本 → 回车发送。""" + _set_text_to_clipboard(text) + pyautogui.hotkey("ctrl", "v") + time.sleep(0.3) + pyautogui.press("enter") + time.sleep(wait_send) + preview = text[:50] + ("..." if len(text) > 50 else "") + logger.info("文本已发送: %s", preview) + + +def _send_file(file_path, wait_file_preview=DEFAULT_WAIT_FILE_PREVIEW): + """文件入剪贴板 → Ctrl+V → 等待预览框 → 回车发送。""" + _set_file_to_clipboard(file_path) + pyautogui.hotkey("ctrl", "v") + time.sleep(wait_file_preview) + pyautogui.press("enter") + time.sleep(DEFAULT_WAIT_SEND) + logger.info("文件已发送: %s", file_path) + + +# ==================== 高层 API ==================== +class DingTalkSender: + """ + 钉钉消息推送器,封装可调参数。多次发送复用同一实例可保持参数一致。 + + Args: + activate_method: 窗口激活方式,auto(默认Ctrl+D回退win32) | hotkey | win32 + wait_search: 搜索后等待结果加载的秒数 + wait_send: 文本发送后等待的秒数 + wait_file_preview: 文件粘贴后等待预览框的秒数 + """ + + def __init__( + self, + activate_method=DEFAULT_ACTIVATE_METHOD, + wait_search=DEFAULT_WAIT_SEARCH, + wait_send=DEFAULT_WAIT_SEND, + wait_file_preview=DEFAULT_WAIT_FILE_PREVIEW, + ): + _check_deps() + self.activate_method = activate_method + self.wait_search = wait_search + self.wait_send = wait_send + self.wait_file_preview = wait_file_preview + + @retry(max_attempts=2) + def _activate(self): + _activate(self.activate_method) + + @retry(max_attempts=2) + def _search(self, target): + _search_and_open(target, self.wait_search) + + def send(self, target, text="", file_path="", is_group=False): + """ + 向指定目标发送消息。 + + Args: + target: 群名或联系人姓名(用于搜索) + text: 要发送的文本,空字符串表示不发送文本 + file_path: 要发送的文件绝对/相对路径,空字符串表示不发送文件 + is_group: True=群消息,False=个人消息(仅日志区分,搜索流程一致) + + Raises: + ValueError: target 为空,或 text 和 file_path 都为空 + FileNotFoundError: file_path 指向的文件不存在 + RuntimeError: 激活/搜索失败(自动重试 2 次后仍失败) + """ + if not target: + raise ValueError("target 不能为空") + if not text and not file_path: + raise ValueError("text 和 file_path 至少需要传一个") + + kind = "群" if is_group else "个人" + logger.info( + "开始发送 [%s] 目标=%s, 文本=%s, 文件=%s", + kind, target, bool(text), file_path or "无", + ) + + self._activate() + self._search(target) + + if text: + _send_text(text, self.wait_send) + + if file_path: + _send_file(file_path, self.wait_file_preview) + + logger.info("发送完成 [%s]: %s", kind, target) + + +def send_dingtalk_message( + target, + text="", + file_path="", + is_group=False, + activate_method=DEFAULT_ACTIVATE_METHOD, + wait_search=DEFAULT_WAIT_SEARCH, + wait_send=DEFAULT_WAIT_SEND, + wait_file_preview=DEFAULT_WAIT_FILE_PREVIEW, +): + """ + 一次性发送钉钉消息的便捷函数(内部创建 DingTalkSender)。 + + Args: + target: 群名或联系人姓名 + text: 文本内容 + file_path: 文件路径 + is_group: 是否群消息 + activate_method: auto | hotkey | win32 + wait_search: 搜索等待秒数 + wait_send: 文本发送等待秒数 + wait_file_preview: 文件预览框等待秒数 + """ + setup_logging() + sender = DingTalkSender( + activate_method=activate_method, + wait_search=wait_search, + wait_send=wait_send, + wait_file_preview=wait_file_preview, + ) + sender.send(target, text=text, file_path=file_path, is_group=is_group) + + +def send_to_group(group_name, text="", file_path="", **kwargs): + """快捷封装:向指定群发送消息。额外参数透传给 send_dingtalk_message。""" + send_dingtalk_message(group_name, text=text, file_path=file_path, is_group=True, **kwargs) + + +def send_to_person(name, text="", file_path="", **kwargs): + """快捷封装:向指定联系人发送消息。额外参数透传给 send_dingtalk_message。""" + send_dingtalk_message(name, text=text, file_path=file_path, is_group=False, **kwargs) + + +# ==================== 命令行入口(便于手动测试) ==================== +def main(): + import argparse + + parser = argparse.ArgumentParser(description="钉钉消息推送工具") + parser.add_argument("target", help="群名或联系人姓名") + parser.add_argument("-t", "--text", default="", help="文本内容") + parser.add_argument("-f", "--file", default="", help="文件路径") + parser.add_argument("-g", "--group", action="store_true", help="发送到群") + parser.add_argument( + "--activate-method", default=DEFAULT_ACTIVATE_METHOD, + choices=["auto", "hotkey", "win32"], help="窗口激活方式", + ) + args = parser.parse_args() + + send_dingtalk_message( + args.target, + text=args.text, + file_path=args.file, + is_group=args.group, + activate_method=args.activate_method, + ) + + +if __name__ == "__main__": + main() diff --git a/app/utils/intelligent_retry.py b/app/utils/intelligent_retry.py index 1e8172f..be1c603 100644 --- a/app/utils/intelligent_retry.py +++ b/app/utils/intelligent_retry.py @@ -9,15 +9,11 @@ """ import functools -import os import random -import sys import time from typing import Callable -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from logger import get_logger +from app.utils.logger import get_logger logger = get_logger(__name__) @@ -76,4 +72,4 @@ def retry(max_attempts: int = 3) -> Callable: ) from last_exc return wrapper - return decorator \ No newline at end of file + return decorator diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b5481a9 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,20 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "process-automation" +version = "1.0.0" +description = "OA 系统审批自动化工具" +requires-python = ">=3.8" +dependencies = [ + "DrissionPage", + "python-dotenv", + "chinese_calendar", + "pyautogui", + "pywin32", + "pyperclip", +] + +[tool.setuptools.packages.find] +include = ["app*"] diff --git a/requirements.txt b/requirements.txt index d5ca991..29c15c8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,6 @@ DrissionPage python-dotenv -chinese_calendar \ No newline at end of file +chinese_calendar +pyautogui +pywin32 +pyperclip \ No newline at end of file diff --git a/tests/hrbp/_helpers.py b/tests/hrbp/_helpers.py index ca6440e..6e808ce 100644 --- a/tests/hrbp/_helpers.py +++ b/tests/hrbp/_helpers.py @@ -11,17 +11,14 @@ import os import sys -# ---------- 统一 sys.path:项目根 + app/ ---------- +# ---------- 统一 sys.path:项目根 ---------- # 项目根加进来后可用 from app.service.hrbp... 形式 import -# app/ 加进来兼容业务模块内部的 from utils.xxx / from hrbp.oa... 写法 _PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) -_APP_DIR = os.path.join(_PROJECT_ROOT, 'app') -for _p in (_PROJECT_ROOT, _APP_DIR): - if _p not in sys.path: - sys.path.insert(0, _p) +if _PROJECT_ROOT not in sys.path: + sys.path.insert(0, _PROJECT_ROOT) # 初始化日志(测试脚本共用) -from utils.logger import setup_logging, get_logger # noqa: E402 +from app.utils.logger import setup_logging, get_logger # noqa: E402 setup_logging() logger = get_logger("tests.hrbp") @@ -43,7 +40,6 @@ def get_logged_in_session(subject: str = "加班"): from app.service.hrbp.oa.common.session_manager import ( load_saved_session, is_session_valid, - oa_login, # noqa: F401 (保留便于调试时直接登录) init_session_from_page, save_browser_cookies, create_browser_with_saved_cookies, diff --git a/tests/hrbp/test_05_leave_validator.py b/tests/hrbp/test_05_leave_validator.py new file mode 100644 index 0000000..054db0a --- /dev/null +++ b/tests/hrbp/test_05_leave_validator.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +""" +@Module: tests.hrbp.test_05_leave_validator +@FileName: test_05_leave_validator.py +@Author: 小布丁 +@CreateTime: 2026-08-06 +@Description: 连通性测试⑤——请假校验模块(纯逻辑,离线测试,无需登录) +@Version: 1.0.0 +""" +import os +import sys +from unittest.mock import MagicMock, patch + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) + +from tests.hrbp._helpers import logger # noqa: E402 + + +# ---------- 测试数据 ---------- + +SAMPLE_ATTENDANCE_HTML = """ +正常 +正常 +休息 +正常 +正常 +休息 +休息 +正常 +""" + +# 跨月排班 HTML(9月) +SAMPLE_ATTENDANCE_HTML_SEP = """ +正常 +正常 +休息 +""" + + +# ---------- 测试:假期类型编码映射 ---------- + +def test_vacation_type_mapping(): + """测试:假期类型编码→名称映射""" + from app.service.hrbp.oa.leave.parser import _resolve_vacation_type, VACATION_TYPE_MAP + + # 所有编码应能映射到名称 + for code, name in VACATION_TYPE_MAP.items(): + result = _resolve_vacation_type({"vacation_type": code}) + assert result == name, f"编码 {code} 映射失败: 期望 {name}, 实际 {result}" + + # 直接传名称也能识别 + result = _resolve_vacation_type({"vacation_type": "事假"}) + assert result == "事假" + + # 通过 leave_type 字段 + result = _resolve_vacation_type({"leave_type": "04"}) + assert result == "病假" + + # 通过 sub_type 字段 + result = _resolve_vacation_type({"sub_type": "05"}) + assert result == "产假" + + # 空值返回空字符串 + result = _resolve_vacation_type({}) + assert result == "" + + logger.info("[通过] 假期类型编码映射: %d 种类型全部正确", len(VACATION_TYPE_MAP)) + + +# ---------- 测试:请假表单解析 ---------- + +def test_parse_leave_form(): + """测试:请假表单解析""" + from app.service.hrbp.oa.leave.parser import _parse_leave_form + + form_data = { + "staff_id": "test-001", + "staff_name": "张三", + "dept_org_name": "技术部", + "vacation_type": "09", + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-12 18:00", + "leave_days": 3.0, + "leave_hours": 24.0, + "file": "attachment-id-123", + } + info = _parse_leave_form(form_data) + assert info["请假人员ID"] == "test-001" + assert info["请假人员"] == "张三" + assert info["所属部门"] == "技术部" + assert info["假期类型"] == "事假" + assert info["开始时间"] == "2026-08-10 09:00" + assert info["结束时间"] == "2026-08-12 18:00" + assert info["请假天数"] == 3.0 + assert info["请假小时"] == 24.0 + assert info["附件"] == "attachment-id-123" + + # 无附件场景 + form_data_no_file = {**form_data, "file": None} + info2 = _parse_leave_form(form_data_no_file) + assert info2["附件"] is None + + logger.info("[通过] 请假表单解析: 字段提取正确") + + +def test_parse_leave_form_fallback_fields(): + """测试:请假表单解析的降级字段名""" + from app.service.hrbp.oa.leave.parser import _parse_leave_form + + # 使用备用字段名(leave_day / ot_day) + form_data = { + "staff_id": "test-002", + "staff_name": "李四", + "vacation_type": "04", + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-10 18:00", + "leave_day": 1.0, + "leave_hour": 8.0, + } + info = _parse_leave_form(form_data) + assert info["假期类型"] == "病假" + assert info["请假天数"] == 1.0 + assert info["请假小时"] == 8.0 + + # 使用 ot_day / ot_hour 字段 + form_data2 = { + "staff_id": "test-003", + "staff_name": "王五", + "sub_type": "11", + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-10 12:00", + "ot_day": 0.5, + "ot_hour": 4.0, + } + info2 = _parse_leave_form(form_data2) + assert info2["假期类型"] == "调休假" + assert info2["请假天数"] == 0.5 + assert info2["请假小时"] == 4.0 + + logger.info("[通过] 请假表单降级字段: 备用字段名解析正确") + + +# ---------- 测试:日期处理 ---------- + +def test_get_date_range(): + """测试:从起止时间提取日期范围""" + from app.service.hrbp.oa.leave.validator import _get_date_range + + start, end = _get_date_range("2026-08-10 09:00", "2026-08-12 18:00") + assert start == "2026-08-10" + assert end == "2026-08-12" + + # 空值处理 + start2, end2 = _get_date_range(None, "2026-08-12 18:00") + assert start2 is None + assert end2 == "2026-08-12" + + logger.info("[通过] 日期范围提取: start=%s, end=%s", start, end) + + +def test_get_months_in_range(): + """测试:获取日期范围内所有月份(跨月场景)""" + from app.service.hrbp.oa.leave.validator import _get_months_in_range + + # 单月 + months = _get_months_in_range("2026-08-10", "2026-08-20") + assert months == [(2026, 8)], f"单月范围错误: {months}" + + # 跨月 + months = _get_months_in_range("2026-08-10", "2026-10-05") + assert months == [(2026, 8), (2026, 9), (2026, 10)], f"跨月范围错误: {months}" + + # 跨年 + months = _get_months_in_range("2026-12-25", "2027-01-05") + assert months == [(2026, 12), (2027, 1)], f"跨年范围错误: {months}" + + # 同一天 + months = _get_months_in_range("2026-08-10", "2026-08-10") + assert months == [(2026, 8)], f"同天范围错误: {months}" + + logger.info("[通过] 月份范围计算: 单月/跨月/跨年均正确") + + +# ---------- 测试:validate_doc 审批决策逻辑 ---------- + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_group1_pass(mock_get_attendance_html): + """测试:Group 1(事假)天数一致 → 通过""" + from app.service.hrbp.oa.leave.validator import validate_doc + + mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML + + doc = { + "title": "张三的请假申请", + "creator": "张三", + "time": "2026-08-09 10:00", + "formData": { + "staff_id": "test-001", + "staff_name": "张三", + "vacation_type": "09", # 事假 + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-11 18:00", + "leave_days": 2.0, # 填报2天,排班2天(10、11都是正常) + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "通过", f"期望通过,实际: {result['decision']} - {result['note']}" + assert result["leave_info"]["实际上班天数"] == 2 + assert result["leave_info"]["填报天数"] == 2.0 + logger.info("[通过] Group1(事假)天数一致→通过: %s", result["note"]) + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_group1_reject(mock_get_attendance_html): + """测试:Group 1(事假)天数不一致 → 驳回""" + from app.service.hrbp.oa.leave.validator import validate_doc + + mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML + + doc = { + "title": "张三的请假申请", + "creator": "张三", + "time": "2026-08-09 10:00", + "formData": { + "staff_id": "test-001", + "staff_name": "张三", + "vacation_type": "09", # 事假 + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-14 18:00", + "leave_days": 5.0, # 填报5天,但排班中12、15、16休息,实际只有3天上班 + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "不通过", f"期望驳回,实际: {result['decision']} - {result['note']}" + assert "不一致" in result["note"] + assert result["leave_info"]["实际上班天数"] == 4 + assert result["leave_info"]["填报天数"] == 5.0 + logger.info("[通过] Group1(事假)天数不一致→驳回: %s", result["note"]) + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_group2_pass(mock_get_attendance_html): + """测试:Group 2(病假)天数一致 + 有附件 → 通过""" + from app.service.hrbp.oa.leave.validator import validate_doc + + mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML + + doc = { + "title": "李四的病假申请", + "creator": "李四", + "time": "2026-08-09 10:00", + "formData": { + "staff_id": "test-002", + "staff_name": "李四", + "vacation_type": "04", # 病假 + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-11 18:00", + "leave_days": 2.0, # 填报2天,排班2天 + "file": "attachment-id-456", + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "通过", f"期望通过,实际: {result['decision']} - {result['note']}" + assert "附件" in result["note"] + logger.info("[通过] Group2(病假)天数一致+有附件→通过: %s", result["note"]) + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_group2_reject_no_attachment(mock_get_attendance_html): + """测试:Group 2(病假)天数一致但无附件 → 驳回""" + from app.service.hrbp.oa.leave.validator import validate_doc + + mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML + + doc = { + "title": "李四的病假申请", + "creator": "李四", + "time": "2026-08-09 10:00", + "formData": { + "staff_id": "test-002", + "staff_name": "李四", + "vacation_type": "04", # 病假 + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-11 18:00", + "leave_days": 2.0, # 天数一致 + # 无 file 字段 + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "不通过", f"期望驳回,实际: {result['decision']} - {result['note']}" + assert "附件" in result["note"] + logger.info("[通过] Group2(病假)无附件→驳回: %s", result["note"]) + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_group2_reject_both(mock_get_attendance_html): + """测试:Group 2(病假)天数不一致 + 无附件 → 驳回(双原因)""" + from app.service.hrbp.oa.leave.validator import validate_doc + + mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML + + doc = { + "title": "李四的病假申请", + "creator": "李四", + "time": "2026-08-09 10:00", + "formData": { + "staff_id": "test-002", + "staff_name": "李四", + "vacation_type": "04", # 病假 + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-14 18:00", + "leave_days": 5.0, # 填报5天,排班10/11/13/14上班,实际4天,不一致 + # 无附件 + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "不通过" + assert "不一致" in result["note"] + assert "附件" in result["note"] + logger.info("[通过] Group2(病假)天数不一致+无附件→驳回: %s", result["note"]) + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_unknown_type(mock_get_attendance_html): + """测试:未识别的假期类型 → 驳回""" + from app.service.hrbp.oa.leave.validator import validate_doc + + mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML + + doc = { + "title": "未知假期申请", + "creator": "赵六", + "time": "2026-08-09 10:00", + "formData": { + "staff_id": "test-003", + "staff_name": "赵六", + "vacation_type": "99", # 不存在的类型 + "start_time": "2026-08-10 09:00", + "end_time": "2026-08-11 18:00", + "leave_days": 2.0, + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "不通过" + assert "无法识别" in result["note"] + logger.info("[通过] 未识别假期类型→驳回: %s", result["note"]) + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_missing_fields(mock_get_attendance_html): + """测试:缺失必要字段 → 驳回""" + from app.service.hrbp.oa.leave.validator import validate_doc + + session = MagicMock() + + # 缺失假期类型 + doc1 = {"title": "test", "creator": "t", "time": "t", "formData": {"staff_id": "001"}} + r1 = validate_doc(doc1, session) + assert r1["decision"] == "不通过" + assert "假期类型" in r1["note"] + + # 缺失 staff_id + doc2 = {"title": "test", "creator": "t", "time": "t", "formData": {"vacation_type": "09"}} + r2 = validate_doc(doc2, session) + assert r2["decision"] == "不通过" + assert "人员ID" in r2["note"] + + # 缺失起止时间 + doc3 = {"title": "test", "creator": "t", "time": "t", + "formData": {"staff_id": "001", "vacation_type": "09"}} + r3 = validate_doc(doc3, session) + assert r3["decision"] == "不通过" + assert "时间" in r3["note"] + + logger.info("[通过] 缺失必要字段→驳回: 3种场景均正确") + + +@patch("app.service.hrbp.oa.leave.validator.get_attendance_html") +def test_validate_doc_cross_month(mock_get_attendance_html): + """测试:跨月请假排班获取""" + from app.service.hrbp.oa.leave.validator import validate_doc + + # 模拟跨月请求:8月返回部分数据,9月返回部分数据 + def side_effect(session, staff_id, year, month): + if month == 8: + return SAMPLE_ATTENDANCE_HTML + elif month == 9: + return SAMPLE_ATTENDANCE_HTML_SEP + return "" + + mock_get_attendance_html.side_effect = side_effect + + doc = { + "title": "跨月请假", + "creator": "王五", + "time": "2026-08-30 10:00", + "formData": { + "staff_id": "test-004", + "staff_name": "王五", + "vacation_type": "11", # 调休假 + "start_time": "2026-08-30 09:00", + "end_time": "2026-09-02 18:00", + "leave_days": 2.0, # 8月30/31无排班不计数,9月1/2正常 = 2天 + }, + } + session = MagicMock() + result = validate_doc(doc, session) + + assert result["decision"] == "通过", f"期望通过,实际: {result['decision']} - {result['note']}" + assert result["leave_info"]["实际上班天数"] == 2 + logger.info("[通过] 跨月请假排班获取: 实际上班天数=%d, %s", + result["leave_info"]["实际上班天数"], result["note"]) + + +# ---------- 测试:reporter 报告生成 ---------- + +def test_generate_report(): + """测试:报告生成""" + from app.service.hrbp.oa.leave.reporter import generate_report + + results = [ + { + "title": "张三的请假", + "creator": "张三", + "time": "2026-08-09 10:00", + "decision": "通过", + "note": "审批通过", + "leave_info": { + "假期类型": "事假", + "请假人员": "张三", + "所属部门": "技术部", + "开始时间": "2026-08-10 09:00", + "结束时间": "2026-08-11 18:00", + "填报天数": 2.0, + "实际上班天数": 2, + "请假小时": 16.0, + "附件": "file-id", + }, + }, + { + "title": "李四的病假", + "creator": "李四", + "time": "2026-08-09 11:00", + "decision": "不通过", + "note": "未上传附件", + "leave_info": { + "假期类型": "病假", + "请假人员": "李四", + "所属部门": "人事部", + "开始时间": "2026-08-10 09:00", + "结束时间": "2026-08-10 18:00", + "填报天数": 1.0, + "实际上班天数": 1, + "请假小时": 8.0, + "附件": None, + }, + }, + ] + + report = generate_report(results) + assert "请假审批报告" in report + assert "张三" in report + assert "李四" in report + assert "通过" in report + assert "不通过" in report + assert "共 2 单" in report + logger.info("[通过] 报告生成: 包含 %d 条记录", len(results)) + + +# ---------- 主入口 ---------- + +if __name__ == "__main__": + logger.info("========== 测试⑤:请假校验模块(离线) ==========") + + test_vacation_type_mapping() + test_parse_leave_form() + test_parse_leave_form_fallback_fields() + test_get_date_range() + test_get_months_in_range() + test_validate_doc_group1_pass() + test_validate_doc_group1_reject() + test_validate_doc_group2_pass() + test_validate_doc_group2_reject_no_attachment() + test_validate_doc_group2_reject_both() + test_validate_doc_unknown_type() + test_validate_doc_missing_fields() + test_validate_doc_cross_month() + test_generate_report() + + logger.info("========== 测试⑤结束 ==========") \ No newline at end of file diff --git a/tests/hrbp/test_06_leave_online.py b/tests/hrbp/test_06_leave_online.py new file mode 100644 index 0000000..38db669 --- /dev/null +++ b/tests/hrbp/test_06_leave_online.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +""" +@Module: tests.hrbp.test_06_leave_online +@FileName: test_06_leave_online.py +@Author: 小布丁 +@CreateTime: 2026-08-06 +@Description: 连通性测试⑥——请假流程在线测试(需登录) + 测试项: + 1. 请假记录接口(get_leave_records) + 2. 待办列表接口 - 请假主题 + 3. 请假全流程(SSO → 表单 → 校验 → 报告) +@Version: 1.0.0 +""" + +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) + +from tests.hrbp._helpers import get_logged_in_session, pick_first_todo, logger # noqa: E402 + +# 测试用员工(黄俊林),与 test_03 共用 +TEST_STAFF_ID = "572e6cce-7a9f-11ec-b449-000c296f9469" +TEST_DATE = "2026-08-02" + + +def test_leave_records_api(session, staff_id: str): + """测试:请假记录接口连通性 + 自动分页""" + from app.service.hrbp.oa.common.oa_api import get_leave_records + + records = get_leave_records(session, staff_id, "2026-01-01", "2026-12-31", page_size=10) + assert isinstance(records, list), "请假记录格式异常" + logger.info("[通过] 请假记录接口正常,共 %d 条记录", len(records)) + + if records: + r = records[0] + logger.info(" 示例: %s | %s | %s天 | %s~%s", + r.get("vacation_type_name") or r.get("sub_type"), + r.get("leave_businessKey"), + r.get("leave_days"), + r.get("start_time"), + r.get("end_time")) + return records + + +def test_leave_todo_list(session): + """测试:待办列表接口 - 请假主题过滤""" + from app.service.hrbp.oa.common.oa_api import get_documents, fetch_todo_page + + # 单页探活 + page_data = fetch_todo_page(session, subject="请假", page_no=1, page_size=1) + total = int(page_data.get("page", {}).get("totalSize", 0)) + assert total >= 0, "请假待办总数字段异常" + logger.info("[通过] 请假待办接口连通,总数=%d", total) + + # 完整拉取 + docs = get_documents(session, subject="请假") + logger.info("[通过] 请假待办解析完成,共 %d 条", len(docs)) + for d in docs[:3]: + logger.info(" - %s | %s", d.get("creator"), d.get("title")) + return docs + + +def test_leave_attendance_html(session, staff_id: str): + """测试:排班 HTML 接口 + 解析(请假场景)""" + from app.service.hrbp.oa.common.oa_api import get_attendance_html + from app.service.hrbp.oa.common.parser import parse_attendance_html, get_work_days_in_range + + year = int(TEST_DATE[:4]) + month = int(TEST_DATE[5:7]) + html = get_attendance_html(session, staff_id, year, month) + assert html, "排班 HTML 为空" + attendance = parse_attendance_html(html) + assert isinstance(attendance, dict), "排班解析结果非字典" + logger.info("[通过] 请假排班接口正常,当月解析到 %d 天班次", len(attendance)) + + # 验证 get_work_days_in_range 可用 + work_days = get_work_days_in_range(attendance, TEST_DATE, TEST_DATE) + logger.info(" %s 排班: %s", TEST_DATE, attendance.get(TEST_DATE, "无排班")) + return attendance + + +def test_leave_full_flow(session, browser): + """ + 测试:请假全流程(如有待办) + 取第一条请假待办 → SSO 解析 → WfActivity → WorkformEngine → 校验 → 报告 + """ + from app.service.hrbp.oa.common.sso import resolve_sso_params + from app.service.hrbp.oa.common.session_manager import refresh_session_cookies + from app.service.hrbp.oa.common.oa_api import ( + get_wf_activity_by_task_id, + extract_form_id, + get_business_data, + ) + from app.service.hrbp.oa.leave.validator import validate_doc + from app.service.hrbp.oa.leave.reporter import generate_report + + doc = pick_first_todo(session, subject="请假") + if not doc: + logger.warning("无请假待办,跳过全流程测试") + return None + + logger.info("待办: %s | %s", doc.get("creator"), doc.get("title")) + + # 1. SSO 解析 + sso_params = resolve_sso_params(browser, doc["detail_url"]) + assert sso_params.get("taskId"), "taskId 提取失败" + assert sso_params.get("businessKey"), "businessKey 提取失败" + logger.info(" [SSO] taskId=%s, businessKey=%s", sso_params["taskId"], sso_params["businessKey"]) + + # 2. 同步 cookie → WfActivity + refresh_session_cookies(session, browser) + wf_data = get_wf_activity_by_task_id(session, sso_params["taskId"]) + form_id = extract_form_id(wf_data) + assert form_id, "formId 提取失败" + logger.info(" [WfActivity] formId=%s", form_id) + + # 3. WorkformEngine → 表单数据 + form_data = get_business_data(session, sso_params["businessKey"], form_id) + assert isinstance(form_data, dict), "表单数据格式异常" + logger.info(" [WorkformEngine] 员工=%s, 表单字段=%s", + form_data.get("staff_name"), list(form_data.keys())) + + # 4. 校验 + doc_detail = {**doc, "formData": form_data} + result = validate_doc(doc_detail, session) + logger.info(" [校验] decision=%s, note=%s", result["decision"], result["note"]) + + # 5. 报告(单条) + report = generate_report([result]) + assert "请假审批报告" in report + logger.info(" [报告] 生成成功") + + # 输出表单关键字段供后续适配参考 + logger.info(" [表单字段快照]") + for k, v in form_data.items(): + logger.info(" %s: %s", k, v) + + return result + + +if __name__ == "__main__": + logger.info("========== 测试⑥:请假流程在线测试 ==========") + browser, session = get_logged_in_session(subject="请假") + + # 1. 请假记录接口 + test_leave_records_api(session, TEST_STAFF_ID) + + # 2. 请假待办列表 + docs = test_leave_todo_list(session) + + # 3. 请假排班接口 + test_leave_attendance_html(session, TEST_STAFF_ID) + + # 4. 请假全流程(如有待办) + test_leave_full_flow(session, browser) + + logger.info("========== 测试⑥结束 ==========") \ No newline at end of file diff --git a/tests/run_all_tests.py b/tests/run_all_tests.py new file mode 100644 index 0000000..50430dc --- /dev/null +++ b/tests/run_all_tests.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +""" +@Module: tests.run_all_tests +@FileName: run_all_tests.py +@Author: 小布丁 +@CreateTime: 2026-08-06 +@Description: 统一测试运行器 + 用法: + python tests/run_all_tests.py # 仅运行离线测试 + python tests/run_all_tests.py --online # 运行全部测试(含在线) + python tests/run_all_tests.py --list # 列出所有测试 + python tests/run_all_tests.py test_05 # 运行指定测试 +""" + +import argparse +import os +import subprocess +import sys + +# 测试文件列表(按依赖顺序排列) +ALL_TESTS = [ + # 离线测试(无需登录,可独立运行) + ("test_04_parsers", "离线", "解析函数(排班/打卡/加班表单)"), + ("test_05_leave_validator", "离线", "请假校验模块"), + + # 在线测试(需登录态,有依赖顺序) + ("test_01_login_session", "在线", "登录 + 会话 + 待办列表"), + ("test_02_form_detail", "在线", "SSO + WfActivity + WorkformEngine"), + ("test_03_attendance", "在线", "排班 + 打卡明细接口"), + ("test_06_leave_online", "在线", "请假记录 + 全流程"), +] + +# 在线测试需要在离线测试之后运行 +ONLINE_TESTS = [t for t in ALL_TESTS if t[1] == "在线"] +OFFLINE_TESTS = [t for t in ALL_TESTS if t[1] == "离线"] + + +def print_header(text: str): + """打印分隔标题""" + width = 60 + print(f"\n{'=' * width}") + print(f" {text}") + print(f"{'=' * width}") + + +def run_test(test_name: str) -> bool: + """运行单个测试文件,返回是否成功""" + test_file = os.path.join(os.path.dirname(__file__), "hrbp", f"{test_name}.py") + if not os.path.exists(test_file): + print(f" [错误] 测试文件不存在: {test_file}") + return False + + print(f"\n ▶ 运行: {test_name}") + result = subprocess.run( + [sys.executable, test_file], + capture_output=False, + cwd=os.path.join(os.path.dirname(__file__), ".."), + ) + return result.returncode == 0 + + +def list_tests(): + """列出所有测试""" + print_header("可用测试列表") + for name, kind, desc in ALL_TESTS: + print(f" [{kind}] {name:30s} {desc}") + print(f"\n 离线测试: {len(OFFLINE_TESTS)} 个") + print(f" 在线测试: {len(ONLINE_TESTS)} 个") + print(f" 共计: {len(ALL_TESTS)} 个") + + +def run_selected(name: str) -> bool: + """运行指定测试(支持模糊匹配)""" + matched = [t for t in ALL_TESTS if name in t[0]] + if not matched: + print(f"未找到匹配 '{name}' 的测试") + return False + + success = True + for test_name, kind, desc in matched: + print_header(f"运行: {test_name} ({kind} - {desc})") + if not run_test(test_name): + success = False + return success + + +def main(): + parser = argparse.ArgumentParser(description="Process-Automation 统一测试运行器") + parser.add_argument("--online", action="store_true", help="同时运行在线测试(需登录态)") + parser.add_argument("--list", action="store_true", help="列出所有测试") + parser.add_argument("test", nargs="?", help="运行指定测试(支持模糊匹配)") + args = parser.parse_args() + + if args.list: + list_tests() + return + + if args.test: + run_selected(args.test) + return + + # 默认:运行所有离线测试 + all_pass = True + print_header("Process-Automation 测试套件") + print(f" 离线测试: {len(OFFLINE_TESTS)} 个") + if args.online: + print(f" 在线测试: {len(ONLINE_TESTS)} 个") + print() + + for test_name, kind, desc in OFFLINE_TESTS: + print(f"\n [{kind}] {desc}") + if not run_test(test_name): + all_pass = False + + if args.online: + print(f"\n{'─' * 60}") + print(" 开始在线测试...") + for test_name, kind, desc in ONLINE_TESTS: + print(f"\n [{kind}] {desc}") + if not run_test(test_name): + all_pass = False + + print_header("测试结果汇总") + if all_pass: + print(" ✅ 全部通过") + else: + print(" ❌ 存在失败项") + print(f"{'=' * 60}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests/test.py b/tests/test.py new file mode 100644 index 0000000..719ac5b --- /dev/null +++ b/tests/test.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +"""端到端测试:向夏一平(个人)和群聊小布丁分别发送测试文本 + 文件。""" +import os +import sys +import time + +# tests/ 在项目根下一级,需往上一级到项目根才能 import app +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from app.utils.dingtalk_sender import send_to_person, send_to_group + +TEST_TEXT = "【自动化测试】这是一条测试消息,请忽略" +TEST_FILE = r"C:\Users\11156\Desktop\测试.txt" + + +def main(): + print("=" * 50) + print("即将发送,运行期间请勿移动鼠标/键盘") + print("=" * 50) + time.sleep(3) # 留 3 秒切换到钉钉、把手离开鼠标 + + # 1. 个人:夏一平 —— 先文本后文件 + print("\n[1/2] 发送给个人「夏一平」: 文本 + 文件") + send_to_person("夏一平", text=TEST_TEXT, file_path=TEST_FILE) + + time.sleep(2) + + # 2. 群聊:小布丁 —— 先文本后文件 + print("\n[2/2] 发送给群聊「小布丁」: 文本 + 文件") + send_to_group("小布丁", text=TEST_TEXT, file_path=TEST_FILE) + + print("\n" + "=" * 50) + print("全部发送完成,请到钉钉核对") + print("=" * 50) + + +if __name__ == "__main__": + main() diff --git a/yingdao/leave_approval_yingdao.py b/yingdao/leave_approval_yingdao.py new file mode 100644 index 0000000..42b1f8d --- /dev/null +++ b/yingdao/leave_approval_yingdao.py @@ -0,0 +1,1170 @@ +# -*- coding: utf-8 -*- +""" +@FileName: leave_approval_yingdao.py +@Author: 小布丁 +@CreateTime: 2026-08-06 +@Description: 请假审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致 +@Version: 1.0.0 + +依赖安装: + pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip + +环境变量(.env 文件或系统变量): + oa_login_url=登录页URL + oa_target_url_keyword=登录成功后URL关键字 + oa_login_username=用户名 + oa_login_password=密码 + dingtalk_notify_enabled=true|false(默认 false,是否推送审批结果到钉钉) + dingtalk_notify_target=钉钉联系人姓名(如 夏一平) +""" + +# ==================== 标准库导入 ==================== +import functools +import json +import logging +import logging.handlers +import os +import random +import re +import sys +import time +from collections import defaultdict +from datetime import datetime, timedelta +from typing import Any, Callable, Dict, List, Tuple +from urllib.parse import urlencode, urlparse, parse_qs + +# ==================== 第三方库导入 ==================== +try: + from DrissionPage import ChromiumPage, SessionPage +except ImportError: + ChromiumPage = None + SessionPage = None + +try: + from dotenv import load_dotenv +except ImportError: + load_dotenv = lambda *args, **kwargs: None + +# 钉钉推送依赖(懒加载,缺失时给出清晰提示) +try: + import pyautogui +except ImportError: + pyautogui = None + +try: + import win32gui + import win32con + import win32clipboard +except ImportError: + win32gui = None + win32con = None + win32clipboard = None + +try: + import pyperclip +except ImportError: + pyperclip = None + + +# ==================== 路径 & 常量配置 ==================== +# 数据目录固定放在 AppData,不依赖脚本位置,每台电脑都有 +_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), 'LeaveApproval') +_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions') +COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json') +_LOG_DIR = os.path.join(_APP_DATA_DIR, 'logs') + +# ---------- OA 系统 ---------- +BASE_URL = "https://oa.37du.co" +HR_BASE_URL = "https://hr.37du.co" +TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do" +FD_TYPE = "13" +WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc" +WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc" +PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc" +KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc" +LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc" + +# ---------- 分页 ---------- +DEFAULT_PAGE_SIZE = 15 + + +# ==================== 日志配置 ==================== +_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s" +_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s" +_date_fmt = "%Y-%m-%d %H:%M:%S" + +_initialized = False + + +class _ColoredFormatter(logging.Formatter): + _colors = { + logging.DEBUG: "\033[36m", + logging.INFO: "\033[32m", + logging.WARNING: "\033[33m", + logging.ERROR: "\033[31m", + logging.CRITICAL: "\033[35m", + } + _reset = "\033[0m" + + def format(self, record: logging.LogRecord) -> str: + color = self._colors.get(record.levelno, "") + orig_levelname = record.levelname + record.levelname = f"{color}{record.levelname}{self._reset}" + result = super().format(record) + record.levelname = orig_levelname + return result + + +def setup_logging(level: int = logging.INFO, log_dir: str = None, log_file: bool = True) -> None: + global _initialized + if _initialized: + return + + logger = logging.getLogger() + logger.setLevel(level) + logger.handlers.clear() + + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setLevel(level) + console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt)) + logger.addHandler(console_handler) + + if log_file: + if log_dir is None: + log_dir = _LOG_DIR + os.makedirs(log_dir, exist_ok=True) + log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log") + file_handler = logging.handlers.RotatingFileHandler( + log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8" + ) + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt)) + logger.addHandler(file_handler) + + _initialized = True + + +def get_logger(name: str) -> logging.Logger: + return logging.getLogger(name) + + +logger = get_logger("leave_approval") + + +# ==================== 重试装饰器 ==================== +class RetryExhaustedError(Exception): + pass + + +def retry(max_attempts: int = 3) -> Callable: + if max_attempts < 1: + raise ValueError("max_attempts must be >= 1") + + def decorator(func: Callable) -> Callable: + @functools.wraps(func) + def wrapper(*args, **kwargs): + last_exc = None + base_delay = 1.0 + backoff = 2.0 + + for attempt in range(1, max_attempts + 1): + try: + return func(*args, **kwargs) + except Exception as e: + last_exc = e + if attempt >= max_attempts: + logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s", func.__name__, max_attempts, e) + break + delay = base_delay * (backoff ** (attempt - 1)) + delay *= random.uniform(0.5, 1.5) + logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay) + time.sleep(delay) + + raise RetryExhaustedError(f"{func.__name__} failed after {max_attempts} attempts") from last_exc + return wrapper + return decorator + + +# ==================== OA/HR API 接口 ==================== +def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE): + params = { + "method": "list", + "dataType": "todo", + "fdType": FD_TYPE, + "fdCateId": "", + "q.fdSubject": subject, + "orderby": "fdCreateTime", + "ordertype": "down", + "page.pageNo": page_no, + "page.pageSize": page_size, + "__seq": int(time.time() * 1000), + } + url = f"{TODO_LIST_URL}?{urlencode(params)}" + logger.debug("请求第 %d 页: %s", page_no, url) + + session.get(url) + resp = session.response + if not resp: + raise RuntimeError("请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}") + try: + return resp.json() + except Exception: + raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态") + + +def parse_todo_list(data): + datas = data.get("datas", []) + if not datas: + return [] + + docs = [] + for row in datas: + title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {}) + title_raw = title_cell.get("value", "") + match = re.search(r']*>(.*?)', title_raw, re.DOTALL) + title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip() + + creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {}) + creator = creator_cell.get("value", "") + + time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {}) + time_str = time_cell.get("value", "") + + href_cell = next((c for c in row if c["col"] == "tr_href"), {}) + detail_url = href_cell.get("value", "") + if detail_url and not detail_url.startswith(("http://", "https://")): + detail_url = BASE_URL + detail_url + + docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url}) + return docs + + +def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE): + all_docs = [] + data = fetch_todo_page(session, subject, page_no=1, page_size=page_size) + total = int(data.get("page", {}).get("totalSize", 0)) + logger.info("总待办[%s]条数: %d", subject, total) + + docs = parse_todo_list(data) + all_docs.extend(docs) + logger.info("第 1 页获取 %d 条", len(docs)) + + if total > page_size: + total_pages = (total + page_size - 1) // page_size + for p in range(2, total_pages + 1): + data = fetch_todo_page(session, subject, page_no=p, page_size=page_size) + docs = parse_todo_list(data) + all_docs.extend(docs) + logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs)) + + return all_docs + + +def get_wf_activity_by_task_id(session, task_id): + url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId" + data = {"taskId": task_id} + logger.info("获取 formId: taskId=%s", task_id) + + session.post(url, data=data) + resp = session.response + if not resp: + raise RuntimeError("WfActivity 请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") + + logger.debug("WfActivity 返回: %s", json_data) + return json_data + + +def extract_form_id(wf_activity_data): + form_id = ( + wf_activity_data.get("formId") + or wf_activity_data.get("FormId") + or wf_activity_data.get("form_id") + ) + if not form_id: + for key in ("data", "result"): + data_obj = wf_activity_data.get(key, {}) + if isinstance(data_obj, dict): + form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id") + if form_id: + break + + if not form_id: + raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}") + + logger.info("提取到 formId: %s", form_id) + return form_id + + +def get_business_data(session, business_key, form_id): + url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate" + data = {"businessKey": business_key, "formId": form_id} + logger.info("获取请假表单: businessKey=%s, formId=%s", business_key, form_id) + + session.post(url, data=data) + resp = session.response + if not resp: + raise RuntimeError("WorkformEngine 请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") + + result = json_data.get("result") + if json_data.get("state") != "1" or not isinstance(result, dict): + raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}") + + logger.info("WorkformEngine 返回成功") + return result + + +def get_attendance_html(session, staff_id, year, month): + url = f"{PAIBAN_URL}?method=geRenPaibanByMonth" + data = {"type": "2", "staffId": staff_id, "year": str(year), "month": str(month)} + logger.info("获取排班: %s %d-%02d", staff_id, year, month) + + session.post(url, data=data) + resp = session.response + if not resp: + raise RuntimeError("排班请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"排班接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + raise RuntimeError("排班接口返回非 JSON 数据") + + if json_data.get("success") != "true": + raise RuntimeError(f"排班接口返回失败: {json_data}") + + html = json_data.get("caleHtml") + if not html: + raise RuntimeError("排班接口未返回 caleHtml 字段") + return html + + +def get_attendance_records(session, staff_id, start_date, end_date): + params = { + "staff_id": staff_id, + "rootId": "", + "countId": "", + "bc_date": start_date, + "bc_date_end": end_date, + "begin": start_date, + "end": end_date, + } + logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date) + + session.get(KQ_DATA_URL, params=params) + resp = session.response + if not resp: + raise RuntimeError("考勤打卡请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"考勤打卡接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"考勤打卡接口返回非 JSON 数据: {body}") + + records = json_data.get("jsonList", []) + logger.info("打卡明细返回 %d 条", len(records)) + return records + + +def fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"): + data = { + "sub_type": sub_type, + "staff_id": staff_id, + "begin_date": begin_date, + "end_date": end_date, + "start": str((page_no - 1) * page_size), + "pageSize": str(page_size), + "sortType": "", + "sortName": "", + "pageNo": str(page_no), + } + logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no) + + session.post(LEAVE_RECORD_URL, data=data) + resp = session.response + if not resp: + raise RuntimeError("请假记录请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}") + + if json_data.get("success") is not True or json_data.get("code") != 200: + raise RuntimeError(f"请假记录接口返回失败: {json_data}") + + page_info = json_data.get("data") + if not isinstance(page_info, dict): + raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}") + return page_info + + +def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"): + all_records = [] + page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=page_size, sub_type=sub_type) + total = int(page_info.get("total", 0)) + page_total = int(page_info.get("pageCount", 1)) + records = page_info.get("list", []) or [] + all_records.extend(records) + logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records)) + + if page_total > 1: + for p in range(2, page_total + 1): + page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=p, page_size=page_size, sub_type=sub_type) + records = page_info.get("list", []) or [] + all_records.extend(records) + logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records)) + + return all_records + + +# ==================== 排班/打卡解析 ==================== +def parse_attendance_html(html): + # 实际接口返回的 HTML 中 data-temp 用单引号(data-temp='2026-08-04'),需同时兼容单/双引号 + pattern = r']*data-temp=["\']([^"\']+)["\'][^>]*>([^<]+)' + matches = re.findall(pattern, html) + result = {} + for date, shift in matches: + result[date.strip()] = shift.strip() + return result + + +def get_work_days_in_range(attendance_dict, start_date, end_date): + start = datetime.strptime(start_date, "%Y-%m-%d") + end = datetime.strptime(end_date, "%Y-%m-%d") + work_days = [] + current = start + while current <= end: + date_str = current.strftime("%Y-%m-%d") + shift = attendance_dict.get(date_str, "") + if shift != "休息" and shift != "": + work_days.append(date_str) + current += timedelta(days=1) + return work_days + + +def summarize_attendance_records(records): + time_format = "%Y-%m-%d %H:%M:%S" + group_map = defaultdict(list) + + for item in records: + staff_id = item.get("staff_id", "") + bc_day = item.get("bc_date", "") + if not staff_id or not bc_day: + continue + try: + kq_dt = datetime.strptime(item["kq_time"], time_format) + except (KeyError, ValueError): + continue + group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt}) + + summary = [] + for (sid, day), items in group_map.items(): + items.sort(key=lambda x: x["_dt"]) + base = items[0] + row = { + "staff_id": sid, + "staff_name": base.get("staff_name", ""), + "dept_name": base.get("DEPT_ORG_NAME", ""), + "post_name": base.get("POST_ALIAS_NAME", ""), + "attend_date": day, + "first_check_in": items[0]["kq_time"], + "last_check_out": items[-1]["kq_time"] if len(items) > 1 else None, + } + summary.append(row) + return summary + + +# ==================== 请假表单解析 ==================== +VACATION_TYPE_MAP = { + "04": "病假", + "05": "产假", + "09": "事假", + "11": "调休假", + "15": "普通事假", + "17": "特殊事假", + "18": "小时特假", + "19": "普通事假(晚/高峰)", + "20": "普通事假(早/中)", + "22": "半天休(仅限人资专用)", + "23": "特别福利假", + "24": "年度福利假", +} + + +def _first_non_null(result, *keys): + """返回 result 中第一个值非 None 的字段(不能用 or 链:0 / 0.0 / "" 是合法值但为 falsy)。""" + for k in keys: + v = result.get(k) + if v is not None: + return v + return None + + +def _resolve_vacation_type(result): + raw = _first_non_null(result, "vacation_type", "leave_type", "sub_type") + raw = str(raw).strip() if raw is not None else "" + if raw in VACATION_TYPE_MAP: + return VACATION_TYPE_MAP[raw] + return raw + + +def _parse_leave_form(result): + return { + "请假人员ID": result.get("staff_id"), + "请假人员": result.get("staff_name"), + "所属部门": result.get("dept_org_name"), + "假期类型": _resolve_vacation_type(result), + "开始时间": result.get("start_time"), + "结束时间": result.get("end_time"), + # leave_days 可能为 0.0(小时假),不能用 or 链(会被 falsy 短路成 None) + "请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"), + "请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"), + "附件": result.get("file"), + } + + +# ==================== 会话管理 ==================== +def init_session_from_page(browser_page, copy_headers=True): + session = SessionPage() + cookies_dict = browser_page.cookies(all_domains=True) + if cookies_dict: + session.set.cookies(cookies_dict) + logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict)) + else: + logger.warning("未获取到 Cookies,请确认浏览器已登录") + + if copy_headers: + headers = {"User-Agent": browser_page.run_js("return navigator.userAgent;")} + session.set.headers(headers) + logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50]) + + session.set.timeout(10) + return session + + +def refresh_session_cookies(session, browser_page): + cookies = browser_page.cookies(all_domains=True) + if cookies: + session.set.cookies(cookies) + logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies)) + else: + logger.warning("未获取到 Cookies,请确认浏览器登录态") + + +def save_browser_cookies(browser_page, path=COOKIE_FILE): + cookies = browser_page.cookies(all_domains=True) + if not cookies: + logger.warning("未获取到 Cookies,跳过保存") + return + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w', encoding='utf-8') as f: + json.dump(cookies, f, ensure_ascii=False, indent=2) + logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path) + + +def load_cookies(path=COOKIE_FILE): + if not os.path.exists(path): + return None + with open(path, encoding='utf-8') as f: + cookies = json.load(f) + return cookies or None + + +def load_saved_session(path=COOKIE_FILE): + cookies = load_cookies(path) + if not cookies: + return None + session = SessionPage() + session.set.cookies(cookies) + session.set.timeout(10) + return session + + +def create_browser_with_saved_cookies(path=COOKIE_FILE): + browser = ChromiumPage() + cookies = load_cookies(path) + if cookies: + browser.set.cookies(cookies) + return browser + + +def is_session_valid(session, subject="请假"): + try: + fetch_todo_page(session, subject=subject, page_no=1, page_size=1) + return True + except Exception as e: + logger.info("会话已失效,需重新登录: %s", e) + return False + + +# ==================== 登录 ==================== +@retry(max_attempts=3) +def oa_login(username=None, password=None, timeout=10, wait_after_load=2): + load_dotenv() + + login_url = os.getenv('oa_login_url') + if not login_url: + raise RuntimeError("环境变量 oa_login_url 未设置") + target_url_keyword = os.getenv('oa_target_url_keyword') + if not target_url_keyword: + raise RuntimeError("环境变量 oa_target_url_keyword 未设置") + + final_username = username or os.getenv('oa_login_username') + final_password = password or os.getenv('oa_login_password') + if not final_username or not final_password: + raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数") + + page = ChromiumPage() + + try: + page.get(login_url) + time.sleep(wait_after_load) + + username_input = page.ele('tag:input@name=j_username') + if not username_input: + raise RuntimeError("未找到用户名输入框") + username_input.input(final_username) + page.wait(0.5) + + password_input = page.ele('tag:input@name=j_password') + if not password_input: + raise RuntimeError("未找到密码输入框") + password_input.input(final_password) + page.wait(0.5) + + login_button = page.ele('.lui_login_button_div_c') + if not login_button: + raise RuntimeError("未找到登录按钮") + login_button.click() + page.wait(0.5) + + start = time.time() + while time.time() - start < timeout: + if target_url_keyword in page.url: + logger.info("登录成功!当前 URL: %s", page.url) + return page + time.sleep(0.5) + + error_elem = page.ele('.error-msg') or page.ele('.alert-danger') + if error_elem: + logger.warning("登录失败,提示: %s", error_elem.text) + raise RuntimeError(f"登录超时,当前 URL: {page.url}") + + except Exception as e: + page.quit() + raise RuntimeError(f"登录过程出错: {e}") + + +# ==================== SSO 解析 ==================== +def resolve_sso_params(browser, sso_url, wait_timeout=20): + logger.info("解析 SSO 重定向: %s", sso_url) + + browser.get(sso_url) + browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False) + logger.info("重定向最终 URL: %s", browser.url) + + params = parse_qs(urlparse(browser.url).query) + task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0] + business_key = params.get("businessKey", [None])[0] + + if not task_id or not business_key: + raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}") + + logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key) + return {"taskId": task_id, "businessKey": business_key} + + +# ==================== 审批引擎 ==================== +def _get_browser_and_session(subject): + saved_session = load_saved_session() + if saved_session is not None and is_session_valid(saved_session, subject): + logger.info("复用已保存的登录会话,跳过登录") + browser = create_browser_with_saved_cookies() + return browser, saved_session, False + + browser = oa_login() + session = init_session_from_page(browser) + save_browser_cookies(browser) + return browser, session, True + + +@retry(max_attempts=3) +def _fetch_documents(session, subject): + return get_documents(session, subject=subject) + + +@retry(max_attempts=3) +def _fetch_doc_detail(browser, session, doc): + detail_url = doc.get("detail_url", "") + if not detail_url: + raise RuntimeError(f"单据无详情链接: {doc.get('title')}") + + sso_params = resolve_sso_params(browser, detail_url) + task_id = sso_params["taskId"] + business_key = sso_params["businessKey"] + logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key) + + refresh_session_cookies(session, browser) + + wf_activity_data = get_wf_activity_by_task_id(session, task_id) + form_id = extract_form_id(wf_activity_data) + + form_data = get_business_data(session, business_key, form_id) + + return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data} + + +# ==================== 钉钉推送(内联精简版,保持单文件自包含) ==================== +DINGTALK_WINDOW_KEYWORD = "钉钉" + + +def _check_dingtalk_deps(): + """检查钉钉推送必需的第三方依赖,缺失时抛出带安装提示的 RuntimeError。""" + missing = [] + if pyautogui is None: + missing.append("pyautogui") + if win32gui is None: + missing.append("pywin32") + if pyperclip is None: + missing.append("pyperclip") + if missing: + raise RuntimeError(f"缺少依赖: {', '.join(missing)},请运行: pip install {' '.join(missing)}") + + +def _find_dingtalk_hwnd(): + """用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。""" + matches = [] + + def _enum(hwnd, _): + if not win32gui.IsWindowVisible(hwnd): + return + title = win32gui.GetWindowText(hwnd) + if title and DINGTALK_WINDOW_KEYWORD in title: + matches.append((hwnd, title)) + + win32gui.EnumWindows(_enum, None) + if not matches: + raise RuntimeError("未找到标题包含「钉钉」的可见窗口,请确认钉钉桌面端已启动并登录") + matches.sort(key=lambda x: len(x[1])) + return matches[0][0] + + +def _is_dingtalk_foreground(): + title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) + return DINGTALK_WINDOW_KEYWORD in title + + +def _activate_dingtalk(): + """激活钉钉窗口:Ctrl+D 优先,失败回退 win32。已在前台则跳过(Ctrl+D 是 toggle)。""" + if _is_dingtalk_foreground(): + logger.info("钉钉窗口已在前台,跳过激活") + return + try: + pyautogui.hotkey("ctrl", "d") + time.sleep(1.0) + if not _is_dingtalk_foreground(): + raise RuntimeError("Ctrl+D 未能激活") + logger.info("通过 Ctrl+D 激活钉钉窗口") + except Exception as e: + logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e) + hwnd = _find_dingtalk_hwnd() + if win32gui.IsIconic(hwnd): + win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) + time.sleep(0.3) + pyautogui.press("alt") + win32gui.SetForegroundWindow(hwnd) + time.sleep(1.0) + + +def _send_dingtalk_text(target, text): + """搜索联系人并发送文本:激活 → Ctrl+Shift+F 搜索 → 回车进会话 → 粘贴 → 回车发送。""" + _check_dingtalk_deps() + _activate_dingtalk() + # 搜索联系人 + pyautogui.hotkey("ctrl", "shift", "f") + time.sleep(0.5) + pyperclip.copy(target) + pyautogui.hotkey("ctrl", "v") + time.sleep(1.0) + pyautogui.press("enter") + time.sleep(1.0) + time.sleep(2.5) # 焦点稳定到消息输入框 + logger.info("已搜索并进入会话: %s", target) + # 粘贴文本并发送 + pyperclip.copy(text) + pyautogui.hotkey("ctrl", "v") + time.sleep(0.3) + pyautogui.press("enter") + time.sleep(1.0) + logger.info("文本已发送: %s", text[:50] + ("..." if len(text) > 50 else "")) + + +def build_push_summary(results, subject=""): + """ + 根据校验结果生成钉钉推送文字消息(多行)。 + 通过/驳回/人工复核三组均以文字说明推送。无业务结果时返回空串。 + """ + if not results: + return "" + passed = [r for r in results if r.get("decision") == "通过"] + rejected = [r for r in results if r.get("decision") == "驳回"] + review = [r for r in results if r.get("decision") == "人工复核"] + failed = [r for r in results if r.get("decision") == "失败"] + if not passed and not rejected and not review: + return "" + + def _item(r): + info = r.get("leave_info", {}) or {} + title = r.get("title", "") or info.get("请假人员") or "未知" + vtype = info.get("假期类型") or "" + return f"{title}-{vtype}" if vtype else title + + all_pass = (not rejected and not review and not failed) + lines = [] + if all_pass: + lines.append(f"【{subject}审批】本次审批 {len(passed)} 条{subject}申请,") + lines.append("分别是:") + for r in passed: + lines.append(_item(r)) + lines.append("全部通过") + else: + lines.append(f"【{subject}审批】本次共审批 {len(results)} 条{subject}申请。") + if passed: + lines.append(f"通过 {len(passed)} 条,分别是:") + for r in passed: + lines.append(_item(r)) + if rejected: + lines.append(f"自动驳回 {len(rejected)} 条,分别是:") + for r in rejected: + lines.append(_item(r)) + lines.append(f"驳回原因:{r.get('note') or r.get('error') or '未知'}") + if review: + lines.append(f"需人工复核 {len(review)} 条,分别是:") + for r in review: + lines.append(_item(r)) + lines.append(f"详情页:{r.get('detail_url') or '无'}") + if failed: + lines.append(f"另有处理失败 {len(failed)} 条,请查看日志。") + return "\n".join(lines) + + +def push_report(report, subject=""): + """推送审批报告到钉钉联系人(env 控制,失败不影响主流程)。""" + load_dotenv() + if not report or not report.strip(): + logger.info("[%s] 无推送内容(无通过项),跳过钉钉推送", subject) + return False + enabled = os.getenv("dingtalk_notify_enabled", "false").lower() == "true" + if not enabled: + logger.info("[%s] 钉钉推送未开启(dingtalk_notify_enabled!=true),跳过", subject) + return False + target = os.getenv("dingtalk_notify_target", "").strip() + if not target: + logger.warning("[%s] 未配置 dingtalk_notify_target,跳过钉钉推送", subject) + return False + try: + _send_dingtalk_text(target, report) + logger.info("[%s] 审批报告已推送至钉钉: %s", subject, target) + return True + except Exception as e: + logger.warning("[%s] 钉钉推送失败: %s", subject, e) + return False + + +def run_flow(subject, validate_doc, generate_report): + setup_logging() + logger.info("%s审批流程开始", subject) + + browser, session, _ = _get_browser_and_session(subject) + + docs = _fetch_documents(session, subject) + logger.info("共获取%s待办 %d 条", subject, len(docs)) + + results = [] + for doc in docs: + try: + doc_detail = _fetch_doc_detail(browser, session, doc) + result = validate_doc(doc_detail, session) + results.append(result) + logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"]) + except Exception as e: + logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e)) + results.append({ + "creator": doc.get("creator", "未知"), + "title": doc.get("title", "未知"), + "decision": "失败", + "error": str(e), + }) + + report = generate_report(results) + print("\n" + report) + + # 推送「通过项汇总」到钉钉(env 控制;无通过项或失败均不影响主流程) + push_report(build_push_summary(results, subject), subject) + + save_browser_cookies(browser) + logger.info("%s审批流程结束,共处理 %d 条", subject, len(results)) + return report + + +# ==================== 请假校验规则 ==================== +# 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可 +HOURLY_LEAVE_TYPES = { + "小时特假", +} + +# Group 1:仅校验排班上班天数与填报天数一致 +LEAVE_TYPE_GROUP_1 = { + "事假", "调休假", "半天休(仅限人资专用)", + "普通事假", "普通事假(早/中)", "普通事假(晚/高峰)", + "年度福利假", +} + +# Group 2:校验天数一致 + 需上传附件 +LEAVE_TYPE_GROUP_2 = { + "病假", "特别福利假", "特殊事假", "产假", +} + + +def _get_date_range(start_time, end_time): + """从请假起止时间中提取日期范围 (start_date, end_date)""" + start_date = start_time[:10] if start_time else None + end_date = end_time[:10] if end_time else None + return start_date, end_date + + +def _get_months_in_range(start_date, end_date): + """获取日期范围内所有 (year, month) 元组列表,跨月按月份分段""" + start = datetime.strptime(start_date, "%Y-%m-%d") + end = datetime.strptime(end_date, "%Y-%m-%d") + months = [] + current = start.replace(day=1) + while current <= end: + months.append((current.year, current.month)) + if current.month == 12: + current = current.replace(year=current.year + 1, month=1) + else: + current = current.replace(month=current.month + 1) + return months + + +def _get_work_days_count(session, staff_id, start_date, end_date): + """获取请假区间内实际上班天数(非休息日),跨月按月份分段请求""" + months = _get_months_in_range(start_date, end_date) + attendance = {} + for year, month in months: + try: + html = get_attendance_html(session, staff_id, year, month) + monthly = parse_attendance_html(html) + attendance.update(monthly) + logger.info("排班数据已获取: %d-%02d, 共 %d 天", year, month, len(monthly)) + except Exception as e: + logger.warning("获取排班失败(%d-%02d): %s", year, month, str(e)) + + if not attendance: + raise RuntimeError("未能获取到任何排班数据") + + work_days = get_work_days_in_range(attendance, start_date, end_date) + logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days)) + return len(work_days) + + +def validate_doc(doc, session): + """ + 校验单张请假单据,返回审批决策。 + + Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过 + Group 2(病假/产假等):天数一致 + 有附件 -> 通过 + """ + form_data = doc.get("formData", {}) or {} + leave_info = _parse_leave_form(form_data) + + staff_id = leave_info.get("请假人员ID") + vacation_type = leave_info.get("假期类型") + start_time = leave_info.get("开始时间") + end_time = leave_info.get("结束时间") + leave_days = leave_info.get("请假天数") + attachment = leave_info.get("附件") + + result = { + "title": doc.get("title", ""), + "creator": doc.get("creator", ""), + "time": doc.get("time", ""), + "detail_url": doc.get("detail_url", ""), + "decision": "通过", + "note": "", + "leave_info": leave_info, + } + + if not vacation_type: + result["decision"] = "驳回" + result["note"] = "无法识别假期类型" + return result + + if not staff_id: + result["decision"] = "驳回" + result["note"] = "请假人员ID缺失" + return result + + start_date, end_date = _get_date_range(start_time, end_time) + if not start_date or not end_date: + result["decision"] = "驳回" + result["note"] = "请假起止时间缺失" + return result + + try: + actual_work_days = _get_work_days_count(session, staff_id, start_date, end_date) + except Exception as e: + logger.warning("计算上班天数失败: %s", str(e)) + result["decision"] = "驳回" + result["note"] = f"获取排班数据失败: {e}" + return result + + try: + fill_days = float(leave_days) if leave_days else 0 + except (TypeError, ValueError): + fill_days = 0 + + leave_info["实际上班天数"] = actual_work_days + leave_info["填报天数"] = fill_days + + days_mismatch = abs(actual_work_days - fill_days) > 0.01 + + if vacation_type in HOURLY_LEAVE_TYPES: + # 按小时请假(如小时特假):不比对天数,只要请假当天落在排班上班日即可 + leave_hours = leave_info.get("请假小时") + if actual_work_days < 1: + result["decision"] = "驳回" + result["note"] = f"请假当天非排班上班日(实际上班天数: {actual_work_days})" + else: + result["decision"] = "通过" + result["note"] = ( + f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours}," + f"当天为上班日)" + ) + + elif vacation_type in LEAVE_TYPE_GROUP_1: + if days_mismatch: + result["decision"] = "驳回" + result["note"] = f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致" + else: + result["decision"] = "通过" + result["note"] = ( + f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days}," + f"填报天数: {fill_days})" + ) + + elif vacation_type in LEAVE_TYPE_GROUP_2: + # 需附件的假期:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);否则驳回 + reasons = [] + if days_mismatch: + reasons.append(f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致") + if not attachment: + reasons.append("未上传附件") + + if reasons: + result["decision"] = "驳回" + result["note"] = ";".join(reasons) + else: + result["decision"] = "人工复核" + result["note"] = ( + f"需人工复核附件(假期类型: {vacation_type},上班天数: {actual_work_days}," + f"填报天数: {fill_days},附件: 已上传)" + ) + else: + result["decision"] = "驳回" + result["note"] = f"无法识别的假期类型: {vacation_type}" + + return result + + +# ==================== 报告生成 ==================== +def _name(r): + info = r.get("leave_info", {}) or {} + return info.get("请假人员") or r.get("creator") or "未知" + + +def _vtype(r): + info = r.get("leave_info", {}) or {} + return info.get("假期类型") or "未知" + + +def generate_report(results): + """生成请假审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。""" + passed = [r for r in results if r.get("decision") == "通过"] + rejected = [r for r in results if r.get("decision") == "驳回"] + review = [r for r in results if r.get("decision") == "人工复核"] + failed = [r for r in results if r.get("decision") == "失败"] + + summary = f"共 {len(results)} 单:通过 {len(passed)},驳回 {len(rejected)},人工复核 {len(review)}" + if failed: + summary += f",处理失败 {len(failed)}" + + lines = [ + "请假审批报告", + "=" * 60, + summary, + "", + ] + + if passed: + names = "、".join(_name(r) for r in passed) + lines.append(f"【通过】{len(passed)} 条:{names}") + lines.append("") + + if rejected: + lines.append("《请假审批自动驳回人员明细清单》") + for i, r in enumerate(rejected, 1): + reason = r.get("note") or r.get("error") or "" + lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 驳回原因: {reason}") + lines.append("") + + if review: + lines.append("《附件人工复核待办清单》") + for i, r in enumerate(review, 1): + url = r.get("detail_url") or "无" + lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url}") + lines.append("") + + if failed: + lines.append("【处理失败】") + for i, r in enumerate(failed, 1): + lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}") + lines.append("") + + return "\n".join(lines) + + +# ==================== 主入口 ==================== +def main(): + """请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告""" + run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report) + + +if __name__ == "__main__": + main() diff --git a/yingdao/overtime_approval_yingdao.py b/yingdao/overtime_approval_yingdao.py new file mode 100644 index 0000000..2f98195 --- /dev/null +++ b/yingdao/overtime_approval_yingdao.py @@ -0,0 +1,1293 @@ +# -*- coding: utf-8 -*- +""" +@FileName: overtime_approval_yingdao.py +@Author: 小布丁 +@CreateTime: 2026-08-06 +@Description: 加班审批流程(影刀单文件版)- 合并自原项目 13 个模块 +@Version: 1.0.0 + +依赖安装: + pip install DrissionPage python-dotenv chinese_calendar pyautogui pywin32 pyperclip + +环境变量(.env 文件或系统变量): + oa_login_url=登录页URL + oa_target_url_keyword=登录成功后URL关键字 + oa_login_username=用户名 + oa_login_password=密码 + dingtalk_notify_enabled=true|false(默认 false,是否推送审批结果到钉钉) + dingtalk_notify_target=钉钉联系人姓名(如 夏一平) +""" + +# ==================== 标准库导入 ==================== +import functools +import json +import 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 +from typing import Any, Callable, Dict, List, Optional +from urllib.parse import urlencode, urlparse, parse_qs + +# ==================== 第三方库导入 ==================== +try: + from DrissionPage import ChromiumPage, SessionPage +except ImportError: + ChromiumPage = None + SessionPage = None + +try: + from dotenv import load_dotenv +except ImportError: + load_dotenv = lambda *args, **kwargs: None + +# 钉钉推送依赖(懒加载,缺失时给出清晰提示) +try: + import pyautogui +except ImportError: + pyautogui = None + +try: + import win32gui + import win32con + import win32clipboard +except ImportError: + win32gui = None + win32con = None + win32clipboard = None + +try: + import pyperclip +except ImportError: + pyperclip = None + + +# ==================== 路径 & 常量配置 ==================== +# 数据目录固定放在 AppData,不依赖脚本位置,每台电脑都有 +_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '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" +HR_BASE_URL = "https://hr.37du.co" +TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do" +FD_TYPE = "13" +WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc" +WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc" +PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc" +KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc" +LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc" + +# ---------- 加班审批规则常量 ---------- +WORK_START_TIME = "09:00" +WORK_END_TIME = "18:00" +FLEX_TRIGGER_TIME = "23:00" +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" + +_initialized = False + + +class _ColoredFormatter(logging.Formatter): + _colors = { + logging.DEBUG: "\033[36m", + logging.INFO: "\033[32m", + logging.WARNING: "\033[33m", + logging.ERROR: "\033[31m", + logging.CRITICAL: "\033[35m", + } + _reset = "\033[0m" + + def format(self, record: logging.LogRecord) -> str: + color = self._colors.get(record.levelno, "") + orig_levelname = record.levelname + record.levelname = f"{color}{record.levelname}{self._reset}" + result = super().format(record) + record.levelname = orig_levelname + return result + + +def setup_logging(level: int = logging.INFO, log_dir: str = None, log_file: bool = True) -> None: + global _initialized + if _initialized: + return + + logger = logging.getLogger() + logger.setLevel(level) + logger.handlers.clear() + + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setLevel(level) + console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt)) + logger.addHandler(console_handler) + + if log_file: + if log_dir is None: + log_dir = _LOG_DIR + os.makedirs(log_dir, exist_ok=True) + log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log") + file_handler = logging.handlers.RotatingFileHandler( + log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8" + ) + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt)) + logger.addHandler(file_handler) + + _initialized = True + + +def get_logger(name: str) -> logging.Logger: + return logging.getLogger(name) + + +logger = get_logger("overtime_approval") + + +# ==================== 重试装饰器 ==================== +class RetryExhaustedError(Exception): + pass + + +def retry(max_attempts: int = 3) -> Callable: + if max_attempts < 1: + raise ValueError("max_attempts must be >= 1") + + def decorator(func: Callable) -> Callable: + @functools.wraps(func) + def wrapper(*args, **kwargs): + last_exc = None + base_delay = 1.0 + backoff = 2.0 + + for attempt in range(1, max_attempts + 1): + try: + return func(*args, **kwargs) + except Exception as e: + last_exc = e + if attempt >= max_attempts: + logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s", func.__name__, max_attempts, e) + break + delay = base_delay * (backoff ** (attempt - 1)) + delay *= random.uniform(0.5, 1.5) + logger.warning("%s 第 %d 次执行失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay) + time.sleep(delay) + + raise RetryExhaustedError(f"{func.__name__} failed after {max_attempts} attempts") from last_exc + return wrapper + return decorator + + +# ==================== OA/HR API 接口 ==================== +def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE): + params = { + "method": "list", + "dataType": "todo", + "fdType": FD_TYPE, + "fdCateId": "", + "q.fdSubject": subject, + "orderby": "fdCreateTime", + "ordertype": "down", + "page.pageNo": page_no, + "page.pageSize": page_size, + "__seq": int(time.time() * 1000), + } + url = f"{TODO_LIST_URL}?{urlencode(params)}" + logger.debug("请求第 %d 页: %s", page_no, url) + + session.get(url) + resp = session.response + if not resp: + raise RuntimeError("请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}") + try: + return resp.json() + except Exception: + raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态") + + +def parse_todo_list(data): + datas = data.get("datas", []) + if not datas: + return [] + + docs = [] + for row in datas: + title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {}) + title_raw = title_cell.get("value", "") + match = re.search(r']*>(.*?)', title_raw, re.DOTALL) + title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip() + + creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {}) + creator = creator_cell.get("value", "") + + time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {}) + time_str = time_cell.get("value", "") + + href_cell = next((c for c in row if c["col"] == "tr_href"), {}) + detail_url = href_cell.get("value", "") + if detail_url and not detail_url.startswith(("http://", "https://")): + detail_url = BASE_URL + detail_url + + docs.append({"title": title, "creator": creator, "time": time_str, "detail_url": detail_url}) + return docs + + +def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE): + all_docs = [] + data = fetch_todo_page(session, subject, page_no=1, page_size=page_size) + total = int(data.get("page", {}).get("totalSize", 0)) + logger.info("总待办[%s]条数: %d", subject, total) + + docs = parse_todo_list(data) + all_docs.extend(docs) + logger.info("第 1 页获取 %d 条", len(docs)) + + if total > page_size: + total_pages = (total + page_size - 1) // page_size + for p in range(2, total_pages + 1): + data = fetch_todo_page(session, subject, page_no=p, page_size=page_size) + docs = parse_todo_list(data) + all_docs.extend(docs) + logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs)) + + return all_docs + + +def get_wf_activity_by_task_id(session, task_id): + url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId" + data = {"taskId": task_id} + logger.info("获取 formId: taskId=%s", task_id) + + session.post(url, data=data) + resp = session.response + if not resp: + raise RuntimeError("WfActivity 请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") + + logger.debug("WfActivity 返回: %s", json_data) + return json_data + + +def extract_form_id(wf_activity_data): + form_id = ( + wf_activity_data.get("formId") + or wf_activity_data.get("FormId") + or wf_activity_data.get("form_id") + ) + if not form_id: + for key in ("data", "result"): + data_obj = wf_activity_data.get(key, {}) + if isinstance(data_obj, dict): + form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id") + if form_id: + break + + if not form_id: + raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}") + + logger.info("提取到 formId: %s", form_id) + return form_id + + +def get_business_data(session, business_key, form_id): + url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate" + data = {"businessKey": business_key, "formId": form_id} + logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id) + + session.post(url, data=data) + resp = session.response + if not resp: + raise RuntimeError("WorkformEngine 请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}") + + result = json_data.get("result") + if json_data.get("state") != "1" or not isinstance(result, dict): + raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}") + + logger.info("WorkformEngine 返回成功") + return result + + +def get_attendance_html(session, staff_id, year, month): + url = f"{PAIBAN_URL}?method=geRenPaibanByMonth" + data = {"type": "2", "staffId": staff_id, "year": str(year), "month": str(month)} + logger.info("获取排班: %s %d-%02d", staff_id, year, month) + + session.post(url, data=data) + resp = session.response + if not resp: + raise RuntimeError("排班请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"排班接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + raise RuntimeError("排班接口返回非 JSON 数据") + + if json_data.get("success") != "true": + raise RuntimeError(f"排班接口返回失败: {json_data}") + + html = json_data.get("caleHtml") + if not html: + raise RuntimeError("排班接口未返回 caleHtml 字段") + return html + + +def get_attendance_records(session, staff_id, start_date, end_date): + params = { + "staff_id": staff_id, + "rootId": "", + "countId": "", + "bc_date": start_date, + "bc_date_end": end_date, + "begin": start_date, + "end": end_date, + } + logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date) + + session.get(KQ_DATA_URL, params=params) + resp = session.response + if not resp: + raise RuntimeError("考勤打卡请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"考勤打卡接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"考勤打卡接口返回非 JSON 数据: {body}") + + records = json_data.get("jsonList", []) + logger.info("打卡明细返回 %d 条", len(records)) + return records + + +def fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"): + data = { + "sub_type": sub_type, + "staff_id": staff_id, + "begin_date": begin_date, + "end_date": end_date, + "start": str((page_no - 1) * page_size), + "pageSize": str(page_size), + "sortType": "", + "sortName": "", + "pageNo": str(page_no), + } + logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no) + + session.post(LEAVE_RECORD_URL, data=data) + resp = session.response + if not resp: + raise RuntimeError("请假记录请求失败,未获取到响应") + if resp.status_code != 200: + raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}") + + try: + json_data = resp.json() + except Exception: + body = (resp.text or "")[:200] + raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}") + + if json_data.get("success") is not True or json_data.get("code") != 200: + raise RuntimeError(f"请假记录接口返回失败: {json_data}") + + page_info = json_data.get("data") + if not isinstance(page_info, dict): + raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}") + return page_info + + +def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"): + all_records = [] + page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=page_size, sub_type=sub_type) + total = int(page_info.get("total", 0)) + page_total = int(page_info.get("pageCount", 1)) + records = page_info.get("list", []) or [] + all_records.extend(records) + logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records)) + + if page_total > 1: + for p in range(2, page_total + 1): + page_info = fetch_leave_record_page(session, staff_id, begin_date, end_date, page_no=p, page_size=page_size, sub_type=sub_type) + records = page_info.get("list", []) or [] + all_records.extend(records) + logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records)) + + return all_records + + +# ==================== 排班/打卡解析 ==================== +def parse_attendance_html(html): + pattern = r']*data-temp="([^"]+)"[^>]*>([^<]+)' + matches = re.findall(pattern, html) + result = {} + for date, shift in matches: + result[date.strip()] = shift.strip() + return result + + +def get_work_days_in_range(attendance_dict, start_date, end_date): + start = datetime.strptime(start_date, "%Y-%m-%d") + end = datetime.strptime(end_date, "%Y-%m-%d") + work_days = [] + current = start + while current <= end: + date_str = current.strftime("%Y-%m-%d") + shift = attendance_dict.get(date_str, "") + if shift != "休息" and shift != "": + work_days.append(date_str) + current += timedelta(days=1) + return work_days + + +def summarize_attendance_records(records): + time_format = "%Y-%m-%d %H:%M:%S" + group_map = defaultdict(list) + + for item in records: + staff_id = item.get("staff_id", "") + bc_day = item.get("bc_date", "") + if not staff_id or not bc_day: + continue + try: + kq_dt = datetime.strptime(item["kq_time"], time_format) + except (KeyError, ValueError): + continue + group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt}) + + summary = [] + for (sid, day), items in group_map.items(): + items.sort(key=lambda x: x["_dt"]) + base = items[0] + row = { + "staff_id": sid, + "staff_name": base.get("staff_name", ""), + "dept_name": base.get("DEPT_ORG_NAME", ""), + "post_name": base.get("POST_ALIAS_NAME", ""), + "attend_date": day, + "first_check_in": items[0]["kq_time"], + "last_check_out": items[-1]["kq_time"] if len(items) > 1 else None, + } + summary.append(row) + return summary + + +# ==================== 加班表单解析 ==================== +OT_TYPE_MAP = {"1": "延时加班", "2": "法定假日加班", "3": "休息日加班"} +SUBSIDY_TYPE_MAP = {"1": "转调休", "2": "转补贴"} + + +def parse_overtime_form(result): + ot_type_code = result.get("ot_type") + subsidy_type_code = result.get("subsidy_type") + + overtime_info = { + "加班人员ID": result.get("staff_id"), + "加班人员": result.get("staff_name"), + "所属部门": result.get("dept_org_name"), + "加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code), + "补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code), + "加班日期": result.get("ot_date"), + "加班开始时间": result.get("start_time"), + "加班结束时间": result.get("end_time"), + "加班时长(小时)": result.get("ot_hour"), + "加班天数(天)": result.get("ot_day"), + "系统判断加班时长(小时)": result.get("judge_ot_hour"), + "系统判断加班天数(天)": result.get("judge_ot_day"), + "附件": result.get("file"), + } + + judge_start = result.get("judge_start_time") + judge_end = result.get("judge_end_time") + if judge_start and judge_end: + overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}" + else: + overtime_info["系统判定加班时间"] = None + + return overtime_info + + +# ==================== 会话管理 ==================== +def init_session_from_page(browser_page, copy_headers=True): + session = SessionPage() + cookies_dict = browser_page.cookies(all_domains=True) + if cookies_dict: + session.set.cookies(cookies_dict) + logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict)) + else: + logger.warning("未获取到 Cookies,请确认浏览器已登录") + + if copy_headers: + headers = {"User-Agent": browser_page.run_js("return navigator.userAgent;")} + session.set.headers(headers) + logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50]) + + session.set.timeout(10) + return session + + +def refresh_session_cookies(session, browser_page): + cookies = browser_page.cookies(all_domains=True) + if cookies: + session.set.cookies(cookies) + logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies)) + else: + logger.warning("未获取到 Cookies,请确认浏览器登录态") + + +def save_browser_cookies(browser_page, path=COOKIE_FILE): + cookies = browser_page.cookies(all_domains=True) + if not cookies: + logger.warning("未获取到 Cookies,跳过保存") + return + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w', encoding='utf-8') as f: + json.dump(cookies, f, ensure_ascii=False, indent=2) + logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path) + + +def load_cookies(path=COOKIE_FILE): + if not os.path.exists(path): + return None + with open(path, encoding='utf-8') as f: + cookies = json.load(f) + return cookies or None + + +def load_saved_session(path=COOKIE_FILE): + cookies = load_cookies(path) + if not cookies: + return None + session = SessionPage() + session.set.cookies(cookies) + session.set.timeout(10) + return session + + +def create_browser_with_saved_cookies(path=COOKIE_FILE): + browser = ChromiumPage() + cookies = load_cookies(path) + if cookies: + browser.set.cookies(cookies) + return browser + + +def is_session_valid(session, subject="加班"): + try: + fetch_todo_page(session, subject=subject, page_no=1, page_size=1) + return True + except Exception as e: + logger.info("会话已失效,需重新登录: %s", e) + return False + + +# ==================== 登录 ==================== +@retry(max_attempts=3) +def oa_login(username=None, password=None, timeout=10, wait_after_load=2): + load_dotenv() + + login_url = os.getenv('oa_login_url') + if not login_url: + raise RuntimeError("环境变量 oa_login_url 未设置") + target_url_keyword = os.getenv('oa_target_url_keyword') + if not target_url_keyword: + raise RuntimeError("环境变量 oa_target_url_keyword 未设置") + + final_username = username or os.getenv('oa_login_username') + final_password = password or os.getenv('oa_login_password') + if not final_username or not final_password: + raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数") + + page = ChromiumPage() + + try: + page.get(login_url) + time.sleep(wait_after_load) + + username_input = page.ele('tag:input@name=j_username') + if not username_input: + raise RuntimeError("未找到用户名输入框") + username_input.input(final_username) + page.wait(0.5) + + password_input = page.ele('tag:input@name=j_password') + if not password_input: + raise RuntimeError("未找到密码输入框") + password_input.input(final_password) + page.wait(0.5) + + login_button = page.ele('.lui_login_button_div_c') + if not login_button: + raise RuntimeError("未找到登录按钮") + login_button.click() + page.wait(0.5) + + start = time.time() + while time.time() - start < timeout: + if target_url_keyword in page.url: + logger.info("登录成功!当前 URL: %s", page.url) + return page + time.sleep(0.5) + + error_elem = page.ele('.error-msg') or page.ele('.alert-danger') + if error_elem: + logger.warning("登录失败,提示: %s", error_elem.text) + raise RuntimeError(f"登录超时,当前 URL: {page.url}") + + except Exception as e: + page.quit() + raise RuntimeError(f"登录过程出错: {e}") + + +# ==================== SSO 解析 ==================== +def resolve_sso_params(browser, sso_url, wait_timeout=20): + logger.info("解析 SSO 重定向: %s", sso_url) + + browser.get(sso_url) + browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False) + logger.info("重定向最终 URL: %s", browser.url) + + params = parse_qs(urlparse(browser.url).query) + task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0] + business_key = params.get("businessKey", [None])[0] + + if not task_id or not business_key: + raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}") + + logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key) + return {"taskId": task_id, "businessKey": business_key} + + +# ==================== 审批引擎 ==================== +def _get_browser_and_session(subject): + saved_session = load_saved_session() + if saved_session is not None and is_session_valid(saved_session, subject): + logger.info("复用已保存的登录会话,跳过登录") + browser = create_browser_with_saved_cookies() + return browser, saved_session, False + + browser = oa_login() + session = init_session_from_page(browser) + save_browser_cookies(browser) + return browser, session, True + + +@retry(max_attempts=3) +def _fetch_documents(session, subject): + return get_documents(session, subject=subject) + + +@retry(max_attempts=3) +def _fetch_doc_detail(browser, session, doc): + detail_url = doc.get("detail_url", "") + if not detail_url: + raise RuntimeError(f"单据无详情链接: {doc.get('title')}") + + sso_params = resolve_sso_params(browser, detail_url) + task_id = sso_params["taskId"] + business_key = sso_params["businessKey"] + logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key) + + refresh_session_cookies(session, browser) + + wf_activity_data = get_wf_activity_by_task_id(session, task_id) + form_id = extract_form_id(wf_activity_data) + + form_data = get_business_data(session, business_key, form_id) + + return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data} + + +# ==================== 钉钉推送(内联精简版,保持单文件自包含) ==================== +DINGTALK_WINDOW_KEYWORD = "钉钉" + + +def _check_dingtalk_deps(): + """检查钉钉推送必需的第三方依赖,缺失时抛出带安装提示的 RuntimeError。""" + missing = [] + if pyautogui is None: + missing.append("pyautogui") + if win32gui is None: + missing.append("pywin32") + if pyperclip is None: + missing.append("pyperclip") + if missing: + raise RuntimeError(f"缺少依赖: {', '.join(missing)},请运行: pip install {' '.join(missing)}") + + +def _find_dingtalk_hwnd(): + """用 win32gui.EnumWindows 按标题查找钉钉主窗口句柄。""" + matches = [] + + def _enum(hwnd, _): + if not win32gui.IsWindowVisible(hwnd): + return + title = win32gui.GetWindowText(hwnd) + if title and DINGTALK_WINDOW_KEYWORD in title: + matches.append((hwnd, title)) + + win32gui.EnumWindows(_enum, None) + if not matches: + raise RuntimeError("未找到标题包含「钉钉」的可见窗口,请确认钉钉桌面端已启动并登录") + matches.sort(key=lambda x: len(x[1])) + return matches[0][0] + + +def _is_dingtalk_foreground(): + title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) + return DINGTALK_WINDOW_KEYWORD in title + + +def _activate_dingtalk(): + """激活钉钉窗口:Ctrl+D 优先,失败回退 win32。已在前台则跳过(Ctrl+D 是 toggle)。""" + if _is_dingtalk_foreground(): + logger.info("钉钉窗口已在前台,跳过激活") + return + try: + pyautogui.hotkey("ctrl", "d") + time.sleep(1.0) + if not _is_dingtalk_foreground(): + raise RuntimeError("Ctrl+D 未能激活") + logger.info("通过 Ctrl+D 激活钉钉窗口") + except Exception as e: + logger.warning("Ctrl+D 激活失败(%s),回退到 win32 查窗口激活", e) + hwnd = _find_dingtalk_hwnd() + if win32gui.IsIconic(hwnd): + win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) + time.sleep(0.3) + pyautogui.press("alt") + win32gui.SetForegroundWindow(hwnd) + time.sleep(1.0) + + +def _send_dingtalk_text(target, text): + """搜索联系人并发送文本:激活 → Ctrl+Shift+F 搜索 → 回车进会话 → 粘贴 → 回车发送。""" + _check_dingtalk_deps() + _activate_dingtalk() + # 搜索联系人 + pyautogui.hotkey("ctrl", "shift", "f") + time.sleep(0.5) + pyperclip.copy(target) + pyautogui.hotkey("ctrl", "v") + time.sleep(1.0) + pyautogui.press("enter") + time.sleep(1.0) + time.sleep(2.5) # 焦点稳定到消息输入框 + logger.info("已搜索并进入会话: %s", target) + # 粘贴文本并发送 + pyperclip.copy(text) + pyautogui.hotkey("ctrl", "v") + time.sleep(0.3) + pyautogui.press("enter") + time.sleep(1.0) + logger.info("文本已发送: %s", text[:50] + ("..." if len(text) > 50 else "")) + + +def build_push_summary(results, subject=""): + """ + 根据校验结果生成钉钉推送文字消息(多行)。 + 通过/驳回/人工复核三组均以文字说明推送。无业务结果时返回空串。 + """ + if not results: + return "" + passed = [r for r in results if r.get("decision") == "通过"] + rejected = [r for r in results if r.get("decision") == "驳回"] + review = [r for r in results if r.get("decision") == "人工复核"] + failed = [r for r in results if r.get("decision") == "失败"] + if not passed and not rejected and not review: + return "" + + def _item(r): + info = r.get("overtime_info", {}) or {} + title = r.get("title", "") or info.get("加班人员") or "未知" + vtype = info.get("加班类型") or "" + return f"{title}-{vtype}" if vtype else title + + all_pass = (not rejected and not review and not failed) + lines = [] + if all_pass: + lines.append(f"【{subject}审批】本次审批 {len(passed)} 条{subject}申请,") + lines.append("分别是:") + for r in passed: + lines.append(_item(r)) + lines.append("全部通过") + else: + lines.append(f"【{subject}审批】本次共审批 {len(results)} 条{subject}申请。") + if passed: + lines.append(f"通过 {len(passed)} 条,分别是:") + for r in passed: + lines.append(_item(r)) + if rejected: + lines.append(f"自动驳回 {len(rejected)} 条,分别是:") + for r in rejected: + lines.append(_item(r)) + lines.append(f"驳回原因:{r.get('note') or r.get('error') or '未知'}") + if review: + lines.append(f"需人工复核 {len(review)} 条,分别是:") + for r in review: + lines.append(_item(r)) + lines.append(f"详情页:{r.get('detail_url') or '无'}") + if failed: + lines.append(f"另有处理失败 {len(failed)} 条,请查看日志。") + return "\n".join(lines) + + +def push_report(report, subject=""): + """推送审批报告到钉钉联系人(env 控制,失败不影响主流程)。""" + load_dotenv() + if not report or not report.strip(): + logger.info("[%s] 无推送内容(无通过项),跳过钉钉推送", subject) + return False + enabled = os.getenv("dingtalk_notify_enabled", "false").lower() == "true" + if not enabled: + logger.info("[%s] 钉钉推送未开启(dingtalk_notify_enabled!=true),跳过", subject) + return False + target = os.getenv("dingtalk_notify_target", "").strip() + if not target: + logger.warning("[%s] 未配置 dingtalk_notify_target,跳过钉钉推送", subject) + return False + try: + _send_dingtalk_text(target, report) + logger.info("[%s] 审批报告已推送至钉钉: %s", subject, target) + return True + except Exception as e: + logger.warning("[%s] 钉钉推送失败: %s", subject, e) + return False + + +def run_flow(subject, validate_doc, generate_report): + setup_logging() + logger.info("%s审批流程开始", subject) + + browser, session, _ = _get_browser_and_session(subject) + + docs = _fetch_documents(session, subject) + logger.info("共获取%s待办 %d 条", subject, len(docs)) + + results = [] + for doc in docs: + try: + doc_detail = _fetch_doc_detail(browser, session, doc) + result = validate_doc(doc_detail, session) + results.append(result) + logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"]) + except Exception as e: + logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e)) + results.append({ + "creator": doc.get("creator", "未知"), + "title": doc.get("title", "未知"), + "decision": "失败", + "error": str(e), + }) + + report = generate_report(results) + print("\n" + report) + + # 推送「通过项汇总」到钉钉(env 控制;无通过项或失败均不影响主流程) + push_report(build_push_summary(results, subject), subject) + + save_browser_cookies(browser) + logger.info("%s审批流程结束,共处理 %d 条", subject, len(results)) + return report + + +# ==================== 加班校验规则 ==================== +def _parse_dt(value): + if not value: + return None + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"): + try: + return datetime.strptime(str(value), fmt) + except ValueError: + continue + return None + + +def _calc_delayed_hours(start, end): + total = (end - start).total_seconds() / 3600 + if total < 1: + return 0.0 + return 1.0 + math.floor((total - 1) / 0.5) * 0.5 + + +def _calc_flex_d(actual_checkout, flex_trigger): + return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5 + + +def _calc_day_ot_threshold(days): + return 8.0 * days + int(days) + + +def _next_day(date_str): + d = datetime.strptime(date_str, "%Y-%m-%d") + return (d + timedelta(days=1)).strftime("%Y-%m-%d") + + +def _is_spring_festival(date_str): + try: + import chinese_calendar as cc + date = datetime.strptime(date_str, "%Y-%m-%d").date() + is_holiday, holiday_name = cc.get_holiday_detail(date) + return (is_holiday and holiday_name == 'Spring Festival' + and not cc.is_in_lieu(date) and date.weekday() < 5) + except Exception as e: + logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e)) + return False + + +def _get_shift(session, staff_id, date_str): + if not date_str or not staff_id: + return "未知" + try: + year = int(date_str[:4]) + month = int(date_str[5:7]) + html = get_attendance_html(session, staff_id, year, month) + attendance = parse_attendance_html(html) + return attendance.get(date_str, "无排班") + except Exception as e: + logger.warning("获取排班失败(%s): %s", date_str, str(e)) + return "获取失败" + + +def _check_attendance(session, staff_id, ot_date): + return {"加班当天班次": _get_shift(session, staff_id, ot_date)} + + +def _check_punch_records(session, staff_id, ot_date): + if not ot_date or not staff_id: + return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None, + "打卡备注": "缺少加班日期或员工ID"} + + start = datetime.strptime(ot_date, "%Y-%m-%d") + next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d") + + try: + records = get_attendance_records(session, staff_id, ot_date, next_day) + summary = summarize_attendance_records(records) + day_summary = next((r for r in summary if r["attend_date"] == ot_date), None) + next_summary = next((r for r in summary if r["attend_date"] == next_day), None) + if not day_summary and not next_summary: + return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None, + "打卡备注": "当天及次日无打卡记录"} + return { + "当日最早打卡": day_summary["first_check_in"] if day_summary else None, + "当日最晚打卡": day_summary["last_check_out"] if day_summary else None, + "次日最早打卡": next_summary["first_check_in"] if next_summary else None, + "打卡备注": "", + } + except Exception as e: + logger.warning("获取打卡明细失败: %s", str(e)) + return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None, + "打卡备注": f"获取失败: {e}"} + + +def _check_leave_covers_morning(session, staff_id, date_str): + prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d") + try: + records = get_leave_records(session, staff_id, prev_day, date_str) + except Exception as e: + logger.warning("获取请假记录失败: %s", str(e)) + return False + + morning = datetime.strptime(f"{date_str} {WORK_START_TIME}", "%Y-%m-%d %H:%M") + for r in records: + start = _parse_dt(r.get("start_time")) + end = _parse_dt(r.get("end_time")) + if start and end and start <= morning <= end: + return True + return False + + +def _validate_delayed(info, punch, session, staff_id): + ot_date = info.get("加班日期") + start = _parse_dt(info.get("加班开始时间")) + end = _parse_dt(info.get("加班结束时间")) + actual_checkout = _parse_dt(punch.get("当日最晚打卡")) + reasons = [] + + # 1. 日期校验 + if start is None: + reasons.append("加班开始时间缺失") + elif start.strftime("%Y-%m-%d") != ot_date: + reasons.append(f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致") + + # 2. 时长校验 + hours = None + if end is None: + reasons.append("加班结束时间缺失") + elif start is not None: + hours = _calc_delayed_hours(start, end) + if hours < OT_MIN_HOURS: + reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时") + + # 3. 区间合规校验 + work_end = datetime.strptime(f"{ot_date} {WORK_END_TIME}", "%Y-%m-%d %H:%M") + if start is not None and start < work_end: + reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})") + if end is not None: + if actual_checkout is None: + reasons.append("当日无下班打卡记录,无法校验区间合规") + elif end > actual_checkout: + reasons.append(f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})") + + info["计算加班时长(小时)"] = hours + if reasons: + info["弹性扣减(小时)"] = 0 + info["有效加班时长(小时)"] = hours + info["弹性额度D(小时)"] = 0 + return "驳回", ";".join(reasons) + + # 4. 弹性到岗兑换 + deduction = 0.0 + flex_note = "" + d_hours = 0.0 + flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M") + + if actual_checkout is not None and actual_checkout >= flex_trigger: + d_hours = _calc_flex_d(actual_checkout, flex_trigger) + next_day = _next_day(ot_date) + next_shift = _get_shift(session, staff_id, next_day) + + if next_shift in ("休息", "无排班"): + flex_note = f"次日({next_day})为休息日,不触发弹性兑换" + elif next_shift in ("获取失败", "未知"): + flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换" + elif _check_leave_covers_morning(session, staff_id, next_day): + flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换" + else: + work_start = datetime.strptime(f"{next_day} {WORK_START_TIME}", "%Y-%m-%d %H:%M") + p = _parse_dt(punch.get("次日最早打卡")) + + if p is None: + flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换" + elif p <= work_start: + flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换" + else: + total_natural = (p - start).total_seconds() / 3600 + + if p <= work_start + timedelta(hours=d_hours): + late_hours = max(1, math.ceil((p - work_start).total_seconds() / 3600)) + if hours + late_hours > total_natural: + info["弹性扣减(小时)"] = 0 + info["有效加班时长(小时)"] = hours + info["弹性额度D(小时)"] = d_hours + return "驳回", ( + f"弹性兑换校验驳回:申请加班{hours:g}h + 晚到{late_hours}h " + f"> 总自然时长{total_natural:.1f}h" + ) + deduction = float(late_hours) + flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时" + else: + if hours + d_hours > total_natural: + info["弹性扣减(小时)"] = 0 + info["有效加班时长(小时)"] = hours + info["弹性额度D(小时)"] = d_hours + return "驳回", ( + f"弹性兑换校验驳回:申请加班{hours:g}h + 兑换额度{d_hours:g}h " + f"> 总自然时长{total_natural:.1f}h" + ) + deduction = float(d_hours) + flex_note = ( + f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h)," + f"按D兑换,超出部分交考勤处理" + ) + else: + if actual_checkout is not None: + flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0" + + effective = max(0.0, float(hours) - deduction) + info["弹性扣减(小时)"] = deduction + info["有效加班时长(小时)"] = effective + info["弹性额度D(小时)"] = d_hours + note = f"审批通过,有效加班时长{effective:g}小时" + if flex_note: + note += f"({flex_note})" + return "通过", note + + +def _validate_day_ot(info, punch, session, staff_id, require_holiday): + ot_date = info.get("加班日期") + reasons = [] + + shift = info.get("加班当天班次", "") + if shift not in ("休息", "获取失败", "未知", "无排班"): + reasons.append(f"当天排班为'{shift}',非休息日") + + if require_holiday and not _is_spring_festival(ot_date): + reasons.append(f"{ot_date}不在春节法定节假日列表中") + + ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)") + try: + ot_hour = float(ot_hour) + except (TypeError, ValueError): + ot_hour = 0.0 + if ot_hour <= 0: + reasons.append("加班时长为0或缺失") + + first = _parse_dt(punch.get("当日最早打卡")) + last = _parse_dt(punch.get("当日最晚打卡")) + interval = None + if first is None or last is None: + reasons.append("当天缺少上班或下班打卡") + else: + interval = (last - first).total_seconds() / 3600 + + apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)") + try: + apply_days = float(apply_days) + except (TypeError, ValueError): + apply_days = 0.0 + if apply_days <= 0: + reasons.append("申报天数缺失或为0") + elif interval is not None: + threshold = _calc_day_ot_threshold(apply_days) + if interval < threshold: + reasons.append(f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时") + + info["打卡时间间隔(小时)"] = interval + info["申报天数(天)"] = apply_days + if reasons: + return "驳回", ";".join(reasons) + return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)" + + +def validate_doc(doc, session): + form_data = doc.get("formData", {}) or {} + overtime_info = parse_overtime_form(form_data) + + staff_id = overtime_info.get("加班人员ID") + ot_date = overtime_info.get("加班日期") + + attendance_info = _check_attendance(session, staff_id, ot_date) + punch_info = _check_punch_records(session, staff_id, ot_date) + overtime_info.update(attendance_info) + overtime_info.update(punch_info) + + ot_type_code = str(form_data.get("ot_type") or "") + if ot_type_code == "1": + decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id) + elif ot_type_code == "3": + decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=False) + elif ot_type_code == "2": + require_holiday = _is_spring_festival(ot_date) + decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=require_holiday) + else: + decision, note = "驳回", f"无法识别加班类型: {ot_type_code}" + + return { + "title": doc.get("title", ""), + "creator": doc.get("creator", ""), + "time": doc.get("time", ""), + "detail_url": doc.get("detail_url", ""), + "decision": decision, + "note": note, + "overtime_info": overtime_info, + } + + +# ==================== 报告生成 ==================== +def _name(r): + """员工姓名:优先取表单里的加班人员,缺失时回退到发起人。""" + info = r.get("overtime_info", {}) or {} + return info.get("加班人员") or r.get("creator") or "未知" + + +def _otype(r): + """加班类型。""" + info = r.get("overtime_info", {}) or {} + return info.get("加班类型") or "未知" + + +def generate_report(results): + """ + 生成加班审批报告:汇总行 + 通过名单 + 驳回清单 + 人工复核清单(+处理失败)。 + + 输出两份清单: + 《加班审批自动驳回人员明细清单》:员工姓名、加班类型、驳回原因 + 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接(供人工打开查看附件) + """ + passed = [r for r in results if r.get("decision") == "通过"] + rejected = [r for r in results if r.get("decision") == "驳回"] + review = [r for r in results if r.get("decision") == "人工复核"] + failed = [r for r in results if r.get("decision") == "失败"] + + summary = f"共 {len(results)} 单:通过 {len(passed)},驳回 {len(rejected)},人工复核 {len(review)}" + if failed: + summary += f",处理失败 {len(failed)}" + + lines = [ + "加班审批报告", + "=" * 60, + summary, + "", + ] + + if passed: + names = "、".join(_name(r) for r in passed) + lines.append(f"【通过】{len(passed)} 条:{names}") + lines.append("") + + if rejected: + lines.append("《加班审批自动驳回人员明细清单》") + for i, r in enumerate(rejected, 1): + reason = r.get("note") or r.get("error") or "" + lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 驳回原因: {reason}") + lines.append("") + + if review: + lines.append("《附件人工复核待办清单》") + for i, r in enumerate(review, 1): + url = r.get("detail_url") or "无" + lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}") + lines.append("") + + if 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()