Compare commits
91
Commits
main
...
7e0838de64
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e0838de64 | ||
|
|
be1a2899ba | ||
|
|
dd546fc07b | ||
|
|
a4c172bc98 | ||
|
|
c7add9574e | ||
|
|
b034b51685 | ||
|
|
600379933d | ||
|
|
530cfe38dc | ||
|
|
11fc3cee6a | ||
|
|
78aa8c361c | ||
|
|
f30ab9cc29 | ||
|
|
6d2dd93628 | ||
|
|
813bee743b | ||
|
|
0ab43d0ed8 | ||
|
|
a1a06504a5 | ||
|
|
b86bc1bf97 | ||
|
|
67bb73fa30 | ||
|
|
6f248b0741 | ||
|
|
9f6deaae76 | ||
|
|
d605a7f9cc | ||
|
|
42c7cf24f2 | ||
|
|
c00c4423f0 | ||
|
|
3f901d3882 | ||
|
|
65540fb121 | ||
|
|
9d067c0646 | ||
|
|
be07de0e92 | ||
|
|
0354a1ca58 | ||
|
|
1a16b1b5b7 | ||
|
|
f8889cdf51 | ||
|
|
8593f0fec4 | ||
|
|
e5884bd943 | ||
|
|
657f444041 | ||
|
|
16d59e4e69 | ||
|
|
ea92c62bb9 | ||
|
|
121df38da1 | ||
|
|
75d0903c0a | ||
|
|
8375df692a | ||
|
|
3b5ce2d219 | ||
|
|
9cfa096ec8 | ||
|
|
30218cc339 | ||
|
|
1178ea37b3 | ||
|
|
5c90747d0f | ||
|
|
be6817bafd | ||
|
|
7af2132b99 | ||
|
|
acca8c5e8a | ||
|
|
aee37b200f | ||
|
|
05842f36d5 | ||
|
|
76d7459515 | ||
|
|
fc2cf49c35 | ||
|
|
93795ffec0 | ||
|
|
4b168c3982 | ||
|
|
e3dc6369ee | ||
|
|
bdcc0326bf | ||
|
|
20d93187f9 | ||
|
|
b2db418d39 | ||
|
|
d19b783302 | ||
|
|
13eb46f4e1 | ||
|
|
7a4f3590ef | ||
|
|
9e61206be2 | ||
|
|
e5c598e67a | ||
|
|
39bf3e14a0 | ||
|
|
ce0422979a | ||
|
|
bfef048695 | ||
|
|
2f67a15083 | ||
|
|
d773f783eb | ||
|
|
dc8d038e34 | ||
|
|
195edb8b32 | ||
|
|
59b2ee9acb | ||
|
|
d7f3cbfcfd | ||
|
|
d2b24051af | ||
|
|
0973533bab | ||
|
|
61e9e123c4 | ||
|
|
60a177605a | ||
|
|
60112ad367 | ||
|
|
c95720514b | ||
|
|
2fafd9af18 | ||
|
|
4d9928abf3 | ||
|
|
28b74fce4e | ||
|
|
d468d15032 | ||
|
|
c1c54e61fc | ||
|
|
966d529551 | ||
|
|
186636a8e4 | ||
|
|
c749d951a0 | ||
|
|
9a14f5aca6 | ||
|
|
9927066abb | ||
|
|
7e46b5cc06 | ||
|
|
eef5df9ce2 | ||
|
|
83d8204847 | ||
|
|
0489fbe62c | ||
|
|
5d339b3d0e | ||
|
|
724a4f7b77 |
+34
-2
@@ -13,6 +13,21 @@ sdist/
|
|||||||
wheels/
|
wheels/
|
||||||
*.manifest
|
*.manifest
|
||||||
*.spec
|
*.spec
|
||||||
|
# 前端依赖与构建产物(desktop 桌面端)
|
||||||
|
desktop/*/frontend/node_modules
|
||||||
|
plugins/**/ui-src/node_modules
|
||||||
|
desktop/*/frontend/dist/
|
||||||
|
desktop/**/frontend/*.zip # controlplane-web-dist.zip 等部署用压缩包
|
||||||
|
|
||||||
|
# 桌面版打包产物(PyInstaller 中间/输出、安装包、插件构建包,不入库)
|
||||||
|
# 仅执行机(壳子)/文件服务器仍走 PyInstaller 打包;中心机已改源码部署,不再产出 exe
|
||||||
|
desktop/*/build-exe/
|
||||||
|
desktop/*/dist-exe/
|
||||||
|
desktop/releases/
|
||||||
|
desktop/build/
|
||||||
|
dist-plugin/
|
||||||
|
desktop/**/setup-*.exe
|
||||||
|
desktop/**/installer/
|
||||||
pip-log.txt
|
pip-log.txt
|
||||||
pip-delete-this-directory.txt
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
@@ -26,8 +41,16 @@ ENV/
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
# 各平台会话 cookies 持久化目录(OA / 其他平台共用,按平台名分文件)
|
# 控制面签名密钥 / 运行期产物(禁止入库)
|
||||||
app/service/.sessions/
|
.admin_secret
|
||||||
|
.webhost.pid
|
||||||
|
*.pid
|
||||||
|
desktop/**/keys/
|
||||||
|
desktop/**/packages/
|
||||||
|
desktop/**/controlplane.db
|
||||||
|
desktop/**/_cp_sessions.json
|
||||||
|
# 各平台会话 cookies / 缓存目录(统一移入 %LOCALAPPDATA%\37duAutomation,禁止入库)
|
||||||
|
**/.sessions/
|
||||||
|
|
||||||
# ---------- IDE ----------
|
# ---------- IDE ----------
|
||||||
.idea/
|
.idea/
|
||||||
@@ -49,3 +72,12 @@ logs/
|
|||||||
.coverage
|
.coverage
|
||||||
htmlcov/
|
htmlcov/
|
||||||
.tox/
|
.tox/
|
||||||
|
aa.md
|
||||||
|
|
||||||
|
# vc运行库
|
||||||
|
vc_redist/
|
||||||
|
vc_redist_x64/
|
||||||
|
vc_redist_x86/
|
||||||
|
|
||||||
|
静态资源/
|
||||||
|
.assets/
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
---
|
||||||
|
name: BT-Go-Project-Deploy
|
||||||
|
description: >
|
||||||
|
在宝塔面板上部署 Go 项目(编译好的二进制,含 Go SDK 版本安装、项目注册、进程启停、域名/外网映射),
|
||||||
|
并在项目启动失败时排错。当用户要求把本机编译好的 Go 二进制部署成面板可管理的项目(含 Go SDK 安装、
|
||||||
|
端口/运行用户配置、域名绑定),或 Go 项目启动失败/访问异常需要排查根因时使用。
|
||||||
|
触发关键词:部署 Go、Go 项目、go build 产物部署、Go 二进制、Gin/Beego/Echo 服务、Go SDK 安装、
|
||||||
|
go1.xx、GOPROXY、Go 项目启动失败、error while loading shared libraries、Address already in use。
|
||||||
|
日常的启停/状态/日志/改配置/删项目等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||||
|
---
|
||||||
|
|
||||||
|
# Go 项目部署与启动排错 SOP
|
||||||
|
|
||||||
|
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||||
|
> 本 SOP 只覆盖两个主场景:**① 部署 Go 项目(含 Go SDK 安装);② 项目启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、删除)不做 SOP,直接使用工具。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **先只读侦察,再执行变更** —— 部署前先 `GoProjectInfo` 查是否已存在同名项目、`GoVersion(action=list)` 看 SDK;排错先读日志,不盲目重启。
|
||||||
|
2. **Go 是编译产物,无源码分析** —— `GoProjectCreate` 不需要分析步骤:给二进制绝对路径 + 端口 + 启动命令(缺省=二进制)直接注册。**不提供 analyze_only。**
|
||||||
|
3. **Go SDK 安装走 Bash 后台** —— btpygvm 装的是完整预编译包(快),但网络慢仍可能超时:`GoVersion(action=install, version=...)` 返回 `install_command` 后,必须用 `Bash(command=install_command, run_in_background=true)` 后台执行 + `BashStatus(task_id, wait=true)` 轮询;**一次只装一个版本**。
|
||||||
|
4. **创建即同步启动** —— `GoProjectCreate` 注册后面板同步启动(nohup 脚本 + pid,**无守护、崩了不自愈**);创建成功 ≠ 进程一定活着,必须 `GoProjectInfo` 核验 `run=true` + 端口在 `listen`。
|
||||||
|
5. **Go 项目是编译二进制** —— 缺动态库/权限/端口占用是启动失败主因,排错按日志对号入座(场景二)。
|
||||||
|
6. **改配置即重启** —— `GoProjectModify(action='config')` 面板改完自动 stop+start;改端口后若绑了域名,nginx 反代按新端口重写。
|
||||||
|
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||||
|
8. **禁止操作**:删除项目目录/二进制源码、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景一:部署 Go 项目
|
||||||
|
|
||||||
|
## Step 0 —— 预检
|
||||||
|
1. 确认任务确为"部署 Go 项目"(非排错/运维)。
|
||||||
|
2. 确认有编译好的**可执行二进制**(`go build` 产物,Linux 目标平台),拿到绝对路径。
|
||||||
|
3. 确认**端口**(应用监听,10-65535)与**运行用户**(默认 www)。
|
||||||
|
4. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||||
|
|
||||||
|
## Step 1 —— Go SDK 确认 / 安装
|
||||||
|
1. `GoVersion(action='list')`:看 `data.installed` 是否已有可用 Go、`data.used` 当前版本。
|
||||||
|
2. 没有可用版本 → `GoVersion(action='list')` 的 `data.available` 挑一个稳定版(每项含 `install_command`),再调 `GoVersion(action='install', version=<go1.xx>)` 拿该版本的 install_command。
|
||||||
|
3. **用 Bash 后台执行**:`Bash(command=<install_command>, run_in_background=true)` → 得到 task_id → `BashStatus(task_id, wait=true)` 轮询到完成(预编译包下载+解压,通常几十秒到几分钟)。
|
||||||
|
4. 完成后 `GoVersion(action='list')` 确认该版本在 `installed`;需要时 `GoVersion(action='use', version=...)` 切换当前版本;拉依赖慢可 `GoVersion(action='goproxy', goproxy=<源>)` 设置 GOPROXY。
|
||||||
|
|
||||||
|
## Step 2 —— 创建项目(注册 + 启动)
|
||||||
|
调用 `GoProjectCreate(project_name=..., project_exe=<二进制绝对路径>, port=<端口>, ...)`:
|
||||||
|
- **必填**:`project_name`(字母/数字/下划线)、`project_exe`、`port`。
|
||||||
|
- **可选**:`project_cmd`(缺省=二进制本身)、`run_user`(默认 www)、`domains`(给则自动开启外网映射,'域名' 或 '域名:端口')、`env_list`(`[{"k","v"}]`,如 `[{"k":"PORT","v":"9000"}]`,**字符串 "K=V" 会被 schema 拒**)、`env_file`、`is_power_on`(默认 true)、`ps`、`release_firewall`(需外网访问时 true)。
|
||||||
|
|
||||||
|
> 返回"创建成功"= 已注册并尝试启动;`data.project` 含 run/listen 运行态。
|
||||||
|
|
||||||
|
## Step 3 —— 启动验证(强制)
|
||||||
|
1. `GoProjectInfo(project_name=...)`:`run=true`、端口在 `listen`。
|
||||||
|
2. 用返回的 `log_files` 里应用日志路径(`/www/wwwlogs/go/<name>.log`)调 filesystem `Read` 看尾部无致命异常(`error while loading shared libraries`/`Address already in use`/`bind: address already in use`)。
|
||||||
|
3. 有域名映射的项目核验外网映射(`bind_extranet`)与反代(nginx `go_<name>.conf` 的 `proxy_pass 127.0.0.1:{port}`)。
|
||||||
|
|
||||||
|
- 全通过 → 按"完成汇报"收尾。
|
||||||
|
- 任一失败 → **转场景二排错**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景二:启动排错
|
||||||
|
|
||||||
|
> 适用:创建后 run=false、或用户报"Go 项目启动失败/访问异常"。
|
||||||
|
|
||||||
|
## Step 0 —— 快速定位现状(只读)
|
||||||
|
并行收集,不跳过:
|
||||||
|
1. `GoProjectInfo(project_name=...)`:`run`、`listen`、`project_config`(exe/命令/端口/用户/环境变量)。
|
||||||
|
2. 读应用日志尾部(`log_files` 里"应用日志")找根因。
|
||||||
|
3. 已知配置:二进制路径、启动命令、端口、运行用户、是否绑域名。
|
||||||
|
|
||||||
|
收集后按症状进分支。
|
||||||
|
|
||||||
|
## 分支 A —— 启动失败(进程起不来 / run=false)
|
||||||
|
按日志根因对号入座:
|
||||||
|
| 日志特征 | 根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| `error while loading shared libraries: libxxx.so` | 缺动态库 | 汇报需装系统库(如 glibc/其他 .so),装后 `GoProjectControl(action='start')` |
|
||||||
|
| `bind: address already in use` / `EADDRINUSE` | 端口被占 | `GoProjectModify(action='config', port=新端口)`(自动重启) |
|
||||||
|
| `permission denied` / 无法写入日志 | 运行用户无权限 | `GoProjectModify(action='config', run_user=<有权限用户>)` |
|
||||||
|
| 启动即退出 / pid 无 | 启动命令错 / 环境变量缺 | 核对 `project_cmd` 与 `env_list`;`GoProjectControl(action='start')` 重试 |
|
||||||
|
| 二进制非当前平台编译 | 目标平台不符 | 重新 `go build` 目标平台二进制 |
|
||||||
|
|
||||||
|
- 修正后回场景一 Step 3 重新验证。**Go 进程无守护,崩了不会自动拉起**——排错后必须手动 start。
|
||||||
|
|
||||||
|
## 分支 B —— 访问异常(502/无法访问,但进程活着)
|
||||||
|
1. `GoProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 A。
|
||||||
|
2. **端口/反代核对**:`listen`(实际监听)vs `project_config.port`(反代目标)是否一致;grep `proxy_pass` `nginx/go_<name>.conf` 确认指向 `127.0.0.1:{实际端口}`。
|
||||||
|
- 端口改了没同步 → `GoProjectModify(action='config', port=实际端口)`。
|
||||||
|
- 反代指向错误端口 → 同上。
|
||||||
|
3. 域名绑定:`bind_extranet` 是否开、域名是否在 nginx `server_name`(未绑 → `GoProjectModify(action='add_domain', domains=[...])` + `bind_extranet`)。
|
||||||
|
4. 读 nginx error log(`log_files` 里 `/www/wwwlogs/<name>.error.log`)进一步定位。
|
||||||
|
5. 修正后验证。
|
||||||
|
|
||||||
|
## 分支 C —— 进程在但无响应 / 卡死
|
||||||
|
1. 应用日志尾部看异常/死锁(filesystem `Read`)。
|
||||||
|
2. `SystemInfo()` 看系统资源(CPU/内存/负载)。
|
||||||
|
3. 汇报,建议用户确认后 `GoProjectControl(action='restart')` 重启。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||||
|
|
||||||
|
| 需求 | 工具 |
|
||||||
|
|---|---|
|
||||||
|
| 查看项目列表/状态 | `GoProjectInfo()`(project_name 留空) |
|
||||||
|
| 查看单项目详情(run/listen/log_files/配置) | `GoProjectInfo(project_name=...)` |
|
||||||
|
| 启动 / 停止 / 重启 | `GoProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||||
|
| 看应用日志 / nginx 日志 | `GoProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||||
|
| 改二进制/命令/端口/用户/开机自启/环境变量/备注(自动重启) | `GoProjectModify(action='config', ...)` |
|
||||||
|
| 加域名 / 删域名(至少留一个) / 开 / 关外网映射 | `GoProjectModify(action='add_domain'/'remove_domain'/'bind_extranet'/'unbind_extranet', domains=[...])` |
|
||||||
|
| Go SDK 列表 / 安装(Bash 后台) / 切换 / 卸载 / 设 GOPROXY | `GoVersion(action='list'/'install'/'use'/'uninstall'/'goproxy', ...)` |
|
||||||
|
| **安装 Go SDK(下载+解压,后台)** | `GoVersion` install 取 `install_command` → `Bash(run_in_background=true)` + `BashStatus` 轮询 |
|
||||||
|
| 删除项目(**高风险,先确认**;保留二进制与目录) | `GoProjectDelete(project_name=...)` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 完成汇报模板(部署成功)
|
||||||
|
|
||||||
|
返回:项目名 / 二进制路径(project_exe)/ 端口 / 运行用户 / Go SDK 版本;若绑域名:访问地址 + nginx 配置路径;启动验证结果(进程/端口/日志);遗留隐患提示(GOPROXY 未设、防火墙未放行、依赖库缺失、绑外网未开等)。
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
---
|
||||||
|
name: BT-Html-Project-Deploy
|
||||||
|
description: >
|
||||||
|
在宝塔面板上管理 Html(静态)项目:创建静态站点(域名 + 网站根目录)、把前端构建产物部署到站点目录、
|
||||||
|
编辑伪静态 rewrite 配置(SPA try_files / 自定义 location / 缓存)、改域名/网站根目录/运行目录/启停,
|
||||||
|
并在静态站点访问异常(404 / SPA 刷新 404 / 伪静态不生效 / 目录权限)时排错。
|
||||||
|
当用户要求把前端静态页面(HTML/SPA/单页应用)挂到域名上,或静态站点访问异常需要排查时使用。
|
||||||
|
触发关键词:静态网站、HTML项目、部署前端、SPA、单页应用、伪静态、rewrite、运行目录、静态站 404、
|
||||||
|
SPA 404、BT-Html-Project-Deploy。
|
||||||
|
日常的查看/启停/改备注等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||||
|
---
|
||||||
|
|
||||||
|
# Html(静态)项目运维 SOP
|
||||||
|
|
||||||
|
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||||
|
> 本 SOP 覆盖三个主场景:**① 创建静态项目;② 配置编辑(伪静态 rewrite / 主 conf);③ 静态站点访问异常排错**。其他简单操作(状态查看、启停、改备注、绑删域名、改目录、运行目录、删除)不做 SOP,直接使用工具。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **先只读侦察,再执行变更** —— 操作前先 `HtmlProjectInfo`(site_name 留空)列项目找到站点名(可能带 `_<端口>` 后缀),再 `HtmlProjectInfo(site_name=...)` 看当前域名/路径/运行目录/SSL;排错先读日志,不盲目重写配置。
|
||||||
|
2. **静态站点本质 = 网站根目录 + nginx/apache conf + rewrite 文件** —— nginx 主 conf 在 `/www/server/panel/vhost/nginx/html_<name>.conf`(模板渲染产物),**伪静态 rewrite 文件在 `/www/server/panel/vhost/rewrite/html_<name>.conf`(面板官方自定义配置入口,被主 conf include)**。
|
||||||
|
3. **改配置优先写 rewrite 文件** —— SPA `try_files`、自定义 `location`、静态资源缓存等写 rewrite 文件(面板创建的注释即引导"请将伪静态规则或自定义NGINX配置填写到此处");**只有确实要改 listen/root/自定义 server 段才动主 conf,且改前必须 filesystem `Read` 留基线**(面板 SSL/域名/改目录操作会重写覆盖主 conf)。
|
||||||
|
4. **域名/路径/启停/运行目录走 `HtmlProjectModify`** —— 面板方法同步 domain 表与 nginx/apache server_name;**不要用 filesystem 直接改主 conf 来加域名**,会与面板不同步。
|
||||||
|
5. **创建即生效** —— `HtmlProjectCreate` 成功即写 nginx/apache 配置 + 建目录(目录不存在自动创建)+ 非 80 端口放行防火墙 + 重载服务;返回的 `site_name_hint` 仅供参考,**实际站点名以 `HtmlProjectInfo` 列表返回的 name 为准**(主域名重名会带 `_<端口>`)。
|
||||||
|
6. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||||
|
7. **禁止操作**:`rm -rf` 站点根目录外的路径、修改宝塔/插件自身文件、读取插件 `data/` 凭据、直接写 nginx 主 conf 来改域名(走 Modify)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景一:创建静态项目
|
||||||
|
|
||||||
|
## Step 0 —— 预检
|
||||||
|
1. 确认任务确为"创建 Html(静态)项目"。
|
||||||
|
2. 拿到**要对外暴露的域名**(可带 `:端口`,非 80 端口会成为监听端口)与**网站根目录**(绝对路径,目录不存在会自动创建;也可指向已有前端目录)。
|
||||||
|
3. 确认 Nginx/Apache 已安装(静态站依赖 web 服务)。
|
||||||
|
|
||||||
|
## Step 1 —— 调用创建
|
||||||
|
`HtmlProjectCreate(domains=[...], path=...)`:
|
||||||
|
- **必填**:`domains`(list,首项为主域名,如 `'example.com'` 或 `'example.com:8080'`)、`path`(网站根目录绝对路径,如 `/www/wwwroot/demo.example.com`)。
|
||||||
|
- **可选**:`ps`(备注)、`type_id`(项目分类,默认 0)。
|
||||||
|
|
||||||
|
> 返回"创建成功"= 已写 nginx/apache 配置 + 建目录 + 放行端口 + 重载。`site_name_hint` 仅供参考。
|
||||||
|
|
||||||
|
## Step 2 —— 部署静态文件
|
||||||
|
1. 把前端构建产物(如 `dist/` 下文件)上传到站点根目录 `path`:
|
||||||
|
- 文件已在本机:用文件上传(PrepareUpload 分块上传)到站点目录,或用 filesystem 移动。
|
||||||
|
- 远端构建:先下载到本机再上传,或直接把站点 `path` 指到已有构建目录。
|
||||||
|
2. 确认 `index.html` 已在根目录(或运行目录,见场景二 set_run_path)。
|
||||||
|
|
||||||
|
## Step 3 —— 验证(强制)
|
||||||
|
1. `HtmlProjectInfo`(site_name 留空)确认站点出现,记下真实 `name`。
|
||||||
|
2. `HtmlProjectInfo(site_name=...)` 看域名/路径/SSL。
|
||||||
|
3. 访问域名验证首页正常返回。
|
||||||
|
|
||||||
|
- 全通过 → 按"完成汇报"收尾。
|
||||||
|
- 访问异常 → 转场景三排错。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景二:配置编辑(伪静态 rewrite / 主 conf)
|
||||||
|
|
||||||
|
## Step 0 —— 拿基线与现状
|
||||||
|
1. `HtmlProjectInfo(site_name=...)`:拿到 `rewrite_file`(伪静态/自定义入口)、`config_file`(nginx 主 conf)、`apache_config_file` 路径,以及当前域名/路径/运行目录。
|
||||||
|
2. filesystem `Read` `rewrite_file` 与 `config_file` 看当前配置。
|
||||||
|
|
||||||
|
## Step 1 —— 改配置(优先 rewrite 文件)
|
||||||
|
按「常用静态站点 nginx 配置速查」(见文末)在 **rewrite 文件**里加/改规则。常见操作:
|
||||||
|
- **SPA 路由重写**(刷新子路由 404):`location / { try_files $uri $uri/ /index.html; }`。
|
||||||
|
- **自定义 location**:如 `location /api { proxy_pass http://127.0.0.1:9000; ... }`(把某路径转发到后端)。
|
||||||
|
- **静态资源缓存**:`location ~* \.(js|css|png|jpg|svg|woff2)$ { expires 30d; add_header Cache-Control "public, max-age=2592000"; }`。
|
||||||
|
- **开启 gzip**:`gzip on; gzip_types text/css application/javascript image/svg+xml;`。
|
||||||
|
|
||||||
|
> 只有确实要改 `listen` / `root` / `server_name` 之外的 server 层配置才动**主 conf**:filesystem `Read` `config_file` 留基线 → 改 → filesystem `Write` 回写。**改主 conf 前必须 Read**,写坏可恢复。
|
||||||
|
|
||||||
|
## Step 2 —— 回传并验证
|
||||||
|
1. filesystem `Write` 回写修改后的文件(rewrite 或主 conf)。
|
||||||
|
2. `Bash` 执行 `nginx -t` 确认配置语法通过;失败按报错行修文件重写。
|
||||||
|
3. `Bash` `nginx -s reload`(如有需要)让新配置生效。
|
||||||
|
4. 访问验证(如有域名):确认新规则生效、旧规则仍在。
|
||||||
|
|
||||||
|
- 配置写坏导致站点异常 → 用 Read 留的基线恢复重写;主 conf 被面板覆盖 → 用 `HtmlProjectModify(action='change_path'/'set_run_path')` 走面板。
|
||||||
|
|
||||||
|
## Step 3 —— 面板操作走 Modify(域名/路径/启停/运行目录)
|
||||||
|
| 需求 | 调用 |
|
||||||
|
|---|---|
|
||||||
|
| 加域名 | `HtmlProjectModify(site_name, action='add_domain', domains=['www.example.com'])` |
|
||||||
|
| 删域名 | `HtmlProjectModify(site_name, action='remove_domain', domain='www.example.com')` |
|
||||||
|
| 启/停/重启 | `HtmlProjectModify(site_name, action='start'/'stop'/'restart')` |
|
||||||
|
| 改网站根目录 | `HtmlProjectModify(site_name, action='change_path', path='/www/wwwroot/new')`(**目标目录必须已存在**) |
|
||||||
|
| 设运行目录(子目录) | `HtmlProjectModify(site_name, action='set_run_path', run_path='/dist')` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景三:静态站点访问异常排错
|
||||||
|
|
||||||
|
## Step 0 —— 只读侦察(不盲改)
|
||||||
|
1. `HtmlProjectInfo` 确认项目存在、域名/路径/运行目录现状。
|
||||||
|
2. `Bash` 读 nginx 错误日志 `/www/wwwlogs/<name>.error.log` 与访问日志 `/www/wwwlogs/<name>.log` 尾部。
|
||||||
|
|
||||||
|
## Step 1 —— 按症状对号入座
|
||||||
|
|
||||||
|
| 症状 | 常见根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| **首页 404 / 空白** | 前端文件没传到根目录、`index.html` 缺失、运行目录不对 | 确认文件在站点根目录(或运行目录);`HtmlProjectModify(action='set_run_path', run_path=...)` 指到实际构建目录 |
|
||||||
|
| **子路由刷新 404(SPA)** | 没配 `try_files` 回退 index.html | 场景二在 rewrite 文件加 `location / { try_files $uri $uri/ /index.html; }` |
|
||||||
|
| **伪静态不生效** | rewrite 文件没写对/没 include、nginx 没重载 | `nginx -t` + `nginx -s reload`;确认 rewrite 文件语法 |
|
||||||
|
| **静态资源 404 / 403** | 目录权限不对、资源在子目录但 root 指错 | `Bash` `ls -la` 站点目录、`chown -R www:www` 站点目录 |
|
||||||
|
| **只对本机/内网生效** | 域名未绑定、非 80 端口防火墙未放行 | `HtmlProjectModify(action='add_domain')` 补域名;`Bash` 查防火墙端口放行状态 |
|
||||||
|
| **HTTPS 不生效** | 证书未部署(MCP 不封装 SSL) | 证书部署走面板,MCP 只读 ssl 状态 |
|
||||||
|
|
||||||
|
## Step 2 —— 修复与验证
|
||||||
|
1. 按上表定位根因,**改配置文件必须 filesystem Read 基线 → 改 → Write → `nginx -t`**,改域名/路径走 `HtmlProjectModify`。
|
||||||
|
2. 修复后重访验证;仍异常则回到 Step 0 换角度(读实时日志尾部 `tail -f`)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 运维速查
|
||||||
|
|
||||||
|
| 需求 | 调用 |
|
||||||
|
|---|---|
|
||||||
|
| 列表/找站点名 | `HtmlProjectInfo(search=..., page=...)`(site_name 留空) |
|
||||||
|
| 查看详情/域名/路径/conf 路径 | `HtmlProjectInfo(site_name=...)` |
|
||||||
|
| 创建静态项目 | `HtmlProjectCreate(domains=[...], path=...)` |
|
||||||
|
| 读/改伪静态(优先) | filesystem `Read`/`Write` `rewrite_file`(`/www/server/panel/vhost/rewrite/html_<name>.conf`) |
|
||||||
|
| 读/改 nginx 主 conf | filesystem `Read` 留基线 → 改 → `Write` `config_file`(`/www/server/panel/vhost/nginx/html_<name>.conf`) |
|
||||||
|
| 验证语法 | `Bash` `nginx -t` |
|
||||||
|
| 加删域名 / 启停 / 改目录 / 运行目录 | `HtmlProjectModify(site_name=..., action=..., ...)` |
|
||||||
|
| 删除项目 | `HtmlProjectDelete(site_name=...)`(高风险,确认后;不删站点目录,需删目录用文件系统工具) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 常用静态站点 nginx 配置格式与位置速查
|
||||||
|
|
||||||
|
**位置**:
|
||||||
|
- **rewrite 文件**(`/www/server/panel/vhost/rewrite/html_<name>.conf`):被 nginx 主 conf include 在 server 块内,**伪静态/自定义 location/缓存优先写这里**。
|
||||||
|
- **nginx 主 conf**(`/www/server/panel/vhost/nginx/html_<name>.conf`):完整 server 块(listen/server_name/root/ssl/日志/include),模板渲染产物。
|
||||||
|
|
||||||
|
**典型片段**(写进 rewrite 文件即可):
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
# SPA 单页应用:子路由刷新回退到 index.html(最常用)
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 静态资源缓存
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2|ico)$ {
|
||||||
|
expires 30d;
|
||||||
|
add_header Cache-Control "public, max-age=2592000";
|
||||||
|
}
|
||||||
|
|
||||||
|
# 自定义 location:把某路径转发到后端
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://127.0.0.1:9000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 开启 gzip 压缩(server 层,放 rewrite 文件顶部即可)
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
|
||||||
|
```
|
||||||
|
|
||||||
|
**规则**:
|
||||||
|
- `location / { try_files $uri $uri/ /index.html; }` 是 SPA(Vue/React 等 history 路由)部署后**必配**的伪静态规则,否则刷新子路由 404。
|
||||||
|
- 伪静态/缓存/自定义 location 一律写 rewrite 文件,**不改主 conf**;只有要动 listen/root/自定义 server 段才碰主 conf,且先 `Read` 留基线。
|
||||||
|
- 改完**必须** `nginx -t` 验证,再确认访问生效。
|
||||||
|
- 涉及域名/路径/运行目录的变更走 `HtmlProjectModify`,不要手改主 conf。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 完成汇报模板
|
||||||
|
|
||||||
|
汇报固定四段(每段 1-3 行,用一次工具查证一个结论,不堆 log):
|
||||||
|
|
||||||
|
- **现状**:静态项目 `<name>`,域名 `<域名:端口>`,网站根目录 `<path>`,状态(运行中/已停止)。
|
||||||
|
- **变更**:`<创建了静态项目 / 部署了前端文件到 <path> / 添加了 SPA try_files 伪静态 / 修改了网站根目录 / 启停了项目 / 绑定了域名>`。
|
||||||
|
- **验证**:`nginx -t` 通过 / `HtmlProjectInfo` 复查域名与路径 / 访问 `<域名>` 返回预期。
|
||||||
|
- **遗留**:`<若有:SSL 证书未部署需面板处理 / 后端服务未监听需确认>;否则无`。
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
---
|
||||||
|
name: BT-Java-Project-Deploy
|
||||||
|
description: >
|
||||||
|
在宝塔面板上部署 Java jar 项目(Spring Boot),并在项目启动失败时排错。
|
||||||
|
当用户要求把本机已有的 jar 包部署成面板可管理的 Java 项目(含 JDK、Nginx 代理/域名),
|
||||||
|
或 Java 项目启动失败/访问异常需要排查根因时使用。
|
||||||
|
触发关键词:部署 Java、jar 包部署、Spring Boot 部署、Java 项目创建、
|
||||||
|
Java 项目启动失败、jar 起不来、jar 启动报错、502、访问异常、JDK 版本不匹配。
|
||||||
|
日常的启停/状态/日志/改配置等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||||
|
---
|
||||||
|
|
||||||
|
# Java 项目部署与启动排错 SOP
|
||||||
|
|
||||||
|
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||||
|
> 本 SOP 只覆盖两个主场景:**① 部署 Java 项目;② 项目启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、删除)不做 SOP,直接使用工具。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **先只读侦察,再执行变更** —— 部署前必须完成 jar 分析;排错先读日志,不盲目重启。
|
||||||
|
2. **创建后必须验证启动** —— "创建成功"不算完,必须确认进程存活 + 监听端口 + 日志无致命错误;验证失败即转入场景二。
|
||||||
|
3. **删除项目属高风险**,必须先获得用户明确确认;启停/重启/改配置属中风险,操作前说明影响。
|
||||||
|
4. **JDK 匹配** —— Spring Boot 3.x 需 JDK 17+,Boot 2.x 需 JDK 8/11;安装或切换前先检测本机 JDK。
|
||||||
|
5. **端口唯一性** —— 创建/改端口前检查占用。
|
||||||
|
6. **域名可访问 = 三件事** —— ① `add_domain` 写入 `server_name`;② `bind_extranet` 开启外网框架(生成 conf 骨架,**不含反代**);③ `add_proxy(proxy_port=应用端口)` 真正注入 `proxy_pass http://127.0.0.1:port`。**漏掉 ③ 会访问 403**。创建时带 `domains` 会完成 ①② 并尝试自动建 ③,但**必须验证**(`proxy_list` 或 grep `proxy_pass`),缺失即补 `add_proxy`。
|
||||||
|
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||||
|
8. **禁止操作**:删除 jar 源文件、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景一:部署 Java 项目
|
||||||
|
|
||||||
|
## Step 0 —— 预检
|
||||||
|
1. 确认任务确为"部署新 Java 项目"(非排错/运维)。
|
||||||
|
2. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||||
|
3. (可用 todo 工具时)建任务列表:定位 jar → 分析 → JDK → 创建 → 验证。
|
||||||
|
|
||||||
|
## Step 1 —— 定位 jar 包
|
||||||
|
- 用户直接给出 jar 绝对路径,或:
|
||||||
|
- 用文件工具 `Glob(pattern='**/*.jar')` / `LS(path=...)` 在服务器上定位 jar(排除运行目录与 `lib/` 依赖库)。
|
||||||
|
- **校验**:路径存在、是普通文件、非敏感目录(`/etc`、`/boot`、插件 `data/` 等)。
|
||||||
|
- 记录 jar 绝对路径与所在目录(jar_path)。
|
||||||
|
|
||||||
|
## Step 2 —— 分析 jar(部署前必须)
|
||||||
|
调用 `JavaProjectCreate(jar_path=..., analyze_only=true)`(只读,不创建)。返回:
|
||||||
|
1. 是否 Spring Boot 可执行 jar(jar_info)。
|
||||||
|
2. **应用端口**(`application.yml/properties` 的 `server.port`,或命令行/环境变量覆盖)。
|
||||||
|
3. 实际生效的配置文件路径与优先级(config_files)。
|
||||||
|
4. **启动前隐患清单**(tips:数据库/中间件连通性、账号密码疑似错误、profile 缺失等)。
|
||||||
|
|
||||||
|
**决策**:
|
||||||
|
- 解析不出端口 → 询问用户指定,并在创建时显式传 `port`。
|
||||||
|
- 隐患清单含阻断级(error)→ 向用户说明,确认是否继续。
|
||||||
|
|
||||||
|
## Step 3 —— JDK 确认 / 安装
|
||||||
|
1. `JavaJdk(action='list')` 检测本机 JDK(name/path/operation:0 未装 1 已装 2 系统 3 安装中)。
|
||||||
|
2. 按 Spring Boot 版本定所需 JDK(Boot3→17+,Boot2→8/11)。
|
||||||
|
3. 已有 → 记录 path;无 → 询问用户后 `JavaJdk(action='install', version=...)`(异步,用 list 轮询 operation=3→1)。
|
||||||
|
|
||||||
|
## Step 4 —— 创建项目(注册)
|
||||||
|
调用 `JavaProjectCreate(project_name=..., jar_path=..., port=..., [domains=...])`。
|
||||||
|
创建前确认参数:`project_name`(1-20 字符、不重复)、jar 路径、JDK 路径(缺省自动选已装)、`run_user`(默认 www)、端口(**检查未被占用**)、启动命令(缺省自动拼 `{jdk}/bin/java -jar ... --server.port=<port>`)。
|
||||||
|
**外网映射决策**:
|
||||||
|
- 要域名访问 → `domains=['域名']`(或 `['域名:端口']`),创建时绑定域名并开启外网框架(`server_name`)。创建工具会**尝试**自动建反代(`proxy_path` 默认 `'/'` 全站,可改如 `'/api'`;`proxy_path=''` 关闭)。
|
||||||
|
**创建后必须验证反代已注入**:`JavaProjectModify(action='proxy_list')` 应有 `proxy_port`,或 grep `proxy_pass` `java_<name>.conf`。缺失 → `JavaProjectModify(action='add_proxy', proxy_port=应用端口, proxy_dir='/')` 补齐,否则访问 403。
|
||||||
|
- 仅本机 → 不传 domains(`bind_extranet=0`)。
|
||||||
|
|
||||||
|
## Step 5 —— 启动验证(强制)
|
||||||
|
创建后调用 `JavaProjectInfo(project_name=...)` 依次确认:
|
||||||
|
1. 进程存活(有 pid)。
|
||||||
|
2. 应用端口在 `listen` 列表。
|
||||||
|
3. 用返回的 `log_files` 里的应用日志路径,调 filesystem `Read` 看尾部无致命异常(`Exception`/`Caused by`)。
|
||||||
|
- 全通过 → 按"完成汇报"收尾。
|
||||||
|
- 任一失败 → **转场景二排错**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景二:项目启动排错
|
||||||
|
|
||||||
|
> 适用:部署后验证失败、或用户报"Java 项目启动失败/访问异常"。
|
||||||
|
|
||||||
|
## Step 0 —— 快速定位现状(只读)
|
||||||
|
并行收集 3 项,不跳过:
|
||||||
|
1. `JavaProjectInfo(project_name=...)`:pid 是否生成、`listen` 端口、运行态(区分"进程没起来"与"进程起来了但访问不了")。
|
||||||
|
2. 读应用日志尾部:用返回的 `log_files` 应用日志路径调 filesystem `Read`,找异常堆栈根因。
|
||||||
|
3. 已知配置:jar 路径、JDK、端口、启动命令。
|
||||||
|
|
||||||
|
收集后按症状进分支。
|
||||||
|
|
||||||
|
## 分支 A —— 启动失败(进程起不来 / pid 无 / 端口未监听)
|
||||||
|
按日志根因对号入座:
|
||||||
|
| 日志特征 | 根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| `Address already in use` / 端口占用 | 端口被占 | 换端口:`JavaProjectModify(action='config', project_cmd=改 --server.port=)` 或重建 |
|
||||||
|
| `UnsupportedClassVersionError` | JDK 版本过低/过高 | `JavaProjectModify(action='config', project_jdk=匹配JDK)` 或 `JavaJdk(action='install', version=...)` |
|
||||||
|
| `ClassNotFoundException` / 缺依赖 | 依赖库缺失 | 检查启动命令 `-Dloader.path` 与 lib 目录,改 `project_cmd` |
|
||||||
|
| 数据库/中间件连接失败 | 服务未起或账号密码错 | 结合 Step 2 的 tips,确认中间件与账号 |
|
||||||
|
| 配置缺失 / 环境变量 | 缺配置 | 改 `project_cmd`/`env_file` 补配置后重启 |
|
||||||
|
|
||||||
|
- 无明确报错 → 查 `JavaProjectInfo`:pid 是否生成、端口是否监听、启动命令是否完整。
|
||||||
|
- 修复后回到场景一 Step 5 重新验证。
|
||||||
|
|
||||||
|
## 分支 B —— 访问异常(502 / 无法访问,但进程活着)
|
||||||
|
1. `JavaProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 A。
|
||||||
|
2. **nginx 反代目标匹配**:用 `log_files` 或 `JavaProjectInfo` 定位 `java_<name>.conf`,调 filesystem `Read` 看 `proxy_pass` 是否指向 `127.0.0.1:实际端口`。
|
||||||
|
- 配置里**没有** `proxy_pass` location(`project_config.proxy_info` 为空)→ 反代缺失,用 `JavaProjectModify(action='add_proxy', proxy_port=实际端口, proxy_dir='/')` 补齐,`action='proxy_list'` 核对。
|
||||||
|
- 端口改了但反代没同步 → `JavaProjectModify(action='add_proxy', proxy_port=新端口)` 或改配置重建。
|
||||||
|
3. **反代是否真注入**:`JavaProjectModify(action='proxy_list')` 看有无 `proxy_port`;`grep proxy_pass /www/server/panel/vhost/nginx/java_<name>.conf`。`bind_extranet` 为开但 `proxy_pass` 为空 → 漏了 `add_proxy`,用 `action='add_proxy', proxy_port=实际端口` 补。
|
||||||
|
4. **外网绑定状态**:`bind_extranet` 是否为开;域名是否在 nginx `server_name`(未开 → `JavaProjectModify(action='bind_extranet')`)。
|
||||||
|
5. 读 nginx error log(`log_files` 里的路径)进一步定位。
|
||||||
|
6. 修正后验证。
|
||||||
|
|
||||||
|
## 分支 C —— 进程在但无响应 / 卡死
|
||||||
|
1. 应用日志尾部看异常/死锁(filesystem `Read`)。
|
||||||
|
2. `SystemInfo()` 看系统资源(CPU/内存/负载)是否异常。
|
||||||
|
3. 汇报,建议用户确认后 `JavaProjectControl(action='restart')` 重启。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||||
|
|
||||||
|
| 需求 | 工具 |
|
||||||
|
|---|---|
|
||||||
|
| 查看项目列表/状态 | `JavaProjectInfo()`(project_name 留空) |
|
||||||
|
| 查看单项目详情(含日志路径) | `JavaProjectInfo(project_name=...)` |
|
||||||
|
| 启动 / 停止 / 重启 | `JavaProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||||
|
| 看应用日志 / nginx 日志 | `JavaProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||||
|
| 加域名 / 删域名(至少留一个) | `JavaProjectModify(action='add_domain'/'remove_domain', domains=[...])` |
|
||||||
|
| 开/关外网框架(只生成 server_name 骨架,**不注入反代**) | `JavaProjectModify(action='bind_extranet'/'unbind_extranet')` |
|
||||||
|
| 增反代(真正注入 proxy_pass) | `JavaProjectModify(action='add_proxy', proxy_port=应用端口, proxy_dir='/')` |
|
||||||
|
| 删反代 | `JavaProjectModify(action='remove_proxy', proxy_id=...)`(id 用 proxy_list 取) |
|
||||||
|
| 查反代 | `JavaProjectModify(action='proxy_list')` |
|
||||||
|
| 改 jar / JDK / 启动命令 / 运行用户 / 守护 | `JavaProjectModify(action='config', ...)`(重启生效) |
|
||||||
|
| 删除项目(**高风险,先确认**) | `JavaProjectDelete(project_name=...)`(保留 jar) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 完成汇报模板(部署成功)
|
||||||
|
|
||||||
|
返回:项目名 / jar 路径 / 运行用户 / JDK 路径 / 监听端口;若绑域名:访问地址 + nginx 配置路径;应用日志路径;启动验证结果(进程/端口/日志);遗留隐患提示(若有)。
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
---
|
||||||
|
name: BT-Node-Project-Deploy
|
||||||
|
description: >
|
||||||
|
在宝塔面板上部署 Node.js 项目(nodejs/general/pm2 三种类型,含 Nginx 域名/反代),
|
||||||
|
并在项目启动失败或访问异常时排错。
|
||||||
|
当用户要求把本机已有的 Node 项目目录部署成面板可管理的项目(含 node 版本、依赖安装、
|
||||||
|
Nginx 代理/域名、pm2 守护),或 Node 项目启动失败/访问异常需要排查根因时使用。
|
||||||
|
触发关键词:部署 Node、Node 项目部署、nodejs 部署、npm 项目部署、PM2 部署、
|
||||||
|
Node 项目启动失败、npm 起不来、Node 报错、502、访问异常、pm2 errored、Cannot find module。
|
||||||
|
日常的启停/状态/日志/改配置等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||||
|
---
|
||||||
|
|
||||||
|
# Node.js 项目部署与启动排错 SOP
|
||||||
|
|
||||||
|
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||||
|
> 本 SOP 只覆盖两个主场景:**① 部署 Node 项目;② 启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、删除)不做 SOP,直接使用工具。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **先只读侦察,再执行变更** —— 部署前必须完成项目分析;排错先读日志,不盲目重启。
|
||||||
|
2. **创建后必须验证启动** —— "创建成功"不算完,必须确认进程存活 + 监听端口 + 日志无致命错误;验证失败即转入场景二。
|
||||||
|
3. **删除项目属高风险**,必须先获得用户明确确认;启停/重启/改配置属中风险,操作前说明影响。
|
||||||
|
4. **Node 版本匹配** —— 创建前用 `NodeVersion(action='list')` 检测已装版本;`package.json` 的 `engines.node` 不符时优先换已装版本或安装。
|
||||||
|
5. **端口唯一性** —— 创建/改端口前检查占用;**绑外网必须有端口**(`bind_extranet` 依赖 `port`)。
|
||||||
|
6. **绑域名 = 自动反代** —— Node 的反代由 nginx 模板按 `project_config.port` 自动生成(`proxy_pass http://127.0.0.1:{port}`),**无独立反代步骤**。访问异常时核对:`NodeProjectInfo` 的 `listen`(实际监听端口)vs 配置端口(反代目标)是否一致,不一致 = 502。
|
||||||
|
7. **依赖先行** —— nodejs 类型缺 `node_modules` 启动必失败。创建时 `install_deps=true` 或创建后装依赖再启动。
|
||||||
|
8. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||||
|
9. **禁止操作**:删除项目目录/源码、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景一:部署 Node 项目
|
||||||
|
|
||||||
|
## Step 0 —— 预检
|
||||||
|
1. 确认任务确为"部署新 Node 项目"(非排错/运维)。
|
||||||
|
2. 确定**项目类型**:`nodejs`(package.json scripts)/ `general`(直接指定启动文件)/ `pm2`(守护+cluster+自愈)。
|
||||||
|
3. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||||
|
|
||||||
|
## Step 1 —— 定位项目目录
|
||||||
|
- 用户给出 `project_cwd`(项目根,含 package.json),或:
|
||||||
|
- 用文件工具 `Glob(pattern='**/package.json')` / `LS(path=...)` 定位(排除 `node_modules`、`dist`、`build` 等构建目录)。
|
||||||
|
- **校验**:目录存在、含 `package.json`(nodejs/pm2 必需;general 可没有)、非敏感目录(`/etc`、`/boot`、插件 `data/` 等)。
|
||||||
|
|
||||||
|
## Step 2 —— 分析项目(部署前必须)
|
||||||
|
调用 `NodeProjectCreate(project_cwd=..., analyze_only=true)`(只读,不创建)。返回:
|
||||||
|
1. `package.json` 的 `name/version`、`engines.node`、`dependencies` 数量。
|
||||||
|
2. `scripts` 启动项列表(nodejs 类型的 `project_script` 从这里选)。
|
||||||
|
3. `node_modules` 是否存在(缺 → 需先装依赖)。
|
||||||
|
4. `port`/`port_hints`:从入口文件启发式探测的端口(仅供参考)。
|
||||||
|
|
||||||
|
**决策**:
|
||||||
|
- nodejs 类型:确认启动脚本名(`start`/`dev`/自定义),即 `project_script`。
|
||||||
|
- pm2 类型:确认入口文件(js 或 ecosystem 配置)与 `cluster` 实例数。
|
||||||
|
- 无端口或启发式不准 → 询问用户,创建时显式传 `port`(绑外网必需)。
|
||||||
|
|
||||||
|
## Step 3 —— Node 版本确认 / 安装
|
||||||
|
1. `NodeVersion(action='list')` 检测已装版本与可用包管理器(npm/yarn/pnpm)。
|
||||||
|
2. 若返回 `plugin_installed=false`:nodejs 版本管理器插件未装,**先调 `SoftwareInstall(name='nodejs')` 安装插件**(可再用 `SoftwareList(name='nodejs')` 查进度),装完继续。
|
||||||
|
3. 需要新装版本时,用 `NodeVersion(action='online', lts_only=true, page=...)` 浏览可安装版本(按版本从新到旧排序、本地分页,`lts_only=false` 看全部;每项 `installed` 标记是否已装),从中挑选稳定版。
|
||||||
|
4. 对照 `engines.node`(无则默认 LTS)。
|
||||||
|
5. 已装 → 记录版本号(如 `v20.15.0`);无 → 询问用户后 `NodeVersion(action='install', version=..., install_pm2=<pm2 类型时 true>)`(插件安装,较慢,装完用 list 确认)。
|
||||||
|
|
||||||
|
## Step 4 —— 创建项目(注册)
|
||||||
|
调用 `NodeProjectCreate(project_type=..., project_name=..., project_cwd=..., nodejs_version=..., ...)`。
|
||||||
|
按类型传参:
|
||||||
|
- **nodejs**:`project_script`(scripts key,如 `'start'`)、`pkg_manager`(npm/yarn/pnpm)。
|
||||||
|
- **general**:`project_file`(启动文件绝对路径)、`project_args`(可选)。**同时必须传 `nodejs_version`**(三类型均必填、须已安装——general 漏传会直接报错,不是可选项)。
|
||||||
|
- **pm2**:`project_file`(js 入口或 ecosystem 配置,内容检测自动路由)、`cluster`、`watch`、`max_memory_limit`。**pm2 类型项目启动依赖该 node 版本已全局安装 pm2**——创建工具会自动检测,该版本缺 pm2 时自动调插件安装(结果 `data.pm2_auto_installed` 标记);也可手动 `NodeVersion(action='module', version=<nodejs_version>, modules=['pm2'])`。
|
||||||
|
- **通用**:`port`(绑外网必需)、`run_user`(默认 www)、`env`(**注意:面板对 nodejs 类型的 env 注入有缺陷——存了但不写进启动脚本,需要环境变量的项目建议用 general 类型**)、`install_deps`(package.json 有依赖且未装 node_modules 时给 true)、`release_firewall`(需放行端口时)、`domains=['域名']`(绑域名+自动反代)。
|
||||||
|
|
||||||
|
**外网映射**:要域名访问 → 传 `domains`(自动写 `server_name` + `proxy_pass 127.0.0.1:{port}`,**无需额外反代步骤**)。`install_deps=true` 较慢(npm install),可接受等待。
|
||||||
|
|
||||||
|
## Step 5 —— 启动验证(强制)
|
||||||
|
创建后调用 `NodeProjectInfo(project_name=...)` 依次确认:
|
||||||
|
1. 进程存活(`run=true`)。
|
||||||
|
2. 应用端口在 `listen` 列表(`listen_ok=true`)。
|
||||||
|
3. 用返回的 `log_files` 里应用日志路径,调 filesystem `Read` 看尾部无致命异常(`Cannot find module`/`EADDRINUSE`/`throw er`)。
|
||||||
|
|
||||||
|
⚠️ **pm2 类型不要信创建返回的「已自动启动」**:daemon 可能未持久化(`run:false`、`listen` 空但 `listen_ok=true`)。创建后必须:
|
||||||
|
① 立即 `NodeProjectInfo` 核验 `run=true`;
|
||||||
|
② 间隔几秒**再次** `NodeProjectInfo` 复检持久化(本地等待即可,不调长工具);
|
||||||
|
③ 不持久 → `NodeProjectControl(action='start')` 重拉再复检。
|
||||||
|
|
||||||
|
- 全通过 → 按"完成汇报"收尾。
|
||||||
|
- 任一失败 → **转场景二排错**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景二:启动排错
|
||||||
|
|
||||||
|
> 适用:部署后验证失败、或用户报"Node 项目启动失败/访问异常"。
|
||||||
|
|
||||||
|
## Step 0 —— 快速定位现状(只读)
|
||||||
|
并行收集,不跳过:
|
||||||
|
1. `NodeProjectInfo(project_name=...)`:`run`、`listen`、`listen_ok`(区分"进程没起来"与"起来了但访问不了");pm2 项目看状态。
|
||||||
|
2. 读应用日志尾部:用返回的 `log_files` 应用日志路径调 filesystem `Read`,找异常堆栈根因。
|
||||||
|
3. 已知配置:项目类型、入口/脚本、node 版本、端口、是否已装依赖。
|
||||||
|
|
||||||
|
收集后按症状进分支。
|
||||||
|
|
||||||
|
## 分支 A —— 启动失败(进程起不来 / run=false)
|
||||||
|
按日志根因对号入座:
|
||||||
|
| 日志特征 | 根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| `Error: Cannot find module 'x'` | 依赖未安装 | `NodeProjectCreate(project_cwd=<项目目录>, nodejs_version=..., project_script=..., install_deps=true)` 或装依赖后重启 |
|
||||||
|
| `EADDRINUSE` / `Port 3000 is already in use` | 端口被占 | `NodeProjectModify(action='config', port=新端口)` 后 `NodeProjectControl(action='restart')` |
|
||||||
|
| `npm ERR! Missing script: "start"` | scripts key 名错 | `NodeProjectModify(action='config', project_script=正确key)` |
|
||||||
|
| `throw er; Unhandled 'error' event` | 启动即崩(端口/环境) | 看堆栈中具体原因;换端口或补 env |
|
||||||
|
| `ERR_REQUIRE_ESM` / 语法错误 | 模块系统/代码问题 | 检查入口与 `package.json` 的 `type` 字段 |
|
||||||
|
| node 版本引擎不符 | `engines.node` 不匹配 | `NodeProjectModify(action='config', nodejs_version=匹配版本)` 或 `NodeVersion(action='install')` |
|
||||||
|
| 进程起来但 pid 无/端口没监听 | 启动后立即退出 | 读日志尾找 `exit`/`Error` 根因 |
|
||||||
|
|
||||||
|
- 无明确报错 → 查 `NodeProjectInfo`:run、listen、启动命令是否完整;`log_files` 有无 pm2 err.log。
|
||||||
|
- 修复后回到场景一 Step 5 重新验证。
|
||||||
|
|
||||||
|
## 分支 B —— 访问异常(502/无法访问,但进程活着)
|
||||||
|
1. `NodeProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 A。
|
||||||
|
2. **反代端口匹配**:看 `listen`(实际监听)vs `project_config.port`(反代目标)是否一致;grep `proxy_pass` `node_<name>.conf`(`/www/server/panel/vhost/nginx/node_<name>.conf`)确认反代指向 `127.0.0.1:{实际端口}`。
|
||||||
|
- 端口改了没同步 → `NodeProjectModify(action='config', port=实际端口)`(有 domains 时自动重写反代)。
|
||||||
|
- 反代指向错误端口 → 同上。
|
||||||
|
3. **域名绑定**:`bind_extranet` 是否开、域名是否在 nginx `server_name`(未绑 → `NodeProjectModify(action='add_domain', domains=[...])`)。
|
||||||
|
4. 读 nginx error log(`log_files` 里 `/www/wwwlogs/<name>.error.log`)进一步定位。
|
||||||
|
5. 修正后验证。
|
||||||
|
|
||||||
|
## 分支 C —— PM2 项目异常
|
||||||
|
1. `NodeProjectInfo` 看 pm2 状态(online/stopped/errored)。
|
||||||
|
2. `errored`(崩溃超限)→ 读 `log_files` 里 pm2 `err.log` 找根因;修复后用 `NodeProjectControl(action='restart')` 重启。
|
||||||
|
3. 读 `/www/wwwlogs/pm2/<name>/out.log|err.log`。
|
||||||
|
4. 依赖问题 → 同分支 A。
|
||||||
|
|
||||||
|
## 分支 D —— 进程在但无响应 / 卡死
|
||||||
|
1. 应用日志尾部看异常/死锁(filesystem `Read`)。
|
||||||
|
2. `SystemInfo()` 看系统资源(CPU/内存/负载)。
|
||||||
|
3. 汇报,建议用户确认后 `NodeProjectControl(action='restart')` 重启。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||||
|
|
||||||
|
| 需求 | 工具 |
|
||||||
|
|---|---|
|
||||||
|
| 查看项目列表/状态 | `NodeProjectInfo()`(project_name 留空) |
|
||||||
|
| 查看单项目详情(含日志路径) | `NodeProjectInfo(project_name=...)` |
|
||||||
|
| 启动 / 停止 / 重启 | `NodeProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||||
|
| 看应用日志 / pm2 / nginx 日志 | `NodeProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||||
|
| 改脚本/参数/node 版本/端口/用户/环境/内存 | `NodeProjectModify(action='config', ...)`(重启生效) |
|
||||||
|
| 加域名 / 删域名(至少留一个) | `NodeProjectModify(action='add_domain'/'remove_domain', domains=[...])` |
|
||||||
|
| node 版本检测 / 在线浏览 / 安装 | `NodeVersion(action='list'/'online'/'install', ...)` |
|
||||||
|
| 给 node 版本装全局模块(pm2/pnpm/yarn 等) | `NodeVersion(action='module', version=<nodejs_version>, modules=['pm2'])` |
|
||||||
|
| 删除项目(**高风险,先确认**) | `NodeProjectDelete(project_name=...)`(保留目录源码) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 完成汇报模板(部署成功)
|
||||||
|
|
||||||
|
返回:项目名 / 项目类型 / 目录 / node 版本 / 运行用户 / 监听端口;若绑域名:访问地址 + nginx 配置路径;应用日志路径;启动验证结果(进程/端口/日志);遗留隐患提示(依赖未装、env 未注入等)。
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
---
|
||||||
|
name: BT-Python-Project-Deploy
|
||||||
|
description: >
|
||||||
|
在宝塔面板上部署 Python 项目(uwsgi/gunicorn/command 三种运行方式,含虚拟环境配置、
|
||||||
|
Python 版本安装、requirements 依赖、Nginx 域名/反代),并在环境准备或启动失败时排错。
|
||||||
|
当用户要求把本机已有的 Python 项目目录部署成面板可管理的项目(含 Python 版本安装、
|
||||||
|
虚拟环境创建、pip 依赖、uwsgi/gunicorn 托管或自定义命令启动),或 Python 项目
|
||||||
|
启动失败/访问异常/环境准备失败需要排查根因时使用。
|
||||||
|
触发关键词:部署 Python、Python 项目部署、django/flask/fastapi/sanic 部署、
|
||||||
|
uvicorn/gunicorn/uwsgi、虚拟环境 venv、pip install、Python 项目启动失败、
|
||||||
|
ImportError、ModuleNotFoundError、502、访问异常、celery、关联进程、requirements。
|
||||||
|
日常的启停/状态/日志/改配置/装包等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||||
|
---
|
||||||
|
|
||||||
|
# Python 项目部署与启动排错 SOP
|
||||||
|
|
||||||
|
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||||
|
> 本 SOP 只覆盖两个主场景:**① 部署 Python 项目;② 环境准备/启动排错**。其他简单操作(状态查看、启停、日志、域名、改配置、装包、删除)不做 SOP,直接使用工具。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **先只读侦察,再执行变更** —— 部署前必须完成项目分析;排错先读日志,不盲目重启。
|
||||||
|
2. **创建成功 ≠ 启动成功** —— Python 创建项目后环境准备(装依赖+生成启动脚本+尝试启动)是**后台异步**的。必须用 `PythonProjectInfo` 轮询 `prep_status` 到 `complete`,再核验进程存活 + 监听端口 + 日志无致命错误;`prep_status=failure` 立即转场景二。**这是本场景最容易栽的坑。**
|
||||||
|
3. **建项目前必须有虚拟环境** —— 面板要求 `python_bin` 是已托管的 venv/conda(`can_use_directly`)。部署顺序:版本 → 环境 → 项目。
|
||||||
|
4. **Python 版本安装走 Bash 后台** —— 源码编译极慢(10-30 分钟),不得用同步工具卡住;必须 `Bash(run_in_background=true)` + `BashStatus` 轮询。
|
||||||
|
5. **删除项目保留虚拟环境** —— venv 与项目非强绑定(可复用/共享),删除不删 venv(面板语义);如需移除单独用 `PythonEnv(action='remove')`。删除本身仍高风险(停进程/清配置/删记录),先确认。
|
||||||
|
6. **绑域名 = 外网映射 + 反代** —— `add_domain` 只写域名,需 `bind_extranet` 生成 nginx 配置(proxy 到 127.0.0.1:port);path→port 反代(`add_proxy`)**必须先开启外网映射**。
|
||||||
|
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||||
|
8. **禁止操作**:删除项目目录/源码、`rm -rf` 项目目录、修改宝塔/插件自身文件、读取插件 `data/` 凭据。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景一:部署 Python 项目
|
||||||
|
|
||||||
|
## Step 0 —— 预检
|
||||||
|
1. 确认任务确为"部署新 Python 项目"(非排错/运维)。
|
||||||
|
2. 确定**运行方式 `stype`**:`uwsgi` / `gunicorn` / `command`(直跑,python 文件方式已并入 command)。
|
||||||
|
3. 确认**协议**:`wsgi`(Flask/Django 传统)/ `asgi`(FastAPI/Sanic/uvicorn)。
|
||||||
|
4. 需要外网域名访问时,确认 Nginx 已安装;否则只能本机/内网访问。
|
||||||
|
|
||||||
|
## Step 1 —— 定位项目目录
|
||||||
|
- 用户给出 `project_path`(项目根,含 `*.py`),或:
|
||||||
|
- 用文件工具 `Glob(pattern='**/*.py')` / `LS(path=...)` 定位(排除 `node_modules`、`dist`、`.venv`、`venv` 等)。
|
||||||
|
- **校验**:目录存在、含入口 `*.py`(或 `requirements.txt`)、非敏感目录(`/etc`、`/boot`、插件 `data/` 等)。
|
||||||
|
|
||||||
|
## Step 2 —— 分析项目(部署前必须)
|
||||||
|
调用 `PythonProjectCreate(project_path=..., analyze_only=true)`(只读,不创建)。返回:
|
||||||
|
1. `framework`:django/flask/sanic/fastapi 等(按 requirement/入口代码识别)。
|
||||||
|
2. `runfile`:入口文件、`xsgi`(wsgi/asgi)、`call_app`(可调用对象名)。
|
||||||
|
3. `requirement_path`:requirements 文件(缺 → 需先补)。
|
||||||
|
4. `has_venv` / `port` / `port_hints`:目录是否自带 venv、启发式端口(仅供参考)。
|
||||||
|
|
||||||
|
**决策**:
|
||||||
|
- 选 `stype`:Django/Flask 传统 → `gunicorn`(或 `uwsgi`);FastAPI/Sanic → `gunicorn` + `xsgi='asgi'`;无框架/自写 socket → `command`(`project_cmd='{python_bin} -u {runfile} {parm}'`)。
|
||||||
|
- 确认 `rfile`(启动文件绝对路径)与 `call_app`(app/application,或自动探测)。
|
||||||
|
- 无端口或启发式不准 → 询问用户,创建时显式传 `port`(uwsgi/gunicorn 必填;command 可空)。
|
||||||
|
|
||||||
|
## Step 3 —— Python 版本确认 / 虚拟环境准备
|
||||||
|
1. `PythonVersion(action='list')` 查看已装 Python 版本与当前默认;返回含 `install_hint`。
|
||||||
|
2. 需要新版本时 `PythonVersion(action='online', ...)` 浏览可安装版本(每项含 `install_command`),**用 Bash 后台安装**:
|
||||||
|
- `Bash(command=<install_command>, run_in_background=true)` → 得到 `task_id`;
|
||||||
|
- `BashStatus(task_id, wait=true)` 轮询到完成(后台最长 30 分钟,超时强杀;若超时汇报并让用户决定重跑/换源)。
|
||||||
|
3. `PythonEnv(action='list')` 查看虚拟环境:找 `can_use_directly=true` 的 venv;若需新建,看每项 `source` 与顶层 `source_priority` 判断源优先级。
|
||||||
|
4. 没有可用 venv → `PythonEnv(action='create', venv_name=<项目名或自定义>, python_bin=<源环境bin>, ps=<备注>)` 创建,得到 `python_bin`(venv_path + python_bin)。创建较慢(venv + ensurepip),**创建成功返回后必须再跑一次 `PythonEnv(action='list')` 确认该 venv 出现在列表里且目录真实存在**——工具已规避面板 `create_venv_sync` 的"只写记录不建目录"假成功缺陷并做磁盘校验,但仍建议复核。
|
||||||
|
**源 python_bin 选择优先级(重要)**:① 面板安装的 Python 版本(`source=panel_installed`,如 `/www/server/pyporject_evn/versions/<ver>/bin/python`,**推荐**)→ ② 系统 Python(`source=system`,如 `/usr/bin/python3`,需有 venv/pip,缺则自动安装可能失败)→ ③ 面板自带 pyenv(`source=panel_pyenv`,`/www/server/panel/pyenv`——打包时移除过大量非必要文件,**不适合普通用户**,工具会直接拒绝)。优先用 `PythonVersion` 装好版本再作源。
|
||||||
|
|
||||||
|
## Step 4 —— 创建项目(注册)
|
||||||
|
调用 `PythonProjectCreate(project_name=..., project_path=..., python_bin=<第3步的venv>, stype=..., ...)`。
|
||||||
|
按类型传参:
|
||||||
|
- **uwsgi**:`rfile` + `call_app` + `port`(+ `processes`/`threads`)。
|
||||||
|
- **gunicorn**:`rfile` + `call_app` + `port`;FastAPI/Sanic 加 `xsgi='asgi'`。
|
||||||
|
- **command**:`project_cmd`(如 `'{python_bin} -u {runfile}'`,**占位符由工具替换为实际路径**),`port` 可留 0。
|
||||||
|
- **通用**:`user`(默认 root)、`env_list=[{"k","v"}]`(**必须 dict 格式**,如 `[{"k":"PORT","v":"9000"}]`,字符串 "K=V" 会被 schema 拒绝)、`env_file`、`requirement_path`(有则自动装依赖)、`auto_run`、`release_firewall`(需外网访问时 true)、`initialize`(可选初始化命令)。
|
||||||
|
创建返回 `prep_status=running`(或 complete/failure)+ `prep_log` 路径。
|
||||||
|
|
||||||
|
## Step 5 —— 环境准备等待 + 启动验证(强制)
|
||||||
|
1. `PythonProjectInfo(project_name=...)` 轮询 `prep_status`:**`running` → 等待后重查**(本地 sleep 即可,不调长工具);到 `complete` 继续,到 `failure` **立即转场景二分支 A**。
|
||||||
|
2. 核验启动:`run=true`、应用端口在 `listen` 列表。
|
||||||
|
3. 用返回的 `log_files` 里应用日志路径,调 filesystem `Read` 看尾部无致命异常(`ImportError`/`ModuleNotFoundError`/`Address already in use`/`Error: [Errno 98]`)。
|
||||||
|
4. 有域名映射的项目核验 `services`(关联进程)与反代。
|
||||||
|
|
||||||
|
- 全通过 → 按"完成汇报"收尾。
|
||||||
|
- 任一失败 → **转场景二排错**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景二:环境准备 / 启动排错
|
||||||
|
|
||||||
|
> 适用:部署后验证失败(prep_status=failure / run=false)、或用户报"Python 项目启动失败/访问异常"。
|
||||||
|
|
||||||
|
## Step 0 —— 快速定位现状(只读)
|
||||||
|
并行收集,不跳过:
|
||||||
|
1. `PythonProjectInfo(project_name=...)`:`prep_status`、`run`、`listen`、`log_files`(区分"环境没准备好 / 进程没起来 / 起来了但访问不了")。
|
||||||
|
2. 按症状读日志:`prep_status=failure` 读**环境准备日志**(`log_files` 里 "环境准备日志");`run=false` 读**应用日志**(`log_files` 里 stype 对应项:error.log / uwsgi.log / gunicorn_error.log)。
|
||||||
|
3. 已知配置:stype、入口文件、虚拟环境、端口、是否已装依赖。
|
||||||
|
|
||||||
|
收集后按症状进分支。
|
||||||
|
|
||||||
|
## 分支 A —— 环境准备失败(prep_status=failure)
|
||||||
|
- 读 `log_files` 里的"环境准备日志"(`/www/server/python_project/vhost/logs/<name>.log`)找根因:
|
||||||
|
| 日志特征 | 根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| `pip ... Could not find a version that satisfies` | 依赖源/包名错 | 换 pip 源或 `PythonEnv` 手动装对应包;`PythonProjectControl(action='restart')` 重拉 |
|
||||||
|
| `ImportError` / `ModuleNotFoundError: No module named 'x'` | 缺依赖 | `PythonEnv(action='package', python_bin=<env>, package_action='install', package_name='x')` 后重启 |
|
||||||
|
| `configure: error` / `make: *** Error`(装托管依赖失败) | 编译缺系统库 | 汇报,需安装系统依赖库后再 `re_prep_env` 或重建 |
|
||||||
|
| `uwsgi/gunicorn` 命令 not found | 托管依赖没装上 | 同上 |
|
||||||
|
- 修复后 `PythonProjectControl(action='restart')`(或 `action='start'`)重新拉取,回场景一 Step 5 复检。
|
||||||
|
|
||||||
|
## 分支 B —— 启动失败(进程起不来 / run=false,但 prep_status=complete)
|
||||||
|
按应用日志根因对号入座:
|
||||||
|
| 日志特征 | 根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| `ModuleNotFoundError` / `ImportError: No module named 'x'` | 依赖未装 | `PythonEnv(action='package', python_bin=..., package_action='install', package_name='x')` 后重启 |
|
||||||
|
| `Error: [Errno 98] Address already in use` | 端口被占 | `PythonProjectModify(action='config', port=新端口)` 后 `PythonProjectControl(action='restart')` |
|
||||||
|
| `[Errno 13] Permission denied` | 目录/日志权限 | `PythonProjectModify(action='config', user=<有权限用户>)` 或修目录属主 |
|
||||||
|
| `No module named 'app'` / `gunicorn.errors.HaltServer` | rfile/call_app 错 | `PythonProjectModify(action='config', rfile=/call_app=正确值)` |
|
||||||
|
| `Command '('...')' returned non-zero exit status` | command 命令本身失败 | 检查 `project_cmd` 与环境变量 |
|
||||||
|
| `django.core.exceptions.ImproperlyConfigured` | Django settings 问题 | 检查 env_list 里的 DJANGO_SETTINGS_MODULE 等 |
|
||||||
|
| 进程起来但 pid 无/端口没监听 | 启动后立即退出 | 读日志尾找 `Traceback` 根因 |
|
||||||
|
|
||||||
|
- 无明确报错 → 查 `PythonProjectInfo`:run、listen、启动脚本(`project_config`)是否完整。
|
||||||
|
- 修复后回场景一 Step 5 重新验证。
|
||||||
|
|
||||||
|
## 分支 C —— 访问异常(502/无法访问,但进程活着)
|
||||||
|
1. `PythonProjectInfo`:进程在跑、端口在听吗?→ 不在则回分支 B。
|
||||||
|
2. **映射/反代核对**:
|
||||||
|
- 域名是否绑定、`bind_extranet` 是否开启(未开启 → `PythonProjectModify(action='add_domain', domains=[...])` + `action='bind_extranet'`)。
|
||||||
|
- `listen`(实际监听端口)vs `project_config.port`(反代目标)是否一致;grep `proxy_pass` `python_<name>.conf`(`/www/server/panel/vhost/nginx/python_<name>.conf`)确认反代指向 `127.0.0.1:{实际端口}`。
|
||||||
|
- path→port 反代缺失/指错 → `PythonProjectModify(action='add_proxy', proxy_path='/', proxy_port=实际端口)`(**需已开启外网映射**)。
|
||||||
|
3. 读 nginx error log(`/www/wwwlogs/<name>.error.log`)进一步定位。
|
||||||
|
4. 修正后验证。
|
||||||
|
|
||||||
|
## 分支 D —— 关联进程异常(celery worker 等)
|
||||||
|
1. `PythonProjectService(project_name=..., action='list')` 看各服务 pid/ports(主服务 sid='main' 之外为关联进程)。
|
||||||
|
2. 某服务异常 → `action='log'`(`sid=...`)读服务日志;`action='start'/'stop'/'restart'`(`sid=...`)重拉。
|
||||||
|
3. 缺 celery → `PythonEnv(action='package', python_bin=..., package_action='install', package_name='celery')`。
|
||||||
|
4. 修正后 `action='list'` 复检 pid 存在。
|
||||||
|
|
||||||
|
## 分支 E —— 依赖问题(环境内包管理)
|
||||||
|
- `PythonEnv(action='package', python_bin=<虚拟环境>, package_action='list')` 看已装包。
|
||||||
|
- `package_action='install'`(`package_name` + 可选 `package_version` + 可选 `pip_source`)/ `package_action='uninstall'`(`package_name`)。安装慢,返回 `log_tail`。
|
||||||
|
- 修完回场景一 Step 5 验证。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 日常运维速查(简单操作,直接按工具描述调用)
|
||||||
|
|
||||||
|
| 需求 | 工具 |
|
||||||
|
|---|---|
|
||||||
|
| 查看项目列表/状态 | `PythonProjectInfo()`(project_name 留空) |
|
||||||
|
| 查看单项目详情(prep_status/run/listen/日志路径/服务) | `PythonProjectInfo(project_name=...)` |
|
||||||
|
| 启动 / 停止 / 重启(含关联进程) | `PythonProjectControl(project_name, action='start'/'stop'/'restart')` |
|
||||||
|
| 只启动 / 只停止主服务 | `PythonProjectControl(project_name, action='start_main'/'stop_main')` |
|
||||||
|
| 看应用 / 环境准备 / 服务日志 | `PythonProjectInfo` 返回 `log_files` → filesystem `Read` |
|
||||||
|
| 改端口/启动方式/入口/用户/环境变量/日志路径 | `PythonProjectModify(action='config', ...)`(重启生效) |
|
||||||
|
| 加 / 删域名、开 / 关外网映射、path→port 反代 | `PythonProjectModify(action='add_domain'/'remove_domain'/'bind_extranet'/'unbind_extranet'/'add_proxy', ...)` |
|
||||||
|
| Python 版本检测 / 在线浏览 / 移除 | `PythonVersion(action='list'/'online'/'remove', ...)` |
|
||||||
|
| **安装 Python 版本(编译慢,后台)** | `PythonVersion` online 取 `install_command` → `Bash(run_in_background=true)` + `BashStatus` 轮询 |
|
||||||
|
| 虚拟环境列表 / 创建 / 移除 / 设默认 | `PythonEnv(action='list'/'create'/'remove'/'set_default', ...)` |
|
||||||
|
| 环境内 pip 装 / 卸 / 列表 | `PythonEnv(action='package', python_bin=<env>, package_action='install'/'uninstall'/'list', ...)` |
|
||||||
|
| 关联进程列表 / 启停 / 日志 / **删除(先停再删)** | `PythonProjectService(project_name, action='list'/'start'/'stop'/'restart'/'log'/'remove', sid=...)` |
|
||||||
|
| 删除项目(**高风险,先确认**;保留虚拟环境,需删除用 `PythonEnv(action='remove')`) | `PythonProjectDelete(project_name=...)`(保留目录源码) |
|
||||||
|
|
||||||
|
> ⚠️ **remove_domain 注意**:面板移除域名会连带停止项目服务(主服务+协同服务,与是否剩最后一个域名无关,已实证、根因待定位)。工具**不自动恢复**(避免掩盖根因):移除后必须用 `PythonProjectInfo` 复核运行态,被停则手动 `PythonProjectControl(action='start')` 拉起。
|
||||||
|
> **add_domain 注意**:对已存在的域名面板返回"已存在"=实际已绑定/可访问,工具按逐域结果如实上报(非失败);只有格式错误等才报错。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 完成汇报模板(部署成功)
|
||||||
|
|
||||||
|
返回:项目名 / 运行方式(stype)/ 目录 / 虚拟环境 python_bin / 运行用户 / 监听端口;若绑域名:访问地址 + nginx 配置路径;环境准备状态(prep_status=complete)与启动验证结果(进程/端口/日志);关联进程清单;遗留隐患提示(依赖未装、requirements 缺失、env 未注入、端口启发不准等)。
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
---
|
||||||
|
name: BT-Reverse-Proxy
|
||||||
|
description: >
|
||||||
|
在宝塔面板上管理反向代理项目:创建反代站点(域名 + 目标上游)、查看/增删改 URL 级转发规则、
|
||||||
|
自由编辑 nginx 反代配置、改备注/启停/绑删域名/强制 HTTPS,并在反代访问异常(502/404/转发不生效)时排错。
|
||||||
|
当用户要求把某个域名/路径转发到后端服务(HTTP/HTTPS 或 unix socket),或反代站点访问异常需要排查时使用。
|
||||||
|
触发关键词:反向代理、反代、代理转发、proxy_pass、location 转发、域名转发到端口、nginx 反代配置、
|
||||||
|
反代 502、反代 404、转发不生效、BT-Reverse-Proxy。
|
||||||
|
日常的查看/启停/改备注等简单操作不依赖本 SOP,直接按工具描述调用即可。
|
||||||
|
---
|
||||||
|
|
||||||
|
# 反向代理项目运维 SOP
|
||||||
|
|
||||||
|
> **停止。执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> 本 Skill 的工具均指 bt_agent_mcp 插件暴露的 MCP 工具;同一能力在宝塔 AI 内置端可能有不同命名,按当前环境可用工具调用。
|
||||||
|
> 本 SOP 覆盖三个主场景:**① 创建反代项目;② 编辑/增删 URL 转发规则(自由配置);③ 反代访问异常排错**。其他简单操作(状态查看、启停、改备注、绑删域名、强制 HTTPS、删除)不做 SOP,直接使用工具。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **先只读侦察,再执行变更** —— 操作前先 `ProxyProjectInfo`(site_name 留空)列项目找到站点名(可能带 `_<端口>` 后缀),再 `ProxyProjectInfo(site_name=...)` 看当前规则/域名/端口/SSL;排错先读日志,不盲目重写配置。
|
||||||
|
2. **反代项目 = sites 行 + 反代 JSON** —— 真正的配置在 `/www/server/proxy_project/sites/<name>/<name>.json`(`proxy_info[]` 多条 URL 规则);nginx conf 由它渲染。**改配置必须走 MCP 工具**(ProxyWriteConfig),保持 JSON 与 nginx 同步。
|
||||||
|
3. **URL 规则增删改走自由配置** —— 不要期待 add/set/del_url_proxy 之类的工具(未提供)。改规则 = 读 conf → 改 location 块 → `ProxyWriteConfig` 回传完整 conf → `Bash` `nginx -t` 验证。**面板保存后会自动把 proxy_info/域名/端口同步回反代 JSON。**
|
||||||
|
4. **改配置三步走**:`ProxyProjectInfo` 拿 `config_file` 路径 → filesystem `Read` 读当前 conf 作基线 → 修改后 `ProxyWriteConfig(conf_data=<完整 conf>)` → `Bash` 执行 `nginx -t` 验证。**改前必须 Read 留基线**,写坏可恢复。
|
||||||
|
5. **域名增删走 `ProxyProjectModify`** —— 用 comMod 的方法(会同步反代 JSON);**不要用通用网站域名工具**(不更新反代 JSON,面板会不同步)。至少保留一个域名。
|
||||||
|
6. **创建即生效** —— `ProxyProjectCreate` 成功即写 nginx + 放行防火墙 + 重载服务;返回的 `site_name_hint` 是主域名小写形式,**实际站点名以 `ProxyProjectInfo` 列表返回的 name 为准**(非 80 端口会带 `_<端口>`)。
|
||||||
|
7. **每个任务最多调用 15 次工具**,超出后汇总当前发现并停止。
|
||||||
|
8. **禁止操作**:`rm -rf` 反代站点根目录外的路径、修改宝塔/插件自身文件、读取插件 `data/` 凭据、直接用 filesystem Write 覆盖反代 nginx conf(必须走 ProxyWriteConfig 保持 JSON 同步)。
|
||||||
|
9. **反代目标勿指向 bt_agent_mcp 自身端口**(`127.0.0.1:<MCP端口>`,默认 8765)——会把 MCP 服务暴露给该反代域名,且反代 conf 未设 `X-Real-IP` 时来源 IP 白名单会被绕过(仅剩 API Key 鉴权兜底)。**若工具返回 `data.warning` 说明代理目标指向 MCP 自身,须与用户确认意图**;确需经反代暴露 MCP,则在该 location 补 `proxy_set_header X-Real-IP $remote_addr;` 并把真实客户端 IP 加入白名单(`security.ip_allowlist`)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景一:创建反代项目
|
||||||
|
|
||||||
|
## Step 0 —— 预检
|
||||||
|
1. 确认任务确为"创建反向代理项目"。
|
||||||
|
2. 拿到**要对外暴露的域名**(可带 `:端口`,非 80 端口会成为监听端口)与**目标上游**(http/https URL 或 unix socket 路径)。
|
||||||
|
3. 确认 Nginx 已安装(反代只支持 nginx)。
|
||||||
|
|
||||||
|
## Step 1 —— 调用创建
|
||||||
|
`ProxyProjectCreate(domains=[...], proxy_pass=...)`:
|
||||||
|
- **必填**:`domains`(list,`'example.com'` 或 `'example.com:8080'`)、`proxy_pass`(`http://127.0.0.1:8080`、`https://api.example.com`,或 unix 时 `/tmp/app.sock`)。
|
||||||
|
- **可选**:`proxy_path`(默认 `/`,前缀)、`proxy_host`(默认 `$http_host`,转发 Host)、`proxy_type`(http/unix,默认 http)、`remark`。
|
||||||
|
|
||||||
|
> 返回"添加成功"= 已写 nginx conf + 放行端口 + 重载。`site_name_hint` 仅供参考。
|
||||||
|
|
||||||
|
## Step 2 —— 验证(强制)
|
||||||
|
1. `ProxyProjectInfo`(site_name 留空)确认站点出现,记下真实 `name`。
|
||||||
|
2. `ProxyProjectInfo(site_name=...)` 看 `config`(域名/端口/首条 proxy_info 的 proxy_pass 是否对上)。
|
||||||
|
3. 需要的话 filesystem `Read` conf 确认 `location { proxy_pass ... }` 已渲染。
|
||||||
|
|
||||||
|
- 全通过 → 按"完成汇报"收尾。
|
||||||
|
- 配置与预期不符 → 转场景二修正配置,或转场景三排错。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景二:编辑 / 增删 URL 转发规则(自由配置)
|
||||||
|
|
||||||
|
## Step 0 —— 拿基线与现状
|
||||||
|
1. `ProxyProjectInfo(site_name=...)`:拿到 `config_file` 路径(`/www/server/panel/vhost/nginx/<name>.conf`)、当前 `proxy_info`(每条 proxy_path/proxy_pass/proxy_host/websocket/超时)、域名与端口。
|
||||||
|
2. filesystem `Read` `config_file` 读当前完整 conf。
|
||||||
|
|
||||||
|
## Step 1 —— 修改 conf
|
||||||
|
按「常用 nginx 反代配置速查」(见文末)在 conf 里**增/删/改 location 块**(或 server/http 层配置)。常见操作:
|
||||||
|
- **加一条转发规则**:新增 `location /api { proxy_pass http://127.0.0.1:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }`。
|
||||||
|
- **改目标**:改对应 `location` 里的 `proxy_pass`(换后端端口/地址)。
|
||||||
|
- **删规则**:删掉对应 `location` 块。
|
||||||
|
- **改超时**:在 location 内加 `proxy_connect_timeout 60s; proxy_read_timeout 600s; proxy_send_timeout 600s;`。
|
||||||
|
- **开 WebSocket**:加 `proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";`(反代 JSON 的 websocket 默认支持)。
|
||||||
|
- **强制 HTTPS**:优先用 `ProxyProjectModify(action='force_https', force_https=true)`,不要手改 ssl 块。
|
||||||
|
|
||||||
|
> 注意:**location 的 proxy_pass 末尾不带 `;` 前不可跟变量**(`proxy_pass http://127.0.0.1:9000;` 可直接跟 URI 或不带 URI;用变量时必须 `resolver`)。简单场景直接写死目标即可。
|
||||||
|
|
||||||
|
## Step 2 —— 回传并验证
|
||||||
|
1. `ProxyWriteConfig(site_name=..., conf_data=<修改后的完整 conf>)` → 面板写 conf 并自动同步反代 JSON。
|
||||||
|
2. `Bash` 执行 `nginx -t` 确认配置语法通过;失败按报错行修 conf 重存。
|
||||||
|
3. `ProxyProjectInfo` 复查 `proxy_info` 已同步新规则。
|
||||||
|
4. 访问验证(如有域名):确认新规则生效、旧规则仍在。
|
||||||
|
|
||||||
|
- 配置写坏导致站点异常 → 用 Read 留的基线恢复后 `ProxyWriteConfig` 重存,或面板历史版本回滚。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 场景三:反代访问异常排错
|
||||||
|
|
||||||
|
## Step 0 —— 只读侦察(不盲改)
|
||||||
|
1. `ProxyProjectInfo` 确认项目存在、域名/端口/规则现状。
|
||||||
|
2. filesystem `Read` nginx 错误日志 `/www/wwwlogs/<name>.error.log` 与访问日志 `/www/wwwlogs/<name>.log`;必要时 `ProxyWriteConfig` 不变,仅 Read conf 检查 proxy_pass/upstream。
|
||||||
|
|
||||||
|
## Step 1 —— 按症状对号入座
|
||||||
|
|
||||||
|
| 症状 | 常见根因 | 处置 |
|
||||||
|
|---|---|---|
|
||||||
|
| **502 Bad Gateway** | 后端未启动/端口错、proxy_pass 写错、unix socket 不存在、超时太短 | 确认后端进程在监听(`Bash` `ss -tlnp \| grep <port>`);核对 `ProxyProjectInfo` 的 proxy_pass 与真实后端;unix 路径检查文件存在;长请求调大 `proxy_read_timeout` |
|
||||||
|
| **404** | proxy_path 前缀与后端路由不匹配、location 前缀未命中、误写 `try_files` | 核对 location 的 `proxy_pass` 是否带 URI 前缀;检查 conf 是否有多余 location 拦截 |
|
||||||
|
| **转发不生效 / 仍是静态页** | conf 没保存成功、location 与现有规则冲突、缓存 | `nginx -t` + `ProxyProjectInfo` 看 JSON 是否同步;必要时 `Bash` `nginx -s reload` 后重试;缓存类规则先关 `proxy_cache` |
|
||||||
|
| **只对本机/内网生效** | 域名未绑定外网、防火墙未放行端口 | `ProxyProjectModify(action='add_domain')` 补域名;`Bash` 查防火墙端口放行状态 |
|
||||||
|
| **HTTPS 不强制 / 证书异常** | SSL 未部署、force_https 未开 | `ProxyProjectModify(action='force_https', force_https=true)`;证书部署走面板 |
|
||||||
|
|
||||||
|
## Step 2 —— 修复与验证
|
||||||
|
1. 按上表定位根因,**改 conf 必须走 ProxyWriteConfig + `nginx -t`**,改域名走 `ProxyProjectModify`。
|
||||||
|
2. 修复后重访验证;仍异常则回到 Step 0 换角度(读实时日志尾部 `tail`)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 运维速查
|
||||||
|
|
||||||
|
| 需求 | 调用 |
|
||||||
|
|---|---|
|
||||||
|
| 列表/找站点名 | `ProxyProjectInfo(search=..., page=...)`(site_name 留空) |
|
||||||
|
| 查看详情/规则/conf 路径 | `ProxyProjectInfo(site_name=...)` |
|
||||||
|
| 创建反代 | `ProxyProjectCreate(domains=[...], proxy_pass=...)` |
|
||||||
|
| 读/改 nginx conf | filesystem `Read` + `ProxyWriteConfig(site_name=..., conf_data=...)` |
|
||||||
|
| 验证语法 | `Bash` `nginx -t` |
|
||||||
|
| 改备注 / 启停 / 绑删域名 / 强制 HTTPS | `ProxyProjectModify(site_name=..., action=..., ...)` |
|
||||||
|
| 删除项目 | `ProxyProjectDelete(site_name=..., remove_path=false)`(高风险,确认后) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 常用 nginx 反代配置格式与位置速查
|
||||||
|
|
||||||
|
**位置**:反代项目的 nginx conf(`/www/server/panel/vhost/nginx/<name>.conf`)是完整 server 块。三块区域:
|
||||||
|
- **http 层**(`server {` 之前):upstream 定义、`proxy_cache_path`。
|
||||||
|
- **server 层**(`server { ... }` 内、location 外):`listen`、`server_name`、ssl 证书、`proxy_set_header`、`client_max_body_size`。
|
||||||
|
- **location 层**:每一条 `location <path> { ... }` 是一条 URL 转发规则,对应反代 JSON 的 `proxy_info[]`。
|
||||||
|
|
||||||
|
**典型片段**:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
# location 转发(最常用):/ 全站转发
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 按路径前缀转发:/api 到另一后端
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://127.0.0.1:9000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 带自定义超时 + WebSocket
|
||||||
|
location /ws {
|
||||||
|
proxy_pass http://127.0.0.1:3000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_connect_timeout 60s;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# server 层常用:限制上传大小、传递真实协议
|
||||||
|
client_max_body_size 50m;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
```
|
||||||
|
|
||||||
|
**规则**:
|
||||||
|
- `proxy_pass` 后**直接写死目标**(`http://IP:端口` 或 `https://域名`)最简单;若需在 URL 中带变量,必须配 `resolver`(一般不需要)。
|
||||||
|
- **勿把 `proxy_pass` 指向本机 bt_agent_mcp 自身端口**(默认 8765);若工具返回 `data.warning` 提示目标指向 MCP 自身,先与用户确认,确需暴露则在 location 补 `proxy_set_header X-Real-IP $remote_addr;` 并把真实客户端 IP 加入白名单。
|
||||||
|
- 改完**必须** `nginx -t` 验证,再确认访问生效。
|
||||||
|
- 涉及 SSL/强制 HTTPS 用 `ProxyProjectModify(action='force_https')`,别手改 ssl 块。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 完成汇报模板
|
||||||
|
|
||||||
|
汇报固定四段(每段 1-3 行,用一次工具查证一个结论,不堆 log):
|
||||||
|
|
||||||
|
- **现状**:反代项目 `<name>`,域名 `<域名:端口>`,转发目标 `<proxy_pass>`,状态(运行中/已停止)。
|
||||||
|
- **变更**:`<创建了反代项目 / 新增了 /api 转发规则 / 修改了 proxy_pass / 启停了项目 / 设置了强制 HTTPS>`。
|
||||||
|
- **验证**:`nginx -t` 通过 / `ProxyProjectInfo` 复查 proxy_info 已同步 / 访问 `<域名>` 返回预期。
|
||||||
|
- **遗留**:`<若有:SSL 证书未部署需面板处理 / 后端服务未监听需确认>;否则无`。
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
---
|
||||||
|
name: BT-Website-Troubleshoot
|
||||||
|
description: >
|
||||||
|
诊断并修复 bt panel 网站访问异常和服务启动失败问题。
|
||||||
|
当用户报告以下问题时使用此技能:网站无法打开、403/404/500/502/503 错误、
|
||||||
|
空白页/白屏、数据库连接错误、nginx 或 php-fpm 启动失败、
|
||||||
|
服务启动失败但没有明确原因,或任何网站宕机/访问被拒绝问题。
|
||||||
|
触发关键词:网站宕机、网站打不开、网站无法访问、502、
|
||||||
|
500、403、404、空白页、白屏、nginx 错误、php-fpm 错误、启动失败、
|
||||||
|
数据库连接失败、连接被拒绝、连接数过多、访问被拒绝、
|
||||||
|
网站不可达、服务不可用、错误网关、网站异常。
|
||||||
|
---
|
||||||
|
|
||||||
|
# bt panel 网站故障排查
|
||||||
|
|
||||||
|
> **停止。在执行任何操作前,必须完整阅读本文档。**
|
||||||
|
> **第一个动作:若当前环境有 todo 工具(`TodoWrite`),先用它创建诊断任务列表**;没有则直接进入诊断。
|
||||||
|
> 不要跳过任何章节。按顺序执行决策树。
|
||||||
|
> 永远不要向用户展示原始命令、btpython 路径或代码块 —— 仅使用自然语言报告。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 核心规则
|
||||||
|
|
||||||
|
1. **始终先执行预检查** —— 永远不要跳过 `curl --resolve` 本地回环验证。
|
||||||
|
2. **修复前先读取** —— 在执行任何修复操作前,先诊断根因。
|
||||||
|
3. **每个任务最多调用 15 次工具** —— 超出后,汇总当前发现并停止。
|
||||||
|
4. **绝不让用户手动输入命令** —— 始终通过 `RunCommand/Bash` 执行。
|
||||||
|
5. **修复过程中发生错误时** —— 向用户报告,不要自动重试。
|
||||||
|
6. **服务报告“启动失败”时,始终检查原始服务日志** —— 面板提示通常过于模糊,无法直接采取行动。
|
||||||
|
7. **禁止操作**:删除网站、删除数据库、删除文件、`rm -rf`、`DROP TABLE/DATABASE`。
|
||||||
|
8. **任务跟踪(可选)** —— 若当前环境提供 todo 工具(`TodoWrite`/`TodoRead`),用它跟踪诊断:开始 Step 0 前建任务列表,保持单任务 `in_progress`,完成后标 `completed`,被中断用 `TodoRead` 恢复。没有 todo 工具则跳过,直接按决策树推进。
|
||||||
|
9. **工具名双写(两个部署环境)** —— 同一个能力在内置宝塔 AI 端和插件对外接口里名字不同:执行命令是 `RunCommand` / `Bash`,精确编辑是 `SearchReplace` / `Edit`。本文档统一写成 `RunCommand/Bash`、`SearchReplace/Edit`,你按当前手头可用的那个调用即可。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 0 —— 预检查(强制)
|
||||||
|
|
||||||
|
在任何诊断前,确认网站确实属于当前服务器,并且请求能够到达该服务器。
|
||||||
|
|
||||||
|
1. **创建任务列表(若可用)**:若当前有 `TodoWrite` 工具,先列出本次案例的步骤(预检查 → 探测 → 状态码分支 → 修复);没有则跳过本步,直接进入第 2 步。
|
||||||
|
2. **执行**:`RunCommand/Bash: curl --resolve <domain>:80:127.0.0.1 -sS -o /dev/null -w '%{http_code}\\n' http://<domain>/`
|
||||||
|
- 返回实际到达面板 nginx 的 HTTP 状态码。
|
||||||
|
3. **列出网站**:`SiteList()` → 找到匹配的 `name`(域名,作为 `site_name` 传给 `SiteGetConfig`)、`path`、`project_type`。
|
||||||
|
4. **如果网站不在当前面板上**(`curl` 返回连接错误或返回了其他网站):告知用户该域名可能并未托管在此处,不要继续。
|
||||||
|
|
||||||
|
> 仅当用户明确确认网站位于当前服务器,或直接提供了 `site_name`(域名)时,才可跳过预检查。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1 —— 双探针
|
||||||
|
|
||||||
|
这些探针是只读验证,不产生持久副作用。创建、测试,并在完成后**删除**。
|
||||||
|
|
||||||
|
### 探针 A —— 静态文件(验证域名绑定 + nginx + 根目录)
|
||||||
|
|
||||||
|
1. `RunCommand/Bash: echo 'bt Panel probe $(date)' > <site_path>/.probe_static.html`
|
||||||
|
2. `RunCommand/Bash: chown www:www <site_path>/.probe_static.html && chmod 644 <site_path>/.probe_static.html`
|
||||||
|
3. `RunCommand/Bash: curl --resolve <domain>:80:127.0.0.1 -sS http://<domain>/.probe_static.html`
|
||||||
|
4. **预期结果**:返回探针文本,HTTP 状态码为 200。
|
||||||
|
5. 清理:`RunCommand/Bash: rm -f <site_path>/.probe_static.html`
|
||||||
|
|
||||||
|
### 探针 B —— PHP 文件(验证 PHP 运行时 + php-fpm socket)
|
||||||
|
|
||||||
|
1. `RunCommand/Bash: echo '<?php echo "bt Panel PHP probe ".PHP_VERSION; ?>' > <site_path>/.probe_php.php`
|
||||||
|
2. `RunCommand/Bash: chown www:www <site_path>/.probe_php.php && chmod 644 <site_path>/.probe_php.php`
|
||||||
|
3. `RunCommand/Bash: curl --resolve <domain>:80:127.0.0.1 -sS http://<domain>/.probe_php.php`
|
||||||
|
4. **预期结果**:返回包含 PHP 版本字符串的探针文本。
|
||||||
|
5. 清理:`RunCommand/Bash: rm -f <site_path>/.probe_php.php`
|
||||||
|
|
||||||
|
> 从 `SiteList` 返回的匹配项 `path` 字段获取 `site_path`。`SiteGetConfig(site_name)` 返回的是**原始虚拟主机配置文本**(不是结构化字段)—— 阅读文本中的 `root`、`access_log` 和 `include enable-php-<ver>.conf;` 指令,以验证根目录。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2 —— 状态码决策树
|
||||||
|
|
||||||
|
### 403 Forbidden —— 权限 / 所有权
|
||||||
|
|
||||||
|
**目标**:确认 `www` 拥有网站目录树,目录权限为 755、文件权限为 644,并且父目录可读。
|
||||||
|
|
||||||
|
1. `SiteGetConfig(site_name)` → 获取 `root` 目录。
|
||||||
|
2. `RunCommand/Bash: ls -la <root>/` 和 `RunCommand/Bash: ls -la <parent_of_root>/`(父目录同样重要)。
|
||||||
|
3. 检查:
|
||||||
|
- root 及所有父目录的所有者/用户组 = `www:www`
|
||||||
|
- 目录权限 = `755`
|
||||||
|
- 文件权限 = `644`
|
||||||
|
4. 如果任一项不正确(自动修复,低风险):
|
||||||
|
- `RunCommand/Bash: chown -R www:www <root>`
|
||||||
|
- `RunCommand/Bash: find <root> -type d -exec chmod 755 {} \;`
|
||||||
|
- `RunCommand/Bash: find <root> -type f -exec chmod 644 {} \;`
|
||||||
|
5. 使用预检查 curl 重新测试。如果仍然返回 403,检查 nginx 错误日志:
|
||||||
|
- `Read: /www/wwwlogs/<domain>.error.log`(最后 50 行,查找 `directory index of "..." is forbidden` 或 `access denied`)。
|
||||||
|
|
||||||
|
### 404 Not Found —— 路径 / Rewrite
|
||||||
|
|
||||||
|
**先分类**:缺失的 URL 应该由动态路由(PHP 路由/框架路由)提供,还是由静态文件提供?
|
||||||
|
|
||||||
|
- **静态 404**(例如 `/favicon.ico`、`/uploads/foo.jpg`):
|
||||||
|
1. `SiteGetConfig(site_name)` → 检查 `root` 和 `access_log` 的位置。
|
||||||
|
2. `RunCommand/Bash: ls -la <root>/<expected_path>` → 文件是否缺失?root 是否错误?
|
||||||
|
3. 确认虚拟主机配置中的 `root` 指令与 `SiteList` 返回的实际 `site_path` 一致。
|
||||||
|
|
||||||
|
- **动态 404**(例如 `/category/news/`、`/article/123`、`/admin/login`):
|
||||||
|
1. `SiteGetConfig(site_name)` → 查找 `include .../rewrite/<domain>.conf;` 行。
|
||||||
|
2. `Read: /www/server/panel/vhost/rewrite/<domain>.conf`(如果存在)。
|
||||||
|
3. **常见原因**:框架(WordPress / ThinkPHP / Laravel / Typecho 等)的 rewrite 规则缺失或错误。
|
||||||
|
4. 修复(高风险 —— 需要面板确认):根据框架标准规则使用 `SearchReplace/Edit` 编辑 rewrite 文件,然后执行 `RunCommand/Bash: nginx -t && nginx -s reload`。
|
||||||
|
|
||||||
|
### 500 Internal Server Error —— 三个分支
|
||||||
|
|
||||||
|
运行预检查 curl,确认返回 500。然后依次检查各分支:
|
||||||
|
|
||||||
|
#### 分支 A —— 数据库
|
||||||
|
|
||||||
|
1. 读取 `SiteGetConfig` 找到项目根目录,然后查找框架数据库配置:
|
||||||
|
- WordPress:`Read: <root>/wp-config.php` → 提取 `DB_NAME`、`DB_USER`、`DB_PASSWORD`、`DB_HOST`。
|
||||||
|
- 其他框架:查找 `.env`、`config/database.php`、`application/database.php` 等。
|
||||||
|
2. `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> <DB_NAME> -e "SELECT VERSION()"` → 连接成功时返回 MySQL 版本号(即连接测试通过);失败则按下一步读错误码。
|
||||||
|
3. 如果连接失败,从 `mysql` 客户端的原始错误输出(形如 `ERROR 1045 (28000): ...`)中读取错误码,按下表判断:
|
||||||
|
- `2002` / `2003` → MySQL 未运行。进入**服务启动失败 → MySQL**。
|
||||||
|
- `1045` → 密码错误。比较配置中的 `DB_PASSWORD` 与 `databases` 表;如果不一致,向用户报告(不要自动重置数据库密码)。
|
||||||
|
- `1146` → 数据表缺失。用 `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> <DB_NAME> -e "SHOW TABLES"` / `DESC <表名>` 确认(凭据取自上一步 wp-config;RunCommand/Bash 为 high,会触发确认),然后报告。
|
||||||
|
- `1040` → 连接数过多。执行 `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> -e "SHOW GLOBAL STATUS LIKE 'Threads_connected'; SHOW FULL PROCESSLIST"`,查看连接数与连接来源;建议提高 `max_connections`(高风险)。
|
||||||
|
|
||||||
|
#### 分支 B —— 代码(未捕获异常)
|
||||||
|
|
||||||
|
1. 启用 PHP 错误显示(高风险 —— 需要确认,且仅适用于非生产环境):
|
||||||
|
- `Read: /www/server/php/<ver>/etc/php.ini` → 检查 `display_errors` 和 `error_reporting`。
|
||||||
|
2. `Read: /www/wwwlogs/<domain>.error.log`(最后 100 行)→ 查找 PHP `Fatal error` / `Parse error` / `Uncaught`。
|
||||||
|
3. 向用户报告文件、行号和错误信息。不要自动修改网站代码。
|
||||||
|
|
||||||
|
#### 分支 C —— 配置(HTTP 200 但页面空白)
|
||||||
|
|
||||||
|
1. 这是典型的 **fastcgi.conf 损坏**模式:状态码为 200、响应体为空,并且网站此前正常。
|
||||||
|
2. `Read: /www/server/nginx/conf/fastcgi.conf` → 检查文件是否被清空或被过度注释。
|
||||||
|
3. 如果异常,向用户报告。修复需要恢复面板默认的 `fastcgi.conf`(高风险 —— 需要确认,并需要原始文件)。
|
||||||
|
|
||||||
|
### 502 / 503 Bad Gateway / Service Unavailable —— PHP-FPM 环境
|
||||||
|
|
||||||
|
1. `RunCommand/Bash: ps -ef \| grep php-fpm \| grep -v grep` → php-fpm 是否正在运行?
|
||||||
|
2. `ServiceStatus("php-fpm-<ver>")` → 确认安装和运行状态。从 `SiteGetConfig` 中的 `include enable-php-<ver>.conf;` 行确定版本。
|
||||||
|
3. `SiteGetConfig(site_name)` → 检查虚拟主机实际包含的 `enable-php-<ver>.conf` 是否与运行中的版本**一致**。
|
||||||
|
4. `RunCommand/Bash: curl -sS http://127.0.0.1/phpfpm_<ver>_status` → 检查 active processes、listen queue、max children。
|
||||||
|
- 如果 `listen queue` 非零 → 进程池已耗尽。参见**服务启动失败 → php-fpm**中的 OOM。
|
||||||
|
5. `RunCommand/Bash: free -m` → 查看可用内存;如果少于 200MB,OOM killer 可能已终止 php-fpm。
|
||||||
|
6. 对于**反向代理 502**:从面板主机执行 `RunCommand/Bash: curl -v <upstream_host>` → 检查上游是否可达(防火墙 / DNS / 上游宕机)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3 —— 服务启动失败
|
||||||
|
|
||||||
|
> **核心原则**:当面板显示“启动失败”但没有有效细节时,**始终先读取原始服务日志**。面板提示通常过于模糊,无法直接采取行动。
|
||||||
|
|
||||||
|
### 3.1 nginx
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 语法检查 —— 可给出任何错误的准确文件和行号
|
||||||
|
/www/server/nginx/sbin/nginx -t
|
||||||
|
```
|
||||||
|
|
||||||
|
三种常见失败模式:
|
||||||
|
|
||||||
|
| 现象 | 原因 | 修复 |
|
||||||
|
|---|---|---|
|
||||||
|
| `unknown directive "xxx" in /www/server/panel/vhost/nginx/<site>.conf:N` | 网站虚拟主机配置中存在拼写错误或不受支持的指令 | 使用 `Read` 读取对应行,使用 `SearchReplace/Edit` 修复(高风险),然后重新执行 `nginx -t` |
|
||||||
|
| `bind() to 0.0.0.0:80 failed` / `bind() to [::]:443 failed` | 端口被占用 | `RunCommand/Bash: netstat -tlnp \| grep -E ':80\|:443'` → 找出冲突进程,并向用户报告 |
|
||||||
|
| `host not found in upstream "<name>"` | 启动时无法解析上游 DNS | 使用 `RunCommand/Bash: dig +short <name>` 验证;如果无法解析,向用户报告。修复:在虚拟主机中添加 `resolver` 指令,或替换为 IP(高风险) |
|
||||||
|
|
||||||
|
修复后,**始终**再次执行 `nginx -t`,然后执行 `RunCommand/Bash: /etc/init.d/nginx restart`(或 `ServiceRestart("nginx")`,高风险 —— 需要确认)。
|
||||||
|
|
||||||
|
### 3.2 php-fpm
|
||||||
|
|
||||||
|
从故障网站引用的 `enable-php-<ver>.conf` 中获取版本,然后执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查看原始 php-fpm 错误日志末尾 —— 信息最完整
|
||||||
|
tail -n 50 /www/server/php/<ver>/var/log/php-fpm.log
|
||||||
|
```
|
||||||
|
|
||||||
|
| 现象 | 原因 | 修复 |
|
||||||
|
|---|---|---|
|
||||||
|
| `Unable to load dynamic library '<ext>.so'` / `segfault (core dumped)` | 新安装的 PHP 扩展损坏 | 二分排查:在面板中进入应用商店 → PHP → 设置 → 扩展,逐个卸载最近新增的扩展,每次卸载后重启(`RunCommand/Bash: /etc/init.d/php-fpm-<ver> restart`) |
|
||||||
|
| 启动后立即显示 `active (exited)` | 被 OOM killer 终止 | `RunCommand/Bash: dmesg \| grep -E "php\|oom" \| tail -20` + `RunCommand/Bash: free -m` → 降低 `/www/server/php/<ver>/etc/php-fpm.conf` 中的 `pm.max_children`(高风险) |
|
||||||
|
| `bind() to /tmp/php-cgi-<ver>.sock failed: Address already in use` | 旧 php-fpm 进程仍在运行 | `RunCommand/Bash: pkill php-fpm && sleep 2 && /etc/init.d/php-fpm-<ver> start`(高风险) |
|
||||||
|
| `ERROR: [/www/server/php/<ver>/etc/php-fpm.conf:N] unknown parameter` | 手动编辑导致指令损坏 | 使用 `Read` 读取对应行,修复或通过面板应用商店 → PHP → 设置 → 配置 → 重置(高风险) |
|
||||||
|
| `Unable to access php-fpm.sock: Permission denied` | Socket 文件所有者错误 | `RunCommand/Bash: ls -la /tmp/php-cgi-<ver>.sock` → 如果不是 `www:www`,执行 `RunCommand/Bash: chown www:www /tmp/php-cgi-<ver>.sock && chown -R www:www /www/server/php/<ver>/var/log/`(低风险) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4 —— 工具风险等级
|
||||||
|
|
||||||
|
工具由其注册的 `risk_level` 控制,而不是由命令本身的行为控制。
|
||||||
|
|
||||||
|
| risk_level | 工具 | 典型用途 | 处理方式 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **low** | `Read`、`SiteGetConfig`、`SiteLogs`、`ServiceStatus`、`TodoRead`、`TodoWrite` | 读取配置/日志、检查服务状态、跟踪任务 | 直接执行 |
|
||||||
|
| **high** | `RunCommand/Bash`、`ServiceRestart`、`SearchReplace/Edit`、`Write` | 任何 shell 命令(包括只读的 `curl`/`ls`/`netstat`/`ps`/`mysql -e`,以及 `chown`/`chmod`)、重启服务、编辑 nginx/php 配置、写入文件、执行 SQL(读/写) | 每次调用都必须经过面板确认门禁 |
|
||||||
|
| **forbidden** | — | 删除网站、删除数据库、删除文件、`rm -rf`、`DROP TABLE/DATABASE` | 永不执行 |
|
||||||
|
|
||||||
|
- `RunCommand/Bash` 作为工具的 `risk_level="high"`,因此即使是**只读探测**(`curl`、`ls`、`netstat`)也会触发确认门禁。应优先使用低风险读取工具(使用 `Read` 读取日志/配置,使用 `ServiceStatus` 检查状态),在无需确认的情况下收集事实。
|
||||||
|
- 任何配置编辑(`SearchReplace/Edit`/`Write`)完成后,**必须**执行 `nginx -t` 验证,再进行 reload。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5 —— 输出格式
|
||||||
|
|
||||||
|
向用户报告发现时,始终使用以下形式的**自然语言**:
|
||||||
|
|
||||||
|
```
|
||||||
|
根因:<用一句话说明根因>
|
||||||
|
|
||||||
|
已执行步骤:
|
||||||
|
- <步骤 1>
|
||||||
|
- <步骤 2>
|
||||||
|
...
|
||||||
|
|
||||||
|
建议:
|
||||||
|
- <预防措施或后续操作>
|
||||||
|
```
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- **绝不**在面向用户的消息中粘贴原始 shell 命令、btpython 路径或配置差异。
|
||||||
|
- **绝不**要求用户手动输入命令 —— 如果需要修复,描述修复内容并等待用户确认。
|
||||||
|
- 如果诊断尚不完整(例如无法复现、日志不明确),必须明确说明。不要编造根因。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 快速参考 —— 常见错误码
|
||||||
|
|
||||||
|
这些错误由 `mysql_engine.MYSQL_ERROR_MAP` 自动映射;此处映射仅供 Agent 自身推理使用,**不要向用户原样输出错误码**。
|
||||||
|
|
||||||
|
| SQLSTATE / 错误码 | 友好含义 | 下一步 |
|
||||||
|
|---|---|---|
|
||||||
|
| `2002` / `2003` | 无法连接 MySQL socket / 端口 | 检查 `ServiceStatus("mysql")` |
|
||||||
|
| `1045` | 数据库用户密码错误 | 比较 `wp-config.php` 与面板 `databases` 表 |
|
||||||
|
| `1146` | 数据表不存在 | `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> <DB_NAME> -e "SHOW TABLES"` / `DESC` 确认 |
|
||||||
|
| `1040` | 连接数过多 | `RunCommand/Bash: mysql -h<DB_HOST> -u<DB_USER> -p<DB_PASSWORD> -e "SHOW GLOBAL STATUS LIKE 'Threads_connected'; SHOW FULL PROCESSLIST"` |
|
||||||
|
| `1452` | 外键约束失败 | 检查被引用的数据行,并向用户报告 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 快速参考 —— 文件 / 日志路径
|
||||||
|
|
||||||
|
| 内容 | 路径 |
|
||||||
|
|---|---|
|
||||||
|
| Nginx 虚拟主机配置 | `/www/server/panel/vhost/nginx/<domain>.conf` |
|
||||||
|
| Apache 虚拟主机配置 | `/www/server/panel/vhost/apache/<domain>.conf` |
|
||||||
|
| Rewrite 规则 | `/www/server/panel/vhost/rewrite/<domain>.conf` |
|
||||||
|
| Nginx 主配置 | `/www/server/nginx/conf/nginx.conf` |
|
||||||
|
| Nginx fastcgi 配置(空白页常见原因) | `/www/server/nginx/conf/fastcgi.conf` |
|
||||||
|
| 网站访问日志 | `/www/wwwlogs/<domain>.log` |
|
||||||
|
| 网站错误日志 | `/www/wwwlogs/<domain>.error.log` |
|
||||||
|
| PHP-FPM 错误日志 | `/www/server/php/<ver>/var/log/php-fpm.log` |
|
||||||
|
| PHP-FPM socket | `/tmp/php-cgi-<ver>.sock` |
|
||||||
|
| PHP-FPM 进程池配置 | `/www/server/php/<ver>/etc/php-fpm.conf` |
|
||||||
|
| WordPress 数据库配置 | `<site_root>/wp-config.php` |
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
AI 智能体开发约束 & 项目执行规范
|
||||||
|
本文件为项目根目录全局 Agent 行为规则,AI 编码、重构、调试、优化、答疑均需默认遵循以下配置,无需用户重复说明。
|
||||||
|
|
||||||
|
---
|
||||||
|
1. 运行环境规范
|
||||||
|
- 默认强制使用本地 .venv 虚拟环境,禁止使用任何沙箱环境、在线临时环境、容器模拟环境。
|
||||||
|
- 所有代码运行、依赖安装、调试、语法检查、模块测试,均基于项目根目录 .venv 环境执行。
|
||||||
|
- 如需安装依赖,仅操作本地虚拟环境,不污染全局 Python 环境。
|
||||||
|
- 所有需要【写入文件内容】的操作(导出落盘、覆盖目标文件、复制/移动文件、下载保存等)一律不使用沙箱:执行时触发沙箱外运行(requires_approval 申请用户批准),避免被沙箱拦截(如 D:\资料 等受保护目录只读可读、写入被拒)。
|
||||||
|
2. 影刀开发规范
|
||||||
|
- 影刀项目默认采用单文件自包含架构。
|
||||||
|
- 输出影刀脚本、逻辑代码、流程封装时,优先单文件独立实现,功能自包含、可直接导入运行,不拆分冗余子文件。
|
||||||
|
- 单文件需具备完整性:依赖声明、核心逻辑、异常处理、入口执行全部内聚在当前文件。
|
||||||
|
3. 项目通用架构规范
|
||||||
|
- 代码组织:不同业务、不同流程独立模块化运行,互不侵入、互不影响。
|
||||||
|
- 各方向零依赖:项目并存多个独立演进方向,彼此【绝不跨目录 import】,登录/数据导出等数据层各自内置(允许少量重复换取完全解耦),任一方向可单独拷贝、单独演进、独享依赖与启动:
|
||||||
|
- 桌面端 desktop/:中心机 desktop/controlplane/ + 执行机 desktop/webhost/,两者互不 import、独立演进、可单独拷贝(模块搜索根 = desktop/,运行均以 desktop/ 为 cwd)。
|
||||||
|
- 插件 plugins/:根级独立目录(按号段分桶 plugins/XQ0001-0100/),被执行机按账号权限自下载加载,不随 webhost 发布。
|
||||||
|
- 影刀版 workflows/:单文件自包含,需求脚本按号段分桶(workflows/XQ0001-0100/)。
|
||||||
|
- app/ 蓝图版:已弃用,保留归档、不再维护。
|
||||||
|
- 代码形态分三类,按各方向性质采用不同组织方式(【单文件自包含】仅适用于影刀版,其它一律按正常项目开发):
|
||||||
|
- workflows/(影刀版):沿用单文件自包含架构(见第 2 节,仅影刀适用)。
|
||||||
|
- 桌面端各后端(desktop/controlplane/ 中心机、desktop/webhost/ 执行机底座):按正常 Python 模块化项目开发,允许按包/模块/多文件拆分(如 main.py/app.py 分割逻辑与路由),不做单文件约束。
|
||||||
|
- 插件(执行机加载的执行单元,源码位于根级 plugins/XQ0001-0100/<中文目录>/,如 plugins/XQ0001-0100/XQ0011 考勤月报封存检查/,id 用固定规则 xq{单号},与目录名解耦):内部按正常项目组织,可拆 config/data/logic/report 等多文件;但强调【插件自包含】——插件内模块只能互相引用、依赖 Python 标准库/第三方依赖/底座注入的插件接口(webhost.backend.plugins.base),严禁 import 插件包之外的任何代码(根目录、desktop 底座业务、app 一律禁止),保证插件完整交付物=插件包本身,可单独拷贝发布、独立演进。插件目录结构、前端(ui/ 与 ui-src/)存放、打包产物位置(dist-plugin/<id>_v<版本>.zip)、发布流程等细则见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||||
|
- 环境变量按模块隔离,各自使用自己目录下的 .env,互不覆盖、互不依赖:
|
||||||
|
- 根目录 .env:仅供 workflows/(影刀) 脚本使用,承载各 XQ 业务路径/账号等配置;禁止向根 .env 写入桌面端/app 的变量。
|
||||||
|
- desktop/controlplane/ → desktop/controlplane/.env(中心机配置,含 CONTROLPLANE_PORT、CONTROLPLANE_TOKEN)
|
||||||
|
- desktop/webhost/ → desktop/webhost/.env(执行机底座配置,含 CONTROLPLANE_*、RUN_TIMEOUT 等)
|
||||||
|
- app/ → app/.env(app 版业务配置,已弃用)
|
||||||
|
- workflows/ 影刀不再单独建 .env,所需配置统一放在根 .env。
|
||||||
|
- 各模块加载器只允许读取本模块目录下的 .env,禁止读取/改写其它模块或根 .env。
|
||||||
|
- 错误处理:全局项目级重试机制,最大重试 3 次,三次失败后再记录错误日志。
|
||||||
|
- 日志规范:正常 INFO 级别屏蔽大体积 JSON 调试日志,保证日志整洁;仅 DEBUG 模式开启完整 JSON 调试信息输出。
|
||||||
|
4. AI 工作默认规则
|
||||||
|
- 所有代码生成、修改、重构必须贴合 Python 模块化编程思想。
|
||||||
|
- 不主动创建冗余文件、不随意变更项目结构、不混用沙箱环境。
|
||||||
|
- 输出代码优先保证:可运行、结构清晰、符合项目统一规范、按代码形态适配(单文件自包含仅影刀版需要;后端与插件按正常模块化项目开发)。
|
||||||
|
- 变量配置规范:禁止使用命令行传入变量的方式实现参数配置,所有参数、变量、配置项均在代码/配置文件内部定义、固化或读取本地配置,保证运行无外部参数依赖。
|
||||||
|
5. 发版与自动更新操作规范
|
||||||
|
- 自动更新:插件由执行机按账号权限自下载(plugin_sync.py);壳子由执行机自动下载安装包 + 用户点击升级重启(shell_updater.py)。版本源都在中心机控制面。
|
||||||
|
- 发版统一走 agent CLI(desktop/ 下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli)。插件用 publish / grant / revoke;壳子用 file push --category shell;中心机控制面为源码部署(宝塔 gunicorn 8800),改代码后按 SOP 部署。
|
||||||
|
- 鉴权:密码登录 `--admin puddy --password 123456`(远程机器加 `--base http://117.72.191.188:8800`),或中心机本机密钥自签。
|
||||||
|
- 完整流程、命令示例见 docs/插件/发版规范.md;中心机前后端部署步骤见 docs/部署/控制面前后端部署SOP.md。
|
||||||
@@ -1,2 +1,172 @@
|
|||||||
# Process-Automation
|
# Process-Automation
|
||||||
|
|
||||||
|
HR 业务流程自动化(37duAutomation):覆盖 HRBP OA 审批、EHR 数据核对/导出、社保、考勤、排班、雇主险等场景,并提供影刀 RPA 单文件版本与配套的「需求单 → 评分」文档体系。
|
||||||
|
|
||||||
|
## 项目简介
|
||||||
|
|
||||||
|
基于 Python 的 HR 流程自动化工具,主要包括三类实现路径:
|
||||||
|
|
||||||
|
* **OA 审批自动化**:通过 DrissionPage 浏览器自动化 + OA 接口,自动处理请假、加班、离职电子签等审批流程,内置规则校验、OCR(rapidocr 3.x)附件识别、钉钉/工作沟通推送、审批报告生成;
|
||||||
|
|
||||||
|
* **EHR 数据处理自动化**:对接 HR 平台接口与本地 Excel,完成考勤异常核对、排班异常识别、工资卡核对、社保增减名单/告知书、雇主险名额等;
|
||||||
|
|
||||||
|
* **影刀 RPA 单文件版**:`workflows/` 下按业务隔离的单文件自包含脚本,可直接导入影刀平台运行。
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
Process-Automation/
|
||||||
|
├── 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/ # *已弃用归档,不再维护*(早期模块化蓝图,仅留作参考)
|
||||||
|
│ ├── 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 # 影刀版开发指南
|
||||||
|
├── docs/
|
||||||
|
│ ├── README.md # 文档总索引
|
||||||
|
│ ├── 需求单/ # 各 XQ 四件套 + 需求单索引 + 评分规则
|
||||||
|
│ ├── 插件/ # 插件开发规范 / 发版规范
|
||||||
|
│ ├── 架构/ # 架构蓝图 / 插件管理系统设计 / 迭代规划 / 重构方案
|
||||||
|
│ ├── 部署/ # 控制面前后端部署 SOP
|
||||||
|
│ ├── 桌面端/ # 底座方案(平台账号本地加密存储)
|
||||||
|
│ └── 工作沟通推送/ # OA 工作沟通推送说明
|
||||||
|
└── requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心功能
|
||||||
|
|
||||||
|
| 模块 | 说明 |
|
||||||
|
| ------- | ------------------------------------------- |
|
||||||
|
| 自动登录/会话 | OA(SSO)与 HR 平台登录,cookie 缓存,过期自动重登 |
|
||||||
|
| 审批流程引擎 | 待办获取、表单解析、规则校验、结果提交、报告生成 |
|
||||||
|
| 请假/加班审批 | 多类型(事假/病假/产假/年度福利假/加班类型等)分支校验,含附件 OCR |
|
||||||
|
| 离职电子签审核 | 离职电子签流程自动审批 |
|
||||||
|
| 考勤异常处理 | 周/月考勤异常核对,三查复核,钉钉推送 |
|
||||||
|
| 排班异常识别 | 调动/预入职台账导出 + 部门排班集合比对判定,序列/离职过滤,按店长分组钉钉单聊推送 |
|
||||||
|
| 工资卡核对 | 身份证/姓名/银行卡号格式与一致性校验 |
|
||||||
|
| 社保类 | 增减名单梳理、增减员导入名单、社保转移/参保异常处理 |
|
||||||
|
| 社保告知书 | 按模板生成 Word/PDF 告知书并合并下发 |
|
||||||
|
| 雇主险 | 名额调度、增减操作、变更名单导出 |
|
||||||
|
| 重试/日志 | 项目级最大 3 次重试;INFO 屏蔽大体积 JSON 调试日志,DEBUG 全量输出 |
|
||||||
|
|
||||||
|
## 技术依赖
|
||||||
|
|
||||||
|
* `DrissionPage`:浏览器自动化
|
||||||
|
|
||||||
|
* `pandas` / `openpyxl`:Excel 读写
|
||||||
|
|
||||||
|
* `rapidocr`(3.x)/ `opencv-python`(numpy 2.x):OCR 附件识别
|
||||||
|
|
||||||
|
* `python-docx` / WPS COM:Word/PDF 生成
|
||||||
|
|
||||||
|
* `python-dotenv`、`chinese_calendar` 等
|
||||||
|
|
||||||
|
> 运行一律使用项目本地虚拟环境 `d:\work\code\37duAutomation\.venv`(`.venv\Scripts\python.exe`)。
|
||||||
|
|
||||||
|
## 使用方法
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 进入虚拟环境
|
||||||
|
.venv\Scripts\Activate.ps1
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 影刀版脚本(单文件自包含,直接运行,按号段分桶存放):
|
||||||
|
# 排班异常识别(第二步导出 + 第三步识别)
|
||||||
|
python "workflows/XQ0001-0100/XQ0001 排班异常识别/transfer_roster_export.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0001 排班异常识别/pre_entry_roster_export.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0001 排班异常识别/shift_abnormal_check.py"
|
||||||
|
|
||||||
|
# 雇主险增减操作(名额调度、增减员导入)
|
||||||
|
python "workflows/XQ0001-0100/XQ0002 雇主险增减操作/roster_filter.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0002 雇主险增减操作/employer_insurance_schedule.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0002 雇主险增减操作/add_sub_import.py"
|
||||||
|
|
||||||
|
# OA 审批流程审核(请假 / 加班 / 离职电子签)
|
||||||
|
python "workflows/XQ0001-0100/XQ0003 EHR系统请假流程审核/leave_approval.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0004 EHR系统加班流程审核/overtime_approval.py"
|
||||||
|
python "workflows/XQ0001-0100/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py"
|
||||||
|
|
||||||
|
# 考勤异常处理(周 / 月)
|
||||||
|
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/XQ0015 参保成功及异常告知书制作与下发/notice_mail_merge.py"
|
||||||
|
|
||||||
|
# 先运行登录指令写入共享登录态,再执行业务脚本
|
||||||
|
python workflows/share/oa_login.py
|
||||||
|
python workflows/share/hr_login.py
|
||||||
|
python workflows/share/roster_export.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 文档体系
|
||||||
|
|
||||||
|
* 每个需求单在 `docs/需求单/XQ0001-0100/XQ00xx 名称/` 下维护 需求文档 / 流程文档 / 开发文档 / 评分文档 四件套(需求单目录按号段分桶,每 100 号一桶);
|
||||||
|
|
||||||
|
* RPA 场景分级依据 `docs/需求单/评分规则.md`(系统对接数 / 业务分支数 / 智能识别场景数 / 异常类型数,四档定级);
|
||||||
|
|
||||||
|
* 已落地场景的评分文档为初稿,需经业务方签字 + 网络信息部审批 + 人资备案。
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. 确保已安装 Chrome/Edge;
|
||||||
|
2. 首次运行需手动登录一次并缓存会话/cookie(或先运行 `workflows/share/` 下的 `oa_login.py` / `hr_login.py` 写入共享登录态);
|
||||||
|
3. OA/HR 需在登录态有效期内运行,脚本会自动重登或提示重新登录;
|
||||||
|
4. 影刀版本为单文件自包含,直接导入影刀平台运行;业务脚本不 import 共享指令模块,仅读 cookies 文件、写全局变量,消息生成与发送解耦(详见 `workflows/README.md`)。
|
||||||
|
|
||||||
|
> **桌面端与影刀版**:开发流程为「桌面端(`desktop/`,中心机 + 执行机)测试通过 → 影刀版(`workflows/`,单文件自包含)落地部署」;`app/` 为早期模块化蓝图,已**弃用归档、不再维护**,仅留作参考。桌面端各方向互不 import、独立演进,插件源码统一放根级 `plugins/`。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
{
|
||||||
|
"code": 200,
|
||||||
|
"msg": "Success",
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"store_id": 36,
|
||||||
|
"open_store_id": "00162",
|
||||||
|
"brand_id": 1,
|
||||||
|
"brand_name": "金色印象",
|
||||||
|
"store_name": "加州CEO会馆",
|
||||||
|
"store_address": null,
|
||||||
|
"store_phone": null,
|
||||||
|
"store_longitude": null,
|
||||||
|
"store_latitude": null,
|
||||||
|
"center_name": "金色印象事业部",
|
||||||
|
"part_name": "第三片区",
|
||||||
|
"store_manager": "黄凤",
|
||||||
|
"store_manager_phone": null,
|
||||||
|
"store_visible": true,
|
||||||
|
"store_key": "95682799-5af7-4ff6-8e15-695eaa7fb12a",
|
||||||
|
"store_photo": null,
|
||||||
|
"store_no": null,
|
||||||
|
"extra": null,
|
||||||
|
"hr_json_extra": {
|
||||||
|
"beginDate": "2022-01-21 00:00:00",
|
||||||
|
"branchLeaderCode": "37027103",
|
||||||
|
"branchLeaderId": "e1360067-9871-451d-97d3-b168df74ce82",
|
||||||
|
"branchLeaderName": "李燕",
|
||||||
|
"cantCode": "500000",
|
||||||
|
"cantName": "重庆市",
|
||||||
|
"costOrgCode": null,
|
||||||
|
"costOrgId": null,
|
||||||
|
"costOrgName": null,
|
||||||
|
"country": "",
|
||||||
|
"createTime": "2022-01-21 15:03:58",
|
||||||
|
"endDate": null,
|
||||||
|
"extendItems": [
|
||||||
|
{
|
||||||
|
"columnComment": "发薪日",
|
||||||
|
"columnName": "ext_payday",
|
||||||
|
"columnValue": "11"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"columnComment": "办公详细地址",
|
||||||
|
"columnName": "ext_office_address",
|
||||||
|
"columnValue": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"columnComment": "负责人编码",
|
||||||
|
"columnName": "ext_principal_num",
|
||||||
|
"columnValue": ""
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foundDate": "2022-01-21",
|
||||||
|
"foundReason": null,
|
||||||
|
"globalOrder": "1106109101110101",
|
||||||
|
"hrbpCode": null,
|
||||||
|
"hrbpId": null,
|
||||||
|
"hrbpLeaderCode": null,
|
||||||
|
"hrbpLeaderId": null,
|
||||||
|
"hrbpLeaderName": null,
|
||||||
|
"hrbpName": null,
|
||||||
|
"inUse": "1",
|
||||||
|
"kqCommissionerCode": null,
|
||||||
|
"kqCommissionerId": null,
|
||||||
|
"kqCommissionerName": null,
|
||||||
|
"manageOrgCode": null,
|
||||||
|
"manageOrgName": null,
|
||||||
|
"manageStaff": null,
|
||||||
|
"manageStaffCode": null,
|
||||||
|
"manageStaffId": null,
|
||||||
|
"manageStruId": null,
|
||||||
|
"officeAddress": "1",
|
||||||
|
"operateTime": "2026-08-03 09:19:01",
|
||||||
|
"orgCode": "00162",
|
||||||
|
"orgFullPath": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第三片区-加州CEO会馆",
|
||||||
|
"orgId": "2acb10bd-cbdb-4ebf-86a3-980de8b35dca",
|
||||||
|
"orgName": "加州CEO会馆",
|
||||||
|
"orgTypeCode": "49",
|
||||||
|
"orgTypeName": "会馆",
|
||||||
|
"parentOrgCode": "00144",
|
||||||
|
"parentOrgId": "33562286-627b-4f33-8dbc-53947be08f05",
|
||||||
|
"parentOrgName": "第三片区",
|
||||||
|
"principalStaff": "黄凤",
|
||||||
|
"principalStaffCode": "37000189",
|
||||||
|
"principalStaffId": "4b5105b8-7a9f-11ec-b449-000c296f9469",
|
||||||
|
"remarks": null,
|
||||||
|
"salaryCommissionerCode": null,
|
||||||
|
"salaryCommissionerId": null,
|
||||||
|
"salaryCommissionerName": null,
|
||||||
|
"shortName": "加州CEO会馆",
|
||||||
|
"struOrder": 101.0,
|
||||||
|
"unitOrgCode": "00738",
|
||||||
|
"unitOrgId": "0bcdee12-e592-11ee-b449-000c296f9469",
|
||||||
|
"unitOrgName": "金色印象事业部"
|
||||||
|
},
|
||||||
|
"crm_json_extra": {
|
||||||
|
"host": "https://api.shuhe.crm.waf.37du.co",
|
||||||
|
"shop_id": "10085",
|
||||||
|
"shop_key": "fT3vJb1SmF7RfHBQ4NWds9fJYl7gywMi",
|
||||||
|
"sign_key": "EQO2dQLKw9UAshwYRbzlKRB51MYdEEeW"
|
||||||
|
},
|
||||||
|
"created_at": "2025-07-20T18:43:49.549716",
|
||||||
|
"updated_at": "2026-09-22T11:14:08.172785"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"store_id": 71,
|
||||||
|
"open_store_id": "00615",
|
||||||
|
"brand_id": 1,
|
||||||
|
"brand_name": "金色印象",
|
||||||
|
"store_name": "爱琴海行政会馆",
|
||||||
|
"store_address": null,
|
||||||
|
"store_phone": null,
|
||||||
|
"store_longitude": null,
|
||||||
|
"store_latitude": null,
|
||||||
|
"center_name": "金色印象事业部",
|
||||||
|
"part_name": "第一片区",
|
||||||
|
"store_manager": "吴俊良",
|
||||||
|
"store_manager_phone": null,
|
||||||
|
"store_visible": true,
|
||||||
|
"store_key": "5d771409-0f4a-458a-ae2d-fb862af7f652",
|
||||||
|
"store_photo": null,
|
||||||
|
"store_no": null,
|
||||||
|
"extra": null,
|
||||||
|
"hr_json_extra": {
|
||||||
|
"beginDate": "2023-10-12 00:00:00",
|
||||||
|
"branchLeaderCode": "37027103",
|
||||||
|
"branchLeaderId": "e1360067-9871-451d-97d3-b168df74ce82",
|
||||||
|
"branchLeaderName": "李燕",
|
||||||
|
"cantCode": "",
|
||||||
|
"cantName": "",
|
||||||
|
"costOrgCode": null,
|
||||||
|
"costOrgId": null,
|
||||||
|
"costOrgName": null,
|
||||||
|
"country": "",
|
||||||
|
"createTime": "2023-10-12 16:50:45",
|
||||||
|
"endDate": null,
|
||||||
|
"extendItems": [
|
||||||
|
{
|
||||||
|
"columnComment": "发薪日",
|
||||||
|
"columnName": "ext_payday",
|
||||||
|
"columnValue": "11"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"columnComment": "办公详细地址",
|
||||||
|
"columnName": "ext_office_address",
|
||||||
|
"columnValue": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"columnComment": "负责人编码",
|
||||||
|
"columnName": "ext_principal_num",
|
||||||
|
"columnValue": ""
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"foundDate": "2023-10-12",
|
||||||
|
"foundReason": null,
|
||||||
|
"globalOrder": "1106109103109104",
|
||||||
|
"hrbpCode": null,
|
||||||
|
"hrbpId": null,
|
||||||
|
"hrbpLeaderCode": null,
|
||||||
|
"hrbpLeaderId": null,
|
||||||
|
"hrbpLeaderName": null,
|
||||||
|
"hrbpName": null,
|
||||||
|
"inUse": "1",
|
||||||
|
"kqCommissionerCode": null,
|
||||||
|
"kqCommissionerId": null,
|
||||||
|
"kqCommissionerName": null,
|
||||||
|
"manageOrgCode": null,
|
||||||
|
"manageOrgName": null,
|
||||||
|
"manageStaff": null,
|
||||||
|
"manageStaffCode": null,
|
||||||
|
"manageStaffId": null,
|
||||||
|
"manageStruId": null,
|
||||||
|
"officeAddress": "1",
|
||||||
|
"operateTime": "2026-08-03 09:19:01",
|
||||||
|
"orgCode": "00615",
|
||||||
|
"orgFullPath": "集团-金色印象事业部-第一大区-金色印象渝北经营中心-第一片区-爱琴海行政会馆",
|
||||||
|
"orgId": "6e8c42f6-68dc-11ee-b449-000c296f9469",
|
||||||
|
"orgName": "爱琴海行政会馆",
|
||||||
|
"orgTypeCode": "49",
|
||||||
|
"orgTypeName": "会馆",
|
||||||
|
"parentOrgCode": "00150",
|
||||||
|
"parentOrgId": "c4e6c766-c59d-4cf3-a99f-33aa2496eb35",
|
||||||
|
"parentOrgName": "第一片区",
|
||||||
|
"principalStaff": "吴俊良",
|
||||||
|
"principalStaffCode": "37000565",
|
||||||
|
"principalStaffId": "51711788-7a9f-11ec-b449-000c296f9469",
|
||||||
|
"remarks": null,
|
||||||
|
"salaryCommissionerCode": null,
|
||||||
|
"salaryCommissionerId": null,
|
||||||
|
"salaryCommissionerName": null,
|
||||||
|
"shortName": "爱琴海行政会馆",
|
||||||
|
"struOrder": 104.0,
|
||||||
|
"unitOrgCode": "00738",
|
||||||
|
"unitOrgId": "0bcdee12-e592-11ee-b449-000c296f9469",
|
||||||
|
"unitOrgName": "金色印象事业部"
|
||||||
|
},
|
||||||
|
"crm_json_extra": {
|
||||||
|
"host": "https://api.shuhe.crm.waf.37du.co",
|
||||||
|
"shop_id": "2010247",
|
||||||
|
"shop_key": "2UHRmwKS2qTes7dY7czK39241WLQccwe",
|
||||||
|
"sign_key": "nYXTVTgfgKmNm9uxFRWvY82PRLQFqC7q"
|
||||||
|
},
|
||||||
|
"created_at": "2025-07-20T18:43:49.685611",
|
||||||
|
"updated_at": "2026-09-22T11:14:18.896622"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,47 +1,74 @@
|
|||||||
一、延时加班
|
https://cus.allinpay.com/login
|
||||||
(一)驳回门槛(任一不满足直接驳回)
|
<div class="tab-content" id="loginTabContent">
|
||||||
1. 日期匹配规则:加班开始时间所属日期 = 加班申请日期。当日开始、次日结束的跨天加班,按开始时间判定日期,视为符合要求。
|
<!-- 账号登录 -->
|
||||||
2. 时长达标规则:以「申请结束时间 - 申请开始时间」计算申请加班总时长,统一执行以下计时标准:
|
<div class="tab-pane fade active show" id="account" role="tabpanel">
|
||||||
◦ 不足1小时的,直接驳回;
|
<form id="accountForm" action="/login" method="post" accept-charset="utf-8" style="width: 331.25px; min-height: 349px;">
|
||||||
◦ 满1小时及以上的,超出1小时的部分按0.5小时为单位向下取整累加,不足0.5小时的部分不计入有效时长。
|
<div class="form-group" id="userid_div">
|
||||||
◦ 跨天延时加班的总时长统一套用上述取整规则,不按日期分段计算。
|
<label class="label-username" for="userid"></label>
|
||||||
3. 区间合规校验:申请开始时间 ≥ 当日规定下班时间,且申请结束时间 ≤ 当日实际下班打卡时间;超出该区间的申请直接驳回。
|
<input type="text" class="form-control" id="userid" name="userid" placeholder="请输入登录帐号">
|
||||||
(二)弹性到岗兑换规则(仅影响结算时长,不影响审批通过与否)
|
<div class="invalid-feedback" id="userid_err"></div>
|
||||||
员工可使用当日加班时长等额兑换次日晚到时长,兑换额度、校验规则如下:
|
</div>
|
||||||
1. 弹性额度D计算规则
|
<div class="form-group" id="password_div">
|
||||||
◦ 计算基准:以当日实际下班打卡时间为准,与申请结束时间无关。
|
<label class="label-psw" for="password"></label>
|
||||||
◦ 触发条件:实际下班打卡时间 < 23:00 时,弹性额度 D=0,不可兑换次日晚到。
|
<input type="password" class="form-control usableClick" id="password" placeholder="请输入登录密码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||||
◦ 额度计算公式:实际下班打卡时间 ≥ 23:00 时,基础兑换额度1小时;超出23:00的部分,按0.5小时为单位向下取整,每满0.5小时累加0.5小时额度。
|
<input type="password" id="encpassword" name="encpassword" style="display: none;" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||||
公式:D = 1 + FLOOR( (实际下班打卡时间 - 23:00) / 0.5小时 ) × 0.5小时
|
<div class="invalid-feedback" id="password_err"></div>
|
||||||
2. 次日场景分支校验
|
</div>
|
||||||
对申请日的次日进行判断,符合以下任一情形的,不触发弹性兑换校验,仅校验当日申请与打卡、请假数据匹配(次日为休息且存在加班申请的,同步核实上班打卡记录):
|
<div class="form-group">
|
||||||
① 次日排班为“休息”或无排班;
|
<label class="label-vCode" for="captcha"></label>
|
||||||
② 次日排班数据获取失败;
|
<div class="input-group" id="captcha_div">
|
||||||
③ 次日有请假时段覆盖09:00(任意假期类型)。
|
<input type="text" class="form-control usableClick" id="captcha" name="cuserrorCode" placeholder="请输入验证码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||||
不属于以上情形的正常工作日,按次日实际打卡时间P进行校验:
|
<div class="invalid-feedback" id="captcha_err"></div>
|
||||||
① 无次日打卡记录:不触发弹性兑换校验,仅校验当日数据;
|
<div class="input-group-append">
|
||||||
② P ≤ 09:00:无晚到,无需兑换,直接通过;
|
<img src="/getvalidCode?type=cuserrorCode" dataflag="cuserrorCode" onclick="cusjsUtil.changeCode(this)" alt="验证码" class="captcha-img">
|
||||||
③ 09:00 < P ≤ 09:00+D:实际晚到时长 = P - 09:00,不足1小时按1小时计算;
|
</div>
|
||||||
校验规则:申请加班时长 + 实际晚到时长 ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回;
|
</div>
|
||||||
④ P > 09:00+D:可兑换的晚到时长最高按D计算,超出D的晚到部分按考勤迟到规则处理,不影响本次加班审批;
|
</div>
|
||||||
校验规则:申请加班时长 + D ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回。
|
<button type="button" class="btn btn-primary btn-block btn-lg" onclick="javascript:valandsubmit(this);">登录</button>
|
||||||
---
|
</form>
|
||||||
二、休息日加班
|
<div class="tab-pane__bottom">
|
||||||
(一)适用范围
|
<a href="javascript:void(0)" class="text-muted btnFirstLogin_a">创建账号</a>
|
||||||
1. 周末休息日加班;
|
<a href="javascript:void(0)" class="text-muted btnForgetPsw_a">忘记密码</a>
|
||||||
2. 除春节外的其余法定节假日加班,统一按本规则执行。
|
</div>
|
||||||
(二)审批条件(全部满足则通过,任一不满足即驳回)
|
</div>
|
||||||
1. 申请有效:申请加班时长 > 0;
|
|
||||||
2. 打卡完整:申请对应时段内有完整的上班打卡、下班打卡记录;跨次日0点的连续加班,下班打卡可在次日,只要时段连续、覆盖申请时段,即视为打卡完整;
|
<!-- 验证码登录 -->
|
||||||
3. 排班匹配:申请当日排班显示为休息;
|
<div class="tab-pane fade" id="sms" role="tabpanel">
|
||||||
4. 时长达标:上下班打卡的自然时间间隔(含午休、用餐等自然时长)满足申报档位要求:
|
<form id="smsForm" style="width: 331.25px; min-height: 349px;">
|
||||||
◦ 申报0.5天:打卡间隔 ≥ 4小时
|
<div class="form-group" id="phone_div">
|
||||||
◦ 申报1天:打卡间隔 ≥ 9小时
|
<label class="label-phonenumber" for="phone"></label>
|
||||||
◦ 申报1.5天:打卡间隔 ≥ 13小时
|
<input type="tel" class="form-control" id="phone" placeholder="请输入手机号">
|
||||||
◦ 申报2天:打卡间隔 ≥ 18小时
|
<input type="hidden" id="hid_uifMobile" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||||
以此类推,每增加0.5天,对应时长要求增加4小时。
|
<div class="invalid-feedback" id="phone_err"></div>
|
||||||
---
|
</div>
|
||||||
三、法定假日加班(仅春节法定节假日适用)
|
<div class="form-group">
|
||||||
1. 基础审批规则与休息日加班完全一致;
|
<label class="label-vCode" for="captcha"></label>
|
||||||
2. 额外校验:申请日期必须为春节法定节假日;春节假期内的调休休息日,不适用本规则,按休息日加班规则执行。
|
<div class="input-group" id="phone_captcha_div">
|
||||||
---
|
<input type="text" class="form-control usableClick" id="phone_captcha" name="cuserrorCode" placeholder="请输入验证码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||||
|
<div class="invalid-feedback" id="phone_captcha_err"></div>
|
||||||
|
<div class="input-group-append">
|
||||||
|
<img src="/getvalidCode?type=mobileloginCode" dataflag="mobileloginCode" id="phone_captcha_id" onclick="cusjsUtil.changeCode(this)" alt="验证码" class="captcha-img">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group" id="smsCode_div">
|
||||||
|
<label class="label-vCode" for="smsCode"></label>
|
||||||
|
<div class="input-group">
|
||||||
|
<input type="text" class="form-control" id="smsCode" placeholder="请输入验证码">
|
||||||
|
<div class="invalid-feedback" id="smsCode_err"></div>
|
||||||
|
<div class="input-group-append">
|
||||||
|
<button class="btn btn-smsCode" type="button" id="getSmsCode">获取验证码</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn btn-primary btn-block btn-lg" onclick="javascript:valandsubmit(this);">登录</button>
|
||||||
|
<div class="tab-pane__tips">
|
||||||
|
<i class="icon-warning"></i><p class="text-muted">请先绑定用户后,再使用快捷登录</p><a href="javascript:void(0)" onclick="bindMobie('')">去绑定</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div class="tab-pane__bottom">
|
||||||
|
<a href="javascript:void(0)" class="text-muted btnFirstLogin_a">创建账号</a>
|
||||||
|
<a href="javascript:void(0)" class="text-muted btnForgetPsw_a">忘记密码</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -7,3 +7,7 @@
|
|||||||
@Description: 应用主包
|
@Description: 应用主包
|
||||||
@Version: 1.0.0
|
@Version: 1.0.0
|
||||||
"""
|
"""
|
||||||
|
from app.common.env import load_app_env
|
||||||
|
|
||||||
|
# 导入 app 任意模块时即加载本模块专属 env(app/.env),保证与 cwd 无关、与其它方向互不干扰
|
||||||
|
load_app_env()
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Package: app.common
|
||||||
|
@Description: 项目公共模块(跨业务复用的通用能力)。
|
||||||
|
"""
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# -*- 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)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -4,6 +4,6 @@
|
|||||||
@FileName: __init__.py
|
@FileName: __init__.py
|
||||||
@Author: 小布丁
|
@Author: 小布丁
|
||||||
@CreateTime: 2026-08-05 17:00
|
@CreateTime: 2026-08-05 17:00
|
||||||
@Description: HRBP 审批服务包:oa(OA 系统公共模块)+ flows(业务流程:请假/加班等)
|
@Description: HRBP 审批服务包:oa(OA 系统公共模块 + 业务流程:请假/加班等)
|
||||||
@Version: 1.0.0
|
@Version: 1.0.0
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# -*- 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.
|
After Width: | Height: | Size: 94 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 106 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 97 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,27 @@
|
|||||||
|
# -*- 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": "年度福利假",
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# -*- 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}")
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
# -*- 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 "失败")
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.ehr
|
||||||
|
@Description: HR 系统相关业务模块
|
||||||
|
"""
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# -*- 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"]
|
||||||
@@ -0,0 +1,837 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.ehr.attendance
|
||||||
|
@Description: 考勤异常查询与导出模块
|
||||||
|
"""
|
||||||
@@ -0,0 +1,625 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,454 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.ehr.common
|
||||||
|
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||||
|
"""
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
# -*- 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,
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# -*- 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",
|
||||||
|
]
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# -*- 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, "")
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# -*- 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)
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
# -*- 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(),
|
||||||
|
)
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# -*- 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,
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.ehr.employer_insurance
|
||||||
|
@FileName: __init__.py
|
||||||
|
@Author: 小布丁
|
||||||
|
@CreateTime: 2026-08-13
|
||||||
|
@Description: 雇主险名额调度系统(app 版):花名册业务处理 + 在参名单名额调度 + 变更清单生成
|
||||||
|
@Version: 1.0.0
|
||||||
|
"""
|
||||||
@@ -0,0 +1,652 @@
|
|||||||
|
# -*- 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=["三十七度"])
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
# -*- 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
@@ -0,0 +1,135 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,650 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
# -*- 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}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.ehr.shift_abnormal
|
||||||
|
@FileName: __init__.py
|
||||||
|
@Description: 排班异常识别模块包。
|
||||||
|
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||||
|
"""
|
||||||
@@ -0,0 +1,527 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,411 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,528 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# -*- 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
|
||||||
|
"""
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
# -*- 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))
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.ehr.wage_card
|
||||||
|
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||||
|
"""
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -4,58 +4,139 @@
|
|||||||
@FileName: approval_flow.py
|
@FileName: approval_flow.py
|
||||||
@Author: 小布丁
|
@Author: 小布丁
|
||||||
@CreateTime: 2026-08-05 23:52
|
@CreateTime: 2026-08-05 23:52
|
||||||
@Description: 公共审批引擎:登录(复用登录态)→ 查待办 → 解析 SSO → 获取表单 → 校验 → 生成报告
|
@Description: 公共审批引擎:登录(复用登录态)-> 查待办 -> 解析 SSO -> 获取表单 -> 校验 -> 生成报告
|
||||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
||||||
@Version: 1.2.0
|
@Version: 1.2.0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import time
|
||||||
from typing import Any, Callable, Dict, List
|
from typing import Any, Callable, Dict, List
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
from app.utils.logger import get_logger, setup_logging
|
||||||
|
from app.utils.intelligent_retry import retry
|
||||||
|
|
||||||
from utils.logger import get_logger, setup_logging
|
from app.service.hrbp.oa.common.login import oa_login
|
||||||
from utils.intelligent_retry import retry
|
from app.service.hrbp.oa.common.session_manager import (
|
||||||
|
init_session_from_page,
|
||||||
try:
|
refresh_session_cookies,
|
||||||
from .login import oa_login
|
load_saved_session,
|
||||||
from .session_manager import (
|
save_browser_cookies,
|
||||||
init_session_from_page,
|
create_browser_with_saved_cookies,
|
||||||
refresh_session_cookies,
|
is_session_valid,
|
||||||
load_saved_session,
|
COOKIE_FILE,
|
||||||
save_browser_cookies,
|
)
|
||||||
create_browser_with_saved_cookies,
|
from app.service.hrbp.oa.common.oa_api import (
|
||||||
is_session_valid,
|
OALoginExpiredError,
|
||||||
)
|
get_documents,
|
||||||
from .oa_api import (
|
get_wf_activity_by_task_id,
|
||||||
get_documents,
|
extract_form_id,
|
||||||
get_wf_activity_by_task_id,
|
get_business_data,
|
||||||
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
|
||||||
from .sso import resolve_sso_params
|
|
||||||
except ImportError:
|
|
||||||
from login import oa_login
|
|
||||||
from session_manager import (
|
|
||||||
init_session_from_page,
|
|
||||||
refresh_session_cookies,
|
|
||||||
load_saved_session,
|
|
||||||
save_browser_cookies,
|
|
||||||
create_browser_with_saved_cookies,
|
|
||||||
is_session_valid,
|
|
||||||
)
|
|
||||||
from oa_api import (
|
|
||||||
get_documents,
|
|
||||||
get_wf_activity_by_task_id,
|
|
||||||
extract_form_id,
|
|
||||||
get_business_data,
|
|
||||||
)
|
|
||||||
from sso import resolve_sso_params
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
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)
|
@retry(max_attempts=3)
|
||||||
def _login():
|
def _login():
|
||||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||||
@@ -81,16 +162,16 @@ def _get_browser_and_session(subject: str):
|
|||||||
return browser, session, True
|
return browser, session, True
|
||||||
|
|
||||||
|
|
||||||
@retry(max_attempts=3)
|
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||||
"""按主题拉取待办单据(失败自动重试,最多 3 次)"""
|
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||||
return get_documents(session, subject=subject)
|
return get_documents(session, subject=subject)
|
||||||
|
|
||||||
|
|
||||||
@retry(max_attempts=3)
|
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
解析单据详情:SSO 取 taskId/businessKey → WfActivity 取 formId → WorkformEngine 取表单数据。
|
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
||||||
@@ -135,7 +216,7 @@ def run_flow(
|
|||||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
公共审批流程:登录(优先复用已保存会话)→ 查待办 → 逐单解析详情并校验 → 生成报告。
|
公共审批流程:登录(优先复用已保存会话)-> 查待办 -> 逐单解析详情并校验 -> 生成报告。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
subject: 待办标题关键字,如 "加班" / "请假"
|
subject: 待办标题关键字,如 "加班" / "请假"
|
||||||
@@ -148,35 +229,74 @@ def run_flow(
|
|||||||
setup_logging()
|
setup_logging()
|
||||||
logger.info("%s审批流程开始", subject)
|
logger.info("%s审批流程开始", subject)
|
||||||
|
|
||||||
browser, session, _ = _get_browser_and_session(subject)
|
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||||
|
for login_attempt in range(2):
|
||||||
docs = _fetch_documents(session, subject)
|
browser, session, _ = _get_browser_and_session(subject)
|
||||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for doc in docs:
|
|
||||||
try:
|
try:
|
||||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
docs = _fetch_documents(session, subject)
|
||||||
result = validate_doc(doc_detail, session)
|
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||||
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)
|
results = []
|
||||||
print("\n" + report)
|
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),
|
||||||
|
})
|
||||||
|
|
||||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
report = generate_report(results)
|
||||||
save_browser_cookies(browser)
|
print("\n" + report)
|
||||||
|
|
||||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
# 先推送摘要到钉钉
|
||||||
return 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
|
||||||
|
|||||||
@@ -5,42 +5,141 @@
|
|||||||
@Author: 小布丁
|
@Author: 小布丁
|
||||||
@CreateTime: 2026-08-05 17:09
|
@CreateTime: 2026-08-05 17:09
|
||||||
@Description: OA 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
@Description: OA 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
||||||
@Version: 1.2.0
|
@Version: 1.4.0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# ---------- OA 系统 ----------
|
# ---------- OA 系统 ----------
|
||||||
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
||||||
|
from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402
|
||||||
|
|
||||||
BASE_URL = "https://oa.37du.co"
|
BASE_URL = "https://oa.37du.co"
|
||||||
HR_BASE_URL = "https://hr.37du.co"
|
|
||||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
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" 对应需人工处理的审批类待办
|
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||||
FD_TYPE = "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 域名)
|
# OA 流程接口(hr 域名)
|
||||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
||||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
||||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||||
|
|
||||||
# 排班接口(hr 域名,按员工 + 年月查询当月排班)
|
# 考勤逐日接口(hr 域名,按员工 + 日期范围查询每日班次起止与上下班打卡,返回 data 数组)
|
||||||
PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc"
|
# 加班/请假流程校验统一使用该接口获取排班名/班次时段/上下班打卡,替代原排班日历接口与打卡流水接口。
|
||||||
|
# 注意:kq_status_total 按考勤状态分类返回(0=休息日、1=正常班、9=未打卡、11=异常),
|
||||||
# 考勤打卡明细接口(hr 域名,按员工 + 日期范围查询原始打卡记录)
|
# 需四种状态各查一次后按 work_day 合并去重,才能拿到全部班次信息与当天打卡。
|
||||||
KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc"
|
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||||
|
|
||||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||||
|
|
||||||
# ---------- 加班审批规则常量(对应 aa.md 审批规则) ----------
|
# 打卡明细接口(hr 域名,按员工 + 日期范围查询真实打卡明细)
|
||||||
# 次日正常上班时间 T(固定 09:00)
|
# 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"
|
WORK_START_TIME = "09:00"
|
||||||
# 当日规定下班时间(固定 18:00,用于区间合规校验)
|
# 当日规定下班时间兜底值:区间合规校验优先取员工当天排班结束时间(bc_end_time),
|
||||||
|
# 未获取到排班时段时才回退该默认值
|
||||||
WORK_END_TIME = "18:00"
|
WORK_END_TIME = "18:00"
|
||||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
||||||
FLEX_TRIGGER_TIME = "23:00"
|
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
|
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
|
||||||
|
|
||||||
# ---------- 分页 ----------
|
# ---------- 分页 ----------
|
||||||
DEFAULT_PAGE_SIZE = 15
|
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(见 common/oa_api/todo.py);
|
||||||
|
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||||
|
DEFAULT_PAGE_SIZE = 100
|
||||||
|
|||||||
@@ -9,12 +9,9 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
from app.utils.logger import get_logger
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from DrissionPage import ChromiumPage
|
from DrissionPage import ChromiumPage
|
||||||
@@ -51,8 +48,8 @@ def oa_login(
|
|||||||
异常:
|
异常:
|
||||||
若登录失败或关键元素未找到,抛出 RuntimeError
|
若登录失败或关键元素未找到,抛出 RuntimeError
|
||||||
"""
|
"""
|
||||||
# 加载 .env 环境变量(默认读取当前工作目录下的 .env)
|
# 加载 app/.env 环境变量(始终定位 app 根,与 cwd 无关)
|
||||||
load_dotenv()
|
load_app_env()
|
||||||
|
|
||||||
# 获取配置,参数优先于环境变量
|
# 获取配置,参数优先于环境变量
|
||||||
login_url = os.getenv('oa_login_url')
|
login_url = os.getenv('oa_login_url')
|
||||||
@@ -122,7 +119,7 @@ def oa_login(
|
|||||||
|
|
||||||
# ---------- 使用示例 ----------
|
# ---------- 使用示例 ----------
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
from utils.logger import setup_logging
|
from app.utils.logger import setup_logging
|
||||||
setup_logging()
|
setup_logging()
|
||||||
try:
|
try:
|
||||||
page = oa_login()
|
page = oa_login()
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
# -*- 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,532 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.oa_api
|
|
||||||
@FileName: oa_api.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:10
|
|
||||||
@Description: OA/HR 系统 API 模块,负责调用系统接口(待办列表、流程引擎、表单、排班等)
|
|
||||||
@Version: 1.3.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
import re
|
|
||||||
from typing import List, Dict, Any
|
|
||||||
from urllib.parse import urlencode
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
try:
|
|
||||||
from DrissionPage import SessionPage
|
|
||||||
except ImportError:
|
|
||||||
SessionPage = None
|
|
||||||
|
|
||||||
try:
|
|
||||||
from .config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
|
||||||
except ImportError:
|
|
||||||
from config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
|
||||||
|
|
||||||
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.fdSubject": subject, # 按标题关键字过滤(请假/加班)
|
|
||||||
"orderby": "fdCreateTime",
|
|
||||||
"ordertype": "down",
|
|
||||||
"page.pageNo": page_no,
|
|
||||||
"page.pageSize": page_size,
|
|
||||||
"__seq": int(time.time() * 1000), # 防缓存
|
|
||||||
}
|
|
||||||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
|
||||||
logger.debug("请求第 %d 页: %s", page_no, url)
|
|
||||||
|
|
||||||
session.get(url)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
|
||||||
try:
|
|
||||||
return resp.json()
|
|
||||||
except Exception:
|
|
||||||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
|
||||||
|
|
||||||
|
|
||||||
def parse_todo_list(data: 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
|
|
||||||
|
|
||||||
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))
|
|
||||||
|
|
||||||
return all_docs
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- WfActivity 接口:通过 taskId 获取 formId ----------
|
|
||||||
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)
|
|
||||||
|
|
||||||
session.post(url, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("WfActivity 请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(
|
|
||||||
f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.debug("WfActivity 返回: %s", json_data)
|
|
||||||
return json_data
|
|
||||||
|
|
||||||
|
|
||||||
def extract_form_id(wf_activity_data: 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
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- WorkformEngine 接口:获取加班申请表单数据 ----------
|
|
||||||
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)
|
|
||||||
|
|
||||||
session.post(url, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("WorkformEngine 请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(
|
|
||||||
f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 表单详情在 result 字段中(如 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
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 排班接口 ----------
|
|
||||||
def get_attendance_html(
|
|
||||||
session: SessionPage,
|
|
||||||
staff_id: str,
|
|
||||||
year: int,
|
|
||||||
month: int
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
获取指定员工某月的排班 HTML。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
staff_id: 员工 UUID
|
|
||||||
year: 年份(如 2026)
|
|
||||||
month: 月份(1-12)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
排班表格的 HTML 字符串(从返回 JSON 的 caleHtml 字段提取)
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
|
||||||
data = {
|
|
||||||
"type": "2",
|
|
||||||
"staffId": staff_id,
|
|
||||||
"year": str(year),
|
|
||||||
"month": str(month)
|
|
||||||
}
|
|
||||||
logger.info("获取排班: %s %d-%02d", staff_id, year, month)
|
|
||||||
|
|
||||||
session.post(url, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("排班请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"排班接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
raise RuntimeError("排班接口返回非 JSON 数据")
|
|
||||||
|
|
||||||
if json_data.get("success") != "true":
|
|
||||||
raise RuntimeError(f"排班接口返回失败: {json_data}")
|
|
||||||
|
|
||||||
html = json_data.get("caleHtml")
|
|
||||||
if not html:
|
|
||||||
raise RuntimeError("排班接口未返回 caleHtml 字段")
|
|
||||||
return html
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 考勤打卡明细接口 ----------
|
|
||||||
def get_attendance_records(
|
|
||||||
session: SessionPage,
|
|
||||||
staff_id: str,
|
|
||||||
start_date: str,
|
|
||||||
end_date: str
|
|
||||||
) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
查询员工某时间段的原始打卡明细。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
session: 已登录的 SessionPage 对象
|
|
||||||
staff_id: 员工 UUID
|
|
||||||
start_date: 查询起始日期 "YYYY-MM-DD"
|
|
||||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
打卡记录列表(接口返回的 jsonList,每条含 kq_time / status / time_order 等)
|
|
||||||
- status: "1"=上班打卡, "5"=下班打卡, "6"=重复打卡
|
|
||||||
- time_order: "1"=上班时段, "2"=下班时段
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 请求失败或响应异常
|
|
||||||
"""
|
|
||||||
params = {
|
|
||||||
"staff_id": staff_id,
|
|
||||||
"rootId": "",
|
|
||||||
"countId": "",
|
|
||||||
"bc_date": start_date,
|
|
||||||
"bc_date_end": end_date,
|
|
||||||
"begin": start_date,
|
|
||||||
"end": end_date,
|
|
||||||
}
|
|
||||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date)
|
|
||||||
|
|
||||||
session.get(KQ_DATA_URL, params=params)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("考勤打卡请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"考勤打卡接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(f"考勤打卡接口返回非 JSON 数据: {body}")
|
|
||||||
|
|
||||||
records = json_data.get("jsonList", [])
|
|
||||||
logger.info("打卡明细返回 %d 条", len(records))
|
|
||||||
return records
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 请假记录接口 ----------
|
|
||||||
def fetch_leave_record_page(
|
|
||||||
session: 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)
|
|
||||||
|
|
||||||
session.post(LEAVE_RECORD_URL, data=data)
|
|
||||||
resp = session.response
|
|
||||||
if not resp:
|
|
||||||
raise RuntimeError("请假记录请求失败,未获取到响应")
|
|
||||||
if resp.status_code != 200:
|
|
||||||
raise RuntimeError(f"请假记录接口状态码异常: {resp.status_code}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
json_data = resp.json()
|
|
||||||
except Exception:
|
|
||||||
body = (resp.text or "")[:200]
|
|
||||||
raise RuntimeError(f"请假记录接口返回非 JSON 数据: {body}")
|
|
||||||
|
|
||||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
|
||||||
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
|
|
||||||
|
|
||||||
page_info = json_data.get("data")
|
|
||||||
if not isinstance(page_info, dict):
|
|
||||||
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
|
|
||||||
return page_info
|
|
||||||
|
|
||||||
|
|
||||||
def get_leave_records(
|
|
||||||
session: 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
|
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# -*- 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",
|
||||||
|
]
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# -*- 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)
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
# -*- 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,167 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@Module: hrbp.oa.parser
|
|
||||||
@FileName: parser.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-05 17:10
|
|
||||||
@Description: 解析模块(HTML 排班表格解析,供请假校验使用)
|
|
||||||
@Version: 1.3.0
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import re
|
|
||||||
from collections import defaultdict
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import Any, Dict, List
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 排班 HTML 解析 ----------
|
|
||||||
def parse_attendance_html(html: str) -> Dict[str, str]:
|
|
||||||
"""
|
|
||||||
解析排班 HTML 表格,提取每个日期的班次名称。
|
|
||||||
|
|
||||||
示例 HTML 片段:
|
|
||||||
<a class='cale_a' ... data-temp='2026-08-01' ...>正常</a>
|
|
||||||
或 <a ...>休息</a>
|
|
||||||
|
|
||||||
Args:
|
|
||||||
html: 排班接口返回的 HTML 字符串
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
字典:{日期字符串: 班次名称}
|
|
||||||
例如:{"2026-08-01": "正常", "2026-08-02": "休息"}
|
|
||||||
"""
|
|
||||||
# 正则匹配 <a> 标签中的 data-temp 和文本内容
|
|
||||||
pattern = r'<a[^>]*data-temp="([^"]+)"[^>]*>([^<]+)</a>'
|
|
||||||
matches = re.findall(pattern, html)
|
|
||||||
|
|
||||||
result = {}
|
|
||||||
for date, shift in matches:
|
|
||||||
# 去除可能的空格
|
|
||||||
date_clean = date.strip()
|
|
||||||
shift_clean = shift.strip()
|
|
||||||
result[date_clean] = shift_clean
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def get_work_days_in_range(
|
|
||||||
attendance_dict: Dict[str, str],
|
|
||||||
start_date: str,
|
|
||||||
end_date: str
|
|
||||||
) -> List[str]:
|
|
||||||
"""
|
|
||||||
根据排班字典和请假起止日期,返回请假区间内所有非“休息”的日期列表。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
attendance_dict: 由 parse_attendance_html 返回的字典
|
|
||||||
start_date: 请假开始日期,格式 "YYYY-MM-DD"
|
|
||||||
end_date: 请假结束日期,格式 "YYYY-MM-DD"
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
非休息日的日期字符串列表(格式 "YYYY-MM-DD")
|
|
||||||
"""
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
|
||||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
|
||||||
|
|
||||||
work_days = []
|
|
||||||
current = start
|
|
||||||
while current <= end:
|
|
||||||
date_str = current.strftime("%Y-%m-%d")
|
|
||||||
shift = attendance_dict.get(date_str, "")
|
|
||||||
# 如果该日期没有排班信息,或明确为“休息”,视为休息日
|
|
||||||
if shift != "休息" and shift != "":
|
|
||||||
work_days.append(date_str)
|
|
||||||
current += timedelta(days=1)
|
|
||||||
return work_days
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 打卡明细汇总 ----------
|
|
||||||
def summarize_attendance_records(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
||||||
"""
|
|
||||||
按日汇总员工打卡明细:每天取最早打卡和最晚打卡。
|
|
||||||
|
|
||||||
实际接口返回的打卡记录 status 多为 "6"、time_order 为 null,
|
|
||||||
无法据其区分上下班,因此直接按 bc_date 分组后取时间最早和最晚的打卡。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
records: get_attendance_records 返回的原始打卡列表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
每日汇总列表,每项含:
|
|
||||||
- staff_id / staff_name / dept_name / post_name / attend_date
|
|
||||||
- first_check_in: 当日最早打卡时间(字符串,无则 None)
|
|
||||||
- last_check_out: 当日最晚打卡时间(字符串,仅1条时为 None,含跨天凌晨)
|
|
||||||
"""
|
|
||||||
time_format = "%Y-%m-%d %H:%M:%S"
|
|
||||||
|
|
||||||
# 按 (staff_id, bc_date) 分组,取每天最早和最晚的打卡
|
|
||||||
group_map: Dict[tuple, List[Dict[str, Any]]] = defaultdict(list)
|
|
||||||
|
|
||||||
for item in records:
|
|
||||||
staff_id = item.get("staff_id", "")
|
|
||||||
bc_day = item.get("bc_date", "")
|
|
||||||
if not staff_id or not bc_day:
|
|
||||||
continue
|
|
||||||
|
|
||||||
try:
|
|
||||||
kq_dt = datetime.strptime(item["kq_time"], time_format)
|
|
||||||
except (KeyError, ValueError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt})
|
|
||||||
|
|
||||||
summary: List[Dict[str, Any]] = []
|
|
||||||
for (sid, day), items in group_map.items():
|
|
||||||
items.sort(key=lambda x: x["_dt"])
|
|
||||||
base = items[0]
|
|
||||||
row = {
|
|
||||||
"staff_id": sid,
|
|
||||||
"staff_name": base.get("staff_name", ""),
|
|
||||||
"dept_name": base.get("DEPT_ORG_NAME", ""),
|
|
||||||
"post_name": base.get("POST_ALIAS_NAME", ""),
|
|
||||||
"attend_date": day,
|
|
||||||
"first_check_in": items[0]["kq_time"],
|
|
||||||
"last_check_out": items[-1]["kq_time"] if len(items) > 1 else None,
|
|
||||||
}
|
|
||||||
summary.append(row)
|
|
||||||
|
|
||||||
return summary
|
|
||||||
|
|
||||||
|
|
||||||
# ---------- 使用示例(测试用) ----------
|
|
||||||
if __name__ == "__main__":
|
|
||||||
from utils.logger import setup_logging
|
|
||||||
setup_logging()
|
|
||||||
|
|
||||||
# 测试 HTML 解析
|
|
||||||
sample_html = """
|
|
||||||
<a class='cale_a' data-temp="2026-08-01">休息</a>
|
|
||||||
<a class='cale_a' data-temp="2026-08-02">正常</a>
|
|
||||||
<a class='cale_a' data-temp="2026-08-03">休息</a>
|
|
||||||
"""
|
|
||||||
result = parse_attendance_html(sample_html)
|
|
||||||
logger.info("解析结果: %s", result)
|
|
||||||
|
|
||||||
work = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
|
|
||||||
logger.info("工作日: %s", work)
|
|
||||||
|
|
||||||
# 测试打卡汇总
|
|
||||||
sample_records = [
|
|
||||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
|
||||||
"kq_time": "2026-08-02 08:50:00", "status": "1", "time_order": "1",
|
|
||||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
|
||||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
|
||||||
"kq_time": "2026-08-03 00:30:00", "status": "5", "time_order": "2",
|
|
||||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
|
||||||
]
|
|
||||||
summary = summarize_attendance_records(sample_records)
|
|
||||||
logger.info("打卡汇总: %s", summary)
|
|
||||||
@@ -10,11 +10,9 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
from app.common.app_paths import get_sessions_dir
|
||||||
|
from app.utils.logger import get_logger
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
@@ -24,9 +22,9 @@ except ImportError:
|
|||||||
ChromiumPage = None
|
ChromiumPage = None
|
||||||
SessionPage = None
|
SessionPage = None
|
||||||
|
|
||||||
# 登录 cookies 持久化目录:服务层统一管理各平台会话文件,文件名按平台区分
|
# 登录 cookies 持久化目录:统一放在 AppData\Local\37duAutomation,文件名按平台区分
|
||||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
||||||
_SESSIONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
_SESSIONS_DIR = get_sessions_dir()
|
||||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||||
|
|
||||||
|
|
||||||
@@ -130,14 +128,19 @@ def create_browser_with_saved_cookies(path: str = COOKIE_FILE) -> ChromiumPage:
|
|||||||
|
|
||||||
|
|
||||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
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:
|
try:
|
||||||
from .oa_api import fetch_todo_page
|
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||||
except ImportError:
|
resp = session.response
|
||||||
from oa_api import fetch_todo_page
|
if resp is None or resp.status_code != 200:
|
||||||
try:
|
return False
|
||||||
fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
text = resp.text
|
||||||
return True
|
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.info("会话已失效,需重新登录: %s", e)
|
logger.info("会话已失效,需重新登录: %s", e)
|
||||||
return False
|
return False
|
||||||
@@ -149,9 +152,6 @@ def create_session_from_login() -> SessionPage:
|
|||||||
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
||||||
再提取 SessionPage。
|
再提取 SessionPage。
|
||||||
"""
|
"""
|
||||||
try:
|
from app.service.hrbp.oa.common.login import oa_login
|
||||||
from .login import oa_login
|
|
||||||
except ImportError:
|
|
||||||
from login import oa_login
|
|
||||||
browser = oa_login()
|
browser = oa_login()
|
||||||
return init_session_from_page(browser)
|
return init_session_from_page(browser)
|
||||||
|
|||||||
@@ -8,14 +8,10 @@
|
|||||||
@Version: 1.0.1
|
@Version: 1.0.1
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from urllib.parse import urlparse, parse_qs
|
from urllib.parse import urlparse, parse_qs
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
from app.utils.logger import get_logger
|
||||||
|
|
||||||
from utils.logger import get_logger
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
@@ -48,7 +44,7 @@ def resolve_sso_params(
|
|||||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||||
|
|
||||||
# 浏览器打开 SSO 链接,页面 JS 自动重定向到详情页。
|
# 浏览器打开 SSO 链接,页面 JS 自动重定向到详情页。
|
||||||
# 跳转链: sso.mob → unifyWorkFlow.jsp(中间页,一闪而过) → goToWorkFlow 详情页。
|
# 跳转链: sso.mob -> unifyWorkFlow.jsp(中间页,一闪而过) -> goToWorkFlow 详情页。
|
||||||
# 因此不能等中间页(会匹配不到而超时卡 wait_timeout 秒),改为等待地址栏离开 SSO 链接。
|
# 因此不能等中间页(会匹配不到而超时卡 wait_timeout 秒),改为等待地址栏离开 SSO 链接。
|
||||||
browser.get(sso_url)
|
browser.get(sso_url)
|
||||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
# -*- 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,
|
||||||
|
)
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
# -*- 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))
|
||||||
@@ -8,24 +8,13 @@
|
|||||||
@Version: 1.2.0
|
@Version: 1.2.0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||||
import sys
|
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||||
|
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
|
||||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
||||||
|
|
||||||
try:
|
|
||||||
from ..common.approval_flow import run_flow
|
|
||||||
from .validator import validate_doc
|
|
||||||
from .reporter import generate_report
|
|
||||||
except ImportError:
|
|
||||||
from common.approval_flow import run_flow
|
|
||||||
from validator import validate_doc
|
|
||||||
from reporter import generate_report
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
"""请假审批:登录 → 查待办 → 解析SSO → 获取表单 → 校验 → 报告"""
|
"""请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||||
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# -*- 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"),
|
||||||
|
}
|
||||||
@@ -4,26 +4,131 @@
|
|||||||
@FileName: reporter.py
|
@FileName: reporter.py
|
||||||
@Author: 小布丁
|
@Author: 小布丁
|
||||||
@CreateTime: 2026-08-05 17:11
|
@CreateTime: 2026-08-05 17:11
|
||||||
@Description: 请假流程报告模块,生成审批报告
|
@Description: 请假流程报告模块。
|
||||||
@Version: 1.1.0
|
校验结果分三组:通过 / 校验不通过未处理 / 人工复核。
|
||||||
|
输出两份清单:
|
||||||
|
《请假审批校验不通过未处理人员明细清单》:员工姓名、假期类型、校验不通过原因、详情页链接
|
||||||
|
《附件人工复核待办清单》:员工姓名、假期类型、详情页链接(供人工打开查看附件)
|
||||||
|
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||||
|
@Version: 4.1.0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Any, Dict, List
|
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:
|
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||||
"""
|
"""
|
||||||
根据校验结果生成请假审批报告。
|
生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||||
|
|
||||||
TODO: 按实际报告格式完善(导出 Excel/文件等)。
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
results: validate_doc 返回的校验结果列表
|
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
报告文本
|
报告文本
|
||||||
"""
|
"""
|
||||||
lines = ["请假审批报告", "=" * 30]
|
passed = [r for r in results if r.get("decision") == "通过"]
|
||||||
for r in results:
|
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||||
lines.append(f"{r.get('creator', '')} | {r.get('title', '')} | {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)
|
return "\n".join(lines)
|
||||||
|
|||||||
@@ -4,31 +4,345 @@
|
|||||||
@FileName: validator.py
|
@FileName: validator.py
|
||||||
@Author: 小布丁
|
@Author: 小布丁
|
||||||
@CreateTime: 2026-08-05 17:11
|
@CreateTime: 2026-08-05 17:11
|
||||||
@Description: 请假流程校验模块(审批规则:驳回/人工复核/通过)
|
@Description: 请假流程校验模块(审批决策三态:通过 / 校验不通过未处理 / 人工复核)
|
||||||
@Version: 1.1.0
|
1. 根据假期类型分支处理:
|
||||||
|
- 小时特假:请假当天是排班上班日即通过,否则校验不通过未处理
|
||||||
|
- 事假/调休假/半天休/普通事假等:排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||||
|
- 病假/特别福利假/特殊事假/产假:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);
|
||||||
|
天数不一致或缺附件 -> 校验不通过未处理
|
||||||
|
2. 排班数据获取:调用排班接口(rf_p_kq_count_SelectBanci,按工号+日期范围,含未来日期排班),
|
||||||
|
统计请假区间内非"休息"天数
|
||||||
|
@Version: 4.2.0
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Any, Dict
|
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]:
|
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
校验单张请假单据,返回审批决策。
|
校验单张请假单据,返回审批决策。
|
||||||
|
|
||||||
TODO: 请假审批规则在此实现(依据排班、假期类型、请假时长等判定通过/驳回/人工复核)。
|
流程:
|
||||||
|
1. 解析表单数据,提取假期类型、请假天数、附件等信息
|
||||||
|
2. 调用排班接口,计算请假区间内实际上班天数
|
||||||
|
3. 根据假期类型分支处理:
|
||||||
|
- 小时特假:请假当天为排班上班日 -> 通过,否则校验不通过未处理
|
||||||
|
- Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||||
|
- Group 2(病假/产假等):天数一致且已上传附件 -> 人工复核;否则校验不通过未处理
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||||
session: 已登录的 SessionPage 对象(用于调用排班接口)
|
session: 已登录的 SessionPage 对象(用于下载请假附件)
|
||||||
|
(排班数据走 HR 排班接口,独立使用 HR 登录态,不依赖该 session)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
校验结果,包含审批决策
|
校验结果,包含审批决策及详细信息
|
||||||
"""
|
"""
|
||||||
return {
|
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", ""),
|
"title": doc.get("title", ""),
|
||||||
"creator": doc.get("creator", ""),
|
"creator": doc.get("creator", ""),
|
||||||
"time": doc.get("time", ""),
|
"time": doc.get("time", ""),
|
||||||
"decision": "pending", # pending: 规则未实现,默认待处理
|
"detail_url": doc.get("detail_url", ""),
|
||||||
"note": "请假校验规则待补充",
|
"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
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@Module: hrbp.oa.resign_e_sign
|
||||||
|
@FileName: __init__.py
|
||||||
|
@Author: 小布丁
|
||||||
|
@CreateTime: 2026-08-20
|
||||||
|
@Description: 离职电子签流程审核模块:解析 -> 校验(三态均已完成才同意)-> 报告
|
||||||
|
@Version: 1.0.0
|
||||||
|
"""
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# -*- 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
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
# -*- 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)
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
# -*- 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)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# -*- 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()
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
# -*- 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
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user