rescue: 断电事故后工作区全量备份
This commit is contained in:
+82
-82
@@ -1,83 +1,83 @@
|
||||
# ---------- Python ----------
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
*.egg
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
eggs/
|
||||
sdist/
|
||||
wheels/
|
||||
*.manifest
|
||||
*.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-delete-this-directory.txt
|
||||
|
||||
# ---------- 虚拟环境 ----------
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# ---------- 环境变量 / 密钥 ----------
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
# 控制面签名密钥 / 运行期产物(禁止入库)
|
||||
.admin_secret
|
||||
.webhost.pid
|
||||
*.pid
|
||||
desktop/**/keys/
|
||||
desktop/**/packages/
|
||||
desktop/**/controlplane.db
|
||||
desktop/**/_cp_sessions.json
|
||||
# 各平台会话 cookies / 缓存目录(统一移入 %LOCALAPPDATA%\37duAutomation,禁止入库)
|
||||
**/.sessions/
|
||||
|
||||
# ---------- IDE ----------
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# ---------- 操作系统 ----------
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# ---------- 日志 ----------
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# ---------- 测试 / 覆盖率 ----------
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.tox/
|
||||
aa.md
|
||||
|
||||
# vc运行库
|
||||
vc_redist/
|
||||
vc_redist_x64/
|
||||
vc_redist_x86/
|
||||
|
||||
静态资源/
|
||||
# ---------- Python ----------
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
*.egg
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
eggs/
|
||||
sdist/
|
||||
wheels/
|
||||
*.manifest
|
||||
*.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-delete-this-directory.txt
|
||||
|
||||
# ---------- 虚拟环境 ----------
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# ---------- 环境变量 / 密钥 ----------
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
# 控制面签名密钥 / 运行期产物(禁止入库)
|
||||
.admin_secret
|
||||
.webhost.pid
|
||||
*.pid
|
||||
desktop/**/keys/
|
||||
desktop/**/packages/
|
||||
desktop/**/controlplane.db
|
||||
desktop/**/_cp_sessions.json
|
||||
# 各平台会话 cookies / 缓存目录(统一移入 %LOCALAPPDATA%\37duAutomation,禁止入库)
|
||||
**/.sessions/
|
||||
|
||||
# ---------- IDE ----------
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# ---------- 操作系统 ----------
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# ---------- 日志 ----------
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# ---------- 测试 / 覆盖率 ----------
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.tox/
|
||||
aa.md
|
||||
|
||||
# vc运行库
|
||||
vc_redist/
|
||||
vc_redist_x64/
|
||||
vc_redist_x86/
|
||||
|
||||
静态资源/
|
||||
.assets/
|
||||
@@ -1,182 +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 证书未部署需面板处理 / 后端服务未监听需确认>;否则无`。
|
||||
---
|
||||
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 证书未部署需面板处理 / 后端服务未监听需确认>;否则无`。
|
||||
|
||||
@@ -1,43 +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`),或中心机本机密钥自签。
|
||||
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,235 +1,235 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Process-Automation
|
||||
Copyright (C) 2026 spudding
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Process-Automation
|
||||
Copyright (C) 2026 spudding
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
@@ -1,208 +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"
|
||||
}
|
||||
]
|
||||
{
|
||||
"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,74 +1,74 @@
|
||||
https://cus.allinpay.com/login
|
||||
<div class="tab-content" id="loginTabContent">
|
||||
<!-- 账号登录 -->
|
||||
<div class="tab-pane fade active show" id="account" role="tabpanel">
|
||||
<form id="accountForm" action="/login" method="post" accept-charset="utf-8" style="width: 331.25px; min-height: 349px;">
|
||||
<div class="form-group" id="userid_div">
|
||||
<label class="label-username" for="userid"></label>
|
||||
<input type="text" class="form-control" id="userid" name="userid" placeholder="请输入登录帐号">
|
||||
<div class="invalid-feedback" id="userid_err"></div>
|
||||
</div>
|
||||
<div class="form-group" id="password_div">
|
||||
<label class="label-psw" for="password"></label>
|
||||
<input type="password" class="form-control usableClick" id="password" placeholder="请输入登录密码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<input type="password" id="encpassword" name="encpassword" style="display: none;" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="password_err"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="label-vCode" for="captcha"></label>
|
||||
<div class="input-group" id="captcha_div">
|
||||
<input type="text" class="form-control usableClick" id="captcha" name="cuserrorCode" placeholder="请输入验证码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="captcha_err"></div>
|
||||
<div class="input-group-append">
|
||||
<img src="/getvalidCode?type=cuserrorCode" dataflag="cuserrorCode" onclick="cusjsUtil.changeCode(this)" alt="验证码" class="captcha-img">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<a href="javascript:void(0)" class="text-muted btnForgetPsw_a">忘记密码</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 验证码登录 -->
|
||||
<div class="tab-pane fade" id="sms" role="tabpanel">
|
||||
<form id="smsForm" style="width: 331.25px; min-height: 349px;">
|
||||
<div class="form-group" id="phone_div">
|
||||
<label class="label-phonenumber" for="phone"></label>
|
||||
<input type="tel" class="form-control" id="phone" placeholder="请输入手机号">
|
||||
<input type="hidden" id="hid_uifMobile" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="phone_err"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="label-vCode" for="captcha"></label>
|
||||
<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>
|
||||
https://cus.allinpay.com/login
|
||||
<div class="tab-content" id="loginTabContent">
|
||||
<!-- 账号登录 -->
|
||||
<div class="tab-pane fade active show" id="account" role="tabpanel">
|
||||
<form id="accountForm" action="/login" method="post" accept-charset="utf-8" style="width: 331.25px; min-height: 349px;">
|
||||
<div class="form-group" id="userid_div">
|
||||
<label class="label-username" for="userid"></label>
|
||||
<input type="text" class="form-control" id="userid" name="userid" placeholder="请输入登录帐号">
|
||||
<div class="invalid-feedback" id="userid_err"></div>
|
||||
</div>
|
||||
<div class="form-group" id="password_div">
|
||||
<label class="label-psw" for="password"></label>
|
||||
<input type="password" class="form-control usableClick" id="password" placeholder="请输入登录密码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<input type="password" id="encpassword" name="encpassword" style="display: none;" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="password_err"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="label-vCode" for="captcha"></label>
|
||||
<div class="input-group" id="captcha_div">
|
||||
<input type="text" class="form-control usableClick" id="captcha" name="cuserrorCode" placeholder="请输入验证码" readonly="readonly" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="captcha_err"></div>
|
||||
<div class="input-group-append">
|
||||
<img src="/getvalidCode?type=cuserrorCode" dataflag="cuserrorCode" onclick="cusjsUtil.changeCode(this)" alt="验证码" class="captcha-img">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<a href="javascript:void(0)" class="text-muted btnForgetPsw_a">忘记密码</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 验证码登录 -->
|
||||
<div class="tab-pane fade" id="sms" role="tabpanel">
|
||||
<form id="smsForm" style="width: 331.25px; min-height: 349px;">
|
||||
<div class="form-group" id="phone_div">
|
||||
<label class="label-phonenumber" for="phone"></label>
|
||||
<input type="tel" class="form-control" id="phone" placeholder="请输入手机号">
|
||||
<input type="hidden" id="hid_uifMobile" readonly="readonly" class="usableClick" onfocus="this.removeAttribute('readonly'); this.classList.remove('usableClick');">
|
||||
<div class="invalid-feedback" id="phone_err"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="label-vCode" for="captcha"></label>
|
||||
<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>
|
||||
@@ -1,9 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: HRBP 审批服务包:oa(OA 系统公共模块 + 业务流程:请假/加班等)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: HRBP 审批服务包:oa(OA 系统公共模块 + 业务流程:请假/加班等)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
@@ -1,9 +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
|
||||
"""
|
||||
# -*- 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
|
||||
"""
|
||||
|
||||
+489
-489
@@ -1,489 +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 "失败")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.common
|
||||
@FileName: login.py
|
||||
@Description: HR 登录 + 滑块验证(改进版:双候选 + 低置信度容忍)。
|
||||
HR 平台登录能力(原位于 ehr/common/login.py),上移到共享层供 ehr / oa 复用
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
from PIL import Image, ImageDraw
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
import cv2
|
||||
import numpy as np
|
||||
import io
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
LOGIN_URL = os.getenv('hr_login_url')
|
||||
SUCCESS_KEYWORD = os.getenv('hr_target_url_keyword')
|
||||
USERNAME = os.getenv('hr_login_username')
|
||||
PASSWORD = os.getenv('hr_login_password')
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
# 注意:不再使用 REFRESH_BTN
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
DEBUG_DIR = os.path.join(os.path.dirname(__file__), 'captcha_debug')
|
||||
|
||||
# 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,与 OA 系统一致)
|
||||
_COOKIE_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_COOKIE_DIR, 'hr_cookies.json')
|
||||
|
||||
def ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_COOKIE_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
def load_cookies():
|
||||
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
# ================== 改进的匹配函数(双候选 + 低置信度容忍) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes, debug_prefix=""):
|
||||
"""
|
||||
双候选匹配,返回最佳候选和次佳候选(即使置信度低)
|
||||
返回: (best_distance, best_conf, best_loc, candidates_list, x_offset, y_offset, slider_w, slider_h)
|
||||
其中 candidates_list 为 [(x, y, conf), ...] 用于绘制标记
|
||||
"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
|
||||
if bg_img is None or slider_color is None:
|
||||
print(f" [{debug_prefix}匹配错误] 无法解码图片")
|
||||
return None, 0, None, [], 0, 0, 0, 0
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
s_h, s_w = slider_color.shape[:2]
|
||||
print(f" [{debug_prefix}图片尺寸] 背景: {bg_w}x{bg_h}, 滑块原始: {s_w}x{s_h}")
|
||||
|
||||
# ---- 提取滑块有效区域 ----
|
||||
x_offset = 0
|
||||
y_offset = 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0 and len(xs) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max+1, x_min:x_max+1]
|
||||
x_offset = x_min
|
||||
y_offset = y_min
|
||||
print(f" [{debug_prefix}滑块裁剪] 有效区域: x=[{x_min},{x_max}], y=[{y_min},{y_max}], 裁剪后尺寸: {slider_rgb.shape[1]}x{slider_rgb.shape[0]}")
|
||||
else:
|
||||
print(f" [{debug_prefix}滑块裁剪] 未找到非透明区域,使用完整图")
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
else:
|
||||
if len(slider_color.shape) == 3:
|
||||
slider_rgb = slider_color
|
||||
else:
|
||||
slider_rgb = cv2.cvtColor(slider_color, cv2.COLOR_GRAY2BGR)
|
||||
x_offset = 0
|
||||
y_offset = 0
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
|
||||
# ---- 预处理:灰度 + 高斯模糊 + Canny ----
|
||||
gray_bg = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
|
||||
gray_slider = cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY)
|
||||
gray_bg = cv2.GaussianBlur(gray_bg, (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(gray_slider, (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
|
||||
# ---- 模板匹配(全图) ----
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
# 收集多个候选(前 6 个),避免真实缺口被最右侧干扰或滑块区假候选挤掉
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for i in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03: # 极低则停止
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
# 抑制周围
|
||||
y0 = max(0, max_loc[1] - s_h // 2)
|
||||
y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2)
|
||||
x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
print(f" [{debug_prefix}] 无有效候选")
|
||||
return None, 0, None, [], x_offset, y_offset, s_w, s_h
|
||||
|
||||
# 最右侧判定为干扰项:真实缺口不会紧贴背景图最右端
|
||||
right_margin = max(15, int(bg_w * 0.06))
|
||||
right_limit = bg_w - s_w - right_margin
|
||||
|
||||
# 真实缺口常为半透明白色矩形,白度是强判别信号(区域近白像素占比)
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y+h, x:x+w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
# 在有效区间 [s_w, right_limit] 内按「置信度 + 白度」综合评分选择
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit: # 排除左端滑块区与最右侧干扰
|
||||
continue
|
||||
wn = region_whiteness(x, y, s_w, s_h)
|
||||
score = val + 0.5 * wn
|
||||
scored.append((score, val, loc))
|
||||
print(f" [{debug_prefix}] 有效候选 loc={loc} conf={val:.4f} 白度={wn:.2f} 综合={score:.4f}")
|
||||
|
||||
if not scored:
|
||||
best_val, best_loc = candidates[0] # 全部落在无效区,回退全局最高
|
||||
print(f" [{debug_prefix}] 无有效区候选,回退最高置信度: loc={best_loc}, val={best_val:.4f}")
|
||||
else:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
print(f" [{debug_prefix}] 选择综合最优候选: loc={best_loc}, conf={best_val:.4f}")
|
||||
distance_phys = best_loc[0] - x_offset
|
||||
if distance_phys < 0:
|
||||
distance_phys = 0
|
||||
if distance_phys + s_w > bg_w:
|
||||
distance_phys = bg_w - s_w
|
||||
|
||||
# ---- 若置信度极低,尝试 ORB 辅助 ----
|
||||
if best_val < 0.25 and len(candidates) > 0:
|
||||
orb = cv2.ORB_create(nfeatures=500)
|
||||
kp1, des1 = orb.detectAndCompute(slider_edges, None)
|
||||
kp2, des2 = orb.detectAndCompute(bg_edges, None)
|
||||
if des1 is not None and des2 is not None and len(kp1) > 5 and len(kp2) > 5:
|
||||
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
|
||||
matches = bf.match(des1, des2)
|
||||
matches = sorted(matches, key=lambda x: x.distance)
|
||||
if len(matches) > 10:
|
||||
good = [m for m in matches[:30] if m.distance < np.mean([m.distance for m in matches[:15]]) * 0.7]
|
||||
if len(good) > 5:
|
||||
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
|
||||
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
|
||||
offsets = dst_pts - src_pts
|
||||
median_offset = np.median(offsets, axis=0)[0]
|
||||
orb_x = int(median_offset[0]) - x_offset
|
||||
if 0 < orb_x < bg_w - s_w:
|
||||
print(f" [{debug_prefix}] ORB辅助偏移: {orb_x}px (原模板置信度{best_val:.3f})")
|
||||
distance_phys = orb_x
|
||||
best_val = 0.5 # 提升置信度用于显示
|
||||
|
||||
# ---- 构建候选列表(用于绘图) ----
|
||||
candidate_points = []
|
||||
for val, loc in candidates:
|
||||
candidate_points.append((loc[0], loc[1], val))
|
||||
|
||||
print(f" [{debug_prefix}最终物理距离] distance={distance_phys}px (置信度 {best_val:.4f})")
|
||||
return distance_phys, best_val, best_loc, candidate_points, x_offset, y_offset, s_w, s_h
|
||||
|
||||
def draw_match_debug_multi(bg_bytes, slider_bytes, candidate_points, best_loc, x_offset, y_offset, slider_w, slider_h, distance_phys, distance_css, save_path):
|
||||
"""在背景图上绘制所有候选矩形和最佳匹配"""
|
||||
try:
|
||||
bg_img = Image.open(io.BytesIO(bg_bytes)).convert("RGBA")
|
||||
draw = ImageDraw.Draw(bg_img)
|
||||
|
||||
# 绘制所有候选(灰色虚线框)
|
||||
for i, (cx, cy, conf) in enumerate(candidate_points):
|
||||
if (cx, cy) == (best_loc[0], best_loc[1]):
|
||||
continue # 最佳单独绘制
|
||||
rect = [cx, cy, cx + slider_w, cy + slider_h]
|
||||
draw.rectangle(rect, outline="gray", width=1)
|
||||
draw.text((cx + 5, cy - 10), f"conf={conf:.2f}", fill="gray")
|
||||
|
||||
# 绘制最佳匹配(红色实线)
|
||||
if best_loc:
|
||||
rect = [best_loc[0], best_loc[1], best_loc[0] + slider_w, best_loc[1] + slider_h]
|
||||
draw.rectangle(rect, outline="red", width=3)
|
||||
text = f"best phys={distance_phys} css={distance_css}"
|
||||
draw.text((best_loc[0] + 5, best_loc[1] - 20), text, fill="red")
|
||||
|
||||
bg_img.save(save_path)
|
||||
print(f" [匹配标记] 已保存: {save_path}")
|
||||
except Exception as e:
|
||||
print(f" [匹配标记] 绘制失败: {e}")
|
||||
|
||||
# ================== 轨迹生成与滑动(与原相同) ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15))
|
||||
dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9))
|
||||
dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5))
|
||||
dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3))
|
||||
dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
dt = random.uniform(0.030, 0.080)
|
||||
if random.random() < 0.35:
|
||||
y = random.choice([-1, 0, 1])
|
||||
steps.append((dx, y, dt))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
if random.random() < 0.08:
|
||||
time.sleep(random.uniform(0.010, 0.035))
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
# ================== 验证码处理(移除刷新按钮,容忍低置信度) ==================
|
||||
def handle_captcha(page):
|
||||
ensure_dir(DEBUG_DIR)
|
||||
dpr = page.run_js('return window.devicePixelRatio')
|
||||
print(f"设备像素比(DPR): {dpr}")
|
||||
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry+1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
|
||||
bg_ele = container.ele(BG_IMG)
|
||||
if not bg_ele:
|
||||
bg_ele = container.ele('div[style*="background-image"]')
|
||||
if not bg_ele:
|
||||
print("找不到背景图元素")
|
||||
continue
|
||||
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not slider_ele:
|
||||
print("找不到滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
img_inner = slider_ele.ele('tag:img')
|
||||
if img_inner:
|
||||
slider_ele = img_inner
|
||||
|
||||
# 隐藏滑块 -> 截取背景 -> 恢复 -> 截取滑块
|
||||
bg_screenshot = None
|
||||
slider_screenshot = None
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception as e:
|
||||
print(f"隐藏/截图过程出错:{e}")
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
except:
|
||||
pass
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
# 保存原始截图
|
||||
bg_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}.png")
|
||||
slider_path = os.path.join(DEBUG_DIR, f"slider_{retry}.png")
|
||||
with open(bg_path, 'wb') as f:
|
||||
f.write(bg_screenshot)
|
||||
with open(slider_path, 'wb') as f:
|
||||
f.write(slider_screenshot)
|
||||
print(f" [调试截图] 背景: {bg_path}")
|
||||
print(f" [调试截图] 滑块: {slider_path}")
|
||||
|
||||
# 调用改进的匹配函数
|
||||
ret = match_slider_dual(bg_screenshot, slider_screenshot, debug_prefix=f"retry{retry}")
|
||||
if ret[0] is None:
|
||||
print("匹配失败,无候选,尝试随机拖动触发刷新")
|
||||
# 随机拖动一段距离(比如100-300px)尝试触发刷新
|
||||
random_css = random.uniform(100, 300) / dpr
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn:
|
||||
perform_slide(page, btn, random_css)
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
distance_phys, conf, best_loc, candidate_points, x_offset, y_offset, slider_w, slider_h = ret
|
||||
|
||||
# 转换为 CSS 距离
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" [置信度] {conf:.4f},物理距离: {distance_phys}px,CSS距离: {distance_css:.1f}px")
|
||||
|
||||
# 生成标记图(绘制所有候选)
|
||||
marked_path = os.path.join(DEBUG_DIR, f"bg_clean_{retry}_marked.png")
|
||||
draw_match_debug_multi(bg_screenshot, slider_screenshot, candidate_points, best_loc,
|
||||
x_offset, y_offset, slider_w, slider_h,
|
||||
distance_phys, distance_css, marked_path)
|
||||
|
||||
if distance_css <= 0:
|
||||
print(" CSS距离无效,尝试随机拖动")
|
||||
random_css = random.uniform(100, 300) / dpr
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn:
|
||||
perform_slide(page, btn, random_css)
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if not btn:
|
||||
print("找不到滑块按钮")
|
||||
continue
|
||||
|
||||
# 执行滑动
|
||||
perform_slide(page, btn, distance_css)
|
||||
time.sleep(2) # 等待验证结果
|
||||
|
||||
# 检查是否登录成功
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
# 若验证码容器消失,则认为验证通过
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
else:
|
||||
print("验证未通过,等待自动刷新...")
|
||||
# 不点击刷新按钮,等待网站自行更新验证码
|
||||
time.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
# ================== 登录主流程(不变) ==================
|
||||
def login():
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
|
||||
# 尝试复用已保存的 cookies,免重复登录
|
||||
saved = load_cookies()
|
||||
if saved:
|
||||
try:
|
||||
page.set.cookies(saved)
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已通过缓存的 Cookies 登录")
|
||||
return True
|
||||
print("缓存的 Cookies 已失效,重新登录")
|
||||
except Exception as e:
|
||||
print(f"复用 Cookies 失败:{e}")
|
||||
else:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
else:
|
||||
print("登录失败")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = login()
|
||||
print("最终结果:", "成功" if success else "失败")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr
|
||||
@Description: HR 系统相关业务模块
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr
|
||||
@Description: HR 系统相关业务模块
|
||||
"""
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,162 +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__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.attendance
|
||||
@FileName: attendance_stat_export.py
|
||||
@Description: 考勤统计报表逐日出勤导出:
|
||||
调用「考勤统计报表」接口分页抓取某月全集团数据(每人一行,含 v_1~v_最后一天),
|
||||
导出 Excel,列为「工号/姓名/部门/岗位 + 1日~最后一日」(默认上月,可按参数指定月份)。
|
||||
底层复用:hr_api.attendance_stat(报表抓取)、hr_session(会话管理)。
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 从项目根目录用模块方式运行(依赖打包为 app 包):
|
||||
python -m app.service.hrbp.ehr.attendance.attendance_stat_export
|
||||
2. 可选参数:<保存目录> <月份 YYYYMM>(默认上月)。
|
||||
3. 首次运行会自动完成 HR 登录并缓存 cookies,登录态过期自动重登。
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import fetch_all_attendance_stat
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError, refresh_hr_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 默认保存目录
|
||||
SAVE_DIR = r"D:\资料\人资\考勤统计"
|
||||
|
||||
# 身份信息列(对应报文 datas 里的字段)
|
||||
IDENTITY_COLS: List[Dict[str, str]] = [
|
||||
{"key": "base_code", "title": "工号"},
|
||||
{"key": "staff_name", "title": "姓名"},
|
||||
{"key": "dept_org_name", "title": "部门"},
|
||||
{"key": "post_name", "title": "岗位"},
|
||||
]
|
||||
|
||||
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质(None、浮点 .0 尾缀)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def last_month_ym(today: date = None) -> str:
|
||||
"""返回上月月份 "YYYYMM"。"""
|
||||
today = today or date.today()
|
||||
this_first = today.replace(day=1)
|
||||
last_end = this_first - timedelta(days=1)
|
||||
return f"{last_end.year:04d}{last_end.month:02d}"
|
||||
|
||||
|
||||
def _build_rows(records: List[Dict], days_in_month: int) -> List[Dict]:
|
||||
"""把报表 datas 转成导出行:身份信息 + 1日~最终日(v_1~v_N),缺失留空。"""
|
||||
rows: List[Dict] = []
|
||||
for rec in records:
|
||||
row = {item["title"]: _clean(rec.get(item["key"])) for item in IDENTITY_COLS}
|
||||
for day in range(1, days_in_month + 1):
|
||||
row[f"{day}日"] = _clean(rec.get(f"v_{day}"))
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def export_month_attendance(save_dir: str = None, month: str = None) -> str:
|
||||
"""导出某月考勤统计逐日出勤 Excel,返回文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYYMM"(默认上月)
|
||||
|
||||
Returns:
|
||||
导出文件路径
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
if not month:
|
||||
month = last_month_ym()
|
||||
year, mon = int(month[:4]), int(month[4:6])
|
||||
days_in_month = calendar.monthrange(year, mon)[1]
|
||||
logger.info("===== 考勤统计报表导出,月份:%s(%d 天) =====", month, days_in_month)
|
||||
|
||||
# 1. 会话校验 + 取当前用户 userId
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session = refresh_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError(f"getCurUserInfo 未返回 userId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s", user_id)
|
||||
|
||||
# 2. 分页抓取全集团考勤统计报表明细
|
||||
records = fetch_all_attendance_stat(session, user_id, month)
|
||||
logger.info("考勤统计报表共 %d 人", len(records))
|
||||
if not records:
|
||||
logger.error("考勤统计报表无数据,请检查月份或权限")
|
||||
return ""
|
||||
|
||||
# 3. 组装导出行并输出 Excel
|
||||
columns = [item["title"] for item in IDENTITY_COLS] + [f"{d}日" for d in range(1, days_in_month + 1)]
|
||||
rows = _build_rows(records, days_in_month)
|
||||
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"考勤统计报表_{month}_{ts}.xlsx"))
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
|
||||
df = pd.DataFrame(rows, columns=columns)
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
|
||||
logger.info("导出明细:%d 人 × %d 列", len(rows), len(columns))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【考勤统计报表汇总】")
|
||||
logger.info(" 月份:%s", month)
|
||||
logger.info(" 人数:%d 人", len(rows))
|
||||
logger.info(" 导出文件:%s", save_path)
|
||||
logger.info("=" * 60)
|
||||
return save_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
# 参数:<保存目录> <月份 YYYYMM>
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = export_month_attendance(save_dir, month)
|
||||
if out:
|
||||
logger.info("===== 考勤统计报表导出完成 =====")
|
||||
except Exception as e: # noqa: BLE001
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可。")
|
||||
return
|
||||
logger.error("考勤统计报表导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@Description: HR 系统公共模块(登录、接口调用、会话管理、配置)
|
||||
"""
|
||||
|
||||
@@ -1,130 +1,130 @@
|
||||
# -*- 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": "",
|
||||
}
|
||||
|
||||
# -*- 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"
|
||||
@@ -183,6 +183,6 @@ ROSTER_QUERY_BASE_PARAMS = {
|
||||
"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
|
||||
# 假期类型编码映射已上移到 HR 平台共享层 app/service/hrbp/common/config.py(VACATION_TYPE_MAP),
|
||||
# 由 ehr / oa 两系统统一引用,避免 oa 反向依赖 ehr。需要时从此处 import:
|
||||
# from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
|
||||
@@ -1,88 +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",
|
||||
]
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.common
|
||||
@FileName: hr_api/__init__.py
|
||||
@Description: HR 系统 API 包,按接口拆分到各子模块,此处统一导出(保持 from ...hr_api import X 兼容)
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.common.hr_session import HRSessionExpiredError, _is_expired, hr_request_json
|
||||
from app.service.hrbp.ehr.common.hr_api.wage_card import fetch_wage_card_page, fetch_all_wage_card
|
||||
from app.service.hrbp.ehr.common.hr_api.bank_dict import get_bank_dict, bank_type_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import (
|
||||
fetch_cur_user_info,
|
||||
fetch_attendance_abnormal_page,
|
||||
fetch_all_attendance_abnormal,
|
||||
adjust_abnormal,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_shift_page, fetch_all_shift, fetch_work_date_page, fetch_all_work_date
|
||||
from app.service.hrbp.ehr.common.hr_api.leave import fetch_leave_page, fetch_all_leave
|
||||
from app.service.hrbp.ehr.common.hr_api.overtime import fetch_overtime_page, fetch_all_overtime
|
||||
from app.service.hrbp.ehr.common.hr_api.kq_data import fetch_kq_data_page, fetch_all_kq_data
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance_stat import (
|
||||
fetch_attendance_stat_page,
|
||||
fetch_all_attendance_stat,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.org import fetch_org_page, fetch_all_orgs, to_org_rows
|
||||
from app.service.hrbp.ehr.common.hr_api.roster import (
|
||||
fetch_roster_page,
|
||||
fetch_all_rosters,
|
||||
to_roster_rows,
|
||||
build_leave_conditions,
|
||||
build_in_service_conditions,
|
||||
fetch_roster_code_dicts,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.hr_api.code_dict import get_code_dicts, code_to_name
|
||||
from app.service.hrbp.ehr.common.hr_api.roster_export import export_common_list, export_roster_excel
|
||||
|
||||
__all__ = [
|
||||
# base
|
||||
"HRSessionExpiredError",
|
||||
"_is_expired",
|
||||
"hr_request_json",
|
||||
# wage_card
|
||||
"fetch_wage_card_page",
|
||||
"fetch_all_wage_card",
|
||||
# bank_dict
|
||||
"get_bank_dict",
|
||||
"bank_type_to_name",
|
||||
# attendance
|
||||
"fetch_cur_user_info",
|
||||
"fetch_attendance_abnormal_page",
|
||||
"fetch_all_attendance_abnormal",
|
||||
"adjust_abnormal",
|
||||
# shift
|
||||
"fetch_shift_page",
|
||||
"fetch_all_shift",
|
||||
"fetch_work_date_page",
|
||||
"fetch_all_work_date",
|
||||
# leave
|
||||
"fetch_leave_page",
|
||||
"fetch_all_leave",
|
||||
# overtime
|
||||
"fetch_overtime_page",
|
||||
"fetch_all_overtime",
|
||||
# kq_data
|
||||
"fetch_kq_data_page",
|
||||
"fetch_all_kq_data",
|
||||
# attendance_stat
|
||||
"fetch_attendance_stat_page",
|
||||
"fetch_all_attendance_stat",
|
||||
# org
|
||||
"fetch_org_page",
|
||||
"fetch_all_orgs",
|
||||
"to_org_rows",
|
||||
# roster
|
||||
"fetch_roster_page",
|
||||
"fetch_all_rosters",
|
||||
"to_roster_rows",
|
||||
"build_leave_conditions",
|
||||
"build_in_service_conditions",
|
||||
"fetch_roster_code_dicts",
|
||||
# code_dict
|
||||
"get_code_dicts",
|
||||
"code_to_name",
|
||||
# roster_export
|
||||
"export_common_list",
|
||||
"export_roster_excel",
|
||||
]
|
||||
|
||||
@@ -1,145 +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) # 轻微限速,避免触发风控
|
||||
# -*- 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
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,190 +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 = ["在职"]
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险模块配置:集中管理文件路径、Sheet 名称、列名映射、校验常量等
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# ---------- 文件路径 ----------
|
||||
BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 输入/输出文件路径(三十七度默认,其余类别由 CATEGORIES 动态解析)
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」。
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位;
|
||||
# change_sheet_prefix: 步骤2调度时「变更清单」sheet 名称前缀(各类须统一该命名规则)。
|
||||
# scheme_suffix: 增员导入时「保险方案名称」追加的厂区后缀(HR 侧方案含后缀,
|
||||
# 如 人保-80万-秒创 / 人保-80万-湖畔 / 人保-80万-水庄;三十七度无后缀)。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
|
||||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称。"""
|
||||
return f"{category['change_sheet_prefix']}-{DATE_SHORT}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入文件(步骤3:在 HR「待增减人员」页面上传,aa.md 提供)
|
||||
ADD_SUB_IMPORT_ADD_FILE = os.path.join(BASE_DIR, "商业保险增员导入.xlsx")
|
||||
ADD_SUB_IMPORT_SUB_FILE = os.path.join(BASE_DIR, "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入模板(官方模板:第1行标题/第2行表头/第3行示例说明,第4行起填数据)
|
||||
ADD_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险增员导入模板.xlsx")
|
||||
SUB_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险减员导入模板.xlsx")
|
||||
|
||||
# 固定 Sheet 名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
CHANGE_SHEET_PREFIX = "37度-雇员变更清单"
|
||||
CHANGE_SHEET_NAME = f"{CHANGE_SHEET_PREFIX}-{DATE_SHORT}"
|
||||
|
||||
# ---------- 花名册列名映射(表头在第4行) ----------
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ---------- 校验常量 ----------
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
# ---------- 功能开关 ----------
|
||||
ENABLE_VALIDATION = False # True: 启用数据校验, False: 跳过校验(测试模式)
|
||||
|
||||
# ---------- 本场景 HR 花名册导出模板(roster_export 动态传入,取自 ehr/common 统一配置) ----------
|
||||
ROSTER_TEMPLATE_NAME = ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# 本场景需导出的在职状态(雇主险增减员只需在职人员,无需离职)
|
||||
ROSTER_EXPORT_STATUSES = ["在职"]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,135 +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()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.export_change_sheet
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统(app 版)「步骤2.5:导出变更清单独立工作簿」
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
【运行】python export_change_sheet.py [类别名]
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from copy import copy # noqa: E402
|
||||
from openpyxl import Workbook, load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
CATEGORIES,
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_name: str = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
|
||||
@@ -1,236 +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()
|
||||
# -*- 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()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,317 +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}
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.roster.roster_query
|
||||
@FileName: roster_query.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 花名册共享查询模块 —— 根据员工工号查询:
|
||||
1. 店长查询:返回其所在四级部门的店长工号与姓名(岗位含「店长」,多个取第一个);
|
||||
2. 人事查询:返回其所在经营中心(二级部门含「经营中心」)岗位含「人事」的全部名单;
|
||||
特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(梁敏/37001302),不查花名册。
|
||||
两类查询均支持批量(花名册只读一次)。供「告知书制作与下发」等业务流程复用。
|
||||
@Version: 1.2.0
|
||||
|
||||
使用方式(库函数,参数直接传):
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
find_store_manager, find_store_manager_batch,
|
||||
find_hr_personnel, find_hr_personnel_batch)
|
||||
- find_store_manager(工号, 花名册路径) -> {"success", "error", "manager_code", "manager_name"}
|
||||
- find_hr_personnel(工号, 花名册路径) -> {"success", "error", "dept", "personnel": [{"工号","姓名"}, ...]}
|
||||
- 批量:find_*_batch(工号列表, 花名册路径) -> {工号: 对应单查结果, ...}
|
||||
"""
|
||||
|
||||
import numbers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 默认花名册路径(告知书制作与下发)
|
||||
DEFAULT_ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx"
|
||||
|
||||
# 花名册字段列名(与 aa.md 字段一致)
|
||||
COL_NAME = "姓名" # 姓名
|
||||
COL_CODE = "工号" # 工号
|
||||
COL_DEPT2 = "二级部门" # 二级部门(经营中心)
|
||||
COL_DEPT4 = "四级部门" # 四级部门
|
||||
COL_POSITION = "岗位" # 岗位
|
||||
|
||||
# 岗位关键字(岗位字段包含对应关键字即视为该岗位)
|
||||
MANAGER_KEYWORD = "店长" # 店长岗位关键字
|
||||
HR_KEYWORD = "人事" # 人事岗位关键字
|
||||
DEPT2_MARK = "经营中心" # 二级部门需包含的经营中心标记
|
||||
|
||||
# 人事查询特殊分支:二级部门为「石桥铺会馆」时,不查花名册,直接返回固定人事名单
|
||||
DEPT2_HR_OVERRIDE = {
|
||||
"石桥铺会馆": [{"工号": "37001302", "姓名": "梁敏"}],
|
||||
}
|
||||
|
||||
|
||||
# ==================== 工具函数 ====================
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致匹配失败。
|
||||
|
||||
整型 float(如 37036835.0)去掉小数点后转 str,保证与文本工号("37036835")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _read_roster(roster_path):
|
||||
"""读取花名册,自动定位表头行(含「工号」列的行),返回 DataFrame(列名为字段名)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径
|
||||
|
||||
Returns:
|
||||
pd.DataFrame
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件不存在
|
||||
ValueError: 未找到表头行或缺少必需列(工号/姓名/二级部门/四级部门/岗位)
|
||||
"""
|
||||
roster_path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
|
||||
# 先不设表头读取前几行,定位含「工号」字段的表头行
|
||||
probe = pd.read_excel(roster_path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{roster_path}")
|
||||
|
||||
df = pd.read_excel(roster_path, header=header_row)
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT2, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({roster_path})")
|
||||
return df
|
||||
|
||||
|
||||
def _prepare_df(df):
|
||||
"""统一工号列文本格式并过滤空行,返回预处理后的 DataFrame(副本)。"""
|
||||
df = df.copy()
|
||||
df[COL_CODE] = df[COL_CODE].map(_to_text)
|
||||
return df[df[COL_CODE].notna()]
|
||||
|
||||
|
||||
# ==================== 核心查询 ====================
|
||||
def _find_store_manager_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询店长(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 2. 根据工号查四级部门
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
|
||||
# 3. 无四级部门 -> 返回查询失败、空结果
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门", code)
|
||||
return {"success": False, "error": f"员工(工号 {code})无四级部门",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 4. 在该四级部门内找岗位包含「店长」的人
|
||||
candidates = df[
|
||||
(df[COL_DEPT4].map(_to_text) == dept4)
|
||||
& (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))
|
||||
]
|
||||
if candidates.empty:
|
||||
logger.warning("四级部门「%s」内未找到店长(工号 %s)", dept4, code)
|
||||
return {"success": False, "error": f"四级部门「{dept4}」内未找到店长",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 5. 命中多个时取第一个(按花名册行序)
|
||||
first = candidates.iloc[0]
|
||||
manager_code = _to_text(first[COL_CODE])
|
||||
manager_name = _to_text(first[COL_NAME]) or ""
|
||||
logger.info("工号 %s -> 四级部门「%s」-> 店长 %s(工号 %s)",
|
||||
code, dept4, manager_name, manager_code)
|
||||
return {"success": True, "error": None,
|
||||
"manager_code": manager_code, "manager_name": manager_name}
|
||||
|
||||
|
||||
def _find_hr_personnel_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询经营中心人事名单(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
# 2. 校验二级部门
|
||||
dept2 = _to_text(row.iloc[0][COL_DEPT2]) or ""
|
||||
|
||||
# 2.1 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(不查花名册)
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
personnel = [dict(p) for p in DEPT2_HR_OVERRIDE[dept2]]
|
||||
logger.info("工号 %s -> 二级部门「%s」-> 固定人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
if DEPT2_MARK not in dept2:
|
||||
logger.warning("员工(工号 %s)二级部门「%s」不包含「%s」", code, dept2, DEPT2_MARK)
|
||||
return {"success": False, "error": f"员工(工号 {code})二级部门不包含「{DEPT2_MARK}」",
|
||||
"dept": dept2 or None, "personnel": []}
|
||||
|
||||
# 3. 查询该经营中心下岗位包含「人事」的所有名单
|
||||
candidates = df[
|
||||
(df[COL_DEPT2].map(_to_text) == dept2)
|
||||
& (df[COL_POSITION].astype(str).str.contains(HR_KEYWORD, na=False))
|
||||
]
|
||||
personnel = [
|
||||
{"工号": _to_text(r[COL_CODE]), "姓名": _to_text(r[COL_NAME]) or ""}
|
||||
for _, r in candidates.iterrows()
|
||||
]
|
||||
logger.info("工号 %s -> 经营中心「%s」-> 人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
|
||||
def _error_result(code, e):
|
||||
"""读取花名册失败时的统一错误结果(店长/人事两种结构)。"""
|
||||
return {
|
||||
"store": {"success": False, "error": str(e),
|
||||
"manager_code": None, "manager_name": None},
|
||||
"hr": {"success": False, "error": str(e), "dept": None, "personnel": []},
|
||||
}
|
||||
|
||||
|
||||
def find_store_manager(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在四级部门的店长工号与姓名(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int,如 "37036835" / 37036835)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 无四级部门 / 部门内无店长 / 读取异常)
|
||||
manager_code: str|None 店长工号
|
||||
manager_name: str|None 店长姓名
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["store"]
|
||||
return _find_store_manager_in_df(df, code)
|
||||
|
||||
|
||||
def find_store_manager_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号的店长(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_store_manager 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["store"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_store_manager_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
|
||||
def find_hr_personnel(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在经营中心(二级部门)岗位包含「人事」的全部名单(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 二级部门不包含经营中心 / 读取异常)
|
||||
dept: str|None 二级部门(经营中心)
|
||||
personnel: list 人事名单 [{"工号": str, "姓名": str}, ...]
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["hr"]
|
||||
return _find_hr_personnel_in_df(df, code)
|
||||
|
||||
|
||||
def find_hr_personnel_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号所在经营中心的人事名单(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_hr_personnel 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["hr"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_hr_personnel_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.shift_abnormal
|
||||
@FileName: __init__.py
|
||||
@Description: 排班异常识别模块包。
|
||||
包含预入职台账导出等子模块,供排班异常识别业务场景复用。
|
||||
"""
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,411 +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__":
|
||||
# -*- 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()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@Description: 银行卡(工资卡)信息下载与核对、员工花名册自定义导出模块
|
||||
"""
|
||||
|
||||
@@ -1,89 +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()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查:下载工资卡汇总表并核对数据(身份证/姓名/银行卡号)。
|
||||
员工花名册已独立为 roster_export 模块,不再包含在此流程中。
|
||||
数据保存到 D:\\资料\\人资\\银行卡检查\\
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
直接运行本文件即可依次执行工资卡下载、工资卡核对。
|
||||
python bank_card_check.py
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_download import download_wage_card # noqa: E402
|
||||
from app.service.hrbp.ehr.wage_card.wage_card_check import check_wage_card # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_path = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_path
|
||||
logger.info("工资卡核对完成:%s", check_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python bank_card_check.py"""
|
||||
setup_logging()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,311 +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()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 工资卡汇总表核对:身份证一致性、姓名一致性、空值标记、银行卡号校验。
|
||||
读取工资卡汇总表 Excel,添加核对结果列后保存。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import get_bank_dict, bank_type_to_name # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 银行卡校验规则 =====================
|
||||
# 固定通用规则,无需随表格修改
|
||||
# 16 位银联卡 BIN(按银行归类,经实际工资卡数据比对核验)
|
||||
BIN_16 = {
|
||||
# 招商银行
|
||||
"621483", "621485", "621486", "622588", "622609",
|
||||
# 民生银行
|
||||
"621691", "622615", "622617", "622619", "622620", "622622",
|
||||
# 民生银行信用卡(16 位贷记卡)
|
||||
"622601",
|
||||
# 重庆农村商业银行
|
||||
"621258", "621465", "621528", "622867",
|
||||
# 浦东发展银行
|
||||
"621792", "621793", "622521",
|
||||
# 其他银行
|
||||
"621499", # 建设银行理财金卡
|
||||
"621755", # 重庆三峡银行
|
||||
"623020", # 华夏银行
|
||||
}
|
||||
# 18 位银联储蓄卡 BIN
|
||||
BIN_18 = {"622908"} # 兴业银行
|
||||
# 非 62 开头但合法的老版储蓄卡 BIN(历史卡仍在使用,标准均为 19 位)
|
||||
NON62_BIN = {
|
||||
"436742", # 建设银行龙卡储蓄卡
|
||||
"601382", # 中国银行长城电子借记卡
|
||||
"955882", # 工商银行牡丹灵通卡
|
||||
}
|
||||
# 正则:匹配全数字
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
def check_bank_card(card_raw) -> dict:
|
||||
"""校验银行卡号,返回 {card, status, reason}。"""
|
||||
# 处理 pandas 从 Excel 读取时将卡号转为 float 的问题
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw: # NaN
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
bin6 = card[:6]
|
||||
if not (card.startswith("62") or bin6 in NON62_BIN):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ===================== 核对分类 =====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account):
|
||||
"""按 4 类异常对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, id_inconsistent, bank_info)
|
||||
issues: 4 类异常标签(写入核对结果)
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
"""
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if _is_empty(bank_account):
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 身份证不一致(开户人身份证非空且与员工不一致) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
if id_inconsistent:
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
|
||||
# ---- 3. 姓名不一致(仅身份证一致时比对) ----
|
||||
if (not id_inconsistent and not _is_empty(card_idcard)
|
||||
and not _is_empty(card_name) and staff_name != card_name):
|
||||
issues.append("员工姓名与开户人姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 4. 银行卡信息异常(银行卡非空但格式/位数错误) ----
|
||||
if not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
issues.append("银行卡信息异常")
|
||||
basis.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
|
||||
return issues, basis, id_inconsistent, bank_info
|
||||
|
||||
|
||||
# ===================== 列名常量 =====================
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
|
||||
def _is_empty(val) -> bool:
|
||||
"""判断值是否为空(None、空字符串、NaN)。"""
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val: # NaN
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val) -> str:
|
||||
"""将身份证号/银行卡号统一转为字符串,处理 pandas 读取 Excel 时的 float 转换问题。"""
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val: # NaN
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
output_path: 核对结果保存路径,默认在输入文件同目录加 _核对结果
|
||||
|
||||
Returns:
|
||||
核对结果文件路径
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法处理 Excel")
|
||||
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if COL_BANK_NAME not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df[COL_BANK_NAME] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"] if bk else ""
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"] if bk else ""
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
# 将核对结果列移到最前面
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
# ---- 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_rows))
|
||||
abnormal = df[mask]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = f"{os.path.dirname(base)}{os.sep}工资卡异常名单{ext}"
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
abnormal_path = None
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return output_path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python wage_card_check.py [输入文件] [输出文件]"""
|
||||
setup_logging()
|
||||
input_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
|
||||
r"D:\资料\人资\银行卡检查", "工资卡汇总表.xlsx"
|
||||
)
|
||||
output_path = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
try:
|
||||
out = check_wage_card(input_path, output_path)
|
||||
logger.info("===== 工资卡核对完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,205 +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()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.wage_card
|
||||
@FileName: wage_card_download.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08 10:20
|
||||
@Description: 银行卡(工资卡)信息下载与核对:抓取「在职 + 离职」人员工资卡数据,
|
||||
将英文字段映射为中文并导出 .xlsx 汇总表。
|
||||
底层能力复用:接口调用(hr_api.py)、会话管理(session_manager.py)、接口地址(config.py)。
|
||||
@Version: 1.3.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可下载在职/离职工资卡数据并生成汇总 Excel。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
# 底层复用:接口调用 / 会话管理
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_wage_card_page,
|
||||
fetch_all_wage_card,
|
||||
get_bank_dict,
|
||||
bank_type_to_name,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.common.hr_session import ( # noqa: E402
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError:
|
||||
pd = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 配置区(自行修改) =====================
|
||||
# 接口地址、分页大小统一在 ehr/common/config.py 中维护
|
||||
# 导出文件名 & 默认保存目录
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
SAVE_DIR = r"D:\资料\人资\银行卡检查"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 提供)
|
||||
COL_MAP: Dict[str, str] = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
|
||||
# 自定义列展示顺序(核心字段放最前面)
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 离职筛选时间范围(按当前日期动态计算)
|
||||
# ----------------------------------------------
|
||||
def get_leave_range(today: date = None) -> tuple:
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
# 上月 1 日
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
# 本月 1 日
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 2. 登录态预检
|
||||
# ----------------------------------------------
|
||||
def preflight(session):
|
||||
"""正式抓取前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 导出汇总 Excel
|
||||
# ----------------------------------------------
|
||||
def export_excel(data_on_job: List[dict], data_leave: List[dict], save_dir: str = ".") -> str:
|
||||
"""合并在职/离职数据,字段映射为中文、调整列顺序并导出 .xlsx。
|
||||
|
||||
用 pandas 做数据处理,如需后续设置单元格格式可在保存前用 openpyxl 对 ws 加工。
|
||||
"""
|
||||
if pd is None:
|
||||
raise RuntimeError("缺少 pandas 依赖,无法导出 Excel")
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
save_path = os.path.abspath(os.path.join(save_dir, SAVE_NAME))
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def download_wage_card(save_dir: str = None) -> str:
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel,返回导出文件路径。"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = preflight(build_hr_session())
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("\n===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else SAVE_DIR
|
||||
try:
|
||||
out = download_wage_card(save_dir)
|
||||
logger.info("===== 抓取完成,导出:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("抓取失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,302 +1,302 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.approval_flow
|
||||
@FileName: approval_flow.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:52
|
||||
@Description: 公共审批引擎:登录(复用登录态)-> 查待办 -> 解析 SSO -> 获取表单 -> 校验 -> 生成报告
|
||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
refresh_session_cookies,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
is_session_valid,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
OALoginExpiredError,
|
||||
get_documents,
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.notify import push_report, build_push_summary
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 真实审批提交(默认关闭) ====================
|
||||
# 仅自动提交"同意"(校验通过):驳回/校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _approve_enabled() -> bool:
|
||||
"""是否启用真实审批提交(同意/退回申请人)。默认关闭。
|
||||
开关:.env 中 overtime_approve_enabled=true/false。
|
||||
未确认校验准确性前保持关闭,确认后再启用。"""
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
return os.getenv("overtime_approve_enabled", "false").lower() == "true"
|
||||
|
||||
|
||||
def _find_button(browser, selector: str, timeout: float = 3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
btn = browser.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = browser.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(browser, decision: str) -> Dict[str, str]:
|
||||
"""
|
||||
按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
Args:
|
||||
browser: 停留在详情页的 ChromiumPage
|
||||
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in _APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = _APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(browser, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = browser.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
|
||||
people = browser.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
def _get_browser_and_session(subject: str):
|
||||
"""
|
||||
获取浏览器和会话:优先复用已保存的登录 cookies,无效或不存在时才完整登录。
|
||||
|
||||
Returns:
|
||||
(browser, session, is_fresh_login)
|
||||
"""
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session, False
|
||||
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
||||
session: 已登录的 SessionPage 对象(用于后台 API 请求)
|
||||
doc: 单据信息(包含 detail_url)
|
||||
|
||||
Returns:
|
||||
单据信息 + taskId/businessKey/formId/formData
|
||||
"""
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
# Step 1: 浏览器打开 SSO 链接,从重定向后的 URL 提取 taskId 和 businessKey
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
|
||||
# SSO 的 linkLogin 在 hr 域产生了新的会话 cookie,先同步回 SessionPage
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
# Step 2: 通过 taskId 获取 formId
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
|
||||
# Step 3: 通过 businessKey + formId 获取表单数据
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
|
||||
return {
|
||||
**doc,
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
"formData": form_data,
|
||||
}
|
||||
|
||||
|
||||
def run_flow(
|
||||
subject: str,
|
||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||
) -> str:
|
||||
"""
|
||||
公共审批流程:登录(优先复用已保存会话)-> 查待办 -> 逐单解析详情并校验 -> 生成报告。
|
||||
|
||||
Args:
|
||||
subject: 待办标题关键字,如 "加班" / "请假"
|
||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
||||
generate_report: 校验结果报告生成函数
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过/校验不通过未处理,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
result["creator"], result["title"], result["decision"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 再推送完整报告(含审批明细),保证请假/加班通知都展示具体审批明细
|
||||
push_report(report, subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.approval_flow
|
||||
@FileName: approval_flow.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:52
|
||||
@Description: 公共审批引擎:登录(复用登录态)-> 查待办 -> 解析 SSO -> 获取表单 -> 校验 -> 生成报告
|
||||
加班/请假共用,业务差异通过 subject + validate_doc + generate_report 注入
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
init_session_from_page,
|
||||
refresh_session_cookies,
|
||||
load_saved_session,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
is_session_valid,
|
||||
COOKIE_FILE,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
OALoginExpiredError,
|
||||
get_documents,
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.notify import push_report, build_push_summary
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 真实审批提交(默认关闭) ====================
|
||||
# 仅自动提交"同意"(校验通过):驳回/校验不通过未处理一律不自动提交,保留待人工处理
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
|
||||
def _approve_enabled() -> bool:
|
||||
"""是否启用真实审批提交(同意/退回申请人)。默认关闭。
|
||||
开关:.env 中 overtime_approve_enabled=true/false。
|
||||
未确认校验准确性前保持关闭,确认后再启用。"""
|
||||
from app.common.env import load_app_env
|
||||
load_app_env()
|
||||
return os.getenv("overtime_approve_enabled", "false").lower() == "true"
|
||||
|
||||
|
||||
def _find_button(browser, selector: str, timeout: float = 3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
btn = browser.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = browser.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(browser, decision: str) -> Dict[str, str]:
|
||||
"""
|
||||
按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
Args:
|
||||
browser: 停留在详情页的 ChromiumPage
|
||||
decision: 校验决策(通过/校验不通过未处理;其余决策不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in _APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = _APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(browser, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
# 确认按钮为唯一 id,主文档直接用 ele() 高频等待其动态出现,避免 _find_button 的 iframe 遍历开销
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = browser.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
# 选人弹窗(容器常驻但默认隐藏,仅弹出时才可见)兜底
|
||||
people = browser.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
def _get_browser_and_session(subject: str):
|
||||
"""
|
||||
获取浏览器和会话:优先复用已保存的登录 cookies,无效或不存在时才完整登录。
|
||||
|
||||
Returns:
|
||||
(browser, session, is_fresh_login)
|
||||
"""
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session, False
|
||||
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject: str) -> List[Dict[str, Any]]:
|
||||
"""按主题拉取待办单据(失败自动重试,最多 3 次;登录失效直接上抛交给上层重登)"""
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析单据详情:SSO 取 taskId/businessKey -> WfActivity 取 formId -> WorkformEngine 取表单数据。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(用于执行 SSO 的 JS 跳转)
|
||||
session: 已登录的 SessionPage 对象(用于后台 API 请求)
|
||||
doc: 单据信息(包含 detail_url)
|
||||
|
||||
Returns:
|
||||
单据信息 + taskId/businessKey/formId/formData
|
||||
"""
|
||||
detail_url = doc.get("detail_url", "")
|
||||
if not detail_url:
|
||||
raise RuntimeError(f"单据无详情链接: {doc.get('title')}")
|
||||
|
||||
# Step 1: 浏览器打开 SSO 链接,从重定向后的 URL 提取 taskId 和 businessKey
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
|
||||
# SSO 的 linkLogin 在 hr 域产生了新的会话 cookie,先同步回 SessionPage
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
# Step 2: 通过 taskId 获取 formId
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
|
||||
# Step 3: 通过 businessKey + formId 获取表单数据
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
|
||||
return {
|
||||
**doc,
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
"formData": form_data,
|
||||
}
|
||||
|
||||
|
||||
def run_flow(
|
||||
subject: str,
|
||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||
) -> str:
|
||||
"""
|
||||
公共审批流程:登录(优先复用已保存会话)-> 查待办 -> 逐单解析详情并校验 -> 生成报告。
|
||||
|
||||
Args:
|
||||
subject: 待办标题关键字,如 "加班" / "请假"
|
||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
||||
generate_report: 校验结果报告生成函数
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
setup_logging()
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
orig_decision = result.get("decision")
|
||||
submit = submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
# 提交失败兜底:单据在 OA 中状态未变,不能仍标为通过/校验不通过未处理,
|
||||
# 归为「异常」并附机器结论,交由人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
result["审批结果"] = f"{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
result["creator"], result["title"], result["decision"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 再推送完整报告(含审批明细),保证请假/加班通知都展示具体审批明细
|
||||
push_report(report, subject)
|
||||
|
||||
# 保存最新 cookies(SSO 已刷新 hr 域会话,供下次运行免登录复用)
|
||||
save_browser_cookies(browser)
|
||||
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1,145 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:09
|
||||
@Description: OA 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
||||
from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402
|
||||
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
# ---------- 工作沟通推送接口(oa 域名) ----------
|
||||
# 人员搜索接口:按工号/姓名模糊搜索,返回人员 XML(<data id=.. name=..>)
|
||||
PERSON_SEARCH_URL = f"{BASE_URL}/sys/common/dataxml.jsp"
|
||||
# 附件上传接口:getuserkey / submit 两步共用
|
||||
ATT_UPLOAD_URL = f"{BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
# 附件二进制上传接口
|
||||
ATT_UPLOADER_URL = f"{BASE_URL}/sys/attachment/uploaderServlet"
|
||||
# 工作沟通提交接口(新建保存走 method=save&s_seq=1,真实抓包确认;aa.md 中 user.jsp 为错误端点)
|
||||
WORK_COMMUNICATION_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 新建工作沟通页面:method=add 返回表单页,其中含新建草稿 fdId 与通知方式随机字段 __notify_type_<id>
|
||||
WORK_COMMUNICATION_ADD_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do?method=add"
|
||||
# 保存工作沟通:POST 表单字段(application/x-www-form-urlencoded),成功返回「操作成功」提示页
|
||||
KM_COLLABORATE_SAVE_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 沟通内容 fdContent 序列化前缀:真实格式为 固定前缀 + {base64(HTML)}(前缀为抓包确认的固定字节)
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
# 沟通类型(fdCategoryId 必填 validate=required),全部类型如下,调用方可任选,默认「工作安排」
|
||||
FD_CATEGORY_COMMUNICATION = "15e4c970dd59cd559f096644cecadbc7" # 工作交流
|
||||
FD_CATEGORY_INFO = "15e4c980ff72365007fc1a741ceb0c7d" # 信息传递
|
||||
FD_CATEGORY_WORK_ARRANGE = "17646e8283a07a43be3003d485492a4f" # 工作安排
|
||||
FD_CATEGORY_PROJECT = "1767a1195ec34b0de7d53764c84812f1" # 项目沟通
|
||||
FD_CATEGORY_REMINDER = "17efb81557d1e74c532aa78407a95189" # 温馨提示
|
||||
FD_CATEGORY_OTHER = "15e4c985cd9a92cc54cb20c413d9b29e" # 其他
|
||||
# 沟通类型映射:名称 -> ID(submit 时支持直接传中文名)
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": FD_CATEGORY_COMMUNICATION,
|
||||
"信息传递": FD_CATEGORY_INFO,
|
||||
"工作安排": FD_CATEGORY_WORK_ARRANGE,
|
||||
"项目沟通": FD_CATEGORY_PROJECT,
|
||||
"温馨提示": FD_CATEGORY_REMINDER,
|
||||
"其他": FD_CATEGORY_OTHER,
|
||||
}
|
||||
# 默认沟通类型:工作安排
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_WORK_ARRANGE
|
||||
# 工作沟通(协作)业务模型名:附件绑定与沟通提交共用
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
# OA 流程接口(hr 域名)
|
||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 考勤逐日接口(hr 域名,按员工 + 日期范围查询每日班次起止与上下班打卡,返回 data 数组)
|
||||
# 加班/请假流程校验统一使用该接口获取排班名/班次时段/上下班打卡,替代原排班日历接口与打卡流水接口。
|
||||
# 注意:kq_status_total 按考勤状态分类返回(0=休息日、1=正常班、9=未打卡、11=异常),
|
||||
# 需四种状态各查一次后按 work_day 合并去重,才能拿到全部班次信息与当天打卡。
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
|
||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
|
||||
# 打卡明细接口(hr 域名,按员工 + 日期范围查询真实打卡明细)
|
||||
# kq_time=真实打卡时间、bc_date=考勤归属日(跨天打卡次日0点~6点归入前一天)、
|
||||
# time_order=上下班类型(1=上班、2=下班)。加班校验用其替代考勤逐日接口的打卡字段,
|
||||
# 避免人工拼接日期导致跨天打卡归属错误。
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
# 附件下载接口(hr 域名):按 fileId 下载请假单据附件。
|
||||
# 注意:该接口要求有效 EHR 会话(hr.37du.co),会话失效时返回登录页 HTML 或
|
||||
# "外部用户未登录,无法访问",而非报错状态码;前端"在线预览"走的是
|
||||
# PtFjk.mc?method=fjkViewPageDown(返回 HTML 预览页),RPA 下载不使用该地址
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 附件默认保存目录
|
||||
ATTACHMENT_SAVE_DIR = r"D:\资料\人资\请假流程审批\附件"
|
||||
|
||||
# 附件清单查询接口(hr 域名,见 aa.md):按 ids(逗号分隔 fileId)查询附件元信息
|
||||
# (fileName/fileSuffix/herfUrl 等),用于离职电子签签章附件(解除确认书/报酬支付确认)下载
|
||||
FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds"
|
||||
# 离职电子签签章附件默认保存目录
|
||||
RESIGN_ATTACHMENT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
|
||||
# 电子签真实签署状态查询接口(hr 域名,按 main_id 即合同业务主键查询):
|
||||
# is_initiate_sign 是否已发起电子签(hr_staff_contract.is_initiate_sign)
|
||||
# sign_status_yg 员工签署状态(esign_sigin_state)
|
||||
# sign_status_qy 企业签署状态(esign_sigin_state)
|
||||
# file 签章附件 fileId 串(",id1,id2",逗号分隔、可能带前导逗号)。
|
||||
# 接口变更后表单 getBusinessDate 的 contract_file 已恒为空串,
|
||||
# 附件 fileId 只能从本字段的签署记录中获取
|
||||
CONTRACT_SIGNATURE_SELECT_URL = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/getContentLinkage/redApi/"
|
||||
"rf_hr_staff_contract_signature_select_sp_cq37du/WorkformEngine.mc"
|
||||
)
|
||||
|
||||
# ---------- 加班审批规则常量 ----------
|
||||
# 正常上班时间 T 兜底值:所有用到上班时间的地方(区间合规的加班开始时间、弹性到岗
|
||||
# 兑换的次日上班时间、请假覆盖判断的早上上班时间等)都优先取排班开始时间
|
||||
# (bc_begin_time),未获取到排班时段时才回退该默认值
|
||||
WORK_START_TIME = "09:00"
|
||||
# 当日规定下班时间兜底值:区间合规校验优先取员工当天排班结束时间(bc_end_time),
|
||||
# 未获取到排班时段时才回退该默认值
|
||||
WORK_END_TIME = "18:00"
|
||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
|
||||
# 次日弹性上班扣减时扣除的中午休息时长(小时)
|
||||
LUNCH_BREAK_HOURS = 1
|
||||
# 延时加班有效时长门槛:不足该小时数直接校验不通过未处理
|
||||
OT_MIN_HOURS = 1
|
||||
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
# 职能排班半天加班时长:上午3.5小时、下午4.5小时
|
||||
# (休息日/节假日加班,不再统一按4小时半天处理,整天仍为9小时)
|
||||
ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
# 提前到岗型员工只会提前到、不会晚到:打卡须不晚于加班开始时间(晚到则无法证明开始时刻已到岗)。
|
||||
# 到岗打卡证据窗口:加班开始时间前1小时内(含开始时刻)的打卡视为到岗
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ---------- 分页 ----------
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(见 common/oa_api/todo.py);
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:09
|
||||
@Description: OA 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
||||
from app.service.hrbp.common.config import HR_BASE_URL # noqa: E402
|
||||
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
# ---------- 工作沟通推送接口(oa 域名) ----------
|
||||
# 人员搜索接口:按工号/姓名模糊搜索,返回人员 XML(<data id=.. name=..>)
|
||||
PERSON_SEARCH_URL = f"{BASE_URL}/sys/common/dataxml.jsp"
|
||||
# 附件上传接口:getuserkey / submit 两步共用
|
||||
ATT_UPLOAD_URL = f"{BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
# 附件二进制上传接口
|
||||
ATT_UPLOADER_URL = f"{BASE_URL}/sys/attachment/uploaderServlet"
|
||||
# 工作沟通提交接口(新建保存走 method=save&s_seq=1,真实抓包确认;aa.md 中 user.jsp 为错误端点)
|
||||
WORK_COMMUNICATION_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 新建工作沟通页面:method=add 返回表单页,其中含新建草稿 fdId 与通知方式随机字段 __notify_type_<id>
|
||||
WORK_COMMUNICATION_ADD_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do?method=add"
|
||||
# 保存工作沟通:POST 表单字段(application/x-www-form-urlencoded),成功返回「操作成功」提示页
|
||||
KM_COLLABORATE_SAVE_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 沟通内容 fdContent 序列化前缀:真实格式为 固定前缀 + {base64(HTML)}(前缀为抓包确认的固定字节)
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
# 沟通类型(fdCategoryId 必填 validate=required),全部类型如下,调用方可任选,默认「工作安排」
|
||||
FD_CATEGORY_COMMUNICATION = "15e4c970dd59cd559f096644cecadbc7" # 工作交流
|
||||
FD_CATEGORY_INFO = "15e4c980ff72365007fc1a741ceb0c7d" # 信息传递
|
||||
FD_CATEGORY_WORK_ARRANGE = "17646e8283a07a43be3003d485492a4f" # 工作安排
|
||||
FD_CATEGORY_PROJECT = "1767a1195ec34b0de7d53764c84812f1" # 项目沟通
|
||||
FD_CATEGORY_REMINDER = "17efb81557d1e74c532aa78407a95189" # 温馨提示
|
||||
FD_CATEGORY_OTHER = "15e4c985cd9a92cc54cb20c413d9b29e" # 其他
|
||||
# 沟通类型映射:名称 -> ID(submit 时支持直接传中文名)
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": FD_CATEGORY_COMMUNICATION,
|
||||
"信息传递": FD_CATEGORY_INFO,
|
||||
"工作安排": FD_CATEGORY_WORK_ARRANGE,
|
||||
"项目沟通": FD_CATEGORY_PROJECT,
|
||||
"温馨提示": FD_CATEGORY_REMINDER,
|
||||
"其他": FD_CATEGORY_OTHER,
|
||||
}
|
||||
# 默认沟通类型:工作安排
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_WORK_ARRANGE
|
||||
# 工作沟通(协作)业务模型名:附件绑定与沟通提交共用
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
# OA 流程接口(hr 域名)
|
||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 考勤逐日接口(hr 域名,按员工 + 日期范围查询每日班次起止与上下班打卡,返回 data 数组)
|
||||
# 加班/请假流程校验统一使用该接口获取排班名/班次时段/上下班打卡,替代原排班日历接口与打卡流水接口。
|
||||
# 注意:kq_status_total 按考勤状态分类返回(0=休息日、1=正常班、9=未打卡、11=异常),
|
||||
# 需四种状态各查一次后按 work_day 合并去重,才能拿到全部班次信息与当天打卡。
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
|
||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
|
||||
# 打卡明细接口(hr 域名,按员工 + 日期范围查询真实打卡明细)
|
||||
# kq_time=真实打卡时间、bc_date=考勤归属日(跨天打卡次日0点~6点归入前一天)、
|
||||
# time_order=上下班类型(1=上班、2=下班)。加班校验用其替代考勤逐日接口的打卡字段,
|
||||
# 避免人工拼接日期导致跨天打卡归属错误。
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
# 附件下载接口(hr 域名):按 fileId 下载请假单据附件。
|
||||
# 注意:该接口要求有效 EHR 会话(hr.37du.co),会话失效时返回登录页 HTML 或
|
||||
# "外部用户未登录,无法访问",而非报错状态码;前端"在线预览"走的是
|
||||
# PtFjk.mc?method=fjkViewPageDown(返回 HTML 预览页),RPA 下载不使用该地址
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 附件默认保存目录
|
||||
ATTACHMENT_SAVE_DIR = r"D:\资料\人资\请假流程审批\附件"
|
||||
|
||||
# 附件清单查询接口(hr 域名,见 aa.md):按 ids(逗号分隔 fileId)查询附件元信息
|
||||
# (fileName/fileSuffix/herfUrl 等),用于离职电子签签章附件(解除确认书/报酬支付确认)下载
|
||||
FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds"
|
||||
# 离职电子签签章附件默认保存目录
|
||||
RESIGN_ATTACHMENT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
|
||||
# 电子签真实签署状态查询接口(hr 域名,按 main_id 即合同业务主键查询):
|
||||
# is_initiate_sign 是否已发起电子签(hr_staff_contract.is_initiate_sign)
|
||||
# sign_status_yg 员工签署状态(esign_sigin_state)
|
||||
# sign_status_qy 企业签署状态(esign_sigin_state)
|
||||
# file 签章附件 fileId 串(",id1,id2",逗号分隔、可能带前导逗号)。
|
||||
# 接口变更后表单 getBusinessDate 的 contract_file 已恒为空串,
|
||||
# 附件 fileId 只能从本字段的签署记录中获取
|
||||
CONTRACT_SIGNATURE_SELECT_URL = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/getContentLinkage/redApi/"
|
||||
"rf_hr_staff_contract_signature_select_sp_cq37du/WorkformEngine.mc"
|
||||
)
|
||||
|
||||
# ---------- 加班审批规则常量 ----------
|
||||
# 正常上班时间 T 兜底值:所有用到上班时间的地方(区间合规的加班开始时间、弹性到岗
|
||||
# 兑换的次日上班时间、请假覆盖判断的早上上班时间等)都优先取排班开始时间
|
||||
# (bc_begin_time),未获取到排班时段时才回退该默认值
|
||||
WORK_START_TIME = "09:00"
|
||||
# 当日规定下班时间兜底值:区间合规校验优先取员工当天排班结束时间(bc_end_time),
|
||||
# 未获取到排班时段时才回退该默认值
|
||||
WORK_END_TIME = "18:00"
|
||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
|
||||
# 次日弹性上班扣减时扣除的中午休息时长(小时)
|
||||
LUNCH_BREAK_HOURS = 1
|
||||
# 延时加班有效时长门槛:不足该小时数直接校验不通过未处理
|
||||
OT_MIN_HOURS = 1
|
||||
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
# 职能排班半天加班时长:上午3.5小时、下午4.5小时
|
||||
# (休息日/节假日加班,不再统一按4小时半天处理,整天仍为9小时)
|
||||
ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
# 提前到岗型员工只会提前到、不会晚到:打卡须不晚于加班开始时间(晚到则无法证明开始时刻已到岗)。
|
||||
# 到岗打卡证据窗口:加班开始时间前1小时内(含开始时刻)的打卡视为到岗
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ---------- 分页 ----------
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(见 common/oa_api/todo.py);
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
|
||||
+127
-127
@@ -1,127 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.login
|
||||
@FileName: login.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-04 17:34
|
||||
@Description: 自动登录 OA 系统
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = lambda *args, **kwargs: None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def oa_login(
|
||||
username: str = None,
|
||||
password: str = None,
|
||||
timeout: float = 10,
|
||||
wait_after_load: float = 2,
|
||||
) -> ChromiumPage:
|
||||
"""
|
||||
自动登录 OA 系统,返回已登录的 ChromiumPage 对象。
|
||||
|
||||
参数:
|
||||
username: 登录用户名,若不提供则从环境变量 oa_login_username 读取
|
||||
password: 登录密码,若不提供则从环境变量 oa_login_password 读取
|
||||
|
||||
timeout: URL 跳转等待超时(秒,默认 10)
|
||||
wait_after_load: 页面加载后的额外等待时间(秒,默认 2)
|
||||
|
||||
返回:
|
||||
登录成功后的 ChromiumPage 对象
|
||||
|
||||
异常:
|
||||
若登录失败或关键元素未找到,抛出 RuntimeError
|
||||
"""
|
||||
# 加载 app/.env 环境变量(始终定位 app 根,与 cwd 无关)
|
||||
load_app_env()
|
||||
|
||||
# 获取配置,参数优先于环境变量
|
||||
login_url = os.getenv('oa_login_url')
|
||||
if not login_url:
|
||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||||
if not target_url_keyword:
|
||||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
||||
|
||||
final_username = username or os.getenv('oa_login_username')
|
||||
final_password = password or os.getenv('oa_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
||||
|
||||
# 创建浏览器页面对象
|
||||
page = ChromiumPage()
|
||||
# page.set.window.max()
|
||||
|
||||
try:
|
||||
# 访问登录页面
|
||||
page.get(login_url)
|
||||
time.sleep(wait_after_load) # 等待页面初步加载
|
||||
|
||||
# 定位并填写用户名
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# 定位并填写密码
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# 定位并点击登录按钮
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# ---------- 轮询检测 URL ----------
|
||||
start = time.time()
|
||||
while time.time() - start < timeout: # timeout 默认 10 秒
|
||||
if target_url_keyword in page.url:
|
||||
logger.info("登录成功!当前 URL: %s", page.url)
|
||||
return page
|
||||
time.sleep(0.5)
|
||||
|
||||
# 超时处理
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
logger.warning("登录失败,提示: %s", error_elem.text)
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
|
||||
except Exception as e:
|
||||
# 若发生异常,可选择关闭浏览器并重新抛出
|
||||
page.quit()
|
||||
raise RuntimeError(f"登录过程出错: {e}")
|
||||
|
||||
|
||||
# ---------- 使用示例 ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
try:
|
||||
page = oa_login()
|
||||
except RuntimeError as e:
|
||||
logger.error(e)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.login
|
||||
@FileName: login.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-04 17:34
|
||||
@Description: 自动登录 OA 系统
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = lambda *args, **kwargs: None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def oa_login(
|
||||
username: str = None,
|
||||
password: str = None,
|
||||
timeout: float = 10,
|
||||
wait_after_load: float = 2,
|
||||
) -> ChromiumPage:
|
||||
"""
|
||||
自动登录 OA 系统,返回已登录的 ChromiumPage 对象。
|
||||
|
||||
参数:
|
||||
username: 登录用户名,若不提供则从环境变量 oa_login_username 读取
|
||||
password: 登录密码,若不提供则从环境变量 oa_login_password 读取
|
||||
|
||||
timeout: URL 跳转等待超时(秒,默认 10)
|
||||
wait_after_load: 页面加载后的额外等待时间(秒,默认 2)
|
||||
|
||||
返回:
|
||||
登录成功后的 ChromiumPage 对象
|
||||
|
||||
异常:
|
||||
若登录失败或关键元素未找到,抛出 RuntimeError
|
||||
"""
|
||||
# 加载 app/.env 环境变量(始终定位 app 根,与 cwd 无关)
|
||||
load_app_env()
|
||||
|
||||
# 获取配置,参数优先于环境变量
|
||||
login_url = os.getenv('oa_login_url')
|
||||
if not login_url:
|
||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||||
if not target_url_keyword:
|
||||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
||||
|
||||
final_username = username or os.getenv('oa_login_username')
|
||||
final_password = password or os.getenv('oa_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
||||
|
||||
# 创建浏览器页面对象
|
||||
page = ChromiumPage()
|
||||
# page.set.window.max()
|
||||
|
||||
try:
|
||||
# 访问登录页面
|
||||
page.get(login_url)
|
||||
time.sleep(wait_after_load) # 等待页面初步加载
|
||||
|
||||
# 定位并填写用户名
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# 定位并填写密码
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# 定位并点击登录按钮
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# ---------- 轮询检测 URL ----------
|
||||
start = time.time()
|
||||
while time.time() - start < timeout: # timeout 默认 10 秒
|
||||
if target_url_keyword in page.url:
|
||||
logger.info("登录成功!当前 URL: %s", page.url)
|
||||
return page
|
||||
time.sleep(0.5)
|
||||
|
||||
# 超时处理
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
logger.warning("登录失败,提示: %s", error_elem.text)
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
|
||||
except Exception as e:
|
||||
# 若发生异常,可选择关闭浏览器并重新抛出
|
||||
page.quit()
|
||||
raise RuntimeError(f"登录过程出错: {e}")
|
||||
|
||||
|
||||
# ---------- 使用示例 ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
try:
|
||||
page = oa_login()
|
||||
except RuntimeError as e:
|
||||
logger.error(e)
|
||||
|
||||
@@ -1,165 +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)
|
||||
# -*- 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,390 +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
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: flow.py
|
||||
@Description: OA 流程引擎/表单/附件接口:taskId 查 formId、businessKey 查表单数据、附件下载。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, Optional
|
||||
from urllib.parse import unquote
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
WF_ACTIVITY_URL,
|
||||
WORKFORM_ENGINE_URL,
|
||||
FILE_DOWNLOAD_URL,
|
||||
FJK_BY_IDS_URL,
|
||||
CONTRACT_SIGNATURE_SELECT_URL,
|
||||
ATTACHMENT_SAVE_DIR,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_wf_activity_by_task_id(
|
||||
session: SessionPage,
|
||||
task_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 taskId 调用 WfActivity 接口获取 formId。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
task_id: SSO 解析得到的 taskId
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典,包含 formId 等信息
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
data = {"taskId": task_id}
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WfActivity")
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data: Dict[str, Any]) -> str:
|
||||
"""
|
||||
从 WfActivity 接口返回数据中提取 formId。
|
||||
|
||||
Args:
|
||||
wf_activity_data: get_wf_activity_by_task_id 返回的 JSON
|
||||
|
||||
Returns:
|
||||
formId 字符串
|
||||
|
||||
Raises:
|
||||
ValueError: 未找到 formId
|
||||
"""
|
||||
# 常见 formId 字段路径:顶层,以及 data / result 子对象
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = (
|
||||
data_obj.get("formId")
|
||||
or data_obj.get("FormId")
|
||||
or data_obj.get("form_id")
|
||||
)
|
||||
if form_id:
|
||||
break
|
||||
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(
|
||||
session: SessionPage,
|
||||
business_key: str,
|
||||
form_id: str
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
business_key: SSO 解析得到的 businessKey
|
||||
form_id: 从 WfActivity 接口获取的 formId
|
||||
|
||||
Returns:
|
||||
表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
data = {
|
||||
"businessKey": business_key,
|
||||
"formId": form_id,
|
||||
}
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
json_data = oa_request_json(session, "POST", url, data, "WorkformEngine")
|
||||
|
||||
# 表单详情在 result 字段中(如 ot_date / staff_name 等)
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
# ==================== EHR 会话失效自愈 ====================
|
||||
# 关键坑:EHR 会话(hr.37du.co)可能中途失效(共享 cookies 过期/服务端踢下线),
|
||||
# 而待办接口在 oa.37du.co 上仍可用,导致 OA 侧会话校验检测不到——
|
||||
# 表现为附件清单/下载接口返回登录页 HTML 或"外部用户未登录,无法访问"。
|
||||
# 处置:检测到失效时用单据 SSO 详情链接(纯接口,sign 可重复使用)重建会话后重试一次。
|
||||
|
||||
|
||||
def _ehr_resp_is_login(resp) -> bool:
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp) -> bool:
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url: str) -> bool:
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_fjk_file_list(
|
||||
session: SessionPage,
|
||||
file_ids: str,
|
||||
detail_url: str = None,
|
||||
) -> list:
|
||||
"""
|
||||
按 fileId 列表调用 getFjkByIds 查询附件清单。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_ids: 逗号分隔的多个 fileId(如表单 result.contract_file 字段)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
附件清单(jsonList),每项含 id/fileName/fileSuffix/herfUrl/fileSize 等;
|
||||
无有效 fileId 时返回空列表。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
ids = [x.strip() for x in str(file_ids).split(",") if x.strip()]
|
||||
if not ids:
|
||||
return []
|
||||
data = {"ids": ",".join(ids)}
|
||||
logger.info("查询附件清单: ids=%s", ids)
|
||||
for attempt in (1, 2):
|
||||
session.post(FJK_BY_IDS_URL, data=data)
|
||||
resp = session.response
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
json_data = resp.json()
|
||||
logger.debug("getFjkByIds 返回: %s", json_data)
|
||||
return json_data.get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
|
||||
|
||||
def download_attachment(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str = ATTACHMENT_SAVE_DIR,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
根据附件 fileId 从 OA 下载请假单据附件,支持多附件(逗号分隔多个 fileId)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||||
file_id: 附件 fileId 或逗号分隔的多个 fileId(表单 result.file 字段值)
|
||||
save_dir: 保存目录(默认 downloads)
|
||||
detail_url: 单据 SSO 详情链接,用于 EHR 会话失效时重建会话重试
|
||||
|
||||
Returns:
|
||||
成功保存的文件路径;多附件或下载失败时返回逗号拼接的相对路径列表
|
||||
(保持与历史单附件行为一致:单个成功仍返回单个路径字符串)。
|
||||
"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
|
||||
# 兼容多附件:file 字段可能为逗号分隔的多个 fileId,逐个下载
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(
|
||||
session: SessionPage,
|
||||
file_id: str,
|
||||
save_dir: str,
|
||||
detail_url: str = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
下载单个附件 fileId,返回本地保存路径;失败返回 None。
|
||||
|
||||
会话失效(响应非文件流)时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载附件: fileId=%s", file_id)
|
||||
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
session.get(url)
|
||||
resp = session.response
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态查询 ====================
|
||||
# getBusinessDate 返回的 ext_is_initiate_sign / ext_staff_sign_status / ext_org_sign_status
|
||||
# 恒为空串,拿不到真实签署状态;需再调该查询接口(按 main_id 即合同业务主键)取真实状态
|
||||
|
||||
|
||||
def get_contract_sign_status(session: SessionPage, contract_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询电子签真实签署状态。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
contract_id: 合同业务主键(= getBusinessData 返回的 main_id / SSO businessKey)
|
||||
|
||||
Returns:
|
||||
{"is_initiate_sign": ..., "sign_status_yg": ..., "sign_status_qy": ...,
|
||||
"file": 签章附件 fileId 串(可能为 None/空)}
|
||||
查询失败抛 RuntimeError。
|
||||
"""
|
||||
session.post(CONTRACT_SIGNATURE_SELECT_URL, data={
|
||||
"contract_id": contract_id,
|
||||
"inParamFormId": "",
|
||||
"colCode": "main_id",
|
||||
})
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("签署状态查询请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"签署状态查询接口状态码异常: {resp.status_code}")
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"签署状态查询接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
# 业务层执行异常(如该合同无电子签记录,服务端存储过程报错):稳定可复现,
|
||||
# 重试无意义,按"查不到状态"处理——返回空状态,由校验归为"未完成"(不管)
|
||||
logger.warning("签署状态查询业务异常(按未完成处理): contract_id=%s, meg=%s",
|
||||
contract_id, json_data.get("meg"))
|
||||
return {
|
||||
"is_initiate_sign": None,
|
||||
"sign_status_yg": None,
|
||||
"sign_status_qy": None,
|
||||
"file": None,
|
||||
}
|
||||
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
return {
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def enrich_form_sign_status(form_data: Dict[str, Any], session: SessionPage) -> Dict[str, Any]:
|
||||
"""
|
||||
把 getBusinessData 返回的表单数据中的电子签三状态字段补上真实值。
|
||||
|
||||
表单 result 里 ext_is_initiate_sign/ext_staff_sign_status/ext_org_sign_status 恒为空串,
|
||||
需按 main_id 再调签署状态查询接口,把真实状态写回这三个字段,供后续校验使用。
|
||||
接口变更:表单 contract_file 已恒为空串,签章附件 fileId 改从签署记录 file 字段获取
|
||||
(",id1,id2" 格式,get_fjk_file_list 按逗号拆分可容忍前导逗号)。
|
||||
"""
|
||||
contract_id = form_data.get("main_id")
|
||||
if not contract_id:
|
||||
raise RuntimeError("表单数据缺少 main_id,无法查询电子签签署状态")
|
||||
sign_status = get_contract_sign_status(session, contract_id)
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
|
||||
@@ -1,157 +1,157 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.session_manager
|
||||
@FileName: session_manager.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 10:30
|
||||
@Description: 从 ChromiumPage 提取 Cookies,生成 SessionPage 供后台请求;支持 cookies 持久化复用
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
|
||||
# 登录 cookies 持久化目录:统一放在 AppData\Local\37duAutomation,文件名按平台区分
|
||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
||||
_SESSIONS_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
|
||||
def init_session_from_page(
|
||||
browser_page: ChromiumPage,
|
||||
copy_headers: bool = True
|
||||
) -> SessionPage:
|
||||
"""
|
||||
从已登录的 ChromiumPage 中提取 cookies 和 headers,
|
||||
创建并返回一个可直接发送后台请求的 SessionPage 对象。
|
||||
|
||||
Args:
|
||||
browser_page: 已登录的 ChromiumPage 实例
|
||||
copy_headers: 是否复制浏览器的 User-Agent 等头部信息(默认 True)
|
||||
|
||||
Returns:
|
||||
已设置好 cookies 和 headers 的 SessionPage 对象
|
||||
"""
|
||||
session = SessionPage()
|
||||
|
||||
# 1. 获取浏览器 cookies(全域名:oa 域登录态 + hr 域可能已有的会话)
|
||||
cookies_dict = browser_page.cookies(all_domains=True)
|
||||
if cookies_dict:
|
||||
session.set.cookies(cookies_dict)
|
||||
logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器已登录")
|
||||
|
||||
# 2. 可选复制 headers(主要是 User-Agent,防止被反爬)
|
||||
if copy_headers:
|
||||
headers = {
|
||||
"User-Agent": browser_page.run_js("return navigator.userAgent;")
|
||||
}
|
||||
session.set.headers(headers)
|
||||
logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50])
|
||||
|
||||
# 3. 可额外设置默认超时、重试等
|
||||
session.set.timeout(10) # 全局超时 10 秒
|
||||
|
||||
return session
|
||||
|
||||
|
||||
# 便捷函数:SSO 跳转后同步浏览器 cookies 到 SessionPage
|
||||
def refresh_session_cookies(session: SessionPage, browser_page: ChromiumPage) -> None:
|
||||
"""
|
||||
从浏览器重新同步全域名 cookies 到 SessionPage。
|
||||
SSO 的 linkLogin 会在 hr 域产生新的会话 cookie,需在浏览器完成 SSO 跳转后调用。
|
||||
|
||||
Args:
|
||||
session: 目标 SessionPage 对象
|
||||
browser_page: 已登录且已完成 SSO 跳转的 ChromiumPage 实例
|
||||
"""
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
|
||||
|
||||
# ---------- Cookies 持久化(复用登录态,免重复登录) ----------
|
||||
def save_browser_cookies(browser_page: ChromiumPage, path: str = COOKIE_FILE) -> None:
|
||||
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
logger.warning("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||||
|
||||
|
||||
def load_cookies(path: str = COOKIE_FILE):
|
||||
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def load_saved_session(path: str = COOKIE_FILE) -> SessionPage:
|
||||
"""用已保存的 cookies 构建 SessionPage;无可用 cookies 时返回 None。"""
|
||||
cookies = load_cookies(path)
|
||||
if not cookies:
|
||||
return None
|
||||
session = SessionPage()
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
return session
|
||||
|
||||
|
||||
def create_browser_with_saved_cookies(path: str = COOKIE_FILE) -> ChromiumPage:
|
||||
"""用已保存的 cookies 创建 ChromiumPage(免输账号密码,SSO 跳转仍需真浏览器)。"""
|
||||
browser = ChromiumPage()
|
||||
cookies = load_cookies(path)
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
|
||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
||||
"""通过轻量接口 sumTodoCount 判断会话是否有效(无效则需重新登录)。
|
||||
|
||||
会话有效时接口返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});
|
||||
会话失效会被重定向到登录页返回 HTML,据此判定失效。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.config import TODO_COUNT_URL
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# 便捷函数:直接从已登录的浏览器提取会话,一步到位
|
||||
def create_session_from_login() -> SessionPage:
|
||||
"""
|
||||
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
||||
再提取 SessionPage。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
browser = oa_login()
|
||||
return init_session_from_page(browser)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.session_manager
|
||||
@FileName: session_manager.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 10:30
|
||||
@Description: 从 ChromiumPage 提取 Cookies,生成 SessionPage 供后台请求;支持 cookies 持久化复用
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
|
||||
# 登录 cookies 持久化目录:统一放在 AppData\Local\37duAutomation,文件名按平台区分
|
||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
||||
_SESSIONS_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
|
||||
def init_session_from_page(
|
||||
browser_page: ChromiumPage,
|
||||
copy_headers: bool = True
|
||||
) -> SessionPage:
|
||||
"""
|
||||
从已登录的 ChromiumPage 中提取 cookies 和 headers,
|
||||
创建并返回一个可直接发送后台请求的 SessionPage 对象。
|
||||
|
||||
Args:
|
||||
browser_page: 已登录的 ChromiumPage 实例
|
||||
copy_headers: 是否复制浏览器的 User-Agent 等头部信息(默认 True)
|
||||
|
||||
Returns:
|
||||
已设置好 cookies 和 headers 的 SessionPage 对象
|
||||
"""
|
||||
session = SessionPage()
|
||||
|
||||
# 1. 获取浏览器 cookies(全域名:oa 域登录态 + hr 域可能已有的会话)
|
||||
cookies_dict = browser_page.cookies(all_domains=True)
|
||||
if cookies_dict:
|
||||
session.set.cookies(cookies_dict)
|
||||
logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器已登录")
|
||||
|
||||
# 2. 可选复制 headers(主要是 User-Agent,防止被反爬)
|
||||
if copy_headers:
|
||||
headers = {
|
||||
"User-Agent": browser_page.run_js("return navigator.userAgent;")
|
||||
}
|
||||
session.set.headers(headers)
|
||||
logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50])
|
||||
|
||||
# 3. 可额外设置默认超时、重试等
|
||||
session.set.timeout(10) # 全局超时 10 秒
|
||||
|
||||
return session
|
||||
|
||||
|
||||
# 便捷函数:SSO 跳转后同步浏览器 cookies 到 SessionPage
|
||||
def refresh_session_cookies(session: SessionPage, browser_page: ChromiumPage) -> None:
|
||||
"""
|
||||
从浏览器重新同步全域名 cookies 到 SessionPage。
|
||||
SSO 的 linkLogin 会在 hr 域产生新的会话 cookie,需在浏览器完成 SSO 跳转后调用。
|
||||
|
||||
Args:
|
||||
session: 目标 SessionPage 对象
|
||||
browser_page: 已登录且已完成 SSO 跳转的 ChromiumPage 实例
|
||||
"""
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
|
||||
|
||||
# ---------- Cookies 持久化(复用登录态,免重复登录) ----------
|
||||
def save_browser_cookies(browser_page: ChromiumPage, path: str = COOKIE_FILE) -> None:
|
||||
"""把浏览器全域名 cookies 保存到本地文件,下次运行可免登录复用。"""
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
logger.warning("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||||
|
||||
|
||||
def load_cookies(path: str = COOKIE_FILE):
|
||||
"""从本地文件加载 cookies 列表;文件不存在或为空时返回 None。"""
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def load_saved_session(path: str = COOKIE_FILE) -> SessionPage:
|
||||
"""用已保存的 cookies 构建 SessionPage;无可用 cookies 时返回 None。"""
|
||||
cookies = load_cookies(path)
|
||||
if not cookies:
|
||||
return None
|
||||
session = SessionPage()
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
return session
|
||||
|
||||
|
||||
def create_browser_with_saved_cookies(path: str = COOKIE_FILE) -> ChromiumPage:
|
||||
"""用已保存的 cookies 创建 ChromiumPage(免输账号密码,SSO 跳转仍需真浏览器)。"""
|
||||
browser = ChromiumPage()
|
||||
cookies = load_cookies(path)
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
|
||||
def is_session_valid(session: SessionPage, subject: str = "加班") -> bool:
|
||||
"""通过轻量接口 sumTodoCount 判断会话是否有效(无效则需重新登录)。
|
||||
|
||||
会话有效时接口返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});
|
||||
会话失效会被重定向到登录页返回 HTML,据此判定失效。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.config import TODO_COUNT_URL
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# 便捷函数:直接从已登录的浏览器提取会话,一步到位
|
||||
def create_session_from_login() -> SessionPage:
|
||||
"""
|
||||
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
||||
再提取 SessionPage。
|
||||
"""
|
||||
from app.service.hrbp.oa.common.login import oa_login
|
||||
browser = oa_login()
|
||||
return init_session_from_page(browser)
|
||||
|
||||
@@ -1,64 +1,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.sso
|
||||
@FileName: sso.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:50
|
||||
@Description: SSO 链接解析模块:浏览器访问 SSO 链接,从重定向后的详情页 URL 提取 taskId/fkId 和 businessKey
|
||||
@Version: 1.0.1
|
||||
"""
|
||||
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
from typing import Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
|
||||
|
||||
def resolve_sso_params(
|
||||
browser: ChromiumPage,
|
||||
sso_url: str,
|
||||
wait_timeout: float = 20,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
用浏览器打开 SSO 链接,等待 JS 重定向到详情页,
|
||||
从最终 URL 的 query 参数中提取 taskId(部分页面命名为 fkId)和 businessKey。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(SSO 的 JS 跳转必须用真浏览器)
|
||||
sso_url: SSO 跳转链接(完整 URL)
|
||||
wait_timeout: 等待 JS 跳转完成的超时时间(秒,默认 20)
|
||||
|
||||
Returns:
|
||||
包含 taskId 和 businessKey 的字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 跳转失败或 URL 中缺少 taskId/businessKey
|
||||
"""
|
||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||
|
||||
# 浏览器打开 SSO 链接,页面 JS 自动重定向到详情页。
|
||||
# 跳转链: sso.mob -> unifyWorkFlow.jsp(中间页,一闪而过) -> goToWorkFlow 详情页。
|
||||
# 因此不能等中间页(会匹配不到而超时卡 wait_timeout 秒),改为等待地址栏离开 SSO 链接。
|
||||
browser.get(sso_url)
|
||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||
logger.info("重定向最终 URL: %s", browser.url)
|
||||
|
||||
# 从详情页 URL 提取 taskId(fkId 是同一字段的别名)和 businessKey
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(
|
||||
f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}"
|
||||
)
|
||||
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
return {"taskId": task_id, "businessKey": business_key}
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.sso
|
||||
@FileName: sso.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 23:50
|
||||
@Description: SSO 链接解析模块:浏览器访问 SSO 链接,从重定向后的详情页 URL 提取 taskId/fkId 和 businessKey
|
||||
@Version: 1.0.1
|
||||
"""
|
||||
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
from typing import Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
|
||||
|
||||
def resolve_sso_params(
|
||||
browser: ChromiumPage,
|
||||
sso_url: str,
|
||||
wait_timeout: float = 20,
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
用浏览器打开 SSO 链接,等待 JS 重定向到详情页,
|
||||
从最终 URL 的 query 参数中提取 taskId(部分页面命名为 fkId)和 businessKey。
|
||||
|
||||
Args:
|
||||
browser: 已登录的 ChromiumPage 对象(SSO 的 JS 跳转必须用真浏览器)
|
||||
sso_url: SSO 跳转链接(完整 URL)
|
||||
wait_timeout: 等待 JS 跳转完成的超时时间(秒,默认 20)
|
||||
|
||||
Returns:
|
||||
包含 taskId 和 businessKey 的字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 跳转失败或 URL 中缺少 taskId/businessKey
|
||||
"""
|
||||
logger.info("解析 SSO 重定向: %s", sso_url)
|
||||
|
||||
# 浏览器打开 SSO 链接,页面 JS 自动重定向到详情页。
|
||||
# 跳转链: sso.mob -> unifyWorkFlow.jsp(中间页,一闪而过) -> goToWorkFlow 详情页。
|
||||
# 因此不能等中间页(会匹配不到而超时卡 wait_timeout 秒),改为等待地址栏离开 SSO 链接。
|
||||
browser.get(sso_url)
|
||||
browser.wait.url_change(sso_url, exclude=True, timeout=wait_timeout, raise_err=False)
|
||||
logger.info("重定向最终 URL: %s", browser.url)
|
||||
|
||||
# 从详情页 URL 提取 taskId(fkId 是同一字段的别名)和 businessKey
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(
|
||||
f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}"
|
||||
)
|
||||
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
return {"taskId": task_id, "businessKey": business_key}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.leave_approval
|
||||
@FileName: leave_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:21
|
||||
@Description: 请假审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.leave_approval
|
||||
@FileName: leave_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:21
|
||||
@Description: 请假审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,71 +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"),
|
||||
}
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 请假表单解析模块
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.common.config import VACATION_TYPE_MAP
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ---------- 假期类型编码 -> 名称映射 ----------
|
||||
# 已统一收口到 HR 平台共享层(hrbp/common/config.py),此处直接复用,不再重复定义
|
||||
|
||||
|
||||
# ---------- 请假表单解析 ----------
|
||||
|
||||
def _first_non_null(result: Dict[str, Any], *keys: str) -> Any:
|
||||
"""返回 result 中第一个值非 None 的字段(注意:不能用 or 链,0.0 / 0 是合法值但为 falsy)。"""
|
||||
for k in keys:
|
||||
v = result.get(k)
|
||||
if v is not None:
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_vacation_type(result: Dict[str, Any]) -> str:
|
||||
"""从表单数据中提取假期类型名称(支持编码和名称两种输入)"""
|
||||
raw = _first_non_null(result, "vacation_type", "leave_type", "sub_type")
|
||||
raw = str(raw).strip() if raw is not None else ""
|
||||
# 先尝试按编码映射
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
# 否则直接返回原始值(可能已是名称)
|
||||
return raw
|
||||
|
||||
|
||||
def _parse_leave_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析请假表单数据,提取关键字段。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(即 doc['formData'])
|
||||
|
||||
Returns:
|
||||
包含请假关键字段的字典(中文键名)
|
||||
"""
|
||||
return {
|
||||
"请假人员ID": result.get("staff_id"),
|
||||
"工号": result.get("staff_code"),
|
||||
"请假人员": result.get("staff_name"),
|
||||
"所属部门": result.get("dept_org_name"),
|
||||
"假期类型": _resolve_vacation_type(result),
|
||||
# 日期区间以 begin_date/end_date 为准(start_time/end_time 可能跨天,不可用于取日期)
|
||||
"开始日期": result.get("begin_date"),
|
||||
"开始时间": result.get("start_time"),
|
||||
"结束日期": result.get("end_date"),
|
||||
"结束时间": result.get("end_time"),
|
||||
# 注意:leave_days 可能为 0.0(小时假),不能用 or 链(会被 falsy 短路成 None)
|
||||
"请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"),
|
||||
"请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"),
|
||||
"请假原因": result.get("leave_reason"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
@@ -1,134 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程报告模块。
|
||||
校验结果分三组:通过 / 校验不通过未处理 / 人工复核。
|
||||
输出两份清单:
|
||||
《请假审批校验不通过未处理人员明细清单》:员工姓名、假期类型、校验不通过原因、详情页链接
|
||||
《附件人工复核待办清单》:员工姓名、假期类型、详情页链接(供人工打开查看附件)
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 4.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的请假人员,缺失时回退到发起人。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("请假人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _vtype(r: Dict[str, Any]) -> str:
|
||||
"""假期类型。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始时间", "开始时间"),
|
||||
("结束时间", "结束时间"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"请假审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《请假审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
path = r.get("附件路径") or "下载失败"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《请假审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程报告模块。
|
||||
校验结果分三组:通过 / 校验不通过未处理 / 人工复核。
|
||||
输出两份清单:
|
||||
《请假审批校验不通过未处理人员明细清单》:员工姓名、假期类型、校验不通过原因、详情页链接
|
||||
《附件人工复核待办清单》:员工姓名、假期类型、详情页链接(供人工打开查看附件)
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 4.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的请假人员,缺失时回退到发起人。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("请假人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _vtype(r: Dict[str, Any]) -> str:
|
||||
"""假期类型。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始时间", "开始时间"),
|
||||
("结束时间", "结束时间"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"请假审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《请假审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
path = r.get("附件路径") or "下载失败"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《请假审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -1,348 +1,348 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.validator
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程校验模块(审批决策三态:通过 / 校验不通过未处理 / 人工复核)
|
||||
1. 根据假期类型分支处理:
|
||||
- 小时特假:请假当天是排班上班日即通过,否则校验不通过未处理
|
||||
- 事假/调休假/半天休/普通事假等:排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||
- 病假/特别福利假/特殊事假/产假:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);
|
||||
天数不一致或缺附件 -> 校验不通过未处理
|
||||
2. 排班数据获取:调用排班接口(rf_p_kq_count_SelectBanci,按工号+日期范围,含未来日期排班),
|
||||
统计请假区间内非"休息"天数
|
||||
@Version: 4.2.0
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import math
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.oa.leave.parser import VACATION_TYPE_MAP, _resolve_vacation_type, _parse_leave_form
|
||||
from app.service.hrbp.oa.common.oa_api import download_attachment
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift
|
||||
from app.service.hrbp.oa.leave.attachment_check import (
|
||||
check_leave_attachment,
|
||||
check_leave_attachment_detail,
|
||||
marriage_within_one_year,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可
|
||||
HOURLY_LEAVE_TYPES = {
|
||||
"小时特假",
|
||||
}
|
||||
|
||||
# Group 1:仅校验排班上班天数与填报天数一致
|
||||
LEAVE_TYPE_GROUP_1 = {
|
||||
"事假", "调休假", "半天休(仅限人资专用)",
|
||||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||||
"年度福利假",
|
||||
}
|
||||
|
||||
# Group 2:校验天数一致 + 需上传附件
|
||||
LEAVE_TYPE_GROUP_2 = {
|
||||
"病假", "特别福利假", "特殊事假", "产假",
|
||||
}
|
||||
|
||||
|
||||
# ---------- 排班数据获取 ----------
|
||||
|
||||
def _get_date_range(start_time: str, end_time: str) -> Tuple[str, str]:
|
||||
"""从请假起止时间中提取日期范围 (start_date, end_date),格式 YYYY-MM-DD"""
|
||||
start_date = start_time[:10] if start_time else None
|
||||
end_date = end_time[:10] if end_time else None
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
# 排班接口依赖 HR 登录态(hr_cookies.json),单次运行内复用 HR 会话与当前操作人 user_id
|
||||
_HR_CTX = {"session": None, "user_id": None}
|
||||
|
||||
|
||||
def _get_hr_context() -> Tuple[Any, str]:
|
||||
"""获取 (hr_session, user_id),带缓存;失效时清缓存重试一次。"""
|
||||
if _HR_CTX["session"] is not None:
|
||||
return _HR_CTX["session"], _HR_CTX["user_id"]
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||||
_HR_CTX.update(session=session, user_id=user_id)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _get_day_shift(shift_rows: Any, date_str: str) -> str:
|
||||
"""从排班记录中提取指定日期的班次名(动态列 "YYYY-MM-DD_bc_name")。"""
|
||||
for rec in shift_rows:
|
||||
name = rec.get(f"{date_str}_bc_name")
|
||||
time_ = rec.get(f"{date_str}_bc_time")
|
||||
if name or time_:
|
||||
return str(name if name is not None else "")
|
||||
return ""
|
||||
|
||||
|
||||
def _get_work_days_count(staff_code: str, start_date: str, end_date: str) -> int:
|
||||
"""
|
||||
获取请假区间内实际上班天数(非休息日)。
|
||||
|
||||
数据源为排班接口(rf_p_kq_count_SelectBanci),按工号(base_code)+日期范围查询
|
||||
(含未来日期排班),逐日班次存于动态列 "YYYY-MM-DD_bc_name/bc_time/paiban_type"。
|
||||
注意:休息与否只能以 bc_name 为准("休息"或空串=休息日):
|
||||
返回数据中休息日的 paiban_type 可能为 -2/0,而上班日(bc_name 为具体班次名)
|
||||
的 paiban_type 也可能为 0/-3,故不能按 paiban_type 判断。
|
||||
"""
|
||||
session, user_id = _get_hr_context()
|
||||
try:
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
logger.info("排班数据已获取: %s ~ %s, 共 %d 条", start_date, end_date, len(rows))
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,重建会话后重试")
|
||||
_HR_CTX.clear()
|
||||
session, user_id = _get_hr_context()
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
bc_name = _get_day_shift(rows, day)
|
||||
if bc_name not in ("", "休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
# ---------- 主入口 ----------
|
||||
|
||||
def _verify_attachment(session: Any, vacation_type: str, reason: str, file_id: str) -> Tuple[str, str, Any]:
|
||||
"""
|
||||
根据假期类型校验附件内容,返回 (decision, note, attachment_path)。
|
||||
|
||||
- 病假:OCR 病假关键词,命中通过,未命中人工复核
|
||||
- 特别福利假:按请假理由细分
|
||||
- 婚假:OCR 结婚证关键词 + 登记日期 1 年内
|
||||
- 产检假:OCR 产检关键词
|
||||
- 丧假:有附件即通过
|
||||
- 特殊事假 / 产假:有附件即通过
|
||||
"""
|
||||
path = download_attachment(session, file_id)
|
||||
if not path:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
# 多附件支持:download_attachment 对逗号分隔的多个 fileId 返回逗号拼接的路径串,
|
||||
# 拆分后逐个做内容校验,任一命中即通过
|
||||
paths = [p for p in path.split(",") if p]
|
||||
if not paths:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
def _first_hit(checker):
|
||||
return next((p for p in paths if checker(p)), None)
|
||||
|
||||
def _kw_hint(p, leave_type):
|
||||
"""返回该附件 OCR 命中的关键词列表(逗号拼接),用于备注便于人工判断。"""
|
||||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||||
return "、".join(hits) if hits else ""
|
||||
|
||||
if vacation_type == "病假":
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||||
|
||||
if vacation_type == "特别福利假":
|
||||
reason = reason or ""
|
||||
if "婚" in reason:
|
||||
hit = None
|
||||
reg_kw = ""
|
||||
for p in paths:
|
||||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||||
if ok:
|
||||
hit = p
|
||||
reg_kw = "、".join(hits)
|
||||
break
|
||||
if hit is None:
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||||
ok, reg_date = marriage_within_one_year(hit)
|
||||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||||
if ok:
|
||||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||||
if "产" in reason or "孕" in reason:
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||||
if "丧" in reason:
|
||||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||||
|
||||
# 特殊事假 / 产假:有附件即通过
|
||||
return "通过", f"附件已上传({len(paths)}份)", path
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张请假单据,返回审批决策。
|
||||
|
||||
流程:
|
||||
1. 解析表单数据,提取假期类型、请假天数、附件等信息
|
||||
2. 调用排班接口,计算请假区间内实际上班天数
|
||||
3. 根据假期类型分支处理:
|
||||
- 小时特假:请假当天为排班上班日 -> 通过,否则校验不通过未处理
|
||||
- Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||
- Group 2(病假/产假等):天数一致且已上传附件 -> 人工复核;否则校验不通过未处理
|
||||
|
||||
Args:
|
||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||
session: 已登录的 SessionPage 对象(用于下载请假附件)
|
||||
(排班数据走 HR 排班接口,独立使用 HR 登录态,不依赖该 session)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策及详细信息
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
leave_info = _parse_leave_form(form_data)
|
||||
|
||||
staff_id = leave_info.get("请假人员ID")
|
||||
staff_code = leave_info.get("工号")
|
||||
vacation_type = leave_info.get("假期类型")
|
||||
# 日期区间:其他假期一律用 begin_date/end_date(start_time/end_time 可能跨天,
|
||||
# 不可用于取日期);仅小时特假为按小时请假,用 start_time/end_time 取当日排班
|
||||
begin_date = leave_info.get("开始日期")
|
||||
end_date = leave_info.get("结束日期")
|
||||
leave_days = leave_info.get("请假天数")
|
||||
attachment = leave_info.get("附件")
|
||||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||||
if is_hourly:
|
||||
begin_date = leave_info.get("开始时间")
|
||||
end_date = leave_info.get("结束时间")
|
||||
|
||||
result: Dict[str, Any] = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "通过",
|
||||
"note": "",
|
||||
"leave_info": leave_info,
|
||||
}
|
||||
|
||||
# 缺失必要信息
|
||||
if not vacation_type:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法识别假期类型"
|
||||
return result
|
||||
|
||||
if not staff_id:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人员ID缺失"
|
||||
return result
|
||||
|
||||
if not staff_code:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人工号缺失"
|
||||
return result
|
||||
|
||||
# 获取日期范围
|
||||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||||
if not start_date or not end_date:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假起止日期缺失"
|
||||
return result
|
||||
|
||||
# 计算实际上班天数(排班接口按工号查询,含未来日期)
|
||||
try:
|
||||
actual_work_days = _get_work_days_count(staff_code, start_date, end_date)
|
||||
except Exception as e:
|
||||
logger.warning("计算上班天数失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
# 填报天数
|
||||
try:
|
||||
fill_days = float(leave_days) if leave_days else 0
|
||||
except (TypeError, ValueError):
|
||||
fill_days = 0
|
||||
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对:
|
||||
# 0.5天->1个工作日,1.0天->1个工作日,1.5天->2个工作日
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
# ========== 根据假期类型分支处理 ==========
|
||||
|
||||
if vacation_type in HOURLY_LEAVE_TYPES:
|
||||
# 按小时请假(如小时特假):当天为上班日 + 已上传附件才通过
|
||||
leave_hours = leave_info.get("请假小时")
|
||||
if actual_work_days < 1:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"请假当天非排班上班日(实际上班天数: {actual_work_days})"
|
||||
elif not attachment:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "未上传附件"
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["附件路径"] = download_attachment(session, attachment)
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||||
f"当天为上班日,附件已上传)"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_1:
|
||||
# Group 1:仅校验天数一致
|
||||
if days_mismatch:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = (
|
||||
f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
)
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||||
f"填报天数: {fill_days})"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_2:
|
||||
# Group 2:需附件的假期(病假/特别福利假/特殊事假/产假)
|
||||
# - 天数不一致或缺附件 -> 校验不通过未处理
|
||||
# - 附件通过内容校验(OCR/仅附件)-> 通过;OCR 无法确认 -> 人工复核
|
||||
reasons = []
|
||||
if days_mismatch:
|
||||
reasons.append(
|
||||
f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
)
|
||||
if not attachment:
|
||||
reasons.append("未上传附件")
|
||||
|
||||
if reasons:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = ";".join(reasons)
|
||||
else:
|
||||
result["decision"], result["note"], result["附件路径"] = _verify_attachment(
|
||||
session, vacation_type, leave_info.get("请假原因"), attachment
|
||||
)
|
||||
else:
|
||||
# 未识别的假期类型
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||||
|
||||
return result
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.validator
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程校验模块(审批决策三态:通过 / 校验不通过未处理 / 人工复核)
|
||||
1. 根据假期类型分支处理:
|
||||
- 小时特假:请假当天是排班上班日即通过,否则校验不通过未处理
|
||||
- 事假/调休假/半天休/普通事假等:排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||
- 病假/特别福利假/特殊事假/产假:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);
|
||||
天数不一致或缺附件 -> 校验不通过未处理
|
||||
2. 排班数据获取:调用排班接口(rf_p_kq_count_SelectBanci,按工号+日期范围,含未来日期排班),
|
||||
统计请假区间内非"休息"天数
|
||||
@Version: 4.2.0
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import math
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.oa.leave.parser import VACATION_TYPE_MAP, _resolve_vacation_type, _parse_leave_form
|
||||
from app.service.hrbp.oa.common.oa_api import download_attachment
|
||||
from app.service.hrbp.common.hr_session import build_hr_session, HRSessionExpiredError
|
||||
from app.service.hrbp.ehr.common.hr_api.attendance import fetch_cur_user_info
|
||||
from app.service.hrbp.ehr.common.hr_api.shift import fetch_all_shift
|
||||
from app.service.hrbp.oa.leave.attachment_check import (
|
||||
check_leave_attachment,
|
||||
check_leave_attachment_detail,
|
||||
marriage_within_one_year,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 按小时请假的假期类型:不比对天数,只要请假当天是排班上班日即可
|
||||
HOURLY_LEAVE_TYPES = {
|
||||
"小时特假",
|
||||
}
|
||||
|
||||
# Group 1:仅校验排班上班天数与填报天数一致
|
||||
LEAVE_TYPE_GROUP_1 = {
|
||||
"事假", "调休假", "半天休(仅限人资专用)",
|
||||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||||
"年度福利假",
|
||||
}
|
||||
|
||||
# Group 2:校验天数一致 + 需上传附件
|
||||
LEAVE_TYPE_GROUP_2 = {
|
||||
"病假", "特别福利假", "特殊事假", "产假",
|
||||
}
|
||||
|
||||
|
||||
# ---------- 排班数据获取 ----------
|
||||
|
||||
def _get_date_range(start_time: str, end_time: str) -> Tuple[str, str]:
|
||||
"""从请假起止时间中提取日期范围 (start_date, end_date),格式 YYYY-MM-DD"""
|
||||
start_date = start_time[:10] if start_time else None
|
||||
end_date = end_time[:10] if end_time else None
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
# 排班接口依赖 HR 登录态(hr_cookies.json),单次运行内复用 HR 会话与当前操作人 user_id
|
||||
_HR_CTX = {"session": None, "user_id": None}
|
||||
|
||||
|
||||
def _get_hr_context() -> Tuple[Any, str]:
|
||||
"""获取 (hr_session, user_id),带缓存;失效时清缓存重试一次。"""
|
||||
if _HR_CTX["session"] is not None:
|
||||
return _HR_CTX["session"], _HR_CTX["user_id"]
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError("getCurUserInfo 未返回 userId,无法查询排班")
|
||||
_HR_CTX.update(session=session, user_id=user_id)
|
||||
return session, user_id
|
||||
|
||||
|
||||
def _get_day_shift(shift_rows: Any, date_str: str) -> str:
|
||||
"""从排班记录中提取指定日期的班次名(动态列 "YYYY-MM-DD_bc_name")。"""
|
||||
for rec in shift_rows:
|
||||
name = rec.get(f"{date_str}_bc_name")
|
||||
time_ = rec.get(f"{date_str}_bc_time")
|
||||
if name or time_:
|
||||
return str(name if name is not None else "")
|
||||
return ""
|
||||
|
||||
|
||||
def _get_work_days_count(staff_code: str, start_date: str, end_date: str) -> int:
|
||||
"""
|
||||
获取请假区间内实际上班天数(非休息日)。
|
||||
|
||||
数据源为排班接口(rf_p_kq_count_SelectBanci),按工号(base_code)+日期范围查询
|
||||
(含未来日期排班),逐日班次存于动态列 "YYYY-MM-DD_bc_name/bc_time/paiban_type"。
|
||||
注意:休息与否只能以 bc_name 为准("休息"或空串=休息日):
|
||||
返回数据中休息日的 paiban_type 可能为 -2/0,而上班日(bc_name 为具体班次名)
|
||||
的 paiban_type 也可能为 0/-3,故不能按 paiban_type 判断。
|
||||
"""
|
||||
session, user_id = _get_hr_context()
|
||||
try:
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
logger.info("排班数据已获取: %s ~ %s, 共 %d 条", start_date, end_date, len(rows))
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,重建会话后重试")
|
||||
_HR_CTX.clear()
|
||||
session, user_id = _get_hr_context()
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
|
||||
if not rows:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
bc_name = _get_day_shift(rows, day)
|
||||
if bc_name not in ("", "休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
# ---------- 主入口 ----------
|
||||
|
||||
def _verify_attachment(session: Any, vacation_type: str, reason: str, file_id: str) -> Tuple[str, str, Any]:
|
||||
"""
|
||||
根据假期类型校验附件内容,返回 (decision, note, attachment_path)。
|
||||
|
||||
- 病假:OCR 病假关键词,命中通过,未命中人工复核
|
||||
- 特别福利假:按请假理由细分
|
||||
- 婚假:OCR 结婚证关键词 + 登记日期 1 年内
|
||||
- 产检假:OCR 产检关键词
|
||||
- 丧假:有附件即通过
|
||||
- 特殊事假 / 产假:有附件即通过
|
||||
"""
|
||||
path = download_attachment(session, file_id)
|
||||
if not path:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
# 多附件支持:download_attachment 对逗号分隔的多个 fileId 返回逗号拼接的路径串,
|
||||
# 拆分后逐个做内容校验,任一命中即通过
|
||||
paths = [p for p in path.split(",") if p]
|
||||
if not paths:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
def _first_hit(checker):
|
||||
return next((p for p in paths if checker(p)), None)
|
||||
|
||||
def _kw_hint(p, leave_type):
|
||||
"""返回该附件 OCR 命中的关键词列表(逗号拼接),用于备注便于人工判断。"""
|
||||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||||
return "、".join(hits) if hits else ""
|
||||
|
||||
if vacation_type == "病假":
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||||
|
||||
if vacation_type == "特别福利假":
|
||||
reason = reason or ""
|
||||
if "婚" in reason:
|
||||
hit = None
|
||||
reg_kw = ""
|
||||
for p in paths:
|
||||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||||
if ok:
|
||||
hit = p
|
||||
reg_kw = "、".join(hits)
|
||||
break
|
||||
if hit is None:
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||||
ok, reg_date = marriage_within_one_year(hit)
|
||||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||||
if ok:
|
||||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||||
if "产" in reason or "孕" in reason:
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc if kw_desc else ''}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||||
if "丧" in reason:
|
||||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||||
|
||||
# 特殊事假 / 产假:有附件即通过
|
||||
return "通过", f"附件已上传({len(paths)}份)", path
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张请假单据,返回审批决策。
|
||||
|
||||
流程:
|
||||
1. 解析表单数据,提取假期类型、请假天数、附件等信息
|
||||
2. 调用排班接口,计算请假区间内实际上班天数
|
||||
3. 根据假期类型分支处理:
|
||||
- 小时特假:请假当天为排班上班日 -> 通过,否则校验不通过未处理
|
||||
- Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过,否则校验不通过未处理
|
||||
- Group 2(病假/产假等):天数一致且已上传附件 -> 人工复核;否则校验不通过未处理
|
||||
|
||||
Args:
|
||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||
session: 已登录的 SessionPage 对象(用于下载请假附件)
|
||||
(排班数据走 HR 排班接口,独立使用 HR 登录态,不依赖该 session)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策及详细信息
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
leave_info = _parse_leave_form(form_data)
|
||||
|
||||
staff_id = leave_info.get("请假人员ID")
|
||||
staff_code = leave_info.get("工号")
|
||||
vacation_type = leave_info.get("假期类型")
|
||||
# 日期区间:其他假期一律用 begin_date/end_date(start_time/end_time 可能跨天,
|
||||
# 不可用于取日期);仅小时特假为按小时请假,用 start_time/end_time 取当日排班
|
||||
begin_date = leave_info.get("开始日期")
|
||||
end_date = leave_info.get("结束日期")
|
||||
leave_days = leave_info.get("请假天数")
|
||||
attachment = leave_info.get("附件")
|
||||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||||
if is_hourly:
|
||||
begin_date = leave_info.get("开始时间")
|
||||
end_date = leave_info.get("结束时间")
|
||||
|
||||
result: Dict[str, Any] = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "通过",
|
||||
"note": "",
|
||||
"leave_info": leave_info,
|
||||
}
|
||||
|
||||
# 缺失必要信息
|
||||
if not vacation_type:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法识别假期类型"
|
||||
return result
|
||||
|
||||
if not staff_id:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人员ID缺失"
|
||||
return result
|
||||
|
||||
if not staff_code:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人工号缺失"
|
||||
return result
|
||||
|
||||
# 获取日期范围
|
||||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||||
if not start_date or not end_date:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假起止日期缺失"
|
||||
return result
|
||||
|
||||
# 计算实际上班天数(排班接口按工号查询,含未来日期)
|
||||
try:
|
||||
actual_work_days = _get_work_days_count(staff_code, start_date, end_date)
|
||||
except Exception as e:
|
||||
logger.warning("计算上班天数失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
# 填报天数
|
||||
try:
|
||||
fill_days = float(leave_days) if leave_days else 0
|
||||
except (TypeError, ValueError):
|
||||
fill_days = 0
|
||||
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对:
|
||||
# 0.5天->1个工作日,1.0天->1个工作日,1.5天->2个工作日
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
# ========== 根据假期类型分支处理 ==========
|
||||
|
||||
if vacation_type in HOURLY_LEAVE_TYPES:
|
||||
# 按小时请假(如小时特假):当天为上班日 + 已上传附件才通过
|
||||
leave_hours = leave_info.get("请假小时")
|
||||
if actual_work_days < 1:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"请假当天非排班上班日(实际上班天数: {actual_work_days})"
|
||||
elif not attachment:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "未上传附件"
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["附件路径"] = download_attachment(session, attachment)
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||||
f"当天为上班日,附件已上传)"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_1:
|
||||
# Group 1:仅校验天数一致
|
||||
if days_mismatch:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = (
|
||||
f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
)
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||||
f"填报天数: {fill_days})"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_2:
|
||||
# Group 2:需附件的假期(病假/特别福利假/特殊事假/产假)
|
||||
# - 天数不一致或缺附件 -> 校验不通过未处理
|
||||
# - 附件通过内容校验(OCR/仅附件)-> 通过;OCR 无法确认 -> 人工复核
|
||||
reasons = []
|
||||
if days_mismatch:
|
||||
reasons.append(
|
||||
f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
)
|
||||
if not attachment:
|
||||
reasons.append("未上传附件")
|
||||
|
||||
if reasons:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = ";".join(reasons)
|
||||
else:
|
||||
result["decision"], result["note"], result["附件路径"] = _verify_attachment(
|
||||
session, vacation_type, leave_info.get("请假原因"), attachment
|
||||
)
|
||||
else:
|
||||
# 未识别的假期类型
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||||
|
||||
return result
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程审核模块:解析 -> 校验(三态均已完成才同意)-> 报告
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程审核模块:解析 -> 校验(三态均已完成才同意)-> 报告
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
@@ -1,141 +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)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程表单解析模块(解析 WorkformEngine 返回的 result,提取电子签三状态及员工信息)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 是否已发起电子签字典(hr_staff_contract.is_initiate_sign)
|
||||
INITIATE_SIGN_MAP = {
|
||||
"0": "未发起",
|
||||
"1": "已发起",
|
||||
"2": "已完成",
|
||||
"3": "已撤销",
|
||||
"5": "已过期",
|
||||
"7": "已拒签",
|
||||
"8": "已作废",
|
||||
}
|
||||
|
||||
# 员工/企业签署状态字典(esign_sigin_state)
|
||||
SIGN_STATE_MAP = {
|
||||
"1": "签署中",
|
||||
"2": "已完成",
|
||||
"3": "未完成",
|
||||
"4": "已作废",
|
||||
}
|
||||
|
||||
# 电子签三状态均须等于该编码(已完成)才同意
|
||||
SIGN_DONE_CODE = "2"
|
||||
|
||||
# 离职类型字典(hr_staff_contract.leaveoffice_type 编码 -> 展示文本)
|
||||
LEAVEOFFICE_TYPE_MAP = {
|
||||
"": "请选择",
|
||||
"0": "辞职",
|
||||
"1": "辞退",
|
||||
"4": "合同期内辞职",
|
||||
"9": "其他",
|
||||
"2": "进修学习",
|
||||
"3": "参军",
|
||||
"5": "除名",
|
||||
"6": "开除",
|
||||
"7": "死亡",
|
||||
"8": "失踪",
|
||||
"11": "协商一致解除",
|
||||
"12": "主动离职",
|
||||
"13": "非主动离职",
|
||||
"14": "自动离职(未办理离职手续)",
|
||||
"15": "开除人员",
|
||||
"16": "调出",
|
||||
"17": "合同到期未续签",
|
||||
"18": "解除合同",
|
||||
"ext_8": "个人申请辞职",
|
||||
"ext_1": "主动辞职",
|
||||
"ext_2": "到期个人不愿续签",
|
||||
"ext_3": "单位不续签",
|
||||
"ext_4": "劝退无证明",
|
||||
"ext_5": "劝退有证明",
|
||||
"ext_6": "自动离职",
|
||||
"ext_7": "双方协商一致解除",
|
||||
"10": "退休",
|
||||
}
|
||||
|
||||
|
||||
def _sign_name(mapping: Dict[str, str], code: Any) -> str:
|
||||
"""将状态编码转换为名称;空值返回空串,未知编码原样返回。"""
|
||||
if code is None or str(code).strip() == "":
|
||||
return ""
|
||||
return mapping.get(str(code).strip(), str(code))
|
||||
|
||||
|
||||
def parse_resign_e_sign_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析离职电子签表单数据,提取关键字段。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(即 doc['formData'])
|
||||
|
||||
Returns:
|
||||
包含离职电子签关键字段的字典(中文键名),三个电子签状态同时保留编码与名称
|
||||
"""
|
||||
is_initiate = result.get("ext_is_initiate_sign")
|
||||
staff_state = result.get("ext_staff_sign_status")
|
||||
org_state = result.get("ext_org_sign_status")
|
||||
|
||||
return {
|
||||
"员工姓名": result.get("staff_name"),
|
||||
"工号": result.get("base_code"),
|
||||
"身份证号": result.get("idcard"),
|
||||
"所属事业部": result.get("belong_unit_org_name"),
|
||||
"组织架构": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"离职日期": result.get("leaveoffice_time"),
|
||||
"离职类型编码": result.get("leaveoffice_type"),
|
||||
"离职类型": _sign_name(LEAVEOFFICE_TYPE_MAP, result.get("leaveoffice_type")),
|
||||
"手机号": result.get("mobile_phone"),
|
||||
"合同类型": result.get("contract_type"),
|
||||
"合同开始日期": result.get("contract_start_date"),
|
||||
"合同结束日期": result.get("contract_end_date"),
|
||||
"是否已发起电子签编码": is_initiate,
|
||||
"是否已发起电子签": _sign_name(INITIATE_SIGN_MAP, is_initiate),
|
||||
"员工签署状态编码": staff_state,
|
||||
"员工签署状态": _sign_name(SIGN_STATE_MAP, staff_state),
|
||||
"企业签署状态编码": org_state,
|
||||
"企业签署状态": _sign_name(SIGN_STATE_MAP, org_state),
|
||||
}
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 示例 result(WorkformEngine 返回的 result 字段,见 aa.md)
|
||||
sample_result = {
|
||||
"base_code": "37022119",
|
||||
"belong_unit_org_name": "金色印象事业部",
|
||||
"ext_is_initiate_sign": "2",
|
||||
"ext_org_sign_status": "2",
|
||||
"ext_staff_sign_status": "2",
|
||||
"idcard": "511623200311056533",
|
||||
"leaveoffice_time": "2026-07-31",
|
||||
"leaveoffice_type": "ext_8",
|
||||
"mobile_phone": "19950986716",
|
||||
"org_full_path": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第四片区-石油路PLUS会馆-接待组",
|
||||
"post_name": "接待员",
|
||||
"staff_name": "夏礼广",
|
||||
}
|
||||
|
||||
parsed = parse_resign_e_sign_form(sample_result)
|
||||
logger.info("===== 离职电子签信息解析结果 =====")
|
||||
for key, value in parsed.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
|
||||
@@ -1,146 +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)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程报告模块。
|
||||
校验结果分两组:通过(已同意)/ 未完成(不管,待后续流转)。
|
||||
输出清单:
|
||||
《离职电子签未完成待跟进清单》:员工姓名、电子签三状态、详情页链接
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的员工姓名,缺失时回退到发起人。"""
|
||||
info = r.get("resign_info", {}) or {}
|
||||
return info.get("员工姓名") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 resign_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("员工姓名", "员工姓名"),
|
||||
("工号", "工号"),
|
||||
("所属事业部", "所属事业部"),
|
||||
("组织架构", "组织架构"),
|
||||
("岗位", "岗位"),
|
||||
("离职日期", "离职日期"),
|
||||
("离职类型", "离职类型"),
|
||||
("合同类型", "合同类型"),
|
||||
("合同开始日期", "合同开始日期"),
|
||||
("合同结束日期", "合同结束日期"),
|
||||
("是否已发起电子签", "是否已发起电子签"),
|
||||
("员工签署状态", "员工签署状态"),
|
||||
("企业签署状态", "企业签署状态"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def _format_verify(verify: Dict[str, Any]) -> str:
|
||||
"""将文书核验结果格式化为易读摘要行。"""
|
||||
if not verify:
|
||||
return ""
|
||||
parts = [f"文书核验: {'通过' if verify.get('is_pass') else '不通过'}"]
|
||||
if verify.get("msg"):
|
||||
parts.append(str(verify["msg"]))
|
||||
for key in ("离职日期(表单)", "报酬支付确认日期", "解除确认书日期", "文书离职原因", "文书命中离职类型"):
|
||||
val = verify.get(key)
|
||||
if val:
|
||||
parts.append(f"{key}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+处理失败/异常)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/未完成/失败/异常}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
pending = [r for r in results if r.get("decision") == "未完成"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},未完成待跟进 {len(pending)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"离职电子签审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("resign_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({info.get('工号', '')})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("签章附件"):
|
||||
lines.append(f" 签章附件: {r['签章附件']}")
|
||||
if r.get("文书核验"):
|
||||
lines.append(f" {_format_verify(r['文书核验'])}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 未完成(不管)待跟进清单 -----
|
||||
if pending:
|
||||
lines.append("《离职电子签未完成待跟进清单》")
|
||||
lines.append("(电子签未全部完成,或文书核验未通过,机器不处理,待后续流转/人工复核)")
|
||||
for i, r in enumerate(pending, 1):
|
||||
info = r.get("resign_info", {}) or {}
|
||||
note = r.get("note") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(
|
||||
f"{i}. 员工姓名: {_name(r)} | "
|
||||
f"发起: {info.get('是否已发起电子签', '未知')} | "
|
||||
f"员工: {info.get('员工签署状态', '未知')} | "
|
||||
f"企业: {info.get('企业签署状态', '未知')} | "
|
||||
f"原因: {note} | 详情页链接: {url}"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《离职电子签审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -1,22 +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()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.resign_e_sign.resign_e_sign_approval
|
||||
@FileName: resign_e_sign_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 离职电子签流程审核入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.resign_e_sign.validator import validate_doc
|
||||
from app.service.hrbp.oa.resign_e_sign.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""离职电子签流程审核:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="离职电子签流程", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,144 +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
|
||||
# -*- 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
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,265 +1,265 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change.si_insurance_check
|
||||
@FileName: si_insurance_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 15:20
|
||||
@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口,
|
||||
判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。
|
||||
@Version: 2.1.0
|
||||
|
||||
业务判定(对应 aa.md):
|
||||
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
|
||||
- 停保申请表:某工号在 HR 参保记录中「无返回数据」→ 已停保,属异常。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
# HR 平台会话/请求封装(共享层,避免反向依赖 ehr)
|
||||
from app.service.hrbp.common.hr_session import (
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
HRSessionExpiredError,
|
||||
hr_request_json,
|
||||
)
|
||||
|
||||
try:
|
||||
import xlrd
|
||||
except ImportError:
|
||||
xlrd = None
|
||||
|
||||
try:
|
||||
from openpyxl import load_workbook as _load_workbook
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
except ImportError:
|
||||
_load_workbook = None
|
||||
_XlsxWorkbook = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# HR 参保记录查询接口(aa.md 提供的 si_main 接口)
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
|
||||
# 接口基础参数(aa.md 基础参数模板,base_codes 动态替换)
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
|
||||
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
|
||||
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
|
||||
"postStruId": "1", "regist_property": "", "identity": "",
|
||||
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
|
||||
"siName": "", "belongUnitId": "", "belongUnitName": "",
|
||||
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
|
||||
RESULT_COL = "社保记录查询结果"
|
||||
BATCH_SIZE = 15
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 查询参保记录接口
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def query_batch(session, codes_batch: List[str]):
|
||||
"""查询一批工号(≤15个),返回响应 JSON。"""
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15)
|
||||
|
||||
|
||||
def extract_found_codes(response_json) -> set:
|
||||
"""从返回 JSON 中提取所有 base_Code 工号。"""
|
||||
datas = response_json.get("datas") or []
|
||||
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
|
||||
|
||||
|
||||
def check_codes(session, codes_batch: List[str]) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。"""
|
||||
try:
|
||||
return extract_found_codes(query_batch(session, codes_batch))
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def preflight(session) -> "requests.Session":
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
query_batch(session, ["0"])
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 读取表格(支持 .xlsx / .xls)
|
||||
# ----------------------------------------------
|
||||
def read_table(path: str) -> Tuple[List[str], List[list]]:
|
||||
"""读取表格,返回 (表头, 数据行)。"""
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
if ext == ".xlsx":
|
||||
if _load_workbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法读取 .xlsx")
|
||||
ws = _load_workbook(path).active
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
headers = [str(h) if h is not None else "" for h in rows[0]]
|
||||
data = [list(r) for r in rows[1:]]
|
||||
elif ext == ".xls":
|
||||
if xlrd is None:
|
||||
raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls")
|
||||
sh = xlrd.open_workbook(path).sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
data = [[sh.cell_value(r, c) for c in range(sh.ncols)] for r in range(1, sh.nrows)]
|
||||
else:
|
||||
raise ValueError(f"不支持的文件格式:{ext},请提供 .xlsx 或 .xls")
|
||||
return headers, data
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 核对并追加结果列
|
||||
# ----------------------------------------------
|
||||
def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str:
|
||||
"""读表 → 按工号去重 → 逐批查接口 → 追加结果列 → 导出 .xlsx。
|
||||
|
||||
mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常)
|
||||
"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
|
||||
|
||||
headers, data = read_table(table_path)
|
||||
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
# 按工号去重(保持首次出现顺序),再逐批查询
|
||||
unique_codes = []
|
||||
seen = set()
|
||||
for row in data:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code and code not in seen:
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
session = preflight(build_hr_session(auto_login=False))
|
||||
found = set()
|
||||
for i in range(0, len(unique_codes), BATCH_SIZE):
|
||||
batch = unique_codes[i:i + BATCH_SIZE]
|
||||
try:
|
||||
found |= check_codes(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
session = refresh_hr_session()
|
||||
found |= check_codes(session, batch)
|
||||
logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3) # 轻微限速,避免触发风控
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in data:
|
||||
code = str(row[emp_col]).strip()
|
||||
has_record = code in found
|
||||
if is_participate:
|
||||
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
|
||||
else:
|
||||
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
|
||||
new_rows.append(row + [val])
|
||||
|
||||
out_path = os.path.abspath(os.path.join(
|
||||
output_dir,
|
||||
f"{os.path.splitext(os.path.basename(table_path))[0]}_参保核对.xlsx",
|
||||
))
|
||||
out_wb = _XlsxWorkbook()
|
||||
ws = out_wb.active
|
||||
ws.append(headers + [RESULT_COL])
|
||||
for row in new_rows:
|
||||
ws.append(row)
|
||||
out_wb.save(out_path)
|
||||
|
||||
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
|
||||
logger.info("完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
|
||||
len(unique_codes), len(found), len(abnormal), out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def check_participation(table_path: str, output_dir: str = ".") -> str:
|
||||
return check_and_annotate(table_path, "participation", output_dir)
|
||||
|
||||
|
||||
def check_suspension(table_path: str, output_dir: str = ".") -> str:
|
||||
return check_and_annotate(table_path, "suspension", output_dir)
|
||||
|
||||
|
||||
def _latest_cleaned(project: str, keyword: str) -> str:
|
||||
"""在项目目录里找最新(按修改时间)的、文件名含关键字且以 _去重.xlsx 结尾的表。"""
|
||||
matches = [
|
||||
p for p in Path(project).glob("*.xlsx")
|
||||
if keyword in p.name and p.name.endswith("_去重.xlsx")
|
||||
]
|
||||
if not matches:
|
||||
return ""
|
||||
return str(max(matches, key=lambda p: p.stat().st_mtime))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
project = _root
|
||||
|
||||
def pick(keyword):
|
||||
# 优先命令行显式指定,否则自动找最新清洗表
|
||||
for a in args:
|
||||
if keyword in Path(a).name:
|
||||
return a
|
||||
return _latest_cleaned(project, keyword)
|
||||
|
||||
participate = pick("参保")
|
||||
suspend = pick("停保")
|
||||
|
||||
if participate and os.path.exists(participate):
|
||||
check_participation(participate, project)
|
||||
else:
|
||||
logger.warning("未找到参保清洗表(*参保*_去重.xlsx)")
|
||||
|
||||
if suspend and os.path.exists(suspend):
|
||||
check_suspension(suspend, project)
|
||||
else:
|
||||
logger.warning("未找到停保清洗表(*停保*_去重.xlsx)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_change.si_insurance_check
|
||||
@FileName: si_insurance_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07 15:20
|
||||
@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口,
|
||||
判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。
|
||||
@Version: 2.1.0
|
||||
|
||||
业务判定(对应 aa.md):
|
||||
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
|
||||
- 停保申请表:某工号在 HR 参保记录中「无返回数据」→ 已停保,属异常。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
# ---- 单文件运行支持 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
# HR 平台会话/请求封装(共享层,避免反向依赖 ehr)
|
||||
from app.service.hrbp.common.hr_session import (
|
||||
build_hr_session,
|
||||
refresh_hr_session,
|
||||
HRSessionExpiredError,
|
||||
hr_request_json,
|
||||
)
|
||||
|
||||
try:
|
||||
import xlrd
|
||||
except ImportError:
|
||||
xlrd = None
|
||||
|
||||
try:
|
||||
from openpyxl import load_workbook as _load_workbook
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
except ImportError:
|
||||
_load_workbook = None
|
||||
_XlsxWorkbook = None
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# HR 参保记录查询接口(aa.md 提供的 si_main 接口)
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
|
||||
# 接口基础参数(aa.md 基础参数模板,base_codes 动态替换)
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
|
||||
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
|
||||
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
|
||||
"postStruId": "1", "regist_property": "", "identity": "",
|
||||
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
|
||||
"siName": "", "belongUnitId": "", "belongUnitName": "",
|
||||
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
|
||||
RESULT_COL = "社保记录查询结果"
|
||||
BATCH_SIZE = 15
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 1. 查询参保记录接口
|
||||
# ----------------------------------------------
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def query_batch(session, codes_batch: List[str]):
|
||||
"""查询一批工号(≤15个),返回响应 JSON。"""
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
return hr_request_json(session, "POST", SI_QUERY_URL, params, "社保参保记录", timeout=15)
|
||||
|
||||
|
||||
def extract_found_codes(response_json) -> set:
|
||||
"""从返回 JSON 中提取所有 base_Code 工号。"""
|
||||
datas = response_json.get("datas") or []
|
||||
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
|
||||
|
||||
|
||||
def check_codes(session, codes_batch: List[str]) -> set:
|
||||
"""返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。"""
|
||||
try:
|
||||
return extract_found_codes(query_batch(session, codes_batch))
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("批量查询失败 %s:%s", codes_batch, e)
|
||||
return set()
|
||||
|
||||
|
||||
def preflight(session) -> "requests.Session":
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
|
||||
try:
|
||||
query_batch(session, ["0"])
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
|
||||
return refresh_hr_session()
|
||||
return session
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 3. 读取表格(支持 .xlsx / .xls)
|
||||
# ----------------------------------------------
|
||||
def read_table(path: str) -> Tuple[List[str], List[list]]:
|
||||
"""读取表格,返回 (表头, 数据行)。"""
|
||||
ext = os.path.splitext(path)[1].lower()
|
||||
if ext == ".xlsx":
|
||||
if _load_workbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法读取 .xlsx")
|
||||
ws = _load_workbook(path).active
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
headers = [str(h) if h is not None else "" for h in rows[0]]
|
||||
data = [list(r) for r in rows[1:]]
|
||||
elif ext == ".xls":
|
||||
if xlrd is None:
|
||||
raise RuntimeError("缺少 xlrd 依赖,无法读取 .xls")
|
||||
sh = xlrd.open_workbook(path).sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
data = [[sh.cell_value(r, c) for c in range(sh.ncols)] for r in range(1, sh.nrows)]
|
||||
else:
|
||||
raise ValueError(f"不支持的文件格式:{ext},请提供 .xlsx 或 .xls")
|
||||
return headers, data
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 4. 核对并追加结果列
|
||||
# ----------------------------------------------
|
||||
def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str:
|
||||
"""读表 → 按工号去重 → 逐批查接口 → 追加结果列 → 导出 .xlsx。
|
||||
|
||||
mode: "participation"(参保,有记录=异常)/ "suspension"(停保,无记录=异常)
|
||||
"""
|
||||
if _XlsxWorkbook is None:
|
||||
raise RuntimeError("缺少 openpyxl 依赖,无法导出 .xlsx")
|
||||
|
||||
headers, data = read_table(table_path)
|
||||
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
# 按工号去重(保持首次出现顺序),再逐批查询
|
||||
unique_codes = []
|
||||
seen = set()
|
||||
for row in data:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code and code not in seen:
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
session = preflight(build_hr_session(auto_login=False))
|
||||
found = set()
|
||||
for i in range(0, len(unique_codes), BATCH_SIZE):
|
||||
batch = unique_codes[i:i + BATCH_SIZE]
|
||||
try:
|
||||
found |= check_codes(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
|
||||
min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
session = refresh_hr_session()
|
||||
found |= check_codes(session, batch)
|
||||
logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3) # 轻微限速,避免触发风控
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in data:
|
||||
code = str(row[emp_col]).strip()
|
||||
has_record = code in found
|
||||
if is_participate:
|
||||
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
|
||||
else:
|
||||
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
|
||||
new_rows.append(row + [val])
|
||||
|
||||
out_path = os.path.abspath(os.path.join(
|
||||
output_dir,
|
||||
f"{os.path.splitext(os.path.basename(table_path))[0]}_参保核对.xlsx",
|
||||
))
|
||||
out_wb = _XlsxWorkbook()
|
||||
ws = out_wb.active
|
||||
ws.append(headers + [RESULT_COL])
|
||||
for row in new_rows:
|
||||
ws.append(row)
|
||||
out_wb.save(out_path)
|
||||
|
||||
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
|
||||
logger.info("完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
|
||||
len(unique_codes), len(found), len(abnormal), out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ----------------------------------------------
|
||||
# 5. 对外便捷入口
|
||||
# ----------------------------------------------
|
||||
def check_participation(table_path: str, output_dir: str = ".") -> str:
|
||||
return check_and_annotate(table_path, "participation", output_dir)
|
||||
|
||||
|
||||
def check_suspension(table_path: str, output_dir: str = ".") -> str:
|
||||
return check_and_annotate(table_path, "suspension", output_dir)
|
||||
|
||||
|
||||
def _latest_cleaned(project: str, keyword: str) -> str:
|
||||
"""在项目目录里找最新(按修改时间)的、文件名含关键字且以 _去重.xlsx 结尾的表。"""
|
||||
matches = [
|
||||
p for p in Path(project).glob("*.xlsx")
|
||||
if keyword in p.name and p.name.endswith("_去重.xlsx")
|
||||
]
|
||||
if not matches:
|
||||
return ""
|
||||
return str(max(matches, key=lambda p: p.stat().st_mtime))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
project = _root
|
||||
|
||||
def pick(keyword):
|
||||
# 优先命令行显式指定,否则自动找最新清洗表
|
||||
for a in args:
|
||||
if keyword in Path(a).name:
|
||||
return a
|
||||
return _latest_cleaned(project, keyword)
|
||||
|
||||
participate = pick("参保")
|
||||
suspend = pick("停保")
|
||||
|
||||
if participate and os.path.exists(participate):
|
||||
check_participation(participate, project)
|
||||
else:
|
||||
logger.warning("未找到参保清洗表(*参保*_去重.xlsx)")
|
||||
|
||||
if suspend and os.path.exists(suspend):
|
||||
check_suspension(suspend, project)
|
||||
else:
|
||||
logger.warning("未找到停保清洗表(*停保*_去重.xlsx)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_notice
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发模块(读取参保/停保名单 → 按模板批量生成 Word 告知书并转 PDF)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_notice
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发模块(读取参保/停保名单 → 按模板批量生成 Word 告知书并转 PDF)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.overtime_approval
|
||||
@FileName: overtime_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:22
|
||||
@Description: 加班审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.work_overtime.validator import validate_doc
|
||||
from app.service.hrbp.oa.work_overtime.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""加班审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="加班", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.overtime_approval
|
||||
@FileName: overtime_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:22
|
||||
@Description: 加班审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
from app.service.hrbp.oa.common.approval_flow import run_flow
|
||||
from app.service.hrbp.oa.work_overtime.validator import validate_doc
|
||||
from app.service.hrbp.oa.work_overtime.reporter import generate_report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""加班审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="加班", validate_doc=validate_doc, generate_report=generate_report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,103 +1,103 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 09:30
|
||||
@Description: 加班表单解析模块(解析 WorkformEngine 返回的 result,提取关键字段并转换为中文描述)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 加班类型映射
|
||||
OT_TYPE_MAP = {
|
||||
"1": "延时加班",
|
||||
"2": "法定假日加班",
|
||||
"3": "休息日加班",
|
||||
}
|
||||
|
||||
# 补贴类型映射
|
||||
SUBSIDY_TYPE_MAP = {
|
||||
"1": "转调休",
|
||||
"2": "转补贴",
|
||||
}
|
||||
|
||||
|
||||
def parse_overtime_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析加班表单数据,提取关键字段并将代码转换为中文描述。
|
||||
|
||||
注意:入参为 oa_api.get_business_data 返回的 result 字段(state 校验已在
|
||||
get_business_data 内完成),即审批引擎 doc['formData']。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(含 ot_type / staff_name 等)
|
||||
|
||||
Returns:
|
||||
包含加班关键字段的字典(中文键名);找不到映射时保留原始代码值
|
||||
"""
|
||||
# 获取原始类型代码
|
||||
ot_type_code = result.get("ot_type")
|
||||
subsidy_type_code = result.get("subsidy_type")
|
||||
|
||||
overtime_info = {
|
||||
"加班人员ID": result.get("staff_id"),
|
||||
"加班人员": result.get("staff_name"),
|
||||
"所属部门": result.get("dept_org_name"),
|
||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
||||
"加班日期": result.get("ot_date"),
|
||||
"加班开始时间": result.get("start_time"),
|
||||
"加班结束时间": result.get("end_time"),
|
||||
"加班时长(小时)": result.get("ot_hour") or result.get("expect_hour"),
|
||||
"加班天数(天)": result.get("ot_day"),
|
||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
# 拼接系统判定的加班时间段
|
||||
judge_start = result.get("judge_start_time")
|
||||
judge_end = result.get("judge_end_time")
|
||||
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
|
||||
if (judge_start and judge_end
|
||||
and "无" not in str(judge_start) and "无" not in str(judge_end)):
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 示例 result(WorkformEngine 返回的 result 字段)
|
||||
sample_result = {
|
||||
"dept_org_name": "网络项目小组",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"ot_date": "2026-08-02",
|
||||
"ot_hour": 6.0,
|
||||
"ot_type": "1",
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"subsidy_type": "2",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
|
||||
parsed = parse_overtime_form(sample_result)
|
||||
logger.info("===== 加班信息解析结果 =====")
|
||||
for key, value in parsed.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 09:30
|
||||
@Description: 加班表单解析模块(解析 WorkformEngine 返回的 result,提取关键字段并转换为中文描述)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 加班类型映射
|
||||
OT_TYPE_MAP = {
|
||||
"1": "延时加班",
|
||||
"2": "法定假日加班",
|
||||
"3": "休息日加班",
|
||||
}
|
||||
|
||||
# 补贴类型映射
|
||||
SUBSIDY_TYPE_MAP = {
|
||||
"1": "转调休",
|
||||
"2": "转补贴",
|
||||
}
|
||||
|
||||
|
||||
def parse_overtime_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析加班表单数据,提取关键字段并将代码转换为中文描述。
|
||||
|
||||
注意:入参为 oa_api.get_business_data 返回的 result 字段(state 校验已在
|
||||
get_business_data 内完成),即审批引擎 doc['formData']。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(含 ot_type / staff_name 等)
|
||||
|
||||
Returns:
|
||||
包含加班关键字段的字典(中文键名);找不到映射时保留原始代码值
|
||||
"""
|
||||
# 获取原始类型代码
|
||||
ot_type_code = result.get("ot_type")
|
||||
subsidy_type_code = result.get("subsidy_type")
|
||||
|
||||
overtime_info = {
|
||||
"加班人员ID": result.get("staff_id"),
|
||||
"加班人员": result.get("staff_name"),
|
||||
"所属部门": result.get("dept_org_name"),
|
||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
||||
"加班日期": result.get("ot_date"),
|
||||
"加班开始时间": result.get("start_time"),
|
||||
"加班结束时间": result.get("end_time"),
|
||||
"加班时长(小时)": result.get("ot_hour") or result.get("expect_hour"),
|
||||
"加班天数(天)": result.get("ot_day"),
|
||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
# 拼接系统判定的加班时间段
|
||||
judge_start = result.get("judge_start_time")
|
||||
judge_end = result.get("judge_end_time")
|
||||
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
|
||||
if (judge_start and judge_end
|
||||
and "无" not in str(judge_start) and "无" not in str(judge_end)):
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 示例 result(WorkformEngine 返回的 result 字段)
|
||||
sample_result = {
|
||||
"dept_org_name": "网络项目小组",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"ot_date": "2026-08-02",
|
||||
"ot_hour": 6.0,
|
||||
"ot_type": "1",
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"subsidy_type": "2",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
|
||||
parsed = parse_overtime_form(sample_result)
|
||||
logger.info("===== 加班信息解析结果 =====")
|
||||
for key, value in parsed.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
|
||||
@@ -1,162 +1,162 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程报告模块。
|
||||
校验结果分四组:通过 / 校验不通过未处理 / 人工复核 / 超期。
|
||||
输出三份清单:
|
||||
《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因、详情页链接
|
||||
《附件人工复核待办清单》:员工姓名、加班类型、详情页链接(供人工打开查看附件)
|
||||
《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 2.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的加班人员,缺失时回退到发起人。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _otype(r: Dict[str, Any]) -> str:
|
||||
"""加班类型。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if overdue:
|
||||
summary += f",超期待人资处理 {len(overdue)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 超期待人资处理清单 -----
|
||||
if overdue:
|
||||
lines.append("《超期加班待人资处理清单》")
|
||||
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
|
||||
for i, r in enumerate(overdue, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《加班审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程报告模块。
|
||||
校验结果分四组:通过 / 校验不通过未处理 / 人工复核 / 超期。
|
||||
输出三份清单:
|
||||
《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因、详情页链接
|
||||
《附件人工复核待办清单》:员工姓名、加班类型、详情页链接(供人工打开查看附件)
|
||||
《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
|
||||
通过名单的简短汇总由 common.notify.build_push_summary 生成并推送钉钉。
|
||||
@Version: 2.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _name(r: Dict[str, Any]) -> str:
|
||||
"""员工姓名:优先取表单里的加班人员,缺失时回退到发起人。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _otype(r: Dict[str, Any]) -> str:
|
||||
"""加班类型。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info: Dict[str, Any]) -> str:
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("所属部门", "所属部门"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表,decision ∈ {通过/校验不通过未处理/人工复核/失败}
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if overdue:
|
||||
summary += f",超期待人资处理 {len(overdue)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 超期待人资处理清单 -----
|
||||
if overdue:
|
||||
lines.append("《超期加班待人资处理清单》")
|
||||
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
|
||||
for i, r in enumerate(overdue, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《加班审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+596
-596
File diff suppressed because it is too large
Load Diff
+863
-863
File diff suppressed because it is too large
Load Diff
@@ -1,78 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.utils
|
||||
@FileName: utils.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:30
|
||||
@Description: 项目级通用工具(重试装饰器)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import functools
|
||||
import random
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试耗尽后抛出的异常,保留原始异常链。"""
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
"""
|
||||
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
|
||||
|
||||
Args:
|
||||
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
|
||||
no_retry_on: 遇到这些异常类型时直接抛出、不做重试(用于无需重试的确定性失败)。
|
||||
|
||||
内部行为(对调用方透明):
|
||||
- 捕获所有 Exception;
|
||||
- 延迟策略:第 n 次重试等待 1.0 * 2^(n-1) 秒,并乘以 [0.5, 1.5] 随机因子;
|
||||
- 全部失败后抛出 RetryExhaustedError,可通过 __cause__ 获取原始异常。
|
||||
"""
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
base_delay = 1.0
|
||||
backoff = 2.0
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
logger.error(
|
||||
"%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, e,
|
||||
)
|
||||
break
|
||||
|
||||
# 计算退避 + 抖动
|
||||
delay = base_delay * (backoff ** (attempt - 1))
|
||||
delay *= random.uniform(0.5, 1.5)
|
||||
|
||||
logger.warning(
|
||||
"%s 第 %d 次执行失败: %s,%.2f 秒后重试",
|
||||
func.__name__, attempt, e, delay,
|
||||
)
|
||||
time.sleep(delay)
|
||||
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts"
|
||||
) from last_exc
|
||||
|
||||
return wrapper
|
||||
return decorator
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.utils
|
||||
@FileName: utils.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:30
|
||||
@Description: 项目级通用工具(重试装饰器)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import functools
|
||||
import random
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试耗尽后抛出的异常,保留原始异常链。"""
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
|
||||
"""
|
||||
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
|
||||
|
||||
Args:
|
||||
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
|
||||
no_retry_on: 遇到这些异常类型时直接抛出、不做重试(用于无需重试的确定性失败)。
|
||||
|
||||
内部行为(对调用方透明):
|
||||
- 捕获所有 Exception;
|
||||
- 延迟策略:第 n 次重试等待 1.0 * 2^(n-1) 秒,并乘以 [0.5, 1.5] 随机因子;
|
||||
- 全部失败后抛出 RetryExhaustedError,可通过 __cause__ 获取原始异常。
|
||||
"""
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
def decorator(func: Callable) -> Callable:
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
base_delay = 1.0
|
||||
backoff = 2.0
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
logger.error(
|
||||
"%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, e,
|
||||
)
|
||||
break
|
||||
|
||||
# 计算退避 + 抖动
|
||||
delay = base_delay * (backoff ** (attempt - 1))
|
||||
delay *= random.uniform(0.5, 1.5)
|
||||
|
||||
logger.warning(
|
||||
"%s 第 %d 次执行失败: %s,%.2f 秒后重试",
|
||||
func.__name__, attempt, e, delay,
|
||||
)
|
||||
time.sleep(delay)
|
||||
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts"
|
||||
) from last_exc
|
||||
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
+88
-88
@@ -1,89 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils.logger
|
||||
@FileName: logger.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05
|
||||
@Description: 项目统一日志配置:控制台彩色输出 + 文件持久化
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
_initialized = False
|
||||
|
||||
|
||||
class _ColoredFormatter(logging.Formatter):
|
||||
"""控制台彩色日志格式,不修改 record 本身,避免污染文件输出"""
|
||||
|
||||
_colors = {
|
||||
logging.DEBUG: "\033[36m",
|
||||
logging.INFO: "\033[32m",
|
||||
logging.WARNING: "\033[33m",
|
||||
logging.ERROR: "\033[31m",
|
||||
logging.CRITICAL: "\033[35m",
|
||||
}
|
||||
_reset = "\033[0m"
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self._colors.get(record.levelno, "")
|
||||
orig_levelname = record.levelname
|
||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||||
result = super().format(record)
|
||||
record.levelname = orig_levelname
|
||||
return result
|
||||
|
||||
|
||||
def setup_logging(
|
||||
level: int = logging.INFO,
|
||||
log_dir: str = None,
|
||||
log_file: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
初始化项目统一日志配置。只需在入口调用一次。
|
||||
|
||||
Args:
|
||||
level: 日志级别,默认 INFO
|
||||
log_dir: 日志文件目录,默认 app/logs/
|
||||
log_file: 是否同时输出到文件,默认 True
|
||||
"""
|
||||
global _initialized
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(level)
|
||||
logger.handlers.clear()
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
if log_file:
|
||||
if log_dir is None:
|
||||
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
"""获取模块级 logger,用法:logger = get_logger(__name__)"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils.logger
|
||||
@FileName: logger.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05
|
||||
@Description: 项目统一日志配置:控制台彩色输出 + 文件持久化
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
_initialized = False
|
||||
|
||||
|
||||
class _ColoredFormatter(logging.Formatter):
|
||||
"""控制台彩色日志格式,不修改 record 本身,避免污染文件输出"""
|
||||
|
||||
_colors = {
|
||||
logging.DEBUG: "\033[36m",
|
||||
logging.INFO: "\033[32m",
|
||||
logging.WARNING: "\033[33m",
|
||||
logging.ERROR: "\033[31m",
|
||||
logging.CRITICAL: "\033[35m",
|
||||
}
|
||||
_reset = "\033[0m"
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self._colors.get(record.levelno, "")
|
||||
orig_levelname = record.levelname
|
||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||||
result = super().format(record)
|
||||
record.levelname = orig_levelname
|
||||
return result
|
||||
|
||||
|
||||
def setup_logging(
|
||||
level: int = logging.INFO,
|
||||
log_dir: str = None,
|
||||
log_file: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
初始化项目统一日志配置。只需在入口调用一次。
|
||||
|
||||
Args:
|
||||
level: 日志级别,默认 INFO
|
||||
log_dir: 日志文件目录,默认 app/logs/
|
||||
log_file: 是否同时输出到文件,默认 True
|
||||
"""
|
||||
global _initialized
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(level)
|
||||
logger.handlers.clear()
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
if log_file:
|
||||
if log_dir is None:
|
||||
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
"""获取模块级 logger,用法:logger = get_logger(__name__)"""
|
||||
return logging.getLogger(name)
|
||||
+130
-130
@@ -1,130 +1,130 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: app.utils.ocr
|
||||
@FileName: ocr.py
|
||||
@Author: 小布丁
|
||||
@Description: 通用图像文字识别模块(RapidOCR)。
|
||||
只做「传图片 -> 返回识别文本」,不含任何业务判断;
|
||||
业务判断由各业务脚本负责(如请假附件关键词检测见
|
||||
app/service/hrbp/oa/leave/attachment_check.py)。
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Tuple
|
||||
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
from rapidocr import RapidOCR
|
||||
except ImportError:
|
||||
RapidOCR = None
|
||||
|
||||
# 置信度阈值:低于该分数的识别片段会被丢弃
|
||||
_CONFIDENCE_THRESHOLD = 0.5
|
||||
|
||||
# 全局初始化 OCR 引擎,首次运行自动下载模型
|
||||
_ocr_engine = RapidOCR() if RapidOCR is not None else None
|
||||
|
||||
|
||||
def _preprocess_image(img) -> np.ndarray:
|
||||
"""预处理图像:EXIF 转正(修正手机横拍)+ 转灰度 + 提升对比度,返回可喂给 OCR 的图像数组。"""
|
||||
img = ImageOps.exif_transpose(img)
|
||||
gray_img = img.convert("L")
|
||||
enhancer = ImageEnhance.Contrast(gray_img)
|
||||
enhanced_img = enhancer.enhance(2.0)
|
||||
return np.array(enhanced_img)
|
||||
|
||||
|
||||
def _run_ocr(img_array: np.ndarray, debug: bool = False) -> Tuple[str, str]:
|
||||
"""
|
||||
对预处理后的图像数组执行 OCR,返回 (清洗后拼接文本, 原始拼接文本)。
|
||||
|
||||
- 过滤低置信度片段
|
||||
- 清洗:去空格与特殊符号,便于关键词匹配
|
||||
"""
|
||||
if _ocr_engine is None:
|
||||
raise RuntimeError("RapidOCR 未安装,请执行: pip install rapidocr onnxruntime")
|
||||
|
||||
result = _ocr_engine(img_array)
|
||||
|
||||
txts = result.txts if result and result.txts is not None else ()
|
||||
scores = result.scores if result and result.scores is not None else ()
|
||||
|
||||
if debug:
|
||||
print("=" * 60)
|
||||
print("【OCR原始识别片段(含置信度)】")
|
||||
for idx, (txt, score) in enumerate(zip(txts, scores)):
|
||||
print(f" [{idx:02d}] 置信度:{score:.3f} | 文本: {txt}")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
raw_text = ""
|
||||
full_text = ""
|
||||
for text, score in zip(txts, scores):
|
||||
if score < _CONFIDENCE_THRESHOLD:
|
||||
continue
|
||||
raw_text += text
|
||||
clean_text = text.replace(" ", "").replace("\u3000", "")
|
||||
full_text += clean_text
|
||||
|
||||
# 过滤乱码特殊符号,保留常用字符
|
||||
clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]')
|
||||
full_text = clean_pattern.sub('', full_text)
|
||||
|
||||
return full_text, raw_text
|
||||
|
||||
|
||||
def _read_image(img, debug: bool = False) -> Tuple[str, str]:
|
||||
"""对 PIL.Image 做预处理并 OCR,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
img_array = _preprocess_image(img)
|
||||
return _run_ocr(img_array, debug=debug)
|
||||
|
||||
|
||||
def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]:
|
||||
"""OCR 识别图片文件,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
with Image.open(file_path) as img:
|
||||
return _read_image(img, debug=debug)
|
||||
|
||||
|
||||
def recognize_image(img, debug: bool = False) -> str:
|
||||
"""
|
||||
通用图像 OCR(图像输入):传入 PIL.Image 或 numpy 数组,返回识别出的清洗后文本。
|
||||
|
||||
供 PDF 扫描页渲染等内存图像场景复用;图片文件场景请使用 recognize_text()。
|
||||
"""
|
||||
if isinstance(img, np.ndarray):
|
||||
img = Image.fromarray(img)
|
||||
full_text, _ = _read_image(img, debug=debug)
|
||||
return full_text
|
||||
|
||||
|
||||
def recognize_text(file_path: str, debug: bool = False) -> str:
|
||||
"""
|
||||
通用图像 OCR(文件输入):传入图片路径,返回识别出的清洗后文本。
|
||||
|
||||
Args:
|
||||
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
|
||||
debug: 是否打印调试信息
|
||||
|
||||
Returns:
|
||||
识别出的文本(已去空格、过滤特殊符号,便于关键词匹配);文件异常/识别失败抛异常
|
||||
"""
|
||||
full_text, _ = _read_text(file_path, debug=debug)
|
||||
return full_text
|
||||
|
||||
|
||||
def recognize_text_raw(file_path: str, debug: bool = False) -> str:
|
||||
"""
|
||||
通用图像 OCR(文件输入):返回原始拼接文本(保留识别片段原样,含空格/符号)。
|
||||
|
||||
需要展示识别原文时使用;默认请用 recognize_text()。
|
||||
"""
|
||||
_, raw_text = _read_text(file_path, debug=debug)
|
||||
return raw_text
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 简单自测入口
|
||||
path = r"D:\downloads\ocr_test_01.png"
|
||||
print(recognize_text(path, debug=True))
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: app.utils.ocr
|
||||
@FileName: ocr.py
|
||||
@Author: 小布丁
|
||||
@Description: 通用图像文字识别模块(RapidOCR)。
|
||||
只做「传图片 -> 返回识别文本」,不含任何业务判断;
|
||||
业务判断由各业务脚本负责(如请假附件关键词检测见
|
||||
app/service/hrbp/oa/leave/attachment_check.py)。
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Tuple
|
||||
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
from rapidocr import RapidOCR
|
||||
except ImportError:
|
||||
RapidOCR = None
|
||||
|
||||
# 置信度阈值:低于该分数的识别片段会被丢弃
|
||||
_CONFIDENCE_THRESHOLD = 0.5
|
||||
|
||||
# 全局初始化 OCR 引擎,首次运行自动下载模型
|
||||
_ocr_engine = RapidOCR() if RapidOCR is not None else None
|
||||
|
||||
|
||||
def _preprocess_image(img) -> np.ndarray:
|
||||
"""预处理图像:EXIF 转正(修正手机横拍)+ 转灰度 + 提升对比度,返回可喂给 OCR 的图像数组。"""
|
||||
img = ImageOps.exif_transpose(img)
|
||||
gray_img = img.convert("L")
|
||||
enhancer = ImageEnhance.Contrast(gray_img)
|
||||
enhanced_img = enhancer.enhance(2.0)
|
||||
return np.array(enhanced_img)
|
||||
|
||||
|
||||
def _run_ocr(img_array: np.ndarray, debug: bool = False) -> Tuple[str, str]:
|
||||
"""
|
||||
对预处理后的图像数组执行 OCR,返回 (清洗后拼接文本, 原始拼接文本)。
|
||||
|
||||
- 过滤低置信度片段
|
||||
- 清洗:去空格与特殊符号,便于关键词匹配
|
||||
"""
|
||||
if _ocr_engine is None:
|
||||
raise RuntimeError("RapidOCR 未安装,请执行: pip install rapidocr onnxruntime")
|
||||
|
||||
result = _ocr_engine(img_array)
|
||||
|
||||
txts = result.txts if result and result.txts is not None else ()
|
||||
scores = result.scores if result and result.scores is not None else ()
|
||||
|
||||
if debug:
|
||||
print("=" * 60)
|
||||
print("【OCR原始识别片段(含置信度)】")
|
||||
for idx, (txt, score) in enumerate(zip(txts, scores)):
|
||||
print(f" [{idx:02d}] 置信度:{score:.3f} | 文本: {txt}")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
raw_text = ""
|
||||
full_text = ""
|
||||
for text, score in zip(txts, scores):
|
||||
if score < _CONFIDENCE_THRESHOLD:
|
||||
continue
|
||||
raw_text += text
|
||||
clean_text = text.replace(" ", "").replace("\u3000", "")
|
||||
full_text += clean_text
|
||||
|
||||
# 过滤乱码特殊符号,保留常用字符
|
||||
clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]')
|
||||
full_text = clean_pattern.sub('', full_text)
|
||||
|
||||
return full_text, raw_text
|
||||
|
||||
|
||||
def _read_image(img, debug: bool = False) -> Tuple[str, str]:
|
||||
"""对 PIL.Image 做预处理并 OCR,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
img_array = _preprocess_image(img)
|
||||
return _run_ocr(img_array, debug=debug)
|
||||
|
||||
|
||||
def _read_text(file_path: str, debug: bool = False) -> Tuple[str, str]:
|
||||
"""OCR 识别图片文件,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
with Image.open(file_path) as img:
|
||||
return _read_image(img, debug=debug)
|
||||
|
||||
|
||||
def recognize_image(img, debug: bool = False) -> str:
|
||||
"""
|
||||
通用图像 OCR(图像输入):传入 PIL.Image 或 numpy 数组,返回识别出的清洗后文本。
|
||||
|
||||
供 PDF 扫描页渲染等内存图像场景复用;图片文件场景请使用 recognize_text()。
|
||||
"""
|
||||
if isinstance(img, np.ndarray):
|
||||
img = Image.fromarray(img)
|
||||
full_text, _ = _read_image(img, debug=debug)
|
||||
return full_text
|
||||
|
||||
|
||||
def recognize_text(file_path: str, debug: bool = False) -> str:
|
||||
"""
|
||||
通用图像 OCR(文件输入):传入图片路径,返回识别出的清洗后文本。
|
||||
|
||||
Args:
|
||||
file_path: 图片文件路径(png/jpg/jpeg/bmp 等)
|
||||
debug: 是否打印调试信息
|
||||
|
||||
Returns:
|
||||
识别出的文本(已去空格、过滤特殊符号,便于关键词匹配);文件异常/识别失败抛异常
|
||||
"""
|
||||
full_text, _ = _read_text(file_path, debug=debug)
|
||||
return full_text
|
||||
|
||||
|
||||
def recognize_text_raw(file_path: str, debug: bool = False) -> str:
|
||||
"""
|
||||
通用图像 OCR(文件输入):返回原始拼接文本(保留识别片段原样,含空格/符号)。
|
||||
|
||||
需要展示识别原文时使用;默认请用 recognize_text()。
|
||||
"""
|
||||
_, raw_text = _read_text(file_path, debug=debug)
|
||||
return raw_text
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 简单自测入口
|
||||
path = r"D:\downloads\ocr_test_01.png"
|
||||
print(recognize_text(path, debug=True))
|
||||
|
||||
@@ -262,7 +262,8 @@ def _shell_meta() -> dict:
|
||||
if not vf.is_file():
|
||||
return {}
|
||||
try:
|
||||
d = json.loads(vf.read_text(encoding="utf-8"))
|
||||
# utf-8-sig:防 version.json 带 UTF-8 BOM(否则 json.loads 抛 JSONDecodeError → 回退失败)
|
||||
d = json.loads(vf.read_text(encoding="utf-8-sig"))
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
+220
-220
@@ -1,220 +1,220 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
|
||||
|
||||
后台线程发送,失败仅记日志不阻断业务。
|
||||
|
||||
配置项(controlplane/.env):
|
||||
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
|
||||
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
|
||||
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
|
||||
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote_plus
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.dingtalk import _dingtalk_topapi_token
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
|
||||
_SIGN_NAME = "37du 自动化平台"
|
||||
_STATUS_COLORS = {
|
||||
"info": "#0077ff", # 蓝色
|
||||
"success": "#00b300", # 绿色
|
||||
"warning": "#ff9900", # 橙色
|
||||
"error": "#ff0000", # 红色
|
||||
}
|
||||
|
||||
|
||||
def _footer() -> str:
|
||||
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
|
||||
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
req.add_header(k, v)
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
|
||||
def _userid_by_unionid(at: str, unionid: str) -> str:
|
||||
"""unionid → userid(精确,无重名歧义)。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
|
||||
{"unionid": unionid})
|
||||
return ((body.get("result") or {}).get("userid")) or ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _userid_by_name(at: str, name: str) -> str:
|
||||
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://api.dingtalk.com/v1.0/contact/users/search",
|
||||
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
|
||||
headers={"x-acs-dingtalk-access-token": at})
|
||||
lst = body.get("list") or []
|
||||
return str(lst[0]) if lst else ""
|
||||
except Exception as e: # noqa: BLE001 查询失败不阻断业务
|
||||
log.warning("钉钉搜索用户失败(%s):%s", name, e)
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
|
||||
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
|
||||
status: str = "info") -> bool:
|
||||
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
|
||||
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += f"\n\n---\n\n{_footer()}"
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
|
||||
{"agent_id": agent_id, "userid_list": userid,
|
||||
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉工作通知被拒: %s", body)
|
||||
return False
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉工作通知异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
|
||||
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
if not agent_id:
|
||||
return
|
||||
try:
|
||||
at = _dingtalk_topapi_token()
|
||||
if not at:
|
||||
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
|
||||
return
|
||||
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
|
||||
uid = _userid_by_unionid(at, unionid) if unionid else ""
|
||||
if not uid and nickname:
|
||||
uid = _userid_by_name(at, nickname)
|
||||
if uid:
|
||||
_send_work_to(
|
||||
at, agent_id, uid, "账号开通通知",
|
||||
f"**🔹 {nickname or account}‑账号开通**\n\n"
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 初始密码:{password}\n\n"
|
||||
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
|
||||
status="success")
|
||||
else:
|
||||
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
|
||||
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
|
||||
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
|
||||
admin_uid = _userid_by_name(at, admin_name)
|
||||
if admin_uid:
|
||||
_send_work_to(
|
||||
at, agent_id, admin_uid, "新账号待开通权限",
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 姓名:{nickname or '—'}\n\n"
|
||||
f"> 来源:{source}\n\n"
|
||||
"> 备注:请到管理台为该账号开通插件权限",
|
||||
status="warning")
|
||||
else:
|
||||
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉建号通知异常: %s", e)
|
||||
|
||||
|
||||
def notify_account_created(account: str, nickname: str = "", password: str = "",
|
||||
unionid: str = "", source: str = "管理台") -> None:
|
||||
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
|
||||
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
|
||||
def _signed_webhook_url() -> str:
|
||||
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
|
||||
if not url:
|
||||
return ""
|
||||
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
|
||||
if secret:
|
||||
ts = str(int(time.time() * 1000))
|
||||
sign = base64.b64encode(hmac.new(
|
||||
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
|
||||
hashlib.sha256).digest()).decode("utf-8")
|
||||
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
|
||||
return url
|
||||
|
||||
|
||||
def _send_robot(title: str, text: str) -> None:
|
||||
url = _signed_webhook_url()
|
||||
if not url:
|
||||
return
|
||||
try:
|
||||
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉群通知被拒: %s", body)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉群通知异常: %s", e)
|
||||
|
||||
|
||||
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
|
||||
def _admin_names() -> list[str]:
|
||||
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
|
||||
try:
|
||||
from controlplane.core.db import _db
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
|
||||
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
|
||||
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
|
||||
log.warning("取管理员名单失败,离线告警回退群机器人")
|
||||
return []
|
||||
|
||||
|
||||
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
|
||||
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
|
||||
title = "内网文件服务器下线告警"
|
||||
content = (
|
||||
f"> 服务:{hostname or '—'}\n\n"
|
||||
f"> 地址:{host}\n\n"
|
||||
f"> IP:{ip or '—'}\n\n"
|
||||
f"> 最后心跳:{last_seen or '—'}\n\n"
|
||||
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
|
||||
"服务恢复后将自动解除告警")
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
at = _dingtalk_topapi_token() if agent_id else ""
|
||||
sent_any = False
|
||||
if at:
|
||||
for name in _admin_names():
|
||||
if not name:
|
||||
continue
|
||||
uid = _userid_by_name(at, name)
|
||||
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
|
||||
sent_any = True
|
||||
if not sent_any:
|
||||
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
|
||||
if not sent_any:
|
||||
_send_robot(title, content)
|
||||
|
||||
|
||||
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
|
||||
last_seen: str = "") -> None:
|
||||
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
|
||||
threading.Thread(target=_work_fileserver_down,
|
||||
args=(host, hostname, ip, last_seen), daemon=True).start()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
|
||||
|
||||
后台线程发送,失败仅记日志不阻断业务。
|
||||
|
||||
配置项(controlplane/.env):
|
||||
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
|
||||
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
|
||||
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
|
||||
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote_plus
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.dingtalk import _dingtalk_topapi_token
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
|
||||
_SIGN_NAME = "37du 自动化平台"
|
||||
_STATUS_COLORS = {
|
||||
"info": "#0077ff", # 蓝色
|
||||
"success": "#00b300", # 绿色
|
||||
"warning": "#ff9900", # 橙色
|
||||
"error": "#ff0000", # 红色
|
||||
}
|
||||
|
||||
|
||||
def _footer() -> str:
|
||||
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
|
||||
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
req.add_header(k, v)
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
|
||||
def _userid_by_unionid(at: str, unionid: str) -> str:
|
||||
"""unionid → userid(精确,无重名歧义)。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
|
||||
{"unionid": unionid})
|
||||
return ((body.get("result") or {}).get("userid")) or ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _userid_by_name(at: str, name: str) -> str:
|
||||
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://api.dingtalk.com/v1.0/contact/users/search",
|
||||
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
|
||||
headers={"x-acs-dingtalk-access-token": at})
|
||||
lst = body.get("list") or []
|
||||
return str(lst[0]) if lst else ""
|
||||
except Exception as e: # noqa: BLE001 查询失败不阻断业务
|
||||
log.warning("钉钉搜索用户失败(%s):%s", name, e)
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
|
||||
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
|
||||
status: str = "info") -> bool:
|
||||
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
|
||||
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += f"\n\n---\n\n{_footer()}"
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
|
||||
{"agent_id": agent_id, "userid_list": userid,
|
||||
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉工作通知被拒: %s", body)
|
||||
return False
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉工作通知异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
|
||||
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
if not agent_id:
|
||||
return
|
||||
try:
|
||||
at = _dingtalk_topapi_token()
|
||||
if not at:
|
||||
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
|
||||
return
|
||||
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
|
||||
uid = _userid_by_unionid(at, unionid) if unionid else ""
|
||||
if not uid and nickname:
|
||||
uid = _userid_by_name(at, nickname)
|
||||
if uid:
|
||||
_send_work_to(
|
||||
at, agent_id, uid, "账号开通通知",
|
||||
f"**🔹 {nickname or account}‑账号开通**\n\n"
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 初始密码:{password}\n\n"
|
||||
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
|
||||
status="success")
|
||||
else:
|
||||
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
|
||||
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
|
||||
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
|
||||
admin_uid = _userid_by_name(at, admin_name)
|
||||
if admin_uid:
|
||||
_send_work_to(
|
||||
at, agent_id, admin_uid, "新账号待开通权限",
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 姓名:{nickname or '—'}\n\n"
|
||||
f"> 来源:{source}\n\n"
|
||||
"> 备注:请到管理台为该账号开通插件权限",
|
||||
status="warning")
|
||||
else:
|
||||
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉建号通知异常: %s", e)
|
||||
|
||||
|
||||
def notify_account_created(account: str, nickname: str = "", password: str = "",
|
||||
unionid: str = "", source: str = "管理台") -> None:
|
||||
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
|
||||
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
|
||||
def _signed_webhook_url() -> str:
|
||||
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
|
||||
if not url:
|
||||
return ""
|
||||
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
|
||||
if secret:
|
||||
ts = str(int(time.time() * 1000))
|
||||
sign = base64.b64encode(hmac.new(
|
||||
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
|
||||
hashlib.sha256).digest()).decode("utf-8")
|
||||
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
|
||||
return url
|
||||
|
||||
|
||||
def _send_robot(title: str, text: str) -> None:
|
||||
url = _signed_webhook_url()
|
||||
if not url:
|
||||
return
|
||||
try:
|
||||
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉群通知被拒: %s", body)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉群通知异常: %s", e)
|
||||
|
||||
|
||||
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
|
||||
def _admin_names() -> list[str]:
|
||||
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
|
||||
try:
|
||||
from controlplane.core.db import _db
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
|
||||
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
|
||||
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
|
||||
log.warning("取管理员名单失败,离线告警回退群机器人")
|
||||
return []
|
||||
|
||||
|
||||
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
|
||||
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
|
||||
title = "内网文件服务器下线告警"
|
||||
content = (
|
||||
f"> 服务:{hostname or '—'}\n\n"
|
||||
f"> 地址:{host}\n\n"
|
||||
f"> IP:{ip or '—'}\n\n"
|
||||
f"> 最后心跳:{last_seen or '—'}\n\n"
|
||||
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
|
||||
"服务恢复后将自动解除告警")
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
at = _dingtalk_topapi_token() if agent_id else ""
|
||||
sent_any = False
|
||||
if at:
|
||||
for name in _admin_names():
|
||||
if not name:
|
||||
continue
|
||||
uid = _userid_by_name(at, name)
|
||||
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
|
||||
sent_any = True
|
||||
if not sent_any:
|
||||
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
|
||||
if not sent_any:
|
||||
_send_robot(title, content)
|
||||
|
||||
|
||||
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
|
||||
last_seen: str = "") -> None:
|
||||
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
|
||||
threading.Thread(target=_work_fileserver_down,
|
||||
args=(host, hostname, ip, last_seen), daemon=True).start()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"filename": "setup-37du-host-1.0.0.exe",
|
||||
"sha256": "57ee9cb4d10b25914276a277bfe42b0751f4c26c3c408af1293f723c7b4488a0",
|
||||
"notes": "初始版本"
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"filename": "setup-37du-host-1.0.0.exe",
|
||||
"sha256": "57ee9cb4d10b25914276a277bfe42b0751f4c26c3c408af1293f723c7b4488a0",
|
||||
"notes": "初始版本"
|
||||
}
|
||||
@@ -1,487 +1,487 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。
|
||||
|
||||
用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可:
|
||||
- 发布 / 删除插件包(按最近 3 版自动裁剪保留)
|
||||
- 变更插件状态(published / disabled / revoked)与强制更新阈值
|
||||
- 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号
|
||||
- 按账号授予 / 撤销插件与平台权限
|
||||
- 发布执行机壳子(主程序)新版安装包(shell-release,上传到中心机 shell 源)
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
运行(项目 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
python -m controlplane.tools.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.tools.agent_cli plugins
|
||||
python -m controlplane.tools.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.tools.agent_cli users
|
||||
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k, v = _k.strip(), _v.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 内网文件服务器:上传直链来源(复用 controlplane/.env 新增键)
|
||||
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _mint_admin_token(account: str, secret: str) -> str:
|
||||
"""临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.token:
|
||||
h["X-Admin-Token"] = self.token
|
||||
elif self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
return h
|
||||
|
||||
def call(self, method: str, path: str, json_body: Optional[dict] = None,
|
||||
_hdrs_json: Optional[bool] = None) -> dict:
|
||||
import requests
|
||||
url = self.base + path # path 已是完整路径(含 query)
|
||||
try:
|
||||
if json_body is not None:
|
||||
r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30)
|
||||
else:
|
||||
r = requests.request(method, url, headers=self._headers(False), timeout=30)
|
||||
except requests.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。")
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
if isinstance(detail, dict):
|
||||
detail = detail.get("msg") or detail
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}")
|
||||
return data if isinstance(data, dict) else {"result": data}
|
||||
|
||||
def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict:
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/pkg?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||
timeout=60)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"version": version, "notes": notes, "sha256": sha256})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/shell-release?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
|
||||
# ------------------------------ 输出辅助 ------------------------------
|
||||
def _plugin_rows(plugins) -> None:
|
||||
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||
rows = plugins if isinstance(plugins, list) else \
|
||||
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||
if not rows:
|
||||
print("(暂无插件)")
|
||||
return
|
||||
print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数")
|
||||
for p in rows:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}"
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
import requests as _rq
|
||||
except ModuleNotFoundError:
|
||||
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||
fcmd = args.file_cmd
|
||||
|
||||
if fcmd == "push":
|
||||
path = Path(args.path)
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||
if not FILESERVER_BASE_URL or not FILESERVER_TOKEN:
|
||||
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN")
|
||||
# 第一步:传到文件服务器
|
||||
try:
|
||||
with open(path, "rb") as fp:
|
||||
r = _rq.post(f"{FILESERVER_BASE_URL}/api/upload",
|
||||
headers={"X-API-Token": FILESERVER_TOKEN},
|
||||
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
except _rq.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接内网文件服务器 {FILESERVER_BASE_URL}({exc})")
|
||||
if r.status_code >= 400:
|
||||
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||
up = r.json()
|
||||
url = up.get("url", "")
|
||||
if not url:
|
||||
raise SystemExit("[x] 文件服务器未返回 url")
|
||||
sha256 = args.sha256 or up.get("sha256", "")
|
||||
# 第二步:登记到中心机 file_sources
|
||||
body = {"category": args.category, "version": args.version,
|
||||
"filename": up.get("filename", path.name), "url": url,
|
||||
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||
print(f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}")
|
||||
print(f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||
return 0
|
||||
|
||||
if fcmd == "list":
|
||||
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||
files = data.get("files", [])
|
||||
if not files:
|
||||
print("(暂无大文件源)")
|
||||
return 0
|
||||
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||
for f in files:
|
||||
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||
f"{f.get('filename') or ''}")
|
||||
print(f" {f.get('url') or ''}")
|
||||
return 0
|
||||
|
||||
if fcmd == "rm":
|
||||
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||
print(f"[ok] 已删除登记 id={args.id}")
|
||||
return 0
|
||||
|
||||
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="agent_cli",
|
||||
description="37du 中心机 · agent 插件发布与管理 CLI",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||
dest="admin_password",
|
||||
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)")
|
||||
p_pub.add_argument("pkg", help="插件 zip 路径")
|
||||
p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)")
|
||||
p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)")
|
||||
p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0")
|
||||
|
||||
sub.add_parser("plugins", help="列出插件清单")
|
||||
|
||||
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||
p_del.add_argument("plugin_id")
|
||||
|
||||
p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值")
|
||||
p_status.add_argument("plugin_id")
|
||||
p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="",
|
||||
help="新状态(留空不改变)")
|
||||
p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)")
|
||||
p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)")
|
||||
p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置")
|
||||
|
||||
sub.add_parser("users", help="列出账号清单")
|
||||
|
||||
p_user = sub.add_parser("user-add", help="新建账号")
|
||||
p_user.add_argument("account")
|
||||
p_user.add_argument("--password", required=True)
|
||||
p_user.add_argument("--dept", default="")
|
||||
p_user.add_argument("--nickname", default="")
|
||||
p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员")
|
||||
|
||||
p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)")
|
||||
p_upd.add_argument("account")
|
||||
p_upd.add_argument("--dept", default=None)
|
||||
p_upd.add_argument("--nickname", default=None)
|
||||
p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"),
|
||||
default=None)
|
||||
|
||||
p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码")
|
||||
p_rp.add_argument("account")
|
||||
p_rp.add_argument("--password", required=True)
|
||||
|
||||
p_del_u = sub.add_parser("user-del", help="删除账号")
|
||||
p_del_u.add_argument("account")
|
||||
|
||||
p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)")
|
||||
p_grant.add_argument("account")
|
||||
p_grant.add_argument("plugin_id")
|
||||
p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限")
|
||||
p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限")
|
||||
|
||||
p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限")
|
||||
p_revoke.add_argument("account")
|
||||
p_revoke.add_argument("plugin_id")
|
||||
|
||||
p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限")
|
||||
p_gp.add_argument("account")
|
||||
p_gp.add_argument("platform_id")
|
||||
|
||||
p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限")
|
||||
p_rp_plt.add_argument("account")
|
||||
p_rp_plt.add_argument("platform_id")
|
||||
|
||||
sub.add_parser("stats", help="运行统计看板")
|
||||
|
||||
sub.add_parser("me", help="校验当前管理身份")
|
||||
|
||||
p_shell = sub.add_parser("shell-release", help="发布执行机壳子新版安装包(更新 shell 源 + version.json)")
|
||||
p_shell.add_argument("pkg", help="新安装包路径(setup-37du-host-<v>.exe)")
|
||||
p_shell.add_argument("--version", required=True, help="壳子版本号(须高于执行机本地 shell.version)")
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||
p_fpush.add_argument("path", help="本地文件路径")
|
||||
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||
p_frm = file_sub.add_parser("rm", help="删除中心机登记(不动内网服务器文件)")
|
||||
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
if args.admin_password.strip():
|
||||
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||
r = c.call("POST", "/api/admin/auth",
|
||||
{"account": args.admin, "password": args.admin_password})
|
||||
if not r.get("token"):
|
||||
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||
if not r.get("is_admin"):
|
||||
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||
c.token = str(r["token"])
|
||||
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||
else:
|
||||
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
r = c.shell_release(args.pkg, args.version, args.notes, args.sha256)
|
||||
print(f"[ok] 已发布壳子 v{r.get('version')} → {r.get('filename')}")
|
||||
print(f" sha256={str(r.get('sha256') or '')[:16]}… notes={args.notes or '(无)'}")
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "file":
|
||||
return _run_file(args, c)
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
elif cmd == "plugins":
|
||||
data = c.call("GET", "/api/admin/overview")
|
||||
_plugin_rows(data.get("plugins", {}))
|
||||
|
||||
elif cmd == "plugin-del":
|
||||
r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id})
|
||||
print(f"[ok] 已删除插件 {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "plugin-status":
|
||||
import urllib.parse as _q
|
||||
body = {}
|
||||
if args.status:
|
||||
body["status"] = args.status
|
||||
if args.force_min_version and args.force_deadline:
|
||||
body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline})
|
||||
elif args.clear_force:
|
||||
body["clear_force"] = True
|
||||
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||
print("[ok]", json.dumps(r, ensure_ascii=False))
|
||||
|
||||
elif cmd == "users":
|
||||
data = c.call("GET", "/api/admin/accounts")
|
||||
accounts = data.get("accounts", "")
|
||||
if isinstance(accounts, dict):
|
||||
accounts = list(accounts.values())
|
||||
accounts = [a for a in (accounts or []) if isinstance(a, dict)]
|
||||
if not accounts:
|
||||
print("(暂无账号)")
|
||||
return 0
|
||||
print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}")
|
||||
for a in accounts:
|
||||
print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}"
|
||||
f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}")
|
||||
|
||||
elif cmd == "user-add":
|
||||
r = c.call("POST", "/api/admin/account", {
|
||||
"account": args.account, "password": args.password,
|
||||
"dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag})
|
||||
print(f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else ""))
|
||||
|
||||
elif cmd == "user-update":
|
||||
body = {"account": args.account}
|
||||
for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)):
|
||||
if v is not None:
|
||||
body[k] = v
|
||||
r = c.call("POST", "/api/admin/account/update", body)
|
||||
print(f"[ok] 已更新 {r.get('account')}")
|
||||
|
||||
elif cmd == "user-reset-pwd":
|
||||
r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password})
|
||||
print(f"[ok] 已重置 {r.get('account')} 密码")
|
||||
|
||||
elif cmd == "user-del":
|
||||
r = c.call("POST", "/api/admin/account/delete", {"account": args.account})
|
||||
print(f"[ok] 已删除账号 {r.get('account')}")
|
||||
|
||||
elif cmd == "grant":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": True,
|
||||
"can_download": not args.no_download, "can_run": not args.no_run})
|
||||
print(f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}"
|
||||
f"/run={'y' if not args.no_run else 'n'})")
|
||||
|
||||
elif cmd == "revoke":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "grant-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": True})
|
||||
print(f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "revoke-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "stats":
|
||||
print(json.dumps(c.call("GET", "/api/admin/stats"), ensure_ascii=False, indent=2))
|
||||
|
||||
elif cmd == "me":
|
||||
data = c.call("GET", "/api/admin/me")
|
||||
print(f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} "
|
||||
f"部门:{data.get('dept') or ''}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = _build_parser().parse_args()
|
||||
try:
|
||||
_run(args)
|
||||
except SystemExit as exc:
|
||||
if exc.code:
|
||||
print(str(exc.code))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。
|
||||
|
||||
用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可:
|
||||
- 发布 / 删除插件包(按最近 3 版自动裁剪保留)
|
||||
- 变更插件状态(published / disabled / revoked)与强制更新阈值
|
||||
- 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号
|
||||
- 按账号授予 / 撤销插件与平台权限
|
||||
- 发布执行机壳子(主程序)新版安装包(shell-release,上传到中心机 shell 源)
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
运行(项目 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
python -m controlplane.tools.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.tools.agent_cli plugins
|
||||
python -m controlplane.tools.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.tools.agent_cli users
|
||||
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k, v = _k.strip(), _v.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 内网文件服务器:上传直链来源(复用 controlplane/.env 新增键)
|
||||
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _mint_admin_token(account: str, secret: str) -> str:
|
||||
"""临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.token:
|
||||
h["X-Admin-Token"] = self.token
|
||||
elif self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
return h
|
||||
|
||||
def call(self, method: str, path: str, json_body: Optional[dict] = None,
|
||||
_hdrs_json: Optional[bool] = None) -> dict:
|
||||
import requests
|
||||
url = self.base + path # path 已是完整路径(含 query)
|
||||
try:
|
||||
if json_body is not None:
|
||||
r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30)
|
||||
else:
|
||||
r = requests.request(method, url, headers=self._headers(False), timeout=30)
|
||||
except requests.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。")
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
if isinstance(detail, dict):
|
||||
detail = detail.get("msg") or detail
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}")
|
||||
return data if isinstance(data, dict) else {"result": data}
|
||||
|
||||
def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict:
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/pkg?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||
timeout=60)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"version": version, "notes": notes, "sha256": sha256})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/shell-release?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
|
||||
# ------------------------------ 输出辅助 ------------------------------
|
||||
def _plugin_rows(plugins) -> None:
|
||||
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||
rows = plugins if isinstance(plugins, list) else \
|
||||
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||
if not rows:
|
||||
print("(暂无插件)")
|
||||
return
|
||||
print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数")
|
||||
for p in rows:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}"
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
import requests as _rq
|
||||
except ModuleNotFoundError:
|
||||
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||
fcmd = args.file_cmd
|
||||
|
||||
if fcmd == "push":
|
||||
path = Path(args.path)
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||
if not FILESERVER_BASE_URL or not FILESERVER_TOKEN:
|
||||
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN")
|
||||
# 第一步:传到文件服务器
|
||||
try:
|
||||
with open(path, "rb") as fp:
|
||||
r = _rq.post(f"{FILESERVER_BASE_URL}/api/upload",
|
||||
headers={"X-API-Token": FILESERVER_TOKEN},
|
||||
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
except _rq.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接内网文件服务器 {FILESERVER_BASE_URL}({exc})")
|
||||
if r.status_code >= 400:
|
||||
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||
up = r.json()
|
||||
url = up.get("url", "")
|
||||
if not url:
|
||||
raise SystemExit("[x] 文件服务器未返回 url")
|
||||
sha256 = args.sha256 or up.get("sha256", "")
|
||||
# 第二步:登记到中心机 file_sources
|
||||
body = {"category": args.category, "version": args.version,
|
||||
"filename": up.get("filename", path.name), "url": url,
|
||||
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||
print(f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}")
|
||||
print(f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||
return 0
|
||||
|
||||
if fcmd == "list":
|
||||
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||
files = data.get("files", [])
|
||||
if not files:
|
||||
print("(暂无大文件源)")
|
||||
return 0
|
||||
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||
for f in files:
|
||||
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||
f"{f.get('filename') or ''}")
|
||||
print(f" {f.get('url') or ''}")
|
||||
return 0
|
||||
|
||||
if fcmd == "rm":
|
||||
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||
print(f"[ok] 已删除登记 id={args.id}")
|
||||
return 0
|
||||
|
||||
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="agent_cli",
|
||||
description="37du 中心机 · agent 插件发布与管理 CLI",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||
dest="admin_password",
|
||||
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)")
|
||||
p_pub.add_argument("pkg", help="插件 zip 路径")
|
||||
p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)")
|
||||
p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)")
|
||||
p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0")
|
||||
|
||||
sub.add_parser("plugins", help="列出插件清单")
|
||||
|
||||
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||
p_del.add_argument("plugin_id")
|
||||
|
||||
p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值")
|
||||
p_status.add_argument("plugin_id")
|
||||
p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="",
|
||||
help="新状态(留空不改变)")
|
||||
p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)")
|
||||
p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)")
|
||||
p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置")
|
||||
|
||||
sub.add_parser("users", help="列出账号清单")
|
||||
|
||||
p_user = sub.add_parser("user-add", help="新建账号")
|
||||
p_user.add_argument("account")
|
||||
p_user.add_argument("--password", required=True)
|
||||
p_user.add_argument("--dept", default="")
|
||||
p_user.add_argument("--nickname", default="")
|
||||
p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员")
|
||||
|
||||
p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)")
|
||||
p_upd.add_argument("account")
|
||||
p_upd.add_argument("--dept", default=None)
|
||||
p_upd.add_argument("--nickname", default=None)
|
||||
p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"),
|
||||
default=None)
|
||||
|
||||
p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码")
|
||||
p_rp.add_argument("account")
|
||||
p_rp.add_argument("--password", required=True)
|
||||
|
||||
p_del_u = sub.add_parser("user-del", help="删除账号")
|
||||
p_del_u.add_argument("account")
|
||||
|
||||
p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)")
|
||||
p_grant.add_argument("account")
|
||||
p_grant.add_argument("plugin_id")
|
||||
p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限")
|
||||
p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限")
|
||||
|
||||
p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限")
|
||||
p_revoke.add_argument("account")
|
||||
p_revoke.add_argument("plugin_id")
|
||||
|
||||
p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限")
|
||||
p_gp.add_argument("account")
|
||||
p_gp.add_argument("platform_id")
|
||||
|
||||
p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限")
|
||||
p_rp_plt.add_argument("account")
|
||||
p_rp_plt.add_argument("platform_id")
|
||||
|
||||
sub.add_parser("stats", help="运行统计看板")
|
||||
|
||||
sub.add_parser("me", help="校验当前管理身份")
|
||||
|
||||
p_shell = sub.add_parser("shell-release", help="发布执行机壳子新版安装包(更新 shell 源 + version.json)")
|
||||
p_shell.add_argument("pkg", help="新安装包路径(setup-37du-host-<v>.exe)")
|
||||
p_shell.add_argument("--version", required=True, help="壳子版本号(须高于执行机本地 shell.version)")
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||
p_fpush.add_argument("path", help="本地文件路径")
|
||||
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||
p_frm = file_sub.add_parser("rm", help="删除中心机登记(不动内网服务器文件)")
|
||||
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
if args.admin_password.strip():
|
||||
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||
r = c.call("POST", "/api/admin/auth",
|
||||
{"account": args.admin, "password": args.admin_password})
|
||||
if not r.get("token"):
|
||||
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||
if not r.get("is_admin"):
|
||||
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||
c.token = str(r["token"])
|
||||
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||
else:
|
||||
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
r = c.shell_release(args.pkg, args.version, args.notes, args.sha256)
|
||||
print(f"[ok] 已发布壳子 v{r.get('version')} → {r.get('filename')}")
|
||||
print(f" sha256={str(r.get('sha256') or '')[:16]}… notes={args.notes or '(无)'}")
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "file":
|
||||
return _run_file(args, c)
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
elif cmd == "plugins":
|
||||
data = c.call("GET", "/api/admin/overview")
|
||||
_plugin_rows(data.get("plugins", {}))
|
||||
|
||||
elif cmd == "plugin-del":
|
||||
r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id})
|
||||
print(f"[ok] 已删除插件 {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "plugin-status":
|
||||
import urllib.parse as _q
|
||||
body = {}
|
||||
if args.status:
|
||||
body["status"] = args.status
|
||||
if args.force_min_version and args.force_deadline:
|
||||
body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline})
|
||||
elif args.clear_force:
|
||||
body["clear_force"] = True
|
||||
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||
print("[ok]", json.dumps(r, ensure_ascii=False))
|
||||
|
||||
elif cmd == "users":
|
||||
data = c.call("GET", "/api/admin/accounts")
|
||||
accounts = data.get("accounts", "")
|
||||
if isinstance(accounts, dict):
|
||||
accounts = list(accounts.values())
|
||||
accounts = [a for a in (accounts or []) if isinstance(a, dict)]
|
||||
if not accounts:
|
||||
print("(暂无账号)")
|
||||
return 0
|
||||
print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}")
|
||||
for a in accounts:
|
||||
print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}"
|
||||
f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}")
|
||||
|
||||
elif cmd == "user-add":
|
||||
r = c.call("POST", "/api/admin/account", {
|
||||
"account": args.account, "password": args.password,
|
||||
"dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag})
|
||||
print(f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else ""))
|
||||
|
||||
elif cmd == "user-update":
|
||||
body = {"account": args.account}
|
||||
for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)):
|
||||
if v is not None:
|
||||
body[k] = v
|
||||
r = c.call("POST", "/api/admin/account/update", body)
|
||||
print(f"[ok] 已更新 {r.get('account')}")
|
||||
|
||||
elif cmd == "user-reset-pwd":
|
||||
r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password})
|
||||
print(f"[ok] 已重置 {r.get('account')} 密码")
|
||||
|
||||
elif cmd == "user-del":
|
||||
r = c.call("POST", "/api/admin/account/delete", {"account": args.account})
|
||||
print(f"[ok] 已删除账号 {r.get('account')}")
|
||||
|
||||
elif cmd == "grant":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": True,
|
||||
"can_download": not args.no_download, "can_run": not args.no_run})
|
||||
print(f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}"
|
||||
f"/run={'y' if not args.no_run else 'n'})")
|
||||
|
||||
elif cmd == "revoke":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "grant-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": True})
|
||||
print(f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "revoke-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "stats":
|
||||
print(json.dumps(c.call("GET", "/api/admin/stats"), ensure_ascii=False, indent=2))
|
||||
|
||||
elif cmd == "me":
|
||||
data = c.call("GET", "/api/admin/me")
|
||||
print(f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} "
|
||||
f"部门:{data.get('dept') or ''}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = _build_parser().parse_args()
|
||||
try:
|
||||
_run(args)
|
||||
except SystemExit as exc:
|
||||
if exc.code:
|
||||
print(str(exc.code))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,279 +1,279 @@
|
||||
-- ============================================================
|
||||
-- 37du 自动化平台 · 中心机控制面 表结构(MySQL 5.7+)
|
||||
-- 引擎:InnoDB / 字符集:utf8mb4 / 排序:utf8mb4_unicode_ci
|
||||
-- 执行:mysql -h<host> -u<user> -p < schema_mysql.sql
|
||||
-- 幂等:全部 CREATE TABLE IF NOT EXISTS,可重复执行
|
||||
-- ============================================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS 37du_center
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE 37du_center;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 迁移版本记录:db.py 启动幂等建表时登记,替代旧 _ensure_col 渐进补列
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 统一账号
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件元数据
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件版本:每插件仅保留最近 N 版,旧版由应用层裁剪
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-插件授权:含下载/运行权限位(合并原 plugin_grants)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-平台白名单:账号可登录的平台
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 审计日志:下载/授权/管控/发布等关键操作留痕
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 运行上报:执行机运行记录(启动/完成/失败/离线补报)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机设备:环境/心跳上报(配合执行机 Chrome 检测)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Chrome 安装包下载源配置:外链 URL,中心机不存包
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 系统级键值配置:全局配置沉淀(如环境依赖项)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 云端会话令牌:落库共享(gunicorn 多 worker 下 Bearer 身份解析通用)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (token),
|
||||
KEY idx_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 一次性插件下载票据:落库共享,多 worker 通用(进程内存版在 4 worker 下 3/4 概率查不到票据)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (nonce),
|
||||
KEY idx_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 壳子定时任务配置备份:执行机变更后全量推送,仅存数据防丢失(不做管理界面)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schedule_backups (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',
|
||||
data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 内网文件服务器状态:心跳上报 + 离线监控(超时判离线并钉钉告警)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS fileserver_status (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
|
||||
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
|
||||
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
|
||||
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
|
||||
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
|
||||
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
|
||||
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
|
||||
offline_notified TINYINT(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_host (host),
|
||||
KEY idx_status (status),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)';
|
||||
-- ============================================================
|
||||
-- 37du 自动化平台 · 中心机控制面 表结构(MySQL 5.7+)
|
||||
-- 引擎:InnoDB / 字符集:utf8mb4 / 排序:utf8mb4_unicode_ci
|
||||
-- 执行:mysql -h<host> -u<user> -p < schema_mysql.sql
|
||||
-- 幂等:全部 CREATE TABLE IF NOT EXISTS,可重复执行
|
||||
-- ============================================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS 37du_center
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE 37du_center;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 迁移版本记录:db.py 启动幂等建表时登记,替代旧 _ensure_col 渐进补列
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 统一账号
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件元数据
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件版本:每插件仅保留最近 N 版,旧版由应用层裁剪
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-插件授权:含下载/运行权限位(合并原 plugin_grants)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-平台白名单:账号可登录的平台
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 审计日志:下载/授权/管控/发布等关键操作留痕
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 运行上报:执行机运行记录(启动/完成/失败/离线补报)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机设备:环境/心跳上报(配合执行机 Chrome 检测)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Chrome 安装包下载源配置:外链 URL,中心机不存包
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 系统级键值配置:全局配置沉淀(如环境依赖项)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 云端会话令牌:落库共享(gunicorn 多 worker 下 Bearer 身份解析通用)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (token),
|
||||
KEY idx_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 一次性插件下载票据:落库共享,多 worker 通用(进程内存版在 4 worker 下 3/4 概率查不到票据)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (nonce),
|
||||
KEY idx_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 壳子定时任务配置备份:执行机变更后全量推送,仅存数据防丢失(不做管理界面)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schedule_backups (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',
|
||||
data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 内网文件服务器状态:心跳上报 + 离线监控(超时判离线并钉钉告警)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS fileserver_status (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
|
||||
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
|
||||
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
|
||||
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
|
||||
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
|
||||
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
|
||||
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
|
||||
offline_notified TINYINT(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_host (host),
|
||||
KEY idx_status (status),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)';
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,128 +1,128 @@
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named org - imported by pickle (optional)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
|
||||
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
|
||||
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
|
||||
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
|
||||
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
|
||||
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
|
||||
missing module named 'rich.table' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.syntax' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.progress' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.markup' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.console' - imported by httpx._main (top-level)
|
||||
missing module named 'pygments.util' - imported by httpx._main (top-level)
|
||||
missing module named pygments - imported by httpx._main (top-level)
|
||||
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
|
||||
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
|
||||
missing module named zstandard - imported by httpx._decoders (optional)
|
||||
missing module named brotlicffi - imported by httpx._decoders (optional)
|
||||
missing module named brotli - imported by httpx._decoders (optional)
|
||||
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
|
||||
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
|
||||
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
|
||||
missing module named readline - imported by websockets.cli (delayed, optional)
|
||||
missing module named werkzeug - imported by websockets.asyncio.router (optional)
|
||||
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
|
||||
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
|
||||
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
|
||||
missing module named IPython - imported by dotenv.ipython (top-level)
|
||||
excluded module named win32con - imported by win32evtlogutil (top-level)
|
||||
excluded module named win32api - imported by win32evtlogutil (top-level)
|
||||
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
|
||||
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
|
||||
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
|
||||
missing module named outcome - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
|
||||
missing module named cython - imported by pydantic.v1.version (optional)
|
||||
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
|
||||
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
|
||||
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
|
||||
missing module named mypy - imported by pydantic.mypy (top-level)
|
||||
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
|
||||
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
|
||||
missing module named rich - imported by pydantic._internal._core_utils (conditional)
|
||||
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
|
||||
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
|
||||
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
|
||||
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
|
||||
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
|
||||
missing module named gunicorn - imported by uvicorn.workers (top-level)
|
||||
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named org - imported by pickle (optional)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
|
||||
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
|
||||
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
|
||||
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
|
||||
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
|
||||
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
|
||||
missing module named 'rich.table' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.syntax' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.progress' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.markup' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.console' - imported by httpx._main (top-level)
|
||||
missing module named 'pygments.util' - imported by httpx._main (top-level)
|
||||
missing module named pygments - imported by httpx._main (top-level)
|
||||
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
|
||||
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
|
||||
missing module named zstandard - imported by httpx._decoders (optional)
|
||||
missing module named brotlicffi - imported by httpx._decoders (optional)
|
||||
missing module named brotli - imported by httpx._decoders (optional)
|
||||
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
|
||||
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
|
||||
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
|
||||
missing module named readline - imported by websockets.cli (delayed, optional)
|
||||
missing module named werkzeug - imported by websockets.asyncio.router (optional)
|
||||
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
|
||||
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
|
||||
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
|
||||
missing module named IPython - imported by dotenv.ipython (top-level)
|
||||
excluded module named win32con - imported by win32evtlogutil (top-level)
|
||||
excluded module named win32api - imported by win32evtlogutil (top-level)
|
||||
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
|
||||
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
|
||||
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
|
||||
missing module named outcome - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
|
||||
missing module named cython - imported by pydantic.v1.version (optional)
|
||||
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
|
||||
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
|
||||
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
|
||||
missing module named mypy - imported by pydantic.mypy (top-level)
|
||||
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
|
||||
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
|
||||
missing module named rich - imported by pydantic._internal._core_utils (conditional)
|
||||
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
|
||||
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
|
||||
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
|
||||
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
|
||||
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
|
||||
missing module named gunicorn - imported by uvicorn.workers (top-level)
|
||||
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,68 +1,68 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录。
|
||||
|
||||
- 源码运行:fileserver/core/config.py → fileserver/
|
||||
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
||||
"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
||||
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
|
||||
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
|
||||
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 心跳上报间隔(秒)
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# load_dotenv 后再取一次,保证 .env 值生效
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def default_token() -> str:
|
||||
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录。
|
||||
|
||||
- 源码运行:fileserver/core/config.py → fileserver/
|
||||
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
||||
"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
||||
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
|
||||
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
|
||||
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 心跳上报间隔(秒)
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# load_dotenv 后再取一次,保证 .env 值生效
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def default_token() -> str:
|
||||
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
||||
return TOKEN or secrets.token_urlsafe(24)
|
||||
Binary file not shown.
@@ -1,3 +1,3 @@
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
python-multipart>=0.0.9
|
||||
@@ -1,128 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
|
||||
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
|
||||
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
|
||||
_COOKIE_DEFS = {
|
||||
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
|
||||
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
|
||||
}
|
||||
|
||||
# 登录模块(desktop/shared 真源)
|
||||
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
|
||||
|
||||
|
||||
class PlatformAuthError(Exception):
|
||||
"""平台不存在 / 登录态不可用等宿主层错误。"""
|
||||
|
||||
|
||||
def platforms() -> list:
|
||||
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
|
||||
|
||||
|
||||
def is_online(pid: str) -> bool:
|
||||
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
|
||||
if pid == "hr":
|
||||
return _hr._is_hr_session_valid()
|
||||
if pid == "oa":
|
||||
return _oa._is_oa_session_valid()
|
||||
return False
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
if pid not in _LOGIN_MODS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
result = _LOGIN_MODS[pid].ensure_login(force=False)
|
||||
ok = bool(result and result.get("success"))
|
||||
return {"id": pid, "label": _LABELS[pid], "online": ok,
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def logout(pid: str) -> dict:
|
||||
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
|
||||
|
||||
返回 {id, label, online}
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
return {"id": pid, "label": _LABELS[pid], "online": False}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
若登录态缺失则抛 PlatformAuthError,提示先登录。
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if not os.path.exists(path):
|
||||
raise PlatformAuthError(
|
||||
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
if not cookies:
|
||||
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
|
||||
|
||||
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",
|
||||
})
|
||||
domain = _COOKIE_DEFS[pid]["domain"]
|
||||
injected: set = set()
|
||||
for c in cookies:
|
||||
if c.get("domain") and domain in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
injected.add(c["name"])
|
||||
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
|
||||
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
|
||||
for c in cookies:
|
||||
name = c.get("name")
|
||||
if name and name not in injected:
|
||||
session.cookies.set(name, c.get("value", ""),
|
||||
domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def get_user_id(pid: str) -> str:
|
||||
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if pid == "hr":
|
||||
session = build_session("hr")
|
||||
info = _seal.fetch_cur_user_info(session)
|
||||
return str(info.get("userId") or "")
|
||||
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
|
||||
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
|
||||
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容旧逻辑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
|
||||
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
|
||||
_COOKIE_DEFS = {
|
||||
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
|
||||
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
|
||||
}
|
||||
|
||||
# 登录模块(desktop/shared 真源)
|
||||
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
|
||||
|
||||
|
||||
class PlatformAuthError(Exception):
|
||||
"""平台不存在 / 登录态不可用等宿主层错误。"""
|
||||
|
||||
|
||||
def platforms() -> list:
|
||||
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
|
||||
|
||||
|
||||
def is_online(pid: str) -> bool:
|
||||
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
|
||||
if pid == "hr":
|
||||
return _hr._is_hr_session_valid()
|
||||
if pid == "oa":
|
||||
return _oa._is_oa_session_valid()
|
||||
return False
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
if pid not in _LOGIN_MODS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
result = _LOGIN_MODS[pid].ensure_login(force=False)
|
||||
ok = bool(result and result.get("success"))
|
||||
return {"id": pid, "label": _LABELS[pid], "online": ok,
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def logout(pid: str) -> dict:
|
||||
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
|
||||
|
||||
返回 {id, label, online}
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
return {"id": pid, "label": _LABELS[pid], "online": False}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
若登录态缺失则抛 PlatformAuthError,提示先登录。
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if not os.path.exists(path):
|
||||
raise PlatformAuthError(
|
||||
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
if not cookies:
|
||||
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
|
||||
|
||||
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",
|
||||
})
|
||||
domain = _COOKIE_DEFS[pid]["domain"]
|
||||
injected: set = set()
|
||||
for c in cookies:
|
||||
if c.get("domain") and domain in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
injected.add(c["name"])
|
||||
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
|
||||
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
|
||||
for c in cookies:
|
||||
name = c.get("name")
|
||||
if name and name not in injected:
|
||||
session.cookies.set(name, c.get("value", ""),
|
||||
domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def get_user_id(pid: str) -> str:
|
||||
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if pid == "hr":
|
||||
session = build_session("hr")
|
||||
info = _seal.fetch_cur_user_info(session)
|
||||
return str(info.get("userId") or "")
|
||||
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
|
||||
|
||||
@@ -1,323 +1,323 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
_LOGGER.warning("等待 Chrome 安装完成超时")
|
||||
@@ -0,0 +1,128 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""环境包版插件执行守护:Job Object 托管 + 内存上限 + 超时强杀。
|
||||
|
||||
Node 壳(electron-shell runner.js)在**便携环境包**模式下不再直接 spawn
|
||||
plugin_runner,而是经由本守护拉起,以获得旧 Python 底座同等的进程托管能力:
|
||||
|
||||
python job_guard.py [--mem <MB>] [--timeout <秒>] -- <python> -u <plugin_runner.py> [args...]
|
||||
|
||||
- Job Object(KILL_ON_JOB_CLOSE + PROCESS_MEMORY_LIMIT,复用 winjob.py)
|
||||
→ 插件及其拉起的浏览器孙进程整体托管,内存超限/超时/宿主退出即整树终止;
|
||||
- stdin/stdout/stderr 三通道逐字节透传(plugin_runner 协议不经过本进程改写,
|
||||
与 Node 直接 spawn 时逐字节一致:fields 单行 JSON → 事件行/诊断行);
|
||||
- 退出码 = 子进程退出码(透传),Node 侧结论判定逻辑不变;
|
||||
- 非 Windows 平台安全降级为直接 spawn 子进程(winjob 内部 no-op)。
|
||||
|
||||
本文件同时进入环境包运行时子集(webhost/backend/core/job_guard.py),
|
||||
不依赖任何第三方包(ctypes 标准库实现)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from webhost.backend.core import winjob # 环境包/仓库内相对解析
|
||||
except Exception: # noqa: BLE001 兜底:直接同目录导入
|
||||
import winjob
|
||||
|
||||
|
||||
def _forward(src, dst, name: str) -> None:
|
||||
"""把 src 的字节流逐块转发到 dst;EOF 后 flush 并结束。"""
|
||||
try:
|
||||
while True:
|
||||
chunk = src.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
dst.write(chunk)
|
||||
dst.flush()
|
||||
except Exception: # noqa: BLE001 通道关闭即结束
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
dst.flush()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description="37du 插件执行守护(Job Object 托管)")
|
||||
parser.add_argument("--mem", type=int, default=0, help="作业级内存上限(MB),0=不限")
|
||||
parser.add_argument("--timeout", type=int, default=0, help="超时秒数,0=不限(Node 侧仍有兜底强杀)")
|
||||
parser.add_argument("child", nargs=argparse.REMAINDER, help="-- 之后为真实子进程命令")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if not args.child or args.child[0] != "--":
|
||||
print("用法:python job_guard.py [--mem MB] [--timeout 秒] -- <cmd...>", file=sys.stderr)
|
||||
return 2
|
||||
child_cmd = args.child[1:]
|
||||
if not child_cmd:
|
||||
print("缺少子进程命令", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
# 透传环境(宿主注入的 PLUGINS_ROOT / PLATFORM_ACCOUNT 等原样继承)
|
||||
env = dict(os.environ)
|
||||
|
||||
# 1) 子进程:stdin/stdout/stderr 直接对接父进程(Node 侧),协议零改写
|
||||
try:
|
||||
child = subprocess.Popen(
|
||||
child_cmd,
|
||||
stdin=sys.stdin.buffer,
|
||||
stdout=sys.stdout.buffer,
|
||||
stderr=sys.stderr.buffer,
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
bufsize=0,
|
||||
)
|
||||
except OSError as e:
|
||||
print(f"拉起子进程失败: {e}", file=sys.stderr)
|
||||
return 127
|
||||
|
||||
# 2) Job Object 托管(Windows):整树终止 + 内存上限
|
||||
job = winjob.Job(max_mem_mb=int(args.mem or 0))
|
||||
try:
|
||||
job.assign(child)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 3) 超时守护(兜底;Node 侧 taskkill 仍作为第二道防线)
|
||||
timed_out = {"v": False}
|
||||
|
||||
def _kill_on_timeout() -> None:
|
||||
time.sleep(max(1, int(args.timeout or 0)))
|
||||
timed_out["v"] = True
|
||||
try:
|
||||
job.terminate(1)
|
||||
except Exception: # noqa: BLE001
|
||||
try:
|
||||
child.kill()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
timer = None
|
||||
if int(args.timeout or 0) > 0:
|
||||
timer = threading.Thread(target=_kill_on_timeout, daemon=True)
|
||||
timer.start()
|
||||
|
||||
# 4) 等子进程结束(进程退出/超时终止均在此返回);子进程自身已接管三通道
|
||||
try:
|
||||
code = child.wait()
|
||||
except KeyboardInterrupt:
|
||||
job.terminate(1)
|
||||
try:
|
||||
code = child.wait(timeout=5)
|
||||
except Exception: # noqa: BLE001
|
||||
code = 1
|
||||
|
||||
job.close()
|
||||
if timed_out["v"]:
|
||||
print(f"[job_guard] 插件执行超时({args.timeout}s)已强制终止", file=sys.stderr)
|
||||
return int(code) if code is not None else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,241 +1,242 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。
|
||||
|
||||
流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本,
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cloud_plugin_manifest(account: str) -> list | None:
|
||||
"""拉取账号可用插件清单(id/name/version)。控制面不可达/未配置返回 None。"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json().get("plugins", [])
|
||||
except Exception as _exc: # noqa: BLE001 离线兜底
|
||||
_LOGGER.warning("拉取插件清单失败(离线用本地插件):%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _local_version(plugin_id: str) -> str:
|
||||
"""本地已装插件版本:读 plugins/<id>/plugin.json.version;无则空串。"""
|
||||
mf = _PLUGINS_ROOT / plugin_id / "plugin.json"
|
||||
if not mf.is_file():
|
||||
return ""
|
||||
try:
|
||||
return str(json.loads(mf.read_text(encoding="utf-8")).get("version") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""简单版本比较(数字段按 int 比较)。"""
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def _dl_ticket(plugin_id: str, version: str, account: str) -> dict | None:
|
||||
"""向控制面签发一次性下载票据;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{config.CONTROLPLANE_URL}/api/plugins/{plugin_id}/versions/{version}/download-ticket",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("获取下载票据失败 %s@%s:%s", plugin_id, version, _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_pkg(ticket: str) -> bytes | None:
|
||||
"""凭一次性票据下载插件包 zip;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/download/{ticket}",
|
||||
headers=_headers(), timeout=_DL_TIMEOUT)
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载插件包失败:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
"""把插件包解压安装到 plugins/<id>/(临时目录 → 原子替换)。
|
||||
|
||||
包根目录需含 plugin.json;解压前校验非法路径防目录穿越。
|
||||
"""
|
||||
if len(content) > _MAX_PKG_BYTES:
|
||||
_LOGGER.error("插件包 %s 超大小上限,拒绝安装", plugin_id)
|
||||
return False
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
_LOGGER.error("插件包 %s 不是合法 ZIP", plugin_id)
|
||||
return False
|
||||
with zf:
|
||||
names = zf.namelist()
|
||||
if "plugin.json" not in names:
|
||||
_LOGGER.error("插件包 %s 缺 plugin.json", plugin_id)
|
||||
return False
|
||||
for m in names:
|
||||
if m.startswith("/") or ".." in m.split("/"):
|
||||
_LOGGER.error("插件包 %s 含非法路径:%s", plugin_id, m)
|
||||
return False
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f".pkg_{plugin_id}_"))
|
||||
try:
|
||||
zf.extractall(tmp)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("解压插件包 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
# 原子替换:旧目录移除 → 新目录就位
|
||||
target = _PLUGINS_ROOT / plugin_id
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.move(str(tmp), str(target))
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.error("安装插件 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
if not pid or not ver:
|
||||
continue
|
||||
local = _local_version(pid)
|
||||
if local == ver or (local and not _version_lt(local, ver)):
|
||||
result["up_to_date"].append(pid)
|
||||
continue
|
||||
tkt = _dl_ticket(pid, ver, account)
|
||||
if not tkt:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
content = _fetch_pkg(tkt.get("ticket", ""))
|
||||
if not content:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
expect = (tkt.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(content).hexdigest() != expect:
|
||||
_LOGGER.error("插件包 %s@%s sha256 校验失败,拒绝安装", pid, ver)
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
if _install_pkg(pid, content):
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。
|
||||
|
||||
流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本,
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cloud_plugin_manifest(account: str) -> list | None:
|
||||
"""拉取账号可用插件清单(id/name/version)。控制面不可达/未配置返回 None。"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json().get("plugins", [])
|
||||
except Exception as _exc: # noqa: BLE001 离线兜底
|
||||
_LOGGER.warning("拉取插件清单失败(离线用本地插件):%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _local_version(plugin_id: str) -> str:
|
||||
"""本地已装插件版本:读 plugins/<id>/plugin.json.version;无则空串。"""
|
||||
mf = _PLUGINS_ROOT / plugin_id / "plugin.json"
|
||||
if not mf.is_file():
|
||||
return ""
|
||||
try:
|
||||
# utf-8-sig:防 plugin.json 带 UTF-8 BOM(json.loads 遇 BOM 会抛 JSONDecodeError → 误判为新装重下)
|
||||
return str(json.loads(mf.read_text(encoding="utf-8-sig")).get("version") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""简单版本比较(数字段按 int 比较)。"""
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def _dl_ticket(plugin_id: str, version: str, account: str) -> dict | None:
|
||||
"""向控制面签发一次性下载票据;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{config.CONTROLPLANE_URL}/api/plugins/{plugin_id}/versions/{version}/download-ticket",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("获取下载票据失败 %s@%s:%s", plugin_id, version, _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_pkg(ticket: str) -> bytes | None:
|
||||
"""凭一次性票据下载插件包 zip;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/download/{ticket}",
|
||||
headers=_headers(), timeout=_DL_TIMEOUT)
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载插件包失败:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
"""把插件包解压安装到 plugins/<id>/(临时目录 → 原子替换)。
|
||||
|
||||
包根目录需含 plugin.json;解压前校验非法路径防目录穿越。
|
||||
"""
|
||||
if len(content) > _MAX_PKG_BYTES:
|
||||
_LOGGER.error("插件包 %s 超大小上限,拒绝安装", plugin_id)
|
||||
return False
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
_LOGGER.error("插件包 %s 不是合法 ZIP", plugin_id)
|
||||
return False
|
||||
with zf:
|
||||
names = zf.namelist()
|
||||
if "plugin.json" not in names:
|
||||
_LOGGER.error("插件包 %s 缺 plugin.json", plugin_id)
|
||||
return False
|
||||
for m in names:
|
||||
if m.startswith("/") or ".." in m.split("/"):
|
||||
_LOGGER.error("插件包 %s 含非法路径:%s", plugin_id, m)
|
||||
return False
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f".pkg_{plugin_id}_"))
|
||||
try:
|
||||
zf.extractall(tmp)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("解压插件包 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
# 原子替换:旧目录移除 → 新目录就位
|
||||
target = _PLUGINS_ROOT / plugin_id
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.move(str(tmp), str(target))
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.error("安装插件 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
if not pid or not ver:
|
||||
continue
|
||||
local = _local_version(pid)
|
||||
if local == ver or (local and not _version_lt(local, ver)):
|
||||
result["up_to_date"].append(pid)
|
||||
continue
|
||||
tkt = _dl_ticket(pid, ver, account)
|
||||
if not tkt:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
content = _fetch_pkg(tkt.get("ticket", ""))
|
||||
if not content:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
expect = (tkt.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(content).hexdigest() != expect:
|
||||
_LOGGER.error("插件包 %s@%s sha256 校验失败,拒绝安装", pid, ver)
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
if _install_pkg(pid, content):
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
|
||||
@@ -66,12 +66,14 @@ _PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。"""
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。
|
||||
用 utf-8-sig 读取:防文件带 UTF-8 BOM(记事本另存 UTF-8 时常见),否则会读到
|
||||
"\\ufeff1.2.0" 导致版本比对永远判为"不大于"(P1 修复:壳子升级失效根因)。"""
|
||||
if not getattr(sys, "frozen", False):
|
||||
return ""
|
||||
vf = Path(sys.executable).resolve().parent / "shell.version"
|
||||
try:
|
||||
return vf.read_text(encoding="utf-8").strip() if vf.is_file() else ""
|
||||
return vf.read_text(encoding="utf-8-sig").strip() if vf.is_file() else ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
@@ -19,17 +19,22 @@ from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
|
||||
|
||||
# 插件目录(源码/打包统一的"单一真源"位置):
|
||||
# 插件目录(源码/打包/环境包统一的"单一真源"位置):
|
||||
# - 环境包/便携运行时:由宿主(Node 壳)显式注入 PLUGINS_ROOT 环境变量(指向插件根)
|
||||
# - 打包运行(frozen)时:exe 同级 plugins/(中心机下发插件包解压到这里)
|
||||
# - 源码运行:仓库根 plugins/(插件源码独立于底座,不随 webhost 发布)
|
||||
# 两种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
if getattr(sys, "frozen", False):
|
||||
# 三种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
_env_plugins_root = os.getenv("PLUGINS_ROOT", "").strip()
|
||||
if _env_plugins_root:
|
||||
_PLUGINS_ROOT = pathlib.Path(_env_plugins_root).resolve()
|
||||
elif getattr(sys, "frozen", False):
|
||||
_PLUGINS_ROOT = pathlib.Path(sys.executable).resolve().parent / "plugins"
|
||||
else:
|
||||
# __file__ = desktop/webhost/backend/plugins/__init__.py → parents[4] = 仓库根
|
||||
|
||||
@@ -1,449 +1,455 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
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"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_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():
|
||||
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 _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
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 c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
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:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 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:
|
||||
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, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (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)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ 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:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
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())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
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))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
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)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
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) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
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:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and 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
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
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
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
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"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_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():
|
||||
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 _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
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 c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
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:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 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:
|
||||
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, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (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)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ 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:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
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())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
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))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
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)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
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) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
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:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and 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
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
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
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
|
||||
@@ -48,6 +48,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
@@ -125,6 +125,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -90,6 +90,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 自动化工作台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 自动化工作台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
+129
-129
@@ -1,130 +1,130 @@
|
||||
// 与 FastAPI 后端交互 + WebSocket 实时流
|
||||
const WS_BASE = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchMeta() {
|
||||
return j('/api/meta')
|
||||
}
|
||||
|
||||
export async function syncPlugins() {
|
||||
return j('/api/plugins/sync', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function getShellStatus() {
|
||||
return j('/api/shell/update-status')
|
||||
}
|
||||
|
||||
export async function checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function logoutPlatform(id) {
|
||||
return j(`/api/platforms/${id}/logout`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
// ===== 定时任务(壳子内置定时,配置自动备份中心机) =====
|
||||
export async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 统一账户登录/会话(底座仅保留认证与个人密码,管理走中心机控制面) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
// v3 钉钉直连接登录:生成钉钉授权 URL(redirect_uri=本机 /auth/done),前端当前窗口跳转到该 URL
|
||||
export async function authDingtalk() {
|
||||
return j('/api/auth/dingtalk')
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
// 与 FastAPI 后端交互 + WebSocket 实时流
|
||||
const WS_BASE = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchMeta() {
|
||||
return j('/api/meta')
|
||||
}
|
||||
|
||||
export async function syncPlugins() {
|
||||
return j('/api/plugins/sync', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function getShellStatus() {
|
||||
return j('/api/shell/update-status')
|
||||
}
|
||||
|
||||
export async function checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function logoutPlatform(id) {
|
||||
return j(`/api/platforms/${id}/logout`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
// ===== 定时任务(壳子内置定时,配置自动备份中心机) =====
|
||||
export async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 统一账户登录/会话(底座仅保留认证与个人密码,管理走中心机控制面) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
// v3 钉钉直连接登录:生成钉钉授权 URL(redirect_uri=本机 /auth/done),前端当前窗口跳转到该 URL
|
||||
export async function authDingtalk() {
|
||||
return j('/api/auth/dingtalk')
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,353 +1,353 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>已授权插件</span>
|
||||
<span class="mono">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>平台在线</span>
|
||||
<span class="mono">{{ store.platforms.filter(p => p.online).length }}/{{ store.platforms.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 折叠面板:平台登录态 / 我的插件 / 修改密码 -->
|
||||
<el-collapse v-model="activeNames">
|
||||
<el-collapse-item name="platforms">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Connection /></el-icon>
|
||||
<span>平台登录态</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-for="(p, i) in store.platforms" :key="p.id" class="prow">
|
||||
<span class="ridx mono">P0{{ i + 1 }}</span>
|
||||
<span class="dot" :class="{ on: p.online }"></span>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<el-button size="small" :disabled="busy === p.id || p.online" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : p.online ? '正常' : '重新登录' }}
|
||||
</el-button>
|
||||
<el-button v-if="p.online" size="small" plain type="danger" :disabled="busy === p.id" @click="logout(p.id)">登出</el-button>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<el-collapse-item name="plugins">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Box /></el-icon>
|
||||
<span>我的插件 ({{ store.plugins.length }})</span>
|
||||
</div>
|
||||
</template>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<div v-else class="ilist">
|
||||
<div v-for="(p, i) in store.plugins" :key="p.id" class="irow">
|
||||
<span class="ridx mono">{{ String(i + 1).padStart(2, '0') }}</span>
|
||||
<span class="iname">{{ p.name }}</span>
|
||||
<span class="mono iver">v{{ p.version }}</span>
|
||||
<span class="i-dot"></span>
|
||||
</div>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<el-collapse-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
|
||||
const visible = ref(true)
|
||||
|
||||
// 展示名:优先昵称(真实姓名),无昵称时回退账号(工号)
|
||||
const displayName = computed(() => store.nickname || store.current)
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
const activeNames = ref(['platforms', 'plugins']) // 修改密码默认折叠,点击展开
|
||||
const busy = ref('')
|
||||
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
ElMessage.success(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
ElMessage.success(`平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
ElMessage.error(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function logout(id) {
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await logoutPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 已登出`)
|
||||
ElMessage.success(`平台 ${p.label} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
ElMessage.error(`登出失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 修改密码
|
||||
const formRef = ref()
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
const rules = {
|
||||
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码', trigger: 'blur' },
|
||||
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v && v === form.oldPwd
|
||||
? cb(new Error('新密码不能与原密码相同')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v !== form.newPwd
|
||||
? cb(new Error('两次输入的密码不一致')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
}
|
||||
const pwdBusy = ref(false)
|
||||
async function changePwd() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: form.oldPwd,
|
||||
new_password: form.newPwd,
|
||||
})
|
||||
ElMessage.success('密码已修改,下次登录请使用新密码')
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mono { font-family: var(--font-mono); letter-spacing: .04em; }
|
||||
|
||||
/* ================= 个人信息卡 ================= */
|
||||
.pcard {
|
||||
margin-bottom: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.pcard-rows { border-top: 1px solid var(--border); }
|
||||
.crow {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 11px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
.crow:last-child { border-bottom: none; }
|
||||
.crow span:first-child { color: var(--text-sub); }
|
||||
.crow .mono { color: var(--text); font-size: 13px; font-weight: 600; }
|
||||
|
||||
/* ================= 折叠面板 ================= */
|
||||
.panel-title { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-sub); }
|
||||
.panel-title :deep(.el-icon) { color: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.prow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.prow:last-child { border-bottom: none; }
|
||||
.ridx { flex: none; width: 26px; font-size: 11px; color: var(--text-faint); }
|
||||
.dot {
|
||||
flex: none; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: #c6ccdc;
|
||||
}
|
||||
.dot.on { background: #22b07a; box-shadow: 0 0 0 3px rgba(34, 176, 122, .16); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.prow :deep(.el-button--primary) { border-color: transparent; }
|
||||
.prow :deep(.el-button--danger.is-plain) { border-color: rgba(214, 69, 69, .35); color: #d64545; }
|
||||
|
||||
/* ---------- 我的插件:台账式列表 ---------- */
|
||||
.ilist { display: flex; flex-direction: column; }
|
||||
.irow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.irow:last-child { border-bottom: none; }
|
||||
.iname { flex: 1; color: var(--text); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iver { font-size: 11px; color: var(--text-faint); }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>已授权插件</span>
|
||||
<span class="mono">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>平台在线</span>
|
||||
<span class="mono">{{ store.platforms.filter(p => p.online).length }}/{{ store.platforms.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 折叠面板:平台登录态 / 我的插件 / 修改密码 -->
|
||||
<el-collapse v-model="activeNames">
|
||||
<el-collapse-item name="platforms">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Connection /></el-icon>
|
||||
<span>平台登录态</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-for="(p, i) in store.platforms" :key="p.id" class="prow">
|
||||
<span class="ridx mono">P0{{ i + 1 }}</span>
|
||||
<span class="dot" :class="{ on: p.online }"></span>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<el-button size="small" :disabled="busy === p.id || p.online" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : p.online ? '正常' : '重新登录' }}
|
||||
</el-button>
|
||||
<el-button v-if="p.online" size="small" plain type="danger" :disabled="busy === p.id" @click="logout(p.id)">登出</el-button>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<el-collapse-item name="plugins">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Box /></el-icon>
|
||||
<span>我的插件 ({{ store.plugins.length }})</span>
|
||||
</div>
|
||||
</template>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<div v-else class="ilist">
|
||||
<div v-for="(p, i) in store.plugins" :key="p.id" class="irow">
|
||||
<span class="ridx mono">{{ String(i + 1).padStart(2, '0') }}</span>
|
||||
<span class="iname">{{ p.name }}</span>
|
||||
<span class="mono iver">v{{ p.version }}</span>
|
||||
<span class="i-dot"></span>
|
||||
</div>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<el-collapse-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
|
||||
const visible = ref(true)
|
||||
|
||||
// 展示名:优先昵称(真实姓名),无昵称时回退账号(工号)
|
||||
const displayName = computed(() => store.nickname || store.current)
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
const activeNames = ref(['platforms', 'plugins']) // 修改密码默认折叠,点击展开
|
||||
const busy = ref('')
|
||||
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
ElMessage.success(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
ElMessage.success(`平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
ElMessage.error(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function logout(id) {
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await logoutPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 已登出`)
|
||||
ElMessage.success(`平台 ${p.label} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
ElMessage.error(`登出失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 修改密码
|
||||
const formRef = ref()
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
const rules = {
|
||||
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码', trigger: 'blur' },
|
||||
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v && v === form.oldPwd
|
||||
? cb(new Error('新密码不能与原密码相同')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v !== form.newPwd
|
||||
? cb(new Error('两次输入的密码不一致')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
}
|
||||
const pwdBusy = ref(false)
|
||||
async function changePwd() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: form.oldPwd,
|
||||
new_password: form.newPwd,
|
||||
})
|
||||
ElMessage.success('密码已修改,下次登录请使用新密码')
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mono { font-family: var(--font-mono); letter-spacing: .04em; }
|
||||
|
||||
/* ================= 个人信息卡 ================= */
|
||||
.pcard {
|
||||
margin-bottom: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.pcard-rows { border-top: 1px solid var(--border); }
|
||||
.crow {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 11px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
.crow:last-child { border-bottom: none; }
|
||||
.crow span:first-child { color: var(--text-sub); }
|
||||
.crow .mono { color: var(--text); font-size: 13px; font-weight: 600; }
|
||||
|
||||
/* ================= 折叠面板 ================= */
|
||||
.panel-title { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-sub); }
|
||||
.panel-title :deep(.el-icon) { color: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.prow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.prow:last-child { border-bottom: none; }
|
||||
.ridx { flex: none; width: 26px; font-size: 11px; color: var(--text-faint); }
|
||||
.dot {
|
||||
flex: none; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: #c6ccdc;
|
||||
}
|
||||
.dot.on { background: #22b07a; box-shadow: 0 0 0 3px rgba(34, 176, 122, .16); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.prow :deep(.el-button--primary) { border-color: transparent; }
|
||||
.prow :deep(.el-button--danger.is-plain) { border-color: rgba(214, 69, 69, .35); color: #d64545; }
|
||||
|
||||
/* ---------- 我的插件:台账式列表 ---------- */
|
||||
.ilist { display: flex; flex-direction: column; }
|
||||
.irow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.irow:last-child { border-bottom: none; }
|
||||
.iname { flex: 1; color: var(--text); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iver { font-size: 11px; color: var(--text-faint); }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
</style>
|
||||
@@ -1,160 +1,160 @@
|
||||
/* ============ 37du Web Host 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-body: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
|
||||
/* element-plus 主题与品牌蓝统一 */
|
||||
--el-color-primary: #3b6cff;
|
||||
--el-color-primary-light-3: #6f8dff;
|
||||
--el-color-primary-light-5: #a3b7ff;
|
||||
--el-color-primary-light-7: #d0dcff;
|
||||
--el-color-primary-light-8: #e2e9ff;
|
||||
--el-color-primary-light-9: #eef2ff;
|
||||
--el-color-primary-dark-2: #2f56d6;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-border-radius-small: 6px;
|
||||
--el-border-radius-round: 20px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
select.input { padding-right: 30px; appearance: none; cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237b8497' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 10px center; }
|
||||
.field-label { color: var(--text-sub); font-size: 13px; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress { height: 8px; width: 180px; background: #e8ecf5; border-radius: 6px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 6px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(59,108,255,.5); }
|
||||
|
||||
/* 日志 */
|
||||
.log-box {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.75;
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
.log-line:hover { background: #f7f9fd; }
|
||||
.log-box .t { color: var(--text-faint); margin-right: 10px; user-select: none; }
|
||||
.log-box .lv { margin-right: 6px; font-weight: 700; }
|
||||
.log-box .s-INFO { color: var(--primary); }
|
||||
.log-box .s-ERROR { color: var(--err); }
|
||||
.log-box .s-WARN { color: var(--warn); }
|
||||
|
||||
/* 过渡 */
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
/* ============ 37du Web Host 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-body: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
|
||||
/* element-plus 主题与品牌蓝统一 */
|
||||
--el-color-primary: #3b6cff;
|
||||
--el-color-primary-light-3: #6f8dff;
|
||||
--el-color-primary-light-5: #a3b7ff;
|
||||
--el-color-primary-light-7: #d0dcff;
|
||||
--el-color-primary-light-8: #e2e9ff;
|
||||
--el-color-primary-light-9: #eef2ff;
|
||||
--el-color-primary-dark-2: #2f56d6;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-border-radius-small: 6px;
|
||||
--el-border-radius-round: 20px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
select.input { padding-right: 30px; appearance: none; cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237b8497' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 10px center; }
|
||||
.field-label { color: var(--text-sub); font-size: 13px; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress { height: 8px; width: 180px; background: #e8ecf5; border-radius: 6px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 6px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(59,108,255,.5); }
|
||||
|
||||
/* 日志 */
|
||||
.log-box {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.75;
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
.log-line:hover { background: #f7f9fd; }
|
||||
.log-box .t { color: var(--text-faint); margin-right: 10px; user-select: none; }
|
||||
.log-box .lv { margin-right: 6px; font-weight: 700; }
|
||||
.log-box .s-INFO { color: var(--primary); }
|
||||
.log-box .s-ERROR { color: var(--err); }
|
||||
.log-box .s-WARN { color: var(--warn); }
|
||||
|
||||
/* 过渡 */
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
.fade-leave-to { opacity: 0; }
|
||||
+248
-248
@@ -1,249 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
FROZEN = getattr(sys, "frozen", False)
|
||||
PORT = 8799
|
||||
URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(sys.executable).resolve().parent if FROZEN else Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid]
|
||||
|
||||
|
||||
def _kill_existing() -> None:
|
||||
"""杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。"""
|
||||
targets = set(_port_pids())
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
targets.add(int(PID_FILE.read_text().strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
for pid in targets:
|
||||
try:
|
||||
proc = psutil.Process(pid)
|
||||
if proc.name().lower().startswith(("python", "uvicorn", "37du-host")):
|
||||
proc.terminate()
|
||||
proc.wait(timeout=4)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
continue
|
||||
for _ in range(40): # 等待端口释放
|
||||
if not _port_pids():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def _port_free() -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", PORT)) != 0
|
||||
|
||||
|
||||
def _wait_ready(proc: subprocess.Popen | None) -> None:
|
||||
for _ in range(60): # 等待就绪
|
||||
if not _port_free():
|
||||
return
|
||||
if proc is not None and proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("服务启动失败")
|
||||
|
||||
|
||||
def _start_server():
|
||||
"""拉起 uvicorn 服务:源码运行=子进程;打包运行=进程内后台线程。"""
|
||||
if not _port_free():
|
||||
_kill_existing()
|
||||
time.sleep(0.3)
|
||||
if FROZEN:
|
||||
# 窗口模式无 stdout/stderr(None),uvicorn 日志 formatter 会调 sys.stdout.isatty() 崩溃
|
||||
_devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115 进程级常驻
|
||||
sys.stdout = sys.stderr = _devnull
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
import uvicorn
|
||||
from webhost.backend.main import app
|
||||
|
||||
def _serve() -> None:
|
||||
try:
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")
|
||||
except BaseException:
|
||||
import traceback
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
|
||||
t = threading.Thread(target=_serve, daemon=True, name="uvicorn")
|
||||
t.start()
|
||||
_wait_ready(None)
|
||||
return t
|
||||
cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app",
|
||||
"--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"]
|
||||
proc = subprocess.Popen(cmd, cwd=str(HERE.parent),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
PID_FILE.write_text(str(proc.pid))
|
||||
_wait_ready(proc)
|
||||
return proc
|
||||
|
||||
|
||||
def _apply_win11_corners(window) -> None:
|
||||
"""Win11 窗口圆角:去掉老式方角观感(DWM 设置圆角偏好,失败静默忽略)。"""
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
DWMWA_WINDOW_CORNER_PREFERENCE = 33
|
||||
DWMWCP_ROUND = 2
|
||||
|
||||
def _on_shown():
|
||||
try:
|
||||
hwnd = int(window.native.Handle)
|
||||
ctypes.windll.dwmapi.DwmSetWindowAttribute(
|
||||
ctypes.c_int(hwnd),
|
||||
ctypes.c_int(DWMWA_WINDOW_CORNER_PREFERENCE),
|
||||
ctypes.byref(ctypes.c_int(DWMWCP_ROUND)),
|
||||
ctypes.c_int(4),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
window.events.shown += _on_shown
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _open_window(app_name: str) -> bool:
|
||||
"""尝试 PyWebView 原生窗口;失败返回显示不可用。"""
|
||||
try:
|
||||
import webview # noqa: WPS433
|
||||
|
||||
window = webview.create_window(app_name, URL,
|
||||
width=1200, height=780, min_size=(1000, 660),
|
||||
background_color="#eef2f9")
|
||||
_apply_win11_corners(window)
|
||||
webview.start(gui="edgechromium")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop(server) -> None:
|
||||
if isinstance(server, threading.Thread):
|
||||
# 打包运行:uvicorn 为进程内线程,进程退出即随之结束,无需也无法 terminate
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
server.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
app_name = "37du 自动化工作台"
|
||||
# 任务栏图标分组/固定:统一 AppUserModelID(如做快捷方式需保持一致)
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("37du.Host")
|
||||
except Exception:
|
||||
pass
|
||||
proc = _start_server()
|
||||
|
||||
if not _open_window(app_name):
|
||||
# 回退:系统浏览器
|
||||
webbrowser.open(URL)
|
||||
print(f"[webhost] 已用系统浏览器打开:{URL}")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
_stop(proc)
|
||||
return 0
|
||||
else:
|
||||
_stop(proc)
|
||||
return 0
|
||||
|
||||
|
||||
def _fatal_log(msg: str) -> None:
|
||||
"""窗口模式无控制台:崩溃现场落盘到 exe 同级 crash.log,便于诊断。"""
|
||||
try:
|
||||
(HERE / "crash.log").write_text(msg, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
import traceback
|
||||
if FROZEN:
|
||||
_fatal_log(traceback.format_exc())
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
FROZEN = getattr(sys, "frozen", False)
|
||||
PORT = 8799
|
||||
URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(sys.executable).resolve().parent if FROZEN else Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid]
|
||||
|
||||
|
||||
def _kill_existing() -> None:
|
||||
"""杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。"""
|
||||
targets = set(_port_pids())
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
targets.add(int(PID_FILE.read_text().strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
for pid in targets:
|
||||
try:
|
||||
proc = psutil.Process(pid)
|
||||
if proc.name().lower().startswith(("python", "uvicorn", "37du-host")):
|
||||
proc.terminate()
|
||||
proc.wait(timeout=4)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
continue
|
||||
for _ in range(40): # 等待端口释放
|
||||
if not _port_pids():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def _port_free() -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", PORT)) != 0
|
||||
|
||||
|
||||
def _wait_ready(proc: subprocess.Popen | None) -> None:
|
||||
for _ in range(60): # 等待就绪
|
||||
if not _port_free():
|
||||
return
|
||||
if proc is not None and proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("服务启动失败")
|
||||
|
||||
|
||||
def _start_server():
|
||||
"""拉起 uvicorn 服务:源码运行=子进程;打包运行=进程内后台线程。"""
|
||||
if not _port_free():
|
||||
_kill_existing()
|
||||
time.sleep(0.3)
|
||||
if FROZEN:
|
||||
# 窗口模式无 stdout/stderr(None),uvicorn 日志 formatter 会调 sys.stdout.isatty() 崩溃
|
||||
_devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115 进程级常驻
|
||||
sys.stdout = sys.stderr = _devnull
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
import uvicorn
|
||||
from webhost.backend.main import app
|
||||
|
||||
def _serve() -> None:
|
||||
try:
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")
|
||||
except BaseException:
|
||||
import traceback
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
|
||||
t = threading.Thread(target=_serve, daemon=True, name="uvicorn")
|
||||
t.start()
|
||||
_wait_ready(None)
|
||||
return t
|
||||
cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app",
|
||||
"--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"]
|
||||
proc = subprocess.Popen(cmd, cwd=str(HERE.parent),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
PID_FILE.write_text(str(proc.pid))
|
||||
_wait_ready(proc)
|
||||
return proc
|
||||
|
||||
|
||||
def _apply_win11_corners(window) -> None:
|
||||
"""Win11 窗口圆角:去掉老式方角观感(DWM 设置圆角偏好,失败静默忽略)。"""
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
DWMWA_WINDOW_CORNER_PREFERENCE = 33
|
||||
DWMWCP_ROUND = 2
|
||||
|
||||
def _on_shown():
|
||||
try:
|
||||
hwnd = int(window.native.Handle)
|
||||
ctypes.windll.dwmapi.DwmSetWindowAttribute(
|
||||
ctypes.c_int(hwnd),
|
||||
ctypes.c_int(DWMWA_WINDOW_CORNER_PREFERENCE),
|
||||
ctypes.byref(ctypes.c_int(DWMWCP_ROUND)),
|
||||
ctypes.c_int(4),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
window.events.shown += _on_shown
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _open_window(app_name: str) -> bool:
|
||||
"""尝试 PyWebView 原生窗口;失败返回显示不可用。"""
|
||||
try:
|
||||
import webview # noqa: WPS433
|
||||
|
||||
window = webview.create_window(app_name, URL,
|
||||
width=1200, height=780, min_size=(1000, 660),
|
||||
background_color="#eef2f9")
|
||||
_apply_win11_corners(window)
|
||||
webview.start(gui="edgechromium")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop(server) -> None:
|
||||
if isinstance(server, threading.Thread):
|
||||
# 打包运行:uvicorn 为进程内线程,进程退出即随之结束,无需也无法 terminate
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
server.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
app_name = "37du 自动化工作台"
|
||||
# 任务栏图标分组/固定:统一 AppUserModelID(如做快捷方式需保持一致)
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("37du.Host")
|
||||
except Exception:
|
||||
pass
|
||||
proc = _start_server()
|
||||
|
||||
if not _open_window(app_name):
|
||||
# 回退:系统浏览器
|
||||
webbrowser.open(URL)
|
||||
print(f"[webhost] 已用系统浏览器打开:{URL}")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
_stop(proc)
|
||||
return 0
|
||||
else:
|
||||
_stop(proc)
|
||||
return 0
|
||||
|
||||
|
||||
def _fatal_log(msg: str) -> None:
|
||||
"""窗口模式无控制台:崩溃现场落盘到 exe 同级 crash.log,便于诊断。"""
|
||||
try:
|
||||
(HERE / "crash.log").write_text(msg, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
import traceback
|
||||
if FROZEN:
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
@@ -5,7 +5,7 @@
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.2.0"
|
||||
#define MyAppVersion "1.2.1"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.2.0
|
||||
1.2.1
|
||||
+100
-100
@@ -1,100 +1,100 @@
|
||||
# 插件发版与自动更新规范
|
||||
|
||||
> 本文档定义 37duAutomation 各交付物的**发版流程**与执行机**自动更新机制**。
|
||||
> 发版统一走 agent CLI(中心机控制面),执行机端插件按账号权限自下载、壳子由用户点击升级。
|
||||
> 打包产物位置、打包脚本见 [插件开发规范.md](./插件开发规范.md) 第 4 节。
|
||||
|
||||
## 1. 总览
|
||||
|
||||
版本源(插件包 + 壳子安装包 + 文件登记)全部在**中心机控制面**(`http://117.72.191.188:8800`)。
|
||||
|
||||
| 交付物 | 更新机制 | 入口 |
|
||||
|--------|----------|------|
|
||||
| 插件 | 执行机登录后按账号权限自动同步(`plugin_sync.py`) | agent CLI `publish` / `grant` / `revoke` |
|
||||
| 壳子(安装包) | 执行机自动下载 + 用户点击升级重启(`shell_updater.py`) | agent CLI `file push --category shell` |
|
||||
| 中心机控制面 | 源码部署,不打包 | 宝塔上传 + 重启 / 前端构建发布 |
|
||||
|
||||
## 2. 发版工具与鉴权
|
||||
|
||||
统一在 `desktop/` 目录下执行 agent CLI:
|
||||
|
||||
```powershell
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent_cli
|
||||
```
|
||||
|
||||
鉴权两种方式:
|
||||
|
||||
1. **密码登录(推荐,任意机器可用)**:
|
||||
`--admin <管理员> --password <密码>`(或环境变量 `AGENT_ADMIN_PASSWORD` / `AGENT_ADMIN_ACCOUNT`),
|
||||
远程机器再加 `--base http://<中心机地址>:8800`
|
||||
2. **本机密钥自签(仅中心机本机)**:复用 `controlplane/.env` 与 `.admin_secret`
|
||||
|
||||
实际账号:管理员 `puddy`,密码 `123456`,中心机控制面 `http://117.72.191.188:8800`。
|
||||
|
||||
本开发机直接示例:
|
||||
|
||||
```powershell
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
|
||||
--admin puddy --password 123456 --base http://117.72.191.188:8800 `
|
||||
publish <插件.zip> --id <id> --version <v>
|
||||
```
|
||||
|
||||
## 3. 插件发版流程
|
||||
|
||||
1. **打包**:在插件目录(`plugins/XQ0001-0100/XQ00xx <中文名>/`)下执行 `_pack.py`,产物输出到仓库根 `dist-plugin/<id>_v<版本>.zip`
|
||||
(zip 根必须含 `plugin.json`;带 UI 插件需先 `npm run build` 出 `ui/index.html`)。
|
||||
2. **发布**:在 `desktop/` 下执行:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
|
||||
--admin puddy --password 123456 `
|
||||
publish dist-plugin\<id>_v<版本>.zip --id <id> --version <版本>
|
||||
```
|
||||
|
||||
版本号需与 `plugin.json.version` / `ScenePlugin.version` 一致,且高于中心机已有版本。
|
||||
3. **授权 / 收回**(按账号管控可执行性):
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli grant <账号> <id>
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli revoke <账号> <id>
|
||||
```
|
||||
|
||||
4. **执行机端**:登录后按账号权限自动同步——`plugin_sync.py` 拉版本清单 → 下载 → sha256 校验 →
|
||||
解压到 `plugins/<id>/` 原子替换 → 重载注册表;下次执行即用新版本。
|
||||
|
||||
## 4. 壳子发版流程
|
||||
|
||||
> 壳子 / 中心机 / 文件服务器的完整发版步骤见 [桌面端发版SOP](../桌面端/桌面端发版SOP.md),本节为摘要。
|
||||
|
||||
按实际流程执行:
|
||||
|
||||
1. 改 `desktop/webhost/tools/shell.version` 与 `install.iss` 的 `MyAppVersion` 为新版本
|
||||
2. `desktop/webhost/frontend` 下执行 `npm run build`
|
||||
3. PyInstaller 打 `desktop/webhost/tools/37du-host.spec`、`37du-host-runner.spec`
|
||||
(`37du-host-console.spec` 是调试版,不入安装包,可跳过)
|
||||
4. `ISCC.exe desktop/webhost/tools/install.iss` 出安装包
|
||||
5. 上传登记:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
|
||||
--admin puddy --password 123456 `
|
||||
file push <安装包> --category shell --version <新版本> [--notes "说明"]
|
||||
```
|
||||
|
||||
> 安装包上传到内网文件服务器(`FILESERVER_BASE_URL=172.30.35.135:8802`),并登记到中心机
|
||||
> `file_sources(shell)`,执行机 `shell_updater` 从该直链下载。**不要用旧的 `shell-release` 子命令**。
|
||||
|
||||
6. **执行机端**:自动下载安装包,前端提示后用户点击升级重启。
|
||||
|
||||
## 5. 中心机发版流程
|
||||
|
||||
控制面为源码部署(宝塔 gunicorn 8800,不打包 exe):
|
||||
|
||||
- 改后端代码:按 `docs/部署/控制面前后端部署SOP.md`「后端部署流程」上传文件 + 重启项目
|
||||
- 改前端代码:按同一文档「前端部署流程」构建并发布到静态站 8090
|
||||
|
||||
## 6. 发布后检查
|
||||
|
||||
- 插件发布后:执行机下次启动自动检测下载;插件登录后按权限自动下载更新。
|
||||
- 壳子发布后:执行机自动下载,前端提示后点击升级。
|
||||
- 版本冲突 / 更新失败:查执行机 `plugin_sync.py` 与 `shell_updater.py` 日志;核对中心机版本清单与授权。
|
||||
# 插件发版与自动更新规范
|
||||
|
||||
> 本文档定义 37duAutomation 各交付物的**发版流程**与执行机**自动更新机制**。
|
||||
> 发版统一走 agent CLI(中心机控制面),执行机端插件按账号权限自下载、壳子由用户点击升级。
|
||||
> 打包产物位置、打包脚本见 [插件开发规范.md](./插件开发规范.md) 第 4 节。
|
||||
|
||||
## 1. 总览
|
||||
|
||||
版本源(插件包 + 壳子安装包 + 文件登记)全部在**中心机控制面**(`http://117.72.191.188:8800`)。
|
||||
|
||||
| 交付物 | 更新机制 | 入口 |
|
||||
|--------|----------|------|
|
||||
| 插件 | 执行机登录后按账号权限自动同步(`plugin_sync.py`) | agent CLI `publish` / `grant` / `revoke` |
|
||||
| 壳子(安装包) | 执行机自动下载 + 用户点击升级重启(`shell_updater.py`) | agent CLI `file push --category shell` |
|
||||
| 中心机控制面 | 源码部署,不打包 | 宝塔上传 + 重启 / 前端构建发布 |
|
||||
|
||||
## 2. 发版工具与鉴权
|
||||
|
||||
统一在 `desktop/` 目录下执行 agent CLI:
|
||||
|
||||
```powershell
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent_cli
|
||||
```
|
||||
|
||||
鉴权两种方式:
|
||||
|
||||
1. **密码登录(推荐,任意机器可用)**:
|
||||
`--admin <管理员> --password <密码>`(或环境变量 `AGENT_ADMIN_PASSWORD` / `AGENT_ADMIN_ACCOUNT`),
|
||||
远程机器再加 `--base http://<中心机地址>:8800`
|
||||
2. **本机密钥自签(仅中心机本机)**:复用 `controlplane/.env` 与 `.admin_secret`
|
||||
|
||||
实际账号:管理员 `puddy`,密码 `123456`,中心机控制面 `http://117.72.191.188:8800`。
|
||||
|
||||
本开发机直接示例:
|
||||
|
||||
```powershell
|
||||
d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
|
||||
--admin puddy --password 123456 --base http://117.72.191.188:8800 `
|
||||
publish <插件.zip> --id <id> --version <v>
|
||||
```
|
||||
|
||||
## 3. 插件发版流程
|
||||
|
||||
1. **打包**:在插件目录(`plugins/XQ0001-0100/XQ00xx <中文名>/`)下执行 `_pack.py`,产物输出到仓库根 `dist-plugin/<id>_v<版本>.zip`
|
||||
(zip 根必须含 `plugin.json`;带 UI 插件需先 `npm run build` 出 `ui/index.html`)。
|
||||
2. **发布**:在 `desktop/` 下执行:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
|
||||
--admin puddy --password 123456 `
|
||||
publish dist-plugin\<id>_v<版本>.zip --id <id> --version <版本>
|
||||
```
|
||||
|
||||
版本号需与 `plugin.json.version` / `ScenePlugin.version` 一致,且高于中心机已有版本。
|
||||
3. **授权 / 收回**(按账号管控可执行性):
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli grant <账号> <id>
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli revoke <账号> <id>
|
||||
```
|
||||
|
||||
4. **执行机端**:登录后按账号权限自动同步——`plugin_sync.py` 拉版本清单 → 下载 → sha256 校验 →
|
||||
解压到 `plugins/<id>/` 原子替换 → 重载注册表;下次执行即用新版本。
|
||||
|
||||
## 4. 壳子发版流程
|
||||
|
||||
> 壳子 / 中心机 / 文件服务器的完整发版步骤见 [桌面端发版SOP](../桌面端/桌面端发版SOP.md),本节为摘要。
|
||||
|
||||
按实际流程执行:
|
||||
|
||||
1. 改 `desktop/webhost/tools/shell.version` 与 `install.iss` 的 `MyAppVersion` 为新版本
|
||||
2. `desktop/webhost/frontend` 下执行 `npm run build`
|
||||
3. PyInstaller 打 `desktop/webhost/tools/37du-host.spec`、`37du-host-runner.spec`
|
||||
(`37du-host-console.spec` 是调试版,不入安装包,可跳过)
|
||||
4. `ISCC.exe desktop/webhost/tools/install.iss` 出安装包
|
||||
5. 上传登记:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
|
||||
--admin puddy --password 123456 `
|
||||
file push <安装包> --category shell --version <新版本> [--notes "说明"]
|
||||
```
|
||||
|
||||
> 安装包上传到内网文件服务器(`FILESERVER_BASE_URL=172.30.35.135:8802`),并登记到中心机
|
||||
> `file_sources(shell)`,执行机 `shell_updater` 从该直链下载。**不要用旧的 `shell-release` 子命令**。
|
||||
|
||||
6. **执行机端**:自动下载安装包,前端提示后用户点击升级重启。
|
||||
|
||||
## 5. 中心机发版流程
|
||||
|
||||
控制面为源码部署(宝塔 gunicorn 8800,不打包 exe):
|
||||
|
||||
- 改后端代码:按 `docs/部署/控制面前后端部署SOP.md`「后端部署流程」上传文件 + 重启项目
|
||||
- 改前端代码:按同一文档「前端部署流程」构建并发布到静态站 8090
|
||||
|
||||
## 6. 发布后检查
|
||||
|
||||
- 插件发布后:执行机下次启动自动检测下载;插件登录后按权限自动下载更新。
|
||||
- 壳子发布后:执行机自动下载,前端提示后点击升级。
|
||||
- 版本冲突 / 更新失败:查执行机 `plugin_sync.py` 与 `shell_updater.py` 日志;核对中心机版本清单与授权。
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
# Node/Electron 客户端开发交接文档
|
||||
|
||||
> 用途:下一个会话据此开发 **Node 版执行机客户端**(替代现 Python `desktop/webhost/` 底座,技术栈 Electron/Node,插件保持 Python)。
|
||||
> 本会话已完成:服务端(controlplane)重构 + 前端(管理台)重构 + 客户端契约验证。本文件固化全部契约与环境信息,供新客户端开发直接引用,避免重复勘察。
|
||||
> 最后更新:2026-09-23
|
||||
|
||||
---
|
||||
|
||||
## 1. 会话交接摘要(先读这个)
|
||||
|
||||
### 1.1 上一会话完成了什么
|
||||
| 领域 | 成果 |
|
||||
|---|---|
|
||||
| 服务端 controlplane | 管理面全部重构:统一分页(page/page_size → `{items,total}`)、账号/插件/审计/上报筛选、昵称补齐、overview 瘦身、新增 `grant_data`/`account_grants` 轻量接口、强制改密(≥8 位)、头像上传修复(补 Authorization)、审计归属改操作者 |
|
||||
| 前端管理台 | ECharts 趋势/双环图、统一 `usePagedList` + `PagerBar` 分页架构、授权页解耦轻量数据源、账号下拉带昵称、各页搜索框、强制改密对话框 |
|
||||
| 客户端契约 | 存量 webhost 25 个调用逐一核对:**无需改动客户端**,服务端公开接口完全向后兼容(详见 §5) |
|
||||
| 部署 | 服务器 117.72.191.188(gunicorn 8800 + 前端 8090)按 SOP 部署,前端产物 `controlplane-web-dist.zip` 已更新 |
|
||||
|
||||
### 1.2 下一步(新 Node 客户端要做的事)
|
||||
1. 以 Electron + Node 重写执行机底座(替代 `desktop/webhost/`),能力对齐 §6 的模块清单。
|
||||
2. 插件执行机制**保持 Python**:Node 壳负责生命周期/调度/权限,用子进程跑 Python 插件(参照 `webhost.backend.plugins.*` 的接口契约)。
|
||||
3. 服务端契约**以本文件 §5 为准**,服务端是权威方,新客户端必须向后兼容(不得要求服务端改公开接口)。
|
||||
|
||||
### 1.3 踩过的坑(务必避免重犯)
|
||||
- **分页 SQL 拼接**:`args + (limit, offset)`(list+tuple)会抛 `TypeError` → 必须 `args + [limit, offset]`。已全部修复(`apis/admin.py` 4 处)。
|
||||
- **验证要到 SQL 执行层**:401 冒烟 ≠ 通过;分页/筛选改动必须用有效管理员票据真实执行(本次事故根因)。
|
||||
- **业务假设错误**:`grant_data` 曾 `WHERE is_admin = 0` 把管理员过滤掉 → 已改 `WHERE status = 1`(管理员也是插件使用者)。
|
||||
- 前端构建产物会覆盖用户手工改动:改前端后必须重新 `npm run build` + 重打 zip。
|
||||
|
||||
---
|
||||
|
||||
## 2. 系统全景
|
||||
|
||||
```
|
||||
┌─────────────────────────────┐
|
||||
浏览器管理台 │ controlplane 中心机 │
|
||||
(8090 静态站) ────▶│ FastAPI + gunicorn :8800 │──▶ MySQL (127.0.0.1/snny)
|
||||
│ nginx 同域反代 /api → 8800 │
|
||||
└──────────────┬──────────────┘
|
||||
│ 公开接口(X-API-Token / Bearer / 票据)
|
||||
┌──────────────▼──────────────┐
|
||||
│ webhost 执行机(待替换) │
|
||||
│ Python 底座 :8799 │
|
||||
│ └ 插件(Python,独立发布) │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
- **三端零依赖**:`desktop/controlplane/` 与 `desktop/webhost/` 互不 import,可单独拷贝演进(AGENTS.md 强制)。
|
||||
- **插件**:`plugins/` 根级目录按号段分桶,被执行机按账号权限自下载(zip),插件自包含,只能依赖标准库/三方依赖/底座注入接口(`webhost.backend.plugins.base`)。
|
||||
- **数据流核心**:执行机调公开接口拉权限/插件/授权票据 → 本机执行 → 上报运行结果;管理台走 admin 接口管理账号/插件/授权/审计。
|
||||
|
||||
### 2.1 目录索引
|
||||
```
|
||||
desktop/
|
||||
controlplane/ 中心机(FastAPI,本会话重构对象)
|
||||
app.py 组装:lifespan(建表/种子) + 路由 + CORS 白名单
|
||||
apis/ admin.py / auth.py / plugins.py / config_push.py /
|
||||
file_sources.py / schedules.py / dingtalk.py / fileserver_status.py / meta.py
|
||||
core/ config.py / db.py / auth.py / crypto.py / schemas.py /
|
||||
paging.py(统一分页) / pkgutil.py / dingtalk.py / notify.py / monitor.py
|
||||
tools/agent_cli.py 发版 CLI(-m controlplane.tools.agent_cli)
|
||||
frontend/ Vite + Vue3 管理台(build → dist/ → controlplane-web-dist.zip)
|
||||
webhost/ 执行机(Python,本次待替换为 Node)
|
||||
backend/
|
||||
apis/ meta.py / runs.py / schedules.py / plugin_ui.py / admin.py / dingtalk.py
|
||||
core/ config.py / cpapi.py / plugin_sync.py / creds_sync.py / shell_updater.py /
|
||||
chrome_manager.py / licensing.py / tasks.py / runner.py / session.py
|
||||
plugins/ base.py(插件接口契约)
|
||||
plugins/ 插件源码(XQ0001-0100/…,id=xq{单号})
|
||||
docs/
|
||||
部署/服务端前后端部署SOP.md 中心机部署步骤(权威)
|
||||
插件/发版规范.md agent_cli 发版流程(权威)
|
||||
桌面端/桌面端发版SOP.md webhost 壳子发版
|
||||
架构/桌面客户端设计.md 客户端技术选型评估(Electron 决策背景)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 服务端环境与配置
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 服务器 | 117.72.191.188(宝塔,公网) |
|
||||
| 后端 | gunicorn :8800(源码部署于 `/www/wwwroot/controlplane/controlplane/`) |
|
||||
| 前端 | 静态站 :8090(`/www/wwwroot/controlplane-web/`),nginx 同域反代 `/api` → 127.0.0.1:8800(**同源**,浏览器不触发 CORS) |
|
||||
| MySQL | 127.0.0.1,库名 **snny**(服务器本机) |
|
||||
| 本地开发 | `.venv`(D:\work\code\37duAutomation\.venv),`desktop/` 为 cwd 运行 `python -m uvicorn controlplane.app:app --port 8800`;本地 `.env` 的 MYSQL_HOST=117.72.191.188 **直连线上库**(只读验证可行,**禁止写操作**) |
|
||||
| 关键 env | `desktop/controlplane/.env`:CONTROLPLANE_PORT / CONTROLPLANE_TOKEN(机器凭证,见 .env 不写明文)/ MYSQL_* / DINGTALK_* / CORS_ALLOW_ORIGINS |
|
||||
| 执行机 env | `desktop/webhost/.env`:CONTROLPLANE_URL / CONTROLPLANE_ACCOUNT / CONTROLPLANE_TOKEN(默认空=内网可信) |
|
||||
|
||||
**本地跑后端注意**:`/health` 新版只返回 `{"ok":true}`;旧版含 db/host/database 字段——服务器当前应已是新版。
|
||||
|
||||
---
|
||||
|
||||
## 4. 鉴权体系(客户端必须理解的三把钥匙)
|
||||
|
||||
| 凭证 | 载体 | 用途 | 校验方 |
|
||||
|---|---|---|---|
|
||||
| 机器凭证 | `X-API-Token` 头 | 客户端→服务端内部调用(插件清单/下载/上报/壳子更新等);**为空则服务端不强制**(内网可信) | `_check_token` |
|
||||
| 云端会话 | `Authorization: Bearer <cloud_token>` | 员工登录后身份(调 `/api/plugins` 等);服务端落库 `cloud_tokens`,多 worker 可用 | `_cloud_account` |
|
||||
| 管理员票据 | `X-Admin-Token` 头 | 管理台登录签发(12h 有效),`<base64url(json)>.<hmac>` 签名,不可伪造 | `_require_admin` / `_identity` |
|
||||
|
||||
- **身份解析优先级**(`_identity`):Bearer 云 token → X-Admin-Token → (仅当 CONTROLPLANE_TOKEN 非空且 X-API-Token 匹配时)X-Admin-User。
|
||||
- **登录响应**(POST /api/admin/auth)同时返回 `token`(管理员票据)与 `cloud_token`(云端会话),客户端两个都存。
|
||||
- **离线验签**:`GET /api/me/pubkey` 下发 Ed25519 公钥(PEM),客户端缓存用于离线校验 license/control-list 票据签名(`crypto._verify_blob`)。
|
||||
|
||||
---
|
||||
|
||||
## 5. API 契约(客户端对接核心,全部字段级实测通过 2026-09-23)
|
||||
|
||||
> 通用:错误统一 `{"detail": "..."}` + 非 2xx;分页统一 `page`(1起)/`page_size`(默认20,≤1000) → `{items,total}`。
|
||||
> 字段命名:管理接口输出 **camelCase**(`deviceId`/`pluginId`/`durationSec`);公开接口见下。
|
||||
|
||||
### 5.1 认证
|
||||
| 接口 | 鉴权 | 请求 | 响应 |
|
||||
|---|---|---|---|
|
||||
| `POST /api/admin/auth` | 公开 | `{account, password}` | `{ok, account, is_admin, dept, nickname, avatar, must_change_pwd, token, cloud_token}` |
|
||||
| `POST /api/admin/password` | Bearer/X-Admin-Token | `{account, old_password, new_password}`(新密码 ≥8 位) | `{ok, account}` |
|
||||
| `POST /auth/exchange` | 公开 | `{code}`(钉钉扫码 code) | `{token(云), account, nickname, exists, created, must_change_pwd, is_admin}`;未配置钉钉返回 503 |
|
||||
|
||||
### 5.2 插件与权限(执行机核心)
|
||||
| 接口 | 鉴权 | 说明 | 响应 |
|
||||
|---|---|---|---|
|
||||
| `GET /api/plugins?account=x` | X-API-Token 或 Bearer(Bearer 优先,account 兜底兼容旧底座) | 账号可用插件清单(权限隔离) | `{account, plugins:[{id, name, version}]}` |
|
||||
| `GET /api/platforms/allowed?account=x` | 同上 | 平台白名单 | `{account, allowed:[]}` |
|
||||
| `GET /api/me/license?account=x&device=` | X-API-Token | 离线授权票据(Ed25519 签名),7 天有效期 | `{ticket, plugins:[{pluginId,name,canDownload,canRun,status,latestVersion}], issuedAt, expiresAt}` |
|
||||
| `GET /api/me/control-list` | X-API-Token | 管控清单(下架/禁用/强制更新) | `{ticket, control:{revokedPlugins[], disabledPlugins[], forcedUpdates:[{pluginId,minVersion,deadline}], updatedAt, expiresAt}}` |
|
||||
| `GET /api/me/pubkey` | 无 | 中心机公钥(离线验签用) | `{pub, algo:"ed25519"}` |
|
||||
|
||||
### 5.3 插件下载
|
||||
| 接口 | 鉴权 | 说明 | 响应 |
|
||||
|---|---|---|---|
|
||||
| `GET /api/plugins/{pid}/versions/{ver}/download-ticket?account=x` | X-API-Token | 校验 `can_download` 后签发一次性票据(TTL 1h) | `{ticket, url, filename, sha256, expiresAt}` |
|
||||
| `GET /api/download/{ticket}` | X-API-Token | 兑换票据,**一次性作废** | **二进制文件流**(FileResponse,非 JSON 非重定向),客户端 `raise_for_status + content + sha256 校验` |
|
||||
|
||||
### 5.4 运行与设备上报
|
||||
| 接口 | 鉴权 | 请求 | 响应 |
|
||||
|---|---|---|---|
|
||||
| `POST /api/runtime/report` | X-API-Token | `{account, device_id, plugin_id, version, status, msg, duration_sec}`(status: start/done/error/running/offline 补报) | `{ok}`(多余字段如 `at` 被忽略,时间以中心机为准) |
|
||||
| `POST /api/device/report` | X-API-Token | `{device_id, account, hostname, os, ip, chrome_installed(0/1), chrome_version, chrome_ok(0/1), status(0/1)}` | `{ok}`(**注意 int 0/1 语义**) |
|
||||
|
||||
### 5.5 配置备份与恢复(定时任务)
|
||||
| 接口 | 鉴权 | 请求 | 响应 |
|
||||
|---|---|---|---|
|
||||
| `POST /api/schedules/backup` | Bearer/X-Admin-Token/X-Admin-User | `{data:{schedules:[...]}}`(该账号全量配置) | `{ok, account}` |
|
||||
| `GET /api/schedules/backup` | 同上 | — | `{data:{schedules:[...]}}`(无备份返回 `{data:{schedules:[]}}`) |
|
||||
|
||||
### 5.6 壳子与大文件源
|
||||
| 接口 | 鉴权 | 说明 | 响应 |
|
||||
|---|---|---|---|
|
||||
| `GET /api/shell/version` | X-API-Token | 壳子版本比对 | `{available, version, filename, url, sha256, notes}`;`url` 为空则回退 `GET /api/shell/pkg` |
|
||||
| `GET /api/shell/pkg` | X-API-Token | 壳子安装包下载 | 文件流(404 表示未配置) |
|
||||
| `GET /api/file-sources/{category}` | X-API-Token | 某类别最新启用大文件源(如 chrome/shell) | `{available, category, version, filename, url, sha256, notes}`;无则 `{available:false, category}` |
|
||||
|
||||
### 5.7 钉钉扫码登录(代理链路)
|
||||
| 接口 | 鉴权 | 说明 |
|
||||
|---|---|---|
|
||||
| `GET /api/dingtalk/login-url` | X-API-Token | 服务端构造扫码 URL(含回跳 `back`) |
|
||||
| `GET /api/admin/dingtalk/scan?back=` | X-API-Token | 扫码页重定向到 `cb` |
|
||||
| `GET /api/admin/dingtalk/cb` | 公开 | 回调 → 前端拿 `loginTmpCode` |
|
||||
| `POST /api/admin/dingtalk/sns` | Bearer/公开 | `{code}` → 换身份(`_dingtalk_userinfo`) |
|
||||
| `POST /api/admin/dingtalk/auth` | X-API-Token | 账号同步/建号(响应多 token 字段,客户端可不消费) |
|
||||
|
||||
### 5.8 管理台接口(新客户端登录态可复用,简述)
|
||||
- `GET /api/admin/me`:`{account, is_admin, dept, nickname, avatar, must_change_pwd}`
|
||||
- `GET /api/admin/overview`:`{plugins:[{id,name,latest_version,versions[],status}], accounts:[{account,nickname,dept,status,plugins:[]}], admins:[...]}`(已瘦身,删了 per-plugin accounts/grants、per-account grants/platforms)
|
||||
- 分页列表:`/api/admin/accounts|plugins|audit|reports|creds/manage|file-sources`(`{items,total}`,audit 带 `today`、reports 带 `today/failed`)
|
||||
- 授权:`GET /api/admin/grant_data`(`{plugins:[{id,name,status}], accounts:[{account,nickname,dept,status}]}`,**status=1 含管理员**)、`GET /api/admin/account_grants?account=x`(`{plugins:[{plugin_id,canRun,canDownload}], platforms}`)
|
||||
- 头像:`GET /api/avatar/{account}`(文件流,404=未设置)、`POST /api/admin/avatar`(multipart file + account,需 Authorization 或 X-Admin-Token,仅 5 种图片格式 ≤2MB)
|
||||
- 其余:`POST /api/admin/account|account/update|account/reset_pwd|account/delete|account_plugins|account_platforms|pkg|plugin/delete|plugin/patch|creds/seed`、`GET /api/admin/creds`(仅管理员,`{creds:{key:base64}}`)、`GET /api/admin/platforms`(`{platforms:[{id,label}]}`,当前 hr/oa)、`GET /api/admin/stats`(camelCase:total/today/failed/trend/topPlugins/topUsers)、`POST /api/admin/shell-release`、`GET /api/admin/fileserver/status`、`POST /api/fileserver/heartbeat`
|
||||
|
||||
### 5.9 契约验证记录(本会话实测)
|
||||
- 真实 token 实测通过:`/api/plugins`、`/api/platforms/allowed`、`/api/me/control-list`、`/api/shell/version`、`/api/file-sources/chrome|shell`、`/api/schedules/backup`(鉴权正常)、`/api/admin/me`
|
||||
- 有效管理员票据实测通过(SQL 执行层):audit(空/动作+q)、reports(空/多值状态 done,success/q)、accounts(空/q)、plugins(空/q)、grant_data、account_grants
|
||||
- 静态核对通过:download-ticket、/api/download、creds/register、creds GET、runtime/report、license、dingtalk 转发
|
||||
|
||||
---
|
||||
|
||||
## 6. 现 Python 客户端(webhost)参考实现 —— Node 版能力对照
|
||||
|
||||
> Node 版需逐项对齐以下能力。实现参考各文件,**契约以 §5 为准**。
|
||||
|
||||
| Node 版需要的能力 | 现 Python 实现(参考) | 关键逻辑 |
|
||||
|---|---|---|
|
||||
| 配置加载 | `core/config.py` | `.env` 仅本模块;`CONTROLPLANE_URL/ACCOUNT/TOKEN`;本机端口 8799;插件配置目录 `%LOCALAPPDATA%/37duAutomation/plugin_configs` |
|
||||
| 插件清单拉取 | `core/plugin_sync.py` | `GET /api/plugins?account=` + 本地 `plugins/<id>/plugin.json` 版本比对 → download-ticket → 下载 → sha256 校验 → 临时目录原子替换安装 |
|
||||
| 授权票据 | `core/cpapi.py`、`core/licensing.py` | `GET /api/me/license` + `control-list`(联网刷新,7 天窗口);离线验签(Ed25519)后按 `canRun` 放行;`POST /api/runtime/report` 同步上报 |
|
||||
| 敏感凭证 | `core/creds_sync.py` | 上报本机 RSA 公钥(`register`)→ `GET /api/admin/creds` 拉 `{key:base64}` → 本机私钥 OAEP 解密 → 缓存密文落盘;白名单键:`DINGTALK_APPKEY/APPSECRET/AGENT_ID/CORP_ID` |
|
||||
| 定时任务 | `core/tasks.py` | 本地 cron 调度 + 增删改后 `POST /api/schedules/backup` 全量推送;启动时 `GET` 合并恢复(按 account 过滤) |
|
||||
| 壳子自更新 | `core/shell_updater.py` | 启动/每 30 分钟 `GET /api/shell/version` 比对 → `url` 直链或 `GET /api/shell/pkg` 下载 → 静默安装 → 重启 |
|
||||
| Chrome 检测 | `core/chrome_manager.py` | `GET /api/file-sources/chrome` 内网直链下载安装包 + `POST /api/device/report` 上报环境 |
|
||||
| 钉钉扫码 | `core/meta.py`、`apis/dingtalk.py` | 经 `GET /api/dingtalk/login-url` 构造 URL → 本地浏览器扫码 → `/api/admin/dingtalk/sns` 换身份;平台登录走本地 `platform_accounts` 加密存储 |
|
||||
| 会话管理 | `core/session.py` | 云端 token 进程内存态(重启需重新登录);登录时 `POST /api/admin/auth` 拿 `cloud_token` |
|
||||
| 本机 HTTP | `backend/apis/*` | 壳 UI 本地 API:`/api/meta`(聚合)、`/api/runs`(+stop)、`/api/plugins/sync`、`/api/shell/check|download|apply|update-status`、`/api/chrome/*`、`/api/platforms/{pid}/login|logout`、`/api/plugin-config/{pid}`、`/api/admin/me|login|logout|password|overview`(转发中心机)、`/api/avatar` |
|
||||
| 插件运行 | `core/runner.py`、`plugins/base.py` | 手动/定时共用入口;`run_id → Job` 句柄支持整树强杀(含浏览器孙进程);插件接口契约在 `webhost/backend/plugins/base.py` |
|
||||
|
||||
---
|
||||
|
||||
## 7. 关键数据流场景(新客户端必须覆盖)
|
||||
|
||||
1. **首次启动**:读 .env → 无会话则显示登录(账号密码或钉钉扫码)→ 登录拿 cloud_token → 拉插件清单 → 同步安装 → 拉授权票据/管控清单 → 定时任务合并恢复 → Chrome/设备上报 → 进入主界面。
|
||||
2. **登录(钉钉)**:`/api/dingtalk/login-url`(服务端构造,含 back)→ 本地开浏览器扫码 → 服务端 cb → 前端拿 code → `/api/admin/dingtalk/sns` 换身份(或壳直连 `/auth/exchange`)→ 存 token;新号自动创建 + 强制改密。
|
||||
3. **插件同步**:清单 diff → 缺/旧 → download-ticket → 下载 → sha256 → 原子替换 → 更新 plugin.json;被 revoke/disable 的插件按管控清单停用/移除。
|
||||
4. **运行上报**:start(触发) → running(中间态) → done/error(终态);`duration_sec` 以秒计;离线补报。
|
||||
5. **离线授权**:license 票据 7 天窗口,超时须联网刷新;每次刷新重置窗口;管控清单同窗口携带。
|
||||
|
||||
---
|
||||
|
||||
## 8. 开发规范(AGENTS.md 强制,勿违反)
|
||||
|
||||
- 运行统一 `.venv`(D:\work\code\37duAutomation\.venv),禁止沙箱/容器环境。
|
||||
- 三端零依赖:Node 客户端独立目录,**不 import** controlplane/webhost/plugins 任何代码;数据层各自内置。
|
||||
- `.env` 按模块隔离:各端只读自己目录下的 `.env`。
|
||||
- 发版走 `python -m controlplane.tools.agent_cli`(插件 publish/grant/revoke;壳子 file push --category shell)。
|
||||
- 写文件操作走正常文件系统(当前会话 danger-full-access,approval 关闭)。
|
||||
- Node 客户端如需服务端支持新能力:**优先走现有公开接口**;确需新增接口时提交服务端变更 + 同步契约表(§5)+ 前后端同步部署(见 SOP)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 已知问题 / 待办(P2 级,不阻断)
|
||||
|
||||
- 服务端 `overview` 仍是全量聚合(N+1 少量查询),概览页低频可接受;如需优化可做聚合缓存。
|
||||
- `audit`/`reports` 表数据增长后建议加索引(`at`、`status`);`download_tickets` 已有 TTL 清理。
|
||||
- `device/report` 已实现但旧 webhost 无调用方——Node 版应接入(心跳 + Chrome 环境上报)。
|
||||
- 钉钉扫码链路 `sns`/`inline_qr` 服务端不强制鉴权,客户端携带无害;`/auth/exchange` 为无头直连(公开)。
|
||||
- CORS 白名单默认 `http://127.0.0.1:8090,http://localhost:8090`,公网部署用 `CORS_ALLOW_ORIGINS` 配置实际来源(同域反代则不受影响)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 关键文件速查
|
||||
|
||||
| 需求 | 文件 |
|
||||
|---|---|
|
||||
| 部署步骤 | [docs/部署/服务端前后端部署SOP.md](../部署/服务端前后端部署SOP.md) |
|
||||
| 插件发版 | [docs/插件/发版规范.md](../插件/发版规范.md) |
|
||||
| 插件开发规范 | [docs/插件/插件开发规范.md](../插件/插件开发规范.md) |
|
||||
| 壳子发版 | [docs/桌面端/桌面端发版SOP.md](桌面端发版SOP.md) |
|
||||
| 客户端设计评估 | [docs/架构/桌面客户端设计.md](../架构/桌面客户端设计.md) |
|
||||
| **客户端产品化差距分析** | [docs/桌面端/客户端产品化差距分析.md](客户端产品化差距分析.md)(P0/P1/P2 清单 + 环境包设计,后续会话从这里接着做) |
|
||||
| **环境包构建脚本** | `desktop/electron-shell/scripts/build-python-env.ps1`(产物 `dist-env/python-env-<ver>.zip`) |
|
||||
| **环境包客户端模块** | `desktop/electron-shell/electron/env-sync.js`(下载/切换/回滚);`config.js` 的 `pythonEnvRoot/pythonExe/jobGuardScript` |
|
||||
| 服务端路由全集 | `desktop/controlplane/apis/*.py`(每个文件头有职责说明) |
|
||||
| 统一分页 | `desktop/controlplane/core/paging.py` |
|
||||
| 前端统一分页 | `desktop/controlplane/frontend/src/composables/usePagedList.js` + `components/PagerBar.vue` |
|
||||
| 旧客户端 API 调用全集 | `desktop/webhost/backend/core/{cpapi,plugin_sync,creds_sync,shell_updater,chrome_manager,meta,licensing,tasks}.py` |
|
||||
| 插件接口契约 | `desktop/webhost/backend/plugins/base.py` |
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user