feat(xq0002): 新增HR自动导入功能,优化花名册源表新鲜度校验
``` 或者更贴合中文项目习惯的表述: ```msg feat(xq0002): 新增HR自动导入,优化花名册源表新鲜度校验
This commit is contained in:
@@ -14,21 +14,22 @@ AI 智能体开发约束 & 项目执行规范
|
||||
3. 项目通用架构规范
|
||||
- 代码组织:不同业务、不同流程独立模块化运行,互不侵入、互不影响。
|
||||
- 各方向零依赖:项目并存多个独立演进方向,彼此【绝不跨目录 import】,登录/数据导出等数据层各自内置(允许少量重复换取完全解耦),任一方向可单独拷贝、单独演进、独享依赖与启动:
|
||||
- 桌面端 desktop/:中心机 desktop/controlplane/ + 执行机 desktop/webhost/,两者互不 import、独立演进、可单独拷贝(模块搜索根 = desktop/,运行均以 desktop/ 为 cwd)。
|
||||
- 插件 plugins/:根级独立目录(按号段分桶 plugins/XQ0001-0100/),被执行机按账号权限自下载加载,不随 webhost 发布。
|
||||
- 桌面端 desktop/:中心机 desktop/controlplane/ + 执行机桌面壳 desktop/electron-shell/(当前宿主,Electron + Node,内置便携 python 环境 python-env/<版本>/ 跑插件)+ 老版执行机底座 desktop/webhost/(标记老版本、后续废弃、不再维护)。各自互不 import、独立演进、可单独拷贝(模块搜索根 = desktop/,运行均以 desktop/ 为 cwd)。
|
||||
- 插件 plugins/:根级独立目录(按号段分桶 plugins/XQ0001-0100/),被执行机(electron-shell 壳)按账号权限自下载加载,不随底座发布。
|
||||
- 影刀版 workflows/:单文件自包含,需求脚本按号段分桶(workflows/XQ0001-0100/)。
|
||||
- app/ 蓝图版:已弃用,保留归档、不再维护。
|
||||
- 代码形态分三类,按各方向性质采用不同组织方式(【单文件自包含】仅适用于影刀版,其它一律按正常项目开发):
|
||||
- workflows/(影刀版):沿用单文件自包含架构(见第 2 节,仅影刀适用)。
|
||||
- 桌面端各后端(desktop/controlplane/ 中心机、desktop/webhost/ 执行机底座):按正常 Python 模块化项目开发,允许按包/模块/多文件拆分(如 main.py/app.py 分割逻辑与路由),不做单文件约束。
|
||||
- 桌面端各后端(desktop/controlplane/ 中心机、desktop/electron-shell/ 执行机壳、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 等)
|
||||
- desktop/webhost/ → desktop/webhost/.env(老版执行机底座配置,后续废弃);当前宿主 desktop/electron-shell/ 无独立 .env,配置在 electron/config.js,数据根 %LOCALAPPDATA%\37duAutomation
|
||||
- app/ → app/.env(app 版业务配置,已弃用)
|
||||
- workflows/ 影刀不再单独建 .env,所需配置统一放在根 .env。
|
||||
- 各模块加载器只允许读取本模块目录下的 .env,禁止读取/改写其它模块或根 .env。
|
||||
- 插件本地配置(当前宿主 electron-shell):明文 JSON,路径 %LOCALAPPDATA%\37duAutomation\plugin_configs\<插件id>.json,electron-shell/electron/runner.js 直接 JSON.parse 读取、无加密解密(登录类插件需自行清洗首尾空白防误存空格导致"密码不正确"累计触发平台锁定);旧 SQLite 场景配置(plugin_configs 表,enc:v1: AES-256-GCM 加密)是另一套,不参与插件执行参数注入。
|
||||
- 错误处理:全局项目级重试机制,最大重试 3 次,三次失败后再记录错误日志。
|
||||
- 日志规范:正常 INFO 级别屏蔽大体积 JSON 调试日志,保证日志整洁;仅 DEBUG 模式开启完整 JSON 调试信息输出。
|
||||
4. AI 工作默认规则
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// 自动 rebuild 为 Electron ABI,产物无需额外处理。
|
||||
"use strict";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const Database = require("better-sqlite3");
|
||||
const config = require("./config");
|
||||
|
||||
@@ -1,72 +1,17 @@
|
||||
// 场景配置方案(多配置)· SQLite 实现:同一场景可保存多套命名参数组合,运行台/定时任务按需选用。
|
||||
// 表:plugin_configs(shell.db),按账号 + 插件隔离,同名覆盖。
|
||||
// 安全:password 类型字段 AES-256-GCM 加密落盘(本机 MachineGuid 派生密钥,换机密文失效),
|
||||
// 每套方案可绑定不同账号密码,定时任务到点直接用方案字段执行。
|
||||
// 安全:password 字段一律**明文落盘**——不做任何加解密,避免换机/密钥异常导致密码解析出错、
|
||||
// 平台连续密码错误锁号;旧版本 enc:v1 密文数据不兼容,密码需在界面重新保存方案。
|
||||
"use strict";
|
||||
|
||||
const crypto = require("crypto");
|
||||
const { execSync } = require("child_process");
|
||||
const { db } = require("./db");
|
||||
|
||||
const MAX_CONFIGS_PER_PLUGIN = 10; // 单插件最多 10 套方案,防异常堆满
|
||||
const ENC_PREFIX = "enc:v1:"; // 密文字段标记(iv12 + ct + tag16 → base64)
|
||||
|
||||
// ---- 本机绑定加解密(MachineGuid 派生密钥,进程内缓存)----
|
||||
let _key = null;
|
||||
function secretKey() {
|
||||
if (_key) return _key;
|
||||
let guid = "";
|
||||
try {
|
||||
const out = execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid', { encoding: "utf8" });
|
||||
guid = (/MachineGuid\s+REG_SZ\s+(\S+)/.exec(out) || [])[1] || "";
|
||||
} catch (_) { /* 读不到时密钥退化为纯盐(仅本机临时可用) */ }
|
||||
_key = crypto.createHash("sha256").update(`37du-plugin-cfg:${guid}`).digest();
|
||||
return _key;
|
||||
}
|
||||
|
||||
function encVal(v) {
|
||||
if (typeof v !== "string" || !v || v.startsWith(ENC_PREFIX)) return v;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const c = crypto.createCipheriv("aes-256-gcm", secretKey(), iv);
|
||||
const ct = Buffer.concat([c.update(v, "utf8"), c.final(), c.getAuthTag()]);
|
||||
return ENC_PREFIX + Buffer.concat([iv, ct]).toString("base64");
|
||||
}
|
||||
|
||||
function decVal(v) {
|
||||
if (typeof v !== "string" || !v.startsWith(ENC_PREFIX)) return v;
|
||||
try {
|
||||
const buf = Buffer.from(v.slice(ENC_PREFIX.length), "base64");
|
||||
const iv = buf.subarray(0, 12);
|
||||
const tag = buf.subarray(buf.length - 16);
|
||||
const ct = buf.subarray(12, buf.length - 16);
|
||||
const d = crypto.createDecipheriv("aes-256-gcm", secretKey(), iv);
|
||||
d.setAuthTag(tag);
|
||||
return Buffer.concat([d.update(ct), d.final()]).toString("utf8");
|
||||
} catch (_) {
|
||||
return ""; // 换机/密文损坏:解不出当空值,避免把密文当密码用
|
||||
}
|
||||
}
|
||||
|
||||
// password 类型字段加密落盘(已加密值幂等跳过);schema = 插件的 fields 元数据
|
||||
function encryptSecrets(fields, schema) {
|
||||
const secret = new Set(
|
||||
(Array.isArray(schema) ? schema : [])
|
||||
.filter((f) => f && f.type === "password")
|
||||
.map((f) => f.key)
|
||||
);
|
||||
const out = {};
|
||||
for (const [k, v] of Object.entries(fields || {})) {
|
||||
out[k] = secret.has(k) ? encVal(v) : v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function rowToCfg(row) {
|
||||
if (!row) return null;
|
||||
let raw = {};
|
||||
try { raw = JSON.parse(row.fields || "{}"); } catch (_) { raw = {}; }
|
||||
const fields = {};
|
||||
for (const [k, v] of Object.entries(raw)) fields[k] = decVal(v); // 按 enc 前缀解密
|
||||
let fields = {};
|
||||
try { fields = JSON.parse(row.fields || "{}"); } catch (_) { fields = {}; }
|
||||
return { id: String(row.id), name: row.name, fields, at: row.at || "" };
|
||||
}
|
||||
|
||||
@@ -86,10 +31,11 @@ function getConfig(account, pluginId, cfgId) {
|
||||
}
|
||||
|
||||
// 保存/覆盖:同名方案更新字段,否则新增;返回新/更新后的配置
|
||||
// (fields 原样明文落盘,schema 参数保留仅为兼容旧调用方)
|
||||
function saveConfig(account, pluginId, name, fields, schema) {
|
||||
const trimmed = String(name || "").trim().slice(0, 20);
|
||||
if (!trimmed) return null;
|
||||
const keep = encryptSecrets(fields, schema);
|
||||
const keep = fields || {};
|
||||
const at = new Date().toLocaleString("zh-CN", { hour12: false });
|
||||
const exists = db.prepare(
|
||||
"SELECT id FROM plugin_configs WHERE account = ? AND plugin_id = ? AND name = ?"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "37du-electron-shell",
|
||||
"productName": "37du 自动化工作台",
|
||||
"version": "1.0.3",
|
||||
"version": "1.0.5",
|
||||
"description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)",
|
||||
"main": "electron/main.js",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
# 插件 UI 开发规范
|
||||
|
||||
> 本规范定义带前端界面插件的统一开发标准:技术栈、目录结构、公共 kit(usePluginUI)契约、
|
||||
> App.vue 标准骨架、panel 样式契约、构建与打包流程。
|
||||
> 与总规范 [插件开发规范.md](./插件开发规范.md) §3(前端存放位置)配套阅读;新写/改造插件 UI 一律照此执行。
|
||||
> **推荐做法:从参考插件复制 ui-src 整目录 → 改 `api.js` 的 PLUGIN_ID、`vite.config.js` 的 base/端口、
|
||||
> `App.vue` 的表单与默认值 → 构建 → 打包。**
|
||||
|
||||
## 1. 适用范围与「是否做 UI」判断
|
||||
|
||||
- 适用对象:`plugin.json` 声明 `"ui": true` 的插件(界面由底座托管到 `/pui/<id>/`,经壳子 iframe 内嵌)。
|
||||
- 参数能由 `plugin.json.fields` 通用表单承载(text/select/int/password/enum)→ **不做 UI**(`"ui": false`)。
|
||||
- 需要「记住账号密码」「动态联动」「自定义交互」「多配置方案」→ **做 UI**(`"ui": true`)。
|
||||
- 带 UI 插件仍须在 `plugin.json.fields` 完整声明字段(JSON Schema):
|
||||
fields 是**权威契约**(定时任务注入、后端校验依赖它),UI 表单只是它的可视化编辑器。
|
||||
|
||||
## 2. 技术栈与版本(锁定,勿随意升级)
|
||||
|
||||
| 依赖 | 版本 | 说明 |
|
||||
|------|------|------|
|
||||
| vue | ^3.5.13 | `<script setup>` 组合式 API |
|
||||
| element-plus | ^2.14.5 | 组件库(全量引入,产物自包含) |
|
||||
| @element-plus/icons-vue | ^2.3.2 | 图标(当前版式用内联 SVG,可不装新依赖) |
|
||||
| vite | ^6.0.3 | 构建 |
|
||||
| @vitejs/plugin-vue | ^5.2.1 | Vue 插件 |
|
||||
|
||||
- `package.json` 需保留 `"allowScripts": {"esbuild@0.25.12": true}`(npm 允许 esbuild 安装脚本)。
|
||||
- 运行期零外部依赖:构建产物自包含,界面运行不加载任何 CDN/外部资源。
|
||||
|
||||
## 3. ui-src 目录结构与文件职责
|
||||
|
||||
```
|
||||
plugins/<号段桶>/<插件目录>/ui-src/
|
||||
├── index.html # 入口页(<title> = 插件中文名)
|
||||
├── package.json # name = <id>-ui;依赖版本见上表
|
||||
├── vite.config.js # base / outDir / dev 端口 / proxy(见 §6)
|
||||
└── src/
|
||||
├── main.js # createApp + ElementPlus 全量注册 + import 'element-plus/dist/index.css'
|
||||
├── api.js # 仅一行:export const PLUGIN_ID = '<id>'
|
||||
├── usePluginUI.js # 公共 kit(vendored 副本,勿改逻辑!见 §4)
|
||||
└── App.vue # 插件差异部分:表单字段、DEFAULTS、validate、布局(见 §5)
|
||||
```
|
||||
|
||||
- `ui/`(构建产物,`npm run build` 输出到 `../ui/`):**勿手改**;随包发布、底座托管。
|
||||
- `ui-src/`:开发目录;打包时被 `_pack.py` 排除,不进发布包。
|
||||
|
||||
## 4. usePluginUI 公共 kit 契约
|
||||
|
||||
kit 收敛三块通用逻辑,App.vue 只写差异:①本机当前配置(加载/防抖自动保存/恢复默认)
|
||||
②多配置方案(列表/应用/存为方案/删除,供壳子「定时任务」按 config_id 引用)③执行状态机
|
||||
(一键执行/强制停止/WS 实时进度+轮询兜底/未登录重试)。
|
||||
|
||||
### 4.1 调用签名
|
||||
|
||||
```js
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS, // 必传:默认表单工厂;恢复默认时收到当前表单作参考(联动默认值)
|
||||
validate() { ... }, // 可选:执行前校验,失败自行 ElMessage 提示并 return false
|
||||
buildPayload(form) {}, // 可选:定制提交参数(缺省 = 表单全量深拷贝)
|
||||
})
|
||||
```
|
||||
|
||||
### 4.2 内置行为(App.vue 不要重复实现)
|
||||
|
||||
- **自动保存**:表单变更防抖 800ms 后 POST 保存到本机;执行中不保存;头部「已保存 HH:MM:SS」胶囊由 `lastSavedAt` 驱动。
|
||||
- **合并规则(mergeSaved)**:载入已存配置时,标量空值(''/null/undefined)不覆盖默认值,
|
||||
数组照原样应用(空数组可能是有意配置,如「留空=不筛选」)。
|
||||
- **方案**:同名覆盖;单插件上限 10 套;密码等敏感字段**明文保存**(见 §4.3);
|
||||
应用方案 = mergeSaved 进表单再自动保存;执行永远提交表单当前值。
|
||||
- **执行**:`run()` 内部顺序 = 未登录重试 → validate → saveNow → startRun → 连 WS → 5s 轮询兜底;
|
||||
WS 只认本次 run_id 的 `progress`/`run_done` 事件;完成/失败经 `banner` 展示。
|
||||
- **未登录**:任意接口 401 → `needLogin=true`,横幅提示先在壳子登录;执行时先重试一次配置读取再拦截。
|
||||
|
||||
### 4.3 后端 API(kit 已封装,同源 cookie 自动携带)
|
||||
|
||||
| 端点 | 方法 | 用途 |
|
||||
|------|------|------|
|
||||
| `/api/plugin-config/<id>` | GET / POST | 当前配置读取 / 保存(本机明文 JSON) |
|
||||
| `/api/plugin-configs?plugin_id=` | GET | 方案列表 |
|
||||
| `/api/plugin-configs` | POST | 存方案 `{plugin_id, name, fields}`(同名覆盖) |
|
||||
| `/api/plugin-configs/<pluginId>/<cfgId>` | DELETE | 删方案 |
|
||||
| `/api/runs` | POST | 启动 `{plugin_id, fields}` → `{run_id}` |
|
||||
| `/api/runs/<runId>` | GET | 运行状态(轮询兜底) |
|
||||
| `/api/runs/<runId>/stop` | POST | 强制停止(整树强杀执行子进程) |
|
||||
| `/ws` | WebSocket | 实时进度 `progress` / 结束 `run_done` |
|
||||
|
||||
**密码存储口径(全局统一)**:password 类字段一律**明文落盘**(方案存 SQLite `plugin_configs` 表、
|
||||
当前配置存 `%LOCALAPPDATA%\37duAutomation\plugin_configs\<id>.json`),后端不做任何加解密——
|
||||
加密曾因换机/密钥异常导致密码解析出错、平台连续密码错误锁号,已废弃;
|
||||
旧版本 `enc:v1:` 密文数据不兼容,密码需在界面重新保存方案。
|
||||
插件侧责任:登录类插件自行清洗输入首尾空白,防止误存空格导致「密码不正确」累计锁号。
|
||||
|
||||
## 5. App.vue 标准骨架(五段式)与表单约定
|
||||
|
||||
模板五段**顺序与结构固定**(完整样例见参考插件),差异只在分区内容:
|
||||
|
||||
```text
|
||||
① 横幅区 <transition name="fade-slide"> + el-alert
|
||||
needLogin(未登录警告,不可关)/ banner(执行结果,可关)
|
||||
② 卡片头部 el-card.shadow="never" .panel → #header .panel-head
|
||||
.panel-title:.title-ico(内联 SVG 图标)+ .title-txt「执行配置」+ .title-sub 副标题
|
||||
.head-tools:.saved 已保存胶囊 + 方案下拉 + 存为方案 + 删除(方案工具条,一律保留)
|
||||
③ 分区表单 <el-form label-position="top">
|
||||
.sec → .sec-head(.sec-badge 01/02/03… + .sec-name + .sec-line)+ .grid
|
||||
④ 操作区 .actions:btn-run 一键执行(执行中显示「执行中 N%」)+ 强制停止(running 时)
|
||||
+ .spacer + 保存配置 saveNow(true) + 恢复默认 resetDefaults
|
||||
⑤ 运行状态 <transition name="fade-slide"> + .status:el-progress(show-text=false) + .pulse + .status-pct
|
||||
```
|
||||
|
||||
表单/字段约定:
|
||||
|
||||
- **字段名必须与 `plugin.json.fields.properties` 完全一致**,保证已保存配置与定时任务引用向后兼容;
|
||||
改字段名 = 破坏性变更,须升版本并在描述中说明。
|
||||
- `DEFAULTS` 工厂值与 fields 的 `default` 保持一致;占位符/提示写清「留空=」语义(如「留空=今天」)。
|
||||
- 密码输入用 `el-input show-password`;提交流程产生的清洗(trim)放在 validate 或 buildPayload。
|
||||
- 开关类字段用 `el-switch`,放入 `.grid.grid-switch`(紧凑栅格);需解释的开关在分区尾部加 `.tip`。
|
||||
- `validate()` 用 `ElMessage.warning` 给出可操作的错误提示,返回 `false` 阻断执行。
|
||||
- 执行中禁用所有输入(`:disabled="running"`),避免执行期间改动参数。
|
||||
|
||||
## 6. 样式契约(panel 标准风格)
|
||||
|
||||
统一 CSS 块(page / fade-slide / panel / panel-head / title-ico / saved / sec / sec-badge /
|
||||
grid / grid-switch / tip / actions / btn-run / status / pulse)**从参考插件 App.vue 原样复制**,
|
||||
不要自创版式;只允许按需增改个别类(如 XQ0002 的 `.grid-switch`)。
|
||||
|
||||
- **无边框平铺**:`.panel` 背景透明、无边框无阴影、圆角 0——外层由壳子 iframe 统一包边框。
|
||||
- **颜色只用 Element Plus CSS 变量**(`--el-color-primary*`、`--el-text-color-*`、`--el-border-color*`),
|
||||
硬编码色值仅限功能性小元素(如 .saved 的绿色胶囊)。
|
||||
- **主按钮**:`.btn-run` 渐变背景 + 阴影 + hover 位移,`min-width: 150px`。
|
||||
- **动效**:横幅/状态区 fade-slide(0.25s 上下淡入位移)、运行中 `.pulse` 呼吸点。
|
||||
- **栅格**:表单 `repeat(auto-fit, minmax(280px, 1fr))`;开关区 `minmax(210px, 1fr)` + `row-gap: 14px`。
|
||||
|
||||
## 7. vite 配置、构建与联调
|
||||
|
||||
`vite.config.js` 固定模式(仅三处按插件替换):
|
||||
|
||||
```js
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/<id>/', // ← 插件 id(底座托管路径,必须一致)
|
||||
build: { outDir: '../ui', emptyOutDir: true },
|
||||
server: {
|
||||
port: 5180, // ← dev 端口:默认 5180,与本机其它插件联调冲突时改为独立端口(如 5181)
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true }, // 壳子本地服务
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
- **构建**:`ui-src/` 下 `npm install`(首次)→ `npm run build`,产物输出 `../ui/`(index.html + hash 资源)。
|
||||
- **联调**:壳子运行中,`npm run dev` 后浏览器开 `http://localhost:<端口>/`,页面内配置经 proxy 持久化到
|
||||
本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\<id>.json`;未登录时页面显示登录横幅属正常。
|
||||
- **顺序铁律**:改了 ui-src 必须先 `npm run build` 再 `_pack.py`——`_pack.py` 校验 `ui/index.html`
|
||||
存在,打包的是构建产物而非源码。
|
||||
|
||||
## 8. kit 同步规则(vendored 副本,MD5 必须一致)
|
||||
|
||||
- kit 是**构建期内联**(vendored 进各插件 ui-src),跨插件不共享运行时——允许源码级重复换取插件零依赖。
|
||||
- 当前带 UI 插件共 4 个:`xq0002`、`xq0011`、`xq0031_xq0032`、`xq0045_xq0046`。
|
||||
- **改 kit 流程**:任选一个插件改 `usePluginUI.js` → 复制到其余 3 个插件同路径(二进制复制,保证
|
||||
MD5 一致)→ 4 个插件全部 `npm run build` → 全部重新打包。禁止只改一个插件。
|
||||
- `api.js` 同理:只有 `PLUGIN_ID` 一行,各插件不同,但文件格式保持一致。
|
||||
|
||||
## 9. 自检清单(UI 开发完成后)
|
||||
|
||||
- [ ] `api.js` 的 PLUGIN_ID 与 `plugin.json.id` 一致;`vite.config.js` 的 base = `/pui/<id>/`
|
||||
- [ ] App.vue 字段名与 `plugin.json.fields.properties` 完全一致;DEFAULTS 与 fields.default 一致
|
||||
- [ ] 五段式结构齐全,方案工具条保留(方案下拉/存为方案/删除)
|
||||
- [ ] 样式块从参考插件复制,未自创版式;颜色只用 Element Plus CSS 变量
|
||||
- [ ] `npm run build` 后 `ui/index.html` 已更新(hash 文件名变化)
|
||||
- [ ] 若改过 kit:4 个插件 usePluginUI.js MD5 一致,且全部已重建重打包
|
||||
- [ ] `_pack.py` 打包成功(ui-src 未进包);发版走发版规范 agent CLI
|
||||
- [ ] 密码类字段:明文口径(界面提示不出现「加密」字样)、输入已做 trim 清洗
|
||||
|
||||
## 10. 参考实现
|
||||
|
||||
| 插件 | 特点 | 适合参考 |
|
||||
|------|------|----------|
|
||||
| `xq0002` 雇主险增减操作 | 纯参数表单 + 5 开关(panel 风格标准版) | 标准五段式骨架、grid-switch 开关区 |
|
||||
| `xq0011` 考勤月报封存检查 | 常规表单 | 标准骨架同款 |
|
||||
| `xq0031_xq0032` 物料收发与采购订单导出 | `defaults(cur)` 联动默认值(按 erp_system 带出组织/仓库) | 联动默认、登录区 |
|
||||
| `xq0045_xq0046` 金色印象通联数据导出 | `buildPayload` 按模式裁剪、动态默认日期(昨天/上月) | 提交裁剪、日期处理 |
|
||||
|
||||
> 新插件首选:复制 `xq0002/ui-src`(最干净的标准版)起步。
|
||||
+7
-4
@@ -67,6 +67,9 @@ plugins/
|
||||
|
||||
## 3. 前端(UI)存放位置
|
||||
|
||||
> 带 UI 插件的完整开发标准(技术栈、usePluginUI kit 契约、App.vue 五段式骨架、panel 样式契约、
|
||||
> 构建打包流程)见 **[插件UI开发规范.md](./插件UI开发规范.md)**;本节只约定存放位置与判断标准。
|
||||
|
||||
底座的插件前端约定(`webhost/backend/apis/plugin_ui.py`):带 UI 插件在 `plugin.json` 声明
|
||||
`"ui": true`,底座将插件包内 `ui/` 目录静态托管到 `/pui/<id>/`。
|
||||
|
||||
@@ -98,9 +101,9 @@ ui-src/src/
|
||||
`defaults(cur)` 工厂在「恢复默认」时会收到当前表单(可按当前选项带出联动默认值);
|
||||
`buildPayload(form)` 可裁剪提交参数(缺省 = 表单全量)。
|
||||
- App.vue 模板统一保留「执行配置」卡片头部的**方案工具条**(方案下拉 + 存为方案 + 删除):
|
||||
方案经 `/api/plugin-configs` 保存到本机(同名覆盖;password 类字段 AES-256-GCM 加密落盘,
|
||||
本机 MachineGuid 派生密钥、换机失效——每套方案可绑定不同账号),供壳子「定时任务」按
|
||||
`config_id` 引用,到点直接取方案最新参数执行;未选方案 = 插件当前保存的配置。
|
||||
方案经 `/api/plugin-configs` 保存到本机(同名覆盖;password 类字段**明文落盘**,后端不做
|
||||
加解密——加密曾因换机/密钥异常导致密码解析出错、平台锁号,已废弃;每套方案可绑定不同账号),
|
||||
供壳子「定时任务」按 `config_id` 引用,到点直接取方案最新参数执行;未选方案 = 插件当前保存的配置。
|
||||
- kit 是**构建期内联**(vendored 进各插件 ui-src,产物自包含),跨插件不共享运行时——
|
||||
允许源码级重复换取插件零依赖(与后端分层取舍一致)。
|
||||
|
||||
@@ -223,7 +226,7 @@ PLUGINS.append(MyPlugin())
|
||||
|
||||
| 插件 | 形态 | 可参考点 |
|
||||
|------|------|----------|
|
||||
| `xq0011` | 无 UI,四层结构(config/data/logic/report) | 分层结构、config 全局钩子、跨模块相对导入、单工作簿输出 |
|
||||
| `xq0011` | 带 UI(公共 kit + 方案管理),后端四层结构 | 后端分层结构、config 全局钩子、跨模块相对导入、单工作簿输出 |
|
||||
| `xq0002` | 带 UI(公共 kit + 方案管理) | `usePluginUI` kit 接入、多开关表单、方案工具条标准形态 |
|
||||
| `xq0031_xq0032` | 带 UI(公共 kit + 方案管理) | 前端构建流程、`defaults(cur)` 联动默认值、dist-plugin 打包 |
|
||||
| `xq0045_xq0046` | 带 UI(公共 kit + 方案管理) | `buildPayload` 按模式裁剪提交参数、动态默认日期 |
|
||||
|
||||
@@ -2,23 +2,25 @@
|
||||
"""XQ0002 雇主险增减操作 插件入口。
|
||||
|
||||
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
|
||||
1) 花名册确保:源表缺失且开启 auto_export 时自动从 HR 接口导出(TTL 15 分钟复用);
|
||||
1) 花名册确保:源表缺失或超过 TTL(15 分钟)时自动从 HR 接口导出,新鲜度内复用;
|
||||
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
|
||||
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值)。
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值);
|
||||
7) HR 自动导入(可选开关,默认开启):浏览器自动化把调度生成的导入文件导入
|
||||
HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。
|
||||
字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path /
|
||||
auto_export / enable_validation / wps_recalc / export_change_sheet / gen_import_files。
|
||||
enable_validation / wps_recalc / export_change_sheet / gen_import_files / import_to_hr。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import roster_filter, schedule
|
||||
from .logic import roster_filter, schedule, hr_import
|
||||
from .logic.wps_recalc import recalc_target, ComRecalcError
|
||||
from .report import output
|
||||
|
||||
@@ -28,10 +30,10 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.1"
|
||||
version = "1.0.4"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件,"
|
||||
"替代人工 Ctrl+S 刷新公式环节")
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统),替代人工 Ctrl+S 刷新公式与人工上传导入环节")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0002"]
|
||||
@@ -55,11 +57,14 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
cat_names = fields.get("categories") or []
|
||||
categories = [config.get_category(n) for n in cat_names] if cat_names else list(config.CATEGORIES)
|
||||
roster_path = (fields.get("roster_path") or "").strip()
|
||||
auto_export = bool(fields.get("auto_export", True))
|
||||
enable_validation = bool(fields.get("enable_validation", True))
|
||||
wps_recalc = bool(fields.get("wps_recalc", True))
|
||||
export_change_sheet = bool(fields.get("export_change_sheet", True))
|
||||
gen_import_files = bool(fields.get("gen_import_files", True))
|
||||
import_to_hr = bool(fields.get("import_to_hr", True))
|
||||
import_on = import_to_hr and gen_import_files
|
||||
if import_to_hr and not gen_import_files:
|
||||
ctx.log("已开启「自动导入HR系统」但「生成导入文件」未开启,本次无可导入文件,导入步骤将跳过", "WARN")
|
||||
|
||||
if not categories:
|
||||
raise ValueError("未选择任何类别")
|
||||
@@ -70,7 +75,7 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
# ---- 步骤1:花名册确保(5% ~ 10%) ----
|
||||
ctx.progress(5)
|
||||
try:
|
||||
roster_path = roster_filter.ensure_employee_file(roster_path, auto_export, session)
|
||||
roster_path = roster_filter.ensure_employee_file(roster_path, session)
|
||||
ctx.log(f"源表就绪:{roster_path}", "INFO")
|
||||
except Exception as e:
|
||||
notes.append(f"花名册准备失败(筛选复制与调度将受影响):{e}")
|
||||
@@ -109,10 +114,15 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
to_schedule = ok_categories
|
||||
ctx.progress(60)
|
||||
|
||||
# ---- 步骤4:三阶段名额调度(60% ~ 88%) ----
|
||||
# ---- 步骤4:三阶段名额调度 ----
|
||||
# 进度边界:开启 HR 导入时压缩为 60~80(步骤5/6/7 依次 80~84 / 84~90 / 90~100),
|
||||
# 关闭时沿用原 60~88 / 88~95 / 95~100
|
||||
s4_end, s4_span = (80, 20) if import_on else (88, 28)
|
||||
s5_end, s5_span = (84, 4) if import_on else (95, 7)
|
||||
s6_end, s6_span = (90, 6) if import_on else (100, 5)
|
||||
scheduled = []
|
||||
for i, category in enumerate(to_schedule):
|
||||
ctx.progress(60 + int(28 * i / max(len(to_schedule), 1)))
|
||||
ctx.progress(60 + int(s4_span * i / max(len(to_schedule), 1)))
|
||||
try:
|
||||
schedule.schedule_category(category,
|
||||
enable_validation=enable_validation,
|
||||
@@ -124,28 +134,48 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 调度失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度失败:{e}", "WARN")
|
||||
ctx.progress(88)
|
||||
ctx.progress(s4_end)
|
||||
|
||||
# ---- 步骤5:再次重算公式(88% ~ 95%,刷新变更清单/在参名单公式列缓存) ----
|
||||
# ---- 步骤5:再次重算公式(刷新变更清单/在参名单公式列缓存) ----
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(88 + int(7 * i / max(len(scheduled), 1)))
|
||||
ctx.progress(s5_end - s5_span + int(s5_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 调度后重算失败(变更清单独立工作簿将取不到公式值):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度后重算失败:{e}", "WARN")
|
||||
ctx.progress(95)
|
||||
ctx.progress(s5_end)
|
||||
|
||||
# ---- 步骤6:导出变更清单独立工作簿(95% ~ 100%) ----
|
||||
# ---- 步骤6:导出变更清单独立工作簿 ----
|
||||
if export_change_sheet:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(95 + int(5 * i / max(len(scheduled), 1)))
|
||||
ctx.progress(s6_end - s6_span + int(s6_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
output.export_change_sheet_workbook(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}", "WARN")
|
||||
ctx.progress(s6_end)
|
||||
|
||||
# ---- 步骤7:HR 自动导入(90% ~ 100%,仅本次调度成功的类别;先全部减员再全部增员) ----
|
||||
import_results = []
|
||||
if import_on:
|
||||
if not scheduled:
|
||||
ctx.log("无调度成功的类别,跳过 HR 自动导入", "WARN")
|
||||
else:
|
||||
def _on_import_progress(done, total):
|
||||
ctx.progress(90 + int(10 * done / max(total, 1)))
|
||||
|
||||
ctx.log(f"开始 HR 自动导入:先全部【减员】后【增员】,共 {len(scheduled) * 2} 个导入单元")
|
||||
try:
|
||||
import_results = hr_import.import_all(scheduled, on_progress=_on_import_progress)
|
||||
except hr_import.LoginRequiredError as e:
|
||||
notes.append(f"HR 自动导入未执行(登录态缺失):{e}")
|
||||
ctx.log(f"HR 自动导入未执行:{e}", "ERROR")
|
||||
except Exception as e:
|
||||
notes.append(f"HR 自动导入整体失败:{e}")
|
||||
ctx.log(f"HR 自动导入整体失败:{e}", "ERROR")
|
||||
ctx.progress(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
@@ -154,11 +184,21 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
"筛选复制成功": len(ok_categories),
|
||||
"调度成功": len(scheduled),
|
||||
}
|
||||
if import_on:
|
||||
if import_results:
|
||||
import_lines = hr_import.summarize_results(import_results)
|
||||
import_text = ";".join(import_lines) if import_lines else "无导入结果"
|
||||
else:
|
||||
import_text = "未执行(登录态缺失或整体失败,详见注意事项与日志)"
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹。"
|
||||
f"HR 导入结果:{import_text}。")
|
||||
else:
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
|
||||
"请先执行【减员】导入再执行【增员】导入。")
|
||||
summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、"
|
||||
"调度成功 {scheduled} 个。增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
|
||||
"请先执行【减员】导入再执行【增员】导入。").format(
|
||||
"调度成功 {scheduled} 个。{tail}").format(
|
||||
date=config.today_date(), total=len(categories),
|
||||
filtered=len(ok_categories), scheduled=len(scheduled))
|
||||
filtered=len(ok_categories), scheduled=len(scheduled), tail=tail)
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
return {"summary": summary, "notes": notes, "detail": detail,
|
||||
|
||||
@@ -0,0 +1,614 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
|
||||
|
||||
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||||
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
|
||||
|
||||
插件化改造点(相对影刀版):
|
||||
1. 登录态:优先底座注入 session(config.get_session())的 cookies 注入浏览器,
|
||||
未注入/为空时兜底读共享 cookies 文件(hr_cookies.json);
|
||||
2. 导入文件路径经 config.category_import_add_file / category_import_sub_file 实时解析
|
||||
(base_dir 由 run() 注入,不依赖类别配置里的固化 folder);
|
||||
3. 一次运行共用一个浏览器:先全部类别【减员】再全部类别【增员】
|
||||
(替换/修改人员必须先撤旧方案再上新方案,先增员会方案冲突报错);
|
||||
4. 日志统一转发 config.logger;结果 dict 返回,由 __init__.py 汇总进 summary/notes。
|
||||
|
||||
关键语义(与影刀版一致,勿改):
|
||||
- getTmpDataPage.mc 仅在存在异常行时才返回逐行结果:全部成功时 HR 不调用结果接口,
|
||||
流程完整走完(两步「下一步」+「关闭」)且监听正常、未捕获异常行 -> 按文件条数推定全部成功;
|
||||
- 接口每页固定 15 条,弹窗只加载第一页:捕获首响应后按 pageNo 主动翻页拉全;
|
||||
- 需导入条数从导入文件 A 列最大序号统计(模板预格式化空白行不计);
|
||||
- 上传/校验/确认走 UI 控件(input[name=file] 设置路径跳过系统文件选择框)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, get_session
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
_DRP_AVAILABLE = True
|
||||
_DRP_IMPORT_ERROR = None
|
||||
except ImportError as _e: # 模块可安全导入(开关关闭时不触发),使用时再报清晰错误
|
||||
_DRP_AVAILABLE = False
|
||||
_DRP_IMPORT_ERROR = _e
|
||||
|
||||
# ==================== 常量(与影刀版 add_sub_import 一致) ====================
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# HR 系统「待增减人员」页面
|
||||
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=待增减人员"
|
||||
)
|
||||
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc)
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失/失效(页面被重定向到登录页或无可用 cookies)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。"""
|
||||
|
||||
|
||||
# ==================== 登录态:底座注入 session 优先,兜底共享 cookies 文件 ====================
|
||||
def _cookies_from_requests_session(session):
|
||||
"""从底座注入的 requests.Session 提取 37du.co 域 cookies(DrissionPage 字典格式)。"""
|
||||
cookies = []
|
||||
try:
|
||||
jar_items = list(session.cookies)
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar_items:
|
||||
domain = str(getattr(c, "domain", "") or "")
|
||||
if "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name, "value": c.value,
|
||||
"domain": domain, "path": getattr(c, "path", None) or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def _cookies_from_shared_file():
|
||||
"""读取共享 HR cookies 文件(37du.co 域),缺失/为空返回空列表。"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
return []
|
||||
try:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
|
||||
cookies = json.load(f) or []
|
||||
except Exception as e:
|
||||
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
|
||||
return []
|
||||
return [c for c in cookies if c.get("domain") and "37du.co" in str(c["domain"])]
|
||||
|
||||
|
||||
def _collect_browser_cookies():
|
||||
"""收集浏览器登录态 cookies:底座注入 session 优先,为空兜底共享 cookies 文件。"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if cookies:
|
||||
logger.info("使用底座注入 HR 会话的 cookies:%d 个", len(cookies))
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if cookies:
|
||||
logger.info("使用共享 cookies 文件:%d 个(%s)", len(cookies), SHARED_HR_COOKIE_FILE)
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
|
||||
"请先在插件界面完成 HR 登录后再执行导入。")
|
||||
return cookies
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""构建可访问 HR 接口的 requests.Session(供结果接口翻页拉全)。
|
||||
|
||||
cookies 来源与浏览器一致(注入 session 优先,兜底共享文件);构建失败返回 None,
|
||||
调用方降级为仅统计监听到的第一页(与影刀版兜底语义一致)。
|
||||
"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if not cookies:
|
||||
return None
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
try:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
except Exception:
|
||||
continue
|
||||
return s
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _create_page():
|
||||
"""创建 ChromiumPage(统一配置,非无头,与影刀版一致)。"""
|
||||
co = ChromiumOptions()
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,抛 LoginRequiredError。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效(页面被重定向到登录页),请先在插件界面重新登录 HR 再执行导入。")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 增员/减员导入页面流程 ====================
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件(直接对 input[name=file] 设置路径,跳过系统文件选择框)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
result["total_count"] += 1
|
||||
# 成功行返回「导入成功;」固定文案,只计数量不纳入异常
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页:按 pageNo 主动翻页拉全。
|
||||
|
||||
该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中,必须复用首次请求 body 改页码后 POST(直接 GET URL 拿不到目标页)。
|
||||
"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
session = _build_hr_session()
|
||||
if session is None:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话),仅统计弹窗第一页")
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获全部逐行结果(监听须已开启)。
|
||||
|
||||
第一步「下一步」(格式校验/预览)也可能请求该接口但行内 imp_fixed_msg 为空,跳过;
|
||||
仅处理携带导入结果说明的响应。捕获首响应后按 pageCount 主动翻页拉全。
|
||||
|
||||
Returns:
|
||||
dict: {captured, state, meg, listen_ok, success_count, total_count, exceptions}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# 已捕获过解析响应时,再确认一个间隔后结束,合并多次返回的结果
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 预览/校验响应行内 imp_fixed_msg 为空 -> 跳过,继续等待最终结果
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _count_import_rows(file_path):
|
||||
"""统计导入文件需导入条数(A 列最大序号;第 1 行标题/第 2 行表头/第 3 行示例,第 4 行起数据)。
|
||||
|
||||
官方模板自带大量预格式化空白行(max_row 可达数千),不能直接用 max_row 统计。
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
max_seq = 0
|
||||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||||
max_col=1, values_only=True):
|
||||
v = seq[0]
|
||||
if v is None or str(v).strip() == "":
|
||||
continue
|
||||
try:
|
||||
max_seq = max(max_seq, int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return max_seq
|
||||
finally:
|
||||
wb.close()
|
||||
except Exception as e:
|
||||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||||
return 0
|
||||
|
||||
|
||||
def _import_file_path(category, menu_label):
|
||||
"""按菜单解析类别导入文件路径(base_dir 运行时注入,实时拼接)。"""
|
||||
if menu_label == MENU_ADD:
|
||||
from ..config import category_import_add_file
|
||||
return category_import_add_file(category)
|
||||
from ..config import category_import_sub_file
|
||||
return category_import_sub_file(category)
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label):
|
||||
"""对单个类别执行一次导入(选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启 getTmpDataPage.mc 监听(结果接口可能在格式校验或
|
||||
真正导入时触发,提前监听避免漏捕);异常仅记录上报,不中断导入流程。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果(含 expected_total 需导入条数、exceptions 异常明细等)。
|
||||
"""
|
||||
file_path = _import_file_path(category, menu_label)
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
expected_total = _count_import_rows(file_path)
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 第一个「下一步」前开启监听,贯穿「格式校验/预览 + 真正导入」全过程;
|
||||
# 监听启动失败必须上报,否则未捕获异常会被误判为正常(假成功)
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:格式校验/预览
|
||||
_click_next(page) # 第二步:真正导入内容(触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
import_result["expected_total"] = expected_total
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 全部成功时 HR 不调用结果接口:流程完整走完 + 监听正常 + 未捕获异常行 -> 按文件条数推定全部成功
|
||||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||||
import_result["assumed_all_success"] = True
|
||||
import_result["success_count"] = expected_total
|
||||
import_result["total_count"] = expected_total
|
||||
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
elif not listen_ok:
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif import_result.get("assumed_all_success"):
|
||||
logger.info("类别[%s] %s:全部导入成功(HR 未返回结果接口,按文件 %d 条推定),无异常",
|
||||
category["name"], menu_label, expected_total)
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page)
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 对外入口:先减员后增员,全程共用一个浏览器 ====================
|
||||
def import_all(categories, on_progress=None):
|
||||
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
|
||||
|
||||
Args:
|
||||
categories: 类别配置列表(config.CATEGORIES 项,须为本次调度成功的类别,
|
||||
只导入本次新生成的导入文件,避免误传历史文件)。
|
||||
on_progress: 可选回调 on_progress(done, total),每个「类别×菜单」单元完成后调用,
|
||||
供 __init__.py 上报进度。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每单元结果:{category, menu, captured, state, meg, exceptions,
|
||||
listen_ok, expected_total, success_count, total_count,
|
||||
assumed_all_success?, error?, error_type?}
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失/失效(整个导入未开始,无部分导入风险)。
|
||||
RuntimeError: DrissionPage 依赖缺失。
|
||||
"""
|
||||
if not _DRP_AVAILABLE:
|
||||
raise RuntimeError(f"缺少 DrissionPage 依赖(python-env 未内置),无法自动导入:{_DRP_IMPORT_ERROR}")
|
||||
if not categories:
|
||||
logger.info("无待导入类别,跳过 HR 导入")
|
||||
return []
|
||||
|
||||
units = [(c, menu) for menu in (MENU_SUB, MENU_ADD) for c in categories]
|
||||
total_units = len(units)
|
||||
done = 0
|
||||
results = []
|
||||
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动(导入全程共用)")
|
||||
try:
|
||||
cookies = _collect_browser_cookies()
|
||||
page.set.cookies(cookies)
|
||||
_ensure_logged_in(page)
|
||||
|
||||
for category, menu_label in units:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
except Exception as e:
|
||||
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"error": str(e), "error_type": type(e).__name__,
|
||||
})
|
||||
done += 1
|
||||
if on_progress:
|
||||
try:
|
||||
on_progress(done, total_units)
|
||||
except Exception:
|
||||
pass
|
||||
return results
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def summarize_results(results):
|
||||
"""把导入结果汇总为可读文本行列表(供插件 summary 拼接)。
|
||||
|
||||
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
|
||||
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
|
||||
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败。
|
||||
"""
|
||||
lines = []
|
||||
for menu, label in ((MENU_SUB, "减员"), (MENU_ADD, "增员")):
|
||||
rs = [r for r in results if r.get("menu") == menu]
|
||||
if not rs:
|
||||
continue
|
||||
total = sum(r.get("expected_total") or 0 for r in rs if not r.get("error"))
|
||||
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
|
||||
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
|
||||
flow_failed = [r["category"] for r in rs if r.get("error")]
|
||||
unconfirmed = [r["category"] for r in rs
|
||||
if not r.get("error") and not r.get("exceptions")
|
||||
and not r.get("assumed_all_success")
|
||||
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
|
||||
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
|
||||
extras = []
|
||||
if unconfirmed:
|
||||
extras.append(f"{len(unconfirmed)} 个类别结果待人工确认({'、'.join(unconfirmed)})")
|
||||
if flow_failed:
|
||||
extras.append(f"流程失败({'、'.join(flow_failed)})")
|
||||
if extras:
|
||||
line += ";" + ";".join(extras)
|
||||
lines.append(line)
|
||||
return lines
|
||||
@@ -5,7 +5,7 @@
|
||||
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
|
||||
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
|
||||
|
||||
源表缺失时调用 data.roster_export_api.export_roster 自动导出(auto_export 开关),
|
||||
源表缺失或超过 TTL(15 分钟)时调用 data.roster_export_api.export_roster 自动导出,
|
||||
替代影刀版对 share/roster_export.py 的懒加载;登录态经底座注入的 session。
|
||||
"""
|
||||
import os
|
||||
@@ -132,24 +132,20 @@ def filter_and_copy_roster(category, employee_path="", target_file=None):
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ensure_employee_file(employee_path="", auto_export=True, session=None):
|
||||
"""确保花名册源表存在:缺失且 auto_export 时自动调用 HR 接口导出,否则抛错。
|
||||
def ensure_employee_file(employee_path="", session=None):
|
||||
"""确保花名册源表可用:缺失或超过 TTL(15 分钟)时自动重新从 HR 接口导出。
|
||||
|
||||
新鲜度评估交给 export_roster 的 TTL 缓存:源表存在、非空且距上次导出
|
||||
不超过 15 分钟时直接复用,否则重新导出覆盖(不用陈旧花名册做调度)。
|
||||
|
||||
Args:
|
||||
employee_path: 花名册路径(留空=默认根目录/员工花名册.xlsx)
|
||||
auto_export: 源表缺失时是否自动导出
|
||||
session: 底座注入的 HR 会话(导出时使用)
|
||||
|
||||
Returns:
|
||||
源表绝对路径
|
||||
"""
|
||||
path = os.path.abspath(employee_path or employee_file())
|
||||
if os.path.exists(path):
|
||||
logger.info("源表已存在:%s,跳过导出", path)
|
||||
return path
|
||||
if not auto_export:
|
||||
raise FileNotFoundError(f"源表不存在:{path}")
|
||||
logger.info("源表不存在:%s,自动调用花名册导出...", path)
|
||||
export_roster(
|
||||
download_dir=os.path.join(CACHE_DIR, "roster_tmp"),
|
||||
output_path=path,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.1",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件,替代人工 Ctrl+S 刷新公式环节",
|
||||
"version": "1.0.4",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统),替代人工 Ctrl+S 刷新公式与人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
@@ -42,13 +42,7 @@
|
||||
"type": "string",
|
||||
"title": "花名册路径",
|
||||
"default": "",
|
||||
"description": "留空=根目录/员工花名册.xlsx(源表缺失且开启自动导出时自动从 HR 导出)"
|
||||
},
|
||||
"auto_export": {
|
||||
"type": "boolean",
|
||||
"title": "源表缺失时自动导出",
|
||||
"default": true,
|
||||
"description": "勾选=花名册缺失时自动调用 HR 接口导出雇主险模板;不勾选则缺失时报错"
|
||||
"description": "留空=根目录/员工花名册.xlsx(源表缺失或超过 15 分钟 TTL 时自动从 HR 导出)"
|
||||
},
|
||||
"enable_validation": {
|
||||
"type": "boolean",
|
||||
@@ -73,6 +67,12 @@
|
||||
"title": "生成增员/减员导入文件",
|
||||
"default": true,
|
||||
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
|
||||
},
|
||||
"import_to_hr": {
|
||||
"type": "boolean",
|
||||
"title": "自动导入HR系统",
|
||||
"default": true,
|
||||
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(浏览器自动化,先减员后增员,仅导入本次调度成功的类别);需本机 Chrome/Edge 且执行中会弹出浏览器窗口;须同时开启「生成增员/减员导入文件」"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
||||
@@ -3,3 +3,4 @@ pandas
|
||||
openpyxl
|
||||
websocket-client
|
||||
pywin32
|
||||
DrissionPage
|
||||
|
||||
@@ -1,18 +1,35 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
<transition name="fade-slide">
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon
|
||||
title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
</transition>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="card">
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<span class="card-title">执行配置</span>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" />
|
||||
<path d="m9 12 2 2 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
|
||||
<span v-if="lastSavedAt" class="saved">
|
||||
<i class="dot" />已保存 {{ lastSavedAt }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
@change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
@@ -23,57 +40,101 @@
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-width="130px" label-position="right">
|
||||
<div class="grid">
|
||||
<el-form-item label="雇主险根目录">
|
||||
<el-input v-model="form.base_dir" :disabled="running" clearable placeholder="四类各占一个子文件夹,增/减员导入模板放在根目录" />
|
||||
</el-form-item>
|
||||
<el-form-item label="业务日期">
|
||||
<el-date-picker v-model="form.ref_date" type="date" value-format="YYYY-MM-DD" :disabled="running"
|
||||
clearable placeholder="留空=今天" class="wide" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="处理类别">
|
||||
<el-select v-model="form.categories" multiple :disabled="running" class="wide"
|
||||
placeholder="可多选,留空=全部类别">
|
||||
<el-option v-for="c in CATEGORIES" :key="c" :value="c" :label="c" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="花名册路径">
|
||||
<el-input v-model="form.roster_path" :disabled="running" clearable
|
||||
placeholder="留空 = 根目录/员工花名册.xlsx(缺失且开启自动导出时自动从 HR 导出)" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="执行开关">
|
||||
<div class="switches">
|
||||
<el-switch v-model="form.auto_export" :disabled="running" active-text="源表缺失自动导出" />
|
||||
<el-switch v-model="form.enable_validation" :disabled="running" active-text="启用数据校验" />
|
||||
<el-switch v-model="form.wps_recalc" :disabled="running" active-text="WPS/Excel后台重算公式" />
|
||||
<el-switch v-model="form.export_change_sheet" :disabled="running" active-text="导出变更清单独立工作簿" />
|
||||
<el-switch v-model="form.gen_import_files" :disabled="running" active-text="生成增/减员导入文件" />
|
||||
<el-form label-position="top">
|
||||
<!-- 基本设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">基本设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="tip">「WPS/Excel后台重算公式」替代人工 Ctrl+S 刷新公式,需本机装 WPS 专业版/企业版或 MS Excel;关闭后须确保目标文件公式已人工刷新</div>
|
||||
</el-form-item>
|
||||
<div class="grid">
|
||||
<el-form-item label="雇主险根目录">
|
||||
<el-input v-model="form.base_dir" :disabled="running" clearable
|
||||
placeholder="四类各占一个子文件夹,增/减员导入模板放在根目录" />
|
||||
</el-form-item>
|
||||
<el-form-item label="业务日期">
|
||||
<el-date-picker v-model="form.ref_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="留空=今天" :disabled="running" clearable class="wide" />
|
||||
<div class="tip">影响变更清单/在参名单/导入文件中的日期与备份文件名</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 处理范围 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">处理范围</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="处理类别">
|
||||
<el-select v-model="form.categories" multiple :disabled="running" class="wide"
|
||||
placeholder="可多选,留空=全部类别">
|
||||
<el-option v-for="c in CATEGORIES" :key="c" :value="c" :label="c" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="花名册路径">
|
||||
<el-input v-model="form.roster_path" :disabled="running" clearable
|
||||
placeholder="留空 = 根目录/员工花名册.xlsx(缺失且开启自动导出时自动从 HR 导出)" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 执行开关 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">执行开关</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="启用数据校验">
|
||||
<el-switch v-model="form.enable_validation" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="WPS/Excel后台重算公式">
|
||||
<el-switch v-model="form.wps_recalc" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="导出变更清单独立工作簿">
|
||||
<el-switch v-model="form.export_change_sheet" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="生成增/减员导入文件">
|
||||
<el-switch v-model="form.gen_import_files" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="自动导入HR系统">
|
||||
<el-switch v-model="form.import_to_hr" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">「WPS/Excel后台重算公式」替代人工 Ctrl+S 刷新公式,需本机装 WPS 专业版/企业版或 MS Excel;关闭后须确保目标文件公式已人工刷新;「自动导入HR系统」会在执行中弹出浏览器窗口自动完成增/减员导入(先减员后增员),需本机 Chrome/Edge 且保持 HR 登录态</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" :loading="running" @click="run">
|
||||
<el-button type="primary" size="large" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态:进度条 + 日志位置提示(日志实时显示在壳子下方日志区) -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="8" class="status-bar" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
</div>
|
||||
<!-- 运行状态 -->
|
||||
<transition name="fade-slide">
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -88,11 +149,11 @@ const DEFAULTS = () => ({
|
||||
ref_date: '',
|
||||
categories: [...CATEGORIES],
|
||||
roster_path: '',
|
||||
auto_export: true,
|
||||
enable_validation: true,
|
||||
wps_recalc: true,
|
||||
export_change_sheet: true,
|
||||
gen_import_files: true,
|
||||
import_to_hr: true,
|
||||
})
|
||||
|
||||
const {
|
||||
@@ -114,103 +175,263 @@ const {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ---------- 页面骨架 ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 4px 2px 20px;
|
||||
padding: 6px 4px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 10px;
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: opacity 0.25s ease, transform 0.25s ease;
|
||||
}
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
.card-head {
|
||||
/* ---------- 主容器(无边框平铺:外层由壳子 iframe 的边框统一包裹) ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
.panel :deep(.el-card__header) {
|
||||
padding: 6px 2px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
background: transparent;
|
||||
}
|
||||
.panel :deep(.el-card__body) {
|
||||
padding: 16px 2px 2px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.title-ico {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-6));
|
||||
box-shadow: inset 0 0 0 1px var(--el-color-primary-light-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.title-txt {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
line-height: 1.2;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.title-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #67c23a;
|
||||
color: #2ea44f;
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
border: 1px solid rgba(46, 164, 79, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.saved .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #2ea44f;
|
||||
}
|
||||
|
||||
/* ---------- 表单分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.sec-badge {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.sec-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--el-border-color-lighter), transparent);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
flex-wrap: wrap;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
flex: 1;
|
||||
min-width: 300px;
|
||||
.grid :deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.wide {
|
||||
.grid :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.grid :deep(.el-date-editor) {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.switches {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 18px;
|
||||
align-items: center;
|
||||
/* 开关区:单行排布更紧凑(5 个开关一行放不下时自动换行) */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
|
||||
row-gap: 14px;
|
||||
}
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 2px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 16px;
|
||||
margin-top: 6px;
|
||||
padding-top: 18px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
letter-spacing: 2px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
box-shadow: 0 6px 16px var(--el-color-primary-light-6);
|
||||
transition: filter 0.2s, box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
.btn-run:hover {
|
||||
filter: brightness(1.06);
|
||||
box-shadow: 0 8px 20px var(--el-color-primary-light-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.btn-run:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
|
||||
border: 1px solid var(--el-color-primary-light-6);
|
||||
box-shadow: 0 2px 10px var(--el-color-primary-light-7);
|
||||
}
|
||||
.status-bar :deep(.el-progress-bar__outer) {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
.status-bar :deep(.el-progress-bar__inner) {
|
||||
background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
}
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--el-color-primary);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--el-color-primary-light-6);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
.status-txt {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
flex: 1;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.status-pct {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码字段
|
||||
// 不落盘;供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
@@ -165,7 +165,7 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码不入方案,沿用当前表单)→ 防抖自动保存固化为当前配置;
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
@@ -180,7 +180,7 @@ export function usePluginUI(opts = {}) {
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码加密落盘,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
|
||||
+16
-16
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>雇主险增减操作</title>
|
||||
<script type="module" crossorigin src="/pui/xq0002/assets/index-CkWAMjZ6.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-CTix2M2a.css">
|
||||
<script type="module" crossorigin src="/pui/xq0002/assets/index-1OHEXMMP.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-D-w0FhnS.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
@@ -28,7 +28,7 @@ class KqSealCheckPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0011"
|
||||
name = "考勤月报封存检查"
|
||||
version = "1.2.0"
|
||||
version = "1.2.1"
|
||||
description = ("考勤月报封存后自动检查:拉取当月全集团封存数据并按白名单单位预处理,"
|
||||
"自动导出花名册/调动台账,依次执行 6 项检查(在职天数排班/出勤及排休/"
|
||||
"封存最新值/全勤验证/未封存名单/延时加班),输出单工作簿异常名单")
|
||||
|
||||
@@ -192,6 +192,12 @@ def _parse_date(v) -> Optional[date]:
|
||||
return None
|
||||
|
||||
|
||||
def _fmt_date(v) -> str:
|
||||
"""日期格式化为 yyyy-mm-dd(如 2026-09-21 00:00:00 → 2026-09-21)。"""
|
||||
d = _parse_date(v)
|
||||
return d.isoformat() if d else _clean(v)[:10]
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
@@ -313,10 +319,15 @@ def enrich_dept_fields(target: dict, code: str, rec: dict = None,
|
||||
rec = rec or {}
|
||||
target["所属单位"] = info.get("所属单位") or _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
target["岗位"] = info.get("岗位") or _clean(rec.get("POST_ALIAS_NAME"))
|
||||
target["入职时间"] = info.get("入职时间") or _clean(rec.get("join_date"))
|
||||
target["入职时间"] = _fmt_date(info.get("入职时间") or _clean(rec.get("join_date")))
|
||||
# 离职时间以封存记录为准(封存的是检查月当月实际状态):存在离职后又复职的员工,
|
||||
# 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底
|
||||
target["离职时间"] = _clean(rec.get("leaveOffice_date")) or info.get("离职时间")
|
||||
# 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底。
|
||||
# 优先取「封存快照」离职时间 seal_leaveOffice_date(保留检查月离职日期),
|
||||
# 其次当前离职时间 leaveOffice_date,最后花名册。
|
||||
target["离职时间"] = _fmt_date(
|
||||
_clean(rec.get("seal_leaveOffice_date"))
|
||||
or _clean(rec.get("leaveOffice_date"))
|
||||
or info.get("离职时间"))
|
||||
for chn, cn, f in zip(DEPT_CN_ORDER, ROSTER_DEPT_COLS, DEPT_ORG_FIELDS):
|
||||
target[cn] = info.get(cn) or _clean(rec.get(f))
|
||||
return target
|
||||
|
||||
@@ -24,7 +24,9 @@ NOTE_SECOND_HIRE = "员工二次入职,无法校验具体的在职天数,需
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_NAME_FIELD = "staff_name"
|
||||
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
|
||||
SEAL_JOIN_FIELD_SEAL = "seal_join_date" # 封存快照入职日期(离职后复职可能保留原始入职日期)
|
||||
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
|
||||
SEAL_LEAVE_FIELD_SEAL = "seal_leaveOffice_date" # 封存快照离职时间(离职后复职时当前离职时间被清空,以快照为准)
|
||||
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天
|
||||
|
||||
@@ -99,8 +101,13 @@ def run_working_days_shift_check(month: str = None, save_dir: str = None,
|
||||
|
||||
abnormal: List[dict] = []
|
||||
for code, rec in seal_map.items():
|
||||
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
|
||||
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
|
||||
# 入离职时间以「封存快照」为准:离职后复职的员工,当前 leaveOffice_date 会被清空,
|
||||
# 但 seal_leaveOffice_date 保留了检查月的离职日期;快照缺失时兜底当前值。
|
||||
# 否则会把整月算作在职,在职天数被高估导致误报(如 8/21 离职 → 误算 31 天)。
|
||||
join = (_parse_date(rec.get(SEAL_JOIN_FIELD_SEAL))
|
||||
or _parse_date(rec.get(SEAL_JOIN_FIELD)))
|
||||
leave = (_parse_date(rec.get(SEAL_LEAVE_FIELD_SEAL))
|
||||
or _parse_date(rec.get(SEAL_LEAVE_FIELD)))
|
||||
wd = _working_days(first, last, join, leave)
|
||||
if wd <= 0:
|
||||
continue # 当月无在职日,跳过
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0011",
|
||||
"name": "考勤月报封存检查",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"description": "考勤月报封存后自动检查:拉取当月全集团封存数据并按白名单单位预处理,自动导出花名册/调动台账,依次执行 6 项检查(在职天数排班/出勤及排休/封存最新值/全勤验证/未封存名单/延时加班),输出单工作簿异常名单",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -1,327 +1,327 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码字段
|
||||
// 不落盘;供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码不入方案,沿用当前表单)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码加密落盘,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>考勤月报封存检查</title>
|
||||
<script type="module" crossorigin src="/pui/xq0011/assets/index-C6kdsQdY.js"></script>
|
||||
<script type="module" crossorigin src="/pui/xq0011/assets/index-BAs_KBhK.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0011/assets/index-BjCl3jYx.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码字段
|
||||
// 不落盘;供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
@@ -165,7 +165,7 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码不入方案,沿用当前表单)→ 防抖自动保存固化为当前配置;
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
@@ -180,7 +180,7 @@ export function usePluginUI(opts = {}) {
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码加密落盘,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ERP报表导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-EpDPYe3Q.js"></script>
|
||||
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-Cp_413co.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-u2-ZnLC2.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
品牌管理公司(重庆金色印象品牌管理有限公司)、其他账号(其余商户),原全量文件保留。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
@@ -37,8 +37,19 @@ def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _default_day():
|
||||
"""昨日(YYYY-MM-DD),日期留空时由插件按执行日推算(定时任务无需固定日期)。"""
|
||||
return f"{date.today() - timedelta(days=1):%Y-%m-%d}"
|
||||
|
||||
|
||||
def _default_month():
|
||||
"""上月(YYYY-MM),月份留空时由插件按执行日推算。"""
|
||||
first = date.today().replace(day=1)
|
||||
return f"{first - timedelta(days=1):%Y-%m}"
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(前端已用日期选择器选好值,这里只做组装)。"""
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(留空默认值已在 run() 解析区补齐)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
@@ -52,7 +63,7 @@ def _build_tasks(mode, day_date, month_date):
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.9"
|
||||
version = "1.0.11"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地,"
|
||||
"并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿")
|
||||
@@ -66,8 +77,10 @@ class TongLianExportPlugin(ScenePlugin):
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": ""},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": ""},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": "",
|
||||
"description": "留空=昨日(插件按执行日推算)"},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": "",
|
||||
"description": "留空=上月(插件按执行日推算)"},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
@@ -95,6 +108,14 @@ class TongLianExportPlugin(ScenePlugin):
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
# 日期留空 = 插件内按执行日推算默认值(按日→昨日、按月→上月),
|
||||
# 定时任务方案无需固定日期,到点自动导最近的昨日/上月
|
||||
if mode in (MODE_DAY, MODE_BOTH) and not day_date:
|
||||
day_date = _default_day()
|
||||
ctx.log(f"按日导出未选日期,默认导昨日:{day_date}")
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and not month_date:
|
||||
month_date = _default_month()
|
||||
ctx.log(f"按月导出未选月份,默认导上月:{month_date}")
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.9",
|
||||
"version": "1.0.11",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
@@ -35,14 +35,14 @@
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "默认昨天;交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
"description": "留空=昨日(插件按执行日推算,定时任务无需固定日期);交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "默认上月;交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
"description": "留空=上月(插件按执行日推算,定时任务无需固定月份);交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
|
||||
@@ -89,30 +89,30 @@
|
||||
<div v-if="form.mode === '日+月'" class="grid">
|
||||
<el-form-item label="按日导出">
|
||||
<el-date-picker v-model="form.day_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="选择日期(默认昨天)" :disabled="running"
|
||||
placeholder="选择日期(留空=昨天)" :disabled="running"
|
||||
:disabled-date="disableFuture" class="wide" />
|
||||
<div class="tip">默认昨天;区间=所选日 00:00 ~ 次日 24:00(跨 2 天)</div>
|
||||
<div class="tip">留空=昨天(执行时按当天推算);区间=所选日 00:00 ~ 次日 24:00(跨 2 天)</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="按月导出">
|
||||
<el-date-picker v-model="form.month_date" type="month" value-format="YYYY-MM"
|
||||
placeholder="选择月份(默认上月)" :disabled="running"
|
||||
placeholder="选择月份(留空=上月)" :disabled="running"
|
||||
:disabled-date="disableFutureMonth" class="wide" />
|
||||
<div class="tip">默认上月;区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日)</div>
|
||||
<div class="tip">留空=上月(执行时按当天推算);区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日)</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item v-else-if="form.mode === '日'" label="按日导出">
|
||||
<el-date-picker v-model="form.day_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="选择日期(默认昨天)" :disabled="running"
|
||||
placeholder="选择日期(留空=昨天)" :disabled="running"
|
||||
:disabled-date="disableFuture" class="wide" />
|
||||
<div class="tip">默认昨天;区间=所选日 00:00 ~ 次日 24:00(跨 2 天);账单 = 所选日账单</div>
|
||||
<div class="tip">留空=昨天(执行时按当天推算);区间=所选日 00:00 ~ 次日 24:00(跨 2 天);账单 = 所选日账单</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item v-else label="按月导出">
|
||||
<el-date-picker v-model="form.month_date" type="month" value-format="YYYY-MM"
|
||||
placeholder="选择月份(默认上月)" :disabled="running"
|
||||
placeholder="选择月份(留空=上月)" :disabled="running"
|
||||
:disabled-date="disableFutureMonth" class="wide" />
|
||||
<div class="tip">默认上月;区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单</div>
|
||||
<div class="tip">留空=上月(执行时按当天推算);区间=当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="保存目录">
|
||||
@@ -154,41 +154,15 @@
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
function fmtDate(d) {
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${day}`
|
||||
}
|
||||
|
||||
function fmtMonth(d) {
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
return `${y}-${m}`
|
||||
}
|
||||
|
||||
function lastMonthStr(now) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - 1, 1)
|
||||
return fmtMonth(d)
|
||||
}
|
||||
|
||||
function yesterdayStr(now) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
return fmtDate(d)
|
||||
}
|
||||
|
||||
const DEFAULTS = () => {
|
||||
const now = new Date()
|
||||
return {
|
||||
mode: '日+月',
|
||||
content: '两个都导',
|
||||
day_date: yesterdayStr(now), // 默认昨天
|
||||
month_date: lastMonthStr(now), // 默认上月
|
||||
tl_username: '',
|
||||
tl_password: '',
|
||||
save_dir: '',
|
||||
}
|
||||
}
|
||||
const DEFAULTS = () => ({
|
||||
mode: '日+月',
|
||||
content: '两个都导',
|
||||
day_date: '', // 留空=插件按执行日推算昨日(定时任务无需固定日期)
|
||||
month_date: '', // 留空=插件按执行日推算上月
|
||||
tl_username: '',
|
||||
tl_password: '',
|
||||
save_dir: '',
|
||||
})
|
||||
|
||||
function disableFuture(date) {
|
||||
return date.getTime() > Date.now() + 86400000 // 今天及以前可选
|
||||
@@ -211,8 +185,6 @@ const {
|
||||
ElMessage.warning('请先填写通联登录账号和密码')
|
||||
return false
|
||||
}
|
||||
if (form.mode !== '月' && !form.day_date) { ElMessage.warning('请选择按日导出的日期'); return false }
|
||||
if (form.mode !== '日' && !form.month_date) { ElMessage.warning('请选择按月导出的月份'); return false }
|
||||
return true
|
||||
},
|
||||
// 提交参数按执行模式裁剪:按日不带月份、按月不带日期
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码字段
|
||||
// 不落盘;供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
@@ -165,7 +165,7 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码不入方案,沿用当前表单)→ 防抖自动保存固化为当前配置;
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
@@ -180,7 +180,7 @@ export function usePluginUI(opts = {}) {
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码加密落盘,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+23
-23
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>金色印象通联数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0045_xq0046/assets/index-Bge9B6U7.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-qWMFdWZT.css">
|
||||
<script type="module" crossorigin src="/pui/xq0045_xq0046/assets/index-qs3ay3HR.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-C-Ir0bBb.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件入口。
|
||||
|
||||
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
|
||||
1) 花名册确保:源表缺失或超过 TTL(15 分钟)时自动从 HR 接口导出,新鲜度内复用;
|
||||
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
|
||||
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值);
|
||||
7) HR 自动导入(可选开关,默认开启):浏览器自动化把调度生成的导入文件导入
|
||||
HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。
|
||||
字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path /
|
||||
enable_validation / wps_recalc / export_change_sheet / gen_import_files / import_to_hr。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import roster_filter, schedule, hr_import
|
||||
from .logic.wps_recalc import recalc_target, ComRecalcError
|
||||
from .report import output
|
||||
|
||||
|
||||
class EmployerInsurancePlugin(ScenePlugin):
|
||||
"""雇主险名额调度(需求 XQ0002)。"""
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.4"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统),替代人工 Ctrl+S 刷新公式与人工上传导入环节")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0002"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / HR 会话 / userId ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
session = None
|
||||
try:
|
||||
session = ctx.get_session("hr")
|
||||
except Exception as e:
|
||||
ctx.log(f"HR 会话获取失败(花名册自动导出将回退共享 cookies):{e}", "WARN")
|
||||
config.set_session(session)
|
||||
|
||||
# ---- 解析运行参数 ----
|
||||
base_dir = (fields.get("base_dir") or "").strip() or config.DEFAULT_BASE_DIR
|
||||
config.set_base_dir(base_dir)
|
||||
config.set_ref_date(fields.get("ref_date") or "")
|
||||
cat_names = fields.get("categories") or []
|
||||
categories = [config.get_category(n) for n in cat_names] if cat_names else list(config.CATEGORIES)
|
||||
roster_path = (fields.get("roster_path") or "").strip()
|
||||
enable_validation = bool(fields.get("enable_validation", True))
|
||||
wps_recalc = bool(fields.get("wps_recalc", True))
|
||||
export_change_sheet = bool(fields.get("export_change_sheet", True))
|
||||
gen_import_files = bool(fields.get("gen_import_files", True))
|
||||
import_to_hr = bool(fields.get("import_to_hr", True))
|
||||
import_on = import_to_hr and gen_import_files
|
||||
if import_to_hr and not gen_import_files:
|
||||
ctx.log("已开启「自动导入HR系统」但「生成导入文件」未开启,本次无可导入文件,导入步骤将跳过", "WARN")
|
||||
|
||||
if not categories:
|
||||
raise ValueError("未选择任何类别")
|
||||
|
||||
notes: list = []
|
||||
ctx.log(f"===== 雇主险增减操作启动:业务日期 {config.today_date()},根目录 {base_dir} =====", "INFO")
|
||||
|
||||
# ---- 步骤1:花名册确保(5% ~ 10%) ----
|
||||
ctx.progress(5)
|
||||
try:
|
||||
roster_path = roster_filter.ensure_employee_file(roster_path, session)
|
||||
ctx.log(f"源表就绪:{roster_path}", "INFO")
|
||||
except Exception as e:
|
||||
notes.append(f"花名册准备失败(筛选复制与调度将受影响):{e}")
|
||||
ctx.log(f"花名册准备失败:{e}", "WARN")
|
||||
ctx.progress(10)
|
||||
|
||||
# ---- 步骤2:筛选复制(10% ~ 45%) ----
|
||||
ok_categories = []
|
||||
n = len(categories)
|
||||
for i, category in enumerate(categories):
|
||||
ctx.progress(10 + int(35 * i / n))
|
||||
try:
|
||||
roster_filter.filter_and_copy_roster(category, employee_path=roster_path)
|
||||
ok_categories.append(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 筛选复制失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 筛选复制失败:{e}", "WARN")
|
||||
ctx.progress(45)
|
||||
|
||||
# ---- 步骤3:WPS/Excel 后台重算公式(45% ~ 60%,替代人工 Ctrl+S) ----
|
||||
recalc_ok = {}
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(ok_categories):
|
||||
ctx.progress(45 + int(15 * i / max(n, 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
recalc_ok[category["name"]] = True
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 公式重算失败(跳过该类别调度):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 公式重算失败:{e}", "WARN")
|
||||
# 重算失败的类别不进入调度(公式缓存缺失会导致读取不到工种类别/投保方案/方案处理)
|
||||
to_schedule = [c for c in ok_categories if recalc_ok.get(c["name"])]
|
||||
else:
|
||||
ctx.log("已关闭 WPS/Excel 后台重算:请确认目标文件公式已人工刷新(打开保存过),"
|
||||
"否则调度将读取不到公式计算结果", "WARN")
|
||||
to_schedule = ok_categories
|
||||
ctx.progress(60)
|
||||
|
||||
# ---- 步骤4:三阶段名额调度 ----
|
||||
# 进度边界:开启 HR 导入时压缩为 60~80(步骤5/6/7 依次 80~84 / 84~90 / 90~100),
|
||||
# 关闭时沿用原 60~88 / 88~95 / 95~100
|
||||
s4_end, s4_span = (80, 20) if import_on else (88, 28)
|
||||
s5_end, s5_span = (84, 4) if import_on else (95, 7)
|
||||
s6_end, s6_span = (90, 6) if import_on else (100, 5)
|
||||
scheduled = []
|
||||
for i, category in enumerate(to_schedule):
|
||||
ctx.progress(60 + int(s4_span * i / max(len(to_schedule), 1)))
|
||||
try:
|
||||
schedule.schedule_category(category,
|
||||
enable_validation=enable_validation,
|
||||
gen_import_files=gen_import_files)
|
||||
scheduled.append(category)
|
||||
except schedule.DataValidationError:
|
||||
ctx.log("数据校验失败,已中断后续类别调度,请修正数据后重试", "ERROR")
|
||||
raise
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 调度失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度失败:{e}", "WARN")
|
||||
ctx.progress(s4_end)
|
||||
|
||||
# ---- 步骤5:再次重算公式(刷新变更清单/在参名单公式列缓存) ----
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(s5_end - s5_span + int(s5_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 调度后重算失败(变更清单独立工作簿将取不到公式值):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度后重算失败:{e}", "WARN")
|
||||
ctx.progress(s5_end)
|
||||
|
||||
# ---- 步骤6:导出变更清单独立工作簿 ----
|
||||
if export_change_sheet:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(s6_end - s6_span + int(s6_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
output.export_change_sheet_workbook(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}", "WARN")
|
||||
ctx.progress(s6_end)
|
||||
|
||||
# ---- 步骤7:HR 自动导入(90% ~ 100%,仅本次调度成功的类别;先全部减员再全部增员) ----
|
||||
import_results = []
|
||||
if import_on:
|
||||
if not scheduled:
|
||||
ctx.log("无调度成功的类别,跳过 HR 自动导入", "WARN")
|
||||
else:
|
||||
def _on_import_progress(done, total):
|
||||
ctx.progress(90 + int(10 * done / max(total, 1)))
|
||||
|
||||
ctx.log(f"开始 HR 自动导入:先全部【减员】后【增员】,共 {len(scheduled) * 2} 个导入单元")
|
||||
try:
|
||||
import_results = hr_import.import_all(scheduled, on_progress=_on_import_progress)
|
||||
except hr_import.LoginRequiredError as e:
|
||||
notes.append(f"HR 自动导入未执行(登录态缺失):{e}")
|
||||
ctx.log(f"HR 自动导入未执行:{e}", "ERROR")
|
||||
except Exception as e:
|
||||
notes.append(f"HR 自动导入整体失败:{e}")
|
||||
ctx.log(f"HR 自动导入整体失败:{e}", "ERROR")
|
||||
ctx.progress(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
detail = {
|
||||
"处理类别": len(categories),
|
||||
"筛选复制成功": len(ok_categories),
|
||||
"调度成功": len(scheduled),
|
||||
}
|
||||
if import_on:
|
||||
if import_results:
|
||||
import_lines = hr_import.summarize_results(import_results)
|
||||
import_text = ";".join(import_lines) if import_lines else "无导入结果"
|
||||
else:
|
||||
import_text = "未执行(登录态缺失或整体失败,详见注意事项与日志)"
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹。"
|
||||
f"HR 导入结果:{import_text}。")
|
||||
else:
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
|
||||
"请先执行【减员】导入再执行【增员】导入。")
|
||||
summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、"
|
||||
"调度成功 {scheduled} 个。{tail}").format(
|
||||
date=config.today_date(), total=len(categories),
|
||||
filtered=len(ok_categories), scheduled=len(scheduled), tail=tail)
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
return {"summary": summary, "notes": notes, "detail": detail,
|
||||
"path": base_dir, "date": config.today_date()}
|
||||
|
||||
|
||||
PLUGINS.append(EmployerInsurancePlugin())
|
||||
@@ -0,0 +1,404 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log()/logger 输出日志、config.get_session()/get_user_id() 取登录态;
|
||||
运行参数(根目录 / 业务日期)由 __init__.py 的 run() 解析 fields 后注入(set_base_dir/set_ref_date)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
|
||||
# ==================== 共享目录(登录态/缓存,与影刀版同路径) ====================
|
||||
_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')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache')
|
||||
|
||||
# ==================== 默认根目录与业务日期(run() 注入覆盖) ====================
|
||||
DEFAULT_BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
|
||||
# ==================== 固定 Sheet 名称 ====================
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
|
||||
# ==================== 四大类别(合并调度/筛选口径,与 app 版 config 一致) ====================
|
||||
# 每类一个独立文件夹;include_dept/exclude_dept 用于筛选复制;
|
||||
# change_sheet_prefix 为各类「变更清单」sheet 名称前缀;scheme_suffix 为增员导入方案后缀。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# 过滤规则(与 aa.md 宏一致)
|
||||
EXCLUDE_REGIONS = ["虚拟大区"] # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"] # 姓名(N列)含这些关键字的行剔除
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
EXPORT_STATUSES = ["在职"]
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 数据切片(B~O)内 0-based 列索引
|
||||
CODE_COL = 4 # F列 工号(必须文本格式)
|
||||
JOIN_DATE_COL = 11 # M列 入职时间
|
||||
NAME_COL = 12 # N列 姓名
|
||||
ID_COL = 13 # O列 证件号(18位身份证号超出浮点精度,必须文本格式)
|
||||
|
||||
# ==================== 花名册列名映射(表头在第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万"]
|
||||
|
||||
# ==================== 增减员导入模板(雇主险根目录下官方模板) ====================
|
||||
ADD_IMPORT_TEMPLATE = "商业保险增员导入模板.xlsx"
|
||||
SUB_IMPORT_TEMPLATE = "商业保险减员导入模板.xlsx"
|
||||
|
||||
|
||||
# ==================== 运行参数钩子(run() 注入) ====================
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ref_date = None # datetime.date;None 表示今天
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
|
||||
def get_base_dir():
|
||||
return _base_dir
|
||||
|
||||
|
||||
def parse_ref_date(value):
|
||||
"""把 fields.ref_date(YYYY-MM-DD / YYYY.M.D 等)解析为 date;空返回今天。"""
|
||||
if not value:
|
||||
return date.today()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[-./年](\d{1,2})[-./月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
pass
|
||||
return date.today()
|
||||
|
||||
|
||||
def set_ref_date(value):
|
||||
global _ref_date
|
||||
_ref_date = parse_ref_date(value)
|
||||
|
||||
|
||||
def ref_date():
|
||||
"""业务日期(默认今天)。"""
|
||||
return _ref_date or date.today()
|
||||
|
||||
|
||||
def date_str():
|
||||
"""YYYY.M.D(目标表/备份文件名,如 2026.9.22)。"""
|
||||
return ref_date().strftime("%Y.%m.%d")
|
||||
|
||||
|
||||
def date_short():
|
||||
"""M.D(变更清单 sheet 后缀,不补前导零,如 9.22 / 9.1)。"""
|
||||
return f"{ref_date().month}.{ref_date().day}"
|
||||
|
||||
|
||||
def today_date():
|
||||
"""YYYY-MM-DD(批改日期/增员减员日期/投保日期)。"""
|
||||
return ref_date().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 类别辅助函数 ====================
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。"""
|
||||
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 _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(ref_date().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||||
"""
|
||||
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」文件,请先准备今日的雇主险变更记录模板")
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||||
os.path.getmtime(path))
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
def _category_dir(category):
|
||||
"""类别文件夹(base_dir 运行时可能被覆盖,须实时拼接而非 import 时固化)。"""
|
||||
return os.path.join(get_base_dir(), category["name"])
|
||||
|
||||
|
||||
def category_folder(category):
|
||||
return _category_dir(category)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(_category_dir(category))
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"新在参名单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), 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_dir(category), "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险减员导入.xlsx")
|
||||
|
||||
|
||||
def add_import_template():
|
||||
return os.path.join(get_base_dir(), ADD_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def sub_import_template():
|
||||
return os.path.join(get_base_dir(), SUB_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def employee_file(path=""):
|
||||
"""花名册路径:传入优先,否则 {base_dir}\\员工花名册.xlsx。"""
|
||||
return (path or "").strip() or os.path.join(get_base_dir(), "员工花名册.xlsx")
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
# ==================== 文本/日期辅助函数(logic/report 层共用) ====================
|
||||
def to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||||
|
||||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||||
"""
|
||||
import numbers
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
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 clean_text(value):
|
||||
"""转可写文本;None/NaN/空白返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def parse_join_date(value):
|
||||
"""解析入职时间为 date 对象(兼容 datetime/字符串「YYYY-MM-DD」「YYYY.M.D」等)。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[.\-/年](\d{1,2})[.\-/月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return _dt(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def to_date(value):
|
||||
"""将日期/日期字符串统一转为 date 对象;无法解析时返回 None。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"):
|
||||
try:
|
||||
return _dt.strptime(s, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 data 层:花名册导出(接口版)。"""
|
||||
@@ -0,0 +1,453 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 员工花名册导出(接口版,由 xq0011 插件同模块内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
|
||||
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 内置「雇主险增减员导出模板」(B~O 共 14 列:所属单位→证件号,与 app 版 roster_template 一致);
|
||||
3. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, EXPORT_TEMPLATE, EXPORT_STATUSES
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
# 「雇主险增减员导出模板」(14 列 + 序号,B~O:所属单位→证件号,与 app 版 roster_template 一致)
|
||||
ROSTER_TEMPLATE_FILTERS_EMPLOYER = ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
])
|
||||
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数 ----------
|
||||
DEFAULT_TEMPLATE = EXPORT_TEMPLATE # 雇主险增减员导出模板
|
||||
DEFAULT_STATUSES = list(EXPORT_STATUSES) # ["在职"]
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
|
||||
def _build_session(session=None):
|
||||
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
|
||||
if session is not None:
|
||||
return session
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name):
|
||||
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
|
||||
try:
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
|
||||
return None
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先在插件界面重新完成 HR 登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
|
||||
_bind_session(session)
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
|
||||
单 sheet,表头在第1行,数据第2行起。
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None,
|
||||
ttl=DEFAULT_TTL_SECONDS, session=None):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_roster 一致。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
"""
|
||||
download_dir = download_dir or os.path.dirname(output_path or "") or "."
|
||||
output_path = output_path or "花名册.xlsx"
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None:
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
|
||||
template_name, statuses, leave_desc)
|
||||
|
||||
session = _build_session(session)
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 logic 层:筛选复制 + 三阶段名额调度 + WPS/Excel 重算。"""
|
||||
@@ -0,0 +1,614 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
|
||||
|
||||
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||||
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
|
||||
|
||||
插件化改造点(相对影刀版):
|
||||
1. 登录态:优先底座注入 session(config.get_session())的 cookies 注入浏览器,
|
||||
未注入/为空时兜底读共享 cookies 文件(hr_cookies.json);
|
||||
2. 导入文件路径经 config.category_import_add_file / category_import_sub_file 实时解析
|
||||
(base_dir 由 run() 注入,不依赖类别配置里的固化 folder);
|
||||
3. 一次运行共用一个浏览器:先全部类别【减员】再全部类别【增员】
|
||||
(替换/修改人员必须先撤旧方案再上新方案,先增员会方案冲突报错);
|
||||
4. 日志统一转发 config.logger;结果 dict 返回,由 __init__.py 汇总进 summary/notes。
|
||||
|
||||
关键语义(与影刀版一致,勿改):
|
||||
- getTmpDataPage.mc 仅在存在异常行时才返回逐行结果:全部成功时 HR 不调用结果接口,
|
||||
流程完整走完(两步「下一步」+「关闭」)且监听正常、未捕获异常行 -> 按文件条数推定全部成功;
|
||||
- 接口每页固定 15 条,弹窗只加载第一页:捕获首响应后按 pageNo 主动翻页拉全;
|
||||
- 需导入条数从导入文件 A 列最大序号统计(模板预格式化空白行不计);
|
||||
- 上传/校验/确认走 UI 控件(input[name=file] 设置路径跳过系统文件选择框)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, get_session
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
_DRP_AVAILABLE = True
|
||||
_DRP_IMPORT_ERROR = None
|
||||
except ImportError as _e: # 模块可安全导入(开关关闭时不触发),使用时再报清晰错误
|
||||
_DRP_AVAILABLE = False
|
||||
_DRP_IMPORT_ERROR = _e
|
||||
|
||||
# ==================== 常量(与影刀版 add_sub_import 一致) ====================
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# HR 系统「待增减人员」页面
|
||||
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=待增减人员"
|
||||
)
|
||||
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc)
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失/失效(页面被重定向到登录页或无可用 cookies)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。"""
|
||||
|
||||
|
||||
# ==================== 登录态:底座注入 session 优先,兜底共享 cookies 文件 ====================
|
||||
def _cookies_from_requests_session(session):
|
||||
"""从底座注入的 requests.Session 提取 37du.co 域 cookies(DrissionPage 字典格式)。"""
|
||||
cookies = []
|
||||
try:
|
||||
jar_items = list(session.cookies)
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar_items:
|
||||
domain = str(getattr(c, "domain", "") or "")
|
||||
if "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name, "value": c.value,
|
||||
"domain": domain, "path": getattr(c, "path", None) or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def _cookies_from_shared_file():
|
||||
"""读取共享 HR cookies 文件(37du.co 域),缺失/为空返回空列表。"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
return []
|
||||
try:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
|
||||
cookies = json.load(f) or []
|
||||
except Exception as e:
|
||||
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
|
||||
return []
|
||||
return [c for c in cookies if c.get("domain") and "37du.co" in str(c["domain"])]
|
||||
|
||||
|
||||
def _collect_browser_cookies():
|
||||
"""收集浏览器登录态 cookies:底座注入 session 优先,为空兜底共享 cookies 文件。"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if cookies:
|
||||
logger.info("使用底座注入 HR 会话的 cookies:%d 个", len(cookies))
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if cookies:
|
||||
logger.info("使用共享 cookies 文件:%d 个(%s)", len(cookies), SHARED_HR_COOKIE_FILE)
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
|
||||
"请先在插件界面完成 HR 登录后再执行导入。")
|
||||
return cookies
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""构建可访问 HR 接口的 requests.Session(供结果接口翻页拉全)。
|
||||
|
||||
cookies 来源与浏览器一致(注入 session 优先,兜底共享文件);构建失败返回 None,
|
||||
调用方降级为仅统计监听到的第一页(与影刀版兜底语义一致)。
|
||||
"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if not cookies:
|
||||
return None
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
try:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
except Exception:
|
||||
continue
|
||||
return s
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _create_page():
|
||||
"""创建 ChromiumPage(统一配置,非无头,与影刀版一致)。"""
|
||||
co = ChromiumOptions()
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,抛 LoginRequiredError。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效(页面被重定向到登录页),请先在插件界面重新登录 HR 再执行导入。")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 增员/减员导入页面流程 ====================
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件(直接对 input[name=file] 设置路径,跳过系统文件选择框)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
result["total_count"] += 1
|
||||
# 成功行返回「导入成功;」固定文案,只计数量不纳入异常
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页:按 pageNo 主动翻页拉全。
|
||||
|
||||
该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中,必须复用首次请求 body 改页码后 POST(直接 GET URL 拿不到目标页)。
|
||||
"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
session = _build_hr_session()
|
||||
if session is None:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话),仅统计弹窗第一页")
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获全部逐行结果(监听须已开启)。
|
||||
|
||||
第一步「下一步」(格式校验/预览)也可能请求该接口但行内 imp_fixed_msg 为空,跳过;
|
||||
仅处理携带导入结果说明的响应。捕获首响应后按 pageCount 主动翻页拉全。
|
||||
|
||||
Returns:
|
||||
dict: {captured, state, meg, listen_ok, success_count, total_count, exceptions}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# 已捕获过解析响应时,再确认一个间隔后结束,合并多次返回的结果
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 预览/校验响应行内 imp_fixed_msg 为空 -> 跳过,继续等待最终结果
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _count_import_rows(file_path):
|
||||
"""统计导入文件需导入条数(A 列最大序号;第 1 行标题/第 2 行表头/第 3 行示例,第 4 行起数据)。
|
||||
|
||||
官方模板自带大量预格式化空白行(max_row 可达数千),不能直接用 max_row 统计。
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
max_seq = 0
|
||||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||||
max_col=1, values_only=True):
|
||||
v = seq[0]
|
||||
if v is None or str(v).strip() == "":
|
||||
continue
|
||||
try:
|
||||
max_seq = max(max_seq, int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return max_seq
|
||||
finally:
|
||||
wb.close()
|
||||
except Exception as e:
|
||||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||||
return 0
|
||||
|
||||
|
||||
def _import_file_path(category, menu_label):
|
||||
"""按菜单解析类别导入文件路径(base_dir 运行时注入,实时拼接)。"""
|
||||
if menu_label == MENU_ADD:
|
||||
from ..config import category_import_add_file
|
||||
return category_import_add_file(category)
|
||||
from ..config import category_import_sub_file
|
||||
return category_import_sub_file(category)
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label):
|
||||
"""对单个类别执行一次导入(选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启 getTmpDataPage.mc 监听(结果接口可能在格式校验或
|
||||
真正导入时触发,提前监听避免漏捕);异常仅记录上报,不中断导入流程。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果(含 expected_total 需导入条数、exceptions 异常明细等)。
|
||||
"""
|
||||
file_path = _import_file_path(category, menu_label)
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
expected_total = _count_import_rows(file_path)
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 第一个「下一步」前开启监听,贯穿「格式校验/预览 + 真正导入」全过程;
|
||||
# 监听启动失败必须上报,否则未捕获异常会被误判为正常(假成功)
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:格式校验/预览
|
||||
_click_next(page) # 第二步:真正导入内容(触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
import_result["expected_total"] = expected_total
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 全部成功时 HR 不调用结果接口:流程完整走完 + 监听正常 + 未捕获异常行 -> 按文件条数推定全部成功
|
||||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||||
import_result["assumed_all_success"] = True
|
||||
import_result["success_count"] = expected_total
|
||||
import_result["total_count"] = expected_total
|
||||
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
elif not listen_ok:
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif import_result.get("assumed_all_success"):
|
||||
logger.info("类别[%s] %s:全部导入成功(HR 未返回结果接口,按文件 %d 条推定),无异常",
|
||||
category["name"], menu_label, expected_total)
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page)
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 对外入口:先减员后增员,全程共用一个浏览器 ====================
|
||||
def import_all(categories, on_progress=None):
|
||||
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
|
||||
|
||||
Args:
|
||||
categories: 类别配置列表(config.CATEGORIES 项,须为本次调度成功的类别,
|
||||
只导入本次新生成的导入文件,避免误传历史文件)。
|
||||
on_progress: 可选回调 on_progress(done, total),每个「类别×菜单」单元完成后调用,
|
||||
供 __init__.py 上报进度。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每单元结果:{category, menu, captured, state, meg, exceptions,
|
||||
listen_ok, expected_total, success_count, total_count,
|
||||
assumed_all_success?, error?, error_type?}
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失/失效(整个导入未开始,无部分导入风险)。
|
||||
RuntimeError: DrissionPage 依赖缺失。
|
||||
"""
|
||||
if not _DRP_AVAILABLE:
|
||||
raise RuntimeError(f"缺少 DrissionPage 依赖(python-env 未内置),无法自动导入:{_DRP_IMPORT_ERROR}")
|
||||
if not categories:
|
||||
logger.info("无待导入类别,跳过 HR 导入")
|
||||
return []
|
||||
|
||||
units = [(c, menu) for menu in (MENU_SUB, MENU_ADD) for c in categories]
|
||||
total_units = len(units)
|
||||
done = 0
|
||||
results = []
|
||||
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动(导入全程共用)")
|
||||
try:
|
||||
cookies = _collect_browser_cookies()
|
||||
page.set.cookies(cookies)
|
||||
_ensure_logged_in(page)
|
||||
|
||||
for category, menu_label in units:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
except Exception as e:
|
||||
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"error": str(e), "error_type": type(e).__name__,
|
||||
})
|
||||
done += 1
|
||||
if on_progress:
|
||||
try:
|
||||
on_progress(done, total_units)
|
||||
except Exception:
|
||||
pass
|
||||
return results
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def summarize_results(results):
|
||||
"""把导入结果汇总为可读文本行列表(供插件 summary 拼接)。
|
||||
|
||||
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
|
||||
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
|
||||
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败。
|
||||
"""
|
||||
lines = []
|
||||
for menu, label in ((MENU_SUB, "减员"), (MENU_ADD, "增员")):
|
||||
rs = [r for r in results if r.get("menu") == menu]
|
||||
if not rs:
|
||||
continue
|
||||
total = sum(r.get("expected_total") or 0 for r in rs if not r.get("error"))
|
||||
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
|
||||
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
|
||||
flow_failed = [r["category"] for r in rs if r.get("error")]
|
||||
unconfirmed = [r["category"] for r in rs
|
||||
if not r.get("error") and not r.get("exceptions")
|
||||
and not r.get("assumed_all_success")
|
||||
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
|
||||
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
|
||||
extras = []
|
||||
if unconfirmed:
|
||||
extras.append(f"{len(unconfirmed)} 个类别结果待人工确认({'、'.join(unconfirmed)})")
|
||||
if flow_failed:
|
||||
extras.append(f"流程失败({'、'.join(flow_failed)})")
|
||||
if extras:
|
||||
line += ";" + ";".join(extras)
|
||||
lines.append(line)
|
||||
return lines
|
||||
@@ -0,0 +1,158 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 筛选复制(由影刀版 roster_filter.py v2.0.0 移植)。
|
||||
|
||||
从员工花名册按类别 include/exclude 所属单位筛选数据,复制到各自类别目标表
|
||||
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
|
||||
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
|
||||
|
||||
源表缺失或超过 TTL(15 分钟)时调用 data.roster_export_api.export_roster 自动导出,
|
||||
替代影刀版对 share/roster_export.py 的懒加载;登录态经底座注入的 session。
|
||||
"""
|
||||
import os
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SOURCE_HEADER_MARK, EXPORT_TEMPLATE, EXPORT_STATUSES,
|
||||
TARGET_HEADER_ROW, DATA_COLUMNS, CODE_COL, ID_COL, JOIN_DATE_COL, NAME_COL,
|
||||
EXCLUDE_REGIONS, EXCLUDE_NAME_KEYWORDS, category_folder, employee_file,
|
||||
find_latest_target, to_text, parse_join_date, ref_date, CACHE_DIR,
|
||||
)
|
||||
from ..data.roster_export_api import export_roster
|
||||
|
||||
|
||||
def _read_source(employee_path):
|
||||
"""读取源表(员工花名册):自动定位表头行(B 列=「所属单位」),返回 B~O 14 列切片。"""
|
||||
probe = pd.read_excel(employee_path, 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_path, 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 列(所属单位)最后非空行为数据边界
|
||||
return data[data.iloc[:, 0].notna()]
|
||||
|
||||
|
||||
def filter_and_copy_roster(category, employee_path="", target_file=None):
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(含 name/include_dept/exclude_dept)
|
||||
employee_path: 源表路径,默认 {base_dir}\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_path = os.path.abspath(employee_path or employee_file())
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category_folder(category)))
|
||||
|
||||
if not os.path.exists(employee_path):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_path}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表并过滤 ----------
|
||||
data = _read_source(employee_path)
|
||||
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.isin(EXCLUDE_REGIONS)
|
||||
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)
|
||||
|
||||
# 入职时间 > 业务日期 的行剔除(未来才入职的员工暂不纳入,留到当天再筛选出来)
|
||||
today = ref_date()
|
||||
join_dates = data.iloc[:, JOIN_DATE_COL].map(parse_join_date)
|
||||
future_mask = join_dates.map(lambda d: d is not None and d > today)
|
||||
n_future = int(future_mask.sum())
|
||||
mask &= ~future_mask
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除 %s,姓名剔除含 %s,剔除未来入职 %d 人)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", " / ".join(EXCLUDE_REGIONS),
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS), n_future)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 2. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
|
||||
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(覆盖旧数据;F列工号 / O列证件号 强制文本格式)
|
||||
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):
|
||||
c = cell(row=i, column=j)
|
||||
# 工号/证件号为主键:18位身份证号超出浮点精度,文本化避免截断,保证公式/映射匹配
|
||||
if j - 2 in (CODE_COL, ID_COL):
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.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 ensure_employee_file(employee_path="", session=None):
|
||||
"""确保花名册源表可用:缺失或超过 TTL(15 分钟)时自动重新从 HR 接口导出。
|
||||
|
||||
新鲜度评估交给 export_roster 的 TTL 缓存:源表存在、非空且距上次导出
|
||||
不超过 15 分钟时直接复用,否则重新导出覆盖(不用陈旧花名册做调度)。
|
||||
|
||||
Args:
|
||||
employee_path: 花名册路径(留空=默认根目录/员工花名册.xlsx)
|
||||
session: 底座注入的 HR 会话(导出时使用)
|
||||
|
||||
Returns:
|
||||
源表绝对路径
|
||||
"""
|
||||
path = os.path.abspath(employee_path or employee_file())
|
||||
export_roster(
|
||||
download_dir=os.path.join(CACHE_DIR, "roster_tmp"),
|
||||
output_path=path,
|
||||
template_name=EXPORT_TEMPLATE,
|
||||
statuses=EXPORT_STATUSES,
|
||||
session=session,
|
||||
)
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"花名册导出完成但源表仍不存在:{path}")
|
||||
return path
|
||||
@@ -0,0 +1,559 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 三阶段名额调度(由影刀版 employer_insurance_schedule.py v1.3.0 移植)。
|
||||
|
||||
阶段0 初始化(空闲名额池 / 当前参保映射 / 待转入队列)→
|
||||
阶段1 处理业务(增加投保批量 / 要替换逐行)→
|
||||
阶段2 分配名额(复用空闲名额 / 全新新增);
|
||||
含姓名核对修正(J列)、特殊情况槽位追踪(离职/参保减少被复用后保留占位)、
|
||||
以及类别级编排 schedule_category(读取目标文件 → 各阶段 → 输出)。
|
||||
|
||||
文件路径/日期/常量统一来自 config 层;输出(在参名单/变更清单/备份/增减员导入)
|
||||
由 report.output 负责(本模块在编排处懒加载,避免与 report 相互 import 成环)。
|
||||
"""
|
||||
import os
|
||||
from collections import defaultdict
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SHEET_IN_PARAM, DATA_START_ROW,
|
||||
BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME, BIZ_COL_HANDLE,
|
||||
VALID_CATEGORIES, VALID_SCHEMES, category_target_file,
|
||||
category_output_backup, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, to_text, today_date,
|
||||
)
|
||||
|
||||
|
||||
class DataValidationError(Exception):
|
||||
"""数据校验失败异常:直接中断调度,禁止继续往后跑。"""
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、数据校验
|
||||
# ============================================================
|
||||
def validate_biz_data(biz_df):
|
||||
"""校验花名册业务数据的合法性。
|
||||
|
||||
校验规则:
|
||||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:人保-20万 / 50万 / 80万
|
||||
|
||||
返回 errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过。
|
||||
"""
|
||||
errors = []
|
||||
for idx, row in biz_df.iterrows():
|
||||
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
category = row[BIZ_COL_CATEGORY]
|
||||
scheme = row[BIZ_COL_SCHEME]
|
||||
handle = row[BIZ_COL_HANDLE]
|
||||
|
||||
if pd.isna(category) or category not in VALID_CATEGORIES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "工种类别非法",
|
||||
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}",
|
||||
})
|
||||
|
||||
if str(handle).strip() == "增加投保":
|
||||
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "投保方案非法",
|
||||
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}",
|
||||
})
|
||||
return errors
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、阶段0:初始化(从在参名单构建状态)
|
||||
# ============================================================
|
||||
def initialize(in_param_df):
|
||||
"""从「手动维护-在参名单」构建三个核心数据结构。
|
||||
|
||||
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
|
||||
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
|
||||
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
|
||||
|
||||
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
|
||||
"""
|
||||
idle_pools = defaultdict(list)
|
||||
employee_map = {}
|
||||
pending_queues = defaultdict(list)
|
||||
|
||||
IDX_EMP_ID = 10
|
||||
IDX_CUR_SCHEME = 12
|
||||
IDX_HANDLE = 17
|
||||
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[IDX_EMP_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
|
||||
handle = str(row.iloc[IDX_HANDLE]).strip()
|
||||
scheme = row.iloc[IDX_CUR_SCHEME]
|
||||
|
||||
if handle in ["无需", "档次替换"]:
|
||||
# 正常参保或待替换,都视为当前已参保
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
employee_map[emp_id] = scheme
|
||||
elif handle == "离职减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "离职减少", "employee_id": emp_id})
|
||||
elif handle == "参保减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "参保减少", "employee_id": emp_id})
|
||||
# 其他值(如'/')忽略
|
||||
|
||||
# 按优先级排序(离职减少优先)
|
||||
for scheme in idle_pools:
|
||||
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
|
||||
|
||||
return idle_pools, employee_map, pending_queues
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二点五、姓名核对修正(在参名单 J列 与 花名册 姓名比对)
|
||||
# ============================================================
|
||||
def collect_name_corrections(in_param_df, biz_df):
|
||||
"""核对「手动维护-在参名单」J列姓名与花名册「姓名」是否一致,并就地修正。
|
||||
|
||||
以证件号(在参名单 K列 / 花名册 O列)为关联键:
|
||||
- 在参名单中证件号存在、且花名册中能查到该证件号(覆盖离职减少/参保减少等全部行)
|
||||
- 两者姓名不一致且花名册姓名非空 → 记录一条修正,并把 in_param_df J列改为花名册姓名,
|
||||
使后续「删除记录 / 在参名单输出 / 减员导入」统一使用修正后姓名。
|
||||
- 花名册查不到(如已离职)无法核对,跳过不处理。
|
||||
|
||||
Returns:
|
||||
corrections: 修正列表,每项 {emp_id, old_name, new_name, category, scheme}
|
||||
"""
|
||||
biz_dict = {}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
corrections = []
|
||||
for idx, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
biz_row = biz_dict.get(emp_id)
|
||||
if biz_row is None:
|
||||
continue # 花名册查不到,无法核对,跳过
|
||||
new_name = biz_row.get("姓名")
|
||||
if new_name is None or pd.isna(new_name) or str(new_name).strip() == "":
|
||||
continue
|
||||
new_name = str(new_name).strip()
|
||||
old_name = row.iloc[9]
|
||||
old_name_txt = "" if pd.isna(old_name) else str(old_name).strip()
|
||||
if old_name_txt == new_name:
|
||||
continue # 姓名一致,无需修正
|
||||
# 就地修正 in_param_df J列(姓名),供后续统一使用
|
||||
in_param_df.at[idx, in_param_df.columns[9]] = new_name
|
||||
corrections.append({
|
||||
"emp_id": emp_id,
|
||||
"old_name": old_name_txt or "未知",
|
||||
"new_name": new_name,
|
||||
"category": biz_row.get(BIZ_COL_CATEGORY),
|
||||
"scheme": biz_row.get(BIZ_COL_SCHEME),
|
||||
})
|
||||
|
||||
if corrections:
|
||||
logger.info("姓名核对修正:共 %d 条", len(corrections))
|
||||
for c in corrections:
|
||||
logger.info(" %s:%s → %s", c["emp_id"], c["old_name"], c["new_name"])
|
||||
else:
|
||||
logger.info("姓名核对完成:在参名单与花名册姓名全部一致")
|
||||
return corrections
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、阶段1:处理花名册业务
|
||||
# ============================================================
|
||||
def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
"""遍历花名册业务数据,产生待转入队列和额外空闲名额。
|
||||
|
||||
业务类型:
|
||||
1. 增加投保 → 批量加入待转入队列
|
||||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||||
3. 其他 → 记录"非法事件跳过"
|
||||
|
||||
返回:idle_pools, employee_map, pending_queues, change_log
|
||||
"""
|
||||
change_log = []
|
||||
now = today_date()
|
||||
|
||||
# ---------- 1. 增加投保(批量处理) ----------
|
||||
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
|
||||
if not df_add.empty:
|
||||
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
|
||||
if pd.isna(scheme) or scheme == "":
|
||||
for _, row in group.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "投保方案为空,无法增加投保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
|
||||
pending_queues[scheme].extend(emp_ids)
|
||||
for emp_id in emp_ids:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "增加投保",
|
||||
"详情": f"加入 {scheme} 待转入队列",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
|
||||
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
|
||||
for _, row in df_replace.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
target_scheme = row[BIZ_COL_SCHEME]
|
||||
|
||||
# 校验:员工必须当前已参保
|
||||
origin_scheme = employee_map.get(emp_id)
|
||||
if origin_scheme is None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "员工当前未参保,无法进行档次替换",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pd.isna(target_scheme) or target_scheme == "":
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "目标方案为空",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
# 产生"档次替换迁出"名额
|
||||
idle_pools[origin_scheme].append({"type": "档次替换迁出", "employee_id": emp_id})
|
||||
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
|
||||
idle_pools[origin_scheme].sort(
|
||||
key=lambda x: 1 if x["type"] == "离职减少"
|
||||
else 2 if x["type"] == "参保减少"
|
||||
else 3)
|
||||
|
||||
# 员工置为未参保
|
||||
employee_map[emp_id] = None
|
||||
pending_queues[target_scheme].append(emp_id)
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "档次替换迁出",
|
||||
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 3. 其他未知类型 ----------
|
||||
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
|
||||
for _, row in df_other.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return idle_pools, employee_map, pending_queues, change_log
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、阶段2:分配名额
|
||||
# ============================================================
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
"""逐个方案处理待转入队列,分配空闲名额或创建新名额。
|
||||
|
||||
逻辑:
|
||||
1. 队列中的每个员工必须未参保
|
||||
2. 有空闲名额 → 复用(记录来源)
|
||||
3. 无空闲名额 → 全新新增
|
||||
|
||||
返回:final_records, change_log, reused_source_employees
|
||||
"""
|
||||
final_records = []
|
||||
reused_source_employees = []
|
||||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||||
now = today_date()
|
||||
|
||||
for scheme in all_schemes:
|
||||
queue = pending_queues.get(scheme, [])
|
||||
pool = idle_pools.get(scheme, [])
|
||||
|
||||
for emp_id in queue:
|
||||
# 校验:员工必须未参保
|
||||
if employee_map.get(emp_id) is not None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pool:
|
||||
# 复用空闲名额(取出优先级最高的)
|
||||
slot = pool.pop(0)
|
||||
reused_source_employees.append(slot["employee_id"])
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": slot["type"],
|
||||
"来源员工ID": slot["employee_id"],
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "复用空闲名额参保",
|
||||
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
|
||||
"来源员工ID": slot["employee_id"],
|
||||
"时间": now,
|
||||
})
|
||||
else:
|
||||
# 全新新增
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": "全新新增",
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "全新新增名额参保",
|
||||
"详情": f"新增名额,方案 {scheme}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return final_records, change_log, reused_source_employees
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四点半、特殊情况槽位追踪(report 层共用)
|
||||
# ============================================================
|
||||
def _find_special_slots(final_records, in_param_df):
|
||||
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
|
||||
|
||||
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
|
||||
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
|
||||
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
|
||||
|
||||
Returns:
|
||||
special_slots: [{source_id, source_name, source_category, new_scheme}, ...]
|
||||
"""
|
||||
# 初始参保映射:在参名单 M列(投保方案)非空视为"原已参保"
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
|
||||
slot_network = {}
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
slot_network[str(_sid).strip()] = _rec
|
||||
|
||||
# 链条追踪:离职/参保减少释放的名额被老员工复用后,沿"来源员工ID"网络一路追踪,
|
||||
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
|
||||
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
|
||||
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
|
||||
special_slots = []
|
||||
for rec in final_records:
|
||||
if rec.get("名额来源") not in ("离职减少", "参保减少"):
|
||||
continue
|
||||
source_id = rec.get("来源员工ID")
|
||||
# 源员工自身也参保则跳过,避免同一个人出现两条名单
|
||||
if source_id is None or pd.isna(source_id) or source_id in final_emp_ids:
|
||||
continue
|
||||
source_id = str(source_id).strip()
|
||||
# 沿链条追踪,找到末端"未被复用的旧方案"(空闲名额 X档)
|
||||
current_owner = source_id
|
||||
visited = set()
|
||||
loose_end_scheme = None
|
||||
while current_owner not in visited:
|
||||
visited.add(current_owner)
|
||||
next_rec = slot_network.get(current_owner)
|
||||
if next_rec is None:
|
||||
break # 链条断裂
|
||||
receiver_id = str(next_rec["证件号"]).strip()
|
||||
# 接收者不是原已参保老员工(全新新员工)-> 无旧方案可释放,链条自然结束
|
||||
if receiver_id not in initial_employee_map:
|
||||
break
|
||||
# 接收者是老员工:释放自己的旧方案(X档);若该旧名额无人复用则即为空闲名额
|
||||
if receiver_id not in slot_network:
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == receiver_id]
|
||||
if not row_match.empty:
|
||||
loose_end_scheme = row_match.iloc[0].iloc[12]
|
||||
break
|
||||
current_owner = receiver_id # 旧名额被复用,继续追踪下一环
|
||||
if not loose_end_scheme:
|
||||
continue
|
||||
src_match = in_param_df[in_param_df.iloc[:, 10] == source_id]
|
||||
if src_match.empty:
|
||||
continue
|
||||
src_row = src_match.iloc[0]
|
||||
special_slots.append({
|
||||
"source_id": source_id,
|
||||
"source_name": src_row.iloc[9],
|
||||
"source_category": src_row.iloc[11],
|
||||
"new_scheme": loose_end_scheme,
|
||||
})
|
||||
return special_slots
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五、类别级编排(读取目标文件 → 三阶段 → 输出)
|
||||
# ============================================================
|
||||
def _check_import_templates():
|
||||
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
|
||||
|
||||
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
|
||||
才发现模板缺失、需要重做的浪费。
|
||||
"""
|
||||
missing = [
|
||||
path for path in (add_import_template(), sub_import_template())
|
||||
if not os.path.isfile(path)
|
||||
]
|
||||
if missing:
|
||||
raise FileNotFoundError(
|
||||
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
|
||||
|
||||
|
||||
def schedule_category(category, enable_validation=True, gen_import_files=True):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
Args:
|
||||
category: 类别配置
|
||||
enable_validation: 是否启用数据校验(校验失败抛 DataValidationError 中断)
|
||||
gen_import_files: 是否生成增员/减员导入文件
|
||||
|
||||
前置:目标文件已完成筛选复制(roster_filter)并经 WPS/Excel 重算公式。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
output_backup = category_output_backup(category)
|
||||
change_sheet_prefix = category["change_sheet_prefix"]
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
logger.info("=" * 70)
|
||||
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
|
||||
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file},请先完成筛选复制步骤")
|
||||
|
||||
# 检查必需 Sheet
|
||||
xl = pd.ExcelFile(target_file)
|
||||
for s in (SHEET_BIZ, SHEET_IN_PARAM):
|
||||
if s not in xl.sheet_names:
|
||||
raise ValueError(f"目标表缺少必需 Sheet:{s}")
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
if gen_import_files:
|
||||
_check_import_templates()
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
# O列(索引14)证件号强制 dtype=str:含空行的列会被 pandas 推断为 float64,
|
||||
# 18 位身份证号读取即截断(如 ...0009 -> ...0000),导致与在参名单匹配失败
|
||||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3, dtype={14: str})
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
biz_df = biz_df[
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||||
]
|
||||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# ---------- 读取在参名单 ----------
|
||||
# K列(索引10)证件号同样强制 dtype=str,避免 float64 截断 18 位身份证号
|
||||
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5,
|
||||
dtype={10: str})
|
||||
logger.info("在参名单:%d 行", len(in_param_df))
|
||||
|
||||
# 主键文本化:证件号统一转文本(pandas 会把纯数字证件号读为 int64,openpyxl 落盘时
|
||||
# 转浮点会截断 18 位身份证号;统一文本化后匹配/输出全部一致且不丢精度)
|
||||
# 用整列赋值(允许自动升级 dtype),避免 float64 列 iloc 赋值报 LossySetitemError
|
||||
biz_df = biz_df.copy()
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID] = biz_df[BIZ_COL_EMPLOYEE_ID].map(to_text)
|
||||
in_param_df = in_param_df.copy()
|
||||
_id_col = in_param_df.columns[10]
|
||||
in_param_df[_id_col] = in_param_df[_id_col].map(to_text)
|
||||
column_names = in_param_df.columns.tolist()
|
||||
|
||||
# ---------- 姓名核对修正 ----------
|
||||
logger.info("核对在参名单与花名册姓名...")
|
||||
name_corrections = collect_name_corrections(in_param_df, biz_df)
|
||||
|
||||
# ---------- 数据校验 ----------
|
||||
if enable_validation:
|
||||
logger.info("正在校验数据...")
|
||||
errors = validate_biz_data(biz_df)
|
||||
if errors:
|
||||
for e in errors:
|
||||
logger.error(" 行%s 员工%s:%s - %s",
|
||||
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
|
||||
raise DataValidationError(
|
||||
f"类别[{category_name}] 数据校验失败,共 {len(errors)} 个错误,已中断调度")
|
||||
logger.info("数据校验通过!")
|
||||
|
||||
# ---------- 阶段0:初始化 ----------
|
||||
logger.info("初始化状态...")
|
||||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||||
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
|
||||
logger.info(" 当前参保员工:%d 人", len(employee_map))
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
logger.info("处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
biz_df, idle_pools, employee_map, pending_queues)
|
||||
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
|
||||
logger.info(" 变更日志条数:%d", len(change_log))
|
||||
|
||||
# ---------- 阶段2:分配名额 ----------
|
||||
logger.info("分配名额...")
|
||||
final_records, change_log, reused_source_employees = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log)
|
||||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||||
|
||||
# ---------- 阶段3+4:输出(懒加载 report,避免 import 成环) ----------
|
||||
from ..report.output import output_results, export_add_sub_import
|
||||
logger.info("输出结果...")
|
||||
output_results(
|
||||
final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, SHEET_IN_PARAM,
|
||||
name_corrections)
|
||||
|
||||
if gen_import_files:
|
||||
logger.info("生成增员/减员导入文件...")
|
||||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||||
|
||||
logger.info("类别[%s] 调度完成!", category_name)
|
||||
return final_records
|
||||
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - WPS/Excel COM 后台重算工具。
|
||||
|
||||
替代雇主险流程中「人工打开目标文件刷新公式(Ctrl+S 保存)」环节:
|
||||
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘。
|
||||
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → CalculateFullRebuild →
|
||||
Save;WPS 不可用时回退 MS Excel(Excel.Application)。全程后台静默(Visible=False)。
|
||||
"""
|
||||
import os
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
class ComRecalcError(RuntimeError):
|
||||
"""公式重算失败(文件被占用 / 本机无 WPS 专业版或 MS Excel / COM 异常)。"""
|
||||
|
||||
|
||||
def recalc_target(file_path):
|
||||
"""对单个 xlsx 执行「打开 → 全量重算 → 保存」。
|
||||
|
||||
Args:
|
||||
file_path: 目标文件绝对路径。
|
||||
|
||||
Raises:
|
||||
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / 文件正被 WPS 打开等)。
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.isfile(file_path):
|
||||
raise ComRecalcError(f"待重算文件不存在:{file_path}")
|
||||
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
engine = ""
|
||||
try:
|
||||
# 优先 WPS 表格 COM(Ket.Application);失败回退 MS Excel
|
||||
try:
|
||||
app = win32com.client.Dispatch("Ket.Application")
|
||||
engine = "WPS"
|
||||
except Exception:
|
||||
try:
|
||||
app = win32com.client.Dispatch("Excel.Application")
|
||||
engine = "Excel"
|
||||
except Exception as e:
|
||||
raise ComRecalcError(
|
||||
"本机未检测到可用的 WPS 表格 COM / MS Excel COM,无法自动重算公式。\n"
|
||||
"请安装 WPS 专业版/企业版或 MS Excel 后重试,或关闭「WPS/Excel 后台重算公式」开关后人工打开文件 Ctrl+S 刷新公式。"
|
||||
) from e
|
||||
|
||||
app.Visible = False # 后台不显示窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告
|
||||
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
|
||||
wb.Application.CalculateFullRebuild() # 强制完整重算全部公式
|
||||
wb.Save() # 把计算结果缓存写入 xlsx 磁盘
|
||||
wb.Close()
|
||||
logger.info("公式重算完成(%s COM):%s", engine, file_path)
|
||||
except ComRecalcError:
|
||||
raise
|
||||
except Exception as e:
|
||||
# 文件被用户手动打开时 COM 打开会失败/冲突,给出可操作提示
|
||||
raise ComRecalcError(
|
||||
f"公式重算失败({engine or 'COM'}):{e}\n"
|
||||
"请确认该目标文件未被 WPS/Excel 手动打开(关闭后再试)。"
|
||||
) from e
|
||||
finally:
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.4",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统),替代人工 Ctrl+S 刷新公式与人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0002"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base_dir": {
|
||||
"type": "string",
|
||||
"title": "雇主险根目录",
|
||||
"default": "D:\\资料\\人资\\雇主险",
|
||||
"description": "四类各占一个子文件夹(三十七度/水庄餐饮/湖畔酒店/秒创传媒),增/减员导入模板放在根目录"
|
||||
},
|
||||
"ref_date": {
|
||||
"type": "string",
|
||||
"title": "业务日期",
|
||||
"default": "",
|
||||
"description": "留空=今天;影响变更清单/在参名单/导入文件中的日期与备份文件名"
|
||||
},
|
||||
"categories": {
|
||||
"type": "array",
|
||||
"title": "处理类别(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"]
|
||||
},
|
||||
"default": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"],
|
||||
"description": "留空=全部类别"
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string",
|
||||
"title": "花名册路径",
|
||||
"default": "",
|
||||
"description": "留空=根目录/员工花名册.xlsx(源表缺失或超过 15 分钟 TTL 时自动从 HR 导出)"
|
||||
},
|
||||
"enable_validation": {
|
||||
"type": "boolean",
|
||||
"title": "启用数据校验",
|
||||
"default": true,
|
||||
"description": "校验工种类别与投保方案合法性,校验失败终止调度"
|
||||
},
|
||||
"wps_recalc": {
|
||||
"type": "boolean",
|
||||
"title": "WPS/Excel 后台重算公式",
|
||||
"default": true,
|
||||
"description": "筛选复制后/调度后自动打开目标文件全量重算并保存,替代人工 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
|
||||
},
|
||||
"export_change_sheet": {
|
||||
"type": "boolean",
|
||||
"title": "导出变更清单独立工作簿",
|
||||
"default": true,
|
||||
"description": "调度后将各类别变更清单 sheet 复制为独立工作簿(公式转值,保留样式)"
|
||||
},
|
||||
"gen_import_files": {
|
||||
"type": "boolean",
|
||||
"title": "生成增员/减员导入文件",
|
||||
"default": true,
|
||||
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
|
||||
},
|
||||
"import_to_hr": {
|
||||
"type": "boolean",
|
||||
"title": "自动导入HR系统",
|
||||
"default": true,
|
||||
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(浏览器自动化,先减员后增员,仅导入本次调度成功的类别);需本机 Chrome/Edge 且执行中会弹出浏览器窗口;须同时开启「生成增员/减员导入文件」"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 report 层:在参名单更新/变更清单/备份/增减员导入输出。"""
|
||||
@@ -0,0 +1,664 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 结果输出层(由影刀版 employer_insurance_schedule.py 阶段3/五点五 与
|
||||
export_change_sheet.py 合并移植)。
|
||||
|
||||
包含:
|
||||
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
|
||||
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
|
||||
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
|
||||
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
|
||||
(值+样式,公式转缓存结果,避免 #REF!)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from copy import copy
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, DATA_START_ROW, BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME,
|
||||
category_import_add_file, category_import_sub_file, category_target_file,
|
||||
category_change_sheet_workbook, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, today_date,
|
||||
to_text, clean_text, to_date,
|
||||
)
|
||||
from ..logic.schedule import _find_special_slots, scheme_with_suffix
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、输出结果(在参名单 + 变更清单 + 备份 + 姓名修正)
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, in_param_sheet,
|
||||
name_corrections=None):
|
||||
"""输出四部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
"""
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
for rec in final_records:
|
||||
emp_ids_to_clear.add(rec["证件号"])
|
||||
emp_ids_to_clear.update(reused_source_employees)
|
||||
|
||||
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
|
||||
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录)
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
special_source_ids = set(s["source_id"] for s in special_slots)
|
||||
special_src_scheme = {s["source_id"]: s["new_scheme"] for s in special_slots}
|
||||
if special_slots:
|
||||
logger.info("特殊情况:离职/参保减少名额被老员工复用,链条末端空闲名额 %d 例(源员工改为空闲方案保留)",
|
||||
len(special_slots))
|
||||
for s in special_slots:
|
||||
logger.info(" 源 %s -> 改为方案 %s", s["source_id"], s["new_scheme"])
|
||||
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
keep_mask = (
|
||||
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
|
||||
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees))) |
|
||||
(in_param_df[emp_id_col].isin(special_source_ids)) # 特殊情况源员工保留(改M列为老员工旧方案)
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
|
||||
# ---------- 3. 构建员工信息字典 ----------
|
||||
biz_dict = {}
|
||||
for idx, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
# ---------- 4. 构建新参保记录(B~N列) ----------
|
||||
new_records = []
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id not in biz_dict:
|
||||
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
|
||||
continue
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": to_text(row_biz.get("工号")), # B列工号必须为文本
|
||||
"C": row_biz.get("年龄"),
|
||||
"D": row_biz.get("性别"),
|
||||
"E": row_biz.get("岗位"),
|
||||
"F": row_biz.get("职位序列"),
|
||||
"G": row_biz.get("参保类型"),
|
||||
"H": row_biz.get("上下班交通方式"),
|
||||
"I": row_biz.get("入职时间"),
|
||||
"J": row_biz.get("姓名"),
|
||||
"K": row_biz.get("证件号"),
|
||||
"L": row_biz.get("工种类别"),
|
||||
"M": row_biz.get("投保方案"),
|
||||
"N": today_date(),
|
||||
})
|
||||
|
||||
# ---------- 5. 打开工作簿 ----------
|
||||
wb = load_workbook(target_file)
|
||||
ws = wb[in_param_sheet]
|
||||
max_row = ws.max_row
|
||||
|
||||
# ---------- 6. 读取现有数据 ----------
|
||||
existing_rows = []
|
||||
for row_idx in range(DATA_START_ROW, max_row + 1):
|
||||
row_data = []
|
||||
for col in range(1, 27):
|
||||
row_data.append(ws.cell(row=row_idx, column=col).value)
|
||||
existing_rows.append({
|
||||
"row_idx": row_idx,
|
||||
"data": row_data,
|
||||
"emp_id": ws.cell(row=row_idx, column=11).value, # K列
|
||||
})
|
||||
|
||||
# ---------- 7. 构建新数据列表 ----------
|
||||
new_rows = []
|
||||
|
||||
# 姓名修正映射(证件号 -> 新姓名),保留行 J列姓名统一改为花名册姓名
|
||||
corr_by_id = {c["emp_id"]: c["new_name"] for c in (name_corrections or [])}
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
row_data = row_info["data"]
|
||||
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),N列投保日期更新为今天
|
||||
if emp_id in special_src_scheme:
|
||||
row_data[12] = special_src_scheme[emp_id]
|
||||
row_data[13] = today_date() # N列 投保日期
|
||||
# 姓名核对修正:J列姓名改为花名册姓名
|
||||
if emp_id in corr_by_id:
|
||||
row_data[9] = corr_by_id[emp_id]
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": emp_id,
|
||||
"action": "keep",
|
||||
})
|
||||
|
||||
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动;特殊情况源员工已保留,此处不清空)
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if (emp_id in emp_ids_to_clear and emp_id not in special_source_ids) or emp_id is None:
|
||||
row_data = row_info["data"].copy()
|
||||
for i in range(1, 14):
|
||||
row_data[i] = None
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": None,
|
||||
"action": "clear",
|
||||
})
|
||||
|
||||
# 7.3 填充新记录到空行
|
||||
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
|
||||
empty_slots.sort(key=lambda x: x["row_idx"])
|
||||
|
||||
def _fill(row_data, rec):
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
|
||||
for rec in new_records:
|
||||
if empty_slots:
|
||||
slot = empty_slots.pop(0)
|
||||
row_data = slot["data"]
|
||||
_fill(row_data, rec)
|
||||
slot["emp_id"] = rec["K"]
|
||||
slot["action"] = "filled"
|
||||
else:
|
||||
# 追加新行(复制上一行样式)
|
||||
row_data = [None] * 26
|
||||
if existing_rows:
|
||||
src_row_idx = existing_rows[-1]["row_idx"]
|
||||
for col in range(1, 27):
|
||||
src_cell = ws.cell(row=src_row_idx, column=col)
|
||||
dst_cell = ws.cell(row=max_row + 1, column=col)
|
||||
if src_cell.has_style:
|
||||
dst_cell.font = copy(src_cell.font)
|
||||
dst_cell.border = copy(src_cell.border)
|
||||
dst_cell.fill = copy(src_cell.fill)
|
||||
dst_cell.number_format = src_cell.number_format
|
||||
dst_cell.alignment = copy(src_cell.alignment)
|
||||
last_row_data = existing_rows[-1]["data"]
|
||||
for i in range(14, 26):
|
||||
row_data[i] = last_row_data[i]
|
||||
_fill(row_data, rec)
|
||||
new_rows.append({
|
||||
"row_idx": None,
|
||||
"data": row_data,
|
||||
"emp_id": rec["K"],
|
||||
"action": "append",
|
||||
})
|
||||
|
||||
# ---------- 8. 更新现有行(B~N列,列号=索引+1;B列工号强制文本) ----------
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is not None:
|
||||
row_idx = row_info["row_idx"]
|
||||
row_data = row_info["data"]
|
||||
for idx in range(1, 14):
|
||||
c = ws.cell(row=row_idx, column=idx + 1)
|
||||
if idx == 1:
|
||||
c.value = to_text(row_data[idx])
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = row_data[idx]
|
||||
|
||||
# ---------- 9. 追加新行 ----------
|
||||
current_row = max_row + 1
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is None:
|
||||
row_idx = current_row
|
||||
row_data = row_info["data"]
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
c = ws.cell(row=row_idx, column=col_idx)
|
||||
if col_idx == 2:
|
||||
c.value = to_text(value)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = value
|
||||
current_row += 1
|
||||
|
||||
# ---------- 9.5 紧凑化:消除中间空行(只搬移 B~O 数据列,公式列 R/S/T/U/V/W 不动) ----------
|
||||
data_values = []
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
has_data = any(
|
||||
ws.cell(row=row_idx, column=c).value not in (None, "")
|
||||
for c in range(2, 16)
|
||||
)
|
||||
if has_data:
|
||||
data_values.append([ws.cell(row=row_idx, column=c).value for c in range(2, 16)])
|
||||
target_row = DATA_START_ROW
|
||||
for vals in data_values:
|
||||
for col, v in enumerate(vals, start=2):
|
||||
cell = ws.cell(row=target_row, column=col)
|
||||
if col == 2: # B列 工号 强制文本
|
||||
cell.value = to_text(v)
|
||||
cell.number_format = "@"
|
||||
elif col == 14: # N列 投保日期 -> 日期类型 + yyyy-mm-dd
|
||||
cell.value = to_date(v)
|
||||
if cell.value is not None:
|
||||
cell.number_format = "yyyy-mm-dd"
|
||||
else:
|
||||
cell.value = v
|
||||
target_row += 1
|
||||
# 清空多出部分的 B~O 列(公式列不动)
|
||||
for row_idx in range(target_row, current_row):
|
||||
for col in range(2, 16):
|
||||
ws.cell(row=row_idx, column=col).value = None
|
||||
|
||||
# ---------- 10. 重新编号A列 ----------
|
||||
seq = 1
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
if ws.cell(row=row_idx, column=11).value is not None:
|
||||
ws.cell(row=row_idx, column=1).value = seq
|
||||
seq += 1
|
||||
else:
|
||||
ws.cell(row=row_idx, column=1).value = None
|
||||
|
||||
# ============================================================
|
||||
# ★★★ 11. 精细更新变更清单 ★★★
|
||||
# ============================================================
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
# 收集所有以类别变更清单前缀开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(change_sheet_prefix) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
|
||||
|
||||
template_name = max(candidates, key=_template_sort_key) if candidates else None
|
||||
|
||||
if template_name is not None:
|
||||
# 复制最近一次的历史模板Sheet(保留公式与样式)
|
||||
source = wb[template_name]
|
||||
target = wb.copy_worksheet(source)
|
||||
target.title = change_sheet_name
|
||||
logger.info("已从模板 [%s] 复制变更清单", template_name)
|
||||
else:
|
||||
# 没有任何历史模板,创建新Sheet(兜底)
|
||||
ws_change = wb.create_sheet(change_sheet_name)
|
||||
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
|
||||
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
|
||||
"工作单位", "", "备注", "批改日期", "新增费用会馆",
|
||||
"姓名", "证件号", "工种类别", "投保方案"]
|
||||
for col_idx, h in enumerate(headers, start=1):
|
||||
ws_change.cell(row=1, column=col_idx).value = h
|
||||
ws_change.cell(row=2, column=1).value = "公式"
|
||||
ws_change = wb[change_sheet_name]
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
|
||||
DEPT_COL_MARK = "费用会馆"
|
||||
dept_col = 15
|
||||
for _col in range(1, 21):
|
||||
if any(DEPT_COL_MARK in str(ws_change.cell(row=_row, column=_col).value or "")
|
||||
for _row in (1, 2)):
|
||||
dept_col = _col
|
||||
break
|
||||
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
|
||||
|
||||
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
|
||||
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
|
||||
|
||||
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
|
||||
max_row_change = ws_change.max_row
|
||||
if max_row_change >= 3:
|
||||
for row in range(3, max_row_change + 1):
|
||||
ws_change.cell(row=row, column=2).value = None # B列
|
||||
ws_change.cell(row=row, column=13).value = None # M列 备注
|
||||
ws_change.cell(row=row, column=14).value = None # N列
|
||||
ws_change.cell(row=row, column=dept_col).value = None # 四级部门列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 收集变更记录
|
||||
records = []
|
||||
|
||||
# 1. 删除记录(特殊情况源员工一并输出"增加老员工旧方案",保证增减平衡)
|
||||
for emp_id in emp_ids_to_clear:
|
||||
if emp_id in final_emp_ids:
|
||||
continue
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row = row_match.iloc[0]
|
||||
name = row.iloc[9]
|
||||
category = row.iloc[11]
|
||||
scheme = row.iloc[12]
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
# 特殊情况:源员工名额被老员工复用且老员工旧名额无人复用 -> 源员工改为该旧方案
|
||||
if emp_id in special_src_scheme:
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": special_src_scheme[emp_id]})
|
||||
else:
|
||||
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
|
||||
"category": "未知", "scheme": "未知"})
|
||||
|
||||
# 2. 增加记录。档次替换仅当「自己的名额档次替换、不涉及其他人」时合并为一条「修改」
|
||||
# 收集「自己的旧名额被他人复用」的员工集合(来源员工ID)
|
||||
reused_by_others = set()
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
reused_by_others.add(_sid)
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
row_biz = biz_dict[emp_id]
|
||||
name = row_biz.get("姓名")
|
||||
category = row_biz.get("工种类别")
|
||||
scheme = row_biz.get("投保方案")
|
||||
else:
|
||||
name = category = scheme = None
|
||||
if emp_id in initial_employee_map:
|
||||
# 原已参保(档次替换):仅"自己的名额档次替换、不涉及其他人"才合并为「修改」
|
||||
pure_self_replace = (
|
||||
rec.get("名额来源") == "全新新增" and
|
||||
emp_id not in reused_by_others
|
||||
)
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
old_scheme = None
|
||||
if not row_match.empty:
|
||||
old_scheme = row_match.iloc[0].iloc[12]
|
||||
if pure_self_replace:
|
||||
remark = None
|
||||
if old_scheme is not None and str(old_scheme).strip() != "" and \
|
||||
scheme is not None and str(scheme).strip() != "":
|
||||
remark = f"由{old_scheme}替换为{scheme}"
|
||||
records.append({"op": "修改", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme, "remark": remark})
|
||||
else:
|
||||
# 涉及其他人的档次替换:正常两条(删除旧方案 + 增加新方案)
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": old_scheme})
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
else:
|
||||
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 O列 填四级部门
|
||||
new_rec = {"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme}
|
||||
if rec.get("名额来源") == "全新新增":
|
||||
biz_row_dept = biz_dict.get(emp_id)
|
||||
dept = clean_text(biz_row_dept.get(biz_dept_col)) if biz_row_dept is not None else None
|
||||
if dept is None:
|
||||
# 四级部门为空:回退填所属单位,并记录日志供人工核对
|
||||
dept = clean_text(biz_row_dept.get("所属单位")) if biz_row_dept is not None else None
|
||||
logger.warning("员工 %s(%s) 花名册四级部门为空,O列回退填所属单位:%s",
|
||||
name, emp_id, dept)
|
||||
new_rec["dept"] = dept
|
||||
records.append(new_rec)
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for rec in records:
|
||||
op = rec.get("op")
|
||||
name = rec.get("name")
|
||||
emp_id = rec.get("emp_id")
|
||||
category = rec.get("category")
|
||||
scheme = rec.get("scheme")
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=13).value = rec.get("remark") # M列 备注
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date() # N列
|
||||
# 四级部门列:仅纯新增名额(全新新增)的「增加」记录才填
|
||||
if op == "增加" and rec.get("dept") is not None:
|
||||
ws_change.cell(row=current_row_change, column=dept_col).value = rec.get("dept")
|
||||
ws_change.cell(row=current_row_change, column=16).value = name # P列
|
||||
ws_change.cell(row=current_row_change, column=17).value = emp_id # Q列
|
||||
ws_change.cell(row=current_row_change, column=18).value = category # R列
|
||||
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
|
||||
current_row_change += 1
|
||||
|
||||
# 3. 姓名修正记录(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
for corr in (name_corrections or []):
|
||||
ws_change.cell(row=current_row_change, column=2).value = "修改"
|
||||
ws_change.cell(row=current_row_change, column=13).value = \
|
||||
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}"
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date()
|
||||
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"]
|
||||
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"]
|
||||
ws_change.cell(row=current_row_change, column=18).value = corr.get("category")
|
||||
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme")
|
||||
current_row_change += 1
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
|
||||
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
|
||||
logger.info("变更清单已精细更新(共 %d 条变更记录,含 %d 条姓名修正)",
|
||||
len(records) + len(name_corrections or []), len(name_corrections or []))
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、生成增员/减员导入文件(HR「待增减人员」页面上传素材)
|
||||
# ============================================================
|
||||
def _write_import_file(template_path, out_path, rows):
|
||||
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。"""
|
||||
if not os.path.isfile(template_path):
|
||||
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
|
||||
wb = load_workbook(template_path)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for i, row_vals in enumerate(rows):
|
||||
excel_row = 4 + i
|
||||
for col_idx, val in enumerate(row_vals, start=1):
|
||||
c = ws.cell(row=excel_row, column=col_idx)
|
||||
if col_idx == 2: # 工号/身份证列强制文本
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
wb.save(out_path)
|
||||
logger.info("已生成导入文件:%s(%d 条)", out_path, len(rows))
|
||||
|
||||
|
||||
def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees):
|
||||
"""生成各类别「商业保险增员导入.xlsx / 商业保险减员导入.xlsx」(HR 上传素材)。
|
||||
|
||||
集合差模型:按「人 + 投保方案」记录级做差:
|
||||
- 减员 = 原参保记录 − 新参保记录
|
||||
- 增员 = 新参保记录 − 原参保记录
|
||||
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
|
||||
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
|
||||
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
|
||||
|
||||
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错。
|
||||
"""
|
||||
# ---------- 1. 原参保记录集合 ----------
|
||||
orig_records = {} # to_text(证件号) -> 方案
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
scheme = row.iloc[12]
|
||||
if pd.isna(scheme) or str(scheme).strip() == "":
|
||||
continue
|
||||
orig_records[to_text(emp_id)] = scheme
|
||||
|
||||
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录 + 特殊情况保留源员工) ----------
|
||||
cleared_ids = set(to_text(e) for e in reused_source_employees)
|
||||
cleared_ids.update(to_text(rec["证件号"]) for rec in final_records)
|
||||
new_records_map = {
|
||||
emp_id: scheme for emp_id, scheme in orig_records.items()
|
||||
if emp_id not in cleared_ids
|
||||
}
|
||||
for rec in final_records:
|
||||
new_records_map[to_text(rec["证件号"])] = rec["投保方案"]
|
||||
# 特殊情况源员工(离职/参保减少名额被复用后保留在参名单,方案改为空闲方案):
|
||||
# 纳入"新参保记录"参与集合差,保证减员/增员对称、不漏人
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
for _s in special_slots:
|
||||
new_records_map[to_text(_s["source_id"])] = _s["new_scheme"]
|
||||
|
||||
# ---------- 3. 记录级集合差:减员名单 ----------
|
||||
sub_ids = [
|
||||
emp_id for emp_id, orig_scheme in orig_records.items()
|
||||
if emp_id not in new_records_map or new_records_map[emp_id] != orig_scheme
|
||||
]
|
||||
|
||||
# ---------- 4. 员工信息查询(biz_df 优先,其次 in_param_df) ----------
|
||||
emp_info = {} # to_text(证件号) -> {"工号": ..., "姓名": ...}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.iloc[1]), "姓名": row.iloc[9]}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.get("工号")), "姓名": row.get("姓名")}
|
||||
|
||||
def _code(emp_id):
|
||||
"""工号/身份证列:优先工号,空则回退证件号。"""
|
||||
return clean_text(emp_info.get(emp_id, {}).get("工号")) or clean_text(emp_id)
|
||||
|
||||
def _name(emp_id):
|
||||
return clean_text(emp_info.get(emp_id, {}).get("姓名"))
|
||||
|
||||
# ---------- 5. 组装行数据 ----------
|
||||
sub_rows, skipped_sub = [], 0
|
||||
for i, emp_id in enumerate(sub_ids, start=1):
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_sub += 1
|
||||
logger.warning("减员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
sub_rows.append([i, _code(emp_id), name, today_date()])
|
||||
|
||||
add_rows, skipped_add, seq = [], 0, 0
|
||||
for rec in final_records:
|
||||
emp_id = to_text(rec["证件号"])
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, rec["投保方案"]), today_date(),
|
||||
rec.get("名额来源") or "新增"])
|
||||
# 特殊情况源员工(保留在参名单,方案改为空闲方案)也需增员(新增该方案),不漏人
|
||||
for _s in special_slots:
|
||||
emp_id = to_text(_s["source_id"])
|
||||
new_scheme = _s["new_scheme"]
|
||||
# 方案未变(极少见边界)则无需增员
|
||||
if emp_id in orig_records and orig_records[emp_id] == new_scheme:
|
||||
continue
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:特殊情况源员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, new_scheme), today_date(),
|
||||
"特殊情况保留名额"])
|
||||
|
||||
# ---------- 6. 写入模板(保留第1~3行,第4行起填数据) ----------
|
||||
_write_import_file(sub_import_template(), category_import_sub_file(category), sub_rows)
|
||||
_write_import_file(add_import_template(), category_import_add_file(category), add_rows)
|
||||
|
||||
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
|
||||
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
|
||||
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、导出变更清单独立工作簿(值 + 样式,公式转缓存结果)
|
||||
# ============================================================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
requests
|
||||
pandas
|
||||
openpyxl
|
||||
websocket-client
|
||||
pywin32
|
||||
DrissionPage
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>雇主险增减操作</title>
|
||||
<script type="module" crossorigin src="/pui/xq0002/assets/index-1OHEXMMP.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-D-w0FhnS.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -28,7 +28,7 @@ class KqSealCheckPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0011"
|
||||
name = "考勤月报封存检查"
|
||||
version = "1.2.0"
|
||||
version = "1.2.1"
|
||||
description = ("考勤月报封存后自动检查:拉取当月全集团封存数据并按白名单单位预处理,"
|
||||
"自动导出花名册/调动台账,依次执行 6 项检查(在职天数排班/出勤及排休/"
|
||||
"封存最新值/全勤验证/未封存名单/延时加班),输出单工作簿异常名单")
|
||||
|
||||
@@ -192,6 +192,12 @@ def _parse_date(v) -> Optional[date]:
|
||||
return None
|
||||
|
||||
|
||||
def _fmt_date(v) -> str:
|
||||
"""日期格式化为 yyyy-mm-dd(如 2026-09-21 00:00:00 → 2026-09-21)。"""
|
||||
d = _parse_date(v)
|
||||
return d.isoformat() if d else _clean(v)[:10]
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
@@ -313,10 +319,15 @@ def enrich_dept_fields(target: dict, code: str, rec: dict = None,
|
||||
rec = rec or {}
|
||||
target["所属单位"] = info.get("所属单位") or _clean(rec.get("BELONG_UNIT_ORG_NAME"))
|
||||
target["岗位"] = info.get("岗位") or _clean(rec.get("POST_ALIAS_NAME"))
|
||||
target["入职时间"] = info.get("入职时间") or _clean(rec.get("join_date"))
|
||||
target["入职时间"] = _fmt_date(info.get("入职时间") or _clean(rec.get("join_date")))
|
||||
# 离职时间以封存记录为准(封存的是检查月当月实际状态):存在离职后又复职的员工,
|
||||
# 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底
|
||||
target["离职时间"] = _clean(rec.get("leaveOffice_date")) or info.get("离职时间")
|
||||
# 其最新花名册离职日期已被清空,若以花名册为准会漏判当月曾离职;花名册仅作兜底。
|
||||
# 优先取「封存快照」离职时间 seal_leaveOffice_date(保留检查月离职日期),
|
||||
# 其次当前离职时间 leaveOffice_date,最后花名册。
|
||||
target["离职时间"] = _fmt_date(
|
||||
_clean(rec.get("seal_leaveOffice_date"))
|
||||
or _clean(rec.get("leaveOffice_date"))
|
||||
or info.get("离职时间"))
|
||||
for chn, cn, f in zip(DEPT_CN_ORDER, ROSTER_DEPT_COLS, DEPT_ORG_FIELDS):
|
||||
target[cn] = info.get(cn) or _clean(rec.get(f))
|
||||
return target
|
||||
|
||||
@@ -24,7 +24,9 @@ NOTE_SECOND_HIRE = "员工二次入职,无法校验具体的在职天数,需
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_NAME_FIELD = "staff_name"
|
||||
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
|
||||
SEAL_JOIN_FIELD_SEAL = "seal_join_date" # 封存快照入职日期(离职后复职可能保留原始入职日期)
|
||||
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
|
||||
SEAL_LEAVE_FIELD_SEAL = "seal_leaveOffice_date" # 封存快照离职时间(离职后复职时当前离职时间被清空,以快照为准)
|
||||
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天
|
||||
|
||||
@@ -99,8 +101,13 @@ def run_working_days_shift_check(month: str = None, save_dir: str = None,
|
||||
|
||||
abnormal: List[dict] = []
|
||||
for code, rec in seal_map.items():
|
||||
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
|
||||
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
|
||||
# 入离职时间以「封存快照」为准:离职后复职的员工,当前 leaveOffice_date 会被清空,
|
||||
# 但 seal_leaveOffice_date 保留了检查月的离职日期;快照缺失时兜底当前值。
|
||||
# 否则会把整月算作在职,在职天数被高估导致误报(如 8/21 离职 → 误算 31 天)。
|
||||
join = (_parse_date(rec.get(SEAL_JOIN_FIELD_SEAL))
|
||||
or _parse_date(rec.get(SEAL_JOIN_FIELD)))
|
||||
leave = (_parse_date(rec.get(SEAL_LEAVE_FIELD_SEAL))
|
||||
or _parse_date(rec.get(SEAL_LEAVE_FIELD)))
|
||||
wd = _working_days(first, last, join, leave)
|
||||
if wd <= 0:
|
||||
continue # 当月无在职日,跳过
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0011",
|
||||
"name": "考勤月报封存检查",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"description": "考勤月报封存后自动检查:拉取当月全集团封存数据并按白名单单位预处理,自动导出花名册/调动台账,依次执行 6 项检查(在职天数排班/出勤及排休/封存最新值/全勤验证/未封存名单/延时加班),输出单工作簿异常名单",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
品牌管理公司(重庆金色印象品牌管理有限公司)、其他账号(其余商户),原全量文件保留。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
@@ -37,8 +37,19 @@ def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _default_day():
|
||||
"""昨日(YYYY-MM-DD),日期留空时由插件按执行日推算(定时任务无需固定日期)。"""
|
||||
return f"{date.today() - timedelta(days=1):%Y-%m-%d}"
|
||||
|
||||
|
||||
def _default_month():
|
||||
"""上月(YYYY-MM),月份留空时由插件按执行日推算。"""
|
||||
first = date.today().replace(day=1)
|
||||
return f"{first - timedelta(days=1):%Y-%m}"
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(前端已用日期选择器选好值,这里只做组装)。"""
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(留空默认值已在 run() 解析区补齐)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
@@ -52,7 +63,7 @@ def _build_tasks(mode, day_date, month_date):
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.9"
|
||||
version = "1.0.11"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地,"
|
||||
"并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿")
|
||||
@@ -66,8 +77,10 @@ class TongLianExportPlugin(ScenePlugin):
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": ""},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": ""},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": "",
|
||||
"description": "留空=昨日(插件按执行日推算)"},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": "",
|
||||
"description": "留空=上月(插件按执行日推算)"},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
@@ -95,6 +108,14 @@ class TongLianExportPlugin(ScenePlugin):
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
# 日期留空 = 插件内按执行日推算默认值(按日→昨日、按月→上月),
|
||||
# 定时任务方案无需固定日期,到点自动导最近的昨日/上月
|
||||
if mode in (MODE_DAY, MODE_BOTH) and not day_date:
|
||||
day_date = _default_day()
|
||||
ctx.log(f"按日导出未选日期,默认导昨日:{day_date}")
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and not month_date:
|
||||
month_date = _default_month()
|
||||
ctx.log(f"按月导出未选月份,默认导上月:{month_date}")
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.9",
|
||||
"version": "1.0.11",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为金色印象门店/品牌管理公司/其他账号 3 个工作簿",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
@@ -35,14 +35,14 @@
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "默认昨天;交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
"description": "留空=昨日(插件按执行日推算,定时任务无需固定日期);交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "默认上月;交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
"description": "留空=上月(插件按执行日推算,定时任务无需固定月份);交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+23
-23
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>金色印象通联数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0045_xq0046/assets/index-Bge9B6U7.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-qWMFdWZT.css">
|
||||
<script type="module" crossorigin src="/pui/xq0045_xq0046/assets/index-qs3ay3HR.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-C-Ir0bBb.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Reference in New Issue
Block a user