feat(xq0002): 完成雇主险增减操作插件开发并补齐配套资源

- 新增XQ0002雇主险增减操作插件完整实现,包含数据层、逻辑层、UI界面
- 新增测试用的样板数据文件与插件打包脚本
- 更新文档说明插件当前状态与使用方式
- 新增收银系统登录共享模块供业务流程复用
This commit is contained in:
2026-09-22 12:41:16 +08:00
parent a4c172bc98
commit dd546fc07b
39 changed files with 5938 additions and 204 deletions
+206 -71
View File
@@ -1,73 +1,208 @@
{
"code" : 200,
"message" : "操作成功",
"data" : {
"total" : 177,
"start" : 0,
"pageCount" : 4,
"list" : [ {
"teamId" : "3684cc0fc82649d2b9670df19778bb57",
"teamName" : "集团仓储及驾驶员(固休+法定)",
"ext_if_open_kq_month" : "1",
"type" : "3",
"inUse" : "1",
"orgId" : "596bae33-50e9-11ec-b526-822ff8ed5b28",
"priority" : 2,
"workDayId" : "909178c0-c03e-46bf-a49a-8e52169eaa99",
"kqMode" : "1,2",
"verifyAddr" : "0",
"dkNumType" : "2",
"struLevel" : 1,
"ruleId" : "2d4266f85ffc4576baa8e2d2f699494d",
"struId" : "596bae33-50e9-11ec-b526-822ff8ed5b28",
"workDateName" : "集团本部库管及驾驶员",
"workCreateUserId" : "b28cea41-bce3-4fed-8383-4657ce1c115b",
"paibanType" : "2",
"ruleName" : "职能人员考勤规则(含总经理)",
"operateTime" : "2026-09-08 10:06:17",
"createTime" : "2026-08-26 11:02:43",
"ifPaibanGroup" : "0",
"operator_id" : "d3383802-8b3f-4c55-a1bd-a3566cb93e55",
"teamCreateUserId" : "b28cea41-bce3-4fed-8383-4657ce1c115b",
"orgName" : "集团",
"createUserName" : "陈莲",
"operatorName" : "张玲玲",
"paibanName" : "人工排班",
"if_share" : 0,
"only_share" : 0
}, {
"teamId" : "4b40eca3fa8145a9a8404cc7f53e68fd",
"teamName" : "集团本部厨房(固休+法定)",
"ext_if_open_kq_month" : "1",
"type" : "3",
"inUse" : "1",
"orgId" : "596bae33-50e9-11ec-b526-822ff8ed5b28",
"priority" : 1,
"workDayId" : "497c22c9-de37-4791-a6bf-9e307aed76a6",
"kqMode" : "1,2",
"verifyAddr" : "0",
"dkNumType" : "0",
"struLevel" : 2,
"ruleId" : "2d4266f85ffc4576baa8e2d2f699494d",
"struId" : "596bae33-50e9-11ec-b526-822ff8ed5b28",
"workDateName" : "集团本部厨房",
"workCreateUserId" : "d3383802-8b3f-4c55-a1bd-a3566cb93e55",
"paibanType" : "2",
"ruleName" : "职能人员考勤规则(含总经理)",
"operateTime" : "2026-09-08 10:06:08",
"createTime" : "2022-03-30 20:15:29",
"ifPaibanGroup" : "0",
"operator_id" : "d3383802-8b3f-4c55-a1bd-a3566cb93e55",
"teamCreateUserId" : "d3383802-8b3f-4c55-a1bd-a3566cb93e55",
"orgName" : "集团",
"createUserName" : "张玲玲",
"operatorName" : "张玲玲",
"paibanName" : "人工排班",
"if_share" : 0,
"only_share" : 0
}]
},
"des" : null,
"errStack" : null,
"success" : true
"code": 200,
"msg": "Success",
"data": [
{
"store_id": 36,
"open_store_id": "00162",
"brand_id": 1,
"brand_name": "金色印象",
"store_name": "加州CEO会馆",
"store_address": null,
"store_phone": null,
"store_longitude": null,
"store_latitude": null,
"center_name": "金色印象事业部",
"part_name": "第三片区",
"store_manager": "黄凤",
"store_manager_phone": null,
"store_visible": true,
"store_key": "95682799-5af7-4ff6-8e15-695eaa7fb12a",
"store_photo": null,
"store_no": null,
"extra": null,
"hr_json_extra": {
"beginDate": "2022-01-21 00:00:00",
"branchLeaderCode": "37027103",
"branchLeaderId": "e1360067-9871-451d-97d3-b168df74ce82",
"branchLeaderName": "李燕",
"cantCode": "500000",
"cantName": "重庆市",
"costOrgCode": null,
"costOrgId": null,
"costOrgName": null,
"country": "",
"createTime": "2022-01-21 15:03:58",
"endDate": null,
"extendItems": [
{
"columnComment": "发薪日",
"columnName": "ext_payday",
"columnValue": "11"
},
{
"columnComment": "办公详细地址",
"columnName": "ext_office_address",
"columnValue": ""
},
{
"columnComment": "负责人编码",
"columnName": "ext_principal_num",
"columnValue": ""
}
],
"foundDate": "2022-01-21",
"foundReason": null,
"globalOrder": "1106109101110101",
"hrbpCode": null,
"hrbpId": null,
"hrbpLeaderCode": null,
"hrbpLeaderId": null,
"hrbpLeaderName": null,
"hrbpName": null,
"inUse": "1",
"kqCommissionerCode": null,
"kqCommissionerId": null,
"kqCommissionerName": null,
"manageOrgCode": null,
"manageOrgName": null,
"manageStaff": null,
"manageStaffCode": null,
"manageStaffId": null,
"manageStruId": null,
"officeAddress": "1",
"operateTime": "2026-08-03 09:19:01",
"orgCode": "00162",
"orgFullPath": "集团-金色印象事业部-第一大区-金色印象重庆第一经营中心-第三片区-加州CEO会馆",
"orgId": "2acb10bd-cbdb-4ebf-86a3-980de8b35dca",
"orgName": "加州CEO会馆",
"orgTypeCode": "49",
"orgTypeName": "会馆",
"parentOrgCode": "00144",
"parentOrgId": "33562286-627b-4f33-8dbc-53947be08f05",
"parentOrgName": "第三片区",
"principalStaff": "黄凤",
"principalStaffCode": "37000189",
"principalStaffId": "4b5105b8-7a9f-11ec-b449-000c296f9469",
"remarks": null,
"salaryCommissionerCode": null,
"salaryCommissionerId": null,
"salaryCommissionerName": null,
"shortName": "加州CEO会馆",
"struOrder": 101.0,
"unitOrgCode": "00738",
"unitOrgId": "0bcdee12-e592-11ee-b449-000c296f9469",
"unitOrgName": "金色印象事业部"
},
"crm_json_extra": {
"host": "https://api.shuhe.crm.waf.37du.co",
"shop_id": "10085",
"shop_key": "fT3vJb1SmF7RfHBQ4NWds9fJYl7gywMi",
"sign_key": "EQO2dQLKw9UAshwYRbzlKRB51MYdEEeW"
},
"created_at": "2025-07-20T18:43:49.549716",
"updated_at": "2026-09-22T11:14:08.172785"
},
{
"store_id": 71,
"open_store_id": "00615",
"brand_id": 1,
"brand_name": "金色印象",
"store_name": "爱琴海行政会馆",
"store_address": null,
"store_phone": null,
"store_longitude": null,
"store_latitude": null,
"center_name": "金色印象事业部",
"part_name": "第一片区",
"store_manager": "吴俊良",
"store_manager_phone": null,
"store_visible": true,
"store_key": "5d771409-0f4a-458a-ae2d-fb862af7f652",
"store_photo": null,
"store_no": null,
"extra": null,
"hr_json_extra": {
"beginDate": "2023-10-12 00:00:00",
"branchLeaderCode": "37027103",
"branchLeaderId": "e1360067-9871-451d-97d3-b168df74ce82",
"branchLeaderName": "李燕",
"cantCode": "",
"cantName": "",
"costOrgCode": null,
"costOrgId": null,
"costOrgName": null,
"country": "",
"createTime": "2023-10-12 16:50:45",
"endDate": null,
"extendItems": [
{
"columnComment": "发薪日",
"columnName": "ext_payday",
"columnValue": "11"
},
{
"columnComment": "办公详细地址",
"columnName": "ext_office_address",
"columnValue": ""
},
{
"columnComment": "负责人编码",
"columnName": "ext_principal_num",
"columnValue": ""
}
],
"foundDate": "2023-10-12",
"foundReason": null,
"globalOrder": "1106109103109104",
"hrbpCode": null,
"hrbpId": null,
"hrbpLeaderCode": null,
"hrbpLeaderId": null,
"hrbpLeaderName": null,
"hrbpName": null,
"inUse": "1",
"kqCommissionerCode": null,
"kqCommissionerId": null,
"kqCommissionerName": null,
"manageOrgCode": null,
"manageOrgName": null,
"manageStaff": null,
"manageStaffCode": null,
"manageStaffId": null,
"manageStruId": null,
"officeAddress": "1",
"operateTime": "2026-08-03 09:19:01",
"orgCode": "00615",
"orgFullPath": "集团-金色印象事业部-第一大区-金色印象渝北经营中心-第一片区-爱琴海行政会馆",
"orgId": "6e8c42f6-68dc-11ee-b449-000c296f9469",
"orgName": "爱琴海行政会馆",
"orgTypeCode": "49",
"orgTypeName": "会馆",
"parentOrgCode": "00150",
"parentOrgId": "c4e6c766-c59d-4cf3-a99f-33aa2496eb35",
"parentOrgName": "第一片区",
"principalStaff": "吴俊良",
"principalStaffCode": "37000565",
"principalStaffId": "51711788-7a9f-11ec-b449-000c296f9469",
"remarks": null,
"salaryCommissionerCode": null,
"salaryCommissionerId": null,
"salaryCommissionerName": null,
"shortName": "爱琴海行政会馆",
"struOrder": 104.0,
"unitOrgCode": "00738",
"unitOrgId": "0bcdee12-e592-11ee-b449-000c296f9469",
"unitOrgName": "金色印象事业部"
},
"crm_json_extra": {
"host": "https://api.shuhe.crm.waf.37du.co",
"shop_id": "2010247",
"shop_key": "2UHRmwKS2qTes7dY7czK39241WLQccwe",
"sign_key": "nYXTVTgfgKmNm9uxFRWvY82PRLQFqC7q"
},
"created_at": "2025-07-20T18:43:49.685611",
"updated_at": "2026-09-22T11:14:18.896622"
}
]
}
+1 -122
View File
@@ -1,122 +1 @@
# 交接文档:XQ0011 考勤月报封存检查(需求11)→ 插件开发
> 用途:当前会话已跑通 workflows/ 影刀版全流程并测试通过(2026-08 基线)。下一会话需按本单开发**插件版**(plugins/)。本文件是接续的唯一依据,先读本文件再读需求单 4 份文档(需求/流程/开发/评分)。
---
## 1. 需求与范围
- 需求编号:**XQ0011**(用户俗称"需求11"),需求单目录:`docs/需求单/XQ0011 考勤月报封存检查/`(含 需求文档.md / 流程文档.md / 开发文档.md / 评分文档.md)。
- 目标:每月对已封存的考勤月报做 5+1 项检查,输出异常名单,HR 人工复核后重新封存。
- 检查清单(当前实现 6 项):
| 编号 | 名称 | 核心判定 | 模块 |
|---|---|---|---|
| 检查1 | 在职天数排班异常 | 在职天数 ≠ 在职应勤工作日 + 休息天 | working_days_shift_check.py |
| 检查2 | 出勤及排休天数异常 | 实际出勤 > 应勤天 或 正休 > 当月天数-应勤天;**排班方案未匹配应勤天也入异常** | attendance_rest_check.py |
| 检查3 | 封存非最新值 | 实时统计与封存值有差异(对比差异) | latest_seal_check.py |
| 检查4 | 全勤验证异常 | 晋升当月要求全勤 / 有迟到早退仍全勤=1 | full_attendance_check.py |
| 检查5 | 未封存名单 | 花名册在册但无封存记录 | unsealed_check.py |
| 检查6 | 延时加班异常 | 经营系管理岗(花名册职位序列)却有延时加班补贴 | overtime_compensation_check.py |
---
## 2. 已完成的 workflows 版(可直接移植)
目录:`workflows/XQ0011 考勤月报封存检查/`,全部为**接口直连**实现(无浏览器自动化),共享 HR cookies 登录态。
### 2.1 核心文件与职责
| 文件 | 职责 |
|---|---|
| `seal_data_export.py` | **共享枢纽**:HR 会话工具 + 封存数据拉取/白名单筛选/花名册剔除/保存 + 花名册剔除名单 + 工号→1-5级部门缓存 + `enrich_dept_fields()` 部门回填 + `load_seal_rows()` 读取 |
| `monthly_report_check.py` | 汇总编排器:依次跑检查1~6,写**单工作簿多 sheet**(汇总+6),各检查异常不中断 |
| `working_days_shift_check.py` | 检查1 |
| `attendance_rest_check.py` | 检查2(含应勤天方案 1 天文件缓存) |
| `latest_seal_check.py` | 检查3 |
| `full_attendance_check.py` | 检查4(读调动台账) |
| `unsealed_check.py` | 检查5(读花名册) |
| `overtime_compensation_check.py` | 检查6(读花名册职位序列) |
### 2.2 数据流
```
HR 接口直连(hr.37du.co,共享 hr_cookies.json)
├─ 封存数据 getPageAjaxList.mc(全集团)
│ → 白名单单位筛选(SEAL_UNIT_WHITELIST 5 个单位)
│ → 花名册剔除(职业技术培训学校 + 一级部门为空的高管)
│ → 保存 考勤封存数据_{月份}.xlsx(固定路径)
│ → 各检查经 load_seal_rows() 读取(带兜底剔除)
├─ 实时统计 StatV2(检查3 用,全集团批量)
├─ 排班 rf_p_kq_count_SelectBanci(检查2 用)
├─ 应勤天方案三连接口(检查2 用,1 天文件缓存)
├─ 花名册(share/roster_export_api.py 导出,在职+离职)
└─ 调动台账(share/transfer_roster_export_api.py 导出)
输出统一目录:D:\资料\人资\考勤月报封存检查
```
### 2.3 关键口径(移植时务必保留,有坑)
1. **白名单单位**(SEAL_UNIT_WHITELIST):财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部。
2. **花名册剔除名单**(`load_excluded_codes()`,`_load_roster_maps()` lru_cache):
- 一级部门 = 「职业技术培训学校」→ 不参与检查(整月剔除);
- 一级部门为空 = 直属单位根节点的**高管**(董事长/总监/总经理等 11 人,如 郑荣斌37031376、杨明艳37000002)→ 不参与检查。
- 剔除需同时作用于:封存表预处理(export_seal_data)、封存表读取兜底(load_seal_rows)、检查5 花名册(unsealed_check 单独再剔)。
3. **部门回填** `enrich_dept_fields(target, code, rec, roster_path)`:异常行补 所属单位+一级~五级部门,花名册按工号优先、封存记录兜底(封存接口字段 `DEPT_ORG_ONE..FIVE`、`BELONG_UNIT_ORG_NAME`)。
4. **检查3 工号坑(已修复)**:工号必须取封存记录 `base_code` / `seal_base_code`,**不能取 `staff_id`**(那是内部 UUID)。
5. **检查2 排班方案未匹配**:员工当月出现最多的 `{日期}_team_name` 在考勤方案表中匹配不到应勤天 → 输出异常,异常类型固定「排班方案未匹配应勤天」,明细格式 `排班方案「{方案名}」未匹配到应勤天方案,请核对`。2026-08 命中 5 人(湖畔-石桥铺会馆-其他×3、集团职能哺乳假方案早/晚×2)。
6. **检查2 技师**:方案名含「技师岗」固定按 8 天正休校验,不查应勤天。
7. **应勤天方案 1 天缓存**:`%LOCALAPPDATA%\37duAutomation\cache\应勤天方案缓存_{YYYY-MM}.json`,按 `month` + `cached_at==今天` 判命中;键 = 考勤方案 teamName。
8. **异常类型固定少数几种**(便于筛选),详细说明一律放「异常明细」列。
9. **单工作簿输出**:`考勤月报封存检查_{月份}_{时间戳}.xlsx`,sheet=汇总+检查1~6;空结果保留表头。各检查仍保留独立 xlsx(排查用)。
10. 封存表列映射 `CN_FIELD_MAP`(中文表头→接口字段)在 seal_data_export.py,保存时重命名、读取时反查还原。
### 2.4 2026-08 实测基线(核对用)
- 花名册 8699 行(在职+离职,离职时间 2026-08-01~09-20);封存 全集团 8205 → 白名单 8142 → 剔除学校 44 → 8098 人;剔除名单=学校82+高管11=93 人。
- 最终一轮完整汇总(**高管剔除前**):检查1:13、检查2:18、检查3:43、检查4:4、检查5:15、检查6:34,**合计 127**。
- 加入高管剔除后**预期**:检查3→42、检查5→14,**合计 125**(尚未跑完整轮,插件版落地后需用 2026-08 重跑核对本基线)。
- 输出样例:`D:\资料\人资\考勤月报封存检查\考勤月报封存检查_2026-08_20260921_144824.xlsx`(127 人版)。
---
## 3. 插件开发要点
### 3.1 结构约束(必读 AGENTS.md「插件」节)
- 目录:`plugins/<id>/`(如 `plugins/xq0011_kq_seal_check/`),**内部自包含**:只能互相引用 + Python 标准库 + 第三方依赖 + 底座注入接口(`webhost.backend.plugins.base`);**严禁 import 根目录 / desktop 底座业务 / workflows**。交付物 = 插件包本身,可单独拷贝发布。
- 组织参考:`config/`(口径常量、白名单、缓存路径)、`data/`(HR 接口封装:封存/统计/排班/应勤天/花名册/调动台账)、`logic/`(6 个检查 + 编排)、`report/`(单工作簿导出)。
- 现有插件参考:`plugins/xq0031_xq0032/`(plugin.json 结构与 fields 定义范例)。
### 3.2 基类与运行上下文(`desktop/webhost/backend/plugins/base.py`)
```python
class ScenePlugin:
id/name/version/description/platform/uses_month/fields/capabilities/permissions
def run(self, fields: dict, ctx: RunContext) -> dict
class RunContext:
ctx.log(msg, level) / ctx.progress(pct)
ctx.get_session(platform) # 平台登录态 session,如 "hr"
ctx.get_user_id(platform)
```
- `platform = "hr"`(HR 登录态);`uses_month = True`(底座页眉注入执行月份 ref_month)。
- `fields`:month(默认上月)、save_dir(默认 D:\资料\人资\考勤月报封存检查) 等,schema 见 xq0031_xq0032/plugin.json 范例。
- run 内 `session = ctx.get_session("hr")`,user_id = `ctx.get_user_id("hr")`。
- 进度:分 7 段推进(拉封存→花名册剔除→6 检查),用 `ctx.progress()` 上报。
### 3.3 移植注意
- 把 seal_data_export.py 的 HR 会话/剔除/部门回填/封存读写抽成插件内 `data/` 模块,各检查改为引用插件内模块(替换原 `sys.path.insert + from seal_data_export import`)。
- 花名册/调动台账导出(workflows/share/ 的 roster_export_api.py、transfer_roster_export_api.py)不能直接 import,需内嵌进插件 `data/`(或改为纯 HR 接口查询封装,优先内嵌已有实现,逻辑已验证可用)。
- 应勤天缓存沿用 AppData 路径与 1 天有效期;花名册读取 `pd.read_excel(dtype=str)` + 列 strip,在职/离职同工号多行取后覆盖。
- 检查3/检查5 曾出的"工号/部门/剔除"三个坑见 2.3,逐条核对。
- 输出目录统一 `D:\资料\人资\考勤月报封存检查`;单工作簿引擎 `pandas.ExcelWriter(engine="openpyxl")`。
- 发版:插件目录打 zip(根含 plugin.json)→ `agent_cli publish <zip> --id <id> --version <v>`,权限 `agent_cli grant/revoke`(详见 AGENTS.md 第 5 节)。
### 3.4 遗留/待办
1. 插件版落地后跑 2026-08 全量,核对基线 125 人(检查1:13、2:18、3:42、4:4、5:14、6:34)。
2. 花名册/调动台账导出在插件内的触发方式(手动前置 vs run 内自动刷新+TTL 缓存)需按底座约定定稿。
3. 检查1 官方逻辑含入离职异动在职天数计算(流程文档),当前实现口径需与需求单复核一致(评分依据)。
4. 检查4 调动台账依赖「37du调动台账导出」;检查5/6 依赖花名册导出——插件运行时需保证这些前置文件存在或自动拉取。
<div class="zlq-login-form relative w-full px-5 py-8 mx-auto my-auto rounded-md shadow-md xl:ml-16 xl:bg-transparent sm:px-8 xl:p-4 xl:shadow-none sm:w-3/4 lg:w-2/4 xl:w-auto enter-x"><h2 class="mb-3 text-2xl font-bold text-center xl:text-3xl enter-x xl:text-left enter-x">登录</h2><form class="ant-form ant-form-horizontal p-4 enter-x"><div class="ant-row ant-form-item enter-x" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><input placeholder="账号" type="text" id="form_item_account" class="ant-input ant-input-lg fix-auto-fill" value=""></div><!----></div><!----><!----></div></div><div class="ant-row ant-form-item enter-x" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><span class="ant-input-affix-wrapper ant-input-affix-wrapper-lg ant-input-password ant-input-password-large"><!----><input placeholder="密码" id="form_item_password" type="password" class="ant-input ant-input-lg"><span class="ant-input-suffix"><!----><!----><span role="img" aria-label="eye-invisible" tabindex="-1" class="anticon anticon-eye-invisible ant-input-password-icon"><svg focusable="false" class="" data-icon="eye-invisible" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M942.2 486.2Q889.47 375.11 816.7 305l-50.88 50.88C807.31 395.53 843.45 447.4 874.7 512 791.5 684.2 673.4 766 512 766q-72.67 0-133.87-22.38L323 798.75Q408 838 512 838q288.3 0 430.2-300.3a60.29 60.29 0 000-51.5zm-63.57-320.64L836 122.88a8 8 0 00-11.32 0L715.31 232.2Q624.86 186 512 186q-288.3 0-430.2 300.3a60.3 60.3 0 000 51.5q56.69 119.4 136.5 191.41L112.48 835a8 8 0 000 11.31L155.17 889a8 8 0 0011.31 0l712.15-712.12a8 8 0 000-11.32zM149.3 512C232.6 339.8 350.7 258 512 258c54.54 0 104.13 9.36 149.12 28.39l-70.3 70.3a176 176 0 00-238.13 238.13l-83.42 83.42C223.1 637.49 183.3 582.28 149.3 512zm246.7 0a112.11 112.11 0 01146.2-106.69L401.31 546.2A112 112 0 01396 512z"></path><path d="M508 624c-3.46 0-6.87-.16-10.25-.47l-52.82 52.82a176.09 176.09 0 00227.42-227.42l-52.82 52.82c.31 3.38.47 6.79.47 10.25a111.94 111.94 0 01-112 112z"></path></svg></span></span></span></div><!----></div><!----><!----></div></div><div class="ant-row enter-x" style="row-gap: 0px;"><div class="ant-col ant-col-12"><div class="ant-row ant-form-item" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><label class="ant-checkbox-wrapper"><span class="ant-checkbox"><input type="checkbox" class="ant-checkbox-input"><span class="ant-checkbox-inner"></span></span><span>记住我</span></label></div><!----></div><!----><!----></div></div></div><div class="ant-col ant-col-12"><div class="ant-row ant-form-item" style="text-align: right; row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><!----><button class="ant-btn ant-btn-link ant-btn-sm" type="button"><!----><span>忘记密码?</span></button></div><!----></div><!----><!----></div></div></div></div><div class="ant-row ant-form-item enter-x" style="row-gap: 0px;"><!----><div class="ant-col ant-form-item-control"><div class="ant-form-item-control-input"><div class="ant-form-item-control-input-content"><button class="ant-btn ant-btn-primary ant-btn-lg ant-btn-block" type="button"><!----><span>登 录</span></button></div><!----></div><!----><!----></div></div><div class="ant-divider ant-divider-horizontal ant-divider-with-text ant-divider-with-text-center enter-x" role="separator"><span class="ant-divider-inner-text">其他登录方式</span></div><div class="flex justify-center enter-x zlq-login-sign-in-way"><span role="img" aria-label="dingding" tabindex="-1" class="anticon anticon-dingding"><svg focusable="false" class="" data-icon="dingding" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M573.7 252.5C422.5 197.4 201.3 96.7 201.3 96.7c-15.7-4.1-17.9 11.1-17.9 11.1-5 61.1 33.6 160.5 53.6 182.8 19.9 22.3 319.1 113.7 319.1 113.7S326 357.9 270.5 341.9c-55.6-16-37.9 17.8-37.9 17.8 11.4 61.7 64.9 131.8 107.2 138.4 42.2 6.6 220.1 4 220.1 4s-35.5 4.1-93.2 11.9c-42.7 5.8-97 12.5-111.1 17.8-33.1 12.5 24 62.6 24 62.6 84.7 76.8 129.7 50.5 129.7 50.5 33.3-10.7 61.4-18.5 85.2-24.2L565 743.1h84.6L603 928l205.3-271.9H700.8l22.3-38.7c.3.5.4.8.4.8S799.8 496.1 829 433.8l.6-1h-.1c5-10.8 8.6-19.7 10-25.8 17-71.3-114.5-99.4-265.8-154.5z"></path></svg></span></div></form><!----><!----></div>
+1 -1
View File
@@ -54,7 +54,7 @@
| XQ | 流程名称 | 影刀版 | 插件版 | 备注 |
|----|----------|--------|--------|------|
| XQ0001 | 排班异常识别 | ✅ 已实现 | — | |
| XQ0002 | 雇主险增减操作 | ✅ 已实现 | — | |
| XQ0002 | 雇主险增减操作 | ✅ 已实现 | ✅ `xq0002` v1.0.0(有 UI) | 双版本并存 |
| XQ0003 | EHR系统请假流程审核 | ✅ 已实现 | — | |
| XQ0004 | EHR系统加班流程审核 | ✅ 已实现 | — | |
| XQ0005 | 银行卡检查 | ✅ 已实现 | — | |
@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*-
"""XQ0002 雇主险增减操作 插件入口。
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
1) 花名册确保:源表缺失且开启 auto_export 时自动从 HR 接口导出(TTL 15 分钟复用);
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值)。
运行上下文:底座注入 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。
"""
import os
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
from . import config
from .logic import roster_filter, schedule
from .logic.wps_recalc import recalc_target, ComRecalcError
from .report import output
class EmployerInsurancePlugin(ScenePlugin):
"""雇主险名额调度(需求 XQ0002)。"""
id = "xq0002"
name = "雇主险增减操作"
version = "1.0.0"
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→"
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件,"
"替代人工 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()
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))
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, auto_export, 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:三阶段名额调度(60% ~ 88%) ----
scheduled = []
for i, category in enumerate(to_schedule):
ctx.progress(60 + int(28 * 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(88)
# ---- 步骤5:再次重算公式(88% ~ 95%,刷新变更清单/在参名单公式列缓存) ----
if wps_recalc:
for i, category in enumerate(scheduled):
ctx.progress(88 + int(7 * 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)
# ---- 步骤6:导出变更清单独立工作簿(95% ~ 100%) ----
if export_change_sheet:
for i, category in enumerate(scheduled):
ctx.progress(95 + int(5 * 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(100)
# ---- 汇总 ----
detail = {
"处理类别": len(categories),
"筛选复制成功": len(ok_categories),
"调度成功": len(scheduled),
}
summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、"
"调度成功 {scheduled} 个。增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
"请先执行【减员】导入再执行【增员】导入。").format(
date=config.today_date(), total=len(categories),
filtered=len(ok_categories), scheduled=len(scheduled))
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,52 @@
# -*- coding: utf-8 -*-
"""XQ0002 雇主险增减操作 插件打包脚本(统一规范版,与 xq0011/xq0031 一致)。
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
用法(任意 cwd 均可):
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0002 雇主险增减操作\\_pack.py"
随后发布:
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
dist-plugin\\xq0002_v<版本>.zip --id xq0002 --version <版本>
"""
import json
import sys
import zipfile
from pathlib import Path
_HERE = Path(__file__).resolve().parent
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
_REPO_ROOT = _HERE.parents[2]
_OUT_DIR = _REPO_ROOT / "dist-plugin"
# 排除项:打包脚本自身 / 前端源码与依赖 / 缓存 / 调试文件
_EXCLUDE_DIRS = {"ui-src", "node_modules", "__pycache__", ".git", ".idea", "debug", ".sessions"}
_EXCLUDE_FILES = {"_pack.py"}
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
def main():
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
pid = manifest["id"]
ver = manifest["version"]
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
_OUT_DIR.mkdir(exist_ok=True)
out = _OUT_DIR / f"{pid}_v{ver}.zip"
count = 0
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
for p in sorted(_HERE.rglob("*")):
rel = p.relative_to(_HERE)
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
or p.suffix in _EXCLUDE_SUFFIXES:
continue
if p.is_file():
zf.write(p, str(rel))
count += 1
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
if __name__ == "__main__":
main()
@@ -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,162 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 - 筛选复制(由影刀版 roster_filter.py v2.0.0 移植)。
从员工花名册按类别 include/exclude 所属单位筛选数据,复制到各自类别目标表
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
源表缺失时调用 data.roster_export_api.export_roster 自动导出(auto_export 开关),
替代影刀版对 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="", auto_export=True, session=None):
"""确保花名册源表存在:缺失且 auto_export 时自动调用 HR 接口导出,否则抛错。
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,
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.0",
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件,替代人工 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(源表缺失且开启自动导出时自动从 HR 导出)"
},
"auto_export": {
"type": "boolean",
"title": "源表缺失时自动导出",
"default": true,
"description": "勾选=花名册缺失时自动调用 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 待增减人员页面上传素材)"
}
},
"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,5 @@
requests
pandas
openpyxl
websocket-client
pywin32
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>雇主险增减操作</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,22 @@
{
"name": "xq0002-ui",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"element-plus": "^2.14.5",
"vue": "^3.5.13"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.1",
"vite": "^6.0.3"
},
"allowScripts": {
"esbuild@0.25.12": true
}
}
@@ -0,0 +1,318 @@
<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>
<!-- 执行配置 -->
<el-card shadow="never" class="card">
<template #header>
<span class="card-title">执行配置</span>
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
</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="生成增/减员导入文件" />
</div>
<div class="tip">「WPS/Excel后台重算公式」替代人工 Ctrl+S 刷新公式,需本机装 WPS 专业版/企业版或 MS Excel;关闭后须确保目标文件公式已人工刷新</div>
</el-form-item>
<div class="actions">
<el-button type="primary" size="large" :loading="running" @click="run">
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
</el-button>
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
@click="forceStop">强制停止</el-button>
<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>
</div>
</template>
<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { connectWS, getRun, loadConfig, saveConfig, startRun, stopRun } from './api'
const CATEGORIES = ['三十七度', '水庄餐饮', '湖畔酒店', '秒创传媒']
const DEFAULTS = () => ({
base_dir: 'D:\\资料\\人资\\雇主险',
ref_date: '',
categories: [...CATEGORIES],
roster_path: '',
auto_export: true,
enable_validation: true,
wps_recalc: true,
export_change_sheet: true,
gen_import_files: true,
})
const form = reactive(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()
Object.keys(form).forEach((k) => {
if (saved[k] !== undefined && saved[k] !== null && saved[k] !== '') form[k] = saved[k]
if (k === 'categories' && Array.isArray(saved[k]) && saved[k].length) form.categories = saved[k]
})
} catch (e) {
if (e.code === 401) needLogin.value = true
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
}
loaded.value = true
})
// 配置变更自动保存(防抖),执行中不改存
watch(form, () => {
if (!loaded.value || running.value) return
clearTimeout(saveTimer)
saveTimer = setTimeout(() => saveNow(false), 800)
}, { deep: true })
async function saveNow(explicit) {
try {
await saveConfig(JSON.parse(JSON.stringify(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())
ElMessage.info('已恢复默认配置')
}
// ---------- 执行 ----------
function validate() {
if (!form.base_dir.trim()) { ElMessage.warning('请填写雇主险根目录'); return false }
if (!form.categories.length) { ElMessage.warning('请至少选择一个处理类别'); return false }
if (form.ref_date && !/^\d{4}-\d{2}-\d{2}$/.test(form.ref_date)) {
ElMessage.warning('业务日期格式应为 YYYY-MM-DD,或留空使用今天'); return false
}
return true
}
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()) return
await saveNow(false)
running.value = true
progress.value = 0
banner.value = null
try {
const r = await startRun(JSON.parse(JSON.stringify(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 }
}
async 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 }
}
</script>
<style scoped>
.page {
width: 100%;
padding: 4px 2px 20px;
display: flex;
flex-direction: column;
gap: 12px;
}
.card {
border-radius: 10px;
}
.card-title {
font-weight: 600;
font-size: 14px;
}
.saved {
float: right;
font-size: 12px;
font-weight: 400;
color: #67c23a;
}
.grid {
display: flex;
gap: 18px;
flex-wrap: wrap;
}
.grid .el-form-item {
flex: 1;
min-width: 300px;
}
.wide {
width: 100%;
}
.switches {
display: flex;
flex-wrap: wrap;
gap: 18px;
align-items: center;
}
.tip {
width: 100%;
font-size: 12px;
color: #909399;
line-height: 1.6;
margin-top: 2px;
}
.actions {
display: flex;
align-items: center;
gap: 10px;
border-top: 1px dashed var(--el-border-color);
padding-top: 16px;
margin-top: 6px;
}
.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 {
flex: 1;
}
.status-txt {
font-size: 12px;
color: #606266;
white-space: nowrap;
}
</style>
@@ -0,0 +1,50 @@
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
export const PLUGIN_ID = 'xq0002'
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 (e) { /* 保留默认 */ }
throw new Error(msg)
}
return res.json()
}
export function loadConfig() {
return j(`/api/plugin-config/${PLUGIN_ID}`)
}
export function saveConfig(data) {
return j(`/api/plugin-config/${PLUGIN_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export function startRun(fields) {
return j('/api/runs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
})
}
export function getRun(runId) {
return j(`/api/runs/${runId}`)
}
export function stopRun(runId) {
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
}
export 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
}
@@ -0,0 +1,7 @@
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import App from './App.vue'
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
@@ -0,0 +1,21 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 插件 UI 由壳子后端托管在 /pui/xq0002/ 下,
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
// dev 模式经代理访问本机壳子后端,便于联调。
export default defineConfig({
plugins: [vue()],
base: '/pui/xq0002/',
build: {
outDir: '../ui',
emptyOutDir: true,
},
server: {
port: 5181,
proxy: {
'/api': 'http://127.0.0.1:8799',
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
},
},
})
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-b6COCLM2.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-DkUqd0or.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
Binary file not shown.
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""
@Description: WPS COM 可行性验证(雇主险场景)——
模拟「openpyxl 写入业务数据 → 目标表公式列缓存丢失 → WPS COM 打开重算保存 → openpyxl 读回公式结果」。
验证 WPS 个人版 Ket.Application 是否满足 XQ0002 插件版「自动化替代人工 Ctrl+S 刷新公式」的需求。
不触碰真实业务文件,全部在 %TEMP%\\wps_com_feasibility\\ 下完成。
@Run: d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests\\wps_com_feasibility.py
"""
import os
import sys
import shutil
import tempfile
import traceback
from datetime import datetime
import openpyxl
from openpyxl import load_workbook
import win32com.client
import pythoncom
WORK_DIR = os.path.join(tempfile.gettempdir(), "wps_com_feasibility")
TEST_FILE = os.path.join(WORK_DIR, "雇主险验证-重算公式.xlsx")
def step1_write_data_via_openpyxl():
"""openpyxl 模拟雇主险写入:业务值 + 目标表已有公式列(openpyxl 不计算,缓存留空)"""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "花名册导出-雇主险使用基础信息"
# 业务数据(模拟 B~O 列一部分)
ws["B4"] = "三十七度"
ws["O5"] = "5101**********1234"
ws["P5"] = "一类"
ws["Q5"] = "人保-20万"
ws["W5"] = "增加投保"
# 模拟目标表里的公式列:V5 = 证件号长度(真实业务里是公式),openpyxl 只写公式不计算
ws["V5"] = '=IF(LEN(O5)>0,"有证","无证")'
# 模拟跨 sheet 公式(变更清单场景)
ws2 = wb.create_sheet("37度-雇员变更清单-9.22")
ws2["B3"] = 100
ws2["C3"] = 200
ws2["D3"] = "=B3+C3" # 公式列,openpyxl 写后缓存为空
ws2["E3"] = '=IF(D3>0,"OK","-")'
wb.save(TEST_FILE)
wb.close()
print(f"[1] openpyxl 写入完成: {TEST_FILE}")
# 证明:data_only 读公式列缓存为空(这就是业务里"必须人工 Ctrl+S"的原因)
wb_r = load_workbook(TEST_FILE, data_only=True)
v1 = wb_r["花名册导出-雇主险使用基础信息"]["V5"].value
v2 = wb_r["37度-雇员变更清单-9.22"]["D3"].value
v3 = wb_r["37度-雇员变更清单-9.22"]["E3"].value
wb_r.close()
print(f" 写后缓存值(应为 None): V5={v1!r} D3={v2!r} E3={v3!r}")
assert v1 is None and v2 is None and v3 is None, "openpyxl 写后公式缓存应全空"
def step2_recalc_via_wps_com():
"""WPS COM 打开 → 全量重算 → 保存(替代人工 Ctrl+S)"""
pythoncom.CoInitialize()
app = None
try:
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
app.Visible = False
app.DisplayAlerts = False
wb = app.Workbooks.Open(os.path.abspath(TEST_FILE), UpdateLinks=2)
wb.Application.CalculateFullRebuild()
wb.Save()
wb.Close()
print("[2] WPS COM 重算并保存成功")
finally:
if app is not None:
app.Quit()
pythoncom.CoUninitialize()
def step3_read_back():
"""openpyxl data_only 读回公式结果,验证缓存已落盘"""
wb = load_workbook(TEST_FILE, data_only=True)
v1 = wb["花名册导出-雇主险使用基础信息"]["V5"].value
v2 = wb["37度-雇员变更清单-9.22"]["D3"].value
v3 = wb["37度-雇员变更清单-9.22"]["E3"].value
wb.close()
print(f"[3] 重算后缓存值: V5={v1!r} D3={v2!r} E3={v3!r}")
assert v1 == "有证" and v2 == 300 and v3 == "OK", f"公式结果不符: {v1=} {v2=} {v3=}"
print(" ✅ 全部公式结果已计算并缓存落盘,openpyxl 可直接读取")
if __name__ == "__main__":
try:
shutil.rmtree(WORK_DIR, ignore_errors=True)
os.makedirs(WORK_DIR, exist_ok=True)
step1_write_data_via_openpyxl()
step2_recalc_via_wps_com()
step3_read_back()
print("\n结论:WPS 个人版 Ket.Application COM 可行 —— 可替代雇主险人工刷新公式(Ctrl+S)环节")
except Exception:
print("\n结论:验证失败,详情如下")
traceback.print_exc()
sys.exit(1)
+341
View File
@@ -0,0 +1,341 @@
# -*- coding: utf-8 -*-
"""XQ0002 雇主险插件 全链路冒烟自测(本机 .venv 执行)。
覆盖链路:花名册筛选复制 → WPS/Excel COM 后台重算(可选)→ 三阶段名额调度
(更新在参名单 / 精细更新变更清单 / 备份新在参名单)→ 增/减员导入文件 → 变更清单独立工作簿。
测试数据(临时目录):
- 员工花名册.xlsx:表头行 B 列=「所属单位」,B~O 14 列;8 名员工,含各类被过滤样本
(金色湖畔事业部 / 虚拟大区 / 姓名含测试 / 未来入职 / 方案处理=/)。
- 三十七度-雇主险变更记录-测试.xlsx:SHEET_BIZ 表头第4行(P/Q/V/W 为公式列)、
SHEET_IN_PARAM 表头第6行(数据第17行起)、历史变更清单模板 sheet。
- 商业保险增/减员导入模板.xlsx(第1~3行固定,第4行起填数据)。
预期(业务场景):
- 花名册过滤后 4 人(张三/李四/王五/赵六),赵六方案处理=/ 在调度阶段被过滤。
- 在参名单:王五(20万,要替换→80万) 迁出;钱十离职减少名额被李四(20万)复用;
张三(50万) 全新新增;王五(80万) 全新新增;陈十一(50万) 保留。
- 变更清单 4 条:删除钱十 / 增加张三(带四级部门) / 增加李四 / 修改王五。
- 减员导入 2 条(钱十、王五);增员导入 3 条(张三/李四/王五)。
用法(仓库根目录执行):
.venv\\Scripts\\python.exe tests\\xq0002_plugin_smoke.py
"""
import importlib
import os
import shutil
import sys
from datetime import date
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(REPO_ROOT, "desktop")) # webhost 底座
sys.path.insert(0, os.path.join(REPO_ROOT, "plugins", "XQ0001-0100")) # 插件包
# 通过 importlib 导入包名含空格/中文的插件模块
cfg = importlib.import_module("XQ0002 雇主险增减操作.config")
roster_filter = importlib.import_module("XQ0002 雇主险增减操作.logic.roster_filter")
schedule_mod = importlib.import_module("XQ0002 雇主险增减操作.logic.schedule")
wps_recalc = importlib.import_module("XQ0002 雇主险增减操作.logic.wps_recalc")
report_output = importlib.import_module("XQ0002 雇主险增减操作.report.output")
import pandas as pd
from openpyxl import Workbook, load_workbook
# ==================== 测试目录与结果收集 ====================
WORK_DIR = os.path.join(REPO_ROOT, "tests", "_xq0002_smoke_data")
if os.path.isdir(WORK_DIR):
shutil.rmtree(WORK_DIR)
CATEGORY_DIR = os.path.join(WORK_DIR, "三十七度")
os.makedirs(CATEGORY_DIR, exist_ok=True)
RESULTS = [] # (名称, 通过?, 说明)
def check(name, ok, detail=""):
RESULTS.append((name, bool(ok), detail))
print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" -> {detail}" if detail and not ok else ""))
def _sheet(wb, title):
if title in wb.sheetnames:
return wb[title]
return wb.create_sheet(title)
# ==================== 1. 构建测试数据 ====================
def build_source(path):
"""员工花名册:表头行 B 列=「所属单位」,B~O 14 列。"""
wb = Workbook()
ws = wb.active
ws.title = "花名册"
headers = ["类型", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号"]
for i, h in enumerate(headers, start=1):
ws.cell(row=1, column=i, value=h)
rows = [
# 所属单位 一级部门 工号 年龄 性别 岗位 职位序列 参保 交通 入职日期 姓名 证件号
["三十七度", "三十七度大区", "10001", 30, "男", "厨师", "厨师长", "全职", "班车", date(2020, 1, 1), "张三", "110101199001010001"],
["三十七度", "三十七度大区", "10002", 29, "女", "服务员", "服务员", "全职", "班车", date(2021, 1, 1), "李四", "110101199002010002"],
["三十七度", "三十七度大区", "10003", 35, "男", "领班", "领班", "全职", "班车", date(2019, 6, 1), "王五", "110101198906010003"],
["三十七度", "三十七度大区", "10004", 28, "男", "传菜", "传菜员", "全职", "班车", date(2022, 1, 1), "赵六", "110101199301010004"],
["金色湖畔事业部", "金色湖畔大区", "10005", 26, "女", "前台", "前台", "全职", "班车", date(2020, 5, 1), "孙七", "110101199405010005"],
["三十七度", "三十七度大区", "10006", 24, "女", "实习", "实习生", "兼职", "班车", date(2020, 1, 1), "测试员", "110101199601010006"],
["三十七度", "虚拟大区", "10007", 27, "男", "杂工", "杂工", "全职", "班车", date(2020, 1, 1), "周八", "110101199701010007"],
["三十七度", "三十七度大区", "10008", 25, "男", "帮厨", "帮厨", "全职", "班车", date(2099, 1, 1), "吴九", "110101199801010008"],
]
for r, row in enumerate(rows, start=2):
ws.cell(row=r, column=2, value=row[0]) # B 所属单位
ws.cell(row=r, column=3, value=row[1]) # C 一级部门
ws.cell(row=r, column=6, value=row[2]) # F 工号
ws.cell(row=r, column=7, value=row[3]) # G 年龄
ws.cell(row=r, column=8, value=row[4]) # H 性别
ws.cell(row=r, column=9, value=row[5]) # I 岗位
ws.cell(row=r, column=10, value=row[6]) # J 职位序列
ws.cell(row=r, column=11, value=row[7]) # K 参保类型
ws.cell(row=r, column=12, value=row[8]) # L 上下班交通方式
ws.cell(row=r, column=13, value=row[9]) # M 入职时间
ws.cell(row=r, column=14, value=row[10]) # N 姓名
ws.cell(row=r, column=15, value=row[11]) # O 证件号
wb.save(path)
def build_target(path):
"""类别目标表:SHEET_BIZ(表头第4行) + SHEET_IN_PARAM(表头第6行,数据第17行起) + 历史变更清单模板。"""
wb = Workbook()
# ---- SHEET_BIZ:表头第4行 ----
ws = _sheet(wb, cfg.SHEET_BIZ)
biz_headers = ["序号", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号",
"工种类别", "投保方案", "方案组别编号", "是否有工伤保险", "工作单位",
"新增费用会馆", "四级部门", "方案处理"]
for i, h in enumerate(biz_headers, start=1):
ws.cell(row=4, column=i, value=h)
# 模拟真实模板:P/Q/W/V 为公式/待填列(数据行5~8 与花名册筛选结果对应)
# 公式列需经 WPS/Excel 重算才有缓存值;重算不可用时测试兜底直接填值
# 赵六 为「方案处理=/」的占位员工(调度阶段被过滤,不参与参保)
formulas = {
5: ("=\"一类\"", "=\"人保-50万\"", "=\"增加投保\"", "三十七度-后厨"),
6: ("=\"二类\"", "=\"人保-20万\"", "=\"增加投保\"", "三十七度-前厅"),
7: ("=\"三类\"", "=\"人保-80万\"", "=\"要替换\"", "三十七度-后勤"),
8: ("=\"一类\"", "=\"人保-20万\"", "=\"/\"", None),
}
for r, (p, q, w, v) in formulas.items():
ws.cell(row=r, column=16, value=p) # P 工种类别
ws.cell(row=r, column=17, value=q) # Q 投保方案
ws.cell(row=r, column=23, value=w) # W 方案处理
ws.cell(row=r, column=22, value=v) # V 四级部门
# ---- SHEET_IN_PARAM:表头第6行,数据第17行起 ----
ws2 = _sheet(wb, cfg.SHEET_IN_PARAM)
in_headers = ["序号", "工号", "年龄", "性别", "岗位", "职位序列", "参保类型", "上下班交通方式",
"入职时间", "姓名", "证件号", "工种类别", "投保方案", "投保日期",
"方案组别编号", "每人责任限额", "是否有工伤保险", "方案处理"]
for i, h in enumerate(in_headers, start=1):
ws2.cell(row=6, column=i, value=h)
# 王五(要替换: 20万→80万) / 钱十(离职减少: 20万) / 陈十一(无需: 50万)
in_rows = {
17: (1, "10003", "王五", "110101198906010003", "三类", "人保-20万", date(2020, 1, 1), "档次替换"),
18: (2, "10009", "钱十", "110101199009010009", "一类", "人保-20万", date(2021, 1, 1), "离职减少"),
19: (3, "10010", "陈十一", "110101199110100010", "一类", "人保-50万", date(2020, 6, 1), "无需"),
}
for r, (seq, code, name, emp_id, cat, scheme, join_date, handle) in in_rows.items():
ws2.cell(row=r, column=1, value=seq) # A 序号
ws2.cell(row=r, column=2, value=code) # B 工号
ws2.cell(row=r, column=10, value=name) # J 姓名
ws2.cell(row=r, column=11, value=emp_id) # K 证件号
ws2.cell(row=r, column=12, value=cat) # L 工种类别
ws2.cell(row=r, column=13, value=scheme) # M 投保方案
ws2.cell(row=r, column=14, value=join_date) # N 投保日期
ws2.cell(row=r, column=18, value=handle) # R 方案处理
# ---- 历史变更清单模板 sheet(供复制)----
ws3 = _sheet(wb, "37度-雇员变更清单9.1")
chg_headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄", "员工职业类别",
"每人责任限额", "方案组别编号", "是否有工伤保险", "工作单位", "", "备注",
"批改日期", "新增费用会馆\n(自留后续划成本用)", "姓名", "证件号", "工种类别", "投保方案"]
for i, h in enumerate(chg_headers, start=1):
ws3.cell(row=1, column=i, value=h)
ws3.cell(row=2, column=1, value="公式")
ws3.cell(row=2, column=15, value="公式")
wb.save(path)
def build_templates(base_dir):
"""增/减员导入模板:第1~3行固定,第4行起填数据。"""
for name in (cfg.ADD_IMPORT_TEMPLATE, cfg.SUB_IMPORT_TEMPLATE):
wb = Workbook()
ws = wb.active
ws.title = "导入模板"
ws.cell(row=1, column=1, value=f"{name} 标题")
ws.cell(row=2, column=1, value="序号")
ws.cell(row=2, column=2, value="工号/证件号")
ws.cell(row=2, column=3, value="姓名")
ws.cell(row=3, column=1, value="示例说明行(保留)")
wb.save(os.path.join(base_dir, name))
# ==================== 2. 冒烟流程 ====================
def main():
today = date.today()
cfg.set_base_dir(WORK_DIR)
cfg.set_ref_date(today.strftime("%Y-%m-%d"))
category = cfg.get_category("三十七度")
source_path = cfg.employee_file()
target_path = os.path.join(CATEGORY_DIR, "三十七度-雇主险变更记录-测试.xlsx")
print("== 构建测试数据 ==")
build_source(source_path)
build_target(target_path)
build_templates(WORK_DIR)
# ---------- 2.1 WPS/Excel COM 重算能力探测 ----------
print("\n== Part A:WPS/Excel COM 公式重算 ==")
probe = os.path.join(WORK_DIR, "recalc_probe.xlsx")
pb = Workbook()
pws = pb.active
pws["A1"] = 2
pws["B1"] = 3
pws["C1"] = "=A1+B1"
pb.save(probe)
com_ok = False
try:
wps_recalc.recalc_target(probe)
cached = load_workbook(probe, data_only=True)["Sheet"]["C1"].value
com_ok = (cached == 5)
check("PartA 公式重算(Ket/Excel COM)", com_ok,
f"期望 C1=5,实际 {cached!r}")
except Exception as e:
check("PartA 公式重算(Ket/Excel COM)", False, str(e))
# ---------- 2.2 筛选复制 ----------
print("\n== 步骤1:花名册筛选复制 ==")
n_copied = roster_filter.filter_and_copy_roster(category, employee_path=source_path,
target_file=target_path)
check("筛选复制行数=4(张三/李四/王五/赵六)", n_copied == 4, f"实际 {n_copied} 行")
# F 列工号强制文本
wb0 = load_workbook(target_path)
f_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=6).value
check("F列工号文本格式", isinstance(f_val, str) and f_val == "10001", repr(f_val))
# O 列证件号强制文本(18位身份证号防浮点截断)
o_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=15).value
check("O列证件号文本格式", isinstance(o_val, str) and o_val == "110101199001010001", repr(o_val))
# ---------- 2.3 公式重算(可用则走真实链路,否则兜底填值) ----------
print("\n== 步骤2:公式重算 ==")
if com_ok:
try:
wps_recalc.recalc_target(target_path)
check("目标表公式重算", True)
except Exception as e:
com_ok = False
check("目标表公式重算", False, str(e))
if not com_ok:
# 兜底:把 P/Q/W 直接填为值(模拟已重算的公式缓存),保证调度链路可继续
wb1 = load_workbook(target_path)
ws1 = wb1[cfg.SHEET_BIZ]
for r, (p, q, w, v) in {
5: ("一类", "人保-50万", "增加投保", "三十七度-后厨"),
6: ("二类", "人保-20万", "增加投保", "三十七度-前厅"),
7: ("三类", "人保-80万", "要替换", "三十七度-后勤"),
8: ("一类", "人保-20万", "/", None),
}.items():
ws1.cell(row=r, column=16, value=p)
ws1.cell(row=r, column=17, value=q)
ws1.cell(row=r, column=23, value=w)
ws1.cell(row=r, column=22, value=v)
wb1.save(target_path)
print("(提示:本机 COM 重算不可用,已兜底直接填公式列值)")
# ---------- 2.4 三阶段名额调度 ----------
print("\n== 步骤3:三阶段名额调度 ==")
final_records = schedule_mod.schedule_category(category,
enable_validation=True,
gen_import_files=True)
check("调度生成参保记录=3", len(final_records) == 3, f"实际 {len(final_records)}")
# ---------- 2.5 断言在参名单更新 ----------
wb2 = load_workbook(target_path)
ws_in = wb2[cfg.SHEET_IN_PARAM]
expect_in = {
17: ("10001", "110101199001010001", "人保-50万"), # 张三 全新新增
18: ("10002", "110101199002010002", "人保-20万"), # 李四 复用钱十名额
19: ("10010", "110101199110100010", "人保-50万"), # 陈十一 保留
20: ("10003", "110101198906010003", "人保-80万"), # 王五 追加新行
}
for row_idx, (code, emp_id, scheme) in expect_in.items():
c_b = ws_in.cell(row=row_idx, column=2).value
c_k = ws_in.cell(row=row_idx, column=11).value
c_m = ws_in.cell(row=row_idx, column=13).value
check(f"在参名单第{row_idx}行: {code}/{emp_id}/{scheme}",
str(c_b) == code and str(c_k) == emp_id and c_m == scheme,
f"实际 B={c_b!r} K={c_k!r} M={c_m!r}")
# ---------- 2.6 断言变更清单 ----------
chg_name = cfg.category_change_sheet_name(category)
ws_chg = wb2[chg_name]
expect_chg = {
3: ("删除", "钱十", "110101199009010009", "人保-20万"),
4: ("增加", "张三", "110101199001010001", "人保-50万"),
5: ("增加", "李四", "110101199002010002", "人保-20万"),
6: ("修改", "王五", "110101198906010003", "人保-80万"),
}
for row_idx, (op, name, emp_id, scheme) in expect_chg.items():
got = (ws_chg.cell(row=row_idx, column=2).value,
ws_chg.cell(row=row_idx, column=16).value,
ws_chg.cell(row=row_idx, column=17).value,
ws_chg.cell(row=row_idx, column=19).value)
check(f"变更清单第{row_idx}行: {op} {name}",
got == (op, name, emp_id, scheme), f"实际 {got}")
check("变更清单 张三 带四级部门", ws_chg.cell(row=4, column=15).value == "三十七度-后厨",
repr(ws_chg.cell(row=4, column=15).value))
check("变更清单 王五 备注替换说明",
ws_chg.cell(row=6, column=13).value == "由人保-20万替换为人保-80万",
repr(ws_chg.cell(row=6, column=13).value))
# ---------- 2.7 断言备份 ----------
backup = cfg.category_output_backup(category)
check("备份新在参名单存在", os.path.isfile(backup))
if os.path.isfile(backup):
df_backup = pd.read_excel(backup)
check("备份含 3 条参保记录", len(df_backup) == 3, f"实际 {len(df_backup)}")
# ---------- 2.8 断言增/减员导入 ----------
add_file = cfg.category_import_add_file(category)
sub_file = cfg.category_import_sub_file(category)
df_add = pd.read_excel(add_file, header=2)
df_sub = pd.read_excel(sub_file, header=2)
check("增员导入=3 条", len(df_add) == 3, f"实际 {len(df_add)}")
check("减员导入=2 条", len(df_sub) == 2, f"实际 {len(df_sub)}")
add_codes = [str(v) for v in df_add.iloc[:, 1].tolist()]
sub_codes = [str(v) for v in df_sub.iloc[:, 1].tolist()]
check("增员含 张三/李四/王五", sorted(add_codes) == ["10001", "10002", "10003"], repr(add_codes))
check("减员含 钱十/王五", sorted(sub_codes) == ["10003", "10009"], repr(sub_codes))
# ---------- 2.9 断言变更清单独立工作簿 ----------
ok_wb = report_output.export_change_sheet_workbook(category)
wb_out = cfg.category_change_sheet_workbook(category)
check("导出变更清单独立工作簿", ok_wb and os.path.isfile(wb_out))
if os.path.isfile(wb_out):
wb3 = load_workbook(wb_out, data_only=True)
ws3 = wb3[chg_name]
check("独立工作簿 保留 4 条变更", ws3.cell(row=3, column=2).value == "删除"
and ws3.cell(row=6, column=2).value == "修改",
f"第3行={ws3.cell(row=3, column=2).value!r} 第6行={ws3.cell(row=6, column=2).value!r}")
# ---------- 汇总 ----------
print("\n" + "=" * 60)
failed = [r for r in RESULTS if not r[1]]
print(f"共 {len(RESULTS)} 项检查,通过 {len(RESULTS) - len(failed)} 项,失败 {len(failed)} 项")
for name, ok, detail in RESULTS:
if not ok:
print(f" FAIL {name}: {detail}")
print(f"测试数据目录(可人工核查):{WORK_DIR}")
sys.exit(1 if failed else 0)
if __name__ == "__main__":
main()
@@ -197,6 +197,194 @@ PUSH_AT_ALL_ENV = "absence_push_at_all" # "1" 时推送文本 @所有
# 缓存以 月/工号 为键互不影响,如需强制刷新删除对应缓存文件即可。
CACHE_DIR = os.path.join(_APP_DATA_DIR, "absence_cache")
# ==================== 收银系统技师考勤(内联,单文件自包含) ====================
# 背景:HR 系统从 2026-09 起不再有技师考勤数据(技师考勤迁移到收银系统),需求9 需两个系统联动:
# - 技师:未出勤日集合来自收银技师月度考勤接口(旷工/请假/休息 逐日显式标记);
# - 非技师:仍走 HR 考勤统计报表 + 请假流程(下方 HR 逻辑不变)。
# 时间边界(重要):2026-09 是技师数据迁移分界——
# - 统计月 / 当前月 >= 2026-09 时,技师未出勤/返岗判定走收银(HR 该月起无技师数据);
# - 统计月早于 2026-09,以及跨月追溯的历史月(2026-09 之前),一律走 HR 原逻辑
# (历史技师数据仍在 HR,见 _month_status_map / _person_month_absent,不做收银覆盖)。
CASHIER_MIGRATE_MONTH = "2026-09" # HR 技师数据迁移到收银的起始月
CASHIER_TOKEN_FILE = os.path.join(_SESSIONS_DIR, 'cashier_tokens.json')
CASHIER_API_BASE = "https://api.37du.cashier.37du.co"
CASHIER_STORE_LIST_URL = f"{CASHIER_API_BASE}/store/manager/connect/list"
CASHIER_ATT_URL = f"{CASHIER_API_BASE}/store/manager/techAttendanceMonthlyReport/month"
CASHIER_STORE_CACHE = os.path.join(_APP_DATA_DIR, 'data', 'cashier_stores.json')
CASHIER_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
# 收银逐日 un_duty_type 首个 code → 需求9 未出勤类别(其余非空 code 一律归为请假)
# code:2=正休(休息)、6=旷工;7=假别7/特殊事假、3=假别3、5=病假、1=事假、4=长假、9/10=假别9/10(请假)
CASHIER_UN_DUTY_CAT = {6: "旷工", 2: "休息"}
# 收银扩展运行时状态(懒初始化):
# session 收银 requests 会话(由 _cashier_build_session 构建)
# tech_codes 已拉取收银考勤的技师 37工号 集合(用于跨月追溯判断「该人走收银数据」)
# month_status 收银未出勤映射缓存 {month: {code: {日期: 类别}}}
# month_on 收银出勤日缓存 {month: {code: {日期}}}(当前月返岗判定用)
_cashier_ext = {"session": None, "tech_codes": set(),
"month_status": {}, "month_on": {}}
def _cashier_build_session():
"""内联:读共享收银 token 构造 requests 会话(认证头 Access-Token/Refresh-Token)。"""
if not os.path.exists(CASHIER_TOKEN_FILE):
raise RuntimeError("未找到收银系统登录态 tokens,请先执行「37du收银登录」指令完成登录后再重试。")
with open(CASHIER_TOKEN_FILE, encoding='utf-8') as f:
tokens = json.load(f)
access = tokens.get("access") or tokens.get("Access-Token") or ""
if not access:
raise RuntimeError("收银系统登录态 tokens 缺少 access token,请重新执行「37du收银登录」指令。")
s = requests.Session()
s.headers.update({
"User-Agent": CASHIER_UA,
"Access-Token": access,
"Refresh-Token": tokens.get("refresh") or tokens.get("Refresh-Token") or "",
})
return s
def _cashier_request(session, method, url, params=None, payload=None):
"""收银接口请求(项目级重试 3 次;401/非 JSON 视为登录失效直接报错)。"""
last_exc = None
for attempt in range(1, 4):
try:
kwargs = {"timeout": 30}
if params:
kwargs["params"] = params
if payload is not None:
kwargs["json"] = payload
resp = session.request(method, url, **kwargs)
if resp.status_code == 401:
raise RuntimeError("收银登录态已失效(HTTP 401),请重新执行「37du收银登录」指令。")
if resp.status_code != 200:
raise RuntimeError(f"收银接口状态码异常:HTTP {resp.status_code}")
text = resp.text
if not text.lstrip().startswith(("{", "[")):
raise RuntimeError("收银登录态已失效(接口未返回 JSON),请重新执行「37du收银登录」指令。")
return resp.json()
except RuntimeError:
raise
except Exception as e:
last_exc = e
if attempt >= 3:
break
time.sleep(2.0 * attempt)
raise last_exc
def _cashier_store_list(session):
"""内联:收银门店列表(带缓存文件复用,避免每次重复拉取)。"""
if os.path.exists(CASHIER_STORE_CACHE):
try:
with open(CASHIER_STORE_CACHE, encoding='utf-8') as f:
cached = json.load(f)
stores = cached.get("stores") or []
if stores:
return stores
except Exception:
pass
data = _cashier_request(session, "GET", CASHIER_STORE_LIST_URL,
params={"_t": str(int(time.time() * 1000))})
stores = data.get("data") or []
if not stores:
raise RuntimeError("收银门店列表接口未返回任何门店")
try:
os.makedirs(os.path.dirname(CASHIER_STORE_CACHE), exist_ok=True)
with open(CASHIER_STORE_CACHE, 'w', encoding='utf-8') as f:
json.dump({"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"), "stores": stores},
f, ensure_ascii=False, indent=2)
except Exception as e:
logger.warning("收银门店缓存写入失败:%s", e)
return stores
def _cashier_day_cat(det):
"""收银逐日明细 → 需求9 未出勤类别(旷工/请假/休息);正常出勤返回 None。
以 un_duty_type 首个 code 为准(6=旷工、2=正休,其余非空=请假);display_text 兜底。
"""
un = det.get("un_duty_type")
if isinstance(un, list) and un:
cat = CASHIER_UN_DUTY_CAT.get(un[0])
return cat if cat else "请假"
txt = "".join(det.get("display_text") or [])
if "旷工" in txt:
return "旷工"
if "正休" in txt:
return "休息"
if txt and txt != "正常":
return "请假"
return None
def _is_cashier_month(month_str):
"""月份是否落在技师数据迁移月(2026-09)及以后——该月技师考勤需同时取收银数据。
兼容 "YYYY-MM" 与 "YYYYMM" 两种入参。
"""
try:
ym = int(str(month_str).replace("-", "")[:6])
return ym >= int(CASHIER_MIGRATE_MONTH.replace("-", ""))
except Exception:
return False
def _cashier_tech_status(month_key):
"""拉取某月全部门店收银技师考勤 → 未出勤映射 {工号: {日期: 类别}}(带缓存)。
同时把该月各技师「出勤日集合」写入 _cashier_ext["month_on"][month_key][code],
供当前月返岗判定使用;技师工号并入 _cashier_ext["tech_codes"]。
未初始化收银会话(无 token)时返回空 dict(调用方降级仅用 HR 数据)。
注意:仅统计月 / 当前月(>= CASHIER_MIGRATE_MONTH)才调用本函数;跨月追溯的历史月
(2026-09 之前)技师数据仍在 HR,走 _month_status_map / _person_month_absent 原逻辑。
"""
if _cashier_ext["session"] is None:
return {}
if month_key in _cashier_ext["month_status"]:
return _cashier_ext["month_status"][month_key]
year, month = int(month_key[:4]), int(month_key[5:7])
mb, me = _month_range(month_key)
stores = _cashier_store_list(_cashier_ext["session"])
result, on_map = {}, {}
for store in stores:
store_id = store.get("store_id")
try:
data = _cashier_request(
_cashier_ext["session"], "POST", CASHIER_ATT_URL,
payload={"store_id": store_id, "year": year, "month": month}).get("data") or []
except Exception as e:
logger.warning("收银门店 %s(%s) 考勤拉取失败:%s", store_id, store.get("store_name"), e)
continue
time.sleep(0.3) # 门店间限速,避免被接口限流
for t in data:
code = str(t.get("tech_base_code") or "").strip()
if not code:
continue
daymap, on_days = {}, set()
for det in (t.get("monthly_detail") or []):
day = det.get("day")
if not isinstance(day, int) or not (mb.day <= day <= me.day):
continue
d = date(year, month, day)
cat = _cashier_day_cat(det)
if cat:
daymap[d] = cat
else:
on_days.add(d) # 正常出勤日
if daymap:
result[code] = daymap
if on_days:
on_map[code] = on_days
_cashier_ext["tech_codes"].add(code)
_cashier_ext["month_status"][month_key] = result
_cashier_ext["month_on"][month_key] = on_map
logger.info("收银技师考勤 %s:%d 家门店、%d 名技师进入未出勤映射、%d 名有出勤日",
month_key, len(stores), len(result), len(on_map))
return result
# ==================== 登录态(共享 cookies 文件) ====================
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login.py),
# 本脚本仅读取共享 cookies 文件;花名册由「37du花名册导出」指令导出到固定路径后由本脚本读取。
@@ -780,6 +968,15 @@ def _month_status_map(month_cache, session, user_id, month_str, seen=None):
mb, me = _month_range(month_str)
records = _cached_attendance(session, user_id, month_str.replace("-", ""))
merged = _report_records_to_status(records, mb, me, seen)
# 追溯月 >= 2026-09:HR + 收银两份数据,技师未出勤以收银为准覆盖(HR 该月起无技师数据)
if _is_cashier_month(month_str):
try:
tech_map = _cashier_tech_status(month_str)
for code, daymap in tech_map.items():
merged[code] = daymap
logger.info("收银技师考勤并入追溯月 %s:%d 人", month_str, len(tech_map))
except Exception as e:
logger.warning("收银技师考勤拉取失败(追溯月 %s 技师数据可能缺失):%s", month_str, e)
leaves = _cached_leave(session, user_id, "", month_str)
_merge_leave_status(merged, leaves, mb, me)
logger.info("已构建 %s 月缺勤映射(报表 %d 人 + 全集团请假 %d 条)",
@@ -843,6 +1040,16 @@ def _person_month_absent(session, user_id, code, month_str, seen=None, status_ca
d += timedelta(days=1)
i += 1
break
# 追溯月 >= 2026-09:技师未出勤以收银为准覆盖(HR 该月起无技师数据,避免技师段漏判)。
# 直接查该月收银映射是否含该工号,命中即视为技师并以收银为准(不依赖全局 tech_codes)。
if _is_cashier_month(month_str):
try:
tech_daymap = _cashier_tech_status(month_str).get(code, {})
if tech_daymap:
daymap = dict(tech_daymap)
logger.info("收银技师考勤覆盖追溯月 %s %s(%d 天)", month_str, code, len(daymap))
except Exception as e:
logger.warning("收银技师考勤拉取失败(%s %s):%s", month_str, code, e)
_merge_leave_status({code: daymap}, _cached_leave(session, user_id, code, month_str), mb, me)
if status_cache is not None and daymap:
status_cache.setdefault(month_str, {}).setdefault(code, {}).update(daymap)
@@ -975,7 +1182,9 @@ def _analyze(emp, month_status, session, user_id, begin, end, cur_ctx=None):
再逐个解析起始日、统计备注并组装名单行。
month_status:查询月全集团状态映射 {工号: {日期: 类别}}(含 旷工/休息/请假)。
cur_ctx:返岗判定上下文 (cur_status, cur_rows, cur_begin, cur_end),None 表示不需要。
cur_ctx:返岗判定上下文 (cur_status, cur_rows, cur_begin, cur_end, cashier_cur),
None 表示不需要。cashier_cur 为收银技师当前月「出勤日集合」{工号: {日期}},
code 命中时以其判定返岗(技师源,HR 当前月无技师数据);未命中走 cur_rows 报表判定。
"""
seen = {}
query_month = begin.strftime("%Y-%m")
@@ -1034,16 +1243,23 @@ def _analyze(emp, month_status, session, user_id, begin, end, cur_ctx=None):
# 否则回到情况A:请假仍在进行(已备案假单 end_date > 统计月末)取请假截止日,无则「未归岗,时间待定」。
return_day = None
if cur_ctx is not None:
cur_status, cur_rows, cur_begin, cur_end = cur_ctx
row = cur_rows.get(code)
if row is not None:
cur_absent = cur_status.get(code, {})
d = cur_begin
while d <= cur_end:
if _clean(row.get(f"v_{d.day}")) and d not in cur_absent:
cur_status, cur_rows, cur_begin, cur_end, cashier_cur = cur_ctx
# 技师(收银源,>= 2026-09 的当前月):用收银「出勤日集合」判定返岗(HR 当前月无技师数据)
if code in cashier_cur:
for d in sorted(cashier_cur[code]):
if cur_begin <= d <= cur_end:
return_day = d
break
d += timedelta(days=1)
else:
row = cur_rows.get(code)
if row is not None:
cur_absent = cur_status.get(code, {})
d = cur_begin
while d <= cur_end:
if _clean(row.get(f"v_{d.day}")) and d not in cur_absent:
return_day = d
break
d += timedelta(days=1)
if return_day is not None:
end_date = return_day - timedelta(days=1)
end_str = end_date.strftime("%Y-%m-%d")
@@ -1186,6 +1402,20 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
session = build_hr_session()
session, user_id = _validate_session(session)
# 2.5 收银系统会话(技师考勤源):HR 自 CASHIER_MIGRATE_MONTH(2026-09) 起不再有技师数据。
# 统计月或当前月落在迁移月及以后时初始化收银会话;无 token 时降级仅用 HR(不阻断流程)。
# 时间边界(与用户确认):月份 < 2026-09 只用 HR;>= 2026-09 则 HR + 收银两份,
# 技师未出勤以收银为准;跨月追溯历史月同样按此规则(见 _month_status_map / _person_month_absent)。
today_m = date.today().strftime("%Y-%m")
cashier_ready = False
if _is_cashier_month(month_str) or _is_cashier_month(today_m):
try:
_cashier_ext["session"] = _cashier_build_session()
cashier_ready = True
logger.info("收银系统会话就绪(技师考勤源,迁移月 %s)", CASHIER_MIGRATE_MONTH)
except Exception as e:
logger.warning("收银系统登录态不可用(技师考勤将缺失,非技师不受影响):%s", e)
# 3. 拉取上月全集团考勤统计报表,按报表判定「休息/旷工」,再并入整天请假(leave_days>=1)
# 统计月(上月)始终实时调接口,不走缓存;跨月追溯的历史月才走懒缓存。
seen = {}
@@ -1195,6 +1425,15 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
logger.error("考勤统计报表无数据,请检查月份或权限")
return ""
month_status = _report_records_to_status(records, begin, end, seen)
# 统计月 >= 2026-09:HR + 收银两份,技师未出勤以收银为准覆盖(HR 该月起无技师数据)
if cashier_ready and _is_cashier_month(month_str):
try:
tech_map = _cashier_tech_status(month_str)
for code, daymap in tech_map.items():
month_status[code] = daymap
logger.info("收银技师考勤并入统计月 %d 人", len(tech_map))
except Exception as e:
logger.warning("收银技师考勤拉取失败(技师数据可能缺失):%s", e)
leaves = fetch_all_leave(
session, user_id, "", begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
_merge_leave_status(month_status, leaves, begin, end)
@@ -1213,7 +1452,16 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
session, user_id, "", cur_begin.strftime("%Y-%m-%d"), cur_end.strftime("%Y-%m-%d"))
_merge_leave_status(cur_status, cur_leaves, cur_begin, cur_end)
cur_rows = {_clean(r.get("base_code")): r for r in cur_records if _clean(r.get("base_code"))}
cur_ctx = (cur_status, cur_rows, cur_begin, cur_end)
# 当前月 >= 2026-09:技师返岗判定用收银「出勤日集合」(HR 当前月无技师数据,row 为空会漏判)
cashier_cur = {}
if cashier_ready and _is_cashier_month(today_m):
try:
_cashier_tech_status(today_m) # 先确保当前月收银映射(含出勤日 month_on)已加载
cashier_cur = dict(_cashier_ext["month_on"].get(today_m, {}))
logger.info("收银技师当前月返岗判定:%d 名技师有出勤日", len(cashier_cur))
except Exception as e:
logger.warning("收银技师当前月数据拉取失败(返岗判定降级):%s", e)
cur_ctx = (cur_status, cur_rows, cur_begin, cur_end, cashier_cur)
logger.info("统计月 %s 已结束,补拉当前月 %s~%s 考勤用于返岗判定(%d 人,请假 %d 条)",
month_str, cur_begin, cur_end, len(cur_rows), len(cur_leaves))
+293
View File
@@ -0,0 +1,293 @@
# -*- coding: utf-8 -*-
"""
@FileName: cashier_login.py
@Description: 收银系统登录自定义指令(影刀编码版 Python 模块源码)。
作为「37du收银登录」影刀自定义指令的模块源码(单一真源),
供所有收银系统影刀脚本复用,避免每个脚本各自内联登录逻辑。
登录页(Ant Design Vue SPA)元素:
账号输入框 <input id="form_item_account" placeholder="账号" type="text">
密码输入框 <input id="form_item_password" placeholder="密码" type="password">
登录按钮 <button class="ant-btn ant-btn-primary ant-btn-lg ant-btn-block">登录</button>
登录成功判定:URL 进入 cashier_target_url_keyword(默认 admin.37du.cashier.37du.co/)
即视为登录成功;登录页无滑块/图形验证码,属纯账号密码登录。
如何在影刀中创建指令:
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 cashier_login,添加 Python 模块;
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 Access-Token。
约定(与 OA/HR/ERP 登录模块一致):
- 配置:读取共享 .env(%LOCALAPPDATA%\\37duAutomation\\.env)与项目根 .env
(workflows 影刀脚本统一使用根 .env,见 AGENTS.md),再兼容当前工作目录 .env;
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\cashier_tokens.json
(Access-Token/Refresh-Token 请求头,收银认证不走 cookie),
各影刀业务脚本自行用这些 token 构建 requests.Session。
配置(读取 .env,缺失时使用内置默认值):
cashier_login_url=收银登录页 URL
cashier_target_url_keyword=登录成功后 URL 关键字
cashier_login_username=账号(仅从 .env 读取,不内置明文)
cashier_login_password=密码(仅从 .env 读取,不内置明文)
cashier_validate_url=(可选)会话校验接口 URL;不配置时默认请求
cashier_target_url_keyword,被重定向回 /login 即视为会话失效
全局变量(在影刀流程中创建,此指令负责写入):
login_state 登录成功或缓存的 token 有效时写入 True,否则为 False
依赖(影刀「Python包管理」安装):
pip install DrissionPage requests python-dotenv
入口:
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
python cashier_login.py 独立运行(等价于 main({"force": true}))
"""
import os
import json
import time
from DrissionPage import ChromiumPage
from dotenv import load_dotenv
import requests
# ================== 共享路径(与 OA/HR 模块统一) ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
# 收银系统登录态不是 cookie 而是 Access-Token/Refresh-Token 请求头(存在浏览器 localStorage,
# 无法直接解码)。登录指令负责抓取 token 写入 TOKEN_FILE;cashier_api 用其构造请求头。
TOKEN_FILE = os.path.join(_SESSIONS_DIR, 'cashier_tokens.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
# workflows/ 影刀脚本统一使用项目根 .env(本文件位于 workflows/share/ 下,向上三级为项目根)
_ROOT_ENV_FILE = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), '.env')
def _load_shared_env():
"""统一加载配置:优先共享 .env,再加载项目根 .env,最后兼容当前工作目录 .env 与系统变量。"""
if os.path.exists(SHARED_ENV_FILE):
load_dotenv(SHARED_ENV_FILE)
if os.path.exists(_ROOT_ENV_FILE):
load_dotenv(_ROOT_ENV_FILE)
load_dotenv()
# ================== 配置 ==================
# 账号密码只从 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目根 .env),不内置明文,
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
_load_shared_env()
LOGIN_URL = os.getenv('cashier_login_url', 'https://admin.37du.cashier.37du.co/login')
SUCCESS_KEYWORD = os.getenv('cashier_target_url_keyword', 'https://admin.37du.cashier.37du.co/')
USERNAME = os.getenv('cashier_login_username', '')
PASSWORD = os.getenv('cashier_login_password', '')
# 登录页元素定位(Ant Design Vue,id 固定)
USERNAME_INPUT = '#form_item_account'
PASSWORD_INPUT = '#form_item_password'
LOGIN_BTN = 'css:.ant-btn-primary.ant-btn-lg.ant-btn-block'
TIMEOUT = 10
WAIT_AFTER_LOAD = 2
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
# ================== Token 持久化(Access-Token / Refresh-Token) ==================
def save_tokens(page):
"""抓取 Access-Token/Refresh-Token 并保存到 TOKEN_FILE。
token 存放在浏览器 localStorage(加密 blob 无法直接解码),最可靠的方式是监听 SPA 发出的
api.37du.cashier.37du.co 请求,从请求头读取 Access-Token/Refresh-Token 两个 UUID。
通过刷新页面强制触发一次带 token 的 API 请求后再抓取。
"""
try:
page.listen.set_targets("api.37du.cashier.37du.co")
page.listen.start()
page.refresh()
tokens = {}
for packet in page.listen.steps(timeout=15):
try:
h = packet.request.headers
if h.get("Access-Token"):
tokens = {"access": h.get("Access-Token"),
"refresh": h.get("Refresh-Token", "")}
break
except Exception:
pass
finally:
try:
page.listen.stop()
except Exception:
pass
if not tokens.get("access"):
print("未抓到 Access-Token,跳过保存")
return False
ensure_dir(_SESSIONS_DIR)
with open(TOKEN_FILE, 'w', encoding='utf-8') as f:
json.dump(tokens, f, ensure_ascii=False, indent=2)
print(f"已保存 Access-Token/Refresh-Token 到 {TOKEN_FILE}")
return True
def load_tokens():
if not os.path.exists(TOKEN_FILE):
return None
with open(TOKEN_FILE, encoding='utf-8') as f:
tokens = json.load(f)
return tokens or None
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== API 校验 Token 有效性(无需打开浏览器) ==================
def _is_cashier_session_valid():
"""API 轻量校验收银系统 Access-Token。
用已保存的 Access-Token/Refresh-Token 请求头调用门店列表接口:
返回 JSON(以 { 开头)即视为有效。
"""
try:
tokens = load_tokens()
if not tokens or not tokens.get("access"):
return False
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
"Access-Token": tokens["access"],
"Refresh-Token": tokens.get("refresh", ""),
})
resp = session.get(
"https://api.37du.cashier.37du.co/store/manager/connect/list",
params={"_t": str(int(time.time() * 1000))}, timeout=15)
if resp.status_code != 200:
print(f"API 校验 Token 状态码异常:{resp.status_code}")
return False
text = resp.text
return bool(text) and text.lstrip().startswith("{")
except Exception as e:
print(f"API 校验 Token 异常:{e}")
return False
# ================== 登录主流程 ==================
def _on_target(page):
"""登录成功判定:进入目标地址,或已离开 /login 登录页(SPA 路由跳转)。"""
return SUCCESS_KEYWORD in page.url or '/login' not in page.url
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
"""打开浏览器完成收银系统账号密码登录,成功保存 Access-Token/Refresh-Token。"""
page = ChromiumPage()
try:
page.get(LOGIN_URL)
time.sleep(wait_after_load)
# 已登录(浏览器带有效会话时打开登录页会被 SPA 重定向到首页)
if _on_target(page):
print(f"打开登录页时已处于登录态:{page.url}")
save_tokens(page)
return True
username_input = page.ele(USERNAME_INPUT)
if not username_input:
raise RuntimeError("未找到账号输入框")
username_input.input(USERNAME)
page.wait(0.5)
password_input = page.ele(PASSWORD_INPUT)
if not password_input:
raise RuntimeError("未找到密码输入框")
password_input.input(PASSWORD)
page.wait(0.5)
login_button = page.ele(LOGIN_BTN)
if not login_button:
raise RuntimeError("未找到登录按钮")
login_button.click()
page.wait(0.5)
start = time.time()
while time.time() - start < timeout:
if _on_target(page):
print(f"登录成功!当前 URL: {page.url}")
save_tokens(page)
return True
time.sleep(0.5)
error_elem = page.ele('.ant-message-error') or page.ele('.ant-form-item-explain-error')
if error_elem:
print(f"登录失败,提示: {error_elem.text}")
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
finally:
try:
page.quit()
except Exception:
pass
def ensure_login(force=False):
"""
确保存在有效的收银系统登录态并缓存 Access-Token/Refresh-Token。
返回 JSON 安全 dict:{success, token_path, message, relogin}
"""
_load_shared_env()
# 默认未登录;登录成功或复用有效 token 后再置 True
_set_login_state(False)
if not (LOGIN_URL and SUCCESS_KEYWORD):
return {"success": False, "token_path": TOKEN_FILE,
"message": "登录配置缺失(cashier_login_url / cashier_target_url_keyword 未配置且无内置默认值)", "relogin": False}
if not (USERNAME and PASSWORD):
return {"success": False, "token_path": TOKEN_FILE,
"message": "登录配置缺失(cashier_login_username / cashier_login_password 未配置且无内置默认值)", "relogin": False}
# 优先复用已保存的 token(通过 API 校验有效性,无需打开浏览器)
if not force and _is_cashier_session_valid():
print("已通过缓存的 Access-Token 复用收银系统登录态")
_set_login_state(True)
return {"success": True, "token_path": TOKEN_FILE,
"message": "复用缓存登录态", "relogin": False}
ok = _do_login()
if ok:
_set_login_state(True)
return {"success": True, "token_path": TOKEN_FILE, "message": "登录成功", "relogin": True}
return {"success": False, "token_path": TOKEN_FILE,
"message": "登录失败", "relogin": False}
# ================== 影刀自定义指令入口 ==================
def main(args):
"""
影刀自定义指令「37du收银登录」调用入口。
args: dict,可选字段 force(bool) 是否强制重新登录
返回: dict {success, token_path, message, relogin}
"""
if not args:
args = {}
force = bool(args.get("force", False))
try:
return ensure_login(force=force)
except Exception as e:
return {"success": False, "token_path": TOKEN_FILE,
"message": f"登录过程异常:{e}", "relogin": False}
if __name__ == "__main__":
result = main({"force": True})
print("最终结果:", result)