refactor: 重构执行机架构为 Electron 壳内置 Python 运行时子集
将原 webhost 底座的后端、前端、工具等代码迁移至 electron-shell 目录,构建自包含的 Python 环境包,移除冗余的前端代码、旧的后端模块及相关依赖,更新版本号至 1.0.6,优化平台登录态预检逻辑,统一代码结构为单一真源,避免多副本维护问题。
This commit is contained in:
@@ -1,88 +1,82 @@
|
||||
# Process-Automation
|
||||
|
||||
HR 业务流程自动化(37duAutomation):覆盖 HRBP OA 审批、EHR 数据核对/导出、社保、考勤、排班、雇主险等场景,并提供影刀 RPA 单文件版本与配套的「需求单 → 评分」文档体系。
|
||||
HR 业务流程自动化(37duAutomation):覆盖 HRBP OA 审批、EHR 数据核对/导出、社保、考勤、排班、雇主险等场景,提供桌面端插件体系(中心机 + 执行机)、影刀 RPA 单文件版本及配套的「需求单 → 评分」文档体系。
|
||||
|
||||
## 项目简介
|
||||
|
||||
基于 Python 的 HR 流程自动化工具,主要包括三类实现路径:
|
||||
基于 Python / Node 的 HR 流程自动化工具,实现形态上分两条落地路线:
|
||||
|
||||
* **桌面端插件体系**:中心机控制面(插件发布 / 账号权限 / 壳子分发)+ 执行机桌面壳(Electron + Node,内置便携 Python,插件以 Python 子进程运行),插件按账号权限自动同步加载,另配独立内网文件服务器承载大文件分发;
|
||||
|
||||
* **影刀 RPA 单文件版**:`workflows/` 下按业务隔离的单文件自包含脚本,可直接导入影刀平台运行。
|
||||
|
||||
业务上覆盖两大类场景:
|
||||
|
||||
* **OA 审批自动化**:通过 DrissionPage 浏览器自动化 + OA 接口,自动处理请假、加班、离职电子签等审批流程,内置规则校验、OCR(rapidocr 3.x)附件识别、钉钉/工作沟通推送、审批报告生成;
|
||||
|
||||
* **EHR 数据处理自动化**:对接 HR 平台接口与本地 Excel,完成考勤异常核对、排班异常识别、工资卡核对、社保增减名单/告知书、雇主险名额等;
|
||||
|
||||
* **影刀 RPA 单文件版**:`workflows/` 下按业务隔离的单文件自包含脚本,可直接导入影刀平台运行。
|
||||
* **EHR 数据处理自动化**:对接 HR 平台接口与本地 Excel,完成考勤异常核对、排班异常识别、工资卡核对、社保增减名单/告知书、雇主险名额等。
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
Process-Automation/
|
||||
├── desktop/ # 桌面端:中心机 + 执行机,两方向独立演进
|
||||
├── desktop/ # 桌面端:中心机 + 执行机 + 文件服务,各方向独立演进(模块搜索根 = desktop/,运行 cwd 均为 desktop/)
|
||||
│ ├── controlplane/ # 中心机:插件发布 / 账号权限 / 壳子分发控制面
|
||||
│ │ ├── app.py # FastAPI 服务入口(在 desktop/ 下 python -m controlplane.app)
|
||||
│ │ ├── core/ # 配置、存储、鉴权
|
||||
│ │ ├── apis/ # REST 接口
|
||||
│ │ ├── tools/ # agent_cli 发布 CLI、运维脚本
|
||||
│ │ └── frontend/ # 中心机管理前端
|
||||
│ └── webhost/ # 执行机:本地服务 + 前端工作台 + 插件运行底座
|
||||
│ ├── launch.py # 启动器(uvicorn + PyWebView 窗口)
|
||||
│ ├── backend/ # FastAPI 服务与插件加载器(backend/plugins)
|
||||
│ ├── frontend/ # 工作台前端
|
||||
│ └── tools/ # 壳子打包 spec / install.iss / 版本管理
|
||||
├── plugins/ # 插件源码(独立于桌面端,执行机按权限动态加载)
|
||||
│ ├── seal_check/ # 印章核对插件(目录包,含 __init__.py)
|
||||
│ ├── sb_person_change/ # 人员变更插件
|
||||
│ ├── demo.py
|
||||
│ └── platform_check.py
|
||||
│ │ ├── app.py # FastAPI 服务入口(desktop/ 下 python -m controlplane.app)
|
||||
│ │ ├── core/ / apis/ / frontend/ # 配置存储鉴权 / REST 接口 / 管理前端
|
||||
│ │ ├── packages/ / shell/ # 插件包与壳子安装包仓库
|
||||
│ │ └── tools/ # agent_cli 发布 CLI、运维脚本
|
||||
│ ├── electron-shell/ # 执行机桌面壳(当前宿主,Electron + Node)
|
||||
│ │ ├── electron/ # 主进程:本地服务、插件同步/调度/执行、壳子自动升级、Chrome 管理
|
||||
│ │ ├── frontend/ / renderer/ # 工作台前端
|
||||
│ │ ├── python-env/ # 内置便携 Python(插件以 Python 子进程执行)
|
||||
│ │ └── dist-app/ # 打包产物(electron-builder NSIS)
|
||||
│ ├── fileserver/ # 内网文件服务器(独立 FastAPI,端口 8802,存放壳子更新包/Chrome 安装包等大文件)
|
||||
│ └── webhost/ # 老版执行机底座(Python + PyWebView,已废弃,不再维护)
|
||||
├── plugins/ # 插件:号段桶目录为源码,扁平 id 目录为开发态运行目录
|
||||
│ ├── XQ0001-0100/ # 插件源码(按号段分桶,含 ui-src/ 前端源码与 _pack.py 打包脚本)
|
||||
│ │ ├── XQ0002 雇主险增减操作/
|
||||
│ │ ├── XQ0010 EHR系统月考勤异常处理/
|
||||
│ │ ├── XQ0011 考勤月报封存检查/
|
||||
│ │ └── ... # 插件内部按 config/data/logic/report/ui 多文件组织,自包含可独立发布
|
||||
│ └── xq0002/ xq0010/ xq0011/ ... # 开发态运行目录(打包产物解压得到,执行机注册表只扫一层)
|
||||
├── dist-plugin/ # 插件打包产物 <id>_v<版本>.zip(经 agent_cli publish 发布到中心机)
|
||||
├── workflows/ # 影刀 RPA 单文件版(需求脚本按号段分桶,对应 docs/需求单/XQ00xx)
|
||||
│ ├── share/ # 共享指令:钉钉群机器人/推送、OA/HR 登录、花名册导出、工作沟通
|
||||
│ ├── XQ0001-0100/ # 需求脚本(每 100 号一桶)
|
||||
│ │ ├── XQ0001 排班异常识别/ # 调动/预入职台账导出 + 排班异常判定(钉钉单聊推送)
|
||||
│ │ ├── XQ0002 雇主险增减操作/ # 名额调度、变更清单导出、增减员导入
|
||||
│ │ ├── XQ0003 EHR系统请假流程审核/
|
||||
│ │ ├── XQ0004 EHR系统加班流程审核/
|
||||
│ │ ├── XQ0005 银行卡检查/
|
||||
│ │ ├── XQ0006 EHR系统周考勤异常处理/
|
||||
│ │ ├── XQ0007 OA系统社保增减名单梳理/
|
||||
│ │ ├── XQ0008 重庆社保增减员导入名单制作/ # 增员/减员导入名单生成
|
||||
│ │ ├── XQ0009 门店上月请休假异常人员名单梳理/
|
||||
│ │ ├── XQ0010 EHR系统月考勤异常处理/
|
||||
│ │ ├── XQ0011 考勤月报封存检查/ # 月报封存、加班补偿、休班核对等多维检查
|
||||
│ │ ├── XQ0012 EHR预支及支付报酬自动发起ERP付款申请/ # *仅说明文档,未实现*
|
||||
│ │ ├── XQ0013 社保费用申报导出并汇总/ # *仅说明文档,未实现*
|
||||
│ │ ├── XQ0014 社保系统增减员办理/ # 社保系统登录、增员/减员导入、回盘审核结果检查回写
|
||||
│ │ ├── XQ0015 参保成功及异常告知书制作与下发/ # 覆盖 XQ0016 社保转移告知书
|
||||
│ │ ├── XQ0016 社保转移告知书制作与下发/ # *已由 XQ0015 覆盖*
|
||||
│ │ ├── XQ0017 入职人事手续办理/ # *仅说明文档,未实现*
|
||||
│ │ ├── XQ0018 调动人事手续跟进/ # *仅说明文档,未实现*
|
||||
│ │ ├── XQ0019 离职人事手续跟进与检查/ # *仅说明文档,未实现*
|
||||
│ │ ├── XQ0020 EHR系统离职电子签流程审核/
|
||||
│ │ ├── XQ0031 物料收发汇总表导出/
|
||||
│ │ └── XQ0032 ERP采购订单列表导出/
|
||||
│ └── README.md # 影刀版开发指南
|
||||
├── app/ # *已弃用归档,不再维护*(早期模块化蓝图,仅留作参考)
|
||||
│ ├── service/hrbp/
|
||||
│ │ ├── common/ # HR 平台公共层:会话、登录、配置、验证码调试
|
||||
│ │ ├── oa/ # OA 系统
|
||||
│ │ │ ├── common/ # 审批流引擎、登录/SSO、会话、通知、工作沟通、oa_api
|
||||
│ │ │ ├── leave/ # 请假审批(validator 校验 + reporter 报告)
|
||||
│ │ │ ├── work_overtime/ # 加班审批
|
||||
│ │ │ ├── resign_e_sign/ # 离职电子签流程审核
|
||||
│ │ │ ├── social_change/ # 社保增减名单梳理
|
||||
│ │ │ └── social_notice/ # 社保告知书制作与下发
|
||||
│ │ └── ehr/ # EHR 平台
|
||||
│ │ ├── common/hr_api/ # HR 接口封装(考勤/排班/工资卡/假期/加班/银行字典)
|
||||
│ │ ├── absence/ # 请休假异常分析
|
||||
│ │ ├── attendance/ # 考勤异常核对、月报封存、考勤统计导出
|
||||
│ │ ├── shift_abnormal/ # 排班异常识别
|
||||
│ │ ├── wage_card/ # 工资卡/银行卡核对
|
||||
│ │ ├── employer_insurance/ # 雇主险增减操作
|
||||
│ │ └── roster/ # 花名册导出与查询
|
||||
│ └── utils/ # 智能重试、日志
|
||||
├── workflows/ # 影刀 RPA 单文件版本(按需求单编号目录归档,对应 docs/需求单/XQ00xx)
|
||||
│ ├── share/ # 共享指令:钉钉群机器人/推送、OA/HR 登录、花名册导出、工作沟通
|
||||
│ ├── XQ0001 排班异常识别/ # 调动/预入职台账导出 + 排班异常判定(钉钉单聊推送)
|
||||
│ ├── XQ0002 雇主险增减操作/ # 名额调度、变更清单导出、增减员导入
|
||||
│ ├── XQ0003 EHR系统请假流程审核/
|
||||
│ ├── XQ0004 EHR系统加班流程审核/
|
||||
│ ├── XQ0005 银行卡检查/
|
||||
│ ├── XQ0006 EHR系统周考勤异常处理/
|
||||
│ ├── XQ0007 OA系统社保增减名单梳理/
|
||||
│ ├── XQ0008 重庆社保增减员导入名单制作/ # *占位,未实现*
|
||||
│ ├── XQ0009 门店上月请休假异常人员名单梳理/
|
||||
│ ├── XQ0010 EHR系统月考勤异常处理/
|
||||
│ ├── XQ0011 考勤月报封存检查/ # *占位,未实现*
|
||||
│ ├── XQ0012 EHR预支及支付报酬自动发起ERP付款申请/ # *占位,未实现*
|
||||
│ ├── XQ0013 社保费用申报导出并汇总/ # *占位,未实现*
|
||||
│ ├── XQ0014 社保系统增减员办理/ # *占位,未实现*
|
||||
│ ├── XQ0015 参保成功及异常告知书制作与下发/ # 覆盖 XQ0016 社保转移告知书
|
||||
│ ├── XQ0016 社保转移告知书制作与下发/ # *已由 XQ0015 覆盖*
|
||||
│ ├── XQ0017 入职人事手续办理/ # *占位,未实现*
|
||||
│ ├── XQ0018 调动人事手续跟进/ # *占位,未实现*
|
||||
│ ├── XQ0019 离职人事手续跟进与检查/ # *占位,未实现*
|
||||
│ ├── XQ0020 EHR系统离职电子签流程审核/
|
||||
│ └── README.md # 影刀版开发指南
|
||||
├── tests/ # 测试与试验脚本(run_all_tests.py、插件冒烟、OCR/WPS 可行性验证等)
|
||||
├── docs/
|
||||
│ ├── README.md # 文档总索引
|
||||
│ ├── 需求单/ # 各 XQ 四件套 + 需求单索引 + 评分规则
|
||||
│ ├── 插件/ # 插件开发规范 / 发版规范
|
||||
│ ├── 架构/ # 架构蓝图 / 插件管理系统设计 / 迭代规划 / 重构方案
|
||||
│ ├── 部署/ # 控制面前后端部署 SOP
|
||||
│ ├── 桌面端/ # 底座方案(平台账号本地加密存储)
|
||||
│ └── 工作沟通推送/ # OA 工作沟通推送说明
|
||||
│ ├── README.md # 文档总索引
|
||||
│ ├── 需求单/ # 各 XQ 四件套(按号段分桶 XQ0001-0100/)+ 需求单索引 + 评分规则 + 实现形态登记表
|
||||
│ ├── 插件/ # 插件开发规范 / 插件UI开发规范 / 发版规范
|
||||
│ ├── 架构/ # 架构蓝图 / 插件管理系统设计 / 迭代规划 / 重构方案
|
||||
│ ├── 部署/ # 控制面前后端部署 SOP
|
||||
│ └── 桌面端/ # Node 版客户端开发交接 / 桌面端发版 SOP / 平台账号本地加密存储等
|
||||
├── AGENTS.md # AI 智能体开发约束 & 项目执行规范
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
@@ -90,16 +84,18 @@ Process-Automation/
|
||||
|
||||
| 模块 | 说明 |
|
||||
| ------- | ------------------------------------------- |
|
||||
| 自动登录/会话 | OA(SSO)与 HR 平台登录,cookie 缓存,过期自动重登 |
|
||||
| 自动登录/会话 | OA(SSO)、HR 平台、社保系统登录,cookie 缓存,过期自动重登 |
|
||||
| 审批流程引擎 | 待办获取、表单解析、规则校验、结果提交、报告生成 |
|
||||
| 请假/加班审批 | 多类型(事假/病假/产假/年度福利假/加班类型等)分支校验,含附件 OCR |
|
||||
| 离职电子签审核 | 离职电子签流程自动审批 |
|
||||
| 考勤异常处理 | 周/月考勤异常核对,三查复核,钉钉推送 |
|
||||
| 考勤月报封存检查 | 月报封存状态、加班补偿、休班核对等多维检查与封存数据导出 |
|
||||
| 排班异常识别 | 调动/预入职台账导出 + 部门排班集合比对判定,序列/离职过滤,按店长分组钉钉单聊推送 |
|
||||
| 工资卡核对 | 身份证/姓名/银行卡号格式与一致性校验 |
|
||||
| 社保类 | 增减名单梳理、增减员导入名单、社保转移/参保异常处理 |
|
||||
| 社保类 | 增减名单梳理、导入名单生成、社保系统增减员办理与回盘核对、参保异常处理 |
|
||||
| 社保告知书 | 按模板生成 Word/PDF 告知书并合并下发 |
|
||||
| 雇主险 | 名额调度、增减操作、变更名单导出 |
|
||||
| 数据导出类插件 | 物料收发汇总、ERP 采购订单列表、通联交易数据导出(按商户分组拆分) |
|
||||
| 重试/日志 | 项目级最大 3 次重试;INFO 屏蔽大体积 JSON 调试日志,DEBUG 全量输出 |
|
||||
|
||||
## 技术依赖
|
||||
@@ -114,6 +110,8 @@ Process-Automation/
|
||||
|
||||
* `python-dotenv`、`chinese_calendar` 等
|
||||
|
||||
* `Electron` + `Node.js`:执行机桌面壳(当前宿主),插件以 Python 子进程运行
|
||||
|
||||
> 运行一律使用项目本地虚拟环境 `d:\work\code\37duAutomation\.venv`(`.venv\Scripts\python.exe`)。
|
||||
|
||||
## 使用方法
|
||||
@@ -123,6 +121,13 @@ Process-Automation/
|
||||
.venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 中心机控制面 / 内网文件服务器(cwd = desktop/,用项目根 .venv)
|
||||
python -m controlplane.app
|
||||
python -m fileserver.main
|
||||
|
||||
# 执行机桌面壳开发态(desktop/electron-shell/ 下)
|
||||
npm run dev
|
||||
|
||||
# 影刀版脚本(单文件自包含,直接运行,按号段分桶存放):
|
||||
# 排班异常识别(第二步导出 + 第三步识别)
|
||||
python "workflows/XQ0001-0100/XQ0001 排班异常识别/transfer_roster_export.py"
|
||||
@@ -143,8 +148,10 @@ python "workflows/XQ0001-0100/XQ0020 EHR系统离职电子签流程审核/resign
|
||||
python "workflows/XQ0001-0100/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py"
|
||||
python "workflows/XQ0001-0100/XQ0010 EHR系统月考勤异常处理/attendance_abnormal_monthly.py"
|
||||
|
||||
# 社保增减名单梳理 / 告知书制作与下发
|
||||
# 社保增减名单梳理 / 增减员导入名单 / 社保系统增减员办理 / 告知书制作与下发
|
||||
python "workflows/XQ0001-0100/XQ0007 OA系统社保增减名单梳理/social_change.py"
|
||||
python "workflows/XQ0001-0100/XQ0008 重庆社保增减员导入名单制作/generate_add.py"
|
||||
python "workflows/XQ0001-0100/XQ0014 社保系统增减员办理/import_add.py"
|
||||
python "workflows/XQ0001-0100/XQ0015 参保成功及异常告知书制作与下发/notice_mail_merge.py"
|
||||
|
||||
# 先运行登录指令写入共享登录态,再执行业务脚本
|
||||
@@ -168,5 +175,4 @@ python workflows/share/roster_export.py
|
||||
3. OA/HR 需在登录态有效期内运行,脚本会自动重登或提示重新登录;
|
||||
4. 影刀版本为单文件自包含,直接导入影刀平台运行;业务脚本不 import 共享指令模块,仅读 cookies 文件、写全局变量,消息生成与发送解耦(详见 `workflows/README.md`)。
|
||||
|
||||
> **桌面端与影刀版**:开发流程为「桌面端(`desktop/`,中心机 + 执行机)测试通过 → 影刀版(`workflows/`,单文件自包含)落地部署」;`app/` 为早期模块化蓝图,已**弃用归档、不再维护**,仅留作参考。桌面端各方向互不 import、独立演进,插件源码统一放根级 `plugins/`。
|
||||
|
||||
> **桌面端与影刀版**:桌面端 = 中心机 `desktop/controlplane/` + 执行机壳 `desktop/electron-shell/`(当前宿主)+ 内网文件服务 `desktop/fileserver/`,各方向互不 import、独立演进、可单独拷贝;`desktop/webhost/` 为老版执行机底座,已废弃不再维护。插件源码统一放根级 `plugins/`(按号段分桶),打包产物在 `dist-plugin/`,经 agent CLI 发布到中心机后由执行机按账号权限自下载。开发流程为「桌面端测试通过 → 影刀版(`workflows/`,单文件自包含)落地部署」;`app/` 为早期模块化蓝图,已**弃用归档、不再维护**,仅留作参考。
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: app
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 应用主包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
from app.common.env import load_app_env
|
||||
|
||||
# 导入 app 任意模块时即加载本模块专属 env(app/.env),保证与 cwd 无关、与其它方向互不干扰
|
||||
load_app_env()
|
||||
@@ -1,5 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Package: app.common
|
||||
@Description: 项目公共模块(跨业务复用的通用能力)。
|
||||
"""
|
||||
@@ -1,40 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: common.app_paths
|
||||
@FileName: app_paths.py
|
||||
@Author: 小布丁
|
||||
@Description: 公共路径模块:统一管理所有缓存/登录态文件的存放位置。
|
||||
所有缓存统一放在 %LOCALAPPDATA%\\37duAutomation 下,避免散落在脚本目录或各自独立的 AppData 文件夹。
|
||||
- app 版(服务层)统一放在 <根目录>\\.sessions\\,按文件名区分平台(hr_cookies.json / oa_cookies.json / 字典缓存等);
|
||||
- 影刀单文件脚本各自独立子目录(<根目录>\\<模块名>\\),保持自包含、互不影响。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
# 统一的应用数据根目录名
|
||||
APP_DATA_DIR_NAME = "37duAutomation"
|
||||
|
||||
# app 版会话 cookies / 缓存默认子目录名
|
||||
SESSIONS_DIR_NAME = ".sessions"
|
||||
|
||||
|
||||
def get_app_data_dir() -> str:
|
||||
"""返回统一的应用数据根目录:%LOCALAPPDATA%\\37duAutomation。"""
|
||||
base = os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~')
|
||||
return os.path.join(base, APP_DATA_DIR_NAME)
|
||||
|
||||
|
||||
def get_sessions_dir() -> str:
|
||||
"""返回 app 版登录态/会话 cookies 与缓存持久化目录:<根目录>\\.sessions。"""
|
||||
return os.path.join(get_app_data_dir(), SESSIONS_DIR_NAME)
|
||||
|
||||
|
||||
def get_module_dir(module_name: str) -> str:
|
||||
"""返回某业务/影刀脚本独立的缓存子目录:<根目录>\\<module_name>。"""
|
||||
return os.path.join(get_app_data_dir(), module_name)
|
||||
|
||||
|
||||
def ensure_dir(path: str) -> None:
|
||||
"""确保目录存在(不存在则创建)。"""
|
||||
os.makedirs(path, exist_ok=True)
|
||||
@@ -1,38 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: common.env
|
||||
@FileName: env.py
|
||||
@Author: 小布丁
|
||||
@Description: app 蓝图版专属 .env 加载器。
|
||||
与其它方向(webhost/controlplane)的 env 互不干扰:本模块只加载
|
||||
<app 根目录>/.env,即使进程 cwd 不在 app 目录也能读到;且不覆盖已存在的环境变量。
|
||||
所有 app 模块统一改用 load_app_env() 替代裸 load_dotenv()。
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# app/.env 固定定位:本文件(app/common/env.py)上两级即 app 根
|
||||
APP_ENV_PATH = Path(__file__).resolve().parent.parent / ".env"
|
||||
|
||||
|
||||
def load_app_env(path: str | os.PathLike = APP_ENV_PATH) -> None:
|
||||
"""幂等加载 app/.env(默认不覆盖已设环境变量)。"""
|
||||
env_path = Path(path)
|
||||
if not env_path.is_file():
|
||||
return
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv(str(env_path), override=False)
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
# python-dotenv 缺失时手动解析,保证零第三方依赖可用
|
||||
for line in env_path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, value = line.partition("=")
|
||||
key = key.strip()
|
||||
value = value.strip().strip("\"'")
|
||||
if key and value and key not in os.environ:
|
||||
os.environ[key] = value
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: HRBP 审批服务包:oa(OA 系统公共模块 + 业务流程:请假/加班等)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.common
|
||||
@FileName: __init__.py
|
||||
@Description: HR 平台共享层:供 ehr / oa 两个系统模块复用。
|
||||
HR(hr.37du.co) 是两套系统共用的底座(OA 的流程引擎/排班/打卡等接口也在 HR 域),
|
||||
因此把 HR 平台的登录、会话、请求封装与共享常量上移到此层,避免 oa 反向依赖 ehr。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 94 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 106 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 97 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.3 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.3 KiB |
@@ -1,27 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.common
|
||||
@FileName: config.py
|
||||
@Description: HR 平台共享配置:供 ehr / oa 两个系统模块复用
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# HR 平台根域名(ehr / oa 大量后台接口均位于该域)
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
# ---------- 假期类型编码 -> 名称映射(请假接口 leave_type 过滤 / 请假表单解析共用) ----------
|
||||
# 来源:OA 请假表单解析模块原 VACATION_TYPE_MAP,统一收口到 HR 平台共享层供各模块复用
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.common
|
||||
@FileName: hr_session.py
|
||||
@Description: HR 平台 requests 会话与请求封装(共享层):
|
||||
- build_hr_session / refresh_hr_session:构建 HR requests 会话,登录态过期自动重登
|
||||
- HRSessionExpiredError / _is_expired / hr_request_json:HR 接口请求通用封装
|
||||
供 ehr / oa 所有访问 hr.37du.co 接口的模块复用。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
requests = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# HR 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,login.py 登录成功后保存)
|
||||
_SESSIONS_DIR = get_sessions_dir()
|
||||
HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def build_hr_session(auto_login: bool = True) -> "requests.Session":
|
||||
"""用本地缓存的 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。
|
||||
|
||||
Args:
|
||||
auto_login: 无 cookies 缓存时是否自动执行 HR 登录。
|
||||
True=自动登录(ehr 各模块默认);False=直接抛错提示先登录(OA 侧批处理默认)
|
||||
"""
|
||||
if requests is None:
|
||||
raise RuntimeError("缺少 requests 依赖,请先安装")
|
||||
if not os.path.exists(HR_COOKIE_FILE):
|
||||
if not auto_login:
|
||||
raise RuntimeError(f"未找到 HR cookies 缓存文件:{HR_COOKIE_FILE},请先执行 HR 登录")
|
||||
logger.info("未找到 HR cookies 缓存,先执行 HR 登录")
|
||||
refresh_hr_session()
|
||||
if not os.path.exists(HR_COOKIE_FILE):
|
||||
raise RuntimeError(f"HR 登录后仍未生成 cookies 文件:{HR_COOKIE_FILE}")
|
||||
|
||||
with open(HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def refresh_hr_session() -> "requests.Session":
|
||||
"""HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。"""
|
||||
from app.service.hrbp.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 登录态过期后重新登录失败")
|
||||
return build_hr_session()
|
||||
|
||||
|
||||
def hr_request_json(session, method: str, url: str, params: dict, label: str, timeout: int = 20):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/登录态 → 返回解析后的 JSON。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
method: "POST" / "GET"
|
||||
url: 接口地址
|
||||
params: 表单参数(POST 用 data,GET 用 params)
|
||||
label: 接口中文名(用于报错信息)
|
||||
timeout: 请求超时秒数,默认 20
|
||||
|
||||
Returns:
|
||||
解析后的 JSON 字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
if method.upper() == "GET":
|
||||
resp = session.request(method, url, params=params, timeout=timeout)
|
||||
else:
|
||||
resp = session.request(method, url, data=params, timeout=timeout)
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError(f"HR 登录态已过期,{label}接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
@@ -1,489 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.common
|
||||
@FileName: login.py
|
||||
@Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍)。
|
||||
HR 平台登录能力(原位于 ehr/common/login.py),上移到共享层供 ehr / oa 复用
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
from PIL import Image, ImageDraw
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
import cv2
|
||||
import numpy as np
|
||||
import io
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
LOGIN_URL = os.getenv('hr_login_url')
|
||||
SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword')
|
||||
USERNAME = os.getenv('hr_login_username')
|
||||
PASSWORD = os.getenv('hr_login_password')
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
# 注意:不再使用 REFRESH_BTN
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
DEBUG_DIR = os.path.join(os.path.dirname(__file__), 'captcha_debug')
|
||||
|
||||
# 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,与 OA 系统一致)
|
||||
_COOKIE_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_COOKIE_DIR, 'hr_cookies.json')
|
||||
|
||||
def ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_COOKIE_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
def load_cookies():
|
||||
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
# ================== 改进的匹配函数(双候选 + 低置信度容忍) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes, debug_prefix=""):
|
||||
"""
|
||||
双候选匹配,返回最佳候选和次佳候选(即使置信度低)
|
||||
返回: (best_distance, best_conf, best_loc, candidates_list, x_offset, y_offset, slider_w, slider_h)
|
||||
其中 candidates_list 为 [(x, y, conf), ...] 用于绘制标记
|
||||
"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
|
||||
if bg_img is None or slider_color is None:
|
||||
print(f" [{debug_prefix}匹配错误] 无法解码图片")
|
||||
return None, 0, None, [], 0, 0, 0, 0
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
s_h, s_w = slider_color.shape[:2]
|
||||
print(f" [{debug_prefix}图片尺寸] 背景: {bg_w}x{bg_h}, 滑块原始: {s_w}x{s_h}")
|
||||
|
||||
# ---- 提取滑块有效区域 ----
|
||||
x_offset = 0
|
||||
y_offset = 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0 and len(xs) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max+1, x_min:x_max+1]
|
||||
x_offset = x_min
|
||||
y_offset = y_min
|
||||
print(f" [{debug_prefix}滑块裁剪] 有效区域: x=[{x_min},{x_max}], y=[{y_min},{y_max}], 裁剪后尺寸: {slider_rgb.shape[1]}x{slider_rgb.shape[0]}")
|
||||
else:
|
||||
print(f" [{debug_prefix}滑块裁剪] 未找到非透明区域,使用完整图")
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
else:
|
||||
if len(slider_color.shape) == 3:
|
||||
slider_rgb = slider_color
|
||||
else:
|
||||
slider_rgb = cv2.cvtColor(slider_color, cv2.COLOR_GRAY2BGR)
|
||||
x_offset = 0
|
||||
y_offset = 0
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
|
||||
# ---- 预处理:灰度 + 高斯模糊 + Canny ----
|
||||
gray_bg = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
|
||||
gray_slider = cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY)
|
||||
gray_bg = cv2.GaussianBlur(gray_bg, (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(gray_slider, (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
|
||||
# ---- 模板匹配(全图) ----
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
# 收集多个候选(前 6 个),避免真实缺口被最右侧干扰或滑块区假候选挤掉
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for i in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03: # 极低则停止
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
# 抑制周围
|
||||
y0 = max(0, max_loc[1] - s_h // 2)
|
||||
y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2)
|
||||
x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
print(f" [{debug_prefix}] 无有效候选")
|
||||
return None, 0, None, [], x_offset, y_offset, s_w, s_h
|
||||
|
||||
# 最右侧判定为干扰项:真实缺口不会紧贴背景图最右端
|
||||
right_margin = max(15, int(bg_w * 0.06))
|
||||
right_limit = bg_w - s_w - right_margin
|
||||
|
||||
# 真实缺口常为半透明白色矩形,白度是强判别信号(区域近白像素占比)
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y+h, x:x+w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
# 在有效区间 [s_w, right_limit] 内按「置信度 + 白度」综合评分选择
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit: # 排除左端滑块区与最右侧干扰
|
||||
continue
|
||||
wn = region_whiteness(x, y, s_w, s_h)
|
||||
score = val + 0.5 * wn
|
||||
scored.append((score, val, loc))
|
||||
print(f" [{debug_prefix}] 有效候选 loc={loc} conf={val:.4f} 白度={wn:.2f} 综合={score:.4f}")
|
||||
|
||||
if not scored:
|
||||
best_val, best_loc = candidates[0] # 全部落在无效区,回退全局最高
|
||||
print(f" [{debug_prefix}] 无有效区候选,回退最高置信度: loc={best_loc}, val={best_val:.4f}")
|
||||
else:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
print(f" [{debug_prefix}] 选择综合最优候选: loc={best_loc}, conf={best_val:.4f}")
|
||||
distance_phys = best_loc[0] - x_offset
|
||||
if distance_phys < 0:
|
||||
distance_phys = 0
|
||||
if distance_phys + s_w > bg_w:
|
||||
distance_phys = bg_w - s_w
|
||||
|
||||
# ---- 若置信度极低,尝试 ORB 辅助 ----
|
||||
if best_val < 0.25 and len(candidates) > 0:
|
||||
orb = cv2.ORB_create(nfeatures=500)
|
||||
kp1, des1 = orb.detectAndCompute(slider_edges, None)
|
||||
kp2, des2 = orb.detectAndCompute(bg_edges, None)
|
||||
if des1 is not None and des2 is not None and len(kp1) > 5 and len(kp2) > 5:
|
||||
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
||||
matches = bf.match(des1, des2)
|
||||
matches = sorted(matches, key=lambda x: x.distance)
|
||||
if len(matches) > 10:
|
||||
good = [m for m in matches[:30] if m.distance < np.mean([m.distance for m in matches[:15]]) * 0.7]
|
||||
if len(good) > 5:
|
||||
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
|
||||
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
|
||||
offsets = dst_pts - src_pts
|
||||
median_offset = np.median(offsets, axis=0)[0]
|
||||
orb_x = int(median_offset[0]) - x_offset
|
||||
if 0 < orb_x < bg_w - s_w:
|
||||
print(f" [{debug_prefix}] ORB辅助偏移: {orb_x}px (原模板置信度{best_val:.3f})")
|
||||
distance_phys = orb_x
|
||||
best_val = 0.5 # 提升置信度用于显示
|
||||
|
||||
# ---- 构建候选列表(用于绘图) ----
|
||||
candidate_points = []
|
||||
for val, loc in candidates:
|
||||
candidate_points.append((loc[0], loc[1], val))
|
||||
|
||||
print(f" [{debug_prefix}最终物理距离] distance={distance_phys}px (置信度 {best_val:.4f})")
|
||||
return distance_phys, best_val, best_loc, candidate_points, x_offset, y_offset, s_w, s_h
|
||||
|
||||
def draw_match_debug_multi(bg_bytes, slider_bytes, candidate_points, best_loc, x_offset, y_offset, slider_w, slider_h, distance_phys, distance_css, save_path):
|
||||
"""在背景图上绘制所有候选矩形和最佳匹配"""
|
||||
try:
|
||||
bg_img = Image.open(io.BytesIO(bg_bytes)).convert("RGBA")
|
||||
draw = ImageDraw.Draw(bg_img)
|
||||
|
||||
# 绘制所有候选(灰色虚线框)
|
||||
for i, (cx, cy, conf) in enumerate(candidate_points):
|
||||
if (cx, cy) == (best_loc[0], best_loc[1]):
|
||||
continue # 最佳单独绘制
|
||||
rect = [cx, cy, cx + slider_w, cy + slider_h]
|
||||
draw.rectangle(rect, outline="gray", width=1)
|
||||
draw.text((cx + 5, cy - 10), f"conf={conf:.2f}", fill="gray")
|
||||
|
||||
# 绘制最佳匹配(红色实线)
|
||||
if best_loc:
|
||||
rect = [best_loc[0], best_loc[1], best_loc[0] + slider_w, best_loc[1] + slider_h]
|
||||
draw.rectangle(rect, outline="red", width=3)
|
||||
text = f"best phys={distance_phys} css={distance_css}"
|
||||
draw.text((best_loc[0] + 5, best_loc[1] - 20), text, fill="red")
|
||||
|
||||
bg_img.save(save_path)
|
||||
print(f" [匹配标记] 已保存: {save_path}")
|
||||
except Exception as e:
|
||||
print(f" [匹配标记] 绘制失败: {e}")
|
||||
|
||||
# ================== 轨迹生成与滑动(与原相同) ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15))
|
||||
dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9))
|
||||
dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5))
|
||||
dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3))
|
||||
dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
dt = random.uniform(0.030, 0.080)
|
||||
if random.random() < 0.35:
|
||||
y = random.choice([-1, 0, 1])
|
||||
steps.append((dx, y, dt))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
if random.random() < 0.08:
|
||||
time.sleep(random.uniform(0.010, 0.035))
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
# ================== 验证码处理(移除刷新按钮,容忍低置信度) ==================
|
||||
def handle_captcha(page):
|
||||
ensure_dir(DEBUG_DIR)
|
||||
dpr = page.run_js('return window.devicePixelRatio')
|
||||
print(f"设备像素比(DPR): {dpr}")
|
||||
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry+1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
|
||||
bg_ele = container.ele(BG_IMG)
|
||||
if not bg_ele:
|
||||
bg_ele = container.ele('div[style*="background-image"]')
|
||||
if not bg_ele:
|
||||
print("找不到背景图元素")
|
||||
continue
|
||||
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not slider_ele:
|
||||
print("找不到滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
img_inner = slider_ele.ele('tag:img')
|
||||
if img_inner:
|
||||
slider_ele = img_inner
|
||||
|
||||
# 隐藏滑块 -> 截取背景 -> 恢复 -> 截取滑块
|
||||
bg_screenshot = None
|
||||
slider_screenshot = None
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception as e:
|
||||
print(f"隐藏/截图过程出错:{e}")
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
except:
|
||||
pass
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
# 保存原始截图
|
||||
bg_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}.png")
|
||||
slider_path = os.path.join(DEBUG_DIR, f"slider_{retry}.png")
|
||||
with open(bg_path, 'wb') as f:
|
||||
f.write(bg_screenshot)
|
||||
with open(slider_path, 'wb') as f:
|
||||
f.write(slider_screenshot)
|
||||
print(f" [调试截图] 背景: {bg_path}")
|
||||
print(f" [调试截图] 滑块: {slider_path}")
|
||||
|
||||
# 调用改进的匹配函数
|
||||
ret = match_slider_dual(bg_screenshot, slider_screenshot, debug_prefix=f"retry{retry}")
|
||||
if ret[0] is None:
|
||||
print("匹配失败,无候选,尝试随机拖动触发刷新")
|
||||
# 随机拖动一段距离(比如100-300px)尝试触发刷新
|
||||
random_css = random.uniform(100, 300) / dpr
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn:
|
||||
perform_slide(page, btn, random_css)
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
distance_phys, conf, best_loc, candidate_points, x_offset, y_offset, slider_w, slider_h = ret
|
||||
|
||||
# 转换为 CSS 距离
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" [置信度] {conf:.4f},物理距离: {distance_phys}px,CSS距离: {distance_css:.1f}px")
|
||||
|
||||
# 生成标记图(绘制所有候选)
|
||||
marked_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}_marked.png")
|
||||
draw_match_debug_multi(bg_screenshot, slider_screenshot, candidate_points, best_loc,
|
||||
x_offset, y_offset, slider_w, slider_h,
|
||||
distance_phys, distance_css, marked_path)
|
||||
|
||||
if distance_css <= 0:
|
||||
print(" CSS距离无效,尝试随机拖动")
|
||||
random_css = random.uniform(100, 300) / dpr
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn:
|
||||
perform_slide(page, btn, random_css)
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if not btn:
|
||||
print("找不到滑块按钮")
|
||||
continue
|
||||
|
||||
# 执行滑动
|
||||
perform_slide(page, btn, distance_css)
|
||||
time.sleep(2) # 等待验证结果
|
||||
|
||||
# 检查是否登录成功
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
# 若验证码容器消失,则认为验证通过
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
else:
|
||||
print("验证未通过,等待自动刷新...")
|
||||
# 不点击刷新按钮,等待网站自行更新验证码
|
||||
time.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
# ================== 登录主流程(不变) ==================
|
||||
def login():
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
|
||||
# 尝试复用已保存的 cookies,免重复登录
|
||||
saved = load_cookies()
|
||||
if saved:
|
||||
try:
|
||||
page.set.cookies(saved)
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已通过缓存的 Cookies 登录")
|
||||
return True
|
||||
print("缓存的 Cookies 已失效,重新登录")
|
||||
except Exception as e:
|
||||
print(f"复用 Cookies 失败:{e}")
|
||||
else:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
else:
|
||||
print("登录失败")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = login()
|
||||
print("最终结果:", "成功" if success else "失败")
|
||||
@@ -1,5 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr
|
||||
@Description: HR 系统相关业务模块
|
||||
"""
|
||||
@@ -1,10 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.absence
|
||||
@Description: 请休假异常分析包:门店上月请休假异常人员名单梳理。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.ehr.absence.absence_analysis import export_absence_list
|
||||
|
||||
__all__ = ["export_absence_list"]
|
||||
@@ -1,837 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.absence
|
||||
@FileName: absence_analysis.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-14
|
||||
@Description: 门店上月请休假异常人员名单梳理:
|
||||
花名册(员工基础信息模板)+ 考勤统计报表(逐日出勤 v_1~v_最后一天)+ 请假记录。
|
||||
每个人的「没到公司」日 = 报表中的(休息 ∪ 旷工)∪ 整天请假(leave_days>=1),
|
||||
计算每人「月末往前」连续未出勤段(报表判定 休息/旷工,整天请假仅认 已备案(002)
|
||||
且 leave_days>=1 计入),月末最后 5 天(从最后一天往前连续)均没出勤者纳入名单
|
||||
(统计月内已回来出勤的不放入名单)。
|
||||
若连续段触及查询月首,则一个月一个月往前推(按月全量缓存/单人查询两种策略),
|
||||
直到上一个上班日(跨月追溯)→ 确定请休假起止日期与天数 → 导出 Excel。
|
||||
结束日期:统计月 ≠ 当前月时,用当前月 1 日~今天 的考勤判定是否已返岗(返岗日-1),
|
||||
不再只靠请假判断;未返岗者取请假截止日(end_date 而非带时刻溢出的 end_time),无则「未归岗」。
|
||||
底层能力复用:roster_export(花名册导出)、hr_api(attendance_stat 报表 / leave)、hr_session(会话管理)。
|
||||
@Version: 2.2.0
|
||||
|
||||
说明:
|
||||
1. 数据源:「考勤统计报表」负责精确判定 休息/旷工(== 全等);请假类逐日出勤
|
||||
改由「请假接口」按整天请假(leave_days>=1) 覆盖,半天假/小时特假(leave_days<1) 不算整天缺席。
|
||||
迟到/漏打卡/早退/出差 等一律算「到公司」。无需再从报表文本猜测请假语义。
|
||||
整天请假仅认 已备案(002) 的假单:已撤销(003)/已销假(005)/申请中(001) 的假单在考勤报表里
|
||||
不体现,若也计入会把实际正常上班的人误判为缺勤。
|
||||
2. 跨月追溯采用「追溯月全量缓存」:每月首次访问拉一次全集团报表+请假并缓存,
|
||||
该月所有员工从内存解析,接口数退化为「追溯月数(报表+请假各1次/月)」。
|
||||
3. 名单「结束日期」/「未归岗」的判定:统计月已结束且当前月 != 统计月时,补拉当前月
|
||||
1 日~今天 的考勤报表,出现首次出勤 = 已返岗,结束日期 = 返岗日前一日(不再只靠请假判断);
|
||||
否则仅当已备案请假截止日 > 统计期最后一天才算请假仍在进行,取其截止日,无则填「未归岗,事件待定」。
|
||||
4. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Set, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in __import__("pathlib").Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(__import__("pathlib").Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理 / 花名册导出
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_cur_user_info,
|
||||
fetch_all_attendance_stat,
|
||||
fetch_all_leave,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_NAME # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\请休假异常"
|
||||
|
||||
# 连续未出勤天数阈值:>= 该天数纳入名单
|
||||
MIN_CONSECUTIVE_DAYS = 5
|
||||
|
||||
# 跨月追溯「逐月重估」:每往前推一个月,仍在追溯人数 >= TRACE_SINGLE_MAX 时用「整月全量缓存」
|
||||
# (每月报表+请假各拉一次,多人共用),否则切「按工号单人查询」(少人数长缺勤,如产假/长期病假,
|
||||
# 逐人回溯到上班日)。追溯人数逐月递减,早期月份批量、人少了自动切单人,减少全量拉取。不设月份上限。
|
||||
TRACE_SINGLE_MAX = 10
|
||||
|
||||
# 名单输出列(需求文档第 4 节)
|
||||
COLUMNS: List[str] = [
|
||||
"序号", "经营中心", "片区", "门店", "37工号", "姓名", "联系电话", "岗位",
|
||||
"技师工号", "参保类型", "入职时间", "请休假起始日期", "请休假结束日期", "请休假天数",
|
||||
"备注",
|
||||
]
|
||||
|
||||
# 花名册模板字段 -> 名单字段映射(Q9 已确认「员工基础信息」模板包含所需字段)
|
||||
ROSTER_COL_MAP: Dict[str, str] = {
|
||||
"二级部门": "经营中心",
|
||||
"三级部门": "片区",
|
||||
"四级部门": "门店",
|
||||
"工号": "37工号",
|
||||
"姓名": "姓名",
|
||||
"手机号码": "联系电话",
|
||||
"岗位": "岗位",
|
||||
"技师工号": "技师工号",
|
||||
"参保类型": "参保类型",
|
||||
"入职时间": "入职时间",
|
||||
}
|
||||
|
||||
# 未归岗占位文案(情况 A 且无任何请假流程)
|
||||
NOT_BACK_TEXT = "未归岗,事件待定"
|
||||
|
||||
# 请假记录状态(bpm_status):001=申请中;002=已备案(生效);003=已撤销;004=销假中;
|
||||
# 005=已销假;006=撤销加班;007=销差;008=已审批未备案。
|
||||
# 整天请假缺勤判定与「仍在请假中」判定均只认 002 已备案记录:撤销(003)/已销假(005)/申请中(001)
|
||||
# 的假单在考勤报表里不体现,若也计入会把实际正常上班的人误放进名单。
|
||||
ACTIVE_LEAVE_STATUS = "002"
|
||||
|
||||
# 当前月「返岗」判定用:报表单元格命中任一请假类片段即视为「未到公司」。
|
||||
# 休息/旷工 单独精确匹配(保持统计月口径:半天「上班旷工/下班旷工」不算整天缺席)。
|
||||
NOT_ATTEND_FRAGMENTS = (
|
||||
"事假", "病假", "产假", "调休假", "年度福利假", "特别福利假", "小时特假",
|
||||
)
|
||||
|
||||
# ===================== 考勤统计报表 v_* 状态判定 =====================
|
||||
# 报表负责精确判定两类「没到公司」:休息、旷工(均用 == 全等,不含「上班旷工/下班旷工」半天)。
|
||||
# 请假类的逐日出勤不由报表文本猜测,改由请假接口按「整天请假(leave_days>=1)」精确覆盖
|
||||
# (半天假/小时特假 leave_days<1 不算整天缺席)。迟到/漏打卡/早退/出差等一律算「到公司」。
|
||||
|
||||
|
||||
def _float(v, default: float = 0.0) -> float:
|
||||
"""把请假天数/小时等转 float,解析失败返回 default。"""
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return default
|
||||
try:
|
||||
return float(s)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
def _is_absent(status, seen: Optional[Dict[str, int]]) -> bool:
|
||||
"""报表单个逐日状态是否算「没到公司」。仅精确命中 休息/旷工 才算。空值视为不在职该日,不算。"""
|
||||
s = _clean(status)
|
||||
if not s:
|
||||
return False
|
||||
if seen is not None:
|
||||
seen[s] = seen.get(s, 0) + 1
|
||||
return s == "休息" or s == "旷工"
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 日期范围:默认上月完整月份
|
||||
# ----------------------------------------------
|
||||
def last_month_range(today: date = None) -> Tuple[date, date]:
|
||||
"""返回上月完整月份的 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
this_first = today.replace(day=1)
|
||||
last_end = this_first - timedelta(days=1)
|
||||
last_begin = last_end.replace(day=1)
|
||||
return last_begin, last_end
|
||||
|
||||
|
||||
def _month_range(month: str) -> Tuple[date, date]:
|
||||
"""按 "YYYY-MM" 返回该月完整范围的 (开始日期, 结束日期)。"""
|
||||
year, mon = map(int, month.split("-"))
|
||||
last_day = calendar.monthrange(year, mon)[1]
|
||||
return date(year, mon, 1), date(year, mon, last_day)
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 单元格清洗
|
||||
# ----------------------------------------------
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质(None、浮点 .0 尾缀)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. cookies 有效性校验(复用考勤模块逻辑)
|
||||
# ----------------------------------------------
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id)。
|
||||
若登录态过期则重新登录并重建会话后重试。
|
||||
"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s", user_id)
|
||||
return session, user_id
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 花名册读取(优先用已有文件,否则浏览器导出)
|
||||
# ----------------------------------------------
|
||||
def _load_roster(roster_path: str = None, save_dir: str = None) -> "pd.DataFrame":
|
||||
"""读取花名册数据(合并后的「员工基础信息」Excel,表头在第 1 行)。
|
||||
|
||||
Args:
|
||||
roster_path: 已有花名册文件路径;为空则调用 export_roster 导出最新数据。
|
||||
save_dir: 导出时的下载/输出目录,默认 SAVE_DIR。
|
||||
|
||||
Returns:
|
||||
花名册 DataFrame(列名已去除首尾空格,全部按字符串读取)。
|
||||
"""
|
||||
if roster_path and not os.path.exists(roster_path):
|
||||
raise RuntimeError(f"指定的花名册文件不存在:{roster_path}")
|
||||
|
||||
if not roster_path:
|
||||
from app.service.hrbp.ehr.roster.roster_export import export_roster
|
||||
target = os.path.abspath(save_dir or SAVE_DIR)
|
||||
os.makedirs(target, exist_ok=True)
|
||||
download_dir = os.path.join(target, "roster_download")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
out_path = os.path.join(target, f"花名册_{ts}.xlsx")
|
||||
logger.info("===== 未指定花名册文件,开始浏览器导出 =====")
|
||||
roster_path = export_roster(
|
||||
download_dir=download_dir,
|
||||
template_name=ROSTER_TEMPLATE_NAME,
|
||||
output_path=out_path,
|
||||
statuses=["在职", "离职"],
|
||||
)
|
||||
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _build_emp_map(df: "pd.DataFrame") -> Dict[str, "pd.Series"]:
|
||||
"""按工号建员工信息映射;同一工号多条时优先「在职」记录。"""
|
||||
emp: Dict[str, "pd.Series"] = {}
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get("工号"))
|
||||
if not code:
|
||||
continue
|
||||
if code in emp and _clean(row.get("类型")) != "在职":
|
||||
continue # 已有在职记录,跳过离职/其他
|
||||
emp[code] = row
|
||||
logger.info("花名册有效员工:%d 人", len(emp))
|
||||
return emp
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 数据口径:考勤统计报表 v_* 直接判定「没到公司」日
|
||||
# ----------------------------------------------
|
||||
def _report_records_to_status(records, begin: date, end: date,
|
||||
seen: Optional[Dict[str, int]]) -> Dict[str, Dict[date, str]]:
|
||||
"""把某月全集团报表 datas 转成 {工号: {日期: 类别}}。
|
||||
|
||||
类别 ∈ {旷工, 休息}(报表「休息/旷工」判未出勤;其余如迟到/漏打卡算到公司)。
|
||||
返回的同时保留每日具体类别,供「备注」列直接统计,无需再发请求。
|
||||
"""
|
||||
out: Dict[str, Dict[date, str]] = {}
|
||||
for rec in records:
|
||||
code = _clean(rec.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
daymap: Dict[date, str] = {}
|
||||
d = begin
|
||||
i = 1
|
||||
while d <= end:
|
||||
cell = _clean(rec.get(f"v_{i}"))
|
||||
if cell == "休息":
|
||||
daymap[d] = "休息"
|
||||
elif cell == "旷工":
|
||||
daymap[d] = "旷工"
|
||||
elif _is_absent(rec.get(f"v_{i}"), seen):
|
||||
daymap[d] = "请假" # 报表里出现的其他缺勤态兜底归为请假
|
||||
d += timedelta(days=1)
|
||||
i += 1
|
||||
if daymap:
|
||||
out[code] = daymap
|
||||
return out
|
||||
|
||||
|
||||
def _cur_month_status(records, begin: date, end: date) -> Dict[str, Dict[date, str]]:
|
||||
"""构建当前月(部分月)「未到公司」状态映射 {工号: {日期: 类别}},仅用于返岗判定。
|
||||
|
||||
统计月之后的当前月 1 日~今天,判断某人是否已返岗:报表单元格非空且不在该映射内 = 当天出勤。
|
||||
判定口径与统计月保持一致(休息/旷工 精确全等算未出勤),另把报表出现的请假类文本
|
||||
(病假/事假/产假/调休假/福利假/小时特假等,见 NOT_ATTEND_FRAGMENTS)一并判为未出勤,
|
||||
避免把「仍在请假中」的人误判成已返岗;「上班旷工,下班旷工」整天没来也判未出勤
|
||||
(半天「上班旷工/下班旷工」单独出现仍算到公司,与统计月口径一致)。
|
||||
"""
|
||||
out: Dict[str, Dict[date, str]] = {}
|
||||
for rec in records:
|
||||
code = _clean(rec.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
daymap: Dict[date, str] = {}
|
||||
d = begin
|
||||
while d <= end:
|
||||
cell = _clean(rec.get(f"v_{d.day}"))
|
||||
if cell == "休息":
|
||||
daymap[d] = "休息"
|
||||
elif cell == "旷工":
|
||||
daymap[d] = "旷工"
|
||||
elif cell and any(frag in cell for frag in NOT_ATTEND_FRAGMENTS):
|
||||
daymap[d] = "请假"
|
||||
elif "上班旷工" in cell and "下班旷工" in cell:
|
||||
daymap[d] = "旷工"
|
||||
d += timedelta(days=1)
|
||||
if daymap:
|
||||
out[code] = daymap
|
||||
return out
|
||||
|
||||
|
||||
def _full_day_leave_status(leaves, begin: date, end: date) -> Dict[str, Dict[date, str]]:
|
||||
"""把全集团请假记录转成 {工号: {日期: '请假'}}(仅已备案 002 且 leave_days>=1,半天/小时假排除)。
|
||||
|
||||
整天请假以请假记录起止区间逐日覆盖;半天假/小时特假(leave_days<1)不构成整天缺席。
|
||||
仅认 status=002(已备案)的假单:已撤销(003)/已销假(005)/申请中(001) 的假单在考勤报表里
|
||||
不体现,若计入会把实际正常上班的人误判为缺勤,故一并排除。
|
||||
"""
|
||||
out: Dict[str, Dict[date, str]] = {}
|
||||
for rec in leaves:
|
||||
code = _clean(rec.get("base_code"))
|
||||
if not code:
|
||||
continue
|
||||
# 只认已备案(002)的请假;已撤销/已销假/申请中的假单不构成整天缺席
|
||||
if _clean(rec.get("status")) != ACTIVE_LEAVE_STATUS:
|
||||
continue
|
||||
st = _parse_date(rec.get("start_time") or rec.get("begin_date") or rec.get("START_TIME"))
|
||||
et = _parse_date(rec.get("end_time") or rec.get("end_date") or rec.get("END_TIME"))
|
||||
if not st or not et:
|
||||
continue
|
||||
# leave_days 为空字符串/0/0.5 等(半天假、小时特假)一律不算整天缺席;
|
||||
# _float 对空值返回默认 0.0,故 ""、0.0、0.5 都会被 <1 分支排除。
|
||||
if _float(rec.get("leave_days")) < 1:
|
||||
continue
|
||||
d = st
|
||||
while d <= et:
|
||||
if begin <= d <= end:
|
||||
out.setdefault(code, {})[d] = "请假"
|
||||
d += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def _merge_leave_status(base: Dict[str, Dict[date, str]],
|
||||
leaves, begin: date, end: date) -> None:
|
||||
"""把整天请假类目并入 base。优先级:已有 旷工/休息 不覆盖;否则记为 请假。"""
|
||||
for code, daymap in _full_day_leave_status(leaves, begin, end).items():
|
||||
for d, cat in daymap.items():
|
||||
base.setdefault(code, {}).setdefault(d, cat)
|
||||
|
||||
|
||||
def _status_to_set(status: Dict[str, Dict[date, str]]) -> Dict[str, Set[date]]:
|
||||
"""把状态映射 {工号: {日期: 类别}} 转成 {工号: 缺勤日集合},供连续段计算使用。"""
|
||||
return {code: set(daymap.keys()) for code, daymap in status.items()}
|
||||
|
||||
|
||||
def _month_status_map(month_cache: Dict[str, Dict[str, Dict[date, str]]],
|
||||
session, user_id: str, month_str: str,
|
||||
seen: Optional[Dict[str, int]]) -> Dict[str, Dict[date, str]]:
|
||||
"""构建并缓存某月全集团「没到公司」状态映射 {工号: {日期: 类别}}(报表 休息/旷工 + 全天请假)。
|
||||
|
||||
供跨月追溯复用:某月首次访问时拉一次全集团报表 + 一次全集团请假并合并存入缓存,
|
||||
之后该月所有员工直接从缓存解析,避免按人逐次查询。类别含 旷工/休息/请假。
|
||||
"""
|
||||
if month_str not in month_cache:
|
||||
mb, me = _month_range(month_str)
|
||||
records = fetch_all_attendance_stat(session, user_id, month_str.replace("-", ""))
|
||||
merged = _report_records_to_status(records, mb, me, seen)
|
||||
leaves = fetch_all_leave(
|
||||
session, user_id, "", mb.strftime("%Y-%m-%d"), me.strftime("%Y-%m-%d")
|
||||
)
|
||||
_merge_leave_status(merged, leaves, mb, me)
|
||||
logger.info("已构建 %s 月缺勤映射(报表 %d 人 + 全集团请假 %d 条)",
|
||||
month_str, len(merged), len(leaves))
|
||||
month_cache[month_str] = merged
|
||||
return month_cache[month_str]
|
||||
|
||||
|
||||
def _log_statuses(seen: Dict[str, int]) -> None:
|
||||
"""打印观察到的所有逐日状态,供人工核对「休息/旷工精确判定」是否符合预期。"""
|
||||
if not seen:
|
||||
return
|
||||
summary = ", ".join(f"{k}={v}" for k, v in sorted(seen.items(), key=lambda x: -x[1]))
|
||||
logger.info("考勤统计报表逐日状态分布(值=次数):%s", summary)
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 连续未出勤段(休息日计入;月份边界触及则跨月往前推)
|
||||
# ----------------------------------------------
|
||||
def _trailing_absence_run(abs_or_rest: Set[date], begin: date, end: date):
|
||||
"""计算「从月末最后一天往前」的连续未出勤段。
|
||||
|
||||
「没到公司」= 该日在 abs_or_rest(请假 ∪ 旷工 ∪ 休息)。
|
||||
名单口径:仅统计月末最后一天往前连续未出勤 >= MIN_CONSECUTIVE_DAYS 天的人员
|
||||
(即月末最后 MIN_CONSECUTIVE_DAYS 天均没出勤);最后一天已出勤、或连续段不足
|
||||
阈值者不纳入名单(统计月内已回来出勤或月初即回岗的不算)。
|
||||
|
||||
Returns:
|
||||
(start, end, opens_back) 或 None。
|
||||
start:从月末往前连续未出勤段的起点;opens_back:段触及 begin(月首,需往前推)。
|
||||
"""
|
||||
d = end
|
||||
while d >= begin and d in abs_or_rest:
|
||||
d -= timedelta(days=1)
|
||||
start = d + timedelta(days=1)
|
||||
if (end - start).days + 1 < MIN_CONSECUTIVE_DAYS:
|
||||
return None
|
||||
return start, end, start == begin
|
||||
|
||||
|
||||
def _person_month_absent(session, user_id: str, code: str, month_str: str,
|
||||
seen: Optional[Dict[str, int]],
|
||||
status_cache: Optional[Dict[str, Dict[str, Dict[date, str]]]] = None) -> Set[date]:
|
||||
"""查某员工某月「没到公司」日集合(报表 base_code 单人查询 休息/旷工 + 该员工整天请假)。
|
||||
|
||||
同时把每月状态并入 status_cache({month: {code: {date: cat}}}),供「备注」统计复用,
|
||||
避免单人追溯场景下备注再发请求。
|
||||
"""
|
||||
mb, me = _month_range(month_str)
|
||||
daymap: Dict[date, str] = {}
|
||||
records = fetch_all_attendance_stat(session, user_id, month_str.replace("-", ""), base_code=code)
|
||||
for rec in records:
|
||||
if _clean(rec.get("base_code")) != code:
|
||||
continue
|
||||
d = mb
|
||||
i = 1
|
||||
while d <= me:
|
||||
cell = _clean(rec.get(f"v_{i}"))
|
||||
if cell == "休息":
|
||||
daymap[d] = "休息"
|
||||
elif cell == "旷工":
|
||||
daymap[d] = "旷工"
|
||||
elif _is_absent(rec.get(f"v_{i}"), seen):
|
||||
daymap[d] = "请假"
|
||||
d += timedelta(days=1)
|
||||
i += 1
|
||||
break
|
||||
_merge_leave_status({code: daymap}, fetch_all_leave(
|
||||
session, user_id, code, mb.strftime("%Y-%m-%d"), me.strftime("%Y-%m-%d")), mb, me)
|
||||
if status_cache is not None and daymap:
|
||||
status_cache.setdefault(month_str, {}).setdefault(code, {}).update(daymap)
|
||||
return set(daymap.keys())
|
||||
|
||||
|
||||
def _backward_starts_batch(session, user_id: str, begin: date,
|
||||
traced: List[Tuple[str, date]],
|
||||
month_cache: Dict[str, Dict[str, Dict[date, str]]],
|
||||
single_cache: Dict[str, Dict[str, Dict[date, str]]],
|
||||
seen: Optional[Dict[str, int]]) -> Dict[str, date]:
|
||||
"""逐月重估的跨月追溯:所有「段触及月首」的员工从统计月首前一日同速往回走。
|
||||
|
||||
每往前推一个月,先看「仍在追溯的人数」:
|
||||
- 人数 >= TRACE_SINGLE_MAX → 整月全量缓存(month_cache,每月报表+请假各拉一次,多人共用);
|
||||
- 人数 < TRACE_SINGLE_MAX → 逐人单人查询(single_cache,每月每人报表+请假各一次)。
|
||||
追溯人数随月份往前递减(找到上班日的逐步毕业),早期月份批量、人少了自动切单人,
|
||||
避免像固定「整月全量缓存」那样为最后几个人还每月全量拉取。
|
||||
|
||||
每月状态均并入对应缓存(month_cache / single_cache),供「备注」统计复用。
|
||||
|
||||
Args:
|
||||
begin: 统计月首日期(opens_back 的段起点,即 begin-1 起步)。
|
||||
traced: [(code, lower_bound), ...],段触及月首、需要跨月追溯的员工。
|
||||
|
||||
Returns:
|
||||
{code: 请休假起始日期};回溯到入职日前仍未上班的返回 lower_bound。
|
||||
"""
|
||||
result: Dict[str, date] = {}
|
||||
d = begin - timedelta(days=1) # 所有人同速从统计月首前一日往回走
|
||||
active = list(traced)
|
||||
while active:
|
||||
m_str = d.strftime("%Y-%m")
|
||||
mb, _ = _month_range(m_str)
|
||||
if len(active) >= TRACE_SINGLE_MAX:
|
||||
logger.info("追溯月 %s:%d 人在追溯,用整月全量缓存", m_str, len(active))
|
||||
month_map = _month_status_map(month_cache, session, user_id, m_str, seen)
|
||||
def get_not_att(code):
|
||||
return month_map.get(code, {})
|
||||
else:
|
||||
logger.info("追溯月 %s:%d 人在追溯,切为单人查询", m_str, len(active))
|
||||
for code, _ in active:
|
||||
_person_month_absent(session, user_id, code, m_str, seen, single_cache)
|
||||
def get_not_att(code):
|
||||
return single_cache.get(m_str, {}).get(code, {})
|
||||
next_active = []
|
||||
for code, lower_bound in active:
|
||||
not_att = get_not_att(code)
|
||||
dd = d
|
||||
while dd >= mb and dd >= lower_bound:
|
||||
if dd in not_att:
|
||||
dd -= timedelta(days=1)
|
||||
else:
|
||||
result[code] = dd + timedelta(days=1) # 昨日为上班日
|
||||
break
|
||||
else:
|
||||
if lower_bound < mb:
|
||||
next_active.append((code, lower_bound)) # 本月内未找到上班日,继续往前
|
||||
else:
|
||||
result[code] = lower_bound # 已回溯到入职日前仍未上班
|
||||
d = mb - timedelta(days=1)
|
||||
active = next_active
|
||||
return result
|
||||
|
||||
|
||||
def _segment_breakdown(code: str, seg_start: date, seg_end: date,
|
||||
query_month: str, q_map: Dict[date, str],
|
||||
get_month_status) -> Dict[str, int]:
|
||||
"""统计连续未出勤段内 旷工/请假/休息 天数(纯内存,复用已拉取的状态映射,0 额外请求)。
|
||||
|
||||
query_month:查询月 "YYYY-MM";q_map:该员工查询月状态 {日期: 类别}。
|
||||
get_month_status(month_str) -> {工号: {日期: 类别}},取查询月之外的追溯月状态。
|
||||
"""
|
||||
cnt = {"旷工": 0, "请假": 0, "休息": 0}
|
||||
m_start = seg_start.replace(day=1)
|
||||
while m_start <= seg_end:
|
||||
m_str = m_start.strftime("%Y-%m")
|
||||
mb, me = _month_range(m_str)
|
||||
if m_str == query_month:
|
||||
dmap = q_map
|
||||
else:
|
||||
status_map = get_month_status(m_str)
|
||||
dmap = status_map.get(code, {}) if status_map is not None else {}
|
||||
lo = max(mb, seg_start)
|
||||
hi = min(me, seg_end)
|
||||
d = lo
|
||||
while d <= hi:
|
||||
cat = dmap.get(d)
|
||||
if cat in cnt:
|
||||
cnt[cat] += 1
|
||||
d += timedelta(days=1)
|
||||
m_start = me + timedelta(days=1)
|
||||
return cnt
|
||||
|
||||
|
||||
def _latest_leave_end(session, user_id: str, code: str, begin: date, end: date) -> Optional[str]:
|
||||
"""查询该员工查询月请假记录,返回「请假实际截止日期晚于统计期最后一天」的最新请假截止日。
|
||||
|
||||
情况A(月末仍缺席)判定:仅当存在请假截止日期 > 统计期最后一天(请假仍在进行/跨出统计期)
|
||||
时,以其截止日作为请休假结束日期;否则视为未归岗(返回 None,外部填「未归岗,事件待定」)。
|
||||
|
||||
两个防误判点:
|
||||
1. 用 end_date(请假实际结束日期)而非 end_time(带时刻,跨下班时段结束的假会溢出到
|
||||
下月 1 号 00:00/00:30…),避免把「月末下半段结束的假」误判成跨月仍在休;
|
||||
2. 仅认 status=002(已备案)的假单:已撤销(003)/已销假(005) 的假单不构成「仍在休假中」。
|
||||
"""
|
||||
leaves = fetch_all_leave(
|
||||
session, user_id, code, begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
)
|
||||
ongoing = [
|
||||
d for r in leaves
|
||||
if _clean(r.get("status")) == ACTIVE_LEAVE_STATUS
|
||||
and (d := _parse_date(r.get("end_date") or r.get("end_time")))
|
||||
and d > end
|
||||
]
|
||||
if not ongoing:
|
||||
return None
|
||||
return max(ongoing).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 7. 名单梳理主流程
|
||||
# ----------------------------------------------
|
||||
def _analyze(emp: Dict[str, "pd.Series"], month_status: Dict[str, Dict[date, str]],
|
||||
session, user_id: str, begin: date, end: date,
|
||||
cur_ctx=None) -> List[dict]:
|
||||
"""按每人「没到公司」日集合,计算月末往前连续未出勤段,组装名单行。
|
||||
|
||||
名单口径:仅保留「从月末最后一天往前连续未出勤 >= MIN_CONSECUTIVE_DAYS 天」的人员
|
||||
(即月末最后 5 天均没出勤);统计月内已回来出勤、或月末最后 5 天内有出勤的不放入名单。
|
||||
|
||||
结束日期口径(情况A/B):
|
||||
- 统计月已结束且当前月 != 统计月时,用当前月 1 日~今天 的考勤判定返岗(cur_ctx):
|
||||
当前月内出现首次出勤 = 已返岗,结束日期 = 返岗日前一日(情况B);无出勤则走情况A;
|
||||
- 情况A:请假仍在进行(已备案假单 end_date > 统计月末)取请假截止日,否则「未归岗,事件待定」。
|
||||
|
||||
两遍处理:
|
||||
1. 先对全部候选算 `_trailing_absence_run`,过滤掉不合格人员并统计需跨月追溯的人数;
|
||||
2. 跨月追溯用「逐月重估」:每往前推一个月按仍在追溯的人数选整月缓存或单人查询,
|
||||
再逐个解析起始日、统计备注并组装名单行。
|
||||
|
||||
month_status:查询月全集团状态映射 {工号: {日期: 类别}}(含 旷工/休息/请假)。
|
||||
cur_ctx:返岗判定上下文 (cur_status, cur_rows, cur_begin, cur_end),None 表示不需要。
|
||||
"""
|
||||
seen: Dict[str, int] = {}
|
||||
query_month = begin.strftime("%Y-%m")
|
||||
month_absent = _status_to_set(month_status) # 供连续段计算使用的缺勤日集合
|
||||
candidate_codes = list(month_absent.keys())
|
||||
logger.info("候选员工(当月有请假/旷工/休息至少一天):%d 人", len(candidate_codes))
|
||||
|
||||
# 第一遍:求每人「月末往前」连续未出勤段 + 追溯需求,统计追溯人数
|
||||
# 名单口径:仅统计月末最后一天往前连续未出勤 >= 5 天的人员(月末最后 5 天均没出勤);
|
||||
# 月末最后一天已出勤、或段不足阈值者(统计月内已回来出勤)不纳入名单。
|
||||
runs: Dict[str, dict] = {}
|
||||
for code in candidate_codes:
|
||||
r = emp.get(code)
|
||||
res = _trailing_absence_run(month_absent.get(code, set()), begin, end)
|
||||
if res is None:
|
||||
continue
|
||||
seg_start, seg_end, opens_back = res
|
||||
join = _parse_date(r.get("入职时间")) if r is not None else None
|
||||
lower_bound = (join if join and join < begin else begin - timedelta(days=365 * 2))
|
||||
runs[code] = {
|
||||
"r": r, "seg_start": seg_start, "seg_end": seg_end,
|
||||
"opens_back": opens_back,
|
||||
"lower_bound": lower_bound,
|
||||
}
|
||||
n_trace = sum(1 for it in runs.values() if it["opens_back"])
|
||||
logger.info("需跨月追溯(段触及月首)员工:%d 人", n_trace)
|
||||
|
||||
# 跨月追溯改用「逐月重估」:所有段触及月首的员工从统计月首前一日同速往回走,
|
||||
# 每往前推一个月按「仍在追溯的人数」选整月缓存(>= TRACE_SINGLE_MAX)或单人查询,
|
||||
# 追溯人数逐月递减,人少了自动切单人,减少全量拉取(详见 _backward_starts_batch)。
|
||||
cache: Dict[str, Dict[str, Dict[date, str]]] = {} # 整月全量缓存 {month: {code: {date: cat}}}
|
||||
single_cache: Dict[str, Dict[str, Dict[date, str]]] = {} # 单人查询缓存 {month: {code: {date: cat}}}
|
||||
|
||||
def get_month_status(month_str: str):
|
||||
if month_str == query_month:
|
||||
return month_status
|
||||
if month_str in cache:
|
||||
return cache[month_str]
|
||||
return single_cache.get(month_str)
|
||||
|
||||
# 追溯起始日:段触及月首的员工统一逐月往回推(逐月重估批量/单人),其余直接取段起点
|
||||
traced = [(code, it["lower_bound"]) for code, it in runs.items() if it["opens_back"]]
|
||||
starts = _backward_starts_batch(session, user_id, begin, traced, cache, single_cache, seen) \
|
||||
if traced else {}
|
||||
|
||||
# 第二遍:解析各人起始日 + 组装名单行
|
||||
rows: List[dict] = []
|
||||
for code, it in runs.items():
|
||||
seg_start = starts.get(code, it["seg_start"])
|
||||
seg_end = it["seg_end"]
|
||||
r = it["r"]
|
||||
|
||||
# 结束日期与天数:
|
||||
# 优先用「当前月考勤返岗判定」:统计月后当前月 1 日~今天 内首次出勤(报表有状态且非
|
||||
# 休息/旷工/请假类)= 已返岗,结束日期 = 返岗日前一日(情况B口径),不再只靠请假判断;
|
||||
# 否则回到情况A:请假仍在进行(已备案假单 end_date > 统计月末)取请假截止日,无则「未归岗,事件待定」。
|
||||
return_day = None
|
||||
if cur_ctx is not None:
|
||||
cur_status, cur_rows, cur_begin, cur_end = cur_ctx
|
||||
row = cur_rows.get(code)
|
||||
if row is not None:
|
||||
cur_absent = cur_status.get(code, {})
|
||||
d = cur_begin
|
||||
while d <= cur_end:
|
||||
if _clean(row.get(f"v_{d.day}")) and d not in cur_absent:
|
||||
return_day = d
|
||||
break
|
||||
d += timedelta(days=1)
|
||||
if return_day is not None:
|
||||
end_date = return_day - timedelta(days=1)
|
||||
end_str = end_date.strftime("%Y-%m-%d")
|
||||
days_str = str((end_date - seg_start).days + 1)
|
||||
else:
|
||||
leave_end = _latest_leave_end(session, user_id, code, begin, end)
|
||||
if leave_end:
|
||||
end_str = leave_end
|
||||
days_str = str((_parse_date(leave_end) - seg_start).days + 1)
|
||||
else:
|
||||
end_str = NOT_BACK_TEXT
|
||||
days_str = ""
|
||||
|
||||
# 备注:统计连续未出勤段内 旷工/请假/休息 天数(纯内存复用已拉取状态,0 额外请求)
|
||||
cnt = _segment_breakdown(code, seg_start, seg_end, query_month,
|
||||
month_status.get(code, {}), get_month_status)
|
||||
note = "旷工{}天,请假{}天,休息{}天".format(cnt["旷工"], cnt["请假"], cnt["休息"])
|
||||
|
||||
rows.append({
|
||||
"序号": 0,
|
||||
"经营中心": _clean(r.get("二级部门")) if r is not None else "",
|
||||
"片区": _clean(r.get("三级部门")) if r is not None else "",
|
||||
"门店": _clean(r.get("四级部门")) if r is not None else "",
|
||||
"37工号": code,
|
||||
"姓名": _clean(r.get("姓名")) if r is not None else "",
|
||||
"联系电话": _clean(r.get("手机号码")) if r is not None else "",
|
||||
"岗位": _clean(r.get("岗位")) if r is not None else "",
|
||||
"技师工号": _clean(r.get("技师工号")) if r is not None else "",
|
||||
"参保类型": _clean(r.get("参保类型")) if r is not None else "",
|
||||
"入职时间": _date_part(r.get("入职时间")) if r is not None else "",
|
||||
"请休假起始日期": seg_start.strftime("%Y-%m-%d"),
|
||||
"请休假结束日期": end_str,
|
||||
"请休假天数": days_str,
|
||||
"备注": note,
|
||||
})
|
||||
|
||||
# 排序并补序号(按 经营中心/片区/门店/工号)
|
||||
rows.sort(key=lambda r: (r["经营中心"], r["片区"], r["门店"], r["37工号"]))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
logger.info("月末最后 %d 天均未出勤(连续未出勤,跨月前推)的员工:%d 人",
|
||||
MIN_CONSECUTIVE_DAYS, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 8. 导出名单 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(rows: List[dict], save_dir: str, month_str: str) -> str:
|
||||
"""将名单行导出为 .xlsx(无数据时也保留表头,便于对照)。"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
df = pd.DataFrame(rows, columns=COLUMNS)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"门店上月请休假异常名单_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("名单数据:%d 条", len(rows))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 9. 对外入口
|
||||
# ----------------------------------------------
|
||||
def export_absence_list(save_dir: str = None, roster_path: str = None, month: str = None) -> str:
|
||||
"""梳理上月请休假异常名单并导出 Excel,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
roster_path: 已有花名册文件路径;为空则浏览器导出最新花名册
|
||||
month: 查询月份 "YYYY-MM"(默认上月)
|
||||
|
||||
Returns:
|
||||
导出文件路径
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
# 统计范围:默认上月完整月份
|
||||
if month:
|
||||
begin, end = _month_range(month)
|
||||
else:
|
||||
begin, end = last_month_range()
|
||||
month_str = f"{begin:%Y%m}"
|
||||
logger.info("===== 请休假异常名单梳理,统计范围:%s ~ %s =====",
|
||||
begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
|
||||
|
||||
# 1. 花名册
|
||||
df = _load_roster(roster_path, save_dir)
|
||||
emp = _build_emp_map(df)
|
||||
|
||||
# 2. 会话校验
|
||||
session = build_hr_session()
|
||||
session, user_id = _validate_session(session)
|
||||
|
||||
# 3. 拉取上月全集团考勤统计报表,按报表判定「休息/旷工」,再并入整天请假(leave_days>=1)
|
||||
seen: Dict[str, int] = {}
|
||||
records = fetch_all_attendance_stat(session, user_id, month_str)
|
||||
logger.info("考勤统计报表共 %d 人", len(records))
|
||||
if not records:
|
||||
logger.error("考勤统计报表无数据,请检查月份或权限")
|
||||
return ""
|
||||
month_status = _report_records_to_status(records, begin, end, seen)
|
||||
leaves = fetch_all_leave(
|
||||
session, user_id, "", begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
)
|
||||
_merge_leave_status(month_status, leaves, begin, end)
|
||||
logger.info("全集团请假记录 %d 条(整天请假已并入缺勤判定)", len(leaves))
|
||||
_log_statuses(seen)
|
||||
|
||||
# 3.5 返岗判定数据:统计月已结束且当前月 != 统计月时,补拉当前月 1 日~今天 的考勤报表+请假记录,
|
||||
# 用于判断名单人员是否已返岗(不再只靠请假判断)。当前月始终实时调接口,不走缓存。
|
||||
cur_ctx = None
|
||||
if end < date.today():
|
||||
cur_begin = date.today().replace(day=1)
|
||||
cur_end = date.today()
|
||||
cur_records = fetch_all_attendance_stat(session, user_id, date.today().strftime("%Y%m"))
|
||||
cur_status = _cur_month_status(cur_records, cur_begin, cur_end)
|
||||
cur_leaves = fetch_all_leave(
|
||||
session, user_id, "", cur_begin.strftime("%Y-%m-%d"), cur_end.strftime("%Y-%m-%d"))
|
||||
_merge_leave_status(cur_status, cur_leaves, cur_begin, cur_end)
|
||||
cur_rows = {_clean(r.get("base_code")): r for r in cur_records if _clean(r.get("base_code"))}
|
||||
cur_ctx = (cur_status, cur_rows, cur_begin, cur_end)
|
||||
logger.info("统计月 %s 已结束,补拉当前月 %s~%s 考勤用于返岗判定(%d 人,请假 %d 条)",
|
||||
month_str, cur_begin, cur_end, len(cur_rows), len(cur_leaves))
|
||||
|
||||
# 4. 计算月末往前连续未出勤段(请假/旷工/休息构成,月末最后 >= 5 天均没出勤;段触及月首则跨月往前推)
|
||||
rows = _analyze(emp, month_status, session, user_id, begin, end, cur_ctx)
|
||||
|
||||
# 5. 导出
|
||||
path = export_excel(rows, save_dir, month_str)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【请休假异常名单汇总】")
|
||||
logger.info(" 统计范围:%s ~ %s", begin, end)
|
||||
logger.info(" 月末最后 %d 天均未出勤:%d 人", MIN_CONSECUTIVE_DAYS, len(rows))
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
return path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
roster_path = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
month = sys.argv[3] if len(sys.argv) > 3 else None
|
||||
try:
|
||||
out = export_absence_list(save_dir, roster_path, month)
|
||||
logger.info("===== 请休假异常名单梳理完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
# 文件被 Excel 占用:只提醒关闭后重试,不抛堆栈
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return
|
||||
logger.error("请休假异常名单梳理失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@Description: 考勤异常查询与导出模块
|
||||
"""
|
||||
@@ -1,625 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-14
|
||||
@Description: 月考勤异常三重复核:结合考勤异常 / 请假 / 加班 / 打卡四类接口,
|
||||
对当月数据做三项检查并输出多 Sheet Excel 报告(独立于周考勤异常处理流程):
|
||||
|
||||
检查1:已确认异常(is_adjusted=2)的日期,是否存在请假流程?
|
||||
—— 可能存在「提前确认后请假」导致仍为考勤异常的情况;
|
||||
检查2:休息日加班(类型3)且加班天数为 0.5 天,当日打卡是否按考勤班段正常打卡(无漏打卡)?
|
||||
检查3:员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)处于确认
|
||||
—— 弹出提示「该员工XX日考勤状态存在异常」。
|
||||
|
||||
底层复用:接口调用(app.service.hrbp.ehr.common.hr_api)、会话管理(app.service.hrbp.common.hr_session)。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到
|
||||
AppData\\Local\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可对当月做三查并导出 Excel 报告。
|
||||
3. 加班/请假接口按「空工号=查询全部」调用,返回的记录自带工号,无需额外员工列表接口。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_cur_user_info,
|
||||
fetch_all_attendance_abnormal,
|
||||
fetch_all_leave,
|
||||
fetch_all_overtime,
|
||||
fetch_all_kq_data,
|
||||
fetch_all_shift,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
from app.service.hrbp.common.config import VACATION_TYPE_MAP # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录(与周考勤异常导出目录保持一致)
|
||||
SAVE_DIR = r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
IS_ADJUSTED_CONFIRMED = "2" # 已确认异常(检查1)
|
||||
IS_ADJUSTED_OPEN = "0" # 未调整异常(检查3并集之一)
|
||||
IS_ADJUSTED_ALL = "" # 全部状态
|
||||
|
||||
# 加班类型:空=全部、1=延时加班、2=法定假日加班、3=休息日加班
|
||||
WORK_OVERTIME_TYPE_REST = "3"
|
||||
|
||||
# 休息日半天加班判定阈值(ot_days / sys_ot_days / plan_ot_days ≈ 0.5)
|
||||
HALF_DAY = 0.5
|
||||
EPS = 1e-6
|
||||
|
||||
# 打卡与班段边界匹配容差(分钟):上班打卡在班段开始前后、下班打卡在班段结束前后
|
||||
# 该时间内有打卡即视为「按班段正常打卡」,用于排除晚到/早走导致的漏打卡误报
|
||||
PUNCH_TOLERANCE_MIN = 60
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 工具函数
|
||||
# ----------------------------------------------
|
||||
def current_month_range(today: date = None) -> Tuple[str, str]:
|
||||
"""返回当月的查询日期范围 (开始日期, 结束日期)。开始=当月1日,结束=今天。"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _get(rec: Dict[str, Any], *keys: str, default: Any = "") -> Any:
|
||||
"""从记录中取第一个存在的键的值(兼容字段大小写差异)。"""
|
||||
for k in keys:
|
||||
if rec.get(k) is not None and rec.get(k) != "":
|
||||
return rec[k]
|
||||
return default
|
||||
|
||||
|
||||
def _to_date_str(value: Any) -> str:
|
||||
"""将接口返回的日期/时间值归一化为 'YYYY-MM-DD'(取前10位)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
return s[:10] if len(s) >= 10 else s
|
||||
|
||||
|
||||
def _float(value: Any, default: float = 0.0) -> float:
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _is_half_day_ot(rec: Dict[str, Any]) -> bool:
|
||||
"""判断加班记录是否为休息日半天(0.5 天)。
|
||||
|
||||
依次取 ot_days / sys_ot_days / plan_ot_days,任一 ≈ 0.5 即判定半天。
|
||||
"""
|
||||
for key in ("ot_days", "sys_ot_days", "plan_ot_days"):
|
||||
val = rec.get(key)
|
||||
if val is not None and val != "":
|
||||
if abs(_float(val) - HALF_DAY) <= EPS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _leave_type_name(rec: Dict[str, Any]) -> str:
|
||||
"""从请假记录中提取假期类型名称(兼容编码与名称两种输入)。"""
|
||||
raw = _get(rec, "leave_type", "vacation_type", "sub_type", "LEAVE_TYPE")
|
||||
raw = str(raw).strip()
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def _staff_name(rec: Dict[str, Any]) -> str:
|
||||
"""兼容取员工姓名字段(不同接口命名不同)。"""
|
||||
return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default=""))
|
||||
|
||||
|
||||
def _punch_analysis(records: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""对某日打卡流水做统计。
|
||||
|
||||
打卡记录无法可靠区分上下班(time_order 多为空),按时间最早=上班、最晚=下班汇总。
|
||||
|
||||
Returns:
|
||||
{count, first, last}:count 打卡次数,first/last 最早/最晚打卡时间(含时分)
|
||||
"""
|
||||
times = []
|
||||
for rec in records:
|
||||
t = _get(rec, "kq_time", "kqTime", "punch_time")
|
||||
if t:
|
||||
times.append(str(t))
|
||||
times.sort()
|
||||
if not times:
|
||||
return {"count": 0, "first": "", "last": ""}
|
||||
return {"count": len(times), "first": times[0], "last": times[-1]}
|
||||
|
||||
|
||||
def _to_minutes(value: Any) -> Optional[int]:
|
||||
"""将 "HH:MM[:SS]" 时间串转为当日分钟数;解析失败返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
# 兼容 "09:00" / "09:00:00" / "2026-08-03 09:00:00"(取最后的时间段)
|
||||
import re
|
||||
m = re.search(r"(\d{1,2}):(\d{2})(?::(\d{2}))?$", s)
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2))
|
||||
|
||||
|
||||
def _time_hhmm(value: Any) -> str:
|
||||
"""取日期时间串中的 "HH:MM";无时间部分返回空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
import re
|
||||
m = re.search(r"(\d{1,2}):(\d{2})", str(value))
|
||||
return f"{int(m.group(1)):02d}:{m.group(2)}" if m else ""
|
||||
|
||||
|
||||
def _shift_segment(rec: Dict[str, Any]) -> str:
|
||||
"""合成异常记录的班段 "HH:MM ~ HH:MM"(begin_time ~ end_time,区分同一日多班段异常)。"""
|
||||
b = _time_hhmm(_get(rec, "begin_time"))
|
||||
e = _time_hhmm(_get(rec, "end_time"))
|
||||
return f"{b} ~ {e}" if b or e else ""
|
||||
|
||||
|
||||
def _parse_shift_time(bc_time: str) -> Tuple[Optional[int], Optional[int]]:
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
|
||||
if not bc_time:
|
||||
return None, None
|
||||
import re
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None, None
|
||||
start = int(m.group(1)) * 60 + int(m.group(2))
|
||||
end = int(m.group(3)) * 60 + int(m.group(4))
|
||||
return start, end
|
||||
|
||||
|
||||
def _extract_day_shift(shift_rows: List[Dict[str, Any]], date_str: str) -> Dict[str, Any]:
|
||||
"""从某员工排班记录中提取指定日期的班段信息。
|
||||
|
||||
排班接口 datas 为动态列(key 为 "YYYY-MM-DD_bc_name/bc_time/..."):
|
||||
- bc_name:班次名(休息日为「休息」,是休息与否的可靠判定依据)
|
||||
- bc_time:班段时间,如 "09:00 ~ 18:00"(休息日为空串)
|
||||
注意:paiban_type 不可靠(休息也可能为 -2 / 0),不可用来判定休息。
|
||||
|
||||
Returns:
|
||||
{"bc_name": 班次名, "bc_time": 班段时间}
|
||||
"""
|
||||
info = {"bc_name": "", "bc_time": ""}
|
||||
for rec in shift_rows:
|
||||
name = _get(rec, f"{date_str}_bc_name", default="")
|
||||
time_ = _get(rec, f"{date_str}_bc_time", default="")
|
||||
if name or time_:
|
||||
info = {"bc_name": str(name), "bc_time": str(time_)}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
def _judge_punch_by_shift(p: Dict[str, Any], shift_info: Dict[str, Any]) -> str:
|
||||
"""结合班段时间判断当日打卡是否正常。
|
||||
|
||||
规则:
|
||||
- 排班有班段时间(如 "09:00 ~ 12:00"):最早打卡应覆盖班段开始(前后容差内),
|
||||
最晚打卡应覆盖班段结束,且打卡次数 >= 2 → 正常;
|
||||
- 排班为休息日(无班段时间):退化为打卡次数判断(>=2 正常)。
|
||||
"""
|
||||
start_min, end_min = _parse_shift_time(shift_info.get("bc_time", ""))
|
||||
count = p["count"]
|
||||
tol = PUNCH_TOLERANCE_MIN
|
||||
|
||||
# 无班段(休息日排班):按打卡次数判断
|
||||
if start_min is None or end_min is None:
|
||||
if count >= 2:
|
||||
return "正常(有上班+下班打卡)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
|
||||
# 有班段:最早打卡覆盖班段开始、最晚打卡覆盖班段结束
|
||||
first_min = _to_minutes(p["first"])
|
||||
last_min = _to_minutes(p["last"])
|
||||
first_ok = first_min is not None and first_min <= start_min + tol
|
||||
last_ok = last_min is not None and last_min >= end_min - tol
|
||||
if count >= 2 and first_ok and last_ok:
|
||||
return "正常(按班段上班/下班打卡齐全)"
|
||||
if count == 0:
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(打卡未按班段覆盖上下班)"
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. cookies 有效性校验(员工基础信息接口)
|
||||
# ----------------------------------------------
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。
|
||||
若登录态过期则重新登录并重建会话后重试。
|
||||
"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return session, user_id, treecode
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 数据获取(全量拉取,返回记录自带工号)
|
||||
# ----------------------------------------------
|
||||
def _fetch_all_data(session, user_id: str, treecode: str, begin: str, end: str) -> Dict[str, list]:
|
||||
"""一次性拉取三项检查所需的基础数据。
|
||||
|
||||
- abnormal_confirmed: 已确认异常(is_adjusted=2)
|
||||
- abnormal_open: 未调整异常(is_adjusted=0)
|
||||
- leaves: 全部请假记录(空工号=全量,检查1/检查3共用)
|
||||
- rest_overtime: 全部休息日加班(类型3,空工号=全量,检查2用)
|
||||
|
||||
Returns:
|
||||
以名称为键的列表字典
|
||||
"""
|
||||
logger.info("===== 月考勤异常三查,日期范围:%s ~ %s =====", begin, end)
|
||||
|
||||
abnormal_confirmed = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_CONFIRMED
|
||||
)
|
||||
abnormal_open = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_OPEN
|
||||
)
|
||||
logger.info("已确认异常 %d 条,未调整异常 %d 条", len(abnormal_confirmed), len(abnormal_open))
|
||||
|
||||
# 请假:空工号 = 查询全部员工(返回记录自带 base_code)
|
||||
leaves = fetch_all_leave(session, user_id, "", begin, end)
|
||||
logger.info("请假记录(全部员工)%d 条", len(leaves))
|
||||
|
||||
# 休息日加班:空工号 = 查询全部员工
|
||||
rest_overtime = fetch_all_overtime(
|
||||
session, user_id, "", begin, end, WORK_OVERTIME_TYPE_REST
|
||||
)
|
||||
logger.info("休息日加班记录(全部员工)%d 条", len(rest_overtime))
|
||||
|
||||
return {
|
||||
"abnormal_confirmed": abnormal_confirmed,
|
||||
"abnormal_open": abnormal_open,
|
||||
"leaves": leaves,
|
||||
"rest_overtime": rest_overtime,
|
||||
}
|
||||
|
||||
|
||||
def _build_leave_set(leaves: List[Dict[str, Any]], need_full_day: bool = False) -> Dict[Tuple[str, str], Dict]:
|
||||
"""把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。
|
||||
|
||||
need_full_day=True 时只保留整日请假(leave_days>=1)的每一天;
|
||||
否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。
|
||||
"""
|
||||
index: Dict[Tuple[str, str], Dict] = {}
|
||||
for rec in leaves:
|
||||
code = str(_get(rec, "base_code")).strip()
|
||||
# 用 begin_date/end_date(考勤归属日期)而非 start_time/end_time:
|
||||
# 跨天夜班请假 end_time 会落到次日,导致请假范围多算一天
|
||||
start = _to_date_str(_get(rec, "begin_date", "start_time"))
|
||||
end = _to_date_str(_get(rec, "end_date", "end_time"))
|
||||
leave_days = _float(rec.get("leave_days"))
|
||||
if not code or not start or not end:
|
||||
continue
|
||||
if need_full_day and leave_days < 1:
|
||||
continue
|
||||
try:
|
||||
cur = datetime.strptime(start, "%Y-%m-%d").date()
|
||||
end_d = datetime.strptime(end, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
continue
|
||||
if end_d < cur:
|
||||
continue
|
||||
step = timedelta(days=1)
|
||||
while cur <= end_d:
|
||||
index[(code, cur.strftime("%Y-%m-%d"))] = rec
|
||||
cur += step
|
||||
return index
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 检查1:已确认异常日期 × 请假流程
|
||||
# ----------------------------------------------
|
||||
def check_leave_after_confirm(abnormal_confirmed: List[Dict[str, Any]],
|
||||
leave_index: Dict[Tuple[str, str], Dict]) -> List[Dict[str, Any]]:
|
||||
"""已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。
|
||||
|
||||
若存在,说明可能是「提前确认后请假」导致仍为考勤异常,需人工复核。
|
||||
"""
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for ab in abnormal_confirmed:
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = leave_index.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"考勤日期": work_day,
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假起止": f"{_to_date_str(_get(leave_rec, 'begin_date', 'start_time'))} ~ "
|
||||
f"{_to_date_str(_get(leave_rec, 'end_date', 'end_time'))}",
|
||||
"问题说明": "该日期已确认考勤异常,但同时存在请假流程,可能为「提前确认后请假」仍为异常",
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 检查2:休息日半天加班 × 打卡校验(结合排班班段)
|
||||
# ----------------------------------------------
|
||||
def check_rest_day_half_day_punch(session, user_id: str, treecode: str,
|
||||
rest_overtime: List[Dict[str, Any]],
|
||||
begin: str, end: str) -> List[Dict[str, Any]]:
|
||||
"""休息日加班(类型3)且加班天数为 0.5 天时,校验当日打卡是否按考勤班段正常打卡。
|
||||
|
||||
步骤:
|
||||
1. 按工号拉取排班(fetch_all_shift),取加班日期的班段时间(bc_time);
|
||||
2. 拉取该员工当日打卡流水(fetch_all_kq_data);
|
||||
3. 结合班段判定:最早打卡覆盖班段开始、最晚打卡覆盖班段结束且次数>=2 → 正常,
|
||||
否则漏打卡;休息日排班(无班段)则退化为按打卡次数判断。
|
||||
"""
|
||||
rows: List[Dict[str, Any]] = []
|
||||
half_ots = [ot for ot in rest_overtime if _is_half_day_ot(ot)]
|
||||
logger.info("休息日半天加班 %d 条,逐一校验打卡(结合排班班段)", len(half_ots))
|
||||
|
||||
# 按工号缓存排班记录,避免重复请求
|
||||
shift_cache: Dict[str, List[Dict[str, Any]]] = {}
|
||||
|
||||
for ot in half_ots:
|
||||
code = str(_get(ot, "base_code")).strip()
|
||||
ot_date = _to_date_str(_get(ot, "OT_DATE", "ot_date"))
|
||||
if not code or not ot_date:
|
||||
continue
|
||||
try:
|
||||
kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode)
|
||||
except HRSessionExpiredError:
|
||||
# fetch_all_kq_data 内部已处理重登;此处兜底
|
||||
raise
|
||||
|
||||
# 拉取该员工排班(缓存),取加班日的班段
|
||||
if code not in shift_cache:
|
||||
shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode)
|
||||
shift_info = _extract_day_shift(shift_cache.get(code, []), ot_date)
|
||||
|
||||
p = _punch_analysis(kq)
|
||||
judge = _judge_punch_by_shift(p, shift_info)
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ot),
|
||||
"工号": code,
|
||||
"加班日期": ot_date,
|
||||
"加班天数": _get(ot, "ot_days", "sys_ot_days", "plan_ot_days", default="0.5"),
|
||||
"排班班次": shift_info["bc_name"],
|
||||
"排班班段时间": shift_info["bc_time"],
|
||||
"计划时段": f"{_get(ot, 'PLAN_START_TIME') or _get(ot, 'FINAL_START_TIME')} ~ "
|
||||
f"{_get(ot, 'PLAN_END_TIME') or _get(ot, 'FINAL_END_TIME')}",
|
||||
"上班打卡": p["first"],
|
||||
"下班打卡": p["last"],
|
||||
"打卡次数": p["count"],
|
||||
"判定": judge,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 检查3:整日请假 × 考勤异常 → 提示
|
||||
# ----------------------------------------------
|
||||
def check_full_day_leave_abnormal(abnormal_confirmed: List[Dict[str, Any]],
|
||||
abnormal_open: List[Dict[str, Any]],
|
||||
leaves: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。
|
||||
|
||||
异常并集 = 未调整(is_adjusted=0) + 已确认(is_adjusted=2)。
|
||||
"""
|
||||
rows: List[Dict[str, Any]] = []
|
||||
|
||||
# 整日请假日期索引 {(code, date): leave_rec}
|
||||
full_day_leave = _build_leave_set(leaves, need_full_day=True)
|
||||
if not full_day_leave:
|
||||
logger.info("无整日请假记录,检查3跳过")
|
||||
return rows
|
||||
|
||||
# 异常并集(同一员工同一日期可能同时有未调整/已确认,各自输出一条便于核查)
|
||||
for ab in list(abnormal_open) + list(abnormal_confirmed):
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = full_day_leave.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
is_adjusted = str(ab.get("is_adjusted", ""))
|
||||
status = "确认异常" if is_adjusted == "2" else ("未调整" if is_adjusted == "0" else "异常")
|
||||
hint = f"该员工{work_day}考勤状态存在异常"
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"请假日期": work_day,
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假天数": _get(leave_rec, "leave_days"),
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"班段": _shift_segment(ab),
|
||||
"异常状态": status,
|
||||
"提示": hint,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 7. 导出多 Sheet Excel 报告
|
||||
# ----------------------------------------------
|
||||
def export_report(results: Dict[str, List[Dict[str, Any]]], save_dir: str, month_str: str) -> str:
|
||||
"""将三项检查结果导出为多 Sheet Excel 报告。
|
||||
|
||||
Sheet 顺序:汇总 -> 检查1 -> 检查2 -> 检查3(无数据的 Sheet 也保留表头便于对照)。
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"月考勤异常三查_{month_str}_{ts}.xlsx"))
|
||||
|
||||
sheet_cfg = [
|
||||
("检查1_确认异常有请假", "check1", [
|
||||
"员工姓名", "工号", "考勤日期", "异常类型", "请假类型", "请假起止", "问题说明"]),
|
||||
("检查2_休息日半天打卡", "check2", [
|
||||
"员工姓名", "工号", "加班日期", "加班天数", "排班班次", "排班班段时间", "计划时段",
|
||||
"上班打卡", "下班打卡", "打卡次数", "判定"]),
|
||||
("检查3_整日请假有异常", "check3", [
|
||||
"员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "班段",
|
||||
"异常状态", "提示"]),
|
||||
]
|
||||
|
||||
c1 = results.get("check1", [])
|
||||
c2 = results.get("check2", [])
|
||||
c3 = results.get("check3", [])
|
||||
|
||||
# 汇总行
|
||||
summary = [
|
||||
{"检查项": "检查1:确认异常日期存在请假流程", "条数": len(c1)},
|
||||
{"检查项": "检查2:休息日半天加班打卡校验", "条数": len(c2)},
|
||||
{"检查项": "检查3:整日请假当日仍有考勤异常", "条数": len(c3)},
|
||||
]
|
||||
summary[1]["备注"] = "「判定」列中 漏打卡 需人工复核"
|
||||
summary[0]["备注"] = "可能为「提前确认后请假」仍为异常"
|
||||
|
||||
try:
|
||||
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
for sheet_name, key, cols in sheet_cfg:
|
||||
data = results.get(key, [])
|
||||
df = pd.DataFrame(data, columns=cols)
|
||||
df.to_excel(writer, sheet_name=sheet_name, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("月考勤异常三查完成:检查1=%d 条,检查2=%d 条,检查3=%d 条",
|
||||
len(c1), len(c2), len(c3))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 8. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def handle_abnormal_check(save_dir: str = None, month: str = None) -> str:
|
||||
"""执行月考勤异常三项检查并导出 Excel 报告,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月,
|
||||
不传则按「当月 1 日 至 今天」查询。
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = build_hr_session()
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
month_str = month
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
month_str = date.today().strftime("%Y-%m")
|
||||
|
||||
data = _fetch_all_data(session, user_id, treecode, begin, end)
|
||||
|
||||
# 请假索引(全部请假,供检查1判断日期是否有请假流程)
|
||||
leave_index = _build_leave_set(data["leaves"], need_full_day=False)
|
||||
|
||||
# 检查1
|
||||
c1 = check_leave_after_confirm(data["abnormal_confirmed"], leave_index)
|
||||
logger.info("检查1(确认异常有请假):命中 %d 条", len(c1))
|
||||
for r in c1:
|
||||
logger.warning("【检查1】%s %s 考勤日期 %s,异常:%s,请假:%s",
|
||||
r["员工姓名"], r["工号"], r["考勤日期"], r["异常类型"], r["请假类型"])
|
||||
|
||||
# 检查2
|
||||
c2 = check_rest_day_half_day_punch(session, user_id, treecode,
|
||||
data["rest_overtime"], begin, end)
|
||||
logger.info("检查2(休息日半天打卡):校验 %d 条", len(c2))
|
||||
for r in c2:
|
||||
if "漏打卡" in r["判定"]:
|
||||
logger.warning("【检查2】%s %s %s 加班半天,%s",
|
||||
r["员工姓名"], r["工号"], r["加班日期"], r["判定"])
|
||||
|
||||
# 检查3
|
||||
c3 = check_full_day_leave_abnormal(
|
||||
data["abnormal_confirmed"], data["abnormal_open"], data["leaves"])
|
||||
logger.info("检查3(整日请假有异常):命中 %d 条", len(c3))
|
||||
for r in c3:
|
||||
logger.warning("【检查3】%s %s %s:%s(异常:%s / %s)",
|
||||
r["员工姓名"], r["工号"], r["请假日期"], r["提示"],
|
||||
r["异常类型"], r["异常状态"])
|
||||
|
||||
return export_report({"check1": c1, "check2": c2, "check3": c3}, save_dir, month_str)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = handle_abnormal_check(save_dir, month)
|
||||
logger.info("===== 月考勤异常三查完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return
|
||||
logger.error("月考勤异常三查失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,454 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: attendance_abnormal.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-10
|
||||
@Description: 考勤异常查询与导出:通过员工基础信息接口(getCurUserInfo)校验 cookies 有效性,
|
||||
再调用考勤异常接口分页拉取【本月(1 号查上月,否则当月)】全部考勤异常数据,导出为 Excel;
|
||||
并按规则分级处理:轻微异常(迟到/早退 <30 分钟)整月自动确认;需推送的(迟到/早退 >=30 分钟,
|
||||
或其他类型异常)仅上周(周一~周日)向对应员工推送钉钉核实通知;
|
||||
仅推送 first_type_name 含「职能」的人员,且按「姓名-工号」合并为一人一条,减少推送次数。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可查询本月(1 号查上月,否则当月)考勤异常并导出 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_cur_user_info,
|
||||
fetch_all_attendance_abnormal,
|
||||
adjust_abnormal,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\考勤异常"
|
||||
# 推送记录保存目录(按场景传入,不写死;空串=不记录)
|
||||
PUSH_RECORD_DIR = os.path.join(SAVE_DIR, "推送记录")
|
||||
# 自动确认总开关(默认启用:整月轻微异常直接批量确认;置 "false" 关闭仅统计不执行)
|
||||
AUTO_CONFIRM_ENABLED = "true"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供的考勤异常字段,其余字段保留原样)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"abnormal_id": "异常ID",
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"base_code": "工号",
|
||||
"first_type_name": "职位序列",
|
||||
"work_day": "考勤日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"abnormal_minute": "异常时长(分钟)",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面,其余字段自动排在后面)
|
||||
SHOW_ORDER = [
|
||||
"异常ID", "员工姓名", "工号", "职位序列", "考勤日期", "班次", "异常类型", "异常时长(分钟)", "处理方式",
|
||||
]
|
||||
|
||||
# 考勤异常调整状态过滤(本次只查询「未调整」)
|
||||
# 0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
IS_ADJUSTED = "0"
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 查询范围(默认整月:1 号查上月,否则当月;推送仍按上周一~上周日)
|
||||
# ----------------------------------------------
|
||||
def last_week_range(today: date = None) -> tuple:
|
||||
"""返回上周(周一~周日)的查询日期范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
上周定义:本周一往前推 7 天为上周一,上周一 + 6 天为上周日。
|
||||
"""
|
||||
today = today or date.today()
|
||||
this_monday = today - timedelta(days=today.weekday()) # 本周一
|
||||
last_monday = this_monday - timedelta(days=7)
|
||||
last_sunday = this_monday - timedelta(days=1)
|
||||
return last_monday.strftime("%Y-%m-%d"), last_sunday.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def query_month(today: date = None) -> str:
|
||||
"""本次查询月份:1 号(2 号之前,不含 2 号)查上月,否则查当月。
|
||||
|
||||
当月数据过少(仅 1 天)时补处理上月整月;2 号及以后按当月处理。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day < 2:
|
||||
first_of_this_month = today.replace(day=1)
|
||||
return (first_of_this_month - timedelta(days=1)).strftime("%Y-%m")
|
||||
return today.strftime("%Y-%m")
|
||||
|
||||
|
||||
def in_last_week(item: dict, push_begin: str, push_end: str) -> bool:
|
||||
"""判断异常记录(按 work_day)是否落在上周范围内;work_day 缺失时返回 False。"""
|
||||
work_day = str(item.get("work_day") or "")[:10]
|
||||
return bool(work_day) and push_begin <= work_day <= push_end
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. cookies 有效性校验(员工基础信息接口)
|
||||
# ----------------------------------------------
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。
|
||||
若登录态过期则重新登录并重建会话后重试。
|
||||
"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return session, user_id, treecode
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出当月考勤异常 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data: List[dict], save_dir: str, month_str: str) -> str:
|
||||
"""将考勤异常数据映射为中文、调整列顺序并导出 .xlsx。"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
# 处理方式:轻微异常(自动确认)/ 需核实(钉钉推送)
|
||||
df["处理方式"] = df.apply(
|
||||
lambda r: "自动确认" if not classify_abnormal(r) else "钉钉推送", axis=1
|
||||
)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
# 文件名加时间戳,避免同名文件被占用导致 PermissionError
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤异常_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("考勤异常数据:%d 条", len(data))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 筛选 + 钉钉推送(按姓名)
|
||||
# ----------------------------------------------
|
||||
def classify_abnormal(item: dict) -> bool:
|
||||
"""判断该条异常是否需要钉钉推送。
|
||||
|
||||
规则(需求):
|
||||
- 迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常);
|
||||
- 迟到/早退 且 异常时长 >= 30 分钟 → 推送;
|
||||
- 其他类型异常(旷工/工时不足/漏打卡等)→ 推送。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item: dict) -> bool:
|
||||
"""判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
|
||||
|
||||
def build_notify_text(items: List[dict]) -> str:
|
||||
"""按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。
|
||||
|
||||
每条异常保留原确认行格式:按实际异常类型动态生成;
|
||||
迟到/早退会在确认项前附上分钟数。
|
||||
"""
|
||||
first = items[0]
|
||||
lines = [
|
||||
"【考勤异常核实通知】",
|
||||
f"姓名:{first.get('STAFF_NAME', '')}",
|
||||
f"工号:{first.get('base_code', '')}",
|
||||
f"共 {len(items)} 条考勤异常,请逐条确认:",
|
||||
]
|
||||
for idx, item in enumerate(items, 1):
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute")
|
||||
# 迟到/早退 附上分钟数
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute not in ("", None):
|
||||
confirm_item = f"{abnormal}{minute}分钟"
|
||||
else:
|
||||
confirm_item = abnormal
|
||||
lines.append(
|
||||
f"{idx}. 考勤日期:{item.get('work_day', '')}|班次:{item.get('bc_name', '')}"
|
||||
f"|异常类型:{abnormal}|异常时长:{minute}分钟"
|
||||
)
|
||||
lines.append(f" 请确认本次{confirm_item}真实情况:{abnormal}/漏打卡/外出/其他")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def push_abnormal(items: List[dict]) -> int:
|
||||
"""按「姓名-工号」分组生成钉钉通知文本并直接推送(app 版主脚本直接调用,无需全局变量)。
|
||||
|
||||
同一人员多条异常合并为一条通知,大幅减少推送次数。
|
||||
|
||||
Returns:
|
||||
成功推送的人员数(即推送次数)
|
||||
"""
|
||||
from app.utils.dingtalk_sender import send_to_person
|
||||
|
||||
groups: Dict[tuple, List[dict]] = {}
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
key = (name, it.get("base_code", "") or "")
|
||||
groups.setdefault(key, []).append(it)
|
||||
|
||||
for (_name, _code), group in groups.items():
|
||||
text = build_notify_text(group)
|
||||
send_to_person(_name, text=text, keyword=_code, record_dir=PUSH_RECORD_DIR)
|
||||
logger.info("已向 %s 推送考勤异常通知(%d 条合并)", _name, len(group))
|
||||
return len(groups)
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 内部抓取(供下载/处理共用)
|
||||
# ----------------------------------------------
|
||||
def _fetch_abnormal_data(month: str = None) -> tuple:
|
||||
"""校验会话、计算查询范围、拉取当月考勤异常数据。
|
||||
|
||||
Returns:
|
||||
(data, month_str):data 为异常明细列表,month_str 为查询月份 "YYYY-MM"
|
||||
"""
|
||||
session = build_hr_session()
|
||||
# 校验 cookies 有效性,并获取查询所需 user_id / treecode
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
# 计算查询范围:默认整月(1 号查上月,否则当月)
|
||||
month = month or query_month()
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
month_str = month
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s(%s 整月),调整状态:%s =====",
|
||||
begin, end, month, IS_ADJUSTED or "所有")
|
||||
|
||||
data = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED
|
||||
)
|
||||
return data, month_str
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def confirm_abnormal(abnormal_ids, type_code: int = 1, session=None):
|
||||
"""确认/调整考勤异常单据(按 abnormal_id 唯一编号)。
|
||||
|
||||
Args:
|
||||
abnormal_ids: 异常单据 id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(默认)
|
||||
session: 已登录会话;为空时自动构建并校验
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
"""
|
||||
if session is None:
|
||||
session = build_hr_session()
|
||||
session, _, _ = _validate_session(session)
|
||||
return adjust_abnormal(session, abnormal_ids, type_code)
|
||||
|
||||
|
||||
def is_mild_abnormal(item: dict) -> bool:
|
||||
"""轻微异常:迟到/早退 且 异常时长 < 30 分钟(自动确认范围,不分职能序列)。"""
|
||||
return not classify_abnormal(item)
|
||||
|
||||
|
||||
def auto_confirm_mild(data, session=None) -> int:
|
||||
"""自动确认轻微异常(迟到/早退 < 30 分钟,不分职能序列)。
|
||||
|
||||
Args:
|
||||
data: 未调整考勤异常记录列表
|
||||
session: 已登录会话;为空时自动构建并校验
|
||||
|
||||
Returns:
|
||||
确认成功的条数
|
||||
"""
|
||||
mild = [it for it in data if is_mild_abnormal(it) and it.get("abnormal_id")]
|
||||
if not mild:
|
||||
logger.info("无轻微异常(迟到/早退<30分钟),跳过自动确认")
|
||||
return 0
|
||||
ids = [it["abnormal_id"] for it in mild]
|
||||
logger.info("自动确认轻微异常 %d 条(不分职能序列)", len(ids))
|
||||
result = confirm_abnormal(ids, session=session)
|
||||
if result.get("state") == "1":
|
||||
logger.info("自动确认接口返回处理成功,共 %d 条", len(ids))
|
||||
return len(ids)
|
||||
logger.error("自动确认失败:%s", result.get("meg") or result)
|
||||
return 0
|
||||
|
||||
|
||||
def build_group_summary(total_count: int, mild_count: int, confirmed_count: int,
|
||||
non_func_count: int, func_count: int, push_count: int,
|
||||
other_count: int, month: str, begin: str, end: str) -> str:
|
||||
"""生成考勤异常处理条数汇总消息(与汇总日志格式一致)。"""
|
||||
return (
|
||||
"【考勤异常处理汇总】\n"
|
||||
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n"
|
||||
f"考勤异常总数:{total_count} 条\n"
|
||||
f"直接处理(轻微,整月自动确认):{mild_count} 条,确认成功 {confirmed_count} 条\n"
|
||||
f"待通知(职能,上周):{func_count} 条,合并为 {push_count} 条推送\n"
|
||||
f"上周非职能(不推送):{non_func_count} 条\n"
|
||||
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
|
||||
)
|
||||
|
||||
|
||||
def download_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
"""查询当月考勤异常并导出 Excel,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM";默认本月(1 号查上月,否则当月)
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
data, month_str = _fetch_abnormal_data(month)
|
||||
if not data:
|
||||
logger.info("本月(%s)无考勤异常数据", month_str)
|
||||
return None
|
||||
return export_excel(data, save_dir, month_str)
|
||||
|
||||
|
||||
def handle_attendance_abnormal(save_dir: str = None, month: str = None) -> str:
|
||||
"""查询当月考勤异常,导出 Excel,并按要求向钉钉推送需核实的异常。
|
||||
|
||||
规则:轻微异常(迟到/早退 < 30 分钟)整月自动确认;需推送的仅上周(周一~周日)
|
||||
严重异常,且仅推送 first_type_name 含「职能」的人员,按「姓名-工号」合并为一人一条。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM";默认本月(1 号查上月,否则当月)
|
||||
|
||||
Returns:
|
||||
导出文件路径(无数据时返回 None)
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
data, month_str = _fetch_abnormal_data(month)
|
||||
if not data:
|
||||
logger.info("本月(%s)无考勤异常数据,跳过导出与推送", month_str)
|
||||
return None
|
||||
|
||||
path = export_excel(data, save_dir, month_str)
|
||||
|
||||
# 分级分类:轻微异常整月自动确认;需推送的仅上周(周一~周日)严重异常
|
||||
mild_list = [it for it in data if not classify_abnormal(it)]
|
||||
push_begin, push_end = last_week_range()
|
||||
push_list = [it for it in data if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
|
||||
other_list = [it for it in data if classify_abnormal(it) and not in_last_week(it, push_begin, push_end)]
|
||||
logger.info("考勤异常共 %d 条:轻微整月自动确认 %d 条,上周需推送 %d 条,其他严重仅留痕 %d 条",
|
||||
len(data), len(mild_list), len(push_list), len(other_list))
|
||||
|
||||
# 自动确认轻微异常(整月,迟到/早退<30分钟,不分职能序列)——总开关 AUTO_CONFIRM_ENABLED 控制
|
||||
# 统计不受开关影响:始终按数据计算实际条数(开关只决定是否真正调用确认接口)
|
||||
mild_count = len([it for it in mild_list if it.get("abnormal_id")])
|
||||
if AUTO_CONFIRM_ENABLED:
|
||||
confirmed_count = auto_confirm_mild(mild_list)
|
||||
else:
|
||||
confirmed_count = 0
|
||||
logger.info("自动确认未启用(AUTO_CONFIRM_ENABLED!=true),仅统计待自动确认 %d 条,未执行确认", mild_count)
|
||||
|
||||
# 只推送「职能」序列(first_type_name 含「职能」),并按 姓名-工号 合并推送
|
||||
func_list = [it for it in push_list if is_func_staff(it)]
|
||||
non_func_list = [it for it in push_list if not is_func_staff(it)]
|
||||
if func_list:
|
||||
push_count = push_abnormal(func_list)
|
||||
else:
|
||||
push_count = 0
|
||||
logger.info("无需推送的异常,跳过钉钉通知")
|
||||
logger.info("处理条数汇总:%s",
|
||||
build_group_summary(len(data), mild_count, confirmed_count, len(non_func_list),
|
||||
len(func_list), push_count, len(other_list), month_str,
|
||||
push_begin, push_end))
|
||||
|
||||
# ---- 最终统计汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤异常处理汇总】")
|
||||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||||
logger.info(" 直接处理(轻微,整月自动确认):%d 条,确认成功 %d 条", mild_count, confirmed_count)
|
||||
logger.info(" 待通知(职能,上周):%d 条,合并为 %d 条推送", len(func_list), push_count)
|
||||
logger.info(" 上周非职能(不推送):%d 条", len(non_func_list))
|
||||
logger.info(" 本月其他严重异常(非上周,仅导出留痕):%d 条", len(other_list))
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
return path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = handle_attendance_abnormal(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:本月无数据 =====")
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
# 文件被 Excel 占用:只提醒关闭后重试,不抛堆栈
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return
|
||||
logger.error("考勤异常处理失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,162 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: attendance_stat_export.py
|
||||
@Description: 考勤统计报表逐日出勤导出:
|
||||
调用「考勤统计报表」接口分页抓取某月全集团数据(每人一行,含 v_1~v_最后一天),
|
||||
导出 Excel,列为「工号/姓名/部门/岗位 + 1日~最后一日」(默认上月,可按参数指定月份)。
|
||||
底层复用:hr_api.attendance_stat(报表抓取)、hr_session(会话管理)。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 从项目根目录用模块方式运行(依赖打包为 app 包):
|
||||
python -m app.service.hrbp.ehr.attendance.attendance_stat_export
|
||||
2. 可选参数:<保存目录> <月份 YYYYMM>(默认上月)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import fetch_all_attendance_stat
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError, refresh_hr_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\考勤统计"
|
||||
|
||||
# 身份信息列(对应报文 datas 里的字段)
|
||||
IDENTITY_COLS: List[Dict[str, str]] = [
|
||||
{"key": "base_code", "title": "工号"},
|
||||
{"key": "staff_name", "title": "姓名"},
|
||||
{"key": "dept_org_name", "title": "部门"},
|
||||
{"key": "post_name", "title": "岗位"},
|
||||
]
|
||||
|
||||
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质(None、浮点 .0 尾缀)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def last_month_ym(today: date = None) -> str:
|
||||
"""返回上月月份 "YYYYMM"。"""
|
||||
today = today or date.today()
|
||||
this_first = today.replace(day=1)
|
||||
last_end = this_first - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
def _build_rows(records: List[Dict], days_in_month: int) -> List[Dict]:
|
||||
"""把报表 datas 转成导出行:身份信息 + 1日~最终日(v_1~v_N),缺失留空。"""
|
||||
rows: List[Dict] = []
|
||||
for rec in records:
|
||||
row = {item["title"]: _clean(rec.get(item["key"])) for item in IDENTITY_COLS}
|
||||
for day in range(1, days_in_month + 1):
|
||||
row[f"{day}日"] = _clean(rec.get(f"v_{day}"))
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def export_month_attendance(save_dir: str = None, month: str = None) -> str:
|
||||
"""导出某月考勤统计逐日出勤 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYYMM"(默认上月)
|
||||
|
||||
Returns:
|
||||
导出文件路径
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
if not month:
|
||||
month = last_month_ym()
|
||||
year, mon = int(month[:4]), int(month[4:6])
|
||||
days_in_month = calendar.monthrange(year, mon)[1]
|
||||
logger.info("===== 考勤统计报表导出,月份:%s(%d 天) =====", month, days_in_month)
|
||||
|
||||
# 1. 会话校验 + 取当前用户 userId
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError(f"getCurUserInfo 未返回 userId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s", user_id)
|
||||
|
||||
# 2. 分页抓取全集团考勤统计报表明细
|
||||
records = fetch_all_attendance_stat(session, user_id, month)
|
||||
logger.info("考勤统计报表共 %d 人", len(records))
|
||||
if not records:
|
||||
logger.error("考勤统计报表无数据,请检查月份或权限")
|
||||
return ""
|
||||
|
||||
# 3. 组装导出行并输出 Excel
|
||||
columns = [item["title"] for item in IDENTITY_COLS] + [f"{d}日" for d in range(1, days_in_month + 1)]
|
||||
rows = _build_rows(records, days_in_month)
|
||||
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤统计报表_{month}_{ts}.xlsx"))
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
|
||||
df = pd.DataFrame(rows, columns=columns)
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
|
||||
logger.info("导出明细:%d 人 × %d 列", len(rows), len(columns))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤统计报表汇总】")
|
||||
logger.info(" 月份:%s", month)
|
||||
logger.info(" 人数:%d 人", len(rows))
|
||||
logger.info(" 导出文件:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
# 参数:<保存目录> <月份 YYYYMM>
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = export_month_attendance(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤统计报表导出完成 =====")
|
||||
except Exception as e: # noqa: BLE001
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可。")
|
||||
return
|
||||
logger.error("考勤统计报表导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||
"""
|
||||
@@ -1,164 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: common_query.py
|
||||
@Description: HR 前端查询参数 commonQuery 的加密/解密(自定义 Base64 + 盐值 + 首尾重排,
|
||||
与前端 encodeURIComponent + JSON.stringify 行为完全一致,已通过抓包串回环验证)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
PAD_CHAR = '7' # 填充字符(索引64)
|
||||
SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
# 反向映射表(解码用)
|
||||
CUSTOM_REV = {ch: idx for idx, ch in enumerate(CUSTOM_CHARS)}
|
||||
|
||||
|
||||
# ---------- 自定义 Base64 编码 ----------
|
||||
def custom_base64_encode(data: bytes) -> str:
|
||||
"""
|
||||
使用自定义字符表进行 Base64 编码。
|
||||
data: 已 UTF-8 编码的字节序列
|
||||
返回: 编码后的字符串(填充使用 '7')
|
||||
"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(CUSTOM_CHARS[enc1])
|
||||
result.append(CUSTOM_CHARS[enc2])
|
||||
result.append(CUSTOM_CHARS[enc3])
|
||||
result.append(CUSTOM_CHARS[enc4])
|
||||
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
# ---------- 自定义 Base64 解码 ----------
|
||||
def custom_base64_decode(s: str) -> bytes:
|
||||
"""
|
||||
使用自定义字符表解码 Base64 字符串。
|
||||
返回原始 UTF-8 字节序列。
|
||||
"""
|
||||
# 过滤掉不属于字符表的字符(与前端一致)
|
||||
filtered = ''.join(ch for ch in s if ch in CUSTOM_REV)
|
||||
result = []
|
||||
for i in range(0, len(filtered), 4):
|
||||
chunk = filtered[i:i + 4]
|
||||
# 补足4个字符(使用填充字符'7')
|
||||
while len(chunk) < 4:
|
||||
chunk += PAD_CHAR
|
||||
enc1 = CUSTOM_REV[chunk[0]]
|
||||
enc2 = CUSTOM_REV[chunk[1]]
|
||||
enc3 = CUSTOM_REV[chunk[2]]
|
||||
enc4 = CUSTOM_REV[chunk[3]]
|
||||
|
||||
b1 = ((enc1 << 2) | (enc2 >> 4)) & 0xFF
|
||||
b2 = ((enc2 << 4) | (enc3 >> 2)) & 0xFF
|
||||
b3 = ((enc3 << 6) | enc4) & 0xFF
|
||||
|
||||
result.append(b1)
|
||||
if enc3 != 64:
|
||||
result.append(b2)
|
||||
if enc4 != 64:
|
||||
result.append(b3)
|
||||
return bytes(result)
|
||||
|
||||
|
||||
# ---------- 加密(编码)----------
|
||||
def encode_common_query(query_list: list) -> str:
|
||||
"""
|
||||
将查询条件列表(Python 对象)加密为 commonQuery 字符串。
|
||||
参数 query_list: 与前端格式一致的列表,例如:
|
||||
[
|
||||
{"queryField": "`pt_organzation.IN_USE`", ...},
|
||||
...
|
||||
]
|
||||
返回: 加密后的字符串(可直接用于表单提交)
|
||||
"""
|
||||
# 1. 转为 JSON 字符串(无空格,与前端 JSON.stringify 一致)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
# 2. URI 编码(模拟 encodeURIComponent:不编码 ! ' ( ) * - . _ ~)
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 转为 UTF-8 字节
|
||||
utf8_bytes = uri_encoded.encode('utf-8')
|
||||
# 4. 自定义 Base64 编码
|
||||
base64_str = custom_base64_encode(utf8_bytes)
|
||||
# 5. 追加盐值
|
||||
en_str = base64_str + SALT
|
||||
# 6. 重排:前2位 + 后3位 + 中间部分
|
||||
first = en_str[:2]
|
||||
second = en_str[2:-3]
|
||||
third = en_str[-3:]
|
||||
return first + third + second
|
||||
|
||||
|
||||
# ---------- 解密(解码)----------
|
||||
def decode_common_query(encrypted: str) -> list:
|
||||
"""
|
||||
将加密的 commonQuery 字符串还原为原始查询条件列表。
|
||||
参数 encrypted: 加密后的字符串
|
||||
返回: 原始的查询条件列表(Python 对象)
|
||||
"""
|
||||
# 1. 逆向重排:前2位 + 中间部分 + 后3位
|
||||
first = encrypted[:2]
|
||||
third = encrypted[2:5]
|
||||
second = encrypted[5:]
|
||||
orgin = first + second + third
|
||||
# 2. 去除盐值
|
||||
if orgin.endswith(SALT):
|
||||
orgin = orgin[:-len(SALT)]
|
||||
else:
|
||||
# 容错:如果盐值不完整,尝试匹配前缀(有时末尾会缺失几个字符)
|
||||
if orgin.endswith(SALT[:-3]):
|
||||
orgin = orgin[:-(len(SALT) - 3)]
|
||||
# 3. 自定义 Base64 解码
|
||||
utf8_bytes = custom_base64_decode(orgin)
|
||||
uri_encoded = utf8_bytes.decode('utf-8')
|
||||
# 4. URI 解码
|
||||
json_str = urllib.parse.unquote(uri_encoded)
|
||||
# 5. 解析 JSON
|
||||
return json.loads(json_str)
|
||||
|
||||
|
||||
# ---------- 辅助函数 ----------
|
||||
def build_condition(
|
||||
query_field: str,
|
||||
query_type: str,
|
||||
query_value: str,
|
||||
query_text: str = "",
|
||||
left_bracket: str = "",
|
||||
right_bracket: str = "",
|
||||
logic: str = "AND",
|
||||
input_type: str = "text",
|
||||
) -> dict:
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:40
|
||||
@Description: HR 系统配置,集中管理接口地址、分页大小等常量(供各业务模块复用)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.ehr.common.common_query import build_condition, encode_common_query
|
||||
|
||||
# ---------- 银行卡(工资卡)信息查询接口 ----------
|
||||
# 分页查询工资卡信息(aa.md 提供),返回 JSON
|
||||
WAGE_CARD_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
|
||||
# 单页最大抓取条数
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口 ----------
|
||||
BANK_DICT_URL = "https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
|
||||
# ---------- 员工花名册(自定义导出)页面 ----------
|
||||
# 花名册自定义导出页面
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=员工花名册"
|
||||
|
||||
# 待增减人员操作页面
|
||||
ADD_SUB_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/getCustomCommonList.mc?menuName=待增减人员"
|
||||
|
||||
# 预入职台账(排班异常识别)自定义导出页面(aa.md 提供)
|
||||
PRE_ENTRY_ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-07406&nworktoday-40175-24311|/RedseaPlatform/hrRoster/10fe9cd6-b094-11ea-b588-14187743d052/getCustomCommonList.mc?_t=1787581570094&clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=预入职台账&_t=1787581570094"
|
||||
|
||||
# 调动台账(排班异常识别)自定义导出页面(aa.md 提供)
|
||||
TRANSFER_ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-39687&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1123d951-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E8%B0%83%E5%8A%A8%E5%8F%B0%E8%B4%A6"
|
||||
|
||||
# 花名册自定义导出模板(下拉框中全部模板,后续各业务场景可按需选用)
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息" # 默认模板
|
||||
ROSTER_TEMPLATE_CADRE_SELECT = "干部选拔信息" # 干部选拔
|
||||
ROSTER_TEMPLATE_INDIVIDUAL_TAX = "个税申报基础信息" # 个税申报
|
||||
ROSTER_TEMPLATE_EMPLOYER_INSURANCE = "雇主险增减员导出模板" # 雇主险增减员
|
||||
ROSTER_TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出" # 排班异常识别(预入职台账)
|
||||
|
||||
# ---------- 考勤异常查询接口 ----------
|
||||
# 获取当前用户信息(用于校验 cookies 有效性,并取得查询考勤异常所需的 userId / rootId(treecode))
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
# 分页查询考勤异常(aa.md 提供)
|
||||
ATTENDANCE_ABNORMAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 考勤异常确认/调整接口(abnormalIds=异常单据id,type=1 表示自动确认)
|
||||
ATTENDANCE_ADJUST_URL = "https://hr.37du.co/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
|
||||
# 查询排班接口
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
|
||||
# 按部门查询排班集合接口(aa.md 提供):org_name=部门名,返回该部门全部排班
|
||||
# (data.list 记录含 work_date_name 排班名、org_name 部门名,逐条记录 = 一个排班)
|
||||
WORK_DATE_QUERY_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_s_kq_work_date_query/redApiExec.mc"
|
||||
|
||||
# 查询请假记录接口
|
||||
LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询加班记录接口
|
||||
OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询打卡记录接口
|
||||
KQ_DATA_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# ---------- 考勤统计报表(逐日出勤,aa.md 提供) ----------
|
||||
# 分页查询"考勤统计报表",每人一行含 v_1~v_最后一天(当月逐日出勤状态),返回 JSON
|
||||
MONTH_ATT_REPORT_URL = "https://hr.37du.co/RedseaPlatform/pt/report/excel/detail/getPageAjax.mc"
|
||||
MONTH_ATT_REPORT_ID = "f880c52a619446e0b74e3820b898d53b"
|
||||
# 集团根组织 struId(aa.md 中 struId / belongUnitStruId / ds1.struId / ds2.stru_id 共用)
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
|
||||
# ---------- 组织维护(组织设置)查询接口(aa.md 提供) ----------
|
||||
# 组织维护台账实时数据查询,返回 JSON(count/datas/pageCount)
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由前端加密算法自构造(等价于抓包原始串,即 in_use in ('1') 条件),
|
||||
# 需要追加/修改查询条件时直接改 ORG_QUERY_CONDITIONS 后重新加密即可
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"belongUnitStruId": COMPANY_STRU_ID,
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 员工花名册(实时数据查询接口,纯 API 版) ----------
|
||||
# 花名册台账实时数据查询(与组织维护 queryRealTimeData 同模式),返回 JSON(count/datas/pageCount)
|
||||
ROSTER_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ROSTER_TABLE_ID = "assemble-hr_staff_base"
|
||||
ROSTER_ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
|
||||
# 花名册查询默认条件(等价抓包串:主职 in (1) + 在职状态 in (1),即「在职主职在职人员」),
|
||||
# 需要查离职等其它状态时在调用方覆盖 conditions
|
||||
ROSTER_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ROSTER_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": ROSTER_TABLE_ID,
|
||||
"rosterId": ROSTER_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"belongUnitStruId": COMPANY_STRU_ID,
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# 假期类型编码映射已上移到 HR 平台共享层 app/service/hrbp/common/config.py(VACATION_TYPE_MAP),
|
||||
# 由 ehr / oa 两系统统一引用,避免 oa 反向依赖 ehr。需要时从此处 import:
|
||||
# from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
@@ -1,88 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: hr_api/__init__.py
|
||||
@Description: HR 系统 API 包,按接口拆分到各子模块,此处统一导出(保持 from ...hr_api import X 兼容)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, _is_expired, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.wage_card import fetch_wage_card_page, fetch_all_wage_card
|
||||
from app.service.hrbp.ehr.common.hr_api.bank_dict import get_bank_dict, bank_type_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import (
|
||||
fetch_cur_user_info,
|
||||
fetch_attendance_abnormal_page,
|
||||
fetch_all_attendance_abnormal,
|
||||
adjust_abnormal,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_shift_page, fetch_all_shift, fetch_work_date_page, fetch_all_work_date
|
||||
from app.service.hrbp.ehr.common.hr_api.leave import fetch_leave_page, fetch_all_leave
|
||||
from app.service.hrbp.ehr.common.hr_api.overtime import fetch_overtime_page, fetch_all_overtime
|
||||
from app.service.hrbp.ehr.common.hr_api.kq_data import fetch_kq_data_page, fetch_all_kq_data
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import (
|
||||
fetch_attendance_stat_page,
|
||||
fetch_all_attendance_stat,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.org import fetch_org_page, fetch_all_orgs, to_org_rows
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
fetch_roster_page,
|
||||
fetch_all_rosters,
|
||||
to_roster_rows,
|
||||
build_leave_conditions,
|
||||
build_in_service_conditions,
|
||||
fetch_roster_code_dicts,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.code_dict import get_code_dicts, code_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_export import export_common_list, export_roster_excel
|
||||
|
||||
__all__ = [
|
||||
# base
|
||||
"HRSessionExpiredError",
|
||||
"_is_expired",
|
||||
"hr_request_json",
|
||||
# wage_card
|
||||
"fetch_wage_card_page",
|
||||
"fetch_all_wage_card",
|
||||
# bank_dict
|
||||
"get_bank_dict",
|
||||
"bank_type_to_name",
|
||||
# attendance
|
||||
"fetch_cur_user_info",
|
||||
"fetch_attendance_abnormal_page",
|
||||
"fetch_all_attendance_abnormal",
|
||||
"adjust_abnormal",
|
||||
# shift
|
||||
"fetch_shift_page",
|
||||
"fetch_all_shift",
|
||||
"fetch_work_date_page",
|
||||
"fetch_all_work_date",
|
||||
# leave
|
||||
"fetch_leave_page",
|
||||
"fetch_all_leave",
|
||||
# overtime
|
||||
"fetch_overtime_page",
|
||||
"fetch_all_overtime",
|
||||
# kq_data
|
||||
"fetch_kq_data_page",
|
||||
"fetch_all_kq_data",
|
||||
# attendance_stat
|
||||
"fetch_attendance_stat_page",
|
||||
"fetch_all_attendance_stat",
|
||||
# org
|
||||
"fetch_org_page",
|
||||
"fetch_all_orgs",
|
||||
"to_org_rows",
|
||||
# roster
|
||||
"fetch_roster_page",
|
||||
"fetch_all_rosters",
|
||||
"to_roster_rows",
|
||||
"build_leave_conditions",
|
||||
"build_in_service_conditions",
|
||||
"fetch_roster_code_dicts",
|
||||
# code_dict
|
||||
"get_code_dicts",
|
||||
"code_to_name",
|
||||
# roster_export
|
||||
"export_common_list",
|
||||
"export_roster_excel",
|
||||
]
|
||||
@@ -1,202 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: attendance.py
|
||||
@Description: 当前用户信息 + 考勤异常查询/确认接口
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
GET_CUR_USER_INFO_URL,
|
||||
ATTENDANCE_ABNORMAL_URL,
|
||||
ATTENDANCE_ADJUST_URL,
|
||||
PAGE_MAX_SIZE,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_cur_user_info(session) -> Dict[str, Any]:
|
||||
"""
|
||||
调用 getCurUserInfo 校验 cookies 有效性,并返回当前登录用户信息。
|
||||
|
||||
该接口同时返回查询考勤异常所需的 userId 与 rootId(treecode):
|
||||
- 正常返回 JSON(含 userId / rootId),说明 cookies 有效;
|
||||
- 返回登录页等非 JSON 内容,说明登录态过期。
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(含 userId / rootId 等字段)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def adjust_abnormal(
|
||||
session,
|
||||
abnormal_ids,
|
||||
type_code: int = 1,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
确认/调整考勤异常单据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(按接口约定)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
if isinstance(abnormal_ids, (list, tuple)):
|
||||
ids = ",".join(str(i) for i in abnormal_ids)
|
||||
else:
|
||||
ids = str(abnormal_ids)
|
||||
|
||||
params = {"abnormalIds": ids, "type": type_code}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(
|
||||
session,
|
||||
user_id: str,
|
||||
treecode: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
is_adjusted: str = "0",
|
||||
abnormal_type: str = "",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页考勤异常数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
|
||||
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"(当月)
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数
|
||||
is_adjusted: 调整状态过滤,0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
abnormal_type: 异常类型过滤,2=旷工类(旷工/上班旷工/下班旷工),空=全部
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": abnormal_type,
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(
|
||||
session,
|
||||
user_id: str,
|
||||
treecode: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
is_adjusted: str = "0",
|
||||
abnormal_type: str = "",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取指定日期范围内的全部考勤异常数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id / treecode: 由 getCurUserInfo 返回的 userId / rootId
|
||||
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
|
||||
is_adjusted: 调整状态过滤,0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
abnormal_type: 异常类型过滤,2=旷工类(旷工/上班旷工/下班旷工),空=全部
|
||||
|
||||
Returns:
|
||||
异常明细列表(接口 datas 字段内容)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
# 重新登录后需重新获取 user_id / treecode
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date, page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
@@ -1,145 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: attendance_stat.py
|
||||
@Description: 考勤统计报表(逐日出勤)查询接口:
|
||||
- fetch_attendance_stat_page:请求单页报表数据
|
||||
- fetch_all_attendance_stat:分页抓取某月全集团逐日出勤明细(每人一行,含 v_1~v_最后一天)
|
||||
- 登录态过期自动重登(复用 hr_session)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
MONTH_ATT_REPORT_URL,
|
||||
MONTH_ATT_REPORT_ID,
|
||||
COMPANY_STRU_ID,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 报表接口单页最大支持 1000 条(用户确认),全集团一次拉取即可减少翻页请求
|
||||
REPORT_PAGE_SIZE = 1000
|
||||
|
||||
|
||||
def fetch_attendance_stat_page(
|
||||
session,
|
||||
user_id: str,
|
||||
month: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = REPORT_PAGE_SIZE,
|
||||
stru_id: str = COMPANY_STRU_ID,
|
||||
base_code: str = "",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页"考勤统计报表"数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId(当前登录用户)
|
||||
month: 查询月份 "YYYYMM"
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数(单页最大 1000)
|
||||
stru_id: 集团根组织 struId,默认 COMPANY_STRU_ID
|
||||
base_code: 员工工号;非空时仅查该员工(用于跨月追溯单人查询)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为明细数组,pageCount 为总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = {
|
||||
"reportId": MONTH_ATT_REPORT_ID,
|
||||
"struId": stru_id,
|
||||
"start": (page_no - 1) * page_size,
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ds1.userId": user_id,
|
||||
"ds1.struId": stru_id,
|
||||
"ds1.month": month,
|
||||
"ds2.stru_id": stru_id,
|
||||
"ds3.month": "#ds1.month#",
|
||||
"orgTypeCode": "1",
|
||||
"rootId": "cq37du",
|
||||
"showSetField": "1",
|
||||
"menuName": "考勤统计报表",
|
||||
"treePermitType": "permit",
|
||||
"struTreeCode": "cq37du",
|
||||
"belongUnitStruId": stru_id,
|
||||
"isVirtual": "0",
|
||||
"isHistory": "undefined",
|
||||
"useSealTreeData": "0",
|
||||
"orgAlias": "集团",
|
||||
"commonQuery": "[]",
|
||||
"ds1.base_code": base_code,
|
||||
}
|
||||
url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
|
||||
return hr_request_json(session, "POST", url, params, "考勤统计报表")
|
||||
|
||||
|
||||
def fetch_all_attendance_stat(
|
||||
session,
|
||||
user_id: str,
|
||||
month: str,
|
||||
stru_id: str = COMPANY_STRU_ID,
|
||||
base_code: str = "",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取某月考勤统计报表明细(每人一行,含 v_1~v_最后一天)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
month: 查询月份 "YYYYMM"
|
||||
stru_id: 集团根组织 struId,默认 COMPANY_STRU_ID
|
||||
base_code: 员工工号;非空时仅查该员工(用于跨月追溯单人查询)
|
||||
|
||||
Returns:
|
||||
报表明细列表(接口 datas 字段内容)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤统计报表 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
# 重新登录后需重新获取当前用户 userId
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
user_id = fetch_cur_user_info(session).get("userId", "")
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤统计报表第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤统计报表无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤统计报表已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
@@ -1,121 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: bank_dict.py
|
||||
@Description: 银行字典接口(缓存 code -> 开卡银行 映射)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
BANK_DICT_URL,
|
||||
BANK_DICT_CODE_TYPE,
|
||||
BANK_DICT_EXPIRE_SEC,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
from app.service.hrbp.common.hr_session import build_hr_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录
|
||||
_BANK_DICT_CACHE_DIR = get_sessions_dir()
|
||||
BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json")
|
||||
BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json")
|
||||
|
||||
|
||||
def _fetch_bank_dict(session=None):
|
||||
"""远程调用接口获取银行字典,并写入本地缓存。
|
||||
|
||||
Returns:
|
||||
(list[dict], dict[code->name])
|
||||
"""
|
||||
if session is None:
|
||||
session = build_hr_session()
|
||||
payload = {
|
||||
"codeType": BANK_DICT_CODE_TYPE,
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp_json = hr_request_json(session, "POST", BANK_DICT_URL, payload, "银行字典", timeout=30)
|
||||
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
|
||||
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
|
||||
for item in raw_list]
|
||||
result_map = {item["code"]: item["name"] for item in result_list}
|
||||
|
||||
os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True)
|
||||
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_list, f, ensure_ascii=False, indent=2)
|
||||
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_map, f, ensure_ascii=False, indent=2)
|
||||
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
|
||||
return result_list, result_map
|
||||
|
||||
|
||||
def _load_bank_dict_cache():
|
||||
"""读取本地银行字典缓存,失败返回 (None, None)。"""
|
||||
try:
|
||||
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
|
||||
lst = json.load(f)
|
||||
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
|
||||
mp = json.load(f)
|
||||
return lst, mp
|
||||
except Exception as e:
|
||||
logger.warning("银行字典本地缓存读取失败:%s", e)
|
||||
return None, None
|
||||
|
||||
|
||||
def get_bank_dict(session=None, force_refresh: bool = False):
|
||||
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
|
||||
|
||||
Args:
|
||||
session: 可选的已登录 requests.Session;未提供时自动构建
|
||||
force_refresh: True 强制重新调用接口
|
||||
|
||||
Returns:
|
||||
(list版本, dict[code->name]版本)
|
||||
"""
|
||||
need_refresh = force_refresh
|
||||
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
|
||||
need_refresh = True
|
||||
else:
|
||||
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
|
||||
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
|
||||
need_refresh = True
|
||||
|
||||
if need_refresh:
|
||||
try:
|
||||
return _fetch_bank_dict(session)
|
||||
except Exception as e:
|
||||
logger.error("银行字典远程拉取失败:%s", e)
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is not None:
|
||||
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
return [], {}
|
||||
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is None:
|
||||
# 缓存异常时重新拉取
|
||||
return _fetch_bank_dict(session)
|
||||
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
|
||||
|
||||
def bank_type_to_name(bank_type, bank_map) -> str:
|
||||
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
|
||||
if bank_type is None:
|
||||
return ""
|
||||
if isinstance(bank_type, float):
|
||||
if bank_type != bank_type: # NaN
|
||||
return ""
|
||||
bank_type = str(int(bank_type))
|
||||
elif isinstance(bank_type, int):
|
||||
bank_type = str(bank_type)
|
||||
else:
|
||||
bank_type = str(bank_type).strip()
|
||||
return bank_map.get(bank_type, "")
|
||||
@@ -1,105 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: code_dict.py
|
||||
@FileName 备注: HR 平台通用数据字典接口(PtCodeTypeValue.mc),供各业务模块翻译编码字段。
|
||||
codeType 为「表名.字段名」格式(如 COMMON.SEX / WAGE.BANKTYPE),
|
||||
支持 codeType 参数逗号分隔批量查询;返回 {codeType: {code: [名称, ...]}}。
|
||||
本地缓存统一存放,默认 7 天过期(与 bank_dict 一致)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import BANK_DICT_URL
|
||||
from app.service.hrbp.common.hr_session import hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 字典缓存文件({codeType: {code: name}}),7 天过期
|
||||
_CODE_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60
|
||||
_CODE_DICT_FILE = os.path.join(get_sessions_dir(), "code_dicts.json")
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
"""读取本地字典缓存,异常返回空 dict。"""
|
||||
try:
|
||||
with open(_CODE_DICT_FILE, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_cache(maps: dict) -> None:
|
||||
"""写入本地字典缓存。"""
|
||||
os.makedirs(os.path.dirname(_CODE_DICT_FILE), exist_ok=True)
|
||||
with open(_CODE_DICT_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(maps, f, ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
def _parse_items(raw) -> dict:
|
||||
"""将接口返回的字典项转换为 {code: 名称}。
|
||||
|
||||
兼容两种返回形态:
|
||||
- list[dict]: [{"code": "1", "name": "男", ...}, ...]
|
||||
- dict: {"1": ["男", ...], ...}(键值对形态)
|
||||
"""
|
||||
if isinstance(raw, dict):
|
||||
return {str(code): (item[0] if isinstance(item, (list, tuple)) and item else "")
|
||||
for code, item in raw.items()}
|
||||
result = {}
|
||||
for item in raw or []:
|
||||
code = item.get("code", "")
|
||||
result[str(code)] = item.get("name", "")
|
||||
return result
|
||||
|
||||
|
||||
def get_code_dicts(session, code_types, force_refresh: bool = False) -> dict:
|
||||
"""批量获取数据字典(优先本地缓存,缺失/过期才请求接口)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
code_types: codeType 列表,如 ["COMMON.SEX", "COMMON.NATION"]
|
||||
force_refresh: True 强制重新请求接口刷新
|
||||
|
||||
Returns:
|
||||
{codeType: {code: 名称}} 字典(未命中的 codeType 值为空 dict)
|
||||
"""
|
||||
cache = {} if force_refresh else _load_cache()
|
||||
need = [ct for ct in code_types
|
||||
if ct not in cache or not isinstance(cache.get(ct), dict)]
|
||||
|
||||
# 缓存命中校验:文件整体过期时间(mtime)
|
||||
if need and not force_refresh and os.path.exists(_CODE_DICT_FILE):
|
||||
if time.time() - os.path.getmtime(_CODE_DICT_FILE) <= _CODE_DICT_EXPIRE_SEC:
|
||||
# 文件未过期但缺 key -> 记为空字典,避免反复请求不存在的类型
|
||||
for ct in need:
|
||||
cache.setdefault(ct, {})
|
||||
need = [ct for ct in need if not cache.get(ct)]
|
||||
|
||||
if need:
|
||||
payload = {
|
||||
"codeType": ",".join(need),
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp = hr_request_json(session, "POST", BANK_DICT_URL, payload, "数据字典", timeout=30)
|
||||
for ct in need:
|
||||
raw = (resp.get("result") or {}).get(ct) or resp.get(ct)
|
||||
cache[ct] = _parse_items(raw) if raw else {}
|
||||
_save_cache(cache)
|
||||
logger.info("数据字典远程拉取完成:%s", {ct: len(cache[ct]) for ct in need})
|
||||
|
||||
return {ct: cache.get(ct, {}) for ct in code_types}
|
||||
|
||||
|
||||
def code_to_name(code, code_map: dict) -> Any:
|
||||
"""按字典映射翻译编码;未命中返回原值(None/空串原样返回)。"""
|
||||
if code is None or code == "":
|
||||
return code
|
||||
return code_map.get(str(code).strip(), code)
|
||||
@@ -1,137 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: kq_data.py
|
||||
@Description: 查询打卡记录接口(用于校验休息日半天上班是否按班段打卡)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import KQ_DATA_URL, PAGE_MAX_SIZE
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_kq_data_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页打卡记录数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为打卡流水数组,关键字段见下)
|
||||
"""
|
||||
params = {
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_data_query",
|
||||
# datas 记录关键字段(aa.md 提供的返回样例):
|
||||
# base_code 工号、staff_id、staff_name、
|
||||
# kq_time 打卡时间("YYYY-MM-DD HH:MM:SS")、kq_type 打卡类型(如 9)、
|
||||
# status 打卡状态、addr_status 地址状态、time_order 上/下班顺序、
|
||||
# bc_date 班次日期、kq_bc_id 考勤班次id、pb_id 排班id、address 打卡地点、
|
||||
# time_zone_min 时区分钟、varchar1 扩展标记
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"kqStaffIds": "",
|
||||
"staff_id": "",
|
||||
"staff_name": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"kq_type": "",
|
||||
"post_type": "",
|
||||
"person_status": "",
|
||||
"dkstatus": "",
|
||||
"addr_status": " ",
|
||||
"struTreeCode": treecode,
|
||||
"belongUnitStruId": "",
|
||||
"work_day_begin": start_time,
|
||||
"work_day_end": end_time,
|
||||
"base_code": base_code,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_DATA_URL, params, "打卡查询")
|
||||
|
||||
|
||||
def fetch_all_kq_data(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部打卡记录。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
|
||||
Returns:
|
||||
打卡记录列表(接口 datas 字段内容)
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("打卡查询 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("打卡查询第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("打卡查询无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("打卡查询已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
@@ -1,147 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: leave.py
|
||||
@Description: 查询请假记录接口(用于过滤虚假异常,暂未在主流程调用)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import LEAVE_URL, PAGE_MAX_SIZE
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_leave_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
leave_type=None,
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页请假记录数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
leave_type: 请假类型编码(leave_type),可为单个值或列表,如 "22" / ["09", "22"];
|
||||
不传(None)表示全部类型
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为请假记录数组,字段含 start_time/end_time/leave_days/
|
||||
begin_date_other_name/end_date_other_name/base_code/staff_id 等)
|
||||
"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"begin_date": "",
|
||||
"end_date": "",
|
||||
"sqlId": "select_kqLeave_record",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"post_no": "",
|
||||
"source": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"processing_date": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "operat_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
# leave_type 可多值(如 22&09&24...),requests 会把列表序列化为重复键;不传表示全部类型
|
||||
if leave_type:
|
||||
if isinstance(leave_type, (list, tuple)):
|
||||
params["leave_type"] = [str(t) for t in leave_type]
|
||||
else:
|
||||
params["leave_type"] = str(leave_type)
|
||||
return hr_request_json(session, "POST", LEAVE_URL, params, "请假查询")
|
||||
|
||||
|
||||
def fetch_all_leave(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
leave_type=None,
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部请假记录。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
leave_type: 请假类型编码(leave_type),可为单个值或列表,如 "22" / ["09", "22"];
|
||||
不传(None)表示全部类型
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
|
||||
Returns:
|
||||
请假记录列表(接口 datas 字段内容,含 start_time/end_time/leave_days 等)
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_leave_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
leave_type, treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("请假查询 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_leave_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
leave_type, treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("请假查询第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("请假查询无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
@@ -1,172 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: org.py
|
||||
@Description: 组织维护(组织设置)台账查询接口
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
ORG_QUERY_URL,
|
||||
ORG_QUERY_BASE_PARAMS,
|
||||
PAGE_MAX_SIZE,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 接口字段 → 页面列名映射(「序号」接口不返回,转换时按行号生成;
|
||||
# 分管部门对应 pt_structure2.ORG_ALIAS,当前数据未使用但列位保留)
|
||||
ORG_FIELD_MAP = [
|
||||
("pt_organzation.ORG_NAME", "组织名称"),
|
||||
("pt_organzation.ORG_CODE", "组织编号"),
|
||||
("pt_organzation.ORG_TYPE_CODE", "组织类型"),
|
||||
("pt_structure1.ORG_ALIAS", "上级组织"),
|
||||
("org_principal_staff_name_select.org_principal_staff_name", "组织负责人"),
|
||||
("pt_structure2.ORG_ALIAS", "分管部门"),
|
||||
("branch_leader_name_select.branch_leader_name", "分管领导"),
|
||||
("pt_organzation.BEGIN_DATE", "成立日期"),
|
||||
("pt_orgnization_extend.FOUND_DOC_NUM", "成立文号"),
|
||||
("pt_organzation.CANT_CODE", "所属地区"),
|
||||
("pt_organzation.office_address", "办公地址"),
|
||||
("pt_organzation.remarks", "备注"),
|
||||
("pt_orgnization_extend.FOUND_REASON", "成立原因"),
|
||||
("pt_structure.ORG_FULL_PATH", "组织全路径"),
|
||||
("pt_organzation.create_time", "创建时间"),
|
||||
("pt_organzation.IN_USE", "使用状态"),
|
||||
("pt_organzation_ext.ext_payday", "发薪日"),
|
||||
]
|
||||
|
||||
# 使用状态编码 → 文字
|
||||
IN_USE_MAP = {"1": "在用", "0": "停用"}
|
||||
|
||||
|
||||
def to_org_rows(datalist: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""将接口原始记录转换为页面列名顺序的字典列表(18 列,含序号)。
|
||||
|
||||
Args:
|
||||
datalist: fetch_all_orgs / fetch_org_page 返回的 datas 原始记录列表
|
||||
|
||||
Returns:
|
||||
按页面列顺序组织好的字典列表(序号/组织名称/.../发薪日)
|
||||
"""
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for i, r in enumerate(datalist, 1):
|
||||
row: Dict[str, Any] = {"序号": i}
|
||||
for key, name in ORG_FIELD_MAP:
|
||||
value = r.get(key)
|
||||
if name == "使用状态":
|
||||
value = IN_USE_MAP.get(str(value), value)
|
||||
elif name == "成立日期" and value:
|
||||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||||
row[name] = value
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def get_date_params() -> Dict[str, str]:
|
||||
"""生成组织维护查询所需的动态日期参数(当月 / 上月 / 当年首月)。
|
||||
|
||||
Returns:
|
||||
含 currentDate / currentMonth / currentMonthBar / lastMonth /
|
||||
lastMonFirstDay / lastMonLastDay / curYearFirstMon / curYearFirstMonBar 的字典
|
||||
"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def fetch_org_page(
|
||||
session,
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页组织维护数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数(最大 500)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为组织明细数组,count 总条数,pageCount 总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = ORG_QUERY_BASE_PARAMS.copy()
|
||||
params.update(get_date_params())
|
||||
params.update({
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
return hr_request_json(session, "POST", ORG_QUERY_URL, params, "组织维护")
|
||||
|
||||
|
||||
def fetch_all_orgs(session) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取全部组织维护数据(在职组织,in_use=1)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
|
||||
Returns:
|
||||
组织明细列表(接口 datas 字段内容,每条含 ORG_ID / ORG_NAME / ORG_CODE /
|
||||
ORG_FULL_PATH / STRU_LEVEL / STRU_ORDER 等字段)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_org_page(session, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("组织维护 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
data = fetch_org_page(session, page_no, PAGE_MAX_SIZE)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("组织维护第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("组织维护无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total = data.get("count", 0)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("组织维护已抓取 %d/%d 页,累计 %d/%d 条",
|
||||
page_no, total_page, len(all_rows), total)
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
@@ -1,143 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: overtime.py
|
||||
@Description: 查询加班记录接口(用于过滤虚假异常,暂未在主流程调用)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import OVERTIME_URL, PAGE_MAX_SIZE
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_overtime_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
work_overtime_type: str = "",
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页加班记录数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
work_overtime_type: 加班类型 WORK_OVERTIME_TYPE,空=全部、1=延时加班、2=法定假日加班、3=休息日加班
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为加班记录数组,关键字段见下)
|
||||
"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_overtime_detail_select",
|
||||
# datas 记录关键字段(aa.md 提供的返回样例):
|
||||
# base_code 工号、STAFF_ID、WORK_OVERTIME_TYPE 加班类型(1延时/2法定/3休息日)、
|
||||
# OT_DATE 加班日期、ot_days / sys_ot_days / plan_ot_days 加班天数(筛 0.5 天用)、
|
||||
# ot_hours / FINAL_HOURS 加班小时、
|
||||
# PLAN_START_TIME/PLAN_END_TIME、ACTUAL_START_TIME/ACTUAL_END_TIME、FINAL_START_TIME/FINAL_END_TIME 时间段、
|
||||
# SB_DA_RANGE / XB_DA_RANGE 上下班打卡分钟范围、SB_TIME_MORE/LESS、XB_TIME_MORE/LESS、OT_SB_TYPE/OT_XB_TYPE
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"BPM_STATUS": "",
|
||||
"post_no": "",
|
||||
"postName": "",
|
||||
"source": "",
|
||||
"IS_SUBSIDY": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"WORK_OVERTIME_TYPE": work_overtime_type,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "OPERATE_TIME",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", OVERTIME_URL, params, "加班查询")
|
||||
|
||||
|
||||
def fetch_all_overtime(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
start_time: str,
|
||||
end_time: str,
|
||||
work_overtime_type: str = "",
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部加班记录。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
start_time / end_time: 查询日期范围 "YYYY-MM-DD"
|
||||
work_overtime_type: 加班类型 WORK_OVERTIME_TYPE,空=全部、1=延时加班、2=法定假日加班、3=休息日加班
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
|
||||
Returns:
|
||||
加班记录列表(接口 datas 字段内容)
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("加班查询 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("加班查询第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("加班查询无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
@@ -1,289 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: roster.py
|
||||
@Description: 员工花名册台账实时查询接口(纯 API 版,替代浏览器下载)。
|
||||
与组织维护 org.py 同模式:queryRealTimeData.mc 分页查询;
|
||||
commonQuery 由 common_query 自实现加密构造。
|
||||
模板列映射对齐页面自定义导出模板:「员工基础信息」「雇主险增减员导出模板」。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.common_query import build_condition, encode_common_query
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
ROSTER_QUERY_URL,
|
||||
ROSTER_QUERY_BASE_PARAMS,
|
||||
ROSTER_QUERY_CONDITIONS,
|
||||
PAGE_MAX_SIZE,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.code_dict import code_to_name, get_code_dicts
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 在职状态编码(已通过抓包实证:在职抓包串 queryValue=1,离职抓包串 queryValue=2)
|
||||
PERSON_STATUS_MAP = {"1": "在职", "2": "离职"}
|
||||
|
||||
# 字典字段 -> codeType(来源:花名册页面源码内嵌的字典定义,已实测接口可查)
|
||||
ROSTER_CODE_TYPE_MAP = {
|
||||
"hr_staff_base.sex": "COMMON.SEX", # 性别
|
||||
"hr_staff_base.nation": "COMMON.NATION", # 民族
|
||||
"hr_staff_base.identity": "COMMON.IDENTITY", # 用工类型
|
||||
"hr_staff_base.marriage": "COMMON.MARRIAGE", # 婚姻状况
|
||||
"hr_staff_base.from_nation": "COMMON.FROMNATION", # 国籍
|
||||
"hr_staff_base.highedu": "HR_RECRUIT_EDU.EDUCATION", # 最高学历
|
||||
}
|
||||
|
||||
# 需去掉时分秒的日期字段
|
||||
_DATE_FIELDS = {"hr_staff_base.join_date", "hr_staff_base.leaveOffice_date",
|
||||
"hr_staff_base.Regular_Time", "hr_staff_base.pre_correction_date"}
|
||||
|
||||
# ---------- 模板列映射(field, 列名),顺序与页面自定义导出模板一致 ----------
|
||||
# 「员工基础信息」模板(31 列 + 序号,与抓包 exportFilters 完全一致)
|
||||
ROSTER_FIELD_MAP_BASIC = [
|
||||
("hr_staff_base.staff_name", "姓名"),
|
||||
("hr_staff_base.base_code", "工号"),
|
||||
("hr_staff_base.idCard", "证件号"),
|
||||
("hr_staff_base.join_date", "入职时间"),
|
||||
("hr_staff_base.leaveOffice_date", "离职时间"),
|
||||
("pt_staff_stru.BELONG_UNIT_ORG_NAME", "所属单位"),
|
||||
("pt_staff_stru.DEPT_ORG_NAME", "所属部门"),
|
||||
("pt_staff_stru.DEPT_ORG_ONE", "一级部门"),
|
||||
("pt_staff_stru.DEPT_ORG_TWO", "二级部门"),
|
||||
("pt_staff_stru.DEPT_ORG_THREE", "三级部门"),
|
||||
("pt_staff_stru.DEPT_ORG_FOUR", "四级部门"),
|
||||
("pt_staff_stru.DEPT_ORG_FIVE", "五级部门"),
|
||||
("pt_staff_stru.POST_ORG_NAME", "岗位"),
|
||||
("hr_staff_base_ext.ext_technician_code", "技师工号"),
|
||||
("hr_staff_base_ext.ext_star_level", "星级"),
|
||||
("pt_staff_stru.first_type_id", "职位序列"),
|
||||
("pt_staff_stru.POST_LEVEL_ID", "职衔"),
|
||||
("pt_staff_stru.PT_POST_GRADE_ID", "职级"),
|
||||
("pt_post_level.ext_grade_name", "职等"),
|
||||
("hr_staff_base.mobile_phone", "手机号码"),
|
||||
("hr_staff_base.person_status", "在职状态"),
|
||||
("hr_staff_base_ext.ext_insurance_type", "参保类型"),
|
||||
("pt_staff_stru.ORG_FULL_PATH", "组织全路径"),
|
||||
("hr_staff_base.nation", "民族"),
|
||||
("hr_staff_base.sex", "性别"),
|
||||
("hr_staff_base.age", "年龄"),
|
||||
("hr_staff_base.period", "试用期限(月)"),
|
||||
("hr_staff_base.pre_correction_date", "试用期结束日期"),
|
||||
("hr_staff_base_ext.ext_trans_type", "上下班交通方式"),
|
||||
("hr_staff_base_ext.ext_recruit_way", "招聘渠道"),
|
||||
("hr_staff_base.identity", "用工类型"),
|
||||
]
|
||||
|
||||
# 「雇主险增减员导出模板」(14 列 + 序号,无三级/五级部门,顺序按模板)
|
||||
ROSTER_FIELD_MAP_EMPLOYER = [
|
||||
("pt_staff_stru.BELONG_UNIT_ORG_NAME", "所属单位"),
|
||||
("pt_staff_stru.DEPT_ORG_ONE", "一级部门"),
|
||||
("pt_staff_stru.DEPT_ORG_TWO", "二级部门"),
|
||||
("pt_staff_stru.DEPT_ORG_FOUR", "四级部门"),
|
||||
("hr_staff_base.base_code", "工号"),
|
||||
("hr_staff_base.age", "年龄"),
|
||||
("hr_staff_base.sex", "性别"),
|
||||
("pt_staff_stru.POST_ORG_NAME", "岗位"),
|
||||
("pt_staff_stru.first_type_id", "职位序列"),
|
||||
("hr_staff_base_ext.ext_insurance_type", "参保类型"),
|
||||
("hr_staff_base_ext.ext_trans_type", "上下班交通方式"),
|
||||
("hr_staff_base.join_date", "入职时间"),
|
||||
("hr_staff_base.staff_name", "姓名"),
|
||||
("hr_staff_base.idCard", "证件号"),
|
||||
]
|
||||
|
||||
# 模板名 -> 列映射
|
||||
ROSTER_TEMPLATE_FIELD_MAPS = {
|
||||
"员工基础信息": ROSTER_FIELD_MAP_BASIC,
|
||||
"雇主险增减员导出模板": ROSTER_FIELD_MAP_EMPLOYER,
|
||||
}
|
||||
|
||||
|
||||
def get_date_params() -> Dict[str, str]:
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月),与页面请求一致。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def build_leave_conditions(leave_start: str, leave_end: str) -> List[Dict[str, str]]:
|
||||
"""构造「离职人员」查询条件:person_status in (2) + 离职时间区间(等价页面离职筛选抓包串)。
|
||||
|
||||
Args:
|
||||
leave_start: 离职开始日期,如 "2026-08-01"
|
||||
leave_end: 离职结束日期,如 "2026-08-31"
|
||||
|
||||
Returns:
|
||||
查询条件列表(可传给 fetch_roster_page / fetch_all_rosters 的 conditions)
|
||||
"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
def build_in_service_conditions() -> List[Dict[str, str]]:
|
||||
"""构造「在职人员」查询条件(主职 + person_status in (1),即默认抓包条件)。"""
|
||||
return [dict(c) for c in ROSTER_QUERY_CONDITIONS]
|
||||
|
||||
|
||||
def fetch_roster_page(
|
||||
session,
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
conditions: Optional[List[Dict[str, str]]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页花名册数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数(最大 500)
|
||||
conditions: 查询条件列表;None 使用默认在职条件(ROSTER_QUERY_CONDITIONS)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为花名册明细数组,count 总条数,pageCount 总页数)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = ROSTER_QUERY_BASE_PARAMS.copy()
|
||||
params["commonQuery"] = encode_common_query(
|
||||
conditions if conditions is not None else ROSTER_QUERY_CONDITIONS)
|
||||
params.update(get_date_params())
|
||||
params.update({
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
return hr_request_json(session, "POST", ROSTER_QUERY_URL, params, "员工花名册")
|
||||
|
||||
|
||||
def fetch_all_rosters(
|
||||
session,
|
||||
conditions: Optional[List[Dict[str, str]]] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取全部花名册数据(默认在职人员,可传 conditions 查离职等)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
conditions: 查询条件列表;None 使用默认在职条件
|
||||
|
||||
Returns:
|
||||
花名册明细列表(接口 datas 字段内容)
|
||||
|
||||
Raises:
|
||||
HRSessionExpiredError: 登录态过期且重新登录后仍失败
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_roster_page(session, page_no, PAGE_MAX_SIZE, conditions)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("员工花名册 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
data = fetch_roster_page(session, page_no, PAGE_MAX_SIZE, conditions)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("员工花名册第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("员工花名册无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total = data.get("count", 0)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("员工花名册已抓取 %d/%d 页,累计 %d/%d 条",
|
||||
page_no, total_page, len(all_rows), total)
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_roster_code_dicts(session, force_refresh: bool = False) -> Dict[str, Dict[str, str]]:
|
||||
"""拉取花名册所需全部数据字典(带本地缓存),返回 {接口字段: {code: 名称}}。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
force_refresh: True 强制刷新缓存
|
||||
"""
|
||||
maps = get_code_dicts(session, list(ROSTER_CODE_TYPE_MAP.values()), force_refresh)
|
||||
return {field: maps[ct] for field, ct in ROSTER_CODE_TYPE_MAP.items()}
|
||||
|
||||
|
||||
def to_roster_rows(
|
||||
datalist: List[Dict[str, Any]],
|
||||
template: str = "员工基础信息",
|
||||
code_dicts: Optional[Dict[str, Dict[str, str]]] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""将接口原始记录转换为指定模板列顺序的字典列表(含序号列)。
|
||||
|
||||
Args:
|
||||
datalist: fetch_all_rosters / fetch_roster_page 返回的 datas 原始记录列表
|
||||
template: 模板名(ROSTER_TEMPLATE_FIELD_MAPS 的键),默认「员工基础信息」
|
||||
code_dicts: 字典映射 {接口字段: {code: 名称}}(fetch_roster_code_dicts 返回值),
|
||||
提供时性别/民族/用工类型等编码字段翻译为文字;缺省保留原始编码
|
||||
|
||||
Returns:
|
||||
按模板列顺序组织好的字典列表(首列为序号)
|
||||
|
||||
Raises:
|
||||
ValueError: 模板名不存在
|
||||
"""
|
||||
field_map = ROSTER_TEMPLATE_FIELD_MAPS.get(template)
|
||||
if field_map is None:
|
||||
raise ValueError(f"未知花名册模板:{template}(可选:{list(ROSTER_TEMPLATE_FIELD_MAPS)})")
|
||||
code_dicts = code_dicts or {}
|
||||
|
||||
rows: List[Dict[str, Any]] = []
|
||||
for i, r in enumerate(datalist, 1):
|
||||
row: Dict[str, Any] = {"序号": i}
|
||||
for key, name in field_map:
|
||||
value = r.get(key)
|
||||
if key == "hr_staff_base.person_status":
|
||||
value = PERSON_STATUS_MAP.get(str(value), value)
|
||||
elif key in code_dicts:
|
||||
value = code_to_name(value, code_dicts[key])
|
||||
elif key in _DATE_FIELDS and value:
|
||||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||||
row[name] = value
|
||||
rows.append(row)
|
||||
return rows
|
||||
@@ -1,177 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: roster_export.py
|
||||
@Description: 花名册异步导出(服务端生成 Excel,替代浏览器下载导出)。
|
||||
链路:访问台账页面绑定会话 -> ws/bridge 注册会话到 WS 容器 ->
|
||||
WebSocket 订阅主题(HR_DEFINED_HMC_EXPORT) -> POST exportCommonListData 提交任务 ->
|
||||
接收 WS 进度推送至 "--end--|文件路径" -> GET tempFile.mc 下载 Excel。
|
||||
服务端负责全部字典翻译(星级/参保类型/职衔/职级等),与页面导出结果一致。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import websocket
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.common_query import encode_common_query
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
ROSTER_ROSTER_ID,
|
||||
ROSTER_QUERY_BASE_PARAMS,
|
||||
ROSTER_QUERY_CONDITIONS,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
build_in_service_conditions,
|
||||
get_date_params,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_template import ROSTER_TEMPLATE_FILTERS
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 异步导出 WebSocket 主题与相关 URL(redseaWs.js 逻辑的服务端约定)
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
PAGE_URL = (f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ROSTER_ID}/getCustomCommonList.mc")
|
||||
EXPORT_URL = (f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ROSTER_ID}/exportCommonListData.mc")
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
|
||||
def _bind_session(session) -> None:
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise RuntimeError(f"ws/bridge 会话注册失败:{r.text[:100]}")
|
||||
|
||||
|
||||
def export_common_list(
|
||||
session,
|
||||
output_path: str,
|
||||
export_name: str = "员工基础信息",
|
||||
export_filters: Optional[str] = None,
|
||||
conditions: Optional[List[Dict[str, str]]] = None,
|
||||
progress_interval: int = 0,
|
||||
timeout: int = 300,
|
||||
) -> str:
|
||||
"""异步导出台账 Excel(服务端生成并翻译字典),下载保存到 output_path。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
output_path: Excel 保存路径
|
||||
export_name: 导出模板名(对应页面自定义导出模板)
|
||||
export_filters: 导出字段串(逗号分隔);None 则按模板名查 ROSTER_TEMPLATE_FILTERS
|
||||
conditions: 查询条件列表;None 使用默认在职条件
|
||||
progress_interval: 进度日志打印间隔(每 N 条打印一次,0 不打印中间进度)
|
||||
timeout: 等待导出完成的超时秒数
|
||||
|
||||
Returns:
|
||||
output_path(导出成功)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 提交导出失败 / 超时未收到文件地址 / 下载失败
|
||||
"""
|
||||
if export_filters is None:
|
||||
export_filters = ROSTER_TEMPLATE_FILTERS.get(export_name)
|
||||
if not export_filters:
|
||||
raise ValueError(f"未知导出模板:{export_name},且未提供 export_filters")
|
||||
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = encode_common_query(
|
||||
conditions if conditions is not None else ROSTER_QUERY_CONDITIONS)
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": export_name, "exportFilters": export_filters},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(%s)", export_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url: Optional[str] = None
|
||||
deadline = time.time() + timeout
|
||||
ws.settimeout(timeout)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if progress_interval and txt.startswith("正在生成"):
|
||||
try:
|
||||
if int("".join(filter(str.isdigit, txt))) % progress_interval == 0:
|
||||
logger.info("导出进度:%s", txt)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({timeout}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("Excel 已保存:%s(%d 字节)", output_path, len(dl.content))
|
||||
return output_path
|
||||
|
||||
|
||||
# 便捷封装:在职人员按模板导出
|
||||
def export_roster_excel(
|
||||
session,
|
||||
output_path: str,
|
||||
template: str = "员工基础信息",
|
||||
conditions: Optional[List[Dict[str, str]]] = None,
|
||||
) -> str:
|
||||
"""按模板导出花名册 Excel(默认在职人员,conditions 可传离职等条件)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
output_path: Excel 保存路径
|
||||
template: 模板名(ROSTER_TEMPLATE_FILTERS 的键)
|
||||
conditions: 查询条件;None 使用默认在职条件
|
||||
"""
|
||||
return export_common_list(
|
||||
session, output_path,
|
||||
export_name=template,
|
||||
export_filters=ROSTER_TEMPLATE_FILTERS.get(template),
|
||||
conditions=conditions if conditions is not None else build_in_service_conditions(),
|
||||
)
|
||||
@@ -1,66 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: roster_template.py
|
||||
@Description: 花名册自定义导出模板的字段串(exportFilters),顺序与页面导出模板列顺序一致。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
ROSTER_TEMPLATE_FILTERS_BASIC = ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||||
"hr_staff_base_ext.ext_star_level", # 星级
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||||
"pt_post_level.ext_grade_name", # 职等
|
||||
"hr_staff_base.mobile_phone", # 手机号码
|
||||
"hr_staff_base.person_status", # 在职状态
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||||
"hr_staff_base.nation", # 民族
|
||||
"hr_staff_base.sex", # 性别
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.period", # 试用期限(月)
|
||||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||||
"hr_staff_base.identity", # 用工类型
|
||||
])
|
||||
|
||||
# 「雇主险增减员导出模板」(14 列,无三级/五级部门,顺序按模板)
|
||||
ROSTER_TEMPLATE_FILTERS_EMPLOYER = ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
])
|
||||
|
||||
# 模板名 -> exportFilters 字段串
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
"员工基础信息": ROSTER_TEMPLATE_FILTERS_BASIC,
|
||||
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: shift.py
|
||||
@Description: 查询排班接口(用于过滤虚假异常,暂未在主流程调用)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
SHIFT_URL,
|
||||
PAGE_MAX_SIZE,
|
||||
WORK_DATE_QUERY_URL,
|
||||
COMPANY_STRU_ID,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_shift_page(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
treecode: str = "cq37du",
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页排班数据(aa.md 提供的接口入参)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
user_id: 由 getCurUserInfo 返回的 userId
|
||||
base_code: 员工工号
|
||||
begin_date / end_date: 查询日期范围 "YYYY-MM-DD"
|
||||
treecode: 组织树编码,默认 cq37du
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(datas 为排班明细数组,关键字段见下)
|
||||
"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
# datas 记录关键字段(aa.md 提供的返回样例,一条记录 = 一个员工在查询范围内的排班):
|
||||
# base_code 工号、staff_id、staff_name、work_day 首日、total_day / total_hours 汇总、
|
||||
# 基础班次:bc_name 班次名、bc_time 班段时间(如 "09:00 ~ 18:00",即班端)、begin_time / end_time、yq_total_min、
|
||||
# 逐日班次(动态列,key 为 "YYYY-MM-DD_bc_id/bc_name/bc_time/paiban_type/sb_type/xb_type"),
|
||||
# 休息日的可靠判定依据为:当日 bc_name == "休息"(paiban_type 不可靠,休息也可能为 -2,勿用)
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(
|
||||
session,
|
||||
user_id: str,
|
||||
base_code: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
treecode: str = "cq37du",
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""分页抓取指定工号、日期范围内的全部排班数据。"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE,
|
||||
)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第%d页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_work_date_page(
|
||||
session,
|
||||
org_name: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页「某部门排班集合」(rf_s_kq_work_date_query,aa.md 提供)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
org_name: 部门名(现四级部门/现单位),接口按 org_name 精确过滤
|
||||
page_no / page_size: 分页参数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(data.list 记录含 work_date_name 排班名、org_name 部门名,
|
||||
逐条记录 = 一个排班,同一部门可含多个排班)
|
||||
"""
|
||||
params = {
|
||||
"stru_tree_code": "cq37du",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"containLower": "",
|
||||
"work_date_name": "",
|
||||
"paiban_type": "",
|
||||
"holiday_plan_name": "",
|
||||
"org_name": org_name,
|
||||
"work_status": "1",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "create_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", WORK_DATE_QUERY_URL, params, "部门排班")
|
||||
|
||||
|
||||
def fetch_all_work_date(
|
||||
session,
|
||||
org_name: str,
|
||||
) -> List[str]:
|
||||
"""分页抓取某部门的全部排班名列表(work_date_name),登录态过期自动重登后续抓。"""
|
||||
names: List[str] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_work_date_page(session, org_name, page_no)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("部门排班 HR 登录态过期,重新登录后续抓")
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
data = fetch_work_date_page(session, org_name, page_no)
|
||||
|
||||
if not data.get("success"):
|
||||
logger.error("部门排班第%d页请求失败:%s", page_no, data.get("message") or data.get("meg"))
|
||||
break
|
||||
|
||||
data_block = data.get("data") or {}
|
||||
page_list = data_block.get("list") or []
|
||||
if not page_list:
|
||||
logger.info("部门排班无更多数据")
|
||||
break
|
||||
|
||||
for rec in page_list:
|
||||
name = str(rec.get("work_date_name") or "").strip()
|
||||
if name:
|
||||
names.append(name)
|
||||
|
||||
total_page = data_block.get("pageCount", 0)
|
||||
logger.info("部门排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(names))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return names
|
||||
@@ -1,118 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common.hr_api
|
||||
@FileName: wage_card.py
|
||||
@Description: 银行卡(工资卡)信息查询接口
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import WAGE_CARD_URL, PAGE_MAX_SIZE
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_wage_card_page(
|
||||
session,
|
||||
status: int,
|
||||
page_no: int = 1,
|
||||
page_size: int = PAGE_MAX_SIZE,
|
||||
leave_start: str = None,
|
||||
leave_end: str = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页工资卡数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
status: 人员状态,1=在职 / 2=离职
|
||||
page_no: 页码(从 1 开始)
|
||||
page_size: 每页条数
|
||||
leave_start / leave_end: 离职筛选时间范围 "YYYY-MM-DD"(status=2 时必填)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
HRSessionExpiredError: 登录态过期(接口返回非 JSON)
|
||||
"""
|
||||
params = {
|
||||
"start": (page_no - 1) * page_size,
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ftl_list_STRU_TREE_CODE": "cq37du",
|
||||
"sortName": "hr_staff_wage_card.STAFF_NAME",
|
||||
"sortType": "asc",
|
||||
"commonQuery": "[]",
|
||||
"person_status": status,
|
||||
}
|
||||
# 在职、离职参数区分
|
||||
if status == 1:
|
||||
params["leaveOffice_date"] = ""
|
||||
elif leave_start and leave_end:
|
||||
params["leaveOffice_date[0]"] = leave_start
|
||||
params["leaveOffice_date[1]"] = leave_end
|
||||
params["leaveOffice_date_start"] = leave_start
|
||||
params["leaveOffice_date_end"] = leave_end
|
||||
|
||||
return hr_request_json(session, "POST", WAGE_CARD_URL, params, "工资卡")
|
||||
|
||||
|
||||
def fetch_all_wage_card(
|
||||
session,
|
||||
status: int,
|
||||
status_name: str,
|
||||
leave_start: str = None,
|
||||
leave_end: str = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
分页抓取指定人员类型(在职/离职)的全部工资卡数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
status: 人员状态,1=在职 / 2=离职
|
||||
status_name: 人员类型文字(用于日志与数据标记)
|
||||
leave_start / leave_end: 离职筛选时间范围(status=2 时必填)
|
||||
|
||||
Returns:
|
||||
数据行列表(每条已附加「人员类型」字段)
|
||||
"""
|
||||
all_rows: List[Dict[str, Any]] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("【%s】HR 登录态过期,重新登录后续抓", status_name)
|
||||
from app.service.hrbp.common.hr_session import refresh_hr_session
|
||||
session = refresh_hr_session()
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("【%s】无更多数据", status_name)
|
||||
break
|
||||
|
||||
# 给每条数据增加人员类型标识
|
||||
for item in page_list:
|
||||
item["人员类型"] = status_name
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total = data.get("count", 0)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
|
||||
status_name, page_no, total_page, len(all_rows), total)
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险名额调度系统(app 版):花名册业务处理 + 在参名单名额调度 + 变更清单生成
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,652 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance
|
||||
@FileName: add_sub_import.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-18
|
||||
@Description: 雇主险流程「步骤3:增减员导入」。在 HR「待增减人员」页面执行增员/减员导入
|
||||
(复刻 aa.md 的操作流程:访问页面 -> 更多操作 -> 增员导入/减员导入 -> 上传文件 -> 下一步 -> 下一步 -> 关闭)
|
||||
- 前置:步骤2 调度(employer_insurance.py)完成,并准备好增员/减员导入文件
|
||||
- 传入参数:增员(默认商业保险增员导入.xlsx)或 减员(商业保险减员导入.xlsx)
|
||||
- 复用 HR 登录态(app.service.hrbp.common.login 的缓存 cookies)
|
||||
@Version: 1.3.0
|
||||
- v1.3.0:修复监听时机与全量分页——监听从第一个「下一步」前即开启(HR 端流程调整后结果接口
|
||||
可能在第一步即触发,原「第二步前才监听」导致漏捕、误报「未捕获到导入结果接口响应」);
|
||||
wait() 超时返回 False 的判断修正;跳过无 imp_fixed_msg 的格式校验/预览响应;
|
||||
全量翻页改为按首次请求 body 改 pageNo/start 后 POST 拉取(原 GET URL 对 POST 接口无效)。
|
||||
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
|
||||
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块完成登录并缓存 cookies;后续自动复用,过期自动重新登录。
|
||||
2. 通过函数传参调用(无命令行入口):
|
||||
from app.service.hrbp.ehr.employer_insurance.add_sub_import import import_employee_change
|
||||
|
||||
import_employee_change("增员") # 增员导入(全部类别)
|
||||
import_employee_change("减员") # 减员导入(全部类别)
|
||||
import_employee_change("增员", ["三十七度"]) # 指定类别
|
||||
import_employee_change("增员", None, r"D:\\...\\xxx.xlsx") # 指定导入文件
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ADD_SUB_URL # noqa: E402
|
||||
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
CATEGORIES,
|
||||
get_category,
|
||||
category_import_add_file,
|
||||
category_import_sub_file,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 领域异常定义 =====================
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。
|
||||
|
||||
用于区分「UI 状态类失败」(页面没加载出来、元素定位器失效)与其它运行时错误,
|
||||
便于调用方针对性地重试或提示人工介入。
|
||||
"""
|
||||
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
|
||||
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
|
||||
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行导入结果说明:
|
||||
# 异常行如「存在已参保的人员,不允许重复增员!」;成功行返回「导入成功;」(不纳入异常上报)。
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 导入内容结果接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 元素定位辅助(DrissionPage)
|
||||
# ---------------------------------------------------------------
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. 打开待增减人员页面并确保登录态(复用缓存 cookies)
|
||||
# ---------------------------------------------------------------
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,则复用/重登 HR 登录态。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
logger.info("HR 登录态已失效,执行重新登录")
|
||||
from app.service.hrbp.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 重新登录失败")
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
page.set.cookies(cookies)
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError("HR 重新登录后仍停留在登录页")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. 增员/减员导入主流程(aa.md 步骤)
|
||||
# ---------------------------------------------------------------
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
# 若下拉菜单已可见,直接返回
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
# 定位「更多操作」按钮(#more-btns 容器内的 btn-success dropdown-toggle)
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, import_type):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
if import_type not in (MENU_ADD, MENU_SUB):
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为 {MENU_ADD} 或 {MENU_SUB})")
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, import_type)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件。
|
||||
|
||||
aa.md:选择文件夹按钮(glyphicon glyphicon-folder-open)会弹出文件选择器;
|
||||
这里直接用 DrissionPage 对 <input type="file"> 设置文件路径,跳过系统文件选择框。
|
||||
"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3.5 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
# 接口返回的每一行即本次调度的一条需导入记录,全部计入需导入总条数
|
||||
result["total_count"] += 1
|
||||
# HR 对导入成功的行同样返回「导入成功;」等固定文案,成功行只统计数量,
|
||||
# 不纳入异常(否则会被误报为异常,如「异常:导入成功;」)
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""用 HR 登录态(common.login 缓存的 hr_cookies.json)构建可访问 HR 接口的
|
||||
requests.Session(仅注入 37du.co 域 cookies),与 common.login 校验同一套方式。"""
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
raise FileNotFoundError("缺少 HR 登录态 hr_cookies.json(请先完成 HR 登录)")
|
||||
import requests
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in str(c.get("domain", "")):
|
||||
session.cookies.set(c.get("name"), c.get("value"),
|
||||
domain=c.get("domain"), path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页时监听只能统计到 15 条,
|
||||
实际导入量常超 15,导致成功数/异常明细被截断、漏统计。
|
||||
此函数用 HR 登录态按 pageNo 主动拉取剩余页并合并全部结果,保证统计覆盖全量。
|
||||
|
||||
注意:该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中而非 URL 查询串,必须复用首次请求 body 改页码后 POST 拉取,
|
||||
直接 GET URL 会拿不到目标页数据。"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
try:
|
||||
session = _build_hr_session()
|
||||
except Exception as e:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话):%s,仅统计弹窗第一页", e)
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获返回的全部异常。
|
||||
|
||||
监听自第一个「下一步」之前即已开启(见 _import_one),因此无论 HR 端是在第一步
|
||||
格式校验/预览还是第二步「真正导入」时才请求 getTmpDataPage.mc 都能捕获到。
|
||||
本函数只处理携带导入结果说明的响应:
|
||||
- state="1" 表示接口正常;meg 为全局提示;
|
||||
- datas[].imp_fixed_msg 为逐行导入结果说明:异常行如「存在已参保的人员,不允许重复增员!」,
|
||||
成功行返回「导入成功;」(成功行不纳入异常上报);
|
||||
- 第一步格式校验/预览的响应行内 imp_fixed_msg 为空,视为无效响应跳过,继续等待最终结果。
|
||||
接口分页返回(每页固定 pageSize=15,响应带 pageCount 总页数),弹窗默认只加载第一页,
|
||||
故捕获首响应后主动按 pageNo 翻页拉取剩余页合并,保证总条数/成功数/异常明细覆盖全量,
|
||||
不再出现「每次固定 15 条」的截断问题。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"captured": bool, # 是否捕获到解析接口响应
|
||||
"state": str, # 接口 state(未捕获到为空串)
|
||||
"meg": str, # 全局提示
|
||||
"listen_ok": bool, # 接口监听是否成功启动(False=未监听,结果不可信)
|
||||
"success_count": int, # 接口返回的导入成功行数
|
||||
"total_count": int, # 接口返回的需导入总行数(成功+异常,即本次需导入条数)
|
||||
"exceptions": [ # 全部异常明细
|
||||
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
|
||||
],
|
||||
}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# DrissionPage wait() 超时返回 False(非 None),统一按「无新响应」处理:
|
||||
# 若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 第一步「下一步」(格式校验/预览)也可能请求 getTmpDataPage.mc,但此时行内
|
||||
# imp_fixed_msg 为空;仅当携带导入结果说明(imp_fixed_msg 非空)时才视为真正的
|
||||
# 导入结果,空说明的预览/校验响应跳过,继续等待最终结果。
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
# 记录第一页 URL、请求 body 与总页数,用于主动翻页拉全(弹窗默认只加载第一页 15 条)
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
# 该接口为 POST,分页参数在 body 中,保存首次请求 body 供翻页复用
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
# 若接口存在多页(实际导入量超过一页 15 条),主动翻页拉取剩余页后结束
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 对外入口(函数传参调用)
|
||||
# ---------------------------------------------------------------
|
||||
# 参数兼容「增员/减员」短名 与「增员导入/减员导入」菜单全名
|
||||
_IMPORT_TYPE_MAP = {
|
||||
"增员": MENU_ADD,
|
||||
"减员": MENU_SUB,
|
||||
MENU_ADD: MENU_ADD,
|
||||
MENU_SUB: MENU_SUB,
|
||||
}
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label, file_path=None):
|
||||
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启对 getTmpDataPage.mc 的监听:HR 端流程调整后,
|
||||
结果接口可能在第一步「格式校验/预览」或第二步「真正导入」时触发,提前监听避免漏捕;
|
||||
监听捕获导入返回的全部异常,异常仅记录并上报,不中断导入流程。
|
||||
|
||||
Args:
|
||||
page: 已登录的 ChromiumPage 实例。
|
||||
category: 类别配置 dict。
|
||||
menu_label: 菜单文案(增员导入/减员导入)。
|
||||
file_path: 显式上传文件;不传则按类别文件夹取默认导入文件。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 导入文件不存在。
|
||||
"""
|
||||
file_path = file_path or (
|
||||
category_import_add_file(category) if menu_label == MENU_ADD
|
||||
else category_import_sub_file(category))
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 在第一个「下一步」前开启 getTmpDataPage.mc 监听,贯穿「格式校验/预览 + 真正导入」全过程
|
||||
# 监听启动失败必须上报:若静默继续,未捕获到异常会被误报为「正常」,产生假成功
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:下一步(格式校验/预览,同时可能在监听中触发结果接口)
|
||||
_click_next(page) # 第二步:下一步(真正导入内容,触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 上报:全部异常逐条打日志
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
|
||||
elif not import_result.get("listen_ok", True):
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page) # 第三步:关闭
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
def import_employee_change(import_type="增员", category_names=None, file_path=None):
|
||||
"""执行增员/减员导入(可一次传入一个或多个类别,复用同一浏览器)。
|
||||
|
||||
Args:
|
||||
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
file_path: 要上传的文件路径;若传入则对每个类别使用同一文件(覆盖类别解析);
|
||||
不传则按各类别文件夹取 商业保险增员导入.xlsx / 商业保险减员导入.xlsx。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 全部类别流程是否均完成
|
||||
"import_type": str, # 菜单文案(增员导入/减员导入)
|
||||
"categories": [str], # 类别名列表
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions);
|
||||
# 类别流程失败时含 error(错误信息)/error_type(异常类型)字段
|
||||
"exception_count": int, # 上传表格返回的异常总条数
|
||||
}
|
||||
|
||||
Raises:
|
||||
ValueError: import_type 非法。
|
||||
ImportError: 缺少 DrissionPage 依赖。
|
||||
"""
|
||||
setup_logging()
|
||||
if ChromiumPage is None:
|
||||
raise ImportError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
if import_type not in _IMPORT_TYPE_MAP:
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||
menu_label = _IMPORT_TYPE_MAP[import_type]
|
||||
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
logger.info("===== 开始%s,类别:%s =====", menu_label,
|
||||
[c["name"] for c in categories])
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入缓存 cookies,再访问页面
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
|
||||
ok = 0
|
||||
results = []
|
||||
for category in categories:
|
||||
try:
|
||||
res = _import_one(page, category, menu_label, file_path)
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
ok += 1
|
||||
except Exception as e:
|
||||
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"error": str(e),
|
||||
"error_type": type(e).__name__,
|
||||
})
|
||||
exception_count = sum(len(r.get("exceptions") or []) for r in results)
|
||||
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
|
||||
menu_label, ok, len(categories), exception_count)
|
||||
return {
|
||||
"success": ok == len(categories),
|
||||
"import_type": menu_label,
|
||||
"categories": [c["name"] for c in categories],
|
||||
"results": results,
|
||||
"exception_count": exception_count,
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main(category_names=None):
|
||||
"""执行的入口:对指定/全部类别一次性完成增员+减员导入,返回调用方需要的结构化结果。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表,空/None=全部类别。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 增员+减员全部类别是否均完成
|
||||
"categories": [str],
|
||||
"details": {"增员导入": bool, "减员导入": bool},
|
||||
"exceptions": [dict], # 全部异常明细(上传表格返回的异常 + 类别流程失败,合并增/减员)
|
||||
"exception_count": int, # 异常总条数
|
||||
}
|
||||
"""
|
||||
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||
else [c["name"] for c in CATEGORIES]
|
||||
details = {}
|
||||
exceptions = []
|
||||
ok_all = True
|
||||
for import_type in ("增员", "减员"):
|
||||
result = import_employee_change(import_type, category_names)
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
|
||||
ok_all = ok_all and result["success"]
|
||||
for r in result["results"]:
|
||||
r = r or {}
|
||||
category = r.get("category") or ""
|
||||
menu = r.get("menu") or ""
|
||||
# 类别流程本身失败(元素找不到/登录失败/文件缺失等):合并为一条异常上报,避免被漏报
|
||||
if r.get("error"):
|
||||
exceptions.append({
|
||||
"category": category,
|
||||
"menu": menu,
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
for exc in r.get("exceptions") or []:
|
||||
exceptions.append({
|
||||
"category": category,
|
||||
"menu": menu,
|
||||
"staff_code": exc["staff_code"],
|
||||
"staff_name": exc["staff_name"],
|
||||
"insurance_name": exc["insurance_name"],
|
||||
"message": exc["message"],
|
||||
})
|
||||
if exceptions:
|
||||
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
|
||||
for exc in exceptions:
|
||||
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
|
||||
exc["category"], exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
return {
|
||||
"success": ok_all,
|
||||
"categories": categories,
|
||||
"details": details,
|
||||
"exceptions": exceptions,
|
||||
"exception_count": len(exceptions),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
@@ -1,190 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险模块配置:集中管理文件路径、Sheet 名称、列名映射、校验常量等
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# ---------- 文件路径 ----------
|
||||
BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 输入/输出文件路径(三十七度默认,其余类别由 CATEGORIES 动态解析)
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」。
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位;
|
||||
# change_sheet_prefix: 步骤2调度时「变更清单」sheet 名称前缀(各类须统一该命名规则)。
|
||||
# scheme_suffix: 增员导入时「保险方案名称」追加的厂区后缀(HR 侧方案含后缀,
|
||||
# 如 人保-80万-秒创 / 人保-80万-湖畔 / 人保-80万-水庄;三十七度无后缀)。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
|
||||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称。"""
|
||||
return f"{category['change_sheet_prefix']}-{DATE_SHORT}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入文件(步骤3:在 HR「待增减人员」页面上传,aa.md 提供)
|
||||
ADD_SUB_IMPORT_ADD_FILE = os.path.join(BASE_DIR, "商业保险增员导入.xlsx")
|
||||
ADD_SUB_IMPORT_SUB_FILE = os.path.join(BASE_DIR, "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入模板(官方模板:第1行标题/第2行表头/第3行示例说明,第4行起填数据)
|
||||
ADD_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险增员导入模板.xlsx")
|
||||
SUB_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险减员导入模板.xlsx")
|
||||
|
||||
# 固定 Sheet 名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
CHANGE_SHEET_PREFIX = "37度-雇员变更清单"
|
||||
CHANGE_SHEET_NAME = f"{CHANGE_SHEET_PREFIX}-{DATE_SHORT}"
|
||||
|
||||
# ---------- 花名册列名映射(表头在第4行) ----------
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ---------- 校验常量 ----------
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
# ---------- 功能开关 ----------
|
||||
ENABLE_VALIDATION = False # True: 启用数据校验, False: 跳过校验(测试模式)
|
||||
|
||||
# ---------- 本场景 HR 花名册导出模板(roster_export 动态传入,取自 ehr/common 统一配置) ----------
|
||||
ROSTER_TEMPLATE_NAME = ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# 本场景需导出的在职状态(雇主险增减员只需在职人员,无需离职)
|
||||
ROSTER_EXPORT_STATUSES = ["在职"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,135 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.export_change_sheet
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统(app 版)「步骤2.5:导出变更清单独立工作簿」
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
【运行】python export_change_sheet.py [类别名]
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from copy import copy # noqa: E402
|
||||
from openpyxl import Workbook, load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
CATEGORIES,
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_name: str = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
@@ -1,236 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.roster_filter
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「步骤1:筛选复制」。从员工花名册按四大类别筛选数据,复制到各自类别的雇主险变更记录表
|
||||
(复刻 aa.md 的 WPS JS 宏,仅复制,不校验)
|
||||
- 源表:员工花名册.xlsx(统一格式:单 sheet、表头自动定位、业务列 B~O 14列)
|
||||
- 四大类别(config.CATEGORIES):三十七度 / 水庄餐饮 / 湖畔酒店 / 秒创传媒,各自独立文件夹
|
||||
- 过滤:按类别 include/exclude 所属单位(B列)+ 统一排除「虚拟大区」(C列/一级部门)
|
||||
- 目标:各文件夹内最新的「*雇主险变更记录*.xlsx」的「花名册导出-雇主险使用基础信息」sheet,表头第4行,数据第5行起(B~O 14列)
|
||||
- 源表缺失时自动调用 roster_export 从 HR 系统导出(输出位置由本场景指定)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
import pandas as pd # noqa: E402
|
||||
from openpyxl import load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
CATEGORIES,
|
||||
SHEET_BIZ,
|
||||
ROSTER_TEMPLATE_NAME,
|
||||
ROSTER_EXPORT_STATUSES,
|
||||
get_category,
|
||||
find_latest_target,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
|
||||
|
||||
# N列 姓名在数据切片(B~O)内的 0-based 索引
|
||||
NAME_COL = 12
|
||||
|
||||
# 源表统一格式规范(roster_export._merge_roster_files 输出):
|
||||
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||||
# 读取时自动定位表头行(B 列 =「所属单位」),业务列 B~O 共14列不受「类型」列影响
|
||||
SOURCE_HEADER_MARK = "所属单位" # 表头定位标记(B列)
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
|
||||
def filter_and_copy_roster(category: dict, employee_file: str = None, target_file: str = None) -> int:
|
||||
"""
|
||||
从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(config.CATEGORIES 中的一项),含 name/folder/include_dept/exclude_dept
|
||||
employee_file: 源表路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category["folder"]))
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
probe = pd.read_excel(employee_file, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_file, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~(region == EXCLUDE_REGION)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS))
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行,避免大范围逐格清空) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据,本地化 cell 引用减少开销)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
cell(row=i, column=j).value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def export_roster_for_employer_insurance(download_dir: str = None, ttl: int = None) -> str:
|
||||
"""按本场景模板「雇主险增减员导出模板」导出花名册(复用 roster_export,操作 HR 系统)。
|
||||
|
||||
输出位置由本场景指定:D:\\资料\\人资\\雇主险\\员工花名册.xlsx(与筛选复制的源表路径一致)。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 roster_export 的默认目录。
|
||||
ttl: 缓存有效期(秒),None 用 roster_export 默认(15 分钟);传 0 强制重新导出。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
"""
|
||||
from app.service.hrbp.ehr.roster.roster_export import export_roster
|
||||
output_path = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
logger.info("按本场景模板 [%s] 导出花名册(在职状态:%s),输出:%s",
|
||||
ROSTER_TEMPLATE_NAME, ROSTER_EXPORT_STATUSES, output_path)
|
||||
return export_roster(download_dir=download_dir, template_name=ROSTER_TEMPLATE_NAME,
|
||||
output_path=output_path, statuses=ROSTER_EXPORT_STATUSES, ttl=ttl)
|
||||
|
||||
|
||||
def main(category_name: str = None) -> None:
|
||||
"""步骤1:就绪检查 + 导出(如需)+ 类别筛选复制。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance.py)。
|
||||
"""
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
|
||||
# 命令行第一个非 -- 参数可作为类别名(如:python roster_filter.py 湖畔酒店)
|
||||
if not category_name:
|
||||
for a in args:
|
||||
if not a.startswith("--"):
|
||||
category_name = a
|
||||
break
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出;--export-roster 为显式强制导出(ttl=0 绕过缓存)
|
||||
force = "--export-roster" in args
|
||||
if force or not os.path.exists(EMPLOYEE_FILE):
|
||||
export_roster_for_employer_insurance(ttl=0 if force else None)
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 逐类别筛选复制(目标文件=各文件夹内最新的雇主险变更记录)
|
||||
ok = 0
|
||||
for category in categories:
|
||||
try:
|
||||
target_file = find_latest_target(category["folder"])
|
||||
except FileNotFoundError as e:
|
||||
logger.error("跳过类别[%s]:%s", category["name"], e)
|
||||
continue
|
||||
logger.info("=" * 70)
|
||||
logger.info("处理类别[%s],目标文件:%s", category["name"], target_file)
|
||||
try:
|
||||
n = filter_and_copy_roster(category, target_file=target_file)
|
||||
ok += 1
|
||||
logger.info("类别[%s] 完成,写入 %d 行", category["name"], n)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 处理失败", category["name"])
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成(成功 %d/%d 个类别)。请手动打开各目标文件刷新公式计算结果(Ctrl+S 保存),",
|
||||
ok, len(categories))
|
||||
logger.info("确认无误后运行:python employer_insurance.py schedule")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,650 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 员工花名册自定义导出。复用 HR 系统登录及缓存 cookies,通过 DrissionPage 浏览器自动化
|
||||
按 aa.md 流程操作:进入花名册页 -> 组织机构(集团) -> 在职状态=在职 -> 更多操作 -> 自定义导出
|
||||
-> 选择模板「员工基础信息」-> 确认导出,并接收浏览器下载的文件到指定目录。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可触发花名册导出(会弹出浏览器窗口,请勿关闭)。
|
||||
3. 下载目录默认取环境变量 roster_output_dir,否则使用项目根目录。
|
||||
|
||||
底层复用:
|
||||
- HR 登录 & cookies:app.service.hrbp.common.login(load_cookies / login)
|
||||
- 页面地址 & 模板名:app.service.hrbp.ehr.common.config(ROSTER_URL / ROSTER_TEMPLATE_NAME)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
from app.utils.logger import setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
# 底层复用:HR 登录 / cookies / 配置 / 重试 / 离职时间范围
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_URL, ROSTER_TEMPLATE_NAME # noqa: E402
|
||||
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_download import get_leave_range # noqa: E402
|
||||
from app.utils.intelligent_retry import retry # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
PERSON_STATUSES = ["在职", "离职"] # 需导出的在职状态(按顺序逐次导出)
|
||||
BTN_MORE = "更多操作" # 更多操作按钮
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索" # 展开更多筛选条件(离职时间等)
|
||||
LEAVE_RANGE_PLACEHOLDER = "请选择离职时间"
|
||||
FILTER_XPATH = 'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="筛选"]'
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_BEGIN_TIMEOUT = 60 # 等待下载开始
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
|
||||
# 输出目录 & 合并文件名
|
||||
OUTPUT_DIR = r"D:\资料\人资\员工花名册"
|
||||
MERGED_NAME = "员工花名册.xlsx"
|
||||
|
||||
# 花名册 TTL 缓存有效期(秒):按传入 output_path 的 mtime 判断,
|
||||
# 15 分钟内已导出过则直接复用该文件(不弹浏览器),超时才重新导出;传 ttl=0 表示总是重导。
|
||||
ROSTER_TTL_SECONDS = 15 * 60
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 元素定位辅助(DrissionPage)
|
||||
# ---------------------------------------------------------------
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _ensure_person_status(page, status="在职"):
|
||||
"""将「在职状态」筛选设置为仅选中指定状态(在职/离职)。
|
||||
|
||||
注意:该筛选为多选下拉(在职/离职/退休/返聘),需要取消其它已选项,
|
||||
仅保留目标状态,避免导出时把多个状态混在一起。
|
||||
"""
|
||||
container = page.ele('css:div[component-div*="person_status"]', timeout=15)
|
||||
if not container:
|
||||
raise RuntimeError("未找到「在职状态」筛选控件")
|
||||
select = container.ele('css:.el-select', timeout=5)
|
||||
if not select:
|
||||
raise RuntimeError("未找到「在职状态」下拉框")
|
||||
|
||||
# 打开下拉,等待可见面板出现(下拉关闭时选项仍在 DOM 但不可见,必须取可见面板内的选项)
|
||||
select.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
||||
if not panel:
|
||||
select.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
||||
if not panel:
|
||||
raise RuntimeError("在职状态下拉面板未能展开")
|
||||
|
||||
items = panel.eles('css:li.el-select-dropdown__item')
|
||||
if not items:
|
||||
raise RuntimeError("在职状态下拉中没有选项")
|
||||
|
||||
# 文本 -> 选项元素
|
||||
opt_map = {}
|
||||
for it in items:
|
||||
txt = (it.text or "").strip()
|
||||
if txt:
|
||||
opt_map[txt] = it
|
||||
if status not in opt_map:
|
||||
raise RuntimeError(f"在职状态下拉中不存在选项:{status}")
|
||||
|
||||
# 仅保留目标状态选中,其余取消选中
|
||||
for txt, it in opt_map.items():
|
||||
is_selected = "selected" in (it.attr('class') or "")
|
||||
need = (txt == status)
|
||||
if is_selected != need:
|
||||
logger.info("在职状态选项「%s」%s", txt, "选中" if need else "取消选中")
|
||||
it.click()
|
||||
time.sleep(0.2)
|
||||
|
||||
# 关闭下拉(再次点击外壳切换收起)
|
||||
try:
|
||||
select.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("在职状态已设为仅「%s」", status)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""确保「更多搜索」popover 已展开,返回是否成功。
|
||||
|
||||
通过按钮的 aria-describedby 属性找到 popover 内容元素,检查其是否可见来判断展开状态。
|
||||
按钮特征:class 含 search-more-condition-btn / el-popover__reference,外层容器 demo-search-more。
|
||||
"""
|
||||
# 定位「更多搜索」按钮
|
||||
btn = page.ele('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btn:
|
||||
btn = page.ele('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
if not btn:
|
||||
logger.warning("未找到「更多搜索」按钮")
|
||||
return False
|
||||
|
||||
for _ in range(3):
|
||||
# 通过 aria-describedby 找到 popover 元素,检查是否可见
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return True
|
||||
# 兜底:检查是否有可见的「筛选」按钮
|
||||
fb = page.ele(FILTER_XPATH, timeout=2)
|
||||
if fb and _is_displayed(fb):
|
||||
logger.info("更多搜索已展开(检测到可见的「筛选」按钮)")
|
||||
return True
|
||||
# 用 JS 直接 click() 触发 Element UI popover(纯选择器,避免传参问题)
|
||||
page.run_js(
|
||||
'var b=document.querySelector("button.search-more-condition-btn");'
|
||||
'if(b){b.click();}'
|
||||
)
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return False
|
||||
|
||||
|
||||
def _click_filter(page):
|
||||
"""点击更多搜索弹层底部的「筛选」按钮,应用离职时间等筛选条件。
|
||||
|
||||
全部在 JS 中完成:定位 popover -> 在 popover 内部找文本为「筛选」的按钮 -> 直接 .click()。
|
||||
之前全页面搜索可能找到错误的「筛选」按钮,现在限定在 popover 容器内查找。
|
||||
"""
|
||||
result = page.run_js(
|
||||
'var b=document.querySelector("button.search-more-condition-btn");'
|
||||
'if(!b){return "no_btn_more";}'
|
||||
'var id=b.getAttribute("aria-describedby");'
|
||||
'if(!id){return "no_id";}'
|
||||
'var pop=document.getElementById(id);'
|
||||
'if(!pop){return "no_popover:"+id;}'
|
||||
'var btns=pop.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn:"+id;'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _set_leave_date_range(page, leave_start=None, leave_end=None):
|
||||
"""设置「离职时间」筛选范围并应用,时间规则与工资卡离职导出一致(get_leave_range)。"""
|
||||
if not leave_start or not leave_end:
|
||||
leave_start, leave_end = get_leave_range()
|
||||
|
||||
if not _open_more_search(page):
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置离职时间")
|
||||
logger.info("设置离职时间范围:%s ~ %s", leave_start, leave_end)
|
||||
rng = page.ele(f'css:div.split-datetime-range[placeholder="{LEAVE_RANGE_PLACEHOLDER}"]', timeout=10)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「离职时间」选择器")
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到离职时间起止输入框")
|
||||
# 填入日期后按回车确认(input() 无 enter 参数,用 Actions 补回车)
|
||||
start_input.input(leave_start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(leave_end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("离职时间已设置:%s ~ %s", leave_start, leave_end)
|
||||
|
||||
_click_filter(page)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. 打开花名册页并确保登录态(复用缓存 cookies)
|
||||
# ---------------------------------------------------------------
|
||||
def _ensure_logged_in(page):
|
||||
"""访问花名册页面;若被重定向到登录页,则复用/重登 HR 登录态。"""
|
||||
page.get(ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
logger.info("HR 登录态已失效,执行重新登录")
|
||||
from app.service.hrbp.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 重新登录失败")
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
page.set.cookies(cookies)
|
||||
page.get(ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError("HR 重新登录后仍停留在登录页")
|
||||
logger.info("已进入花名册页面:%s", page.url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. 花名册导出主流程(aa.md 步骤)
|
||||
# ---------------------------------------------------------------
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
# 步骤1:点击左侧「组织机构」,切换为组织树
|
||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||||
if org_tab:
|
||||
org_tab.click()
|
||||
logger.info("已点击左侧「组织机构」")
|
||||
time.sleep(WAIT_MID)
|
||||
else:
|
||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||||
_click_text(page, TAB_ORG)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 步骤2:点击组织树根节点「集团」
|
||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||||
if not group:
|
||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||||
if not group:
|
||||
raise RuntimeError("组织树中未找到「集团」节点")
|
||||
group.click()
|
||||
logger.info("已点击组织树根节点「集团」")
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
|
||||
def _open_custom_export_dialog(page):
|
||||
"""点击「更多操作」->「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||||
# 若导出弹窗已打开(存在「模板」下拉),直接返回
|
||||
tpl_label = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||||
if tpl_label and _is_displayed(tpl_label):
|
||||
logger.info("导出弹窗已打开,跳过「更多操作」")
|
||||
time.sleep(WAIT_MID)
|
||||
return
|
||||
|
||||
# 步骤3:点击「更多操作」按钮
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=15)
|
||||
if more_btn:
|
||||
more_btn.click()
|
||||
else:
|
||||
_click_text(page, BTN_MORE)
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
# 步骤4:点击「自定义导出」
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if menu:
|
||||
_click_text_in(page, menu, MENU_CUSTOM_EXPORT)
|
||||
else:
|
||||
_click_text(page, MENU_CUSTOM_EXPORT)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=ROSTER_TEMPLATE_NAME):
|
||||
"""在导出弹窗中选择自定义导出模板。"""
|
||||
# 步骤5:定位「模板」下拉框容器(含「模板」前置标签的 el-select)
|
||||
tpl = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||||
'/following-sibling::div[contains(@class,"el-select")]',
|
||||
timeout=15,
|
||||
)
|
||||
if not tpl:
|
||||
raise RuntimeError("未找到「模板」下拉框")
|
||||
|
||||
# 确保下拉面板已展开(下拉面板会 teleport 到 body,需在页面级查找可见面板)
|
||||
panel = None
|
||||
for _ in range(3):
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||||
if panel and _is_displayed(panel):
|
||||
break
|
||||
tpl.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
if not panel:
|
||||
raise RuntimeError("模板下拉面板未能展开")
|
||||
|
||||
# 步骤6:在可见面板中选择模板(如「员工基础信息」)
|
||||
opt = panel.ele(
|
||||
f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||||
timeout=5,
|
||||
)
|
||||
if not opt:
|
||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||||
opt.click()
|
||||
logger.info("已选择模板:%s", template_name)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_confirm_export(page):
|
||||
"""点击「确认导出」,触发下载。"""
|
||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||||
timeout=10)
|
||||
if not btn:
|
||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「确认导出」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 下载等待
|
||||
# ---------------------------------------------------------------
|
||||
def _wait_download(page, download_dir, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。
|
||||
|
||||
采用文件系统轮询:统计下载目录中新增的、非临时文件,当其大小两次采样一致
|
||||
视为下载完成。避免依赖 DrissionPage 下载任务状态(可能卡在 100% 不结束)。
|
||||
"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
before = set(os.listdir(download_dir))
|
||||
deadline = time.time() + timeout
|
||||
last_sizes = {}
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
files = os.listdir(download_dir)
|
||||
except Exception:
|
||||
files = []
|
||||
for f in files:
|
||||
if f in before or f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||||
continue
|
||||
p = os.path.join(download_dir, f)
|
||||
if not os.path.isfile(p):
|
||||
continue
|
||||
try:
|
||||
size = os.path.getsize(p)
|
||||
except Exception:
|
||||
continue
|
||||
if size <= 0:
|
||||
continue
|
||||
if last_sizes.get(p) == size:
|
||||
logger.info("花名册导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||||
return p
|
||||
last_sizes[p] = size
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 5. 合并多个花名册 Excel 为一个,添加「类型」列
|
||||
# ---------------------------------------------------------------
|
||||
def _merge_roster_files(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态(在职/离职)
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
|
||||
Args:
|
||||
files_with_status: [(status, file_path), ...] 列表
|
||||
output_path: 合并后文件保存路径
|
||||
|
||||
Returns:
|
||||
合并后文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法合并 Excel")
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status # 类型列统一追加到最后一列
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
|
||||
# 删除临时下载的单个文件
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 6. 对外入口
|
||||
# ---------------------------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _export_one_status(page, status, download_dir, template_name):
|
||||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。
|
||||
|
||||
Args:
|
||||
template_name: 自定义导出模板名(如「员工基础信息」「雇主险增减员导出模板」)。
|
||||
"""
|
||||
logger.info(">>> 开始导出在职状态:%s(模板:%s)", status, template_name)
|
||||
try:
|
||||
_ensure_person_status(page, status)
|
||||
if status == "离职":
|
||||
_set_leave_date_range(page)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
_click_confirm_export(page)
|
||||
logger.info(">>> 等待在职状态「%s」的导出文件下载", status)
|
||||
path = _wait_download(page, download_dir)
|
||||
logger.info(">>> 在职状态「%s」导出完成", status)
|
||||
return path
|
||||
except Exception:
|
||||
logger.exception("导出在职状态「%s」失败,详细堆栈如下:", status)
|
||||
raise
|
||||
|
||||
|
||||
def export_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE_NAME,
|
||||
output_path: str = None, statuses: list = None,
|
||||
ttl: int = ROSTER_TTL_SECONDS) -> str:
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过浏览器自动化),
|
||||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||||
不同模板导出到不同路径,不会互相复用。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。
|
||||
template_name: 自定义导出模板名,可按业务场景动态传入(默认「员工基础信息」)。
|
||||
output_path: 合并后文件的保存路径,由调用方传入(如某业务目录下的花名册文件);
|
||||
默认使用 OUTPUT_DIR/员工花名册.xlsx。
|
||||
statuses: 需要导出的在职状态列表,默认 ["在职", "离职"];
|
||||
业务场景可按需传入(如雇主险只需在职时传 ["在职"])。
|
||||
ttl: 缓存有效期(秒),默认 ROSTER_TTL_SECONDS(15 分钟);传 0 表示总是重新导出。
|
||||
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 任何流程步骤失败或下载未检测到时抛出。
|
||||
"""
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
statuses = list(statuses) if statuses else list(PERSON_STATUSES)
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
output_path = os.path.abspath(output_path or os.path.join(OUTPUT_DIR, MERGED_NAME))
|
||||
if ttl is None: # None 使用默认缓存有效期
|
||||
ttl = ROSTER_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用,跳过浏览器导出
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s),下载目录:%s =====",
|
||||
template_name, statuses, download_dir)
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入缓存 cookies,再访问页面
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
|
||||
# 下载目录设置需在触发下载前完成
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(page, status, download_dir, template_name)
|
||||
files_with_status.append((status, path))
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 合并所有花名册文件
|
||||
merged_path = output_path # 已在函数开头按默认值归一化
|
||||
os.makedirs(os.path.dirname(merged_path), exist_ok=True)
|
||||
result = _merge_roster_files(files_with_status, merged_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def debug_filter_only():
|
||||
"""调试模式:只执行到筛选结束,不导出,浏览器保持打开供检查。"""
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
logger.info("===== 调试模式:仅执行到筛选结束 =====")
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
|
||||
_ensure_person_status(page, "离职")
|
||||
_set_leave_date_range(page)
|
||||
|
||||
logger.info("===== 筛选已执行完毕,浏览器保持打开,按回车关闭 =====")
|
||||
input("按回车键关闭浏览器...")
|
||||
except Exception as e:
|
||||
logger.error("调试失败:%s", e)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python roster_export.py [下载目录] [模板名]
|
||||
|
||||
模板名也可通过环境变量 roster_template 传入,优先级:命令行参数 > 环境变量 > 默认「员工基础信息」。
|
||||
"""
|
||||
setup_logging()
|
||||
|
||||
# 调试模式:仅执行到筛选结束
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "debug":
|
||||
debug_filter_only()
|
||||
return
|
||||
|
||||
download_dir = os.getenv("roster_output_dir")
|
||||
if not download_dir and len(sys.argv) > 1 and sys.argv[1] != "debug":
|
||||
download_dir = sys.argv[1]
|
||||
|
||||
template_name = os.getenv("roster_template")
|
||||
if not template_name and len(sys.argv) > 2:
|
||||
template_name = sys.argv[2]
|
||||
template_name = template_name or ROSTER_TEMPLATE_NAME
|
||||
|
||||
try:
|
||||
out = export_roster(download_dir, template_name)
|
||||
logger.info("===== 花名册导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,317 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.roster.roster_query
|
||||
@FileName: roster_query.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 花名册共享查询模块 —— 根据员工工号查询:
|
||||
1. 店长查询:返回其所在四级部门的店长工号与姓名(岗位含「店长」,多个取第一个);
|
||||
2. 人事查询:返回其所在经营中心(二级部门含「经营中心」)岗位含「人事」的全部名单;
|
||||
特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(梁敏/37001302),不查花名册。
|
||||
两类查询均支持批量(花名册只读一次)。供「告知书制作与下发」等业务流程复用。
|
||||
@Version: 1.2.0
|
||||
|
||||
使用方式(库函数,参数直接传):
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
find_store_manager, find_store_manager_batch,
|
||||
find_hr_personnel, find_hr_personnel_batch)
|
||||
- find_store_manager(工号, 花名册路径) -> {"success", "error", "manager_code", "manager_name"}
|
||||
- find_hr_personnel(工号, 花名册路径) -> {"success", "error", "dept", "personnel": [{"工号","姓名"}, ...]}
|
||||
- 批量:find_*_batch(工号列表, 花名册路径) -> {工号: 对应单查结果, ...}
|
||||
"""
|
||||
|
||||
import numbers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 默认花名册路径(告知书制作与下发)
|
||||
DEFAULT_ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx"
|
||||
|
||||
# 花名册字段列名(与 aa.md 字段一致)
|
||||
COL_NAME = "姓名" # 姓名
|
||||
COL_CODE = "工号" # 工号
|
||||
COL_DEPT2 = "二级部门" # 二级部门(经营中心)
|
||||
COL_DEPT4 = "四级部门" # 四级部门
|
||||
COL_POSITION = "岗位" # 岗位
|
||||
|
||||
# 岗位关键字(岗位字段包含对应关键字即视为该岗位)
|
||||
MANAGER_KEYWORD = "店长" # 店长岗位关键字
|
||||
HR_KEYWORD = "人事" # 人事岗位关键字
|
||||
DEPT2_MARK = "经营中心" # 二级部门需包含的经营中心标记
|
||||
|
||||
# 人事查询特殊分支:二级部门为「石桥铺会馆」时,不查花名册,直接返回固定人事名单
|
||||
DEPT2_HR_OVERRIDE = {
|
||||
"石桥铺会馆": [{"工号": "37001302", "姓名": "梁敏"}],
|
||||
}
|
||||
|
||||
|
||||
# ==================== 工具函数 ====================
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致匹配失败。
|
||||
|
||||
整型 float(如 37036835.0)去掉小数点后转 str,保证与文本工号("37036835")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _read_roster(roster_path):
|
||||
"""读取花名册,自动定位表头行(含「工号」列的行),返回 DataFrame(列名为字段名)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径
|
||||
|
||||
Returns:
|
||||
pd.DataFrame
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件不存在
|
||||
ValueError: 未找到表头行或缺少必需列(工号/姓名/二级部门/四级部门/岗位)
|
||||
"""
|
||||
roster_path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
|
||||
# 先不设表头读取前几行,定位含「工号」字段的表头行
|
||||
probe = pd.read_excel(roster_path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{roster_path}")
|
||||
|
||||
df = pd.read_excel(roster_path, header=header_row)
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT2, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({roster_path})")
|
||||
return df
|
||||
|
||||
|
||||
def _prepare_df(df):
|
||||
"""统一工号列文本格式并过滤空行,返回预处理后的 DataFrame(副本)。"""
|
||||
df = df.copy()
|
||||
df[COL_CODE] = df[COL_CODE].map(_to_text)
|
||||
return df[df[COL_CODE].notna()]
|
||||
|
||||
|
||||
# ==================== 核心查询 ====================
|
||||
def _find_store_manager_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询店长(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 2. 根据工号查四级部门
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
|
||||
# 3. 无四级部门 -> 返回查询失败、空结果
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门", code)
|
||||
return {"success": False, "error": f"员工(工号 {code})无四级部门",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 4. 在该四级部门内找岗位包含「店长」的人
|
||||
candidates = df[
|
||||
(df[COL_DEPT4].map(_to_text) == dept4)
|
||||
& (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))
|
||||
]
|
||||
if candidates.empty:
|
||||
logger.warning("四级部门「%s」内未找到店长(工号 %s)", dept4, code)
|
||||
return {"success": False, "error": f"四级部门「{dept4}」内未找到店长",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 5. 命中多个时取第一个(按花名册行序)
|
||||
first = candidates.iloc[0]
|
||||
manager_code = _to_text(first[COL_CODE])
|
||||
manager_name = _to_text(first[COL_NAME]) or ""
|
||||
logger.info("工号 %s -> 四级部门「%s」-> 店长 %s(工号 %s)",
|
||||
code, dept4, manager_name, manager_code)
|
||||
return {"success": True, "error": None,
|
||||
"manager_code": manager_code, "manager_name": manager_name}
|
||||
|
||||
|
||||
def _find_hr_personnel_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询经营中心人事名单(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
# 2. 校验二级部门
|
||||
dept2 = _to_text(row.iloc[0][COL_DEPT2]) or ""
|
||||
|
||||
# 2.1 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(不查花名册)
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
personnel = [dict(p) for p in DEPT2_HR_OVERRIDE[dept2]]
|
||||
logger.info("工号 %s -> 二级部门「%s」-> 固定人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
if DEPT2_MARK not in dept2:
|
||||
logger.warning("员工(工号 %s)二级部门「%s」不包含「%s」", code, dept2, DEPT2_MARK)
|
||||
return {"success": False, "error": f"员工(工号 {code})二级部门不包含「{DEPT2_MARK}」",
|
||||
"dept": dept2 or None, "personnel": []}
|
||||
|
||||
# 3. 查询该经营中心下岗位包含「人事」的所有名单
|
||||
candidates = df[
|
||||
(df[COL_DEPT2].map(_to_text) == dept2)
|
||||
& (df[COL_POSITION].astype(str).str.contains(HR_KEYWORD, na=False))
|
||||
]
|
||||
personnel = [
|
||||
{"工号": _to_text(r[COL_CODE]), "姓名": _to_text(r[COL_NAME]) or ""}
|
||||
for _, r in candidates.iterrows()
|
||||
]
|
||||
logger.info("工号 %s -> 经营中心「%s」-> 人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
|
||||
def _error_result(code, e):
|
||||
"""读取花名册失败时的统一错误结果(店长/人事两种结构)。"""
|
||||
return {
|
||||
"store": {"success": False, "error": str(e),
|
||||
"manager_code": None, "manager_name": None},
|
||||
"hr": {"success": False, "error": str(e), "dept": None, "personnel": []},
|
||||
}
|
||||
|
||||
|
||||
def find_store_manager(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在四级部门的店长工号与姓名(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int,如 "37036835" / 37036835)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 无四级部门 / 部门内无店长 / 读取异常)
|
||||
manager_code: str|None 店长工号
|
||||
manager_name: str|None 店长姓名
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["store"]
|
||||
return _find_store_manager_in_df(df, code)
|
||||
|
||||
|
||||
def find_store_manager_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号的店长(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_store_manager 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["store"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_store_manager_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
|
||||
def find_hr_personnel(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在经营中心(二级部门)岗位包含「人事」的全部名单(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 二级部门不包含经营中心 / 读取异常)
|
||||
dept: str|None 二级部门(经营中心)
|
||||
personnel: list 人事名单 [{"工号": str, "姓名": str}, ...]
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["hr"]
|
||||
return _find_hr_personnel_in_df(df, code)
|
||||
|
||||
|
||||
def find_hr_personnel_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号所在经营中心的人事名单(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_hr_personnel 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["hr"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_hr_personnel_in_df(df, _to_text(c)) for c in codes}
|
||||
@@ -1,7 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
"""
|
||||
@@ -1,527 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: pre_entry_roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-24
|
||||
@Description: 预入职台账自定义导出(排班异常识别模块)。复用 HR 登录及缓存 cookies,通过 DrissionPage
|
||||
浏览器自动化按 aa.md 流程操作:进入预入职台账页 -> 组织机构(集团) -> 点击「已入职」
|
||||
-> 更多搜索 -> 输入预入职日期(近30天)-> 筛选 -> 自定义导出 -> 选择模板「排班异常识别导出」
|
||||
-> 确认导出,并接收浏览器下载的文件到指定目录。参考花名册导出(roster_export.py)实现。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可触发预入职台账导出(会弹出浏览器窗口,请勿关闭)。
|
||||
3. 下载/输出目录可通过环境变量 pre_entry_output_dir 覆盖,默认项目根目录。
|
||||
|
||||
底层复用:
|
||||
- HR 登录 & cookies:app.service.hrbp.common.login(load_cookies / login)
|
||||
- 页面地址 & 模板名:app.service.hrbp.ehr.common.config(PRE_ENTRY_ROSTER_URL / ROSTER_TEMPLATE_SHIFT_ABNORMAL)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
from app.utils.logger import setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
# 底层复用:HR 登录 / cookies / 配置 / 重试
|
||||
from app.service.hrbp.ehr.common.config import ( # noqa: E402
|
||||
PRE_ENTRY_ROSTER_URL,
|
||||
ROSTER_TEMPLATE_SHIFT_ABNORMAL,
|
||||
)
|
||||
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
||||
from app.utils.intelligent_retry import retry # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
TAB_ONBOARDED = "已入职" # 预入职台账「已入职」tab(只导已入职预排班)
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索" # 展开更多筛选条件(预入职日期等)
|
||||
PRE_ENTRY_RANGE_PLACEHOLDER = "请选择预入职日期"
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_BEGIN_TIMEOUT = 60 # 等待下载开始
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
|
||||
# 输出目录 & 文件名
|
||||
OUTPUT_DIR = r"D:\资料\人资\排班异常识别"
|
||||
SAVE_NAME = "预入职台账.xlsx"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 预入职日期范围(近30天)
|
||||
# ---------------------------------------------------------------
|
||||
def get_pre_entry_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算预入职日期筛选范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
默认「近30天」:取今天往前 days 天(含今天)。因为已点击「已入职」tab,
|
||||
这批是已入职人员,预入职日期落在过去 30 天内。若业务窗口不同,可传 days 调整。
|
||||
"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. 元素定位辅助(DrissionPage)
|
||||
# ---------------------------------------------------------------
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_more_search_button(page):
|
||||
"""定位当前活跃 tab 的「更多搜索」按钮。
|
||||
|
||||
该页面每个 tab 各有一个「更多搜索」按钮,但只有活跃 tab 的按钮可见。
|
||||
浏览器里所有按钮都在 DOM 中,因此必须只取可见的那一个,避免展开错 tab 的 popover。
|
||||
"""
|
||||
btns = page.eles('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btns:
|
||||
btns = page.eles('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btns:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
return btn if _is_displayed(btn) else None
|
||||
for b in btns:
|
||||
if _is_displayed(b):
|
||||
return b
|
||||
logger.warning("未找到可见的「更多搜索」按钮(DOM 中共 %d 个)", len(btns))
|
||||
return None
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""展开当前活跃 tab 的「更多搜索」popover,返回其内容元素;失败返回 None。"""
|
||||
btn = _find_more_search_button(page)
|
||||
if not btn:
|
||||
return None
|
||||
|
||||
for _ in range(3):
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return popover
|
||||
# 用 JS 直接 click() 触发 Element UI popover,确保点击的是该活跃按钮自身
|
||||
try:
|
||||
btn.run_js('this.click();')
|
||||
except Exception:
|
||||
btn.click()
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return None
|
||||
|
||||
|
||||
def _click_filter(page, popover):
|
||||
"""点击活跃 tab「更多搜索」弹层底部的「筛选」按钮,应用预入职日期等筛选条件。
|
||||
|
||||
限定在传入的 popover 容器内查找,只点本 tab 的「筛选」,避免误点其它 tab 的。
|
||||
"""
|
||||
result = popover.run_js(
|
||||
'var btns=this.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn";'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _find_visible_range_input(page, placeholder):
|
||||
"""在页面级查找可见的预入职日期选择器。
|
||||
|
||||
页面宽度不同会动态布局:页面较宽时选择器直接显示在搜索栏(不在弹层里);
|
||||
页面较窄时它才折叠进「更多搜索」弹层。因此要遍历所有同名元素取可见的第一个。
|
||||
"""
|
||||
rngs = page.eles(f'css:div.split-datetime-range[placeholder="{placeholder}"]', timeout=3)
|
||||
for r in rngs:
|
||||
if _is_displayed(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def _fill_range(page, rng, start, end):
|
||||
"""填入日期范围并回车确认。"""
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到预入职日期起止输入框")
|
||||
# input() 无 enter 参数,用 Actions 补回车
|
||||
start_input.input(start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("预入职日期已设置:%s ~ %s", start, end)
|
||||
|
||||
|
||||
def _set_pre_entry_date_range(page, start=None, end=None):
|
||||
"""设置「预入职日期」筛选范围(近30天)并应用筛选。
|
||||
|
||||
页面宽度决定选择器位置,但「筛选」按钮始终在「更多搜索」弹层底部,因此必须展开弹层:
|
||||
- 页面较宽时选择器直接在搜索栏:填完日期后仍点弹层内「筛选」;
|
||||
- 页面较窄时选择器折叠进弹层:填日期后点弹层内「筛选」。
|
||||
"""
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("设置预入职日期范围:%s ~ %s", start, end)
|
||||
|
||||
popover = _open_more_search(page)
|
||||
if not popover:
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置预入职日期")
|
||||
|
||||
# 先找页面级可见的选择器(页面较宽时在搜索栏);找不到再到弹层内找
|
||||
rng = _find_visible_range_input(page, PRE_ENTRY_RANGE_PLACEHOLDER)
|
||||
if not rng:
|
||||
rng = popover.ele(
|
||||
f'css:div.split-datetime-range[placeholder="{PRE_ENTRY_RANGE_PLACEHOLDER}"]', timeout=5)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「预入职日期」选择器")
|
||||
_fill_range(page, rng, start, end)
|
||||
_click_filter(page, popover)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. 打开预入职台账页并确保登录态(复用缓存 cookies)
|
||||
# ---------------------------------------------------------------
|
||||
def _ensure_logged_in(page):
|
||||
"""访问预入职台账页面;若被重定向到登录页,则复用/重登 HR 登录态。"""
|
||||
page.get(PRE_ENTRY_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
logger.info("HR 登录态已失效,执行重新登录")
|
||||
from app.service.hrbp.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 重新登录失败")
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
page.set.cookies(cookies)
|
||||
page.get(PRE_ENTRY_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError("HR 重新登录后仍停留在登录页")
|
||||
logger.info("已进入预入职台账页面:%s", page.url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 预入职台账导出主流程(aa.md 步骤)
|
||||
# ---------------------------------------------------------------
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
# 步骤1:点击左侧「组织机构」,切换为组织树
|
||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||||
if org_tab:
|
||||
org_tab.click()
|
||||
logger.info("已点击左侧「组织机构」")
|
||||
time.sleep(WAIT_MID)
|
||||
else:
|
||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||||
_click_text(page, TAB_ORG)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 步骤2:点击组织树根节点「集团」
|
||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||||
if not group:
|
||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||||
if not group:
|
||||
raise RuntimeError("组织树中未找到「集团」节点")
|
||||
group.click()
|
||||
logger.info("已点击组织树根节点「集团」")
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
|
||||
def _click_onboarded_tab(page):
|
||||
"""步骤3:点击「已入职」tab,只保留已入职的预入职人员。"""
|
||||
tab = page.ele('xpath://div[contains(@class,"tab-info")]//*[normalize-space(.)="{TAB}"]'
|
||||
.format(TAB=TAB_ONBOARDED), timeout=10)
|
||||
if not tab:
|
||||
tab = _click_text(page, TAB_ONBOARDED)
|
||||
return
|
||||
tab.click()
|
||||
logger.info("已点击「%s」tab", TAB_ONBOARDED)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _open_custom_export_dialog(page):
|
||||
"""点击「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||||
# 若导出弹窗已打开(存在「模板」下拉),直接返回
|
||||
tpl_label = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||||
if tpl_label and _is_displayed(tpl_label):
|
||||
logger.info("导出弹窗已打开,跳过「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
return
|
||||
|
||||
# 步骤4:点击「自定义导出」
|
||||
btn = page.ele('xpath://button[normalize-space(.)="自定义导出"]', timeout=15)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://*[contains(@class,"btn") and normalize-space(.)="自定义导出"]', timeout=5)
|
||||
if not btn:
|
||||
raise RuntimeError("未找到「自定义导出」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=ROSTER_TEMPLATE_SHIFT_ABNORMAL):
|
||||
"""步骤5-6:选择导出模板「排班异常识别导出」。"""
|
||||
# 定位「模板」下拉框容器(含「模板」前置标签的 el-select)
|
||||
tpl = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||||
'/following-sibling::div[contains(@class,"el-select")]',
|
||||
timeout=15,
|
||||
)
|
||||
if not tpl:
|
||||
raise RuntimeError("未找到「模板」下拉框")
|
||||
|
||||
# 确保下拉面板已展开(下拉面板会 teleport 到 body,需在页面级查找可见面板)
|
||||
panel = None
|
||||
for _ in range(3):
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||||
if panel and _is_displayed(panel):
|
||||
break
|
||||
tpl.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
if not panel:
|
||||
raise RuntimeError("模板下拉面板未能展开")
|
||||
|
||||
opt = panel.ele(
|
||||
f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||||
timeout=5,
|
||||
)
|
||||
if not opt:
|
||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||||
opt.click()
|
||||
logger.info("已选择模板:%s", template_name)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_confirm_export(page):
|
||||
"""步骤7:点击「确认导出」,触发下载。"""
|
||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||||
timeout=10)
|
||||
if not btn:
|
||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「确认导出」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 5. 下载等待
|
||||
# ---------------------------------------------------------------
|
||||
def _wait_download(download_dir, before, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。
|
||||
|
||||
采用文件系统轮询:统计下载目录中「下载触发前快照」之后新增的、非临时文件,
|
||||
当其大小两次采样一致视为下载完成。
|
||||
关键是 before 必须在点击「确认导出」前捕获,否则下载很快时真实文件已被误判为「已存在」而被跳过。
|
||||
"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
deadline = time.time() + timeout
|
||||
last_sizes = {}
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
files = os.listdir(download_dir)
|
||||
except Exception:
|
||||
files = []
|
||||
for f in files:
|
||||
# 过滤:下载触发前已存在的文件、浏览器临时文件、Excel 打开时生成的 ~$ 锁文件
|
||||
if f in before or f.startswith('~$'):
|
||||
continue
|
||||
if f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||||
continue
|
||||
p = os.path.join(download_dir, f)
|
||||
if not os.path.isfile(p):
|
||||
continue
|
||||
try:
|
||||
size = os.path.getsize(p)
|
||||
except Exception:
|
||||
continue
|
||||
if size <= 0:
|
||||
continue
|
||||
if last_sizes.get(p) == size:
|
||||
logger.info("预入职台账导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||||
return p
|
||||
last_sizes[p] = size
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 6. 对外入口
|
||||
# ---------------------------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _export_one(page, download_dir, template_name, start=None, end=None):
|
||||
"""执行单次预入职台账导出(筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
logger.info(">>> 开始预入职台账导出(模板:%s)", template_name)
|
||||
try:
|
||||
_set_pre_entry_date_range(page, start, end)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
# 在触发下载前捕获目录快照,避免下载过快时真实文件被误判为已存在而漏检
|
||||
before = set(os.listdir(download_dir))
|
||||
_click_confirm_export(page)
|
||||
logger.info(">>> 等待预入职台账导出文件下载")
|
||||
path = _wait_download(download_dir, before)
|
||||
logger.info(">>> 预入职台账导出完成")
|
||||
return path
|
||||
except Exception:
|
||||
logger.exception("预入职台账导出失败,详细堆栈如下:")
|
||||
raise
|
||||
|
||||
|
||||
def export_pre_entry_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE_SHIFT_ABNORMAL,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行预入职台账自定义导出(预入职日期近30天),返回下载后的 xlsx 文件路径。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。
|
||||
template_name: 自定义导出模板名,默认「排班异常识别导出」。
|
||||
output_path: 导出结果(下载文件)的重命名保存路径;默认保留在 download_dir 下。
|
||||
start/end: 预入职日期范围,默认取近30天(get_pre_entry_range)。
|
||||
|
||||
Returns:
|
||||
导出后的 xlsx 文件路径。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 任何流程步骤失败或下载未检测到时抛出。
|
||||
"""
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("===== 开始预入职台账导出(模板:%s,日期:%s ~ %s),下载目录:%s =====",
|
||||
template_name, start, end, download_dir)
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入缓存 cookies,再访问页面
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
_click_onboarded_tab(page)
|
||||
|
||||
# 下载目录设置需在触发下载前完成
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
path = _export_one(page, download_dir, template_name, start, end)
|
||||
|
||||
# 若指定了 output_path,将下载文件重命名/移动到目标位置
|
||||
if output_path:
|
||||
output_path = os.path.abspath(output_path)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
import shutil
|
||||
shutil.move(path, output_path)
|
||||
path = output_path
|
||||
|
||||
# 未指定 output_path 时,把下载文件统一命名为 SAVE_NAME
|
||||
elif path.endswith('.xlsx'):
|
||||
renamed = os.path.join(download_dir, SAVE_NAME)
|
||||
if os.path.abspath(path) != os.path.abspath(renamed):
|
||||
import shutil
|
||||
shutil.move(path, renamed)
|
||||
path = renamed
|
||||
|
||||
logger.info("===== 预入职台账导出完成:%s =====", path)
|
||||
return path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python pre_entry_roster_export.py [下载目录] [模板名]"""
|
||||
setup_logging()
|
||||
|
||||
download_dir = os.getenv("pre_entry_output_dir")
|
||||
if not download_dir and len(sys.argv) > 1:
|
||||
download_dir = sys.argv[1]
|
||||
|
||||
template_name = os.getenv("shift_abnormal_template")
|
||||
if not template_name and len(sys.argv) > 2:
|
||||
template_name = sys.argv[2]
|
||||
template_name = template_name or ROSTER_TEMPLATE_SHIFT_ABNORMAL
|
||||
|
||||
try:
|
||||
out = export_pre_entry_roster(download_dir, template_name)
|
||||
logger.info("===== 预入职台账导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("预入职台账导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,411 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@Description: 排班异常识别(第三步):读取第二步导出的「调动台账 / 预入职台账」(表头在第 2 行),
|
||||
结合 HR 排班接口判断每人的排班是否异常,导出异常名单 Excel。
|
||||
判断口径:
|
||||
- 调动台账:按「调动时间」筛选近 9 天,对每人查询当日完整排班名
|
||||
({日期}_team_name,形如「印象-{上级部门}-技师岗」)。当「现职位序列」含「职能」
|
||||
时按「现单位」比对,其余按「现四级部门」比对;用 rf_s_kq_work_date_query
|
||||
接口按比对部门查出该部门全部排班集合,当日排班属于该集合才视为正常
|
||||
(接口查不到集合时兜底原「完整排班名包含部门名」判断),否则为排班异常
|
||||
(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」筛选近 9 天,对每人查询「预入职日期」当日完整排班名,
|
||||
当日有完整排班信息即为正常,无排班信息则为排班异常。有排班信息即可,不校验部门。
|
||||
不纳入异常:现职位序列命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的剔除(调动+预入职均生效)。
|
||||
底层能力复用:hr_session(会话管理)、hr_api.shift(排班查询)、roster 导出。
|
||||
@Version: 1.0.0
|
||||
|
||||
说明:
|
||||
1. 输入为第二步导出的《调动台账.xlsx》《预入职台账.xlsx》,两表表头均在第 2 行(pandas header=1)。
|
||||
2. 完整排班名取 {日期}_team_name(含上级部门),而非 {日期}_bc_name(仅班次名,如「技师中班C」)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in __import__("pathlib").Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(__import__("pathlib").Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.common.hr_session import build_hr_session # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import fetch_cur_user_info # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift, fetch_all_work_date # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(可自行修改) =====================
|
||||
# 默认输出目录(与第二步导出目录一致)
|
||||
SAVE_DIR = r"D:\资料\人资\排班异常识别"
|
||||
|
||||
# 第二步导出的台账文件名(表头在第 2 行)
|
||||
TRANSFER_FILE = os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
|
||||
# 每个员工是否重新校验会话(按人数控制频率,避免登录态过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 名单输出列(调动台账 + 预入职台账合并为一张表,类别区分 调动/入职)
|
||||
COLUMNS: List[str] = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
# 现职位序列命中以下序列的不纳入异常(不统计、不导出)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 通用工具
|
||||
# ----------------------------------------------
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。"
|
||||
)
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _validate_session(session):
|
||||
"""校验 cookies 有效性,返回 (session, user_id);过期则重新登录并重建会话。"""
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 按工号查询某日完整排班名({日期}_team_name)
|
||||
# ----------------------------------------------
|
||||
class _ShiftFetcher:
|
||||
"""带缓存的排班查询器:按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
self.cache: Dict[Tuple[str, date], str] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, code: str, day: date) -> str:
|
||||
"""返回某工号某日的完整排班名;无排班则返回空串。"""
|
||||
key = (code, day)
|
||||
if key not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
val = self._query(code, day)
|
||||
self.cache[key] = val
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 调动台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
# 判断字段:现职位序列含「职能」按现单位判断,否则按现四级部门判断
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day) # 当日完整排班名(含上级部门),无排班为空串
|
||||
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 预入职台账判定
|
||||
# ----------------------------------------------
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
# 排班检查日期:预入职日期(筛选按操作时间,查询排班按预入职日期)
|
||||
pj_day = _parse_date(r.get("预入职日期"))
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day) # 当日完整排班名,无则空串
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 主流程
|
||||
# ----------------------------------------------
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher",
|
||||
dept_fetcher: "_DeptShiftFetcher", end: date) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表(未写文件)。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, DAYS)
|
||||
|
||||
rows: List[dict] = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> str:
|
||||
"""执行排班异常识别(调动台账 + 预入职台账),合并导出单张 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
transfer_path: 调动台账 xlsx 路径,默认 TRANSFER_FILE
|
||||
preentry_path: 预入职台账 xlsx 路径,默认 PREENTRY_FILE
|
||||
days: 筛选近 N 天,默认 9
|
||||
"""
|
||||
global DAYS
|
||||
DAYS = days
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
end = date.today()
|
||||
|
||||
session = build_hr_session()
|
||||
session, user_id = _validate_session(session)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
|
||||
rows: List[dict] = []
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未识别到排班异常,或台账文件均不存在(请先完成第二步导出)。")
|
||||
|
||||
# 合并排序并补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常合并名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
try:
|
||||
path = run_shift_abnormal_check()
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 导出名单:%s", path)
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,528 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: transfer_roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-24
|
||||
@Description: 调动台账自定义导出(排班异常识别模块)。复用 HR 登录及缓存 cookies,通过 DrissionPage
|
||||
浏览器自动化按 aa.md 流程操作:进入调动台账页 -> 组织机构(集团) -> 点击「调动已生效」
|
||||
-> 更多搜索 -> 输入调动时间(近30天)-> 筛选 -> 自定义导出 -> 选择模板「排班异常识别导出」
|
||||
-> 确认导出,并接收浏览器下载的文件到指定目录。与预入职台账导出(pre_entry_roster_export.py)
|
||||
流程基本一致,仅页面地址、tab 文案、日期占位符、文件名不同。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可触发调动台账导出(会弹出浏览器窗口,请勿关闭)。
|
||||
3. 下载/输出目录可通过环境变量 transfer_output_dir 覆盖,默认 D:\\资料\\人资\\排班异常识别。
|
||||
|
||||
底层复用:
|
||||
- HR 登录 & cookies:app.service.hrbp.common.login(load_cookies / login)
|
||||
- 页面地址 & 模板名:app.service.hrbp.ehr.common.config(TRANSFER_ROSTER_URL / ROSTER_TEMPLATE_SHIFT_ABNORMAL)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
from app.utils.logger import setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
# 底层复用:HR 登录 / cookies / 配置 / 重试
|
||||
from app.service.hrbp.ehr.common.config import ( # noqa: E402
|
||||
TRANSFER_ROSTER_URL,
|
||||
ROSTER_TEMPLATE_SHIFT_ABNORMAL,
|
||||
)
|
||||
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
||||
from app.utils.intelligent_retry import retry # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
TAB_TRANSFER_EFFECTIVE = "调动已生效" # 调动台账「调动已生效」tab(只导已生效调动)
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索" # 展开更多筛选条件(调动时间等)
|
||||
TRANSFER_RANGE_PLACEHOLDER = "请选择调动时间"
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_BEGIN_TIMEOUT = 60 # 等待下载开始
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
|
||||
# 输出目录 & 文件名
|
||||
OUTPUT_DIR = r"D:\资料\人资\排班异常识别"
|
||||
SAVE_NAME = "调动台账.xlsx"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 调动日期范围(近30天)
|
||||
# ---------------------------------------------------------------
|
||||
def get_transfer_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算调动日期筛选范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
默认「近30天」:取今天往前 days 天(含今天)。因为已点击「调动已生效」tab,
|
||||
这批是已生效调动,调动时间落在过去 30 天内。若业务窗口不同,可传 days 调整。
|
||||
"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. 元素定位辅助(DrissionPage)
|
||||
# ---------------------------------------------------------------
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸(可点击);异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_more_search_button(page):
|
||||
"""定位当前活跃 tab 的「更多搜索」按钮。
|
||||
|
||||
该页面每个 tab 各有一个「更多搜索」按钮,但只有活跃 tab 的按钮可见。
|
||||
浏览器里所有按钮都在 DOM 中,因此必须只取可见的那一个,避免展开错 tab 的 popover。
|
||||
"""
|
||||
btns = page.eles('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btns:
|
||||
btns = page.eles('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btns:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
return btn if _is_displayed(btn) else None
|
||||
for b in btns:
|
||||
if _is_displayed(b):
|
||||
return b
|
||||
logger.warning("未找到可见的「更多搜索」按钮(DOM 中共 %d 个)", len(btns))
|
||||
return None
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""展开当前活跃 tab 的「更多搜索」popover,返回其内容元素;失败返回 None。"""
|
||||
btn = _find_more_search_button(page)
|
||||
if not btn:
|
||||
return None
|
||||
|
||||
for _ in range(3):
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return popover
|
||||
# 用 JS 直接 click() 触发 Element UI popover,确保点击的是该活跃按钮自身
|
||||
try:
|
||||
btn.run_js('this.click();')
|
||||
except Exception:
|
||||
btn.click()
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return None
|
||||
|
||||
|
||||
def _click_filter(page, popover):
|
||||
"""点击活跃 tab「更多搜索」弹层底部的「筛选」按钮,应用调动时间等筛选条件。
|
||||
|
||||
限定在传入的 popover 容器内查找,只点本 tab 的「筛选」,避免误点其它 tab 的。
|
||||
"""
|
||||
result = popover.run_js(
|
||||
'var btns=this.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn";'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _find_visible_range_input(page, placeholder):
|
||||
"""在页面级查找可见的调动时间选择器。
|
||||
|
||||
页面宽度不同会动态布局:页面较宽时选择器直接显示在搜索栏(不在弹层里);
|
||||
页面较窄时它才折叠进「更多搜索」弹层。因此要遍历所有同名元素取可见的第一个。
|
||||
"""
|
||||
rngs = page.eles(f'css:div.split-datetime-range[placeholder="{placeholder}"]', timeout=3)
|
||||
for r in rngs:
|
||||
if _is_displayed(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def _fill_range(page, rng, start, end):
|
||||
"""填入日期范围并回车确认。"""
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到调动时间起止输入框")
|
||||
# input() 无 enter 参数,用 Actions 补回车
|
||||
start_input.input(start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("调动时间已设置:%s ~ %s", start, end)
|
||||
|
||||
|
||||
def _set_transfer_date_range(page, start=None, end=None):
|
||||
"""设置「调动时间」筛选范围(近30天)并应用筛选。
|
||||
|
||||
页面宽度决定选择器位置,但「筛选」按钮始终在「更多搜索」弹层底部,因此必须展开弹层:
|
||||
- 页面较宽时选择器直接在搜索栏:填完日期后仍点弹层内「筛选」;
|
||||
- 页面较窄时选择器折叠进弹层:填日期后点弹层内「筛选」。
|
||||
"""
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("设置调动时间范围:%s ~ %s", start, end)
|
||||
|
||||
popover = _open_more_search(page)
|
||||
if not popover:
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置调动时间")
|
||||
|
||||
# 先找页面级可见的选择器(页面较宽时在搜索栏);找不到再到弹层内找
|
||||
rng = _find_visible_range_input(page, TRANSFER_RANGE_PLACEHOLDER)
|
||||
if not rng:
|
||||
rng = popover.ele(
|
||||
f'css:div.split-datetime-range[placeholder="{TRANSFER_RANGE_PLACEHOLDER}"]', timeout=5)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「调动时间」选择器")
|
||||
_fill_range(page, rng, start, end)
|
||||
_click_filter(page, popover)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. 打开调动台账页并确保登录态(复用缓存 cookies)
|
||||
# ---------------------------------------------------------------
|
||||
def _ensure_logged_in(page):
|
||||
"""访问调动台账页面;若被重定向到登录页,则复用/重登 HR 登录态。"""
|
||||
page.get(TRANSFER_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
logger.info("HR 登录态已失效,执行重新登录")
|
||||
from app.service.hrbp.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 重新登录失败")
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
page.set.cookies(cookies)
|
||||
page.get(TRANSFER_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError("HR 重新登录后仍停留在登录页")
|
||||
logger.info("已进入调动台账页面:%s", page.url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 调动台账导出主流程(aa.md 步骤)
|
||||
# ---------------------------------------------------------------
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
# 步骤1:点击左侧「组织机构」,切换为组织树
|
||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
||||
if org_tab:
|
||||
org_tab.click()
|
||||
logger.info("已点击左侧「组织机构」")
|
||||
time.sleep(WAIT_MID)
|
||||
else:
|
||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
||||
_click_text(page, TAB_ORG)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 步骤2:点击组织树根节点「集团」
|
||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
||||
if not group:
|
||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
||||
if not group:
|
||||
raise RuntimeError("组织树中未找到「集团」节点")
|
||||
group.click()
|
||||
logger.info("已点击组织树根节点「集团」")
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
|
||||
def _click_transfer_tab(page):
|
||||
"""步骤3:点击「调动已生效」tab,只保留已生效的调动记录。"""
|
||||
tab = page.ele('xpath://div[contains(@class,"tab-info")]//*[normalize-space(.)="{TAB}"]'
|
||||
.format(TAB=TAB_TRANSFER_EFFECTIVE), timeout=10)
|
||||
if not tab:
|
||||
_click_text(page, TAB_TRANSFER_EFFECTIVE)
|
||||
return
|
||||
tab.click()
|
||||
logger.info("已点击「%s」tab", TAB_TRANSFER_EFFECTIVE)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _open_custom_export_dialog(page):
|
||||
"""点击「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
||||
# 若导出弹窗已打开(存在「模板」下拉),直接返回
|
||||
tpl_label = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
||||
if tpl_label and _is_displayed(tpl_label):
|
||||
logger.info("导出弹窗已打开,跳过「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
return
|
||||
|
||||
# 步骤4:点击「自定义导出」
|
||||
btn = page.ele('xpath://button[normalize-space(.)="自定义导出"]', timeout=15)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://*[contains(@class,"btn") and normalize-space(.)="自定义导出"]', timeout=5)
|
||||
if not btn:
|
||||
raise RuntimeError("未找到「自定义导出」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=ROSTER_TEMPLATE_SHIFT_ABNORMAL):
|
||||
"""步骤5-6:选择导出模板「排班异常识别导出」。"""
|
||||
# 定位「模板」下拉框容器(含「模板」前置标签的 el-select)
|
||||
tpl = page.ele(
|
||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
||||
'/following-sibling::div[contains(@class,"el-select")]',
|
||||
timeout=15,
|
||||
)
|
||||
if not tpl:
|
||||
raise RuntimeError("未找到「模板」下拉框")
|
||||
|
||||
# 确保下拉面板已展开(下拉面板会 teleport 到 body,需在页面级查找可见面板)
|
||||
panel = None
|
||||
for _ in range(3):
|
||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
||||
if panel and _is_displayed(panel):
|
||||
break
|
||||
tpl.click()
|
||||
time.sleep(WAIT_SHORT)
|
||||
if not panel:
|
||||
raise RuntimeError("模板下拉面板未能展开")
|
||||
|
||||
opt = panel.ele(
|
||||
f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
||||
timeout=5,
|
||||
)
|
||||
if not opt:
|
||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
||||
opt.click()
|
||||
logger.info("已选择模板:%s", template_name)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_confirm_export(page):
|
||||
"""步骤7:点击「确认导出」,触发下载。"""
|
||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
||||
timeout=10)
|
||||
if not btn:
|
||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「确认导出」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 5. 下载等待
|
||||
# ---------------------------------------------------------------
|
||||
def _wait_download(download_dir, before, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。
|
||||
|
||||
采用文件系统轮询:统计下载目录中「下载触发前快照」之后新增的、非临时文件,
|
||||
当其大小两次采样一致视为下载完成。
|
||||
关键是 before 必须在点击「确认导出」前捕获,否则下载很快时真实文件已被误判为「已存在」而被跳过。
|
||||
"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
deadline = time.time() + timeout
|
||||
last_sizes = {}
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
files = os.listdir(download_dir)
|
||||
except Exception:
|
||||
files = []
|
||||
for f in files:
|
||||
# 过滤:下载触发前已存在的文件、浏览器临时文件、Excel 打开时生成的 ~$ 锁文件
|
||||
if f in before or f.startswith('~$'):
|
||||
continue
|
||||
if f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
||||
continue
|
||||
p = os.path.join(download_dir, f)
|
||||
if not os.path.isfile(p):
|
||||
continue
|
||||
try:
|
||||
size = os.path.getsize(p)
|
||||
except Exception:
|
||||
continue
|
||||
if size <= 0:
|
||||
continue
|
||||
if last_sizes.get(p) == size:
|
||||
logger.info("调动台账导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
||||
return p
|
||||
last_sizes[p] = size
|
||||
time.sleep(1.0)
|
||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 6. 对外入口
|
||||
# ---------------------------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _export_one(page, download_dir, template_name, start=None, end=None):
|
||||
"""执行单次调动台账导出(筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
logger.info(">>> 开始调动台账导出(模板:%s)", template_name)
|
||||
try:
|
||||
_set_transfer_date_range(page, start, end)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
# 在触发下载前捕获目录快照,避免下载过快时真实文件被误判为已存在而漏检
|
||||
before = set(os.listdir(download_dir))
|
||||
_click_confirm_export(page)
|
||||
logger.info(">>> 等待调动台账导出文件下载")
|
||||
path = _wait_download(download_dir, before)
|
||||
logger.info(">>> 调动台账导出完成")
|
||||
return path
|
||||
except Exception:
|
||||
logger.exception("调动台账导出失败,详细堆栈如下:")
|
||||
raise
|
||||
|
||||
|
||||
def export_transfer_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE_SHIFT_ABNORMAL,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行调动台账自定义导出(调动时间近30天),返回下载后的 xlsx 文件路径。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。
|
||||
template_name: 自定义导出模板名,默认「排班异常识别导出」。
|
||||
output_path: 导出结果(下载文件)的重命名保存路径;默认保留在 download_dir 下。
|
||||
start/end: 调动时间范围,默认取近30天(get_transfer_range)。
|
||||
|
||||
Returns:
|
||||
导出后的 xlsx 文件路径。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 任何流程步骤失败或下载未检测到时抛出。
|
||||
"""
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("===== 开始调动台账导出(模板:%s,日期:%s ~ %s),下载目录:%s =====",
|
||||
template_name, start, end, download_dir)
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入缓存 cookies,再访问页面
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
_click_transfer_tab(page)
|
||||
|
||||
# 下载目录设置需在触发下载前完成
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
path = _export_one(page, download_dir, template_name, start, end)
|
||||
|
||||
# 若指定了 output_path,将下载文件重命名/移动到目标位置
|
||||
if output_path:
|
||||
output_path = os.path.abspath(output_path)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
import shutil
|
||||
shutil.move(path, output_path)
|
||||
path = output_path
|
||||
|
||||
# 未指定 output_path 时,把下载文件统一命名为 SAVE_NAME
|
||||
elif path.endswith('.xlsx'):
|
||||
renamed = os.path.join(download_dir, SAVE_NAME)
|
||||
if os.path.abspath(path) != os.path.abspath(renamed):
|
||||
import shutil
|
||||
shutil.move(path, renamed)
|
||||
path = renamed
|
||||
|
||||
logger.info("===== 调动台账导出完成:%s =====", path)
|
||||
return path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python transfer_roster_export.py [下载目录] [模板名]"""
|
||||
setup_logging()
|
||||
|
||||
download_dir = os.getenv("transfer_output_dir")
|
||||
if not download_dir and len(sys.argv) > 1:
|
||||
download_dir = sys.argv[1]
|
||||
|
||||
template_name = os.getenv("shift_abnormal_template")
|
||||
if not template_name and len(sys.argv) > 2:
|
||||
template_name = sys.argv[2]
|
||||
template_name = template_name or ROSTER_TEMPLATE_SHIFT_ABNORMAL
|
||||
|
||||
try:
|
||||
out = export_transfer_roster(download_dir, template_name)
|
||||
logger.info("===== 调动台账导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("调动台账导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,12 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.social_import
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保增减员导入名单制作(app 分模块版)
|
||||
- config.py:集中配置(路径/列映射/映射字典/默认值/模板配置/通用辅助)
|
||||
- generate_add.py:增员导入名单生成(1号转移参保 / 11号新参保)
|
||||
- generate_stop.py:停保导入名单生成(28号执行)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,313 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.social_import.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保增减员导入名单制作 —— app 版配置文件
|
||||
集中管理:文件路径、源表结构、列映射、学历/民族/户籍映射、固定默认值、
|
||||
模板配置及通用模板写入/文件定位辅助。
|
||||
增员生成见 generate_add.py,停保生成见 generate_stop.py。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
|
||||
import pandas as pd
|
||||
import xlrd
|
||||
import xlwt
|
||||
from xlutils.copy import copy as xl_copy
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
|
||||
SOURCE_GLOB = "*社保*.xlsx"
|
||||
# 增员/停保导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
|
||||
TEMPLATE_ADD_FILE = "增员模版.xls"
|
||||
TEMPLATE_STOP_FILE = "减员模版.xls"
|
||||
# 目标区域
|
||||
TARGET_REGION = "重庆"
|
||||
# 输出子目录(增员按参保类型分文件夹,停保单独文件夹)
|
||||
OUTPUT_DIR_ADD = {
|
||||
'新参保': '新参保-增员',
|
||||
'转移参保': '转移参保-增员',
|
||||
}
|
||||
OUTPUT_DIR_STOP = '停保-减员'
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
# sheet 名按月变化(如 202609参保名单 / 202609停保名单),按关键字匹配
|
||||
SHEET_KEY_ADD = '参保名单'
|
||||
SHEET_KEY_STOP = '停保名单'
|
||||
# 源表表头在第3行(参保名单 H3-AY3 / 停保名单 同)
|
||||
SOURCE_HEADER_ROW = 3
|
||||
# 源表筛选列
|
||||
REGION_COL = '区域'
|
||||
TYPE_COL = '参保类型'
|
||||
# 分组列(按参保单位存储/命名)
|
||||
GROUP_COL = '参保单位'
|
||||
|
||||
# ==================== 3. 源表列名 ↔ 模板列名映射 ====================
|
||||
# 键为模板列含义,值为源表列名
|
||||
COLUMN_MAP_ADD = {
|
||||
'姓名': '姓名',
|
||||
'证件号码': '身份证号码',
|
||||
'民族': '民族',
|
||||
'月基本工资额': '工资申报', # 月基本工资额取「工资申报」列(申报基数大量为空)
|
||||
'户口性质': '户口性质',
|
||||
'文化程度': '文化程度',
|
||||
'联系电话': '电话号码',
|
||||
'单位名称': '参保单位', # 用于分组/文件名
|
||||
'社保号': '社保号', # 用于 B1 单元格
|
||||
'参保单位全称': '参保单位全称', # 用于 D1 单元格
|
||||
'备注': '备注',
|
||||
}
|
||||
COLUMN_MAP_STOP = {
|
||||
'个人编号': '社保编号', # 模板列 → 源表「社保编号」
|
||||
'证件号码': '身份证号码',
|
||||
'姓名': '停保人姓名',
|
||||
'单位社保号': '单位社保号', # 用于 B1 单元格
|
||||
'单位名称': '参保单位', # 用于分组、文件名 和 D1 单元格
|
||||
}
|
||||
|
||||
# ==================== 4. 学历映射 ====================
|
||||
EDU_MAP = {
|
||||
'硕士研究生': '14.硕士研究生',
|
||||
'本科': '21.大学本科',
|
||||
'大专': '31.大学专科',
|
||||
'高中': '61.普通中学',
|
||||
'职高/中专/中技': '44.职业高中',
|
||||
'初中': '71.初级中学',
|
||||
'小学': '81.小学',
|
||||
}
|
||||
def translate_education(val):
|
||||
if val is None:
|
||||
return '90.其他'
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return '90.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
# ==================== 5. 民族映射 ====================
|
||||
NATION_MAP = {
|
||||
'汉族': '01.汉族', '蒙古族': '02.蒙古族', '回族': '03.回族', '藏族': '04.藏族',
|
||||
'维吾尔族': '05.维吾尔族', '苗族': '06.苗族', '彝族': '07.彝族', '壮族': '08.壮族',
|
||||
'布依族': '09.布依族', '朝鲜族': '10.朝鲜族', '满族': '11.满族', '侗族': '12.侗族',
|
||||
'瑶族': '13.瑶族', '白族': '14.白族', '土家族': '15.土家族', '哈尼族': '16.哈尼族',
|
||||
'哈萨克族': '17.哈萨克族', '傣族': '18.傣族', '黎族': '19.黎族', '傈僳族': '20.傈僳族',
|
||||
'佤族': '21.佤族', '畲族': '22.畲族', '高山族': '23.高山族', '拉祜族': '24.拉祜族',
|
||||
'水族': '25.水族', '东乡族': '26.东乡族', '纳西族': '27.纳西族', '景颇族': '28.景颇族',
|
||||
'柯尔克孜族': '29.柯尔克孜族', '土族': '30.土族', '达斡尔族': '31.达斡尔族',
|
||||
'仫佬族': '32.仫佬族', '羌族': '33.羌族', '布朗族': '34.布朗族', '撒拉族': '35.撒拉族',
|
||||
'毛南族': '36.毛南族', '仡佬族': '37.仡佬族', '锡伯族': '38.锡伯族', '阿昌族': '39.阿昌族',
|
||||
'普米族': '40.普米族', '塔吉克族': '41.塔吉克族', '怒族': '42.怒族',
|
||||
'乌孜别克族': '43.乌孜别克族', '俄罗斯族': '44.俄罗斯族', '鄂温克族': '45.鄂温克族',
|
||||
'德昂族': '46.德昂族', '保安族': '47.保安族', '裕固族': '48.裕固族', '京族': '49.京族',
|
||||
'塔塔尔族': '50.塔塔尔族', '独龙族': '51.独龙族', '鄂伦春族': '52.鄂伦春族',
|
||||
'赫哲族': '53.赫哲族', '门巴族': '54.门巴族', '珞巴族': '55.珞巴族', '基诺族': '56.基诺族',
|
||||
'少数民族': '57.少数民族', '其他': '99.其他',
|
||||
}
|
||||
def translate_nation(val):
|
||||
if val is None:
|
||||
return '99.其他'
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return '99.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
# ==================== 6. 户籍类型映射 ====================
|
||||
RESIDENCE_MAP = {
|
||||
'本地城镇': '11.本市城镇',
|
||||
'本地农村': '21.本市农村',
|
||||
'外地城镇': '12.外市城镇',
|
||||
'外地农村': '22.外市农村',
|
||||
}
|
||||
def translate_residence(val):
|
||||
if val is None:
|
||||
return ''
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
# ==================== 7. 固定默认值 ====================
|
||||
DEFAULT_VALUES_ADD = {
|
||||
'个人身份': '24.工人',
|
||||
'证件类型': '01.居民身份证(户口簿)',
|
||||
'国籍': 'CHN.中国',
|
||||
'专职技能': '499.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '', # 留空
|
||||
'备注': '', # 留空
|
||||
}
|
||||
DEFAULT_VALUES_STOP = {
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
|
||||
# ==================== 8. 模板配置(表头 B 列起,数据从第4行开始) ====================
|
||||
TPL_DATA_START_ROW = 4
|
||||
# 增员模版表头(B2:U2,20列)
|
||||
TPL_COLS_ADD = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
# 减员模版表头(B2:L2,11列)
|
||||
TPL_COLS_STOP = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
# 需按日期写入的模板列
|
||||
DATE_COLS_ADD = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
DATE_COLS_STOP = {'减少时间'}
|
||||
|
||||
# ==================== 9. 通用辅助 ====================
|
||||
def _to_text(value):
|
||||
"""转可写文本:证件号/电话等长数字统一为字符串,避免丢精度/科学计数。"""
|
||||
if value is None:
|
||||
return ''
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」,
|
||||
避免「某某店」拼成「某某店店…」,也避免「某某店店」被全剥成「某某」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _get_dates():
|
||||
"""返回(当日, 当月1日):工伤保险参保时间用当日,其余用当月1日。"""
|
||||
today = datetime.now()
|
||||
first_day = today.replace(day=1)
|
||||
return today, first_day
|
||||
|
||||
|
||||
# ==================== 10. 文件定位辅助 ====================
|
||||
def find_source_file():
|
||||
"""定位源表(*社保*.xlsx,排除 Excel 临时文件 ~$,取最新)。"""
|
||||
candidates = [
|
||||
p for p in glob(os.path.join(BASE_DIR, SOURCE_GLOB))
|
||||
if not os.path.basename(p).startswith("~$")
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到源表(匹配 {SOURCE_GLOB}),请先准备《社保变更及增减名单》。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_template_file(stop=False):
|
||||
"""定位模板:增员《增员模版.xls》或停保《减员模版.xls》。"""
|
||||
name = TEMPLATE_STOP_FILE if stop else TEMPLATE_ADD_FILE
|
||||
exact = os.path.join(BASE_DIR, name)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
key = "减员模版" if stop else "增员模版"
|
||||
candidates = glob(os.path.join(BASE_DIR, f"*{key}*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到《{name}》,请先准备{'停保' if stop else '增员'}导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_source_sheet(source_file, key):
|
||||
"""按关键字匹配源表 sheet(sheet 名按月变化,如 202609参保名单 / 202609停保名单)。"""
|
||||
xl = pd.ExcelFile(source_file)
|
||||
for name in xl.sheet_names:
|
||||
if key in name:
|
||||
return name
|
||||
raise ValueError(
|
||||
f"源表 {os.path.basename(source_file)} 中未找到包含「{key}」的 sheet,"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
|
||||
|
||||
def get_output_dir(sub_dir):
|
||||
"""输出目录(BASE_DIR/{sub_dir}),不存在则自动创建。"""
|
||||
out_dir = os.path.join(BASE_DIR, sub_dir)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
def write_template(template_file, output_path, unit_no, unit_name, records,
|
||||
tpl_cols, date_cols, start_row=TPL_DATA_START_ROW):
|
||||
"""复制 .xls 模板写入 B1/D1 及数据,另存为 output_path。
|
||||
|
||||
使用 xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,
|
||||
保留下拉字典(增员 Sheet2 / 停保 二级代码)与数据有效性。
|
||||
- B1=单位编号,D1=单位名称;数据从模板 start_row 行起,按 tpl_cols 顺序写入 B 列起;
|
||||
- date_cols 中的列以序列数 + YYYY-MM-DD 格式写入;
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
datemode = rb.datemode
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1
|
||||
ws.write(0, 3, unit_name) # D1
|
||||
date_style = xlwt.easyxf(num_format_str='YYYY-MM-DD')
|
||||
for i, rec in enumerate(records):
|
||||
r = start_row - 1 + i # 0-based
|
||||
for c, col in enumerate(tpl_cols):
|
||||
val = rec.get(col)
|
||||
if col in date_cols and val is not None:
|
||||
xld = xlrd.xldate.xldate_from_datetime_tuple(
|
||||
(val.year, val.month, val.day, 0, 0, 0), datemode)
|
||||
ws.write(r, c + 1, xld, date_style)
|
||||
else:
|
||||
ws.write(r, c + 1, _clean_value(val))
|
||||
# 清空模板原数据区(start_row 起)未被覆盖的多余示例行
|
||||
for r in range(start_row - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(tpl_cols) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
logger.info("已生成导入名单:%s(%d 条)", output_path, len(records))
|
||||
@@ -1,145 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.social_import.generate_add
|
||||
@FileName: generate_add.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保增员导入名单制作 —— app 分模块版(生成逻辑)
|
||||
读取《XX月社保变更及增减名单》-【参保名单】sheet(表头第3行),筛选【区域=重庆】且
|
||||
【参保类型=指定类型】;按【参保单位】分组,复制《增员模版.xls》(xlutils 保留下拉),
|
||||
写入 B1(社保号)/D1(参保单位全称) 及 B4 起数据,逐单位另存为
|
||||
《XX增员导入名单.xls》至 BASE_DIR/新参保-增员 或 转移参保-增员。
|
||||
填写标准:首次参加=本月1号、个人身份=24.工人、工伤=当日、其他参保时间=本月1号;
|
||||
月基本工资额取源表「工资申报」列。
|
||||
日期规则:1号→转移参保;11号→新参保(main 自动判断,可显式传入类型)。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用方式(函数传参调用,可被其他流程 import):
|
||||
from app.service.hrbp.ehr.social_import.generate_add import process_add_members
|
||||
process_add_members('新参保') # 显式指定
|
||||
process_add_members('转移参保')
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.social_import import config # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def process_add_members(operation_type):
|
||||
"""
|
||||
生成增员导入名单
|
||||
operation_type: '新参保' 或 '转移参保'
|
||||
"""
|
||||
if operation_type not in config.OUTPUT_DIR_ADD:
|
||||
raise ValueError(
|
||||
f"未知参保类型:{operation_type}(可选:{'/'.join(config.OUTPUT_DIR_ADD)})")
|
||||
|
||||
# 1. 读取源表【参保名单】sheet(表头在第3行)
|
||||
source_file = config.find_source_file()
|
||||
sheet_name = config.find_source_sheet(source_file, config.SHEET_KEY_ADD)
|
||||
logger.info("源表:%s(sheet: %s)", source_file, sheet_name)
|
||||
df_source = config.pd.read_excel(
|
||||
source_file, sheet_name=sheet_name, header=config.SOURCE_HEADER_ROW - 1,
|
||||
# 身份证/电话按文本读:18 位身份证若被推断为数字会丢精度(与停保脚本一致);
|
||||
# 工资申报等数值列保持默认数值读法,写模板时才是数字而非 "5200.0" 文本
|
||||
dtype={'身份证号码': str, '电话号码': str})
|
||||
|
||||
# 2. 筛选:区域=重庆,参保类型=指定类型
|
||||
mask = (
|
||||
(df_source[config.REGION_COL] == config.TARGET_REGION) &
|
||||
(df_source[config.TYPE_COL] == operation_type)
|
||||
)
|
||||
df_filtered = df_source[mask].copy()
|
||||
if df_filtered.empty:
|
||||
logger.warning("没有找到【%s】的数据(%s区域)", operation_type, config.TARGET_REGION)
|
||||
return {"operation_type": operation_type, "files": []}
|
||||
|
||||
# 3. 获取日期
|
||||
today, first_day = config._get_dates()
|
||||
logger.info("今日日期:%s;本月1日:%s;工伤参保时间:%s(当日)",
|
||||
today.strftime('%Y-%m-%d'), first_day.strftime('%Y-%m-%d'),
|
||||
today.strftime('%Y-%m-%d'))
|
||||
|
||||
# 4. 按参保单位分组生成
|
||||
template_file = config.find_template_file(stop=False)
|
||||
output_dir = config.get_output_dir(config.OUTPUT_DIR_ADD[operation_type])
|
||||
logger.info("输出目录:%s", output_dir)
|
||||
cm = config.COLUMN_MAP_ADD
|
||||
files = []
|
||||
for store_name, group in df_filtered.groupby(cm['单位名称']):
|
||||
logger.info("正在处理:%s,共 %d 人", store_name, len(group))
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[cm['社保号']] # B1
|
||||
unit_full_name = first_row[cm['参保单位全称']] # D1
|
||||
|
||||
# 5. 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'证件号码': config._to_text(row[cm['证件号码']]),
|
||||
'姓名': row[cm['姓名']],
|
||||
'民族': config.translate_nation(row[cm['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': config._clean_value(row[cm['月基本工资额']]),
|
||||
'工种': config.DEFAULT_VALUES_ADD['工种'],
|
||||
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
|
||||
'户口性质': config.translate_residence(row[cm['户口性质']]),
|
||||
'联系电话': config._to_text(row[cm['联系电话']]),
|
||||
'文化程度': config.translate_education(row[cm['文化程度']]),
|
||||
'养老保险参保时间': first_day,
|
||||
'失业保险参保时间': first_day,
|
||||
'医疗保险参保时间': first_day,
|
||||
'工伤保险参保时间': today,
|
||||
'生育保险参保时间': first_day,
|
||||
'证件类型': config.DEFAULT_VALUES_ADD['证件类型'],
|
||||
'国籍': config.DEFAULT_VALUES_ADD['国籍'],
|
||||
'备注': config.DEFAULT_VALUES_ADD['备注'],
|
||||
'专职技能': config.DEFAULT_VALUES_ADD['专职技能'],
|
||||
'技能等级': config.DEFAULT_VALUES_ADD['技能等级'],
|
||||
}
|
||||
records.append(rec)
|
||||
|
||||
# 6. 写入模板并另存
|
||||
output_path = os.path.join(output_dir, f"{config.safe_name(store_name)}增员导入名单.xls")
|
||||
config.write_template(template_file, output_path, unit_no, unit_full_name,
|
||||
records, config.TPL_COLS_ADD, config.DATE_COLS_ADD)
|
||||
files.append(output_path)
|
||||
|
||||
logger.info("所有【%s】导入名单生成完成,共 %d 个文件", operation_type, len(files))
|
||||
return {"operation_type": operation_type, "files": files}
|
||||
|
||||
|
||||
def main(operation_type=None):
|
||||
"""入口:默认按日期规则(1号→转移参保,11号→新参保),可显式传入类型强制生成。"""
|
||||
if operation_type:
|
||||
return process_add_members(operation_type)
|
||||
day_of_month = datetime.now().day
|
||||
if day_of_month == 1:
|
||||
return process_add_members('转移参保')
|
||||
if day_of_month == 11:
|
||||
return process_add_members('新参保')
|
||||
logger.info("今日是 %s 号,不在规定日期(1号或11号),不执行增员任务。", day_of_month)
|
||||
return {"operation_type": None, "files": []}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
@@ -1,123 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.social_import.generate_stop
|
||||
@FileName: generate_stop.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保停保导入名单制作 —— app 分模块版(生成逻辑)
|
||||
读取《XX月社保变更及增减名单》-【停保名单】sheet(表头第3行),筛选【区域=重庆】;
|
||||
按【参保单位】分组,复制《减员模版.xls》(xlutils 保留下拉 二级代码),
|
||||
写入 B1(单位社保号)/D1(参保单位) 及 B4 起数据,逐单位另存为
|
||||
《XX减员导入名单.xls》至 BASE_DIR/停保-减员。
|
||||
填写标准:减少时间=当天、减少原因=在职人员主动解除劳动合同、五个减少标志=1 减少、
|
||||
失业原因=3 劳动者自愿辞职。身份证/社保编号按文本读取防丢精度。
|
||||
(固定 28 号执行,main 自动判断,可显式调用)
|
||||
@Version: 1.0.0
|
||||
|
||||
使用方式(函数传参调用,可被其他流程 import):
|
||||
from app.service.hrbp.ehr.social_import.generate_stop import process_stop_members
|
||||
process_stop_members()
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.social_import import config # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def process_stop_members():
|
||||
"""
|
||||
生成停保导入名单
|
||||
规则:区域=重庆;按参保单位分组;减少时间=当天;减少原因=在职人员主动解除劳动合同;
|
||||
五个险种减少标志=1 减少;失业原因=3 劳动者自愿辞职
|
||||
"""
|
||||
# 1. 读取源表【停保名单】sheet(表头在第3行,全列按文本读,保住身份证/社保编号完整值)
|
||||
source_file = config.find_source_file()
|
||||
sheet_name = config.find_source_sheet(source_file, config.SHEET_KEY_STOP)
|
||||
logger.info("源表:%s(sheet: %s)", source_file, sheet_name)
|
||||
df_source = config.pd.read_excel(
|
||||
source_file, sheet_name=sheet_name,
|
||||
header=config.SOURCE_HEADER_ROW - 1, dtype=str)
|
||||
|
||||
# 2. 筛选:区域=重庆
|
||||
df_filtered = df_source[df_source[config.REGION_COL] == config.TARGET_REGION].copy()
|
||||
if df_filtered.empty:
|
||||
logger.warning("没有找到【%s】区域的停保数据", config.TARGET_REGION)
|
||||
return {"files": []}
|
||||
logger.info("共找到 %d 条 %s 区域停保记录", len(df_filtered), config.TARGET_REGION)
|
||||
|
||||
# 3. 获取当天日期(减少时间 = 当天)
|
||||
today, _ = config._get_dates()
|
||||
logger.info("制作日期:%s;减少时间:%s(当日)", today.strftime('%Y-%m-%d'),
|
||||
today.strftime('%Y-%m-%d'))
|
||||
|
||||
# 4. 按参保单位分组生成
|
||||
template_file = config.find_template_file(stop=True)
|
||||
output_dir = config.get_output_dir(config.OUTPUT_DIR_STOP)
|
||||
logger.info("输出目录:%s", output_dir)
|
||||
cm = config.COLUMN_MAP_STOP
|
||||
files = []
|
||||
for group_key, group in df_filtered.groupby(cm['单位名称']):
|
||||
logger.info("正在处理:单位【%s】,共 %d 人", group_key, len(group))
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[cm['单位社保号']] # 单位社保号 → B1
|
||||
unit_name = first_row[cm['单位名称']] # 参保单位 → D1
|
||||
|
||||
# 5. 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'个人编号': config._clean_value(row[cm['个人编号']]),
|
||||
'证件号码': config._clean_value(row[cm['证件号码']]),
|
||||
'姓名': config._clean_value(row[cm['姓名']]),
|
||||
'减少时间': today,
|
||||
'减少原因': config.DEFAULT_VALUES_STOP['减少原因'],
|
||||
'养老保险减少标志': config.DEFAULT_VALUES_STOP['养老保险减少标志'],
|
||||
'失业保险减少标志': config.DEFAULT_VALUES_STOP['失业保险减少标志'],
|
||||
'医疗保险减少标志': config.DEFAULT_VALUES_STOP['医疗保险减少标志'],
|
||||
'工伤保险减少标志': config.DEFAULT_VALUES_STOP['工伤保险减少标志'],
|
||||
'生育保险减少标志': config.DEFAULT_VALUES_STOP['生育保险减少标志'],
|
||||
'失业原因': config.DEFAULT_VALUES_STOP['失业原因'],
|
||||
}
|
||||
records.append(rec)
|
||||
|
||||
# 6. 写入模板并另存
|
||||
output_path = os.path.join(output_dir, f"{config.safe_name(group_key)}减员导入名单.xls")
|
||||
config.write_template(template_file, output_path, unit_no, unit_name,
|
||||
records, config.TPL_COLS_STOP, config.DATE_COLS_STOP)
|
||||
files.append(output_path)
|
||||
|
||||
logger.info("所有停保导入名单生成完成,共 %d 个单位 / %d 个文件",
|
||||
len(df_filtered[cm['单位名称']].unique()), len(files))
|
||||
return {"files": files}
|
||||
|
||||
|
||||
def main():
|
||||
"""入口:固定 28 号执行。"""
|
||||
day_of_month = datetime.now().day
|
||||
if day_of_month == 28:
|
||||
return process_stop_members()
|
||||
logger.info("今日是 %s 号,不在规定日期(28号),不执行停保任务。", day_of_month)
|
||||
return {"files": []}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
@@ -1,5 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||
"""
|
||||
@@ -1,89 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查:下载工资卡汇总表并核对数据(身份证/姓名/银行卡号)。
|
||||
员工花名册已独立为 roster_export 模块,不再包含在此流程中。
|
||||
数据保存到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
直接运行本文件即可依次执行工资卡下载、工资卡核对。
|
||||
python bank_card_check.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_download import download_wage_card # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_check import check_wage_card # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python bank_card_check.py"""
|
||||
setup_logging()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,311 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 工资卡汇总表核对:身份证一致性、姓名一致性、空值标记、银行卡号校验。
|
||||
读取工资卡汇总表 Excel,添加核对结果列后保存。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import get_bank_dict, bank_type_to_name # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 银行卡校验规则 =====================
|
||||
# 固定通用规则,无需随表格修改
|
||||
# 16 位银联卡 BIN(按银行归类,经实际工资卡数据比对核验)
|
||||
BIN_16 = {
|
||||
# 招商银行
|
||||
"621483", "621485", "621486", "622588", "622609",
|
||||
# 民生银行
|
||||
"621691", "622615", "622617", "622619", "622620", "622622",
|
||||
# 民生银行信用卡(16 位贷记卡)
|
||||
"622601",
|
||||
# 重庆农村商业银行
|
||||
"621258", "621465", "621528", "622867",
|
||||
# 浦东发展银行
|
||||
"621792", "621793", "622521",
|
||||
# 其他银行
|
||||
"621499", # 建设银行理财金卡
|
||||
"621755", # 重庆三峡银行
|
||||
"623020", # 华夏银行
|
||||
}
|
||||
# 18 位银联储蓄卡 BIN
|
||||
BIN_18 = {"622908"} # 兴业银行
|
||||
# 非 62 开头但合法的老版储蓄卡 BIN(历史卡仍在使用,标准均为 19 位)
|
||||
NON62_BIN = {
|
||||
"436742", # 建设银行龙卡储蓄卡
|
||||
"601382", # 中国银行长城电子借记卡
|
||||
"955882", # 工商银行牡丹灵通卡
|
||||
}
|
||||
# 正则:匹配全数字
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
def check_bank_card(card_raw) -> dict:
|
||||
"""校验银行卡号,返回 {card, status, reason}。"""
|
||||
# 处理 pandas 从 Excel 读取时将卡号转为 float 的问题
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw: # NaN
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
bin6 = card[:6]
|
||||
if not (card.startswith("62") or bin6 in NON62_BIN):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ===================== 核对分类 =====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account):
|
||||
"""按 4 类异常对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, id_inconsistent, bank_info)
|
||||
issues: 4 类异常标签(写入核对结果)
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
"""
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if _is_empty(bank_account):
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 身份证不一致(开户人身份证非空且与员工不一致) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
if id_inconsistent:
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
|
||||
# ---- 3. 姓名不一致(仅身份证一致时比对) ----
|
||||
if (not id_inconsistent and not _is_empty(card_idcard)
|
||||
and not _is_empty(card_name) and staff_name != card_name):
|
||||
issues.append("员工姓名与开户人姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 4. 银行卡信息异常(银行卡非空但格式/位数错误) ----
|
||||
if not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
issues.append("银行卡信息异常")
|
||||
basis.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
|
||||
return issues, basis, id_inconsistent, bank_info
|
||||
|
||||
|
||||
# ===================== 列名常量 =====================
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
|
||||
def _is_empty(val) -> bool:
|
||||
"""判断值是否为空(None、空字符串、NaN)。"""
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val: # NaN
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val) -> str:
|
||||
"""将身份证号/银行卡号统一转为字符串,处理 pandas 读取 Excel 时的 float 转换问题。"""
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val: # NaN
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
output_path: 核对结果保存路径,默认在输入文件同目录加 _核对结果
|
||||
|
||||
Returns:
|
||||
核对结果文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法处理 Excel")
|
||||
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if COL_BANK_NAME not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df[COL_BANK_NAME] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"] if bk else ""
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"] if bk else ""
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
# 将核对结果列移到最前面
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
# ---- 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_rows))
|
||||
abnormal = df[mask]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = f"{os.path.dirname(base)}{os.sep}工资卡异常名单{ext}"
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
abnormal_path = None
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python wage_card_check.py [输入文件] [输出文件]"""
|
||||
setup_logging()
|
||||
input_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
|
||||
r"D:\资料\人资\银行卡检查", "工资卡汇总表.xlsx"
|
||||
)
|
||||
output_path = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = check_wage_card(input_path, output_path)
|
||||
logger.info("===== 工资卡核对完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,205 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_download.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:20
|
||||
@Description: 银行卡(工资卡)信息下载与核对:抓取「在职 + 离职」人员工资卡数据,
|
||||
将英文字段映射为中文并导出 .xlsx 汇总表。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 1.3.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可下载在职/离职工资卡数据并生成汇总 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_wage_card_page,
|
||||
fetch_all_wage_card,
|
||||
get_bank_dict,
|
||||
bank_type_to_name,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 接口地址、分页大小统一在 ehr/common/config.py 中维护
|
||||
# 导出文件名 & 默认保存目录
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
SAVE_DIR = r"D:\资料\人资\银行卡检查"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面)
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 离职筛选时间范围(按当前日期动态计算)
|
||||
# ----------------------------------------------
|
||||
def get_leave_range(today: date = None) -> tuple:
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
# 上月 1 日
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
# 本月 1 日
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 登录态预检
|
||||
# ----------------------------------------------
|
||||
def preflight(session):
|
||||
"""正式抓取前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出汇总 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data_on_job: List[dict], data_leave: List[dict], save_dir: str = ".") -> str:
|
||||
"""合并在职/离职数据,字段映射为中文、调整列顺序并导出 .xlsx。
|
||||
|
||||
用 pandas 做数据处理,如需后续设置单元格格式可在保存前用 openpyxl 对 ws 加工。
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
save_path = os.path.abspath(os.path.join(save_dir, SAVE_NAME))
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def download_wage_card(save_dir: str = None) -> str:
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel,返回导出文件路径。"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = preflight(build_hr_session())
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("\n===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
try:
|
||||
out = download_wage_card(save_dir)
|
||||
logger.info("===== 抓取完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("抓取失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: OA 系统模块:包含 common(公共组件)、leave(请假流程)、work_overtime(加班流程)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: OA 系统公共模块:登录、会话管理、接口调用、解析
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,302 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.approval_flow
|
||||
@FileName: approval_flow.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:52
|
||||
@Description: 公共审批引擎:登录(复用登录态)-> 查待办 -> 解析 SSO -> 获取表单 -> 校验 -> 生成报告
|
||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
refresh_session_cookies,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
is_session_valid,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
OALoginExpiredError,
|
||||
get_documents,
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.notify import push_report, build_push_summary
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 真实审批提交(默认关闭) ====================
|
||||
# 仅自动提交"同意"(校验通过):驳回/校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _approve_enabled() -> bool:
|
||||
"""是否启用真实审批提交(同意/退回申请人)。默认关闭。
|
||||
开关:.env 中 overtime_approve_enabled=true/false。
|
||||
未确认校验准确性前保持关闭,确认后再启用。"""
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
return os.getenv("overtime_approve_enabled", "false").lower() == "true"
|
||||
|
||||
|
||||
def _find_button(browser, selector: str, timeout: float = 3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
btn = browser.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = browser.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(browser, decision: str) -> Dict[str, str]:
|
||||
"""
|
||||
按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
Args:
|
||||
browser: 停留在详情页的 ChromiumPage
|
||||
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in _APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = _APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(browser, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = browser.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
|
||||
people = browser.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
def _get_browser_and_session(subject: str):
|
||||
"""
|
||||
获取浏览器和会话:优先复用已保存的登录 cookies,无效或不存在时才完整登录。
|
||||
|
||||
Returns:
|
||||
(browser, session, is_fresh_login)
|
||||
"""
|
||||
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 = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
||||
session: 已登录的 SessionPage 对象(用于后台 API 请求)
|
||||
doc: 单据信息(包含 detail_url)
|
||||
|
||||
Returns:
|
||||
单据信息 + taskId/businessKey/formId/formData
|
||||
"""
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
# Step 1: 浏览器打开 SSO 链接,从重定向后的 URL 提取 taskId 和 businessKey
|
||||
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)
|
||||
|
||||
# SSO 的 linkLogin 在 hr 域产生了新的会话 cookie,先同步回 SessionPage
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
# Step 2: 通过 taskId 获取 formId
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
|
||||
# Step 3: 通过 businessKey + formId 获取表单数据
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
|
||||
return {
|
||||
**doc,
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
"formData": form_data,
|
||||
}
|
||||
|
||||
|
||||
def run_flow(
|
||||
subject: str,
|
||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||
) -> str:
|
||||
"""
|
||||
公共审批流程:登录(优先复用已保存会话)-> 查待办 -> 逐单解析详情并校验 -> 生成报告。
|
||||
|
||||
Args:
|
||||
subject: 待办标题关键字,如 "加班" / "请假"
|
||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
||||
generate_report: 校验结果报告生成函数
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过/校验不通过未处理,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
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)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 再推送完整报告(含审批明细),保证请假/加班通知都展示具体审批明细
|
||||
push_report(report, subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,145 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:09
|
||||
@Description: OA 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
||||
from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402
|
||||
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
# ---------- 工作沟通推送接口(oa 域名) ----------
|
||||
# 人员搜索接口:按工号/姓名模糊搜索,返回人员 XML(<data id=.. name=..>)
|
||||
PERSON_SEARCH_URL = f"{BASE_URL}/sys/common/dataxml.jsp"
|
||||
# 附件上传接口:getuserkey / submit 两步共用
|
||||
ATT_UPLOAD_URL = f"{BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
# 附件二进制上传接口
|
||||
ATT_UPLOADER_URL = f"{BASE_URL}/sys/attachment/uploaderServlet"
|
||||
# 工作沟通提交接口(新建保存走 method=save&s_seq=1,真实抓包确认;aa.md 中 user.jsp 为错误端点)
|
||||
WORK_COMMUNICATION_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 新建工作沟通页面:method=add 返回表单页,其中含新建草稿 fdId 与通知方式随机字段 __notify_type_<id>
|
||||
WORK_COMMUNICATION_ADD_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do?method=add"
|
||||
# 保存工作沟通:POST 表单字段(application/x-www-form-urlencoded),成功返回「操作成功」提示页
|
||||
KM_COLLABORATE_SAVE_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 沟通内容 fdContent 序列化前缀:真实格式为 固定前缀 + {base64(HTML)}(前缀为抓包确认的固定字节)
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
# 沟通类型(fdCategoryId 必填 validate=required),全部类型如下,调用方可任选,默认「工作安排」
|
||||
FD_CATEGORY_COMMUNICATION = "15e4c970dd59cd559f096644cecadbc7" # 工作交流
|
||||
FD_CATEGORY_INFO = "15e4c980ff72365007fc1a741ceb0c7d" # 信息传递
|
||||
FD_CATEGORY_WORK_ARRANGE = "17646e8283a07a43be3003d485492a4f" # 工作安排
|
||||
FD_CATEGORY_PROJECT = "1767a1195ec34b0de7d53764c84812f1" # 项目沟通
|
||||
FD_CATEGORY_REMINDER = "17efb81557d1e74c532aa78407a95189" # 温馨提示
|
||||
FD_CATEGORY_OTHER = "15e4c985cd9a92cc54cb20c413d9b29e" # 其他
|
||||
# 沟通类型映射:名称 -> ID(submit 时支持直接传中文名)
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": FD_CATEGORY_COMMUNICATION,
|
||||
"信息传递": FD_CATEGORY_INFO,
|
||||
"工作安排": FD_CATEGORY_WORK_ARRANGE,
|
||||
"项目沟通": FD_CATEGORY_PROJECT,
|
||||
"温馨提示": FD_CATEGORY_REMINDER,
|
||||
"其他": FD_CATEGORY_OTHER,
|
||||
}
|
||||
# 默认沟通类型:工作安排
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_WORK_ARRANGE
|
||||
# 工作沟通(协作)业务模型名:附件绑定与沟通提交共用
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
# OA 流程接口(hr 域名)
|
||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 考勤逐日接口(hr 域名,按员工 + 日期范围查询每日班次起止与上下班打卡,返回 data 数组)
|
||||
# 加班/请假流程校验统一使用该接口获取排班名/班次时段/上下班打卡,替代原排班日历接口与打卡流水接口。
|
||||
# 注意:kq_status_total 按考勤状态分类返回(0=休息日、1=正常班、9=未打卡、11=异常),
|
||||
# 需四种状态各查一次后按 work_day 合并去重,才能拿到全部班次信息与当天打卡。
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
|
||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
|
||||
# 打卡明细接口(hr 域名,按员工 + 日期范围查询真实打卡明细)
|
||||
# kq_time=真实打卡时间、bc_date=考勤归属日(跨天打卡次日0点~6点归入前一天)、
|
||||
# time_order=上下班类型(1=上班、2=下班)。加班校验用其替代考勤逐日接口的打卡字段,
|
||||
# 避免人工拼接日期导致跨天打卡归属错误。
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
# 附件下载接口(hr 域名):按 fileId 下载请假单据附件。
|
||||
# 注意:该接口要求有效 EHR 会话(hr.37du.co),会话失效时返回登录页 HTML 或
|
||||
# "外部用户未登录,无法访问",而非报错状态码;前端"在线预览"走的是
|
||||
# PtFjk.mc?method=fjkViewPageDown(返回 HTML 预览页),RPA 下载不使用该地址
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 附件默认保存目录
|
||||
ATTACHMENT_SAVE_DIR = r"D:\资料\人资\请假流程审批\附件"
|
||||
|
||||
# 附件清单查询接口(hr 域名,见 aa.md):按 ids(逗号分隔 fileId)查询附件元信息
|
||||
# (fileName/fileSuffix/herfUrl 等),用于离职电子签签章附件(解除确认书/报酬支付确认)下载
|
||||
FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds"
|
||||
# 离职电子签签章附件默认保存目录
|
||||
RESIGN_ATTACHMENT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
|
||||
# 电子签真实签署状态查询接口(hr 域名,按 main_id 即合同业务主键查询):
|
||||
# is_initiate_sign 是否已发起电子签(hr_staff_contract.is_initiate_sign)
|
||||
# sign_status_yg 员工签署状态(esign_sigin_state)
|
||||
# sign_status_qy 企业签署状态(esign_sigin_state)
|
||||
# file 签章附件 fileId 串(",id1,id2",逗号分隔、可能带前导逗号)。
|
||||
# 接口变更后表单 getBusinessDate 的 contract_file 已恒为空串,
|
||||
# 附件 fileId 只能从本字段的签署记录中获取
|
||||
CONTRACT_SIGNATURE_SELECT_URL = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/getContentLinkage/redApi/"
|
||||
"rf_hr_staff_contract_signature_select_sp_cq37du/WorkformEngine.mc"
|
||||
)
|
||||
|
||||
# ---------- 加班审批规则常量 ----------
|
||||
# 正常上班时间 T 兜底值:所有用到上班时间的地方(区间合规的加班开始时间、弹性到岗
|
||||
# 兑换的次日上班时间、请假覆盖判断的早上上班时间等)都优先取排班开始时间
|
||||
# (bc_begin_time),未获取到排班时段时才回退该默认值
|
||||
WORK_START_TIME = "09:00"
|
||||
# 当日规定下班时间兜底值:区间合规校验优先取员工当天排班结束时间(bc_end_time),
|
||||
# 未获取到排班时段时才回退该默认值
|
||||
WORK_END_TIME = "18:00"
|
||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
|
||||
# 次日弹性上班扣减时扣除的中午休息时长(小时)
|
||||
LUNCH_BREAK_HOURS = 1
|
||||
# 延时加班有效时长门槛:不足该小时数直接校验不通过未处理
|
||||
OT_MIN_HOURS = 1
|
||||
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
# 职能排班半天加班时长:上午3.5小时、下午4.5小时
|
||||
# (休息日/节假日加班,不再统一按4小时半天处理,整天仍为9小时)
|
||||
ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
# 提前到岗型员工只会提前到、不会晚到:打卡须不晚于加班开始时间(晚到则无法证明开始时刻已到岗)。
|
||||
# 到岗打卡证据窗口:加班开始时间前1小时内(含开始时刻)的打卡视为到岗
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ---------- 分页 ----------
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(见 common/oa_api/todo.py);
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
@@ -1,127 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.login
|
||||
@FileName: login.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-04 17:34
|
||||
@Description: 自动登录 OA 系统
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = lambda *args, **kwargs: None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def oa_login(
|
||||
username: str = None,
|
||||
password: str = None,
|
||||
timeout: float = 10,
|
||||
wait_after_load: float = 2,
|
||||
) -> ChromiumPage:
|
||||
"""
|
||||
自动登录 OA 系统,返回已登录的 ChromiumPage 对象。
|
||||
|
||||
参数:
|
||||
username: 登录用户名,若不提供则从环境变量 oa_login_username 读取
|
||||
password: 登录密码,若不提供则从环境变量 oa_login_password 读取
|
||||
|
||||
timeout: URL 跳转等待超时(秒,默认 10)
|
||||
wait_after_load: 页面加载后的额外等待时间(秒,默认 2)
|
||||
|
||||
返回:
|
||||
登录成功后的 ChromiumPage 对象
|
||||
|
||||
异常:
|
||||
若登录失败或关键元素未找到,抛出 RuntimeError
|
||||
"""
|
||||
# 加载 app/.env 环境变量(始终定位 app 根,与 cwd 无关)
|
||||
load_app_env()
|
||||
|
||||
# 获取配置,参数优先于环境变量
|
||||
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()
|
||||
# page.set.window.max()
|
||||
|
||||
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)
|
||||
|
||||
# ---------- 轮询检测 URL ----------
|
||||
start = time.time()
|
||||
while time.time() - start < timeout: # timeout 默认 10 秒
|
||||
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}")
|
||||
|
||||
|
||||
# ---------- 使用示例 ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
try:
|
||||
page = oa_login()
|
||||
except RuntimeError as e:
|
||||
logger.error(e)
|
||||
@@ -1,165 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.notify
|
||||
@FileName: notify.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 审批报告推送模块。测试阶段通过钉钉桌面客户端推送到指定联系人。
|
||||
推送开关与目标由环境变量控制:
|
||||
dingtalk_notify_enabled = true | false(默认 false,未配置时不推送)
|
||||
dingtalk_notify_target = 联系人姓名(如 夏一平)
|
||||
推送失败仅记录警告、不抛异常,避免影响审批主流程。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = lambda *a, **kw: None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def push_report(report: str, subject: str = "") -> bool:
|
||||
"""
|
||||
推送审批报告到钉钉联系人(测试阶段)。
|
||||
|
||||
通过环境变量 dingtalk_notify_enabled 控制开关,dingtalk_notify_target 指定联系人。
|
||||
推送失败仅记录警告,不抛异常,避免影响审批主流程。
|
||||
|
||||
Args:
|
||||
report: 报告文本
|
||||
subject: 审批主题(请假/加班),仅用于日志
|
||||
|
||||
Returns:
|
||||
True=已推送,False=未开启/未配置/推送失败
|
||||
"""
|
||||
load_app_env()
|
||||
|
||||
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:
|
||||
from app.utils.dingtalk_sender import send_to_person
|
||||
send_to_person(target, text=report)
|
||||
logger.info("[%s] 审批报告已推送至钉钉: %s", subject, target)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("[%s] 钉钉推送失败: %s", subject, e)
|
||||
return False
|
||||
|
||||
|
||||
def build_push_summary(results: list, subject: str = "") -> str:
|
||||
"""
|
||||
根据校验结果生成钉钉推送的文字消息(多行)。
|
||||
|
||||
通过/校验不通过未处理/人工复核/超期四组均以文字说明推送(不再只发表格):
|
||||
- 全部通过:用简洁格式
|
||||
【{subject}审批】本次审批 N 条{subject}申请,
|
||||
分别是:
|
||||
{单据标题}-{假期类型}
|
||||
...
|
||||
全部通过
|
||||
- 混合情况:分组文字说明(通过 / 校验不通过未处理 / 需人工复核)
|
||||
【{subject}审批】本次共审批 N 条{subject}申请。
|
||||
通过 X 条,分别是:
|
||||
{标题}-{类型}
|
||||
校验不通过未处理 Y 条,分别是:
|
||||
{标题}-{类型}
|
||||
校验不通过原因:...
|
||||
需人工复核 Z 条,分别是:
|
||||
{标题}-{类型}
|
||||
详情页:{url}
|
||||
|
||||
仅当至少有一个业务组(通过/校验不通过未处理/人工复核)非空时才生成内容,否则返回空串。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表
|
||||
subject: 审批主题(请假/加班)
|
||||
|
||||
Returns:
|
||||
推送消息文本;无业务结果时返回 ""
|
||||
"""
|
||||
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") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
pending = [r for r in results if r.get("decision") == "未完成"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
if not passed and not rejected and not review and not overdue and not pending and not abnormal:
|
||||
return ""
|
||||
|
||||
def _item(r):
|
||||
# 兼容请假(leave_info/假期类型)、加班(overtime_info/加班类型)与离职电子签(resign_info/员工姓名)
|
||||
info = r.get("leave_info") or r.get("overtime_info") or r.get("resign_info") or {}
|
||||
title = r.get("title", "") or info.get("请假人员") or info.get("加班人员") or info.get("员工姓名") or "未知"
|
||||
vtype = info.get("假期类型") or info.get("加班类型") or ""
|
||||
return f"{title}-{vtype}" if vtype else title
|
||||
|
||||
all_pass = (not rejected and not review and not overdue and not pending and not abnormal 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))
|
||||
reason = r.get("note") or r.get("error") or "未知"
|
||||
lines.append(f"校验不通过原因:{reason}")
|
||||
if review:
|
||||
lines.append(f"需人工复核 {len(review)} 条,分别是:")
|
||||
for r in review:
|
||||
lines.append(_item(r))
|
||||
lines.append(f"详情页:{r.get('detail_url') or '无'}")
|
||||
if overdue:
|
||||
lines.append(f"超期待人资处理 {len(overdue)} 条,分别是:")
|
||||
for r in overdue:
|
||||
lines.append(_item(r))
|
||||
lines.append(f"处理原因:{r.get('note') or r.get('error') or '未知'}")
|
||||
if pending:
|
||||
lines.append(f"未完成待跟进 {len(pending)} 条,分别是:")
|
||||
for r in pending:
|
||||
lines.append(_item(r))
|
||||
lines.append(f"原因:{r.get('note') or r.get('error') or '未知'}")
|
||||
if abnormal:
|
||||
lines.append(f"审批异常 {len(abnormal)} 条,分别是:")
|
||||
for r in abnormal:
|
||||
lines.append(_item(r))
|
||||
lines.append(f"详情页:{r.get('detail_url') or '无'}")
|
||||
if failed:
|
||||
lines.append(f"另有处理失败 {len(failed)} 条,请查看日志。")
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -1,69 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: __init__.py
|
||||
@Description: OA/HR 系统 API 模块:按功能拆分为 todo / flow / attendance / leave 子模块,
|
||||
本文件统一 re-export 公开接口,保持对调用方 import 路径不变。
|
||||
通用请求封装见 base.py(oa_request_json)。
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.oa_api.base import (
|
||||
oa_request_json,
|
||||
_handle_response,
|
||||
OALoginExpiredError,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.todo import (
|
||||
fetch_todo_page,
|
||||
parse_todo_list,
|
||||
get_documents,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.flow import (
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
get_fjk_file_list,
|
||||
download_attachment,
|
||||
get_contract_sign_status,
|
||||
enrich_form_sign_status,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.attendance import (
|
||||
get_attendance_daily,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.leave import (
|
||||
fetch_leave_record_page,
|
||||
get_leave_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.punch import (
|
||||
fetch_punch_record_page,
|
||||
get_punch_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.work_communication import (
|
||||
search_person,
|
||||
upload_attachment,
|
||||
submit_work_communication,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"oa_request_json",
|
||||
"_handle_response",
|
||||
"OALoginExpiredError",
|
||||
"fetch_todo_page",
|
||||
"parse_todo_list",
|
||||
"get_documents",
|
||||
"get_wf_activity_by_task_id",
|
||||
"extract_form_id",
|
||||
"get_business_data",
|
||||
"get_fjk_file_list",
|
||||
"download_attachment",
|
||||
"get_contract_sign_status",
|
||||
"enrich_form_sign_status",
|
||||
"get_attendance_daily",
|
||||
"fetch_leave_record_page",
|
||||
"get_leave_records",
|
||||
"fetch_punch_record_page",
|
||||
"get_punch_records",
|
||||
"search_person",
|
||||
"upload_attachment",
|
||||
"submit_work_communication",
|
||||
]
|
||||
@@ -1,64 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: attendance.py
|
||||
@Description: 考勤逐日接口(按员工 + 日期范围查询每日班次与上下班打卡)。
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import ATTENDANCE_DAILY_URL
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_attendance_daily(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
start_date: str,
|
||||
end_date: str
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
按员工 + 日期范围查询每日考勤(含班次起止时间与上下班打卡)。
|
||||
|
||||
接口: rf_s_kq_count_leave_yc_day_all/redApiExec.mc
|
||||
kq_status_total 按考勤状态分类返回记录(来源为前端 JS 扒取的请求构造):
|
||||
- 0=休息日、1=正常班、9=未打卡、11=异常(如上班漏打卡)
|
||||
因此需按这四种状态各查一次,再按 work_day 合并去重,才能同时拿到
|
||||
班次名/班次时段与休息日、异常班当天的上下班打卡。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
start_date: 查询起始日期 "YYYY-MM-DD"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
|
||||
Returns:
|
||||
每日考勤记录列表(四种状态合并去重后,按日期升序)
|
||||
"""
|
||||
by_day: Dict[str, Dict[str, Any]] = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info(
|
||||
"获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date,
|
||||
)
|
||||
json_data = oa_request_json(session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
@@ -1,72 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: base.py
|
||||
@Description: OA API 通用请求封装(发送 + 校验):只封装「发送 + 状态码 + JSON 解析」,
|
||||
业务级成功判定(state / success / code)保留在各接口自身。
|
||||
对应 docs/通用接口请求封装规划.md。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _handle_response(resp, label):
|
||||
"""统一校验响应:存在性 / 状态码 / JSON 可解析性,返回解析后的 JSON。"""
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
def oa_request_json(
|
||||
session: SessionPage,
|
||||
method: str,
|
||||
url: str,
|
||||
params: dict,
|
||||
label: str,
|
||||
timeout: int = 20,
|
||||
headers: dict = None,
|
||||
):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。
|
||||
|
||||
Args:
|
||||
session: 已登录的 DrissionPage SessionPage 对象(已带登录 Cookie)
|
||||
method: "GET" / "POST"(GET 用 params 传参,POST 用 data 传参)
|
||||
url: 接口地址
|
||||
params: 请求参数
|
||||
label: 接口中文名(用于报错信息)
|
||||
timeout: 请求超时秒数,默认 20
|
||||
headers: 附加请求头(显式传入可规避 DrissionPage 对 session 级
|
||||
Referer 头的 KeyError 问题),可空
|
||||
|
||||
Returns:
|
||||
解析后的 JSON 字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
if method.upper() == "GET":
|
||||
session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
else:
|
||||
session.post(url, data=params, timeout=timeout, headers=headers)
|
||||
return _handle_response(session.response, label)
|
||||
@@ -1,390 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: flow.py
|
||||
@Description: OA 流程引擎/表单/附件接口:taskId 查 formId、businessKey 查表单数据、附件下载。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, Optional
|
||||
from urllib.parse import unquote
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
WF_ACTIVITY_URL,
|
||||
WORKFORM_ENGINE_URL,
|
||||
FILE_DOWNLOAD_URL,
|
||||
FJK_BY_IDS_URL,
|
||||
CONTRACT_SIGNATURE_SELECT_URL,
|
||||
ATTACHMENT_SAVE_DIR,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_wf_activity_by_task_id(
|
||||
session: SessionPage,
|
||||
task_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 taskId 调用 WfActivity 接口获取 formId。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
task_id: SSO 解析得到的 taskId
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典,包含 formId 等信息
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
data = {"taskId": task_id}
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WfActivity")
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data: Dict[str, Any]) -> str:
|
||||
"""
|
||||
从 WfActivity 接口返回数据中提取 formId。
|
||||
|
||||
Args:
|
||||
wf_activity_data: get_wf_activity_by_task_id 返回的 JSON
|
||||
|
||||
Returns:
|
||||
formId 字符串
|
||||
|
||||
Raises:
|
||||
ValueError: 未找到 formId
|
||||
"""
|
||||
# 常见 formId 字段路径:顶层,以及 data / result 子对象
|
||||
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: SessionPage,
|
||||
business_key: str,
|
||||
form_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
business_key: SSO 解析得到的 businessKey
|
||||
form_id: 从 WfActivity 接口获取的 formId
|
||||
|
||||
Returns:
|
||||
表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
data = {
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
}
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WorkformEngine")
|
||||
|
||||
# 表单详情在 result 字段中(如 ot_date / staff_name 等)
|
||||
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
|
||||
|
||||
|
||||
# ==================== EHR 会话失效自愈 ====================
|
||||
# 关键坑:EHR 会话(hr.37du.co)可能中途失效(共享 cookies 过期/服务端踢下线),
|
||||
# 而待办接口在 oa.37du.co 上仍可用,导致 OA 侧会话校验检测不到——
|
||||
# 表现为附件清单/下载接口返回登录页 HTML 或"外部用户未登录,无法访问"。
|
||||
# 处置:检测到失效时用单据 SSO 详情链接(纯接口,sign 可重复使用)重建会话后重试一次。
|
||||
|
||||
|
||||
def _ehr_resp_is_login(resp) -> bool:
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp) -> bool:
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url: str) -> bool:
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_fjk_file_list(
|
||||
session: SessionPage,
|
||||
file_ids: str,
|
||||
detail_url: str = None,
|
||||
) -> list:
|
||||
"""
|
||||
按 fileId 列表调用 getFjkByIds 查询附件清单。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_ids: 逗号分隔的多个 fileId(如表单 result.contract_file 字段)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
附件清单(jsonList),每项含 id/fileName/fileSuffix/herfUrl/fileSize 等;
|
||||
无有效 fileId 时返回空列表。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
ids = [x.strip() for x in str(file_ids).split(",") if x.strip()]
|
||||
if not ids:
|
||||
return []
|
||||
data = {"ids": ",".join(ids)}
|
||||
logger.info("查询附件清单: ids=%s", ids)
|
||||
for attempt in (1, 2):
|
||||
session.post(FJK_BY_IDS_URL, data=data)
|
||||
resp = session.response
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
json_data = resp.json()
|
||||
logger.debug("getFjkByIds 返回: %s", json_data)
|
||||
return json_data.get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
|
||||
|
||||
def download_attachment(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str = ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
根据附件 fileId 从 OA 下载请假单据附件,支持多附件(逗号分隔多个 fileId)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_id: 附件 fileId 或逗号分隔的多个 fileId(表单 result.file 字段值)
|
||||
save_dir: 保存目录(默认 downloads)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
成功保存的文件路径;多附件或下载失败时返回逗号拼接的相对路径列表
|
||||
(保持与历史单附件行为一致:单个成功仍返回单个路径字符串)。
|
||||
"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
|
||||
# 兼容多附件:file 字段可能为逗号分隔的多个 fileId,逐个下载
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
下载单个附件 fileId,返回本地保存路径;失败返回 None。
|
||||
|
||||
会话失效(响应非文件流)时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载附件: fileId=%s", file_id)
|
||||
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
session.get(url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态查询 ====================
|
||||
# getBusinessDate 返回的 ext_is_initiate_sign / ext_staff_sign_status / ext_org_sign_status
|
||||
# 恒为空串,拿不到真实签署状态;需再调该查询接口(按 main_id 即合同业务主键)取真实状态
|
||||
|
||||
|
||||
def get_contract_sign_status(session: SessionPage, contract_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询电子签真实签署状态。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
contract_id: 合同业务主键(= getBusinessData 返回的 main_id / SSO businessKey)
|
||||
|
||||
Returns:
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...,
|
||||
"file": 签章附件 fileId 串(可能为 None/空)}
|
||||
查询失败抛 RuntimeError。
|
||||
"""
|
||||
session.post(CONTRACT_SIGNATURE_SELECT_URL, data={
|
||||
"contract_id": contract_id,
|
||||
"inParamFormId": "",
|
||||
"colCode": "main_id",
|
||||
})
|
||||
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 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
# 业务层执行异常(如该合同无电子签记录,服务端存储过程报错):稳定可复现,
|
||||
# 重试无意义,按"查不到状态"处理——返回空状态,由校验归为"未完成"(不管)
|
||||
logger.warning("签署状态查询业务异常(按未完成处理): contract_id=%s, meg=%s",
|
||||
contract_id, json_data.get("meg"))
|
||||
return {
|
||||
"is_initiate_sign": None,
|
||||
"sign_status_yg": None,
|
||||
"sign_status_qy": None,
|
||||
"file": None,
|
||||
}
|
||||
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
return {
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def enrich_form_sign_status(form_data: Dict[str, Any], session: SessionPage) -> Dict[str, Any]:
|
||||
"""
|
||||
把 getBusinessData 返回的表单数据中的电子签三状态字段补上真实值。
|
||||
|
||||
表单 result 里 ext_is_initiate_sign/ext_staff_sign_status/ext_org_sign_status 恒为空串,
|
||||
需按 main_id 再调签署状态查询接口,把真实状态写回这三个字段,供后续校验使用。
|
||||
接口变更:表单 contract_file 已恒为空串,签章附件 fileId 改从签署记录 file 字段获取
|
||||
(",id1,id2" 格式,get_fjk_file_list 按逗号拆分可容忍前导逗号)。
|
||||
"""
|
||||
contract_id = form_data.get("main_id")
|
||||
if not contract_id:
|
||||
raise RuntimeError("表单数据缺少 main_id,无法查询电子签签署状态")
|
||||
sign_status = get_contract_sign_status(session, contract_id)
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
@@ -1,132 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: leave.py
|
||||
@Description: 员工请假记录接口:单页查询与自动分页。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import LEAVE_RECORD_URL, DEFAULT_PAGE_SIZE
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_leave_record_page(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = DEFAULT_PAGE_SIZE,
|
||||
sub_type: str = "-1"
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页员工请假记录。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
begin_date: 查询起始日期 "YYYY-MM-DD"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_no: 页码(从1开始)
|
||||
page_size: 每页条数
|
||||
sub_type: 假期类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
接口返回的 data 字段字典,包含 total / pageCount / list
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
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)
|
||||
json_data = oa_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录")
|
||||
|
||||
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: SessionPage,
|
||||
staff_id: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_size: int = DEFAULT_PAGE_SIZE,
|
||||
sub_type: str = "-1"
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
查询员工某时间段内的全部请假记录(自动分页)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
begin_date: 查询起始日期 "YYYY-MM-DD"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_size: 每页条数
|
||||
sub_type: 假期类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
请假记录列表,每条包含:
|
||||
- staff_id: 员工ID
|
||||
- staff_name: 员工姓名
|
||||
- leave_businessKey: 审批单号
|
||||
- sub_type: 假期类型编码
|
||||
- vacation_type_name: 假期名称
|
||||
- leave_reason: 请假原因
|
||||
- leave_days: 请假天数
|
||||
- leave_hours: 请假小时
|
||||
- start_time: 开始时间
|
||||
- end_time: 结束时间
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
all_records: List[Dict[str, Any]] = []
|
||||
|
||||
# 请求第一页,获取总条数与总页数
|
||||
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
|
||||
@@ -1,132 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: punch.py
|
||||
@Description: 员工打卡明细接口:单页查询与自动分页。
|
||||
kq_time 为真实打卡时间,bc_date 为考勤归属日(跨天打卡次日0点~6点归入前一天)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import PUNCH_RECORD_URL, DEFAULT_PAGE_SIZE
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_punch_record_page(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = DEFAULT_PAGE_SIZE,
|
||||
sub_type: str = "-1"
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页员工打卡明细。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
begin_date: 查询起始日期 "YYYY-MM-DD"(同时作为 bc_date/bc_date_end/begin/end)
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_no: 页码(从1开始)
|
||||
page_size: 每页条数
|
||||
sub_type: 类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
接口返回的 data 字段字典,包含 total / pageCount / list
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
|
||||
json_data = oa_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
|
||||
|
||||
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_punch_records(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_size: int = DEFAULT_PAGE_SIZE,
|
||||
sub_type: str = "-1"
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
查询员工某时间段内的全部打卡明细(自动分页)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
begin_date: 查询起始日期 "YYYY-MM-DD"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_size: 每页条数
|
||||
sub_type: 类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
打卡明细列表,每条包含:
|
||||
- kq_time: 真实打卡时间 "YYYY-MM-DD HH:MM:SS"
|
||||
- bc_date: 考勤归属日 "YYYY-MM-DD"(跨天打卡次日0点~6点归入前一天)
|
||||
- time_order: 上下班类型 "1"=上班 "2"=下班
|
||||
- status: 打卡状态
|
||||
- address: 打卡地点
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
all_records: List[Dict[str, Any]] = []
|
||||
|
||||
# 请求第一页,获取总条数与总页数
|
||||
page_info = fetch_punch_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_punch_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
|
||||
@@ -1,175 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: todo.py
|
||||
@Description: OA 待办列表接口:分页查询待办单据、解析、去重。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import re
|
||||
import random
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_todo_page(
|
||||
session: SessionPage,
|
||||
subject: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = DEFAULT_PAGE_SIZE
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页待办列表数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
subject: 待办标题关键字,如 "请假" / "加班"
|
||||
page_no: 页码(从1开始)
|
||||
page_size: 每页条数
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或状态码异常
|
||||
"""
|
||||
params = {
|
||||
"method": "list",
|
||||
"dataType": "todo",
|
||||
"fdType": FD_TYPE, # 待办类型(请假/加班)
|
||||
"fdCateId": "",
|
||||
"q.s_raq": str(random.random()), # 防缓存随机数,每次刷新
|
||||
"q.fdSubject": subject, # 按标题关键字过滤(请假/加班)
|
||||
# 分页参数必须用 pageno/rowsize/pagingtype:
|
||||
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
|
||||
"pageno": page_no,
|
||||
"rowsize": page_size,
|
||||
"pagingtype": "default",
|
||||
"orderby": "fdCreateTime",
|
||||
"ordertype": "down",
|
||||
}
|
||||
logger.debug("请求第 %d 页待办[%s]", page_no, subject)
|
||||
return oa_request_json(session, "GET", TODO_LIST_URL, params, "待办列表")
|
||||
|
||||
|
||||
def parse_todo_list(data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
解析接口返回的 JSON,提取每张单据的关键信息。
|
||||
|
||||
Args:
|
||||
data: 接口返回的 JSON
|
||||
|
||||
Returns:
|
||||
单据列表,每项包含:
|
||||
- title: 标题(去除 HTML 标签)
|
||||
- creator: 发起人
|
||||
- time: 接收时间(字符串)
|
||||
- detail_url: SSO 跳转链接(完整 URL)
|
||||
"""
|
||||
datas = data.get("datas", [])
|
||||
if not datas:
|
||||
return []
|
||||
|
||||
docs = []
|
||||
for row in datas:
|
||||
# 1. 标题
|
||||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
||||
title_raw = title_cell.get("value", "")
|
||||
# 移除 <span class="subjecthead"> 标签,仅保留内容
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
|
||||
# 2. 发起人
|
||||
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
|
||||
creator = creator_cell.get("value", "")
|
||||
|
||||
# 3. 接收时间
|
||||
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
|
||||
time_str = time_cell.get("value", "")
|
||||
|
||||
# 4. SSO 跳转链接(补全为完整 URL)
|
||||
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
|
||||
detail_url = href_cell.get("value", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = BASE_URL + detail_url
|
||||
|
||||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:加班申请"):
|
||||
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
|
||||
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
|
||||
continue
|
||||
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": creator,
|
||||
"time": time_str,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(
|
||||
session: SessionPage,
|
||||
subject: str,
|
||||
page_size: int = DEFAULT_PAGE_SIZE
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
主入口:获取所有待处理单据(自动分页)。
|
||||
|
||||
请假与加班流程逻辑一致,仅通过 subject 关键字区分。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已设置 cookies)
|
||||
subject: 待办标题关键字,如 "请假" / "加班"
|
||||
page_size: 每页条数(默认15)
|
||||
|
||||
Returns:
|
||||
所有单据的列表
|
||||
"""
|
||||
all_docs = []
|
||||
|
||||
# 请求第一页,获取总条数
|
||||
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
|
||||
total = int(data.get("page", {}).get("totalSize", 0))
|
||||
logger.info("总待办[%s]条数: %d", subject, total)
|
||||
|
||||
# 解析第一页
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 1 页获取 %d 条", len(docs))
|
||||
|
||||
# 若总条数超过单页,继续翻页
|
||||
if total > page_size:
|
||||
total_pages = (total + page_size - 1) // page_size
|
||||
for p in range(2, total_pages + 1):
|
||||
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
|
||||
docs = parse_todo_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
|
||||
|
||||
# 去重:OA 待办接口分页可能返回重复单据(同一条在多次/多页重复出现),
|
||||
# 以详情链接 detail_url(含唯一 taskId)为键去重,避免同一单重复审批、重复推送
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
@@ -1,359 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: work_communication.py
|
||||
@Description: OA 工作沟通推送接口:搜索接收人 / 上传附件 / 提交工作沟通。
|
||||
对应需求文档 aa.md(OA工作沟通自动化发送)。
|
||||
附件上传采用「普通上传」流程(getuserkey → 二进制上传 → submit 绑定),
|
||||
暂不实现 MD5 秒传(文件已存在时也走完整上传,保证可用性,后续需要再优化)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
BASE_URL,
|
||||
PERSON_SEARCH_URL,
|
||||
ATT_UPLOAD_URL,
|
||||
ATT_UPLOADER_URL,
|
||||
WORK_COMMUNICATION_ADD_URL,
|
||||
KM_COLLABORATE_SAVE_URL,
|
||||
FD_CONTENT_PREFIX,
|
||||
FD_CATEGORY_MAP,
|
||||
FD_CATEGORY_DEFAULT,
|
||||
KM_COLLABORATE_MODEL,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json, OALoginExpiredError
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
|
||||
_DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Referer": f"{BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
def _check_response(resp, label: str):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。供返回 XML 或纯文本等非 JSON 的接口使用。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或状态码异常
|
||||
OALoginExpiredError: 会话失效(接口被重定向到登录页返回 HTML)
|
||||
"""
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
return resp
|
||||
|
||||
|
||||
def search_person(session: SessionPage, keyword: str, org_type: str = "15") -> Optional[tuple]:
|
||||
"""
|
||||
按工号或姓名搜索人员,返回 (person_id, person_name)。
|
||||
|
||||
- 精确匹配优先:姓名或 ID 与关键字完全一致时直接命中;
|
||||
- 模糊命中多个时默认取第一个,并记录警告。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
keyword: 工号或姓名(支持模糊)
|
||||
org_type: 组织类型,默认 "15"(与 aa.md 一致)
|
||||
|
||||
Returns:
|
||||
(person_id, person_name) 元组;未找到返回 None
|
||||
|
||||
Raises:
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
session.get(PERSON_SEARCH_URL, params=params, timeout=20)
|
||||
resp = _check_response(session.response, "人员搜索")
|
||||
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
logger.warning("人员搜索[%s]响应解析失败: %s", keyword, e)
|
||||
return None
|
||||
|
||||
matches = []
|
||||
for node in root.iter("data"):
|
||||
pid = node.get("id")
|
||||
pname = node.get("name")
|
||||
if pid and pname:
|
||||
matches.append((pid, pname))
|
||||
|
||||
if not matches:
|
||||
logger.warning("未搜索到人员: %s", keyword)
|
||||
return None
|
||||
|
||||
# 精确匹配优先(工号/姓名全等)
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
if len(matches) > 1:
|
||||
logger.warning("关键字[%s]模糊匹配到 %d 人,默认取第一个: %s", keyword, len(matches), matches[0])
|
||||
pid, pname = matches[0]
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
def upload_attachment(session: SessionPage, file_path: str) -> str:
|
||||
"""
|
||||
上传单个附件,返回最终附件 ID(attid)。
|
||||
|
||||
普通上传流程(不实现 MD5 秒传,保证可用性):
|
||||
1. 获取 userkey(上传凭证)
|
||||
2. 上传二进制内容,得到 filekey
|
||||
3. submit 绑定附件,得到最终 attid
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
file_path: 附件文件路径(相对路径会自动转绝对路径)
|
||||
|
||||
Returns:
|
||||
最终附件 ID(attid)
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 附件文件不存在
|
||||
RuntimeError: 上传任一步骤失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
|
||||
file_name = os.path.basename(file_path)
|
||||
file_size = str(os.path.getsize(file_path))
|
||||
# 按扩展名推断 MIME 类型(aa.md 原实现硬编码 xlsx,这里通用化支持任意附件类型)
|
||||
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
||||
last_modified = time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0800",
|
||||
time.localtime(os.path.getmtime(file_path)),
|
||||
)
|
||||
# fdSign = Base64(文件名) 并去掉 + / = 字符(与 swf_attachment.js 的 createAttMainInfo 一致)
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# 上传三步统一显式带上 UA/Referer 等请求头(不设 session 级 headers,
|
||||
# 避免触发 DrissionPage 4.1.1.4 对 session 级 Referer 头的 KeyError bug)
|
||||
|
||||
# ---- 步骤1:获取 userkey ----
|
||||
params1 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "getuserkey",
|
||||
"format": "json",
|
||||
"filesize": file_size,
|
||||
"md5": "",
|
||||
"fileName": file_name,
|
||||
"isSupportDirect": "false",
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp1 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params1, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
logger.info(" 1. 获取 userkey 成功")
|
||||
|
||||
# ---- 步骤2:上传二进制(userkey 需随请求带上,否则报「附件上传密钥为空」) ----
|
||||
uploader_url = f"{ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
files = {"file": (file_name, open(file_path, "rb"), file_type)}
|
||||
data2 = {
|
||||
"id": "WU_FILE_0",
|
||||
"name": file_name,
|
||||
"type": file_type,
|
||||
"lastModifiedDate": last_modified,
|
||||
"size": file_size,
|
||||
}
|
||||
session.post(uploader_url, data=data2, files=files, timeout=60, headers=_DEFAULT_HEADERS)
|
||||
resp2 = _check_response(session.response, "附件上传-二进制")
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
logger.info(" 2. 二进制上传成功, filekey: %s...", filekey[:16])
|
||||
|
||||
# ---- 步骤3:submit 绑定附件,获取最终 attid ----
|
||||
params3 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "submit",
|
||||
"format": "json",
|
||||
"filekey": filekey,
|
||||
"filename": file_name,
|
||||
"fdKey": "attachment",
|
||||
"fdModelName": KM_COLLABORATE_MODEL,
|
||||
"fdAttType": "byte",
|
||||
"width": "null",
|
||||
"height": "null",
|
||||
"proportion": "true",
|
||||
"fdSign": fd_sign,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp3 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params3, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
logger.info(" 3. 提交绑定成功, attid: %s", attid)
|
||||
return attid
|
||||
|
||||
|
||||
def _encode_fd_content(content: str) -> str:
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。
|
||||
|
||||
真实抓包确认:CKEditor 保存时 fdContent 形如
|
||||
`䙉堠䵅䉁卅㘴{<base64(HTML)>}`,其中前缀为固定字节,花括号内是内容的 base64。
|
||||
"""
|
||||
return FD_CONTENT_PREFIX + "{" + base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session: SessionPage) -> tuple:
|
||||
"""打开新建工作沟通页(method=add),解析出草稿 fdId 与通知方式随机字段名。
|
||||
|
||||
Returns:
|
||||
(fd_id, notify_field_name):fdId 隐藏域值;`__notify_type_<随机id>` 字段名
|
||||
|
||||
Raises:
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
RuntimeError: 页面解析失败
|
||||
"""
|
||||
session.get(WORK_COMMUNICATION_ADD_URL, timeout=20)
|
||||
resp = _check_response(session.response, "新建工作沟通-取页面")
|
||||
html = resp.text or ""
|
||||
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
|
||||
fd_id = m.group(1) if m else ""
|
||||
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
|
||||
notify_field = m2.group(1) if m2 else ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
logger.info("获取新建草稿 fdId: %s, 通知方式字段: %s", fd_id, notify_field)
|
||||
return fd_id, notify_field
|
||||
|
||||
|
||||
def submit_work_communication(
|
||||
session: SessionPage,
|
||||
receiver_ids: Union[str, List[str]],
|
||||
receiver_names: Union[str, List[str]],
|
||||
subject: str,
|
||||
content: str,
|
||||
attachment_ids: Union[str, List[str]] = None,
|
||||
creator_id: str = None,
|
||||
category_id: str = FD_CATEGORY_DEFAULT,
|
||||
) -> str:
|
||||
"""
|
||||
提交工作沟通(新建),成功返回沟通文档 ID(fdId)。
|
||||
|
||||
真实提交端点:`kmCollaborateMain.do?method=save&s_seq=1`(aa.md 中的 user.jsp 为错误端点)。
|
||||
流程:先打开新建页取草稿 fdId 与通知方式随机字段,再以相同表单结构 POST 保存。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
receiver_ids: 接收人 ID,单个字符串或列表(多个以「;」分号分隔)
|
||||
receiver_names: 接收人姓名,单个字符串或列表(顺序与 ID 一致)
|
||||
subject: 标题
|
||||
content: 内容(支持 HTML 富文本)
|
||||
attachment_ids: 附件 ID(attid),单个字符串或列表(多个以「;」分号分隔),可空
|
||||
creator_id: 创建人(当前操作人)ID,必填
|
||||
category_id: 沟通类型,可传中文名(如「工作安排」)或类型 ID,
|
||||
默认「工作安排」(config.FD_CATEGORY_DEFAULT)
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 提交失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,请传入当前操作人的用户 ID")
|
||||
|
||||
# 沟通类型:支持中文名 -> ID 映射,空值回退默认「工作安排」(fdCategoryId 必填)
|
||||
if category_id in FD_CATEGORY_MAP:
|
||||
category_id = FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = FD_CATEGORY_DEFAULT
|
||||
|
||||
# 真实抓包确认:多人参与人 / 多附件 ID 在表单体里以「;」分号分隔(不是逗号)
|
||||
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
|
||||
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
|
||||
if isinstance(attachment_ids, list):
|
||||
attachment_ids_str = ";".join(attachment_ids)
|
||||
else:
|
||||
attachment_ids_str = attachment_ids or ""
|
||||
|
||||
# 1) 打开新建页,取草稿 fdId 与通知方式随机字段
|
||||
fd_id, notify_field = _get_add_page_fd_info(session)
|
||||
|
||||
# 2) 组装保存请求(结构对齐真实抓包的 method=save&s_seq=1 表单体)
|
||||
data = {
|
||||
"fdId": fd_id,
|
||||
"fdNumber": "",
|
||||
"participantIds": receiver_ids_str,
|
||||
"participantNames": receiver_names_str,
|
||||
"docSubject": subject,
|
||||
"fdIsPriority": "",
|
||||
"fdCategoryId": category_id,
|
||||
"fdContent": _encode_fd_content(content),
|
||||
"attachmentForms.attachment.fdModelId": "",
|
||||
"attachmentForms.attachment.extParam": "",
|
||||
"attachmentForms.attachment.fdModelName": KM_COLLABORATE_MODEL,
|
||||
"attachmentForms.attachment.fdKey": "attachment",
|
||||
"attachmentForms.attachment.fdAttType": "",
|
||||
"attachmentForms.attachment.fdMulti": "",
|
||||
"attachmentForms.attachment.deletedAttachmentIds": "",
|
||||
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
|
||||
"__landray_fileattachment": "",
|
||||
"fdNotifyType": "todo",
|
||||
"__notify_type_placeholder": "todo", # 占位,下方替换为真实随机字段名
|
||||
"_fdPartnerOperating": "true",
|
||||
"fdPartnerOperating": "true",
|
||||
"fdIsOnlyView": "false",
|
||||
"fdIsReminders": "false",
|
||||
"fdRemindersDay_hidden": "",
|
||||
"fdRemindersDay": "2",
|
||||
"docCreatorId": creator_id,
|
||||
}
|
||||
if notify_field:
|
||||
data[notify_field] = data.pop("__notify_type_placeholder")
|
||||
else:
|
||||
data.pop("__notify_type_placeholder", None)
|
||||
|
||||
# 3) POST 保存
|
||||
session.post(KM_COLLABORATE_SAVE_URL, params={"method": "save", "s_seq": "1"}, data=data, timeout=30)
|
||||
resp = _check_response(session.response, "工作沟通提交")
|
||||
text = resp.text or ""
|
||||
|
||||
# 成功标志:返回「您的操作已成功!」提示页(自动关闭),而非数字 ID
|
||||
if "您的操作已成功" in text:
|
||||
logger.info("工作沟通发送成功, 文档ID: %s", fd_id)
|
||||
return fd_id
|
||||
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
@@ -1,157 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.session_manager
|
||||
@FileName: session_manager.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 10:30
|
||||
@Description: 从 ChromiumPage 提取 Cookies,生成 SessionPage 供后台请求;支持 cookies 持久化复用
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
|
||||
# 登录 cookies 持久化目录:统一放在 AppData\Local\37duAutomation,文件名按平台区分
|
||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
||||
_SESSIONS_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
|
||||
def init_session_from_page(
|
||||
browser_page: ChromiumPage,
|
||||
copy_headers: bool = True
|
||||
) -> SessionPage:
|
||||
"""
|
||||
从已登录的 ChromiumPage 中提取 cookies 和 headers,
|
||||
创建并返回一个可直接发送后台请求的 SessionPage 对象。
|
||||
|
||||
Args:
|
||||
browser_page: 已登录的 ChromiumPage 实例
|
||||
copy_headers: 是否复制浏览器的 User-Agent 等头部信息(默认 True)
|
||||
|
||||
Returns:
|
||||
已设置好 cookies 和 headers 的 SessionPage 对象
|
||||
"""
|
||||
session = SessionPage()
|
||||
|
||||
# 1. 获取浏览器 cookies(全域名:oa 域登录态 + hr 域可能已有的会话)
|
||||
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,请确认浏览器已登录")
|
||||
|
||||
# 2. 可选复制 headers(主要是 User-Agent,防止被反爬)
|
||||
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])
|
||||
|
||||
# 3. 可额外设置默认超时、重试等
|
||||
session.set.timeout(10) # 全局超时 10 秒
|
||||
|
||||
return session
|
||||
|
||||
|
||||
# 便捷函数:SSO 跳转后同步浏览器 cookies 到 SessionPage
|
||||
def refresh_session_cookies(session: SessionPage, browser_page: ChromiumPage) -> None:
|
||||
"""
|
||||
从浏览器重新同步全域名 cookies 到 SessionPage。
|
||||
SSO 的 linkLogin 会在 hr 域产生新的会话 cookie,需在浏览器完成 SSO 跳转后调用。
|
||||
|
||||
Args:
|
||||
session: 目标 SessionPage 对象
|
||||
browser_page: 已登录且已完成 SSO 跳转的 ChromiumPage 实例
|
||||
"""
|
||||
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,请确认浏览器登录态")
|
||||
|
||||
|
||||
# ---------- Cookies 持久化(复用登录态,免重复登录) ----------
|
||||
def save_browser_cookies(browser_page: ChromiumPage, path: str = COOKIE_FILE) -> None:
|
||||
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
|
||||
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: str = COOKIE_FILE):
|
||||
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
|
||||
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: str = COOKIE_FILE) -> SessionPage:
|
||||
"""用已保存的 cookies 构建 SessionPage;无可用 cookies 时返回 None。"""
|
||||
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: str = COOKIE_FILE) -> ChromiumPage:
|
||||
"""用已保存的 cookies 创建 ChromiumPage(免输账号密码,SSO 跳转仍需真浏览器)。"""
|
||||
browser = ChromiumPage()
|
||||
cookies = load_cookies(path)
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
|
||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
||||
"""通过轻量接口 sumTodoCount 判断会话是否有效(无效则需重新登录)。
|
||||
|
||||
会话有效时接口返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});
|
||||
会话失效会被重定向到登录页返回 HTML,据此判定失效。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.config import TODO_COUNT_URL
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# 便捷函数:直接从已登录的浏览器提取会话,一步到位
|
||||
def create_session_from_login() -> SessionPage:
|
||||
"""
|
||||
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
||||
再提取 SessionPage。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
browser = oa_login()
|
||||
return init_session_from_page(browser)
|
||||
@@ -1,64 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.sso
|
||||
@FileName: sso.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:50
|
||||
@Description: SSO 链接解析模块:浏览器访问 SSO 链接,从重定向后的详情页 URL 提取 taskId/fkId 和 businessKey
|
||||
@Version: 1.0.1
|
||||
"""
|
||||
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
from typing import Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
|
||||
|
||||
def resolve_sso_params(
|
||||
browser: ChromiumPage,
|
||||
sso_url: str,
|
||||
wait_timeout: float = 20,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
用浏览器打开 SSO 链接,等待 JS 重定向到详情页,
|
||||
从最终 URL 的 query 参数中提取 taskId(部分页面命名为 fkId)和 businessKey。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(SSO 的 JS 跳转必须用真浏览器)
|
||||
sso_url: SSO 跳转链接(完整 URL)
|
||||
wait_timeout: 等待 JS 跳转完成的超时时间(秒,默认 20)
|
||||
|
||||
Returns:
|
||||
包含 taskId 和 businessKey 的字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 跳转失败或 URL 中缺少 taskId/businessKey
|
||||
"""
|
||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||
|
||||
# 浏览器打开 SSO 链接,页面 JS 自动重定向到详情页。
|
||||
# 跳转链: sso.mob -> unifyWorkFlow.jsp(中间页,一闪而过) -> goToWorkFlow 详情页。
|
||||
# 因此不能等中间页(会匹配不到而超时卡 wait_timeout 秒),改为等待地址栏离开 SSO 链接。
|
||||
browser.get(sso_url)
|
||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||
logger.info("重定向最终 URL: %s", browser.url)
|
||||
|
||||
# 从详情页 URL 提取 taskId(fkId 是同一字段的别名)和 businessKey
|
||||
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}
|
||||
@@ -1,135 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.work_communication
|
||||
@FileName: work_communication.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-25
|
||||
@Description: OA 工作沟通推送模块(app 版公共模块)。
|
||||
对外提供 send_work_communication 一键推送入口:
|
||||
搜索接收人 -> 上传附件 -> 提交沟通,三个步骤全部成功才算推送成功;
|
||||
任一接收人解析失败或任一附件上传失败即整体失败,不发送部分数据。
|
||||
底层接口见 oa_api/work_communication.py(search_person / upload_attachment / submit_work_communication),
|
||||
可单独调用。需求文档见 aa.md。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用示例:
|
||||
from app.service.hrbp.oa.common.session_manager import load_saved_session
|
||||
from app.service.hrbp.oa.common.work_communication import send_work_communication
|
||||
|
||||
session = load_saved_session() # 复用「37duOA登录」写入的共享 cookies
|
||||
doc_id = send_work_communication(
|
||||
session=session,
|
||||
receiver_keywords=["37036801", "夏一平"], # 工号或姓名,单个或列表
|
||||
subject="【通知】...",
|
||||
content="<p>正文支持 HTML</p>",
|
||||
attachment_paths=[r"D:\\资料\\附件1.xlsx"], # 可选
|
||||
creator_id="1342173e36cf416088266b17d7d084a4", # 当前操作人 ID(必填)
|
||||
category="工作安排", # 沟通类型(可选):工作交流/信息传递/工作安排/项目沟通/温馨提示/其他
|
||||
)
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.oa_api.work_communication import (
|
||||
search_person,
|
||||
upload_attachment,
|
||||
submit_work_communication,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def _to_list(value: Union[str, List[str], None]) -> List[str]:
|
||||
"""把单个字符串或列表统一成列表(空值返回空列表)。"""
|
||||
if not value:
|
||||
return []
|
||||
return [value] if isinstance(value, str) else list(value)
|
||||
|
||||
|
||||
def send_work_communication(
|
||||
session: SessionPage,
|
||||
receiver_keywords: Union[str, List[str]],
|
||||
subject: str,
|
||||
content: str,
|
||||
attachment_paths: Union[str, List[str]] = None,
|
||||
creator_id: str = None,
|
||||
category: str = None,
|
||||
) -> str:
|
||||
"""
|
||||
发送工作沟通(一键推送入口)。
|
||||
|
||||
完整流程:解析接收人(工号/姓名 -> ID)-> 上传附件 -> 提交沟通。
|
||||
- 接收人支持多个,用工号或姓名(姓名同名时建议用工号保证准确);
|
||||
- 附件支持多个,任一上传失败即整体失败(不发送部分数据);
|
||||
- 所有步骤成功才返回沟通文档 ID(fdId)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(复用共享 cookies)
|
||||
receiver_keywords: 接收人工号或姓名,单个字符串或列表
|
||||
subject: 沟通标题
|
||||
content: 沟通内容(支持 HTML 富文本)
|
||||
attachment_paths: 附件文件路径,单个字符串或列表,可空
|
||||
creator_id: 创建人(当前操作人)用户 ID,必填
|
||||
category: 沟通类型,可传中文名(如「工作安排」「信息传递」)或类型 ID,
|
||||
默认「工作安排」(config.FD_CATEGORY_DEFAULT)
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 接收人解析失败 / 附件上传失败 / 提交失败(含具体原因)
|
||||
"""
|
||||
if not subject or not subject.strip():
|
||||
raise ValueError("subject(标题) 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content(内容) 不能为空")
|
||||
if not creator_id:
|
||||
raise ValueError("creator_id(创建人ID) 必填,请传入当前操作人的用户 ID")
|
||||
|
||||
# ---- 1. 解析接收人 ----
|
||||
receiver_ids, receiver_names = [], []
|
||||
unresolved = []
|
||||
for kw in _to_list(receiver_keywords):
|
||||
kw = str(kw).strip()
|
||||
if not kw:
|
||||
continue
|
||||
result = search_person(session, kw)
|
||||
if result:
|
||||
pid, pname = result
|
||||
receiver_ids.append(pid)
|
||||
receiver_names.append(pname)
|
||||
logger.info("接收人[%s] -> %s (ID: %s)", kw, pname, pid)
|
||||
else:
|
||||
unresolved.append(kw)
|
||||
|
||||
if not receiver_ids:
|
||||
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
|
||||
if unresolved:
|
||||
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
|
||||
|
||||
# ---- 2. 上传附件(任一失败即整体失败) ----
|
||||
attachment_ids = []
|
||||
for path in _to_list(attachment_paths):
|
||||
attid = upload_attachment(session, path)
|
||||
attachment_ids.append(attid)
|
||||
logger.info("附件[%s] -> attid: %s", path, attid)
|
||||
|
||||
# ---- 3. 提交沟通 ----
|
||||
return submit_work_communication(
|
||||
session=session,
|
||||
receiver_ids=receiver_ids,
|
||||
receiver_names=receiver_names,
|
||||
subject=subject,
|
||||
content=content,
|
||||
attachment_ids=attachment_ids or None,
|
||||
creator_id=creator_id,
|
||||
category_id=category,
|
||||
)
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 请假审批流程包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,221 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: app.service.hrbp.oa.leave.attachment_check
|
||||
@FileName: attachment_check.py
|
||||
@Author: 小布丁
|
||||
@Description: 请假附件内容检测(业务层)。
|
||||
基于通用图像 OCR(app.utils.ocr.recognize_text / recognize_text_raw):
|
||||
1. 按假期类型做关键词命中检测(病假/婚假/产检假)
|
||||
2. 结婚证登记日期识别 + 1 年内判断
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
from datetime import date
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from app.utils.ocr import recognize_text, recognize_text_raw
|
||||
|
||||
# 按假期类型分类的关键词库
|
||||
LEAVE_KEYWORDS = {
|
||||
# 病假/医疗类:对应医院诊断证明、病历、检验单等
|
||||
"sick": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
},
|
||||
# 婚假类:对应结婚证、婚姻登记证明
|
||||
"marriage": {
|
||||
"结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关",
|
||||
"婚姻证", "中华人民共和国结婚证",
|
||||
},
|
||||
# 产检假类:对应产检报告、B超单、妊娠诊断证明
|
||||
"maternity": {
|
||||
"产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期",
|
||||
"超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心",
|
||||
},
|
||||
}
|
||||
VALID_TYPES = set(LEAVE_KEYWORDS.keys()) | {"all"}
|
||||
|
||||
|
||||
def _ocr_read(file_path: str, debug: bool = False) -> Tuple[str, str]:
|
||||
"""识别附件图片,返回 (清洗后文本, 原始文本);文件异常/识别失败返回 ("", "")。"""
|
||||
if not os.path.isfile(file_path):
|
||||
return "", ""
|
||||
try:
|
||||
return recognize_text(file_path, debug=debug), recognize_text_raw(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
if debug:
|
||||
print(f"[识别异常] {e}")
|
||||
return "", ""
|
||||
|
||||
|
||||
def _hit_keywords(full_text: str, leave_type: str) -> List[str]:
|
||||
"""返回文本命中的关键词列表(leave_type 支持 all 汇总全部关键词)。"""
|
||||
if leave_type not in VALID_TYPES:
|
||||
return []
|
||||
if leave_type == "all":
|
||||
target_keywords = set()
|
||||
for kw_set in LEAVE_KEYWORDS.values():
|
||||
target_keywords.update(kw_set)
|
||||
else:
|
||||
target_keywords = LEAVE_KEYWORDS[leave_type]
|
||||
return [kw for kw in target_keywords if kw in full_text]
|
||||
|
||||
|
||||
def check_leave_attachment(file_path: str, leave_type: str = "sick", debug: bool = False) -> bool:
|
||||
"""
|
||||
检测请假附件图片是否包含对应假期的关键词。
|
||||
|
||||
Args:
|
||||
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
|
||||
leave_type: sick / marriage / maternity / all
|
||||
debug: 是否打印调试信息
|
||||
|
||||
Returns:
|
||||
命中关键词返回 True;未命中 / 文件异常 / 识别失败返回 False
|
||||
"""
|
||||
full_text, _ = _ocr_read(file_path, debug=debug)
|
||||
if not full_text:
|
||||
return False
|
||||
|
||||
if debug:
|
||||
print("【清洗后匹配文本】")
|
||||
print(full_text)
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
hit_words = _hit_keywords(full_text, leave_type)
|
||||
if debug:
|
||||
print(f"【命中关键词】: {hit_words}")
|
||||
return len(hit_words) > 0
|
||||
|
||||
|
||||
def check_leave_attachment_detail(
|
||||
file_path: str, leave_type: str = "sick", debug: bool = False
|
||||
) -> Tuple[bool, List[str], str]:
|
||||
"""
|
||||
检测请假附件图片是否包含对应假期的关键词,并返回命中的具体关键词列表与 OCR 原文。
|
||||
|
||||
Args:
|
||||
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
|
||||
leave_type: sick / marriage / maternity / all
|
||||
debug: 是否打印调试信息
|
||||
|
||||
Returns:
|
||||
(是否命中, 命中的关键词列表, OCR 识别原文);文件异常/识别失败返回 (False, [], "")
|
||||
"""
|
||||
full_text, raw_text = _ocr_read(file_path, debug=debug)
|
||||
if not full_text:
|
||||
return False, [], ""
|
||||
|
||||
hit_words = _hit_keywords(full_text, leave_type)
|
||||
return len(hit_words) > 0, hit_words, raw_text
|
||||
|
||||
|
||||
def extract_dates(text: str) -> List[date]:
|
||||
"""
|
||||
从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。
|
||||
|
||||
Args:
|
||||
text: OCR 拼接后的文本
|
||||
|
||||
Returns:
|
||||
有效日期列表(datetime.date)
|
||||
"""
|
||||
dates: List[date] = []
|
||||
patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in patterns:
|
||||
for m in re.finditer(pat, text):
|
||||
try:
|
||||
dates.append(date(int(m.group(1)), int(m.group(2)), int(m.group(3))))
|
||||
except ValueError:
|
||||
continue
|
||||
return dates
|
||||
|
||||
|
||||
def _extract_registration_date(text: str) -> Optional[date]:
|
||||
"""
|
||||
从结婚证文本中提取"登记日期"字段对应的日期。
|
||||
|
||||
优先查找"登记日期"关键词后面紧跟的日期,如果找不到则返回 None。
|
||||
|
||||
Args:
|
||||
text: OCR 识别的全文
|
||||
|
||||
Returns:
|
||||
登记日期(如果找到),否则返回 None
|
||||
"""
|
||||
# 查找"登记日期"关键词
|
||||
reg_match = re.search(r'登记日期', text)
|
||||
if not reg_match:
|
||||
return None
|
||||
|
||||
# 从"登记日期"位置开始,提取后面紧跟的日期
|
||||
text_after = text[reg_match.end():]
|
||||
date_patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in date_patterns:
|
||||
m = re.search(pat, text_after)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def marriage_within_one_year(
|
||||
file_path: str,
|
||||
today: Optional[date] = None,
|
||||
debug: bool = False,
|
||||
) -> Tuple[bool, Optional[date]]:
|
||||
"""
|
||||
识别结婚证上的登记日期并判断是否在当前日期 1 年内。
|
||||
|
||||
优先查找"登记日期"关键词附近的日期,如果找不到则取识别到的最大日期作为兜底。
|
||||
|
||||
Args:
|
||||
file_path: 结婚证图片路径
|
||||
today: 基准日期(默认当天)
|
||||
debug: 是否打印调试信息
|
||||
|
||||
Returns:
|
||||
(是否 1 年内, 识别到的登记日期);识别失败/无日期返回 (False, None)
|
||||
"""
|
||||
if today is None:
|
||||
today = date.today()
|
||||
|
||||
full_text, _ = _ocr_read(file_path, debug=debug)
|
||||
if not full_text:
|
||||
return False, None
|
||||
|
||||
dates = extract_dates(full_text)
|
||||
if not dates:
|
||||
if debug:
|
||||
print("【未识别到任何日期】")
|
||||
return False, None
|
||||
|
||||
# 优先查找"登记日期"关键词附近的日期
|
||||
reg_date = _extract_registration_date(full_text)
|
||||
if reg_date is None:
|
||||
# 找不到"登记日期"关键词,fallback 到最大日期
|
||||
reg_date = max(dates)
|
||||
if debug:
|
||||
print("【未找到登记日期关键词,使用最大日期兜底】")
|
||||
|
||||
ok = reg_date <= today and (today - reg_date).days <= 365
|
||||
if debug:
|
||||
print(f"【识别日期】: {dates}")
|
||||
print(f"【登记日期】: {reg_date},1年内: {ok}")
|
||||
return ok, reg_date
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 简单自测入口
|
||||
path = r"D:\downloads\ocr_test_01.png"
|
||||
print("病假关键词:", check_leave_attachment(path, "sick", debug=True))
|
||||
@@ -1,22 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.leave_approval
|
||||
@FileName: leave_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:21
|
||||
@Description: 请假审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,71 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 请假表单解析模块
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ---------- 假期类型编码 -> 名称映射 ----------
|
||||
# 已统一收口到 HR 平台共享层(hrbp/common/config.py),此处直接复用,不再重复定义
|
||||
|
||||
|
||||
# ---------- 请假表单解析 ----------
|
||||
|
||||
def _first_non_null(result: Dict[str, Any], *keys: str) -> Any:
|
||||
"""返回 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: Dict[str, Any]) -> str:
|
||||
"""从表单数据中提取假期类型名称(支持编码和名称两种输入)"""
|
||||
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: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析请假表单数据,提取关键字段。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(即 doc['formData'])
|
||||
|
||||
Returns:
|
||||
包含请假关键字段的字典(中文键名)
|
||||
"""
|
||||
return {
|
||||
"请假人员ID": result.get("staff_id"),
|
||||
"工号": result.get("staff_code"),
|
||||
"请假人员": result.get("staff_name"),
|
||||
"所属部门": result.get("dept_org_name"),
|
||||
"假期类型": _resolve_vacation_type(result),
|
||||
# 日期区间以 begin_date/end_date 为准(start_time/end_time 可能跨天,不可用于取日期)
|
||||
"开始日期": result.get("begin_date"),
|
||||
"开始时间": result.get("start_time"),
|
||||
"结束日期": result.get("end_date"),
|
||||
"结束时间": result.get("end_time"),
|
||||
# 注意:leave_days 可能为 0.0(小时假),不能用 or 链(会被 falsy 短路成 None)
|
||||
"请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"),
|
||||
"请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"),
|
||||
"请假原因": result.get("leave_reason"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程报告模块。
|
||||
校验结果分三组:通过 / 校验不通过未处理 / 人工复核。
|
||||
输出两份清单:
|
||||
《请假审批校验不通过未处理人员明细清单》:员工姓名、假期类型、校验不通过原因、详情页链接
|
||||
《附件人工复核待办清单》:员工姓名、假期类型、详情页链接(供人工打开查看附件)
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 4.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的请假人员,缺失时回退到发起人。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("请假人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _vtype(r: Dict[str, Any]) -> str:
|
||||
"""假期类型。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始时间", "开始时间"),
|
||||
("结束时间", "结束时间"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"请假审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《请假审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
path = r.get("附件路径") or "下载失败"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《请假审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -1,348 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.validator
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程校验模块(审批决策三态:通过 / 校验不通过未处理 / 人工复核)
|
||||
1. 根据假期类型分支处理:
|
||||
- 小时特假:请假当天是排班上班日即通过,否则校验不通过未处理
|
||||
- 事假/调休假/半天休/普通事假等:排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||
- 病假/特别福利假/特殊事假/产假:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);
|
||||
天数不一致或缺附件 -> 校验不通过未处理
|
||||
2. 排班数据获取:调用排班接口(rf_p_kq_count_SelectBanci,按工号+日期范围,含未来日期排班),
|
||||
统计请假区间内非"休息"天数
|
||||
@Version: 4.2.0
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import math
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.oa.leave.parser import VACATION_TYPE_MAP, _resolve_vacation_type, _parse_leave_form
|
||||
from app.service.hrbp.oa.common.oa_api import download_attachment
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift
|
||||
from app.service.hrbp.oa.leave.attachment_check import (
|
||||
check_leave_attachment,
|
||||
check_leave_attachment_detail,
|
||||
marriage_within_one_year,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可
|
||||
HOURLY_LEAVE_TYPES = {
|
||||
"小时特假",
|
||||
}
|
||||
|
||||
# Group 1:仅校验排班上班天数与填报天数一致
|
||||
LEAVE_TYPE_GROUP_1 = {
|
||||
"事假", "调休假", "半天休(仅限人资专用)",
|
||||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||||
"年度福利假",
|
||||
}
|
||||
|
||||
# Group 2:校验天数一致 + 需上传附件
|
||||
LEAVE_TYPE_GROUP_2 = {
|
||||
"病假", "特别福利假", "特殊事假", "产假",
|
||||
}
|
||||
|
||||
|
||||
# ---------- 排班数据获取 ----------
|
||||
|
||||
def _get_date_range(start_time: str, end_time: str) -> Tuple[str, str]:
|
||||
"""从请假起止时间中提取日期范围 (start_date, end_date),格式 YYYY-MM-DD"""
|
||||
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
|
||||
|
||||
|
||||
# 排班接口依赖 HR 登录态(hr_cookies.json),单次运行内复用 HR 会话与当前操作人 user_id
|
||||
_HR_CTX = {"session": None, "user_id": None}
|
||||
|
||||
|
||||
def _get_hr_context() -> Tuple[Any, str]:
|
||||
"""获取 (hr_session, user_id),带缓存;失效时清缓存重试一次。"""
|
||||
if _HR_CTX["session"] is not None:
|
||||
return _HR_CTX["session"], _HR_CTX["user_id"]
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||||
_HR_CTX.update(session=session, user_id=user_id)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _get_day_shift(shift_rows: Any, date_str: str) -> str:
|
||||
"""从排班记录中提取指定日期的班次名(动态列 "YYYY-MM-DD_bc_name")。"""
|
||||
for rec in shift_rows:
|
||||
name = rec.get(f"{date_str}_bc_name")
|
||||
time_ = rec.get(f"{date_str}_bc_time")
|
||||
if name or time_:
|
||||
return str(name if name is not None else "")
|
||||
return ""
|
||||
|
||||
|
||||
def _get_work_days_count(staff_code: str, start_date: str, end_date: str) -> int:
|
||||
"""
|
||||
获取请假区间内实际上班天数(非休息日)。
|
||||
|
||||
数据源为排班接口(rf_p_kq_count_SelectBanci),按工号(base_code)+日期范围查询
|
||||
(含未来日期排班),逐日班次存于动态列 "YYYY-MM-DD_bc_name/bc_time/paiban_type"。
|
||||
注意:休息与否只能以 bc_name 为准("休息"或空串=休息日):
|
||||
返回数据中休息日的 paiban_type 可能为 -2/0,而上班日(bc_name 为具体班次名)
|
||||
的 paiban_type 也可能为 0/-3,故不能按 paiban_type 判断。
|
||||
"""
|
||||
session, user_id = _get_hr_context()
|
||||
try:
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
logger.info("排班数据已获取: %s ~ %s, 共 %d 条", start_date, end_date, len(rows))
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,重建会话后重试")
|
||||
_HR_CTX.clear()
|
||||
session, user_id = _get_hr_context()
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
bc_name = _get_day_shift(rows, day)
|
||||
if bc_name not in ("", "休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
# ---------- 主入口 ----------
|
||||
|
||||
def _verify_attachment(session: Any, vacation_type: str, reason: str, file_id: str) -> Tuple[str, str, Any]:
|
||||
"""
|
||||
根据假期类型校验附件内容,返回 (decision, note, attachment_path)。
|
||||
|
||||
- 病假:OCR 病假关键词,命中通过,未命中人工复核
|
||||
- 特别福利假:按请假理由细分
|
||||
- 婚假:OCR 结婚证关键词 + 登记日期 1 年内
|
||||
- 产检假:OCR 产检关键词
|
||||
- 丧假:有附件即通过
|
||||
- 特殊事假 / 产假:有附件即通过
|
||||
"""
|
||||
path = download_attachment(session, file_id)
|
||||
if not path:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
# 多附件支持:download_attachment 对逗号分隔的多个 fileId 返回逗号拼接的路径串,
|
||||
# 拆分后逐个做内容校验,任一命中即通过
|
||||
paths = [p for p in path.split(",") if p]
|
||||
if not paths:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
def _first_hit(checker):
|
||||
return next((p for p in paths if checker(p)), None)
|
||||
|
||||
def _kw_hint(p, leave_type):
|
||||
"""返回该附件 OCR 命中的关键词列表(逗号拼接),用于备注便于人工判断。"""
|
||||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||||
return "、".join(hits) if hits else ""
|
||||
|
||||
if vacation_type == "病假":
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||||
|
||||
if vacation_type == "特别福利假":
|
||||
reason = reason or ""
|
||||
if "婚" in reason:
|
||||
hit = None
|
||||
reg_kw = ""
|
||||
for p in paths:
|
||||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||||
if ok:
|
||||
hit = p
|
||||
reg_kw = "、".join(hits)
|
||||
break
|
||||
if hit is None:
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||||
ok, reg_date = marriage_within_one_year(hit)
|
||||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||||
if ok:
|
||||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||||
if "产" in reason or "孕" in reason:
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||||
if "丧" in reason:
|
||||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||||
|
||||
# 特殊事假 / 产假:有附件即通过
|
||||
return "通过", f"附件已上传({len(paths)}份)", path
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张请假单据,返回审批决策。
|
||||
|
||||
流程:
|
||||
1. 解析表单数据,提取假期类型、请假天数、附件等信息
|
||||
2. 调用排班接口,计算请假区间内实际上班天数
|
||||
3. 根据假期类型分支处理:
|
||||
- 小时特假:请假当天为排班上班日 -> 通过,否则校验不通过未处理
|
||||
- Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||
- Group 2(病假/产假等):天数一致且已上传附件 -> 人工复核;否则校验不通过未处理
|
||||
|
||||
Args:
|
||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||
session: 已登录的 SessionPage 对象(用于下载请假附件)
|
||||
(排班数据走 HR 排班接口,独立使用 HR 登录态,不依赖该 session)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策及详细信息
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
leave_info = _parse_leave_form(form_data)
|
||||
|
||||
staff_id = leave_info.get("请假人员ID")
|
||||
staff_code = leave_info.get("工号")
|
||||
vacation_type = leave_info.get("假期类型")
|
||||
# 日期区间:其他假期一律用 begin_date/end_date(start_time/end_time 可能跨天,
|
||||
# 不可用于取日期);仅小时特假为按小时请假,用 start_time/end_time 取当日排班
|
||||
begin_date = leave_info.get("开始日期")
|
||||
end_date = leave_info.get("结束日期")
|
||||
leave_days = leave_info.get("请假天数")
|
||||
attachment = leave_info.get("附件")
|
||||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||||
if is_hourly:
|
||||
begin_date = leave_info.get("开始时间")
|
||||
end_date = leave_info.get("结束时间")
|
||||
|
||||
result: Dict[str, Any] = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "通过",
|
||||
"note": "",
|
||||
"leave_info": leave_info,
|
||||
}
|
||||
|
||||
# 缺失必要信息
|
||||
if not vacation_type:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法识别假期类型"
|
||||
return result
|
||||
|
||||
if not staff_id:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人员ID缺失"
|
||||
return result
|
||||
|
||||
if not staff_code:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人工号缺失"
|
||||
return result
|
||||
|
||||
# 获取日期范围
|
||||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||||
if not start_date or not end_date:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假起止日期缺失"
|
||||
return result
|
||||
|
||||
# 计算实际上班天数(排班接口按工号查询,含未来日期)
|
||||
try:
|
||||
actual_work_days = _get_work_days_count(staff_code, start_date, end_date)
|
||||
except Exception as e:
|
||||
logger.warning("计算上班天数失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
# 填报天数
|
||||
try:
|
||||
fill_days = float(leave_days) if leave_days else 0
|
||||
except (TypeError, ValueError):
|
||||
fill_days = 0
|
||||
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对:
|
||||
# 0.5天->1个工作日,1.0天->1个工作日,1.5天->2个工作日
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
# ========== 根据假期类型分支处理 ==========
|
||||
|
||||
if vacation_type in HOURLY_LEAVE_TYPES:
|
||||
# 按小时请假(如小时特假):当天为上班日 + 已上传附件才通过
|
||||
leave_hours = leave_info.get("请假小时")
|
||||
if actual_work_days < 1:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"请假当天非排班上班日(实际上班天数: {actual_work_days})"
|
||||
elif not attachment:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "未上传附件"
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["附件路径"] = download_attachment(session, attachment)
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||||
f"当天为上班日,附件已上传)"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_1:
|
||||
# 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:
|
||||
# Group 2:需附件的假期(病假/特别福利假/特殊事假/产假)
|
||||
# - 天数不一致或缺附件 -> 校验不通过未处理
|
||||
# - 附件通过内容校验(OCR/仅附件)-> 通过;OCR 无法确认 -> 人工复核
|
||||
reasons = []
|
||||
if days_mismatch:
|
||||
reasons.append(
|
||||
f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
)
|
||||
if not attachment:
|
||||
reasons.append("未上传附件")
|
||||
|
||||
if reasons:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = ";".join(reasons)
|
||||
else:
|
||||
result["decision"], result["note"], result["附件路径"] = _verify_attachment(
|
||||
session, vacation_type, leave_info.get("请假原因"), attachment
|
||||
)
|
||||
else:
|
||||
# 未识别的假期类型
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||||
|
||||
return result
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程审核模块:解析 -> 校验(三态均已完成才同意)-> 报告
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,56 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.downloads
|
||||
@FileName: downloads.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@Description: 离职电子签签章附件下载。
|
||||
电子签全部完成后,按 getBusinessData 的 contract_file(逗号分隔 fileId)
|
||||
调 getFjkByIds 获取附件清单(解除确认书/报酬支付确认等),
|
||||
再逐个经 fjkFileDownload.mob 下载到本地,供后续解析校验/归档。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.oa.common.config import RESIGN_ATTACHMENT_SAVE_DIR
|
||||
from app.service.hrbp.oa.common.oa_api.flow import (
|
||||
get_fjk_file_list,
|
||||
download_attachment,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def download_contract_files(
|
||||
session,
|
||||
contract_file: str,
|
||||
save_dir: str = RESIGN_ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
下载离职电子签签章附件(解除确认书/报酬支付确认)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
contract_file: getBusinessData 返回的 contract_file 字段(逗号分隔多个 fileId);
|
||||
接口变更后该字段恒为空,需由 enrich_form_sign_status 从签署记录 file 字段补全
|
||||
save_dir: 保存目录(默认离职电子签签章附件目录)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
{文件名: 本地路径};无附件或全部失败返回空 dict(不抛异常)。
|
||||
"""
|
||||
files = get_fjk_file_list(session, contract_file, detail_url=detail_url)
|
||||
saved: Dict[str, str] = {}
|
||||
for f in files:
|
||||
fid = (f.get("id") or "").strip()
|
||||
if not fid:
|
||||
continue
|
||||
path = download_attachment(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved[f.get("fileName") or fid] = path
|
||||
if not saved:
|
||||
logger.warning("签章附件下载为空: contract_file=%s", contract_file)
|
||||
return saved
|
||||
@@ -1,141 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程表单解析模块(解析 WorkformEngine 返回的 result,提取电子签三状态及员工信息)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 是否已发起电子签字典(hr_staff_contract.is_initiate_sign)
|
||||
INITIATE_SIGN_MAP = {
|
||||
"0": "未发起",
|
||||
"1": "已发起",
|
||||
"2": "已完成",
|
||||
"3": "已撤销",
|
||||
"5": "已过期",
|
||||
"7": "已拒签",
|
||||
"8": "已作废",
|
||||
}
|
||||
|
||||
# 员工/企业签署状态字典(esign_sigin_state)
|
||||
SIGN_STATE_MAP = {
|
||||
"1": "签署中",
|
||||
"2": "已完成",
|
||||
"3": "未完成",
|
||||
"4": "已作废",
|
||||
}
|
||||
|
||||
# 电子签三状态均须等于该编码(已完成)才同意
|
||||
SIGN_DONE_CODE = "2"
|
||||
|
||||
# 离职类型字典(hr_staff_contract.leaveoffice_type 编码 -> 展示文本)
|
||||
LEAVEOFFICE_TYPE_MAP = {
|
||||
"": "请选择",
|
||||
"0": "辞职",
|
||||
"1": "辞退",
|
||||
"4": "合同期内辞职",
|
||||
"9": "其他",
|
||||
"2": "进修学习",
|
||||
"3": "参军",
|
||||
"5": "除名",
|
||||
"6": "开除",
|
||||
"7": "死亡",
|
||||
"8": "失踪",
|
||||
"11": "协商一致解除",
|
||||
"12": "主动离职",
|
||||
"13": "非主动离职",
|
||||
"14": "自动离职(未办理离职手续)",
|
||||
"15": "开除人员",
|
||||
"16": "调出",
|
||||
"17": "合同到期未续签",
|
||||
"18": "解除合同",
|
||||
"ext_8": "个人申请辞职",
|
||||
"ext_1": "主动辞职",
|
||||
"ext_2": "到期个人不愿续签",
|
||||
"ext_3": "单位不续签",
|
||||
"ext_4": "劝退无证明",
|
||||
"ext_5": "劝退有证明",
|
||||
"ext_6": "自动离职",
|
||||
"ext_7": "双方协商一致解除",
|
||||
"10": "退休",
|
||||
}
|
||||
|
||||
|
||||
def _sign_name(mapping: Dict[str, str], code: Any) -> str:
|
||||
"""将状态编码转换为名称;空值返回空串,未知编码原样返回。"""
|
||||
if code is None or str(code).strip() == "":
|
||||
return ""
|
||||
return mapping.get(str(code).strip(), str(code))
|
||||
|
||||
|
||||
def parse_resign_e_sign_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析离职电子签表单数据,提取关键字段。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(即 doc['formData'])
|
||||
|
||||
Returns:
|
||||
包含离职电子签关键字段的字典(中文键名),三个电子签状态同时保留编码与名称
|
||||
"""
|
||||
is_initiate = result.get("ext_is_initiate_sign")
|
||||
staff_state = result.get("ext_staff_sign_status")
|
||||
org_state = result.get("ext_org_sign_status")
|
||||
|
||||
return {
|
||||
"员工姓名": result.get("staff_name"),
|
||||
"工号": result.get("base_code"),
|
||||
"身份证号": result.get("idcard"),
|
||||
"所属事业部": result.get("belong_unit_org_name"),
|
||||
"组织架构": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"离职日期": result.get("leaveoffice_time"),
|
||||
"离职类型编码": result.get("leaveoffice_type"),
|
||||
"离职类型": _sign_name(LEAVEOFFICE_TYPE_MAP, result.get("leaveoffice_type")),
|
||||
"手机号": result.get("mobile_phone"),
|
||||
"合同类型": result.get("contract_type"),
|
||||
"合同开始日期": result.get("contract_start_date"),
|
||||
"合同结束日期": result.get("contract_end_date"),
|
||||
"是否已发起电子签编码": is_initiate,
|
||||
"是否已发起电子签": _sign_name(INITIATE_SIGN_MAP, is_initiate),
|
||||
"员工签署状态编码": staff_state,
|
||||
"员工签署状态": _sign_name(SIGN_STATE_MAP, staff_state),
|
||||
"企业签署状态编码": org_state,
|
||||
"企业签署状态": _sign_name(SIGN_STATE_MAP, org_state),
|
||||
}
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 示例 result(WorkformEngine 返回的 result 字段,见 aa.md)
|
||||
sample_result = {
|
||||
"base_code": "37022119",
|
||||
"belong_unit_org_name": "金色印象事业部",
|
||||
"ext_is_initiate_sign": "2",
|
||||
"ext_org_sign_status": "2",
|
||||
"ext_staff_sign_status": "2",
|
||||
"idcard": "511623200311056533",
|
||||
"leaveoffice_time": "2026-07-31",
|
||||
"leaveoffice_type": "ext_8",
|
||||
"mobile_phone": "19950986716",
|
||||
"org_full_path": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第四片区-石油路PLUS会馆-接待组",
|
||||
"post_name": "接待员",
|
||||
"staff_name": "夏礼广",
|
||||
}
|
||||
|
||||
parsed = parse_resign_e_sign_form(sample_result)
|
||||
logger.info("===== 离职电子签信息解析结果 =====")
|
||||
for key, value in parsed.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
@@ -1,146 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程报告模块。
|
||||
校验结果分两组:通过(已同意)/ 未完成(不管,待后续流转)。
|
||||
输出清单:
|
||||
《离职电子签未完成待跟进清单》:员工姓名、电子签三状态、详情页链接
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的员工姓名,缺失时回退到发起人。"""
|
||||
info = r.get("resign_info", {}) or {}
|
||||
return info.get("员工姓名") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 resign_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("员工姓名", "员工姓名"),
|
||||
("工号", "工号"),
|
||||
("所属事业部", "所属事业部"),
|
||||
("组织架构", "组织架构"),
|
||||
("岗位", "岗位"),
|
||||
("离职日期", "离职日期"),
|
||||
("离职类型", "离职类型"),
|
||||
("合同类型", "合同类型"),
|
||||
("合同开始日期", "合同开始日期"),
|
||||
("合同结束日期", "合同结束日期"),
|
||||
("是否已发起电子签", "是否已发起电子签"),
|
||||
("员工签署状态", "员工签署状态"),
|
||||
("企业签署状态", "企业签署状态"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def _format_verify(verify: Dict[str, Any]) -> str:
|
||||
"""将文书核验结果格式化为易读摘要行。"""
|
||||
if not verify:
|
||||
return ""
|
||||
parts = [f"文书核验: {'通过' if verify.get('is_pass') else '不通过'}"]
|
||||
if verify.get("msg"):
|
||||
parts.append(str(verify["msg"]))
|
||||
for key in ("离职日期(表单)", "报酬支付确认日期", "解除确认书日期", "文书离职原因", "文书命中离职类型"):
|
||||
val = verify.get(key)
|
||||
if val:
|
||||
parts.append(f"{key}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+处理失败/异常)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/未完成/失败/异常}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
pending = [r for r in results if r.get("decision") == "未完成"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},未完成待跟进 {len(pending)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"离职电子签审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("resign_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({info.get('工号', '')})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("签章附件"):
|
||||
lines.append(f" 签章附件: {r['签章附件']}")
|
||||
if r.get("文书核验"):
|
||||
lines.append(f" {_format_verify(r['文书核验'])}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 未完成(不管)待跟进清单 -----
|
||||
if pending:
|
||||
lines.append("《离职电子签未完成待跟进清单》")
|
||||
lines.append("(电子签未全部完成,或文书核验未通过,机器不处理,待后续流转/人工复核)")
|
||||
for i, r in enumerate(pending, 1):
|
||||
info = r.get("resign_info", {}) or {}
|
||||
note = r.get("note") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(
|
||||
f"{i}. 员工姓名: {_name(r)} | "
|
||||
f"发起: {info.get('是否已发起电子签', '未知')} | "
|
||||
f"员工: {info.get('员工签署状态', '未知')} | "
|
||||
f"企业: {info.get('企业签署状态', '未知')} | "
|
||||
f"原因: {note} | 详情页链接: {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("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《离职电子签审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -1,22 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.resign_e_sign_approval
|
||||
@FileName: resign_e_sign_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程审核入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.resign_e_sign.validator import validate_doc
|
||||
from app.service.hrbp.oa.resign_e_sign.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""离职电子签流程审核:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="离职电子签流程", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,144 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.validator
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程校验模块(审批决策两态:通过 / 未完成)。
|
||||
规则(见 aa.md):进入详情取三个电子签状态字段,三者均为"已完成",
|
||||
且下载的签章文书(解除确认书/报酬支付确认)核验通过(日期/离职原因与表单一致),
|
||||
才同意;任一不满足则不处理("不管"),留给后续待办/人工复核。
|
||||
- 是否已发起电子签 ext_is_initiate_sign(hr_staff_contract.is_initiate_sign)
|
||||
- 员工签署状态 ext_staff_sign_status(esign_sigin_state)
|
||||
- 企业签署状态 ext_org_sign_status(esign_sigin_state)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.oa.resign_e_sign.parser import (
|
||||
parse_resign_e_sign_form,
|
||||
SIGN_DONE_CODE,
|
||||
)
|
||||
from app.service.hrbp.oa.resign_e_sign.downloads import download_contract_files
|
||||
from app.service.hrbp.oa.resign_e_sign.verify_docs import verify_resign_docs
|
||||
from app.service.hrbp.oa.common.oa_api.flow import enrich_form_sign_status
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def _is_done(value: Any) -> bool:
|
||||
"""判断电子签状态编码是否为已完成(编码为字符串 "2")。"""
|
||||
return value is not None and str(value).strip() == SIGN_DONE_CODE
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张离职电子签单据,返回审批决策。
|
||||
|
||||
流程:
|
||||
1. 解析表单数据,提取电子签三状态与员工信息
|
||||
2. 三者均已完成 -> 通过(同意),并下载签章附件(解除确认书/报酬支付确认)
|
||||
3. 否则 -> 未完成(不管)
|
||||
|
||||
Args:
|
||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||
session: 已登录的 SessionPage 对象(通过时用于下载签章附件)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策及详细信息
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
# 电子签三状态(ext_*)表单里恒为空串,需按 main_id 调签署状态查询接口补全;
|
||||
# 同时接口变更后表单 contract_file 恒为空串,附件 fileId 也由该步骤从签署记录补全
|
||||
try:
|
||||
enrich_form_sign_status(form_data, session)
|
||||
except Exception as e:
|
||||
logger.warning("补全电子签签署状态失败[%s]: %s", doc.get("title", ""), e)
|
||||
resign_info = parse_resign_e_sign_form(form_data)
|
||||
|
||||
is_initiate = form_data.get("ext_is_initiate_sign")
|
||||
staff_state = form_data.get("ext_staff_sign_status")
|
||||
org_state = form_data.get("ext_org_sign_status")
|
||||
|
||||
result: Dict[str, Any] = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "未完成",
|
||||
"note": "",
|
||||
"resign_info": resign_info,
|
||||
}
|
||||
|
||||
def _label(value: Any, mapping_name: str) -> str:
|
||||
"""取状态名称,缺失时回退为原始值/未知,便于人工判断。"""
|
||||
return resign_info.get(mapping_name) or (str(value).strip() if value is not None else "未知")
|
||||
|
||||
if all(_is_done(v) for v in (is_initiate, staff_state, org_state)):
|
||||
# 三状态均已完成:下载签章附件并核验文书。
|
||||
# 审批决策须「电子签三状态 + 文书核验」全部满足才通过;任一不满足均不审批。
|
||||
verify_result = None
|
||||
try:
|
||||
files = download_contract_files(
|
||||
session, form_data.get("contract_file"),
|
||||
detail_url=doc.get("detail_url"),
|
||||
)
|
||||
if files:
|
||||
result["签章附件"] = " | ".join(f"{name}->{path}" for name, path in files.items())
|
||||
# 文书核验:解析 PDF,比对日期/离职原因与表单字段
|
||||
try:
|
||||
verify_result = verify_resign_docs(files, resign_info)
|
||||
except Exception as e:
|
||||
logger.warning("核验离职电子签文书失败[%s]: %s", doc.get("title", ""), e)
|
||||
verify_result = {"is_pass": False, "msg": f"文书核验失败: {e}"}
|
||||
result["文书核验"] = verify_result
|
||||
else:
|
||||
# 兜底:三状态均已完成却拿不到附件(接口异常/签署记录缺失),按失败处理,
|
||||
# 避免"已完成却无附件"被混入常规"未完成"而漏查
|
||||
result["签章附件"] = "无(未查询到签章附件)"
|
||||
result["decision"] = "失败"
|
||||
result["note"] = "电子签三状态均已完成,但未查询到签章附件,无法核验文书,需人工排查"
|
||||
logger.warning("三状态已完成但未查询到签章附件[%s]: contract_file=%s",
|
||||
doc.get("title", ""), form_data.get("contract_file"))
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.warning("下载离职电子签签章附件失败[%s]: %s", doc.get("title", ""), e)
|
||||
result["签章附件"] = f"下载失败: {e}"
|
||||
result["decision"] = "失败"
|
||||
result["note"] = f"电子签三状态均已完成,但签章附件下载失败,需人工排查: {e}"
|
||||
return result
|
||||
|
||||
if verify_result is not None and verify_result.get("is_pass"):
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
"审批通过(电子签三状态均为已完成,且文书核验通过:"
|
||||
"报酬支付确认/解除确认书日期与离职原因均与表单一致)"
|
||||
)
|
||||
else:
|
||||
result["decision"] = "未完成"
|
||||
result["note"] = (
|
||||
"电子签三状态均已完成,但文书核验未通过,暂不审批待人工复核:"
|
||||
f"{verify_result.get('msg', '') if verify_result else '核验结果缺失'}"
|
||||
)
|
||||
logger.info(
|
||||
"核验不通过单据[%s] %s: %s",
|
||||
doc.get("title", ""), resign_info.get("员工姓名", ""),
|
||||
verify_result.get("msg", "") if verify_result else "核验结果缺失",
|
||||
)
|
||||
else:
|
||||
result["decision"] = "未完成"
|
||||
result["note"] = (
|
||||
f"电子签未全部完成,暂不处理(是否已发起电子签: {_label(is_initiate, '是否已发起电子签')},"
|
||||
f"员工签署状态: {_label(staff_state, '员工签署状态')},"
|
||||
f"企业签署状态: {_label(org_state, '企业签署状态')})"
|
||||
)
|
||||
logger.info(
|
||||
"未完成单据[%s] %s: 发起=%s, 员工=%s, 企业=%s",
|
||||
doc.get("title", ""), resign_info.get("员工姓名", ""),
|
||||
is_initiate, staff_state, org_state,
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -1,202 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.verify_docs
|
||||
@FileName: verify_docs.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@Description: 离职电子签签章文书核验(下载 PDF 之后)。
|
||||
1. 日期核验:报酬支付确认 / 解除确认书中的日期 == 表单实际离职日期(leaveoffice_time)
|
||||
2. 原因核验:解除确认书"因Xxx已于"中的离职原因 == 表单离职类型(leaveoffice_type 中文)
|
||||
核验结论仅用于报告展示与人工复核,不影响审批决策。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import re
|
||||
from datetime import date
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.utils.pdf import parse_pdf
|
||||
from app.service.hrbp.oa.resign_e_sign.parser import LEAVEOFFICE_TYPE_MAP
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
def _norm_zh(s: str) -> str:
|
||||
"""只保留汉字(用于归一化匹配,兼容 OCR 各种标点/空格)。"""
|
||||
return re.sub(r"[^\u4e00-\u9fff]", "", s or "")
|
||||
|
||||
|
||||
# 离职类型展示文本(LEAVEOFFICE_TYPE_MAP 的值,排除空/请选择),
|
||||
# 存 (归一化汉字, 原展示文本) 二元组,按归一化长度降序做最长匹配
|
||||
_LEAVE_TEXT_SORTED = sorted(
|
||||
((_norm_zh(v), v) for v in LEAVEOFFICE_TYPE_MAP.values() if v and v != "请选择"),
|
||||
key=lambda pair: len(pair[0]),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
def extract_doc_reason(text: str) -> Optional[str]:
|
||||
"""提取"因...已于"中间的离职原因,过滤非汉字(兼容 OCR 各种标点)。"""
|
||||
clean_text = re.sub(r"\s+", "", text)
|
||||
match = re.search(r"因(.*?)已于", clean_text)
|
||||
if not match:
|
||||
return None
|
||||
raw_content = match.group(1)
|
||||
reason = re.sub(r"[^\u4e00-\u9fff]", "", raw_content)
|
||||
return reason.strip() or None
|
||||
|
||||
|
||||
def longest_match_leave_type(doc_reason: str) -> Optional[str]:
|
||||
"""在离职类型展示文本列表做最长关键词匹配,返回命中的展示文本;无命中返回 None。"""
|
||||
if not doc_reason:
|
||||
return None
|
||||
norm = _norm_zh(doc_reason)
|
||||
for norm_opt, display in _LEAVE_TEXT_SORTED:
|
||||
if norm_opt and norm_opt in norm:
|
||||
return display
|
||||
return None
|
||||
|
||||
|
||||
def _extract_dates(text: str) -> List[date]:
|
||||
"""提取文本中所有日期,支持 XXXX年X月X日 / XXXX-XX-XX / XXXX/XX/XX 等格式。"""
|
||||
dates: List[date] = []
|
||||
patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in patterns:
|
||||
for m in re.finditer(pat, text):
|
||||
try:
|
||||
d = date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
continue
|
||||
if d not in dates:
|
||||
dates.append(d)
|
||||
return dates
|
||||
|
||||
|
||||
def _parse_form_date(value: str) -> Optional[date]:
|
||||
"""把表单里的离职日期字符串(YYYY-MM-DD)解析为 date。"""
|
||||
if not value:
|
||||
return None
|
||||
m = re.match(r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', str(value).strip())
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _find_by_name(pdf_paths: Dict[str, str], keyword: str) -> Optional[str]:
|
||||
"""按文件名关键字从 {文件名: 路径} 中找对应的本地路径。"""
|
||||
for name, path in pdf_paths.items():
|
||||
if keyword in name:
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def verify_resign_docs(pdf_paths: Dict[str, str], resign_info: Dict) -> Dict:
|
||||
"""
|
||||
核验下载的签章文书(解除确认书 / 报酬支付确认)与表单字段是否一致。
|
||||
|
||||
Args:
|
||||
pdf_paths: {文件名: 本地路径},download_contract_files 的返回
|
||||
resign_info: parse_resign_e_sign_form 结果(含离职日期/离职类型)
|
||||
|
||||
Returns:
|
||||
{
|
||||
"离职日期(表单)": str | None,
|
||||
"离职类型(表单)": str | None,
|
||||
"报酬支付确认日期": str | None, # 识别到的日期(ISO 逗号拼接)
|
||||
"解除确认书日期": str | None,
|
||||
"文书离职原因": str | None,
|
||||
"文书命中离职类型": str | None,
|
||||
"日期是否一致": True | False | None,
|
||||
"原因是否一致": True | False | None,
|
||||
"is_pass": bool, # 日期与原因均比对存在且一致
|
||||
"msg": str, # 可读的核验结论
|
||||
}
|
||||
"""
|
||||
form_date = _parse_form_date(resign_info.get("离职日期"))
|
||||
form_type = resign_info.get("离职类型")
|
||||
|
||||
result = {
|
||||
"离职日期(表单)": resign_info.get("离职日期"),
|
||||
"离职类型(表单)": form_type,
|
||||
"报酬支付确认日期": None,
|
||||
"解除确认书日期": None,
|
||||
"文书离职原因": None,
|
||||
"文书命中离职类型": None,
|
||||
"日期是否一致": None,
|
||||
"原因是否一致": None,
|
||||
"is_pass": False,
|
||||
"msg": "",
|
||||
}
|
||||
issues: List[str] = []
|
||||
|
||||
# ---- 日期核验:报酬支付确认 + 解除确认书 ----
|
||||
doc_dates: Dict[str, List[date]] = {}
|
||||
for keyword in ("报酬支付确认", "解除确认书"):
|
||||
path = _find_by_name(pdf_paths, keyword)
|
||||
if not path:
|
||||
issues.append(f"{keyword}文书缺失")
|
||||
continue
|
||||
try:
|
||||
dates = _extract_dates(parse_pdf(path))
|
||||
except Exception as e:
|
||||
logger.warning("解析%s失败: %s", keyword, e)
|
||||
issues.append(f"{keyword}解析失败({e})")
|
||||
continue
|
||||
result[f"{keyword}日期"] = ",".join(d.isoformat() for d in dates) or None
|
||||
doc_dates[keyword] = dates
|
||||
|
||||
if doc_dates:
|
||||
if form_date is not None:
|
||||
all_ok = True
|
||||
for keyword, dates in doc_dates.items():
|
||||
if form_date not in dates:
|
||||
all_ok = False
|
||||
issues.append(
|
||||
f"{keyword}日期[{result[f'{keyword}日期']}]≠表单离职日期[{form_date.isoformat()}]"
|
||||
)
|
||||
result["日期是否一致"] = all_ok
|
||||
else:
|
||||
issues.append("表单无离职日期,无法核验日期")
|
||||
else:
|
||||
issues.append("未获取到任何文书日期,无法核验日期")
|
||||
|
||||
# ---- 原因核验:解除确认书 ----
|
||||
relieve_path = _find_by_name(pdf_paths, "解除确认书")
|
||||
if relieve_path:
|
||||
try:
|
||||
reason = extract_doc_reason(parse_pdf(relieve_path))
|
||||
except Exception as e:
|
||||
logger.warning("解析解除确认书失败: %s", e)
|
||||
reason = None
|
||||
issues.append(f"解除确认书解析失败({e})")
|
||||
hit = longest_match_leave_type(reason)
|
||||
result["文书离职原因"] = reason
|
||||
result["文书命中离职类型"] = hit
|
||||
if hit and form_type:
|
||||
result["原因是否一致"] = (hit == form_type)
|
||||
if hit != form_type:
|
||||
issues.append(f"解除确认书原因[{hit}]≠表单离职类型[{form_type}]")
|
||||
elif not form_type:
|
||||
issues.append("表单无离职类型,无法核验原因")
|
||||
else:
|
||||
issues.append(f"解除确认书未命中任何离职类型(原因[{reason}])")
|
||||
|
||||
result["is_pass"] = result["日期是否一致"] is True and result["原因是否一致"] is True
|
||||
result["msg"] = ";".join(issues) if issues else "核验通过(日期与原因均与表单一致)"
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 简单自测入口
|
||||
demo_paths = {
|
||||
"解除确认书2026082711135530519.pdf": r"D:\资料\人资\离职电子签流程审核\附件\解除确认书.pdf",
|
||||
"报酬支付确认2026082711135388183.pdf": r"D:\资料\人资\离职电子签流程审核\附件\报酬支付确认.pdf",
|
||||
}
|
||||
demo_info = {"离职日期": "2026-07-31", "离职类型": "个人申请辞职"}
|
||||
print(verify_resign_docs(demo_paths, demo_info))
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 15:00
|
||||
@Description: 社保增减名单模块(导出员工异动名单)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,775 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change.employee_change_list
|
||||
@FileName: employee_change_list.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 14:55
|
||||
@Description: 社保增减名单模块:复用 OA 登录态,监听首页请求动态获取参数并导出员工异动名单(精简版)
|
||||
@Version: 2.4.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional, Tuple
|
||||
from urllib.parse import urljoin, urlparse, parse_qs
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
# HR 平台会话/请求封装(共享层,避免反向依赖 ehr)
|
||||
from app.service.hrbp.common.hr_session import (
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
HRSessionExpiredError,
|
||||
hr_request_json,
|
||||
)
|
||||
from app.service.hrbp.oa.common.config import BASE_URL
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
is_session_valid,
|
||||
load_cookies,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
try:
|
||||
import xlrd
|
||||
except ImportError:
|
||||
xlrd = None
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
from openpyxl.styles import PatternFill, Font, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError:
|
||||
_XlsxWorkbook = None
|
||||
PatternFill = None
|
||||
Font = None
|
||||
Alignment = None
|
||||
get_column_letter = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 常量 ----------
|
||||
HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619903d5"
|
||||
LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp"
|
||||
SEARCH_URL = f"{BASE_URL}/sys/search/search.do"
|
||||
MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do"
|
||||
|
||||
DEFAULT_FIXED_PARAMS = {
|
||||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||||
"canClose": "false",
|
||||
"isNew": "true",
|
||||
"j_aside": "false",
|
||||
"j_rIframe": "true",
|
||||
"j_iframe": "true",
|
||||
}
|
||||
|
||||
DEFAULT_EXPORT_COLUMNS = (
|
||||
"fd_38e9dd25e050e0;docCreator;fd_38d49cbc0ceeae;"
|
||||
"fd_390c6988e241ea;fd_390c639f265c78;fd_38e77e5cd6e9fe;"
|
||||
"fd_38d49cd67211e2;fd_38d49cd73eff02;fd_38deea220dc8c4;docStatus"
|
||||
)
|
||||
|
||||
# 员工停保申请台账的导出列(与参保表单字段不同)
|
||||
DEFAULT_EXPORT_COLUMNS_SUSPEND = (
|
||||
"fd_38d32213b2e9cc;fd_38d322164f42f2;fd_38e6887c2b3690;"
|
||||
"fd_3ec504d4c63e02;fd_38dad8035e33e4;fd_38e6887d6b0088;"
|
||||
"fd_38d32227f7a496;fd_38dee9ae569d6a;fd_38e687e91f4fc6;"
|
||||
"fd_38e687eb56dc4c;docStatus;docPublishTime"
|
||||
)
|
||||
|
||||
# 参保 / 停保 两个菜单名,对应的 searchId 不同,由 get_search_id_from_menu 动态获取
|
||||
MENU_NAME_PARTICIPATE = "员工参保申请"
|
||||
MENU_NAME_SUSPEND = "员工停保申请"
|
||||
|
||||
# 参保 / 停保 两个台账的查询筛选字段下标不同(参保为 2,停保为 3)
|
||||
FILTER_IDX_PARTICIPATE = "2"
|
||||
FILTER_IDX_SUSPEND = "3"
|
||||
|
||||
# ---------- HR 参保记录核对(si_main 接口,对应 aa.md) ----------
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
# HR cookies 由 hrbp/common 共享层管理(login.py 保存、build_hr_session 读取)
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
|
||||
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
|
||||
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
|
||||
"postStruId": "1", "regist_property": "", "identity": "",
|
||||
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
|
||||
"siName": "", "belongUnitId": "", "belongUnitName": "",
|
||||
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
SI_RESULT_COL = "社保记录查询结果"
|
||||
SI_BATCH_SIZE = 15
|
||||
|
||||
|
||||
def _resolve_query_date(query_date: Optional[str] = None) -> str:
|
||||
"""返回查询起始日期:手动传入则用传入值,否则用当前月份第一天。"""
|
||||
if query_date:
|
||||
return query_date
|
||||
return datetime.now().strftime("%Y-%m-01")
|
||||
|
||||
|
||||
def _build_filter_params(filter_idx: str, query_date: Optional[str] = None) -> Dict:
|
||||
"""构造查询筛选参数,如 {v0_2: gt, v1_2: 2026-08-01}。"""
|
||||
day = _resolve_query_date(query_date)
|
||||
return {f"v0_{filter_idx}": "gt", f"v1_{filter_idx}": day}
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 会话获取与登录
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
return oa_login()
|
||||
|
||||
|
||||
def get_session(subject: str = "社保") -> Tuple[Optional[ChromiumPage], SessionPage]:
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录(无需启动浏览器)")
|
||||
if hasattr(saved_session, 'session'):
|
||||
saved_session.session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
|
||||
"Referer": LIST_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||||
})
|
||||
return None, saved_session
|
||||
|
||||
logger.info("无可用会话,执行完整登录")
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
if hasattr(session, 'session'):
|
||||
session.session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Referer": LIST_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||||
})
|
||||
return browser, session
|
||||
|
||||
|
||||
def _check_response(resp, action: str) -> None:
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{action}失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{action}失败,状态码: {resp.status_code}")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 动态提取 fdId(监听浏览器网络请求)
|
||||
# ----------------------------------------------
|
||||
def _get_cookies_with_domain(session: SessionPage) -> list:
|
||||
cookies = []
|
||||
try:
|
||||
raw = session.session.cookies
|
||||
for c in raw:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
})
|
||||
except Exception as e:
|
||||
logger.debug("从底层会话提取 cookies 失败: %s", e)
|
||||
if not cookies:
|
||||
try:
|
||||
cookies = load_cookies(COOKIE_FILE) or []
|
||||
except Exception as e:
|
||||
logger.debug("从本地 cookie 文件读取失败: %s", e)
|
||||
return cookies
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session: SessionPage, browser: Optional[ChromiumPage] = None) -> str:
|
||||
# 优先复用外部传入的浏览器;仅在没有可用浏览器时才自行创建(如复用已保存会话的场景)。
|
||||
# 复用场景下 get_session 已用轻量接口 is_session_valid 校验过会话,无需在此重复校验
|
||||
own_browser = browser is None
|
||||
if own_browser:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||||
|
||||
co = ChromiumOptions()
|
||||
# 如需 Edge 浏览器,请取消注释并设置路径
|
||||
# co.set_browser_path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
|
||||
browser = ChromiumPage(co)
|
||||
browser.set.cookies(cookies)
|
||||
|
||||
try:
|
||||
browser.listen.start()
|
||||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
|
||||
# 兜底:轻量接口校验通过后,若新浏览器 cookies 提取不全仍可能停在登录页,快速失败避免空等
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
|
||||
deadline = time.time() + 10
|
||||
target_request = None
|
||||
while time.time() < deadline:
|
||||
req = browser.listen.wait(timeout=1)
|
||||
if req and 'sysPortalNav.do' in req.url:
|
||||
target_request = req
|
||||
break
|
||||
if target_request is None:
|
||||
raise RuntimeError("超时未监听到菜单请求,请检查网络或登录态")
|
||||
|
||||
url = target_request.url
|
||||
logger.debug("监听到菜单请求: %s", url)
|
||||
qs = parse_qs(urlparse(url).query)
|
||||
fd_id = qs.get('fdId', [None])[0]
|
||||
if not fd_id:
|
||||
raise RuntimeError("菜单请求中未包含 fdId")
|
||||
logger.info("动态获取到 fdId: %s", fd_id)
|
||||
return fd_id
|
||||
finally:
|
||||
browser.listen.stop()
|
||||
if own_browser:
|
||||
browser.quit()
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 从菜单 JSON 获取 searchId
|
||||
# ----------------------------------------------
|
||||
def get_search_id_from_menu(session: SessionPage, fd_id: str,
|
||||
menu_name: str = MENU_NAME_PARTICIPATE) -> str:
|
||||
params = {
|
||||
"method": "portlet",
|
||||
"fdId": fd_id,
|
||||
"f_s": "sourcejs",
|
||||
"t": str(int(time.time() * 1000))
|
||||
}
|
||||
session.get(f"{BASE_URL}{MENU_API_PATH}", params=params)
|
||||
_check_response(session.response, "获取菜单")
|
||||
data = session.response.json()
|
||||
|
||||
def find_item(items):
|
||||
for item in items:
|
||||
if item.get("text") == menu_name:
|
||||
return item
|
||||
if "children" in item:
|
||||
found = find_item(item["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
items = data if isinstance(data, list) else data.get("children", [])
|
||||
item = find_item(items)
|
||||
if not item:
|
||||
raise RuntimeError(f"菜单中未找到 '{menu_name}'")
|
||||
href = item["href"]
|
||||
full_url = urljoin(BASE_URL, href)
|
||||
qs = parse_qs(urlparse(full_url).query)
|
||||
search_id = qs.get("searchId", [None])[0]
|
||||
if not search_id:
|
||||
raise RuntimeError("菜单链接中未包含 searchId")
|
||||
logger.info("从菜单获取到 searchId: %s", search_id)
|
||||
return search_id
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 获取总条数(通过 result 接口)
|
||||
# ----------------------------------------------
|
||||
def get_total_count(session: SessionPage, base_params: Dict, search_id: str, timestamp: str) -> int:
|
||||
"""
|
||||
请求 result 接口,从返回的 HTML 中提取总条数。
|
||||
支持多种格式:exportNum、"总记录数"、"共X条"
|
||||
"""
|
||||
params = {
|
||||
"method": "result",
|
||||
"searchId": search_id,
|
||||
"j_timestamp": timestamp,
|
||||
**base_params
|
||||
}
|
||||
session.get(SEARCH_URL, params=params, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "查询总数")
|
||||
html = session.response.text
|
||||
|
||||
# 1. 优先从 exportNum 提取
|
||||
num_match = re.search(r'exportNum:\s*"(\d+)"', html)
|
||||
if num_match:
|
||||
total = int(num_match.group(1))
|
||||
logger.info("从 exportNum 获取到总记录数: %d", total)
|
||||
return total
|
||||
|
||||
# 2. 备选:从 "总记录数:数字" 提取
|
||||
total_match = re.search(r'总记录数[::]\s*(\d+)', html)
|
||||
if total_match:
|
||||
total = int(total_match.group(1))
|
||||
logger.info("从 '总记录数' 获取到总记录数: %d", total)
|
||||
return total
|
||||
|
||||
# 3. 再尝试从 "共 X 条" 提取(你贴出的HTML中正是这种格式)
|
||||
fallback_match = re.search(r'共\s*(\d+)\s*条', html)
|
||||
if fallback_match:
|
||||
total = int(fallback_match.group(1))
|
||||
logger.info("从 '共X条' 获取到总记录数: %d", total)
|
||||
return total
|
||||
|
||||
logger.warning("未找到总条数,默认为 0")
|
||||
return 0
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 导出数据(直接 POST)
|
||||
# ----------------------------------------------
|
||||
def export_all_data(session: SessionPage, base_params: Dict, total: int, columns: str,
|
||||
search_id: str, timestamp: str) -> bytes:
|
||||
data = {
|
||||
"method": "exportResult",
|
||||
"searchId": search_id,
|
||||
"j_timestamp": timestamp,
|
||||
**base_params,
|
||||
"fdColumns": columns,
|
||||
"fdNum": str(total),
|
||||
"fdNumStart": "1",
|
||||
"fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true",
|
||||
"checkIdValues": "",
|
||||
}
|
||||
session.post(SEARCH_URL, data=data, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "导出数据")
|
||||
return session.response.content
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5.5 按工号去重清洗(去掉『废弃』,每工号保留最新申请日期)
|
||||
# ----------------------------------------------
|
||||
def _normalize_date_key(value) -> float:
|
||||
"""将『申请日期』单元格归一化为可比较的数值键(Excel 序列号或日期天数)。"""
|
||||
if value is None:
|
||||
return 0.0
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
if isinstance(value, str):
|
||||
m = re.match(r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})", value.strip())
|
||||
if m:
|
||||
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
try:
|
||||
return (datetime(y, mo, d) - datetime(1899, 12, 30)).days
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _date_display(value, wb):
|
||||
"""把 Excel 日期序列号转成可读字符串:整天只显示日期,带时间则显示到秒。"""
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
dt = xlrd.xldate_as_datetime(float(value), wb.datemode)
|
||||
except Exception:
|
||||
return value
|
||||
if float(value).is_integer():
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return value
|
||||
|
||||
|
||||
def _read_and_clean(xls_path: str):
|
||||
"""读取 .xls:去掉『废弃』,按工号去重(每工号保留最新申请日期)。
|
||||
|
||||
返回 (headers, rows, emp_col),rows 中工号已统一为字符串、申请日期已格式化为文本。
|
||||
"""
|
||||
if xlrd is None:
|
||||
raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls")
|
||||
|
||||
wb = xlrd.open_workbook(xls_path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
|
||||
def find_col(keyword):
|
||||
for i, h in enumerate(headers):
|
||||
if keyword in h:
|
||||
return i
|
||||
return None
|
||||
|
||||
emp_col = find_col("工号")
|
||||
date_col = find_col("申请日期")
|
||||
status_col = find_col("文档状态")
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
# 1) 过滤:去掉『废弃』,且工号非空;所有日期列统一转成可读文本
|
||||
rows = []
|
||||
for r in range(1, sh.nrows):
|
||||
row = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if sh.cell_type(r, c) == xlrd.XL_CELL_DATE:
|
||||
v = _date_display(v, wb)
|
||||
row.append(v)
|
||||
emp = str(row[emp_col]).strip()
|
||||
if not emp:
|
||||
continue
|
||||
if status_col is not None and str(row[status_col]).strip() == "废弃":
|
||||
continue
|
||||
row[emp_col] = emp
|
||||
rows.append(row)
|
||||
|
||||
# 2) 去重:按工号保留申请日期最新的一条,保持首次出现顺序
|
||||
latest = {}
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
key = _normalize_date_key(row[date_col]) if date_col is not None else 0.0
|
||||
if emp not in latest or key > latest[emp][0]:
|
||||
latest[emp] = (key, row)
|
||||
|
||||
ordered = []
|
||||
seen = set()
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
if emp not in seen:
|
||||
seen.add(emp)
|
||||
ordered.append(latest[emp][1])
|
||||
|
||||
logger.info("清洗完成:去掉废弃后 %d 条,去重后 %d 条", len(rows), len(ordered))
|
||||
return headers, ordered, emp_col
|
||||
|
||||
|
||||
def clean_employee_change_file(xls_path: str, output_dir: str = ".") -> str:
|
||||
"""按工号去重清洗导出的名单,写出清洗后的 .xlsx(兼容旧入口)。"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法执行去重清洗,请先安装")
|
||||
headers, rows, _ = _read_and_clean(xls_path)
|
||||
out_name = f"{os.path.splitext(os.path.basename(xls_path))[0]}_去重.xlsx"
|
||||
out_path = os.path.abspath(os.path.join(output_dir, out_name))
|
||||
out_wb = _XlsxWorkbook()
|
||||
ws = out_wb.active
|
||||
ws.append(headers)
|
||||
for row in rows:
|
||||
ws.append(row)
|
||||
out_wb.save(out_path)
|
||||
logger.info("清洗结果保存为:%s", out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5.6 HR 参保记录核对(调用 si_main 接口,追加结果列)
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _si_query_batch(session, codes_batch):
|
||||
"""查询一批工号(≤15个),返回响应 JSON。"""
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15)
|
||||
|
||||
|
||||
def _si_found_codes(response_json):
|
||||
"""从返回 JSON 中提取所有 base_Code 工号。"""
|
||||
datas = response_json.get("datas") or []
|
||||
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
|
||||
|
||||
|
||||
def _si_check_batch(session, codes_batch) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;查询失败上抛,由调用方决定重登或标注异常。"""
|
||||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||||
|
||||
|
||||
def _si_preflight(session):
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期/异常则重新登录并重建会话。"""
|
||||
try:
|
||||
_si_query_batch(session, ["0"])
|
||||
except HRSessionExpiredError as e:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录: %s", e)
|
||||
return refresh_hr_session()
|
||||
except Exception as e:
|
||||
# 网络超时也可能由 cookies 过期(重定向到登录页后加载超时)引发,先重登重建会话再试
|
||||
logger.warning("预检查询异常,尝试重新登录后重试: %s", e)
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".", session=None) -> str:
|
||||
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。
|
||||
|
||||
session 由调用方预检后传入(复用,避免重复探测);为 None 时内部自行预检。
|
||||
"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
|
||||
|
||||
# 按工号去重(保持首次出现顺序),再逐批查询
|
||||
unique_codes, seen = [], set()
|
||||
for row in rows:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code and code not in seen:
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
if session is None:
|
||||
session = _si_preflight(build_hr_session(auto_login=False))
|
||||
found = set()
|
||||
failed_codes = set()
|
||||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||||
try:
|
||||
found |= _si_check_batch(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
session = refresh_hr_session()
|
||||
try:
|
||||
found |= _si_check_batch(session, batch)
|
||||
except Exception as e:
|
||||
logger.warning("重登后该批仍查询失败,标注为查询异常: %s", e)
|
||||
failed_codes |= set(batch)
|
||||
except Exception as e:
|
||||
# 网络超时/其它异常:宁可标注查询异常,也不当作『无记录』避免误判
|
||||
logger.warning("参保记录查询失败(该批标注查询异常,需人工复核): %s", e)
|
||||
failed_codes |= set(batch)
|
||||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3)
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in rows:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code in failed_codes:
|
||||
val = "异常:参保记录查询失败,需人工复核"
|
||||
else:
|
||||
has_record = code in found
|
||||
if is_participate:
|
||||
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
|
||||
else:
|
||||
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
|
||||
new_rows.append(row + [val])
|
||||
|
||||
out_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{base_name}_参保核对.xlsx"))
|
||||
out_wb = _XlsxWorkbook()
|
||||
|
||||
# 异常行标红 + 结果列加粗红字(便于数据多时一眼定位)
|
||||
red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") if PatternFill else None
|
||||
red_font = Font(color="9C0006", bold=True) if Font else None
|
||||
head_fill = PatternFill(start_color="DDEBF7", end_color="DDEBF7", fill_type="solid") if PatternFill else None
|
||||
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = "核对明细"
|
||||
out_ws.append(headers + [SI_RESULT_COL])
|
||||
for c in range(1, len(headers) + 2):
|
||||
cell = out_ws.cell(1, c)
|
||||
cell.fill = head_fill
|
||||
cell.font = Font(bold=True) if Font else None
|
||||
cell.alignment = Alignment(horizontal="center") if Alignment else None
|
||||
for idx, row in enumerate(new_rows, start=2):
|
||||
out_ws.append(row)
|
||||
if str(row[-1]).startswith("异常"):
|
||||
for c in range(1, len(row) + 1):
|
||||
cell = out_ws.cell(idx, c)
|
||||
cell.fill = red_fill
|
||||
if c == len(row):
|
||||
cell.font = red_font
|
||||
out_ws.freeze_panes = "A2"
|
||||
out_ws.auto_filter.ref = out_ws.dimensions
|
||||
if get_column_letter:
|
||||
for c in range(1, len(headers) + 2):
|
||||
out_ws.column_dimensions[get_column_letter(c)].width = 20
|
||||
|
||||
out_wb.save(out_path)
|
||||
|
||||
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
|
||||
logger.info("参保核对完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
|
||||
len(unique_codes), len(found), len(abnormal), out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
def annotate_si_result(xls_path: str, mode: str, output_dir: str = ".") -> str:
|
||||
"""读取原始 .xls → 清洗去重 → 查 HR 参保记录 → 追加结果列,导出一份最终文件(无中间表)。
|
||||
|
||||
mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常)
|
||||
"""
|
||||
headers, rows, emp_col = _read_and_clean(xls_path)
|
||||
return _write_annotated(headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(xls_path))[0], output_dir)
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 6. 主流程(精简版)
|
||||
# ----------------------------------------------
|
||||
def export_employee_change_list(
|
||||
filter_params: Optional[Dict] = None,
|
||||
columns: str = DEFAULT_EXPORT_COLUMNS,
|
||||
output_dir: str = ".",
|
||||
menu_name: str = MENU_NAME_PARTICIPATE,
|
||||
filter_idx: str = FILTER_IDX_PARTICIPATE,
|
||||
query_date: Optional[str] = None,
|
||||
) -> str:
|
||||
setup_logging()
|
||||
logger.info("社保增减名单导出流程开始(精简版),菜单:%s", menu_name)
|
||||
|
||||
if filter_params is None:
|
||||
filter_params = _build_filter_params(filter_idx, query_date)
|
||||
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **filter_params}
|
||||
|
||||
# 操作前预检 HR 登录态(核对必用),失效则自动重登,避免 OA 导出完成后才发现 HR 不可用
|
||||
hr_session = _si_preflight(build_hr_session(auto_login=False))
|
||||
|
||||
# 登录态失效时自动删除 cookie、重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session = get_session()
|
||||
|
||||
try:
|
||||
# 1. 动态获取 fdId(复用登录浏览器,避免重复创建导致浏览器被提前关闭)
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
|
||||
# 2. 从菜单获取 searchId
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
|
||||
# 3. 生成一个固定的时间戳(毫秒)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
logger.info("使用时间戳: %s", timestamp)
|
||||
|
||||
# 4. 查询获取总条数
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
# 5. 导出数据
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
file_content = export_all_data(session, base_params, total, columns,
|
||||
search_id, timestamp)
|
||||
|
||||
output_filename = f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"
|
||||
output_path = os.path.abspath(os.path.join(output_dir, output_filename))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(file_content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
# 6. 读取原始表并内存清洗(去『废弃』+按工号去重),不落中间表
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
|
||||
# 7. 调用 HR 参保记录接口核对,追加『社保记录查询结果』列(一次性完成)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir,
|
||||
session=hr_session)
|
||||
|
||||
# 8. 清理中间原始导出文件,只保留最终标注表
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if browser is not None:
|
||||
save_browser_cookies(browser)
|
||||
return final_path
|
||||
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e, exc_info=True)
|
||||
is_login_fail = "登录" in str(e) or "cookie" in str(e).lower()
|
||||
if is_login_fail and login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("检测到登录态失效,已删除 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(
|
||||
filter_params: Optional[Dict] = None,
|
||||
columns: str = DEFAULT_EXPORT_COLUMNS,
|
||||
output_dir: str = ".",
|
||||
query_date: Optional[str] = None,
|
||||
) -> str:
|
||||
"""导出员工参保申请名单。"""
|
||||
return export_employee_change_list(
|
||||
filter_params=filter_params,
|
||||
columns=columns,
|
||||
output_dir=output_dir,
|
||||
menu_name=MENU_NAME_PARTICIPATE,
|
||||
filter_idx=FILTER_IDX_PARTICIPATE,
|
||||
query_date=query_date,
|
||||
)
|
||||
|
||||
|
||||
def export_suspension(
|
||||
filter_params: Optional[Dict] = None,
|
||||
columns: str = DEFAULT_EXPORT_COLUMNS_SUSPEND,
|
||||
output_dir: str = ".",
|
||||
query_date: Optional[str] = None,
|
||||
) -> str:
|
||||
"""导出员工停保申请名单。"""
|
||||
return export_employee_change_list(
|
||||
filter_params=filter_params,
|
||||
columns=columns,
|
||||
output_dir=output_dir,
|
||||
menu_name=MENU_NAME_SUSPEND,
|
||||
filter_idx=FILTER_IDX_SUSPEND,
|
||||
query_date=query_date,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = sys.argv[1:]
|
||||
change_type = "全部"
|
||||
query_date = None
|
||||
for a in args:
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2}$", a):
|
||||
query_date = a
|
||||
elif a in ("参保", "participate", "participation"):
|
||||
change_type = "参保"
|
||||
elif a in ("停保", "suspend", "suspension"):
|
||||
change_type = "停保"
|
||||
|
||||
if change_type == "参保":
|
||||
export_participation(query_date=query_date)
|
||||
elif change_type == "停保":
|
||||
export_suspension(query_date=query_date)
|
||||
else:
|
||||
# 默认(含 "全部"/"都要"/无参数):参保 + 停保 都导出
|
||||
export_participation(query_date=query_date)
|
||||
export_suspension(query_date=query_date)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,265 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change.si_insurance_check
|
||||
@FileName: si_insurance_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 15:20
|
||||
@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口,
|
||||
判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。
|
||||
@Version: 2.1.0
|
||||
|
||||
业务判定(对应 aa.md):
|
||||
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
|
||||
- 停保申请表:某工号在 HR 参保记录中「无返回数据」→ 已停保,属异常。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
# HR 平台会话/请求封装(共享层,避免反向依赖 ehr)
|
||||
from app.service.hrbp.common.hr_session import (
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
HRSessionExpiredError,
|
||||
hr_request_json,
|
||||
)
|
||||
|
||||
try:
|
||||
import xlrd
|
||||
except ImportError:
|
||||
xlrd = None
|
||||
|
||||
try:
|
||||
from openpyxl import load_workbook as _load_workbook
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
except ImportError:
|
||||
_load_workbook = None
|
||||
_XlsxWorkbook = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# HR 参保记录查询接口(aa.md 提供的 si_main 接口)
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
|
||||
# 接口基础参数(aa.md 基础参数模板,base_codes 动态替换)
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
|
||||
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
|
||||
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
|
||||
"postStruId": "1", "regist_property": "", "identity": "",
|
||||
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
|
||||
"siName": "", "belongUnitId": "", "belongUnitName": "",
|
||||
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
|
||||
RESULT_COL = "社保记录查询结果"
|
||||
BATCH_SIZE = 15
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 查询参保记录接口
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def query_batch(session, codes_batch: List[str]):
|
||||
"""查询一批工号(≤15个),返回响应 JSON。"""
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15)
|
||||
|
||||
|
||||
def extract_found_codes(response_json) -> set:
|
||||
"""从返回 JSON 中提取所有 base_Code 工号。"""
|
||||
datas = response_json.get("datas") or []
|
||||
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
|
||||
|
||||
|
||||
def check_codes(session, codes_batch: List[str]) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。"""
|
||||
try:
|
||||
return extract_found_codes(query_batch(session, codes_batch))
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def preflight(session) -> "requests.Session":
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
query_batch(session, ["0"])
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 读取表格(支持 .xlsx / .xls)
|
||||
# ----------------------------------------------
|
||||
def read_table(path: str) -> Tuple[List[str], List[list]]:
|
||||
"""读取表格,返回 (表头, 数据行)。"""
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
if ext == ".xlsx":
|
||||
if _load_workbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法读取 .xlsx")
|
||||
ws = _load_workbook(path).active
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
headers = [str(h) if h is not None else "" for h in rows[0]]
|
||||
data = [list(r) for r in rows[1:]]
|
||||
elif ext == ".xls":
|
||||
if xlrd is None:
|
||||
raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls")
|
||||
sh = xlrd.open_workbook(path).sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
data = [[sh.cell_value(r, c) for c in range(sh.ncols)] for r in range(1, sh.nrows)]
|
||||
else:
|
||||
raise ValueError(f"不支持的文件格式:{ext},请提供 .xlsx 或 .xls")
|
||||
return headers, data
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 核对并追加结果列
|
||||
# ----------------------------------------------
|
||||
def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str:
|
||||
"""读表 → 按工号去重 → 逐批查接口 → 追加结果列 → 导出 .xlsx。
|
||||
|
||||
mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常)
|
||||
"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
|
||||
|
||||
headers, data = read_table(table_path)
|
||||
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
# 按工号去重(保持首次出现顺序),再逐批查询
|
||||
unique_codes = []
|
||||
seen = set()
|
||||
for row in data:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code and code not in seen:
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
session = preflight(build_hr_session(auto_login=False))
|
||||
found = set()
|
||||
for i in range(0, len(unique_codes), BATCH_SIZE):
|
||||
batch = unique_codes[i:i + BATCH_SIZE]
|
||||
try:
|
||||
found |= check_codes(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
session = refresh_hr_session()
|
||||
found |= check_codes(session, batch)
|
||||
logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3) # 轻微限速,避免触发风控
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in data:
|
||||
code = str(row[emp_col]).strip()
|
||||
has_record = code in found
|
||||
if is_participate:
|
||||
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
|
||||
else:
|
||||
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
|
||||
new_rows.append(row + [val])
|
||||
|
||||
out_path = os.path.abspath(os.path.join(
|
||||
output_dir,
|
||||
f"{os.path.splitext(os.path.basename(table_path))[0]}_参保核对.xlsx",
|
||||
))
|
||||
out_wb = _XlsxWorkbook()
|
||||
ws = out_wb.active
|
||||
ws.append(headers + [RESULT_COL])
|
||||
for row in new_rows:
|
||||
ws.append(row)
|
||||
out_wb.save(out_path)
|
||||
|
||||
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
|
||||
logger.info("完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
|
||||
len(unique_codes), len(found), len(abnormal), out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def check_participation(table_path: str, output_dir: str = ".") -> str:
|
||||
return check_and_annotate(table_path, "participation", output_dir)
|
||||
|
||||
|
||||
def check_suspension(table_path: str, output_dir: str = ".") -> str:
|
||||
return check_and_annotate(table_path, "suspension", output_dir)
|
||||
|
||||
|
||||
def _latest_cleaned(project: str, keyword: str) -> str:
|
||||
"""在项目目录里找最新(按修改时间)的、文件名含关键字且以 _去重.xlsx 结尾的表。"""
|
||||
matches = [
|
||||
p for p in Path(project).glob("*.xlsx")
|
||||
if keyword in p.name and p.name.endswith("_去重.xlsx")
|
||||
]
|
||||
if not matches:
|
||||
return ""
|
||||
return str(max(matches, key=lambda p: p.stat().st_mtime))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
project = _root
|
||||
|
||||
def pick(keyword):
|
||||
# 优先命令行显式指定,否则自动找最新清洗表
|
||||
for a in args:
|
||||
if keyword in Path(a).name:
|
||||
return a
|
||||
return _latest_cleaned(project, keyword)
|
||||
|
||||
participate = pick("参保")
|
||||
suspend = pick("停保")
|
||||
|
||||
if participate and os.path.exists(participate):
|
||||
check_participation(participate, project)
|
||||
else:
|
||||
logger.warning("未找到参保清洗表(*参保*_去重.xlsx)")
|
||||
|
||||
if suspend and os.path.exists(suspend):
|
||||
check_suspension(suspend, project)
|
||||
else:
|
||||
logger.warning("未找到停保清洗表(*停保*_去重.xlsx)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_notice
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发模块(读取参保/停保名单 → 按模板批量生成 Word 告知书并转 PDF)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,824 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_notice
|
||||
@FileName: notice_mail_merge.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发 —— 参保/停保名单 → 按模板生成告知书(Word + PDF)
|
||||
读取《{YYYYMM}参保与停保名单.xlsx》中「参保名单」sheet(表头第3行),
|
||||
按三类模板规则筛选当月人员,逐人生成 Word 告知书并转 PDF:
|
||||
- 模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
|
||||
- 模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
|
||||
- 模板3 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
|
||||
公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月。
|
||||
输出命名:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份,
|
||||
文件名 = 二级部门_四级部门_告知书类型.docx/pdf,同一部门内多人逐页排列。
|
||||
OA 工作沟通推送:根据命中员工工号查询店长/人事,构造 2 条推送数据
|
||||
(员工参与社会保险+参保异常合并一条、社保转移单独一条)。
|
||||
占位符约定:模板中仅允许纯变量占位符(如 {{姓名}}、{{下月}}、{{一次性扣款}}),
|
||||
不支持 {{当前月+1}} / {{费用*2}} 这类带表达式的写法(脚本会自动兼容旧写法)。
|
||||
PDF 转换:走 WPS 文字 COM(Kwps.Application),兼容未安装 MS Word 的环境。
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
# 保证无论以何种方式(直接运行 / IDE / 模块方式)运行都能导入 app 包:
|
||||
# 从脚本位置向上定位到项目根目录并注入 sys.path。
|
||||
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
|
||||
import openpyxl
|
||||
from docx import Document
|
||||
from docx.enum.text import WD_BREAK
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
DEFAULT_ROSTER_PATH,
|
||||
find_hr_personnel_batch,
|
||||
find_store_manager_batch,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("notice_mail_merge")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 配置区(按需修改,禁止命令行传参)
|
||||
# ------------------------------------------------------------------
|
||||
BASE_DIR = r"D:\资料\人资\告知书制作与下发"
|
||||
OUTPUT_ROOT = os.path.join(BASE_DIR, "输出") # 输出根目录(按月分子目录)
|
||||
|
||||
# 模板清单:folder=输出子目录名;status/type=该类告知书的办理状态与参保类型过滤条件
|
||||
TEMPLATES = {
|
||||
"新参保": {
|
||||
"file": os.path.join(BASE_DIR, "参保状态告知", "员工参与社会保险告知书模板.docx"),
|
||||
"folder": "员工参与社会保险告知书",
|
||||
"status": "已参",
|
||||
"type": "新参保",
|
||||
},
|
||||
"参保异常": {
|
||||
"file": os.path.join(BASE_DIR, "参保状态告知", "参保异常告知模板.docx"),
|
||||
"folder": "参保异常告知书",
|
||||
"status": "参保失败",
|
||||
"type": "新参保",
|
||||
},
|
||||
"社保转移": {
|
||||
"file": os.path.join(BASE_DIR, "社保转移告知书", "社保转移告知模板.docx"),
|
||||
"folder": "社保转移告知书",
|
||||
"status": "已参",
|
||||
"type": "转移参保",
|
||||
},
|
||||
}
|
||||
|
||||
EXCEL_KEYWORD = "参保与停保名单" # 表格文件名关键字
|
||||
SHEET_KEYWORD = "参保名单" # sheet 名关键字
|
||||
HEADER_ROW = 3 # 表头所在行
|
||||
MAIN_COLS = 49 # 主表字段到「费用」列为止(AX 为空列,其后为粘贴重复区)
|
||||
EXCLUDE_TYPE_KEYWORDS = ("职能",) # 人员类型排除关键字
|
||||
DEPT_KEYWORDS = ("经营中心", "石桥铺会馆") # 二级部门需包含的关键字(任一命中即可)
|
||||
RETRY_TIMES = 3 # 全局重试次数(AGENTS.md:最大重试3次)
|
||||
|
||||
# 社保转移数据源(社保变更人员名单):替代「参保与停保名单」中的转移参保
|
||||
TRANSFER_EXCEL_KEYWORD = "社保变更人员名单" # 数据源文件名关键字
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
|
||||
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
|
||||
TRANSFER_CHANGE_COL = "是否变更" # 筛选列
|
||||
TRANSFER_CHANGE_VALUE = "是" # 筛选值
|
||||
# 列名映射:社保变更名单列名 -> 标准列名(模板占位符依赖标准列名)
|
||||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||||
|
||||
# ---- OA 工作沟通推送数据构造 ----
|
||||
# 二级部门 -> 固定人事工号(与 roster_query.DEPT2_HR_OVERRIDE 保持一致,石桥铺会馆不查花名册)
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]}
|
||||
|
||||
# 工作沟通推送配置:rule_keys=参与该条推送的模板名;subject/content 支持 {y}/{m} 动态月份替换
|
||||
OA_MESSAGE_TEMPLATES = (
|
||||
{
|
||||
"key": "参保类",
|
||||
"rule_keys": ("新参保", "参保异常"),
|
||||
"subject": "{y}年{m}月员工参保结果告知书",
|
||||
"content": (
|
||||
"各位店长、人行伙伴:\n"
|
||||
"重庆区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,\n"
|
||||
"现需涉及的门店对员工本人进行传达告知(下载并签收);其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
|
||||
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报表至人资周卫,以便下月再参;\n"
|
||||
"请门店在{m}月26日前完成签署并将《签收回执》传递人行,"
|
||||
"人行跟进本经营中心所有人员的告知书回收,{m}月28日前传递人资周卫。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"key": "社保转移",
|
||||
"rule_keys": ("社保转移",),
|
||||
"subject": "{y}年{m}月员工参保单位变更确认",
|
||||
"content": (
|
||||
"各位领导/同事:\n"
|
||||
"根据《社保执行细则》,本月人力资源部已输出“工作与参保单位不一致”的人员,"
|
||||
"现需要涉及门店/经营中心与员工本人进行转移确认(下载变更告知书、打印并与员工清晰讲解),"
|
||||
"在{m}月25日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月27日内传递人资周卫处。\n"
|
||||
"特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。"
|
||||
"员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
)
|
||||
|
||||
# 正文关键词高亮(红色):keyword 支持 {m} 月份占位符,format 后替换为 <span style="color:#c0392b">
|
||||
OA_HIGHLIGHTS = {
|
||||
"参保类": [
|
||||
("《参保成功告知书》", "#c0392b"),
|
||||
("《参保异常告知书》", "#c0392b"),
|
||||
("《签收回执》", "#c0392b"),
|
||||
("{m}月26日前", "#c0392b"),
|
||||
("{m}月28日前", "#c0392b"),
|
||||
],
|
||||
"社保转移": [
|
||||
("《社保缴纳确认单》", "#c0392b"),
|
||||
("{m}月25日下班前", "#c0392b"),
|
||||
("27日内", "#c0392b"),
|
||||
("特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。", "#c0392b"),
|
||||
],
|
||||
}
|
||||
|
||||
# 旧占位符 → 新占位符(模板兼容旧写法,自动归一化)
|
||||
LEGACY_PLACEHOLDERS = {
|
||||
"{{当前月15日}}": "{{当月15日}}",
|
||||
"{{重庆}}": "{{区域}}",
|
||||
"{{当前月+1}}": "{{下月}}",
|
||||
"{{费用*2}}": "{{一次性扣款}}",
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 基础工具
|
||||
# ------------------------------------------------------------------
|
||||
def _fmt_num(value) -> str:
|
||||
"""金额格式化:509 -> '509';467.42 -> '467.42';#N/A 等错误值返回 ''。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
if s in ("", "#N/A", "#REF!", "#VALUE!", "NA", "None"):
|
||||
return ""
|
||||
try:
|
||||
f = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return s
|
||||
if f == int(f):
|
||||
return str(int(f))
|
||||
return ("%.2f" % f).rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def _month_of(value):
|
||||
"""把单元格值解析为 (年, 月);无法解析返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return (value.year, value.month)
|
||||
if isinstance(value, str):
|
||||
m = re.search(r"(20\d{2})[年\-/\.]?(\d{1,2})", value.strip())
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)))
|
||||
return None
|
||||
|
||||
|
||||
def _extract_ym(filename: str):
|
||||
"""从文件名解析 YYYYMM;失败返回当月。"""
|
||||
m = re.search(r"(20\d{2})(\d{2})", filename)
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)))
|
||||
now = datetime.now()
|
||||
return (now.year, now.month)
|
||||
|
||||
|
||||
def _find_excel(dir_path: str) -> str:
|
||||
"""在目录内查找包含「参保与停保名单」的 xlsx 文件。"""
|
||||
for name in os.listdir(dir_path):
|
||||
if EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||||
return os.path.join(dir_path, name)
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{EXCEL_KEYWORD}」的 xlsx 文件")
|
||||
|
||||
|
||||
def _find_transfer_excel(dir_path: str = None) -> str:
|
||||
"""在目录内查找包含「社保变更人员名单」的 xlsx 文件(社保转移数据源)。"""
|
||||
dir_path = dir_path or BASE_DIR
|
||||
if not os.path.isdir(dir_path):
|
||||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||||
for name in os.listdir(dir_path):
|
||||
if TRANSFER_EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||||
return os.path.join(dir_path, name)
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{TRANSFER_EXCEL_KEYWORD}」的 xlsx 文件")
|
||||
|
||||
|
||||
def _read_insurance_records(excel_path: str) -> list:
|
||||
"""读取「参保名单」sheet,返回人员记录列表(dict,key=表头字段名)。"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheet = None
|
||||
for ws in wb.worksheets:
|
||||
if SHEET_KEYWORD in ws.title:
|
||||
sheet = ws
|
||||
break
|
||||
if sheet is None:
|
||||
raise ValueError(f"工作簿 {excel_path} 中未找到包含「{SHEET_KEYWORD}」的 sheet")
|
||||
|
||||
# 表头第 HEADER_ROW 行,只取主表字段(到「费用」列为止)
|
||||
header = [c.value for c in next(sheet.iter_rows(min_row=HEADER_ROW, max_row=HEADER_ROW, max_col=MAIN_COLS))]
|
||||
col_names = {i: str(h).strip() for i, h in enumerate(header) if h}
|
||||
if "姓名" not in col_names.values() or "办理状态" not in col_names.values():
|
||||
raise ValueError(f"「{sheet.title}」第{HEADER_ROW}行未解析到标准表头(缺少姓名/办理状态等)")
|
||||
|
||||
records = []
|
||||
for row in sheet.iter_rows(min_row=HEADER_ROW + 1, max_row=sheet.max_row, max_col=MAIN_COLS):
|
||||
values = [c.value for c in row]
|
||||
if all(v is None for v in values):
|
||||
continue
|
||||
rec = {name: values[i] for i, name in col_names.items() if i < len(values)}
|
||||
if rec.get("姓名") is not None:
|
||||
records.append(rec)
|
||||
return records
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _match_rule(rec: dict, status: str, ins_type: str, ym: tuple) -> bool:
|
||||
"""按模板规则 + 公共过滤条件判断记录是否命中。"""
|
||||
if str(rec.get("办理状态") or "").strip() != status:
|
||||
return False
|
||||
if str(rec.get("参保类型") or "").strip() != ins_type:
|
||||
return False
|
||||
ptype = str(rec.get("人员类型") or "").strip()
|
||||
if any(kw in ptype for kw in EXCLUDE_TYPE_KEYWORDS):
|
||||
return False
|
||||
dept2 = str(rec.get("二级部门") or "")
|
||||
if not any(kw in dept2 for kw in DEPT_KEYWORDS):
|
||||
return False
|
||||
return _month_of(rec.get("办理时间")) == ym
|
||||
|
||||
|
||||
def _build_placeholders(rec: dict, ym: tuple) -> dict:
|
||||
"""根据记录与目标月份计算占位符替换值。"""
|
||||
y, m = ym
|
||||
next_y, next_m = (y, m + 1) if m < 12 else (y + 1, 1)
|
||||
today = datetime.now()
|
||||
|
||||
fee_txt = _fmt_num(rec.get("费用"))
|
||||
try:
|
||||
fee_num = float(rec.get("费用"))
|
||||
once_txt = _fmt_num(fee_num * 2)
|
||||
except (TypeError, ValueError):
|
||||
once_txt = ""
|
||||
|
||||
return {
|
||||
"{{姓名}}": str(rec.get("姓名") or ""),
|
||||
"{{四级部门}}": str(rec.get("四级部门") or ""),
|
||||
"{{参保单位全称}}": str(rec.get("参保单位全称") or ""),
|
||||
"{{区域}}": str(rec.get("区域") or ""),
|
||||
"{{费用}}": fee_txt,
|
||||
"{{备注}}": str(rec.get("备注") or ""),
|
||||
"{{一次性扣款}}": once_txt,
|
||||
# 模板文案已自带「月」字(如「{{当前月}} 月工资」「{{下月}}月15日」),故取纯数字
|
||||
"{{当前月}}": f"{m}",
|
||||
"{{下月}}": f"{next_m}",
|
||||
"{{当月15日}}": f"{m}月15日",
|
||||
"{{制作日年份}}": str(today.year),
|
||||
"{{制作日月份}}": str(today.month),
|
||||
"{{制作日天}}": str(today.day),
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Word 占位符替换(兼容占位符被 Word 拆成多个 run 的情况)
|
||||
# ------------------------------------------------------------------
|
||||
def _replace_in_paragraph(p, mapping: dict) -> None:
|
||||
runs = p.runs
|
||||
if not runs:
|
||||
return
|
||||
full = "".join(r.text for r in runs)
|
||||
if not any(k in full for k in mapping):
|
||||
return
|
||||
|
||||
# 1) 替换单个 run 内完整的占位符(保留 run 原格式)
|
||||
for r in runs:
|
||||
t = r.text
|
||||
for k, v in mapping.items():
|
||||
if k in t:
|
||||
t = t.replace(k, v)
|
||||
r.text = t
|
||||
|
||||
# 2) 处理跨 run 占位符(合并所在 run 区间,格式取起始 run)
|
||||
for k, v in mapping.items():
|
||||
if k in full and not any(k in r.text for r in runs):
|
||||
for i in range(len(runs)):
|
||||
rt = runs[i].text
|
||||
if k in rt:
|
||||
continue
|
||||
start = None
|
||||
for L in range(min(len(rt), len(k)), 0, -1):
|
||||
if rt[-L:] == k[:L]:
|
||||
start = len(rt) - L
|
||||
break
|
||||
if start is None:
|
||||
continue
|
||||
acc = rt
|
||||
j = i
|
||||
while k not in acc and j + 1 < len(runs):
|
||||
j += 1
|
||||
acc += runs[j].text
|
||||
if k in acc:
|
||||
runs[i].text = acc.replace(k, v)
|
||||
for x in range(i + 1, j + 1):
|
||||
runs[x].text = ""
|
||||
break
|
||||
|
||||
|
||||
def _fill_doc(template_path: str, mapping: dict):
|
||||
"""读取模板并替换占位符,返回内存中的 Document 对象(不保存)。"""
|
||||
doc = Document(template_path)
|
||||
|
||||
# 旧占位符统一归一化为新占位符
|
||||
norm = dict(LEGACY_PLACEHOLDERS)
|
||||
norm.update(mapping)
|
||||
|
||||
for para in doc.paragraphs:
|
||||
_replace_in_paragraph(para, norm)
|
||||
for tbl in doc.tables:
|
||||
for row in tbl.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
_replace_in_paragraph(para, norm)
|
||||
return doc
|
||||
|
||||
|
||||
def _leftover_placeholders(doc) -> set:
|
||||
"""统计文档(含表格)中残留的 {{...}} 占位符。"""
|
||||
leftover = set()
|
||||
for para in doc.paragraphs:
|
||||
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
|
||||
for tbl in doc.tables:
|
||||
for row in tbl.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
|
||||
return leftover
|
||||
|
||||
|
||||
def _merge_notice_docs(docs) -> object:
|
||||
"""把多份已填充的告知书 Document 合并为一份(每份之间插入分页符)。"""
|
||||
base = docs[0]
|
||||
body = base.element.body
|
||||
sect_pr = body.find(qn("w:sectPr"))
|
||||
for d in docs[1:]:
|
||||
# 分页符段落
|
||||
p = base.add_paragraph()
|
||||
p.add_run().add_break(WD_BREAK.PAGE)
|
||||
# 将该份告知书的段落与表格追加到正文末尾(跳过节属性)
|
||||
for child in list(d.element.body):
|
||||
if child.tag == qn("w:sectPr"):
|
||||
continue
|
||||
if sect_pr is not None:
|
||||
sect_pr.addprevious(deepcopy(child))
|
||||
else:
|
||||
body.append(deepcopy(child))
|
||||
return base
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
"""过滤 Windows 文件名非法字符,避免路径/分隔符冲突。"""
|
||||
for ch in '\\/:*?"<>|':
|
||||
name = name.replace(ch, "_")
|
||||
return name.strip() or "未命名"
|
||||
|
||||
|
||||
def _fill_template(template_path: str, mapping: dict, out_path: str) -> int:
|
||||
"""读取模板并替换占位符,保存为 out_path。返回残留占位符数量。"""
|
||||
doc = _fill_doc(template_path, mapping)
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
doc.save(out_path)
|
||||
return len(_leftover_placeholders(doc))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# PDF 转换(WPS 文字 COM,兼容无 MS Word 环境)
|
||||
# ------------------------------------------------------------------
|
||||
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
|
||||
"""用 WPS 打开 src_docx,另存为 target_docx 并导出 target_pdf(可写入受限目录)。"""
|
||||
import win32com.client
|
||||
|
||||
os.makedirs(os.path.dirname(target_docx), exist_ok=True)
|
||||
src_docx = os.path.abspath(src_docx)
|
||||
target_docx = os.path.abspath(target_docx)
|
||||
target_pdf = os.path.abspath(target_pdf)
|
||||
|
||||
for attempt in range(1, RETRY_TIMES + 1):
|
||||
app = None
|
||||
try:
|
||||
app = win32com.client.Dispatch("Kwps.Application")
|
||||
app.Visible = False
|
||||
try:
|
||||
app.DisplayAlerts = 0
|
||||
except Exception:
|
||||
pass
|
||||
doc = app.Documents.Open(src_docx)
|
||||
try:
|
||||
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
|
||||
except Exception:
|
||||
doc.SaveAs(target_docx, 12)
|
||||
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
|
||||
doc.Close(False)
|
||||
return
|
||||
except Exception:
|
||||
logger.exception("WPS 转换失败(第 %d/%d 次): %s -> %s", attempt, RETRY_TIMES, src_docx, target_pdf)
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == RETRY_TIMES:
|
||||
raise
|
||||
raise RuntimeError(f"WPS 转换失败:{src_docx}")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# OA 工作沟通推送数据构造
|
||||
# ------------------------------------------------------------------
|
||||
def _norm_code(value):
|
||||
"""工号统一转文本:浮点整数(37036835.0)去掉小数部分,与花名册文本工号保持一致。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _read_roster_map(roster_path: str) -> dict:
|
||||
"""读取花名册,返回 {工号: {姓名, 二级部门, 四级部门, 岗位}};表头行自动定位(含「工号」列)。"""
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
wb = openpyxl.load_workbook(roster_path, read_only=True, data_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
col_idx, header_row = {}, None
|
||||
for row in ws.iter_rows():
|
||||
if header_row is None:
|
||||
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
|
||||
if "工号" in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「工号」字段):{roster_path}")
|
||||
need = ("工号", "姓名", "二级部门", "四级部门", "岗位")
|
||||
missing = [c for c in need if c not in col_idx]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}")
|
||||
|
||||
def _cell(vals, key):
|
||||
i = col_idx[key]
|
||||
return vals[i] if i < len(vals) else None
|
||||
|
||||
result = {}
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
vals = [c.value for c in row]
|
||||
code = _norm_code(_cell(vals, "工号"))
|
||||
if not code:
|
||||
continue
|
||||
result[code] = {
|
||||
"姓名": str(_cell(vals, "姓名") or ""),
|
||||
"二级部门": str(_cell(vals, "二级部门") or ""),
|
||||
"四级部门": str(_cell(vals, "四级部门") or ""),
|
||||
"岗位": str(_cell(vals, "岗位") or ""),
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _fill_dept4(rec: dict, roster_map: dict) -> str:
|
||||
"""四级部门:源数据缺失时查花名册(按37工号),仍缺失 fallback 二级部门。"""
|
||||
dept4 = str(rec.get("四级部门") or "").strip()
|
||||
if dept4:
|
||||
return dept4
|
||||
code = _norm_code(rec.get("37工号"))
|
||||
if code and roster_map and code in roster_map:
|
||||
dept4 = str(roster_map[code].get("四级部门") or "").strip()
|
||||
if dept4:
|
||||
return dept4
|
||||
return str(rec.get("二级部门") or "").strip() or "未知"
|
||||
|
||||
|
||||
def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
|
||||
"""读取社保变更人员名单,返回「是否变更」=是 的记录列表。
|
||||
|
||||
每条 rec 带标准列名(新区域->区域、个人费用->费用)与 _source=sheet 名(区分职能/门店);
|
||||
四级部门缺失时用花名册补全,仍缺失 fallback 二级部门。
|
||||
"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
records = []
|
||||
for ws in wb.worksheets:
|
||||
if not any(kw in ws.title for kw in TRANSFER_SHEET_GENERATE):
|
||||
continue # 仅处理配置范围内的 sheet(职能及干部/门店)
|
||||
# 自动定位表头行:同时含「37工号」与「是否变更」列
|
||||
col_idx, header_row = None, None
|
||||
for row in ws.iter_rows():
|
||||
if header_row is None:
|
||||
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
|
||||
if "37工号" in names and TRANSFER_CHANGE_COL in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
continue # 非目标 sheet(如说明/汇总页)
|
||||
|
||||
def _cell(vals, key):
|
||||
i = col_idx.get(key)
|
||||
return vals[i] if i is not None and i < len(vals) else None
|
||||
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
vals = [c.value for c in row]
|
||||
if all(v is None for v in vals):
|
||||
continue
|
||||
if str(_cell(vals, TRANSFER_CHANGE_COL) or "").strip() != TRANSFER_CHANGE_VALUE:
|
||||
continue
|
||||
rec = {}
|
||||
for src, std in TRANSFER_COL_MAP.items():
|
||||
if src in col_idx:
|
||||
rec[std] = _cell(vals, src)
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "参保单位全称", "备注"):
|
||||
if key in col_idx:
|
||||
rec[key] = _cell(vals, key)
|
||||
if rec.get("姓名") is None:
|
||||
continue
|
||||
rec["_source"] = ws.title
|
||||
rec["四级部门"] = _fill_dept4(rec, roster_map)
|
||||
if not rec.get("工号") and rec.get("37工号") is not None:
|
||||
rec["工号"] = rec["37工号"]
|
||||
records.append(rec)
|
||||
return records
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _resolve_receivers_batch(roster_path, codes) -> list:
|
||||
"""用花名册批量查询为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。"""
|
||||
store_results = find_store_manager_batch(codes, roster_path)
|
||||
hr_results = find_hr_personnel_batch(codes, roster_path)
|
||||
receivers = []
|
||||
for code in codes:
|
||||
sr = store_results.get(code, {})
|
||||
mgr = sr.get("manager_code") if sr.get("success") else None
|
||||
if mgr and mgr not in receivers:
|
||||
receivers.append(mgr)
|
||||
for p in hr_results.get(code, {}).get("personnel", []):
|
||||
pc = p.get("工号")
|
||||
if pc and pc not in receivers:
|
||||
receivers.append(pc)
|
||||
return receivers
|
||||
|
||||
|
||||
def _collect_rule_pdfs(month_dir: str, rule_folder: str, matched_recs: list) -> list:
|
||||
"""按命中员工的(二级部门,四级部门)分组,收集对应告知书 PDF 附件路径(仅 PDF)。"""
|
||||
folder = os.path.join(month_dir, rule_folder)
|
||||
if not os.path.isdir(folder):
|
||||
return []
|
||||
wanted = {
|
||||
_safe_filename(
|
||||
f"{str(r.get('二级部门') or '未知').strip()}_{str(r.get('四级部门') or '未知').strip()}_{rule_folder}"
|
||||
) + ".pdf"
|
||||
for r in matched_recs
|
||||
}
|
||||
return [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f in wanted]
|
||||
|
||||
|
||||
def _text_to_html(text: str) -> str:
|
||||
"""多行纯文本转 HTML:
|
||||
- 普通段落用 <p style="text-indent:2em"> 首行缩进 2 字符;
|
||||
- 行以 @@R 前缀标记右对齐(落款),输出时去除前缀并用 <p style="text-align:right">。
|
||||
"""
|
||||
parts = []
|
||||
for ln in str(text).splitlines():
|
||||
ln = ln.strip()
|
||||
if not ln:
|
||||
continue
|
||||
if ln.startswith("@@R"):
|
||||
parts.append(f'<p style="text-align:right">{ln[3:]}</p>')
|
||||
else:
|
||||
parts.append(f'<p style="text-indent:2em">{ln}</p>')
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _highlight_text(text: str, highlights: tuple, m: int = None) -> str:
|
||||
"""给文案关键词加颜色高亮(<span style="color:...">),keyword 支持 {m} 月份占位符。"""
|
||||
for keyword, color in highlights:
|
||||
kw = keyword.format(m=m) if m is not None else keyword
|
||||
text = text.replace(kw, f'<span style="color:{color}">{kw}</span>')
|
||||
return text
|
||||
|
||||
|
||||
def build_work_communication_data(excel_path: str = None, output_dir: str = None,
|
||||
ym: tuple = None, roster_path: str = None) -> list:
|
||||
"""
|
||||
构造 OA 工作沟通推送数据:员工参与社会保险+参保异常合并一条、社保转移单独一条。
|
||||
每条含 subject/content(HTML)/attachment_paths(仅PDF)/receivers(店长+人事工号)/category。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT(须先执行 generate_notices 生成 PDF)
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
list: [{"subject", "content", "attachment_paths", "receivers", "category"}, ...]
|
||||
"""
|
||||
excel_path = excel_path or _find_excel(BASE_DIR)
|
||||
ym = ym or _extract_ym(os.path.basename(excel_path))
|
||||
output_dir = output_dir or OUTPUT_ROOT
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
y, m = ym
|
||||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||||
|
||||
logger.info("构造 OA 工作沟通数据:%s(%d-%02d)", excel_path, y, m)
|
||||
records = _read_insurance_records(excel_path)
|
||||
|
||||
# 社保转移:独立数据源(社保变更人员名单),推送仅限「变更-门店」sheet
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or DEFAULT_ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
|
||||
roster_map = {}
|
||||
transfer_excel = _find_transfer_excel(BASE_DIR)
|
||||
transfer_records = _read_transfer_records(transfer_excel, roster_map)
|
||||
|
||||
# 按模板规则筛出命中员工
|
||||
matched_by_rule = {}
|
||||
for rule_name, rule in TEMPLATES.items():
|
||||
if rule_name == "社保转移":
|
||||
matched = [r for r in transfer_records if TRANSFER_SHEET_PUSH in str(r.get("_source") or "")]
|
||||
else:
|
||||
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
|
||||
matched_by_rule[rule_name] = matched
|
||||
logger.info("[%s] 命中 %d 人", rule_name, len(matched))
|
||||
|
||||
messages = []
|
||||
for tpl in OA_MESSAGE_TEMPLATES:
|
||||
matched_recs = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
matched_recs.extend(matched_by_rule.get(rn, []))
|
||||
if not matched_recs:
|
||||
logger.info("[%s] 无命中人员,跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 附件:仅 PDF,按命中员工(二级部门,四级部门)分组收集
|
||||
attachment_paths = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
attachment_paths.extend(
|
||||
_collect_rule_pdfs(month_dir, TEMPLATES[rn]["folder"], matched_by_rule.get(rn, []))
|
||||
)
|
||||
# 同一二级部门的所有告知书挨着排列(文件名首段=二级部门,段内按文件名排)
|
||||
attachment_paths = sorted(
|
||||
attachment_paths,
|
||||
key=lambda p: (os.path.basename(p).split("_", 1)[0], os.path.basename(p)),
|
||||
)
|
||||
if not attachment_paths:
|
||||
logger.warning("[%s] 未收集到告知书 PDF(请先执行告知书生成),跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 接收人:店长 + 人事(工号去重)
|
||||
codes = []
|
||||
for r in matched_recs:
|
||||
c = _norm_code(r.get("工号"))
|
||||
if c:
|
||||
codes.append(c)
|
||||
else:
|
||||
logger.warning("员工「%s」无工号,跳过接收人解析", r.get("姓名"))
|
||||
receivers = _resolve_receivers_batch(roster_path, codes)
|
||||
if not receivers:
|
||||
logger.warning("[%s] 未解析到任何接收人(店长/人事),跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 落款日期 = 实际推送当天日期(如 2026年08月26日,带前导0)
|
||||
push_date = datetime.today().strftime("%Y年%m月%d日")
|
||||
content = _highlight_text(tpl["content"].format(y=y, m=m, push_date=push_date), OA_HIGHLIGHTS.get(tpl["key"], ()), m=m)
|
||||
|
||||
messages.append({
|
||||
"subject": tpl["subject"].format(y=y, m=m),
|
||||
"content": _text_to_html(content),
|
||||
"attachment_paths": attachment_paths,
|
||||
"receivers": receivers,
|
||||
"category": tpl["category"],
|
||||
})
|
||||
logger.info("[%s] 附件 %d 份,接收人 %d 人:%s",
|
||||
tpl["key"], len(attachment_paths), len(receivers), ", ".join(receivers))
|
||||
|
||||
logger.info("构造完成:%d 条工作沟通推送数据", len(messages))
|
||||
return messages
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 主流程
|
||||
# ------------------------------------------------------------------
|
||||
def generate_notices(excel_path: str = None, output_dir: str = None, ym: tuple = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""
|
||||
生成三类告知书(Word + PDF)。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径(社保转移四级部门补全用),默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
{模板名: [输出文件路径, ...]}
|
||||
"""
|
||||
excel_path = excel_path or _find_excel(BASE_DIR)
|
||||
ym = ym or _extract_ym(os.path.basename(excel_path))
|
||||
output_dir = output_dir or OUTPUT_ROOT
|
||||
y, m = ym
|
||||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||||
|
||||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||||
records = _read_insurance_records(excel_path)
|
||||
logger.info("「参保名单」共 %d 条记录", len(records))
|
||||
|
||||
# 社保转移:独立数据源(社保变更人员名单),生成覆盖职能及干部+门店两个 sheet
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or DEFAULT_ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
|
||||
roster_map = {}
|
||||
transfer_excel = _find_transfer_excel(BASE_DIR)
|
||||
transfer_records = _read_transfer_records(transfer_excel, roster_map)
|
||||
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), transfer_excel)
|
||||
|
||||
results = {}
|
||||
for rule_name, rule in TEMPLATES.items():
|
||||
tpl_path = rule["file"]
|
||||
if not os.path.exists(tpl_path):
|
||||
raise FileNotFoundError(f"模板不存在:{tpl_path}")
|
||||
if rule_name == "社保转移":
|
||||
matched = transfer_records
|
||||
else:
|
||||
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
|
||||
if not matched:
|
||||
logger.info("[%s] 无命中人员,跳过", rule_name)
|
||||
results[rule_name] = []
|
||||
continue
|
||||
|
||||
out_folder = os.path.join(month_dir, rule["folder"])
|
||||
os.makedirs(out_folder, exist_ok=True)
|
||||
files = []
|
||||
logger.info("=" * 70)
|
||||
logger.info("[%s] 命中 %d 人(%s)", rule_name, len(matched), ", ".join(str(r.get("姓名")) for r in matched))
|
||||
|
||||
# 按(二级部门,四级部门)分组合并,生成一份告知书
|
||||
groups = {}
|
||||
for rec in matched:
|
||||
key = (str(rec.get("二级部门") or "未知").strip(), str(rec.get("四级部门") or "未知").strip())
|
||||
groups.setdefault(key, []).append(rec)
|
||||
|
||||
for (dept2, dept4), recs in groups.items():
|
||||
# 每人生成一份已填充的内存文档,再合并(每份之间分页)
|
||||
docs = [_fill_doc(tpl_path, _build_placeholders(r, ym)) for r in recs]
|
||||
doc = _merge_notice_docs(docs) if len(docs) > 1 else docs[0]
|
||||
base_name = _safe_filename(f"{dept2}_{dept4}_{rule['folder']}")
|
||||
docx_path = os.path.join(out_folder, base_name + ".docx")
|
||||
pdf_path = docx_path[:-5] + ".pdf"
|
||||
|
||||
doc.save(docx_path)
|
||||
leftover = _leftover_placeholders(doc)
|
||||
if leftover:
|
||||
logger.warning("[%s] %s 模板存在未替换占位符:%s", rule_name, base_name, sorted(leftover))
|
||||
_publish_via_wps(docx_path, docx_path, pdf_path)
|
||||
logger.info("已生成:%s(%d 人)", os.path.basename(docx_path), len(recs))
|
||||
files.append(docx_path)
|
||||
results[rule_name] = files
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("全部完成,输出目录:%s", month_dir)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(message)s")
|
||||
generate_notices()
|
||||
messages = build_work_communication_data()
|
||||
logger.info("共构造 %d 条工作沟通推送数据", len(messages))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,9 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 加班审批流程包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -1,22 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.overtime_approval
|
||||
@FileName: overtime_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:22
|
||||
@Description: 加班审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.work_overtime.validator import validate_doc
|
||||
from app.service.hrbp.oa.work_overtime.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""加班审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="加班", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,103 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 09:30
|
||||
@Description: 加班表单解析模块(解析 WorkformEngine 返回的 result,提取关键字段并转换为中文描述)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 加班类型映射
|
||||
OT_TYPE_MAP = {
|
||||
"1": "延时加班",
|
||||
"2": "法定假日加班",
|
||||
"3": "休息日加班",
|
||||
}
|
||||
|
||||
# 补贴类型映射
|
||||
SUBSIDY_TYPE_MAP = {
|
||||
"1": "转调休",
|
||||
"2": "转补贴",
|
||||
}
|
||||
|
||||
|
||||
def parse_overtime_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析加班表单数据,提取关键字段并将代码转换为中文描述。
|
||||
|
||||
注意:入参为 oa_api.get_business_data 返回的 result 字段(state 校验已在
|
||||
get_business_data 内完成),即审批引擎 doc['formData']。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(含 ot_type / staff_name 等)
|
||||
|
||||
Returns:
|
||||
包含加班关键字段的字典(中文键名);找不到映射时保留原始代码值
|
||||
"""
|
||||
# 获取原始类型代码
|
||||
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") or result.get("expect_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")
|
||||
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
|
||||
if (judge_start and judge_end
|
||||
and "无" not in str(judge_start) and "无" not in str(judge_end)):
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 示例 result(WorkformEngine 返回的 result 字段)
|
||||
sample_result = {
|
||||
"dept_org_name": "网络项目小组",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"ot_date": "2026-08-02",
|
||||
"ot_hour": 6.0,
|
||||
"ot_type": "1",
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"subsidy_type": "2",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
|
||||
parsed = parse_overtime_form(sample_result)
|
||||
logger.info("===== 加班信息解析结果 =====")
|
||||
for key, value in parsed.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
@@ -1,162 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程报告模块。
|
||||
校验结果分四组:通过 / 校验不通过未处理 / 人工复核 / 超期。
|
||||
输出三份清单:
|
||||
《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因、详情页链接
|
||||
《附件人工复核待办清单》:员工姓名、加班类型、详情页链接(供人工打开查看附件)
|
||||
《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 2.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的加班人员,缺失时回退到发起人。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _otype(r: Dict[str, Any]) -> str:
|
||||
"""加班类型。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
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") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if overdue:
|
||||
summary += f",超期待人资处理 {len(overdue)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
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 overdue:
|
||||
lines.append("《超期加班待人资处理清单》")
|
||||
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
|
||||
for i, r in enumerate(overdue, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {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("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《加班审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user