feat(employer-insurance): 新增雇主险增减员导入功能与流程优化

本次提交完成雇主险增减员导入全流程升级,包括:
1.  新增姓名关键字过滤规则,自动剔除测试/人资账号数据
2.  新增变更清单独立工作簿导出功能,保留格式与公式
3.  重构增减员导入流程,监听接口捕获全量导入异常
4.  新增影刀版钉钉推送异常消息适配,支持块格式分组推送
5.  更新文档与配置项,同步维护app与影刀双版本代码
This commit is contained in:
2026-08-26 14:49:33 +08:00
parent db109a686e
commit 343768f52c
13 changed files with 718 additions and 559 deletions
+4 -1
View File
@@ -54,4 +54,7 @@ aa.md
# vc运行库
vc_redist/
vc_redist_x64/
vc_redist_x86/
vc_redist_x86/
静态资源/
.assets/
+2 -469
View File
@@ -1,469 +1,2 @@
# 📄 OA工作沟通自动化发送 - 需求文档
## 1. 项目背景
通过RPA技术,模拟浏览器行为调用OA系统后台接口,实现**无界面、无需人工填写**的工作沟通自动发送,支持:
- 多接收人
- 多附件
- 自定义标题和内容(支持HTML富文本)
---
## 2. 业务流程概览
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 1.登录认证 │───▶│ 2.搜索接收人 │───▶│ 3.上传附件 │───▶│ 4.提交沟通 │───▶│ 5.确认结果 │
│ (Cookie) │ │ (获取ID) │ │ (获取attid)│ │ (user.jsp) │ │ (返回ID) │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
---
## 3. 核心接口清单
| 步骤 | 接口 | 方法 | 关键参数 | 返回 |
|------|------|------|----------|------|
| 搜索人员 | `/sys/common/dataxml.jsp` | GET | `key=工号/姓名` | 人员ID (XML) |
| 获取上传凭证 | `/sysAttMain.do` | GET | `gettype=getuserkey` | `userkey` |
| MD5秒传校验 | `/sysAttMain.do` | GET | `gettype=checkMd5` | `md5Exists` |
| 上传二进制 | `/uploaderServlet` | POST | `file` (二进制) | `filekey` |
| 提交绑定附件 | `/sysAttMain.do` | GET | `gettype=submit` | **`attid`** |
| 提交沟通 | `/sys/ui/resources/user.jsp` | POST | `participantIds`, `docSubject`, `fdContent`, `attachmentIds` | 沟通ID |
---
## 4. 数据结构说明
### 4.1 人员搜索返回(XML)
```xml
<data id="37b1d9a5c5834a98bc4274143ab53d10" name="夏一平" ... />
```
### 4.2 附件上传最终返回
```json
{"attid":"1a037cb5b4a66d17f7224194c9995b29","status":"1"}
```
### 4.3 沟通提交参数
| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `fdId` | string | 否 | 新建传空 |
| `participantIds` | string | 是 | 接收人ID,多个逗号分隔 |
| `participantNames` | string | 是 | 接收人姓名,多个逗号分隔,顺序与ID一致 |
| `docSubject` | string | 是 | 标题 |
| `fdContent` | string | 是 | 内容(支持HTML) |
| `attachmentForms.attachment.attachmentIds` | string | 否 | 附件ID,多个逗号分隔 |
| `docCreatorId` | string | 是 | 创建人ID |
| `fdNotifyType` | string | 是 | 固定 `todo` |
| `fdRemindersDay` | string | 否 | 固定 `2` |
---
# 🐍 完整代码
```python
"""
OA工作沟通自动化发送脚本
支持:多接收人、多附件、HTML内容
依赖:requests, xml.etree.ElementTree
"""
import requests
import hashlib
import os
import base64
import time
import xml.etree.ElementTree as ET
from typing import List, Union, Optional
# ============================================================
# 配置区域(请根据实际情况修改)
# ============================================================
OA_BASE_URL = "https://oa.37du.co" # OA系统根地址
# 登录方式1:已有Cookie(从浏览器导出)
COOKIE_STRING = "" # 如 "JSESSIONID=xxx; Route=xxx"
# 登录方式2:账号密码(需要自行实现登录逻辑)
USERNAME = "" # 工号
PASSWORD = "" # 密码
# 当前操作人的ID(可通过搜索自己的工号获取)
CREATOR_ID = "37b1d9a5c5834a98bc4274143ab53d10" # 替换为实际值
# ============================================================
# 工具函数
# ============================================================
def get_session() -> requests.Session:
"""获取已登录的Session"""
session = requests.Session()
# 方式1:设置已有Cookie
if COOKIE_STRING:
for cookie in COOKIE_STRING.split("; "):
if "=" in cookie:
key, value = cookie.split("=", 1)
session.cookies.set(key, value)
print("✅ 使用已有Cookie登录")
return session
# 方式2:账号密码登录(这里需要根据实际登录接口实现)
if USERNAME and PASSWORD:
# TODO: 实现具体登录逻辑
# login_url = f"{OA_BASE_URL}/login.do"
# session.post(login_url, data={"username": USERNAME, "password": PASSWORD})
print("⚠️ 请实现登录逻辑,或使用COOKIE_STRING方式")
return session
print("⚠️ 未配置登录信息,请设置 COOKIE_STRING 或 USERNAME/PASSWORD")
return session
def search_person(session: requests.Session, keyword: str) -> Optional[tuple]:
"""
根据工号或姓名搜索人员
:return: (person_id, person_name) 或 None
"""
url = f"{OA_BASE_URL}/sys/common/dataxml.jsp"
params = {
"s_bean": "organizationDialogSearch",
"orgType": "15",
"deptLimit": "",
"isExternal": "",
"key": keyword,
"s_ajax": "true"
}
try:
resp = session.get(url, params=params)
if resp.status_code != 200:
print(f"❌ 搜索人员失败: HTTP {resp.status_code}")
return None
# 解析XML
root = ET.fromstring(resp.text)
data = root.find(".//data")
if data is None:
print(f"❌ 未找到人员: {keyword}")
return None
person_id = data.get("id")
person_name = data.get("name")
print(f"✅ 搜索到人员: {person_name} (ID: {person_id})")
return person_id, person_name
except Exception as e:
print(f"❌ 搜索人员异常: {e}")
return None
def upload_attachment(session: requests.Session, file_path: str) -> Optional[str]:
"""
上传单个附件,返回 attid(最终附件ID)
完整模拟了OA的5步上传流程
"""
file_name = os.path.basename(file_path)
file_size = str(os.path.getsize(file_path))
# 计算MD5
with open(file_path, 'rb') as f:
md5_hash = hashlib.md5(f.read()).hexdigest()
# 文件修改时间
last_modified = time.strftime("%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
# fdSign = Base64(文件名)
fd_sign = base64.b64encode(file_name.encode()).decode()
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": f"{OA_BASE_URL}/",
"X-Requested-With": "XMLHttpRequest"
}
session.headers.update(headers)
base_att_url = f"{OA_BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
# ---- 步骤1:获取 userkey ----
params1 = {
"method": "handleAttUpload",
"gettype": "getuserkey",
"format": "json",
"filesize": file_size,
"md5": "",
"fileName": file_name,
"isSupportDirect": "false",
"s_ajax": "true"
}
try:
resp1 = session.get(base_att_url, params=params1)
userkey = resp1.json().get("token", {}).get("header", {}).get("userkey")
if not userkey:
print(f"❌ 获取userkey失败: {resp1.text}")
return None
print(f" ✅ 1. 获取userkey成功")
except Exception as e:
print(f"❌ 步骤1异常: {e}")
return None
# ---- 步骤2:MD5秒传校验 ----
params2 = {
"method": "handleAttUpload",
"gettype": "checkMd5",
"format": "json",
"filesize": file_size,
"md5": md5_hash,
"fileName": file_name,
"isSupportDirect": "false",
"s_ajax": "true"
}
try:
resp2 = session.get(base_att_url, params=params2)
result2 = resp2.json()
md5_exists = result2.get("md5Exists", False)
print(f" ✅ 2. MD5校验: {'已存在(秒传)' if md5_exists else '需上传'}")
except Exception as e:
print(f"❌ 步骤2异常: {e}")
return None
# ---- 步骤3:上传二进制(仅当文件不存在时) ----
if not md5_exists:
uploader_url = f"{OA_BASE_URL}/sys/attachment/uploaderServlet?gettype=upload&format=json"
files = {
'file': (file_name, open(file_path, 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
}
data3 = {
'id': 'WU_FILE_0',
'name': file_name,
'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'lastModifiedDate': last_modified,
'size': file_size
}
try:
resp3 = session.post(uploader_url, files=files, data=data3)
filekey = resp3.json().get("filekey")
if not filekey:
print(f"❌ 上传二进制失败: {resp3.text}")
return None
print(f" ✅ 3. 二进制上传成功, filekey: {filekey[:16]}...")
except Exception as e:
print(f"❌ 步骤3异常: {e}")
return None
else:
# 秒传成功,需要获取已存在文件的filekey
# 这里需要额外接口,部分OA支持直接用md5做submit
# 简化处理:调用一个获取文件信息的接口(如果有)
filekey = md5_hash # 尝试用md5作为filekey(不保证成功)
print(f" ⚠️ 3. 秒传模式,使用md5作为filekey: {filekey[:16]}...")
# ---- 步骤4:提交绑定附件(获取最终attid) ----
params4 = {
"method": "handleAttUpload",
"gettype": "submit",
"format": "json",
"filekey": filekey,
"filename": file_name,
"fdKey": "attachment",
"fdModelName": "com.landray.kmss.km.collaborate.model.KmCollaborateMain",
"fdAttType": "byte",
"width": "null",
"height": "null",
"proportion": "true",
"fdSign": fd_sign,
"s_ajax": "true"
}
try:
resp4 = session.get(base_att_url, params=params4)
result4 = resp4.json()
attid = result4.get("attid")
if result4.get("status") != "1" or not attid:
print(f"❌ 提交绑定失败: {resp4.text}")
return None
print(f" ✅ 4. 提交绑定成功, attid: {attid}")
return attid
except Exception as e:
print(f"❌ 步骤4异常: {e}")
return None
def send_work_communication(
session: requests.Session,
receiver_ids: Union[str, List[str]],
receiver_names: Union[str, List[str]],
subject: str,
content: str,
attachment_ids: Union[str, List[str]] = None,
creator_id: str = None
) -> Optional[str]:
"""
发送工作沟通(新建)
:param session: 已登录的Session
:param receiver_ids: 接收人ID,单个字符串或列表
:param receiver_names: 接收人姓名,单个字符串或列表(顺序需与ID一致)
:param subject: 标题
:param content: 内容(支持HTML)
:param attachment_ids: 附件ID,单个字符串或列表
:param creator_id: 创建人ID,默认使用全局CREATOR_ID
:return: 沟通ID(成功时返回数字字符串)
"""
# 类型转换
if isinstance(receiver_ids, list):
receiver_ids_str = ",".join(receiver_ids)
else:
receiver_ids_str = receiver_ids
if isinstance(receiver_names, list):
receiver_names_str = ",".join(receiver_names)
else:
receiver_names_str = receiver_names
if isinstance(attachment_ids, list):
attachment_ids_str = ",".join(attachment_ids)
else:
attachment_ids_str = attachment_ids or ""
if creator_id is None:
creator_id = CREATOR_ID
# 构造参数
data = {
"fdId": "", # 新建传空
"participantIds": receiver_ids_str,
"participantNames": receiver_names_str,
"docSubject": subject,
"fdContent": content,
"docCreatorId": creator_id,
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
"attachmentForms.attachment.fdModelName": "com.landray.kmss.km.collaborate.model.KmCollaborateMain",
"attachmentForms.attachment.fdKey": "attachment",
"fdNotifyType": "todo",
"fdRemindersDay": "2",
"fdIsOnlyView": "false",
"fdIsReminders": "false",
"fdPartnerOperating": "true",
"_fdPartnerOperating": "true",
"fdCategoryId": "",
}
# 防重复提交参数(取第一个附件ID做标记)
if attachment_ids_str:
first_att = attachment_ids_str.split(",")[0]
data[f"__notify_type_{first_att}"] = "todo"
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do",
"X-Requested-With": "XMLHttpRequest"
}
url = f"{OA_BASE_URL}/sys/ui/resources/user.jsp?s_ajax=true"
try:
resp = session.post(url, data=data, headers=headers)
if resp.status_code != 200:
print(f"❌ 发送沟通失败: HTTP {resp.status_code}")
print(f" 返回: {resp.text[:200]}")
return None
# 成功时返回数字ID(如 "37036361")
if resp.text.strip().isdigit():
print(f"✅ 发送沟通成功! 沟通ID: {resp.text}")
return resp.text.strip()
else:
print(f"❌ 发送沟通失败: {resp.text[:200]}")
return None
except Exception as e:
print(f"❌ 发送沟通异常: {e}")
return None
# ============================================================
# 主流程测试
# ============================================================
def main():
"""主流程:登录 → 搜索人员 → 上传附件 → 发送沟通"""
print("=" * 50)
print("开始执行OA工作沟通自动化发送")
print("=" * 50)
# 1. 获取登录Session
session = get_session()
# 2. 搜索接收人(示例:通过工号搜索)
print("\n--- 搜索接收人 ---")
person_id, person_name = search_person(session, "37036801") # 替换为实际工号
if not person_id:
print("❌ 未找到接收人,退出")
return
# 3. 上传附件(示例:上传一个文件)
print("\n--- 上传附件 ---")
# attid = upload_attachment(session, "data.xlsx") # 替换为实际文件路径
# 4. 发送沟通
print("\n--- 发送沟通 ---")
result = send_work_communication(
session=session,
receiver_ids=person_id,
receiver_names=person_name,
subject="【RPA测试】工作沟通",
content="<p>这是通过RPA接口自动发送的测试内容。</p><p>如有疑问请联系IT支持。</p>",
attachment_ids=None, # 或传入 ["attid1", "attid2"]
creator_id=CREATOR_ID
)
if result:
print(f"\n🎉 全部流程完成! 沟通ID: {result}")
else:
print("\n❌ 流程执行失败,请检查日志")
if __name__ == "__main__":
main()
```
---
# 📋 测试清单
在正式运行前,请确认以下事项:
| 检查项 | 状态 | 说明 |
|--------|------|------|
| ✅ Cookie/登录态 | ☐ | 设置 `COOKIE_STRING` 或实现登录逻辑 |
| ✅ 创建人ID | ☐ | 设置 `CREATOR_ID`,可通过搜索自己工号获取 |
| ✅ 接收人工号 | ☐ | 在 `main()` 中替换 `"37036801"` |
| ✅ 测试文件路径 | ☐ | 在 `main()` 中替换 `"data.xlsx"` |
| ✅ 附件上传测试 | ☐ | 先测试单个小文件(<1MB) |
---
# ⚠️ 常见问题
| 问题 | 可能原因 | 解决方案 |
|------|----------|----------|
| 返回302跳转 | Session过期或Cookie无效 | 重新获取Cookie,检查登录态 |
| `participantNames` 乱码 | 编码问题 | 确保传入的姓名为UTF-8编码 |
| 附件上传失败 | 文件路径错误或权限问题 | 检查文件是否存在,使用绝对路径 |
| 秒传模式 `filekey` 无效 | MD5替代`filekey`不被支持 | 需要额外抓包获取秒传后的`filekey`获取方式 |
| 返回 `{"msg":"参数错误"}` | 缺少必填参数 | 检查 `participantNames`、`docCreatorId` 是否填写 |
---
# 🚀 后续优化建议
1. **批量发送**:封装 `batch_send()` 函数,传入多个接收人和对应附件
2. **模板管理**:将常用标题、内容模板化
3. **日志记录**:记录每次发送的请求和响应,便于追踪
4. **异常重试**:对网络波动导致的失败自动重试
---
"D:\资料\人资\告知书制作与下发\202608参保与停保名单.xlsx"
申请停保 筹建门店 合同单位 参保=合同? EHR参保单位 人员类型 问题 参保类型 序号 申请 工号 姓名 岗位 身份证号码 电话号码 户口性质 残疾证 参保单位 非标基数 申报基数 社保号 参保单位全称 税务登记号 密码 区域 性质 所属单位 一级部门 二级部门 三级部门 四级部门 验证 入职时间 年龄 性别 职级 职衔 身份证地址 文化程度 民族 社保补贴 办理状态 办理人 办理时间 EHR系统更新 参保告知 备注 参保异常处理进度 费用 身份证 姓名 民族 工作日期 工资 工种 个人身份 户口 联系电话 文化程度
@@ -9,7 +9,9 @@
- 前置:步骤2 调度(employer_insurance.py)完成,并准备好增员/减员导入文件
- 传入参数:增员(默认商业保险增员导入.xlsx)或 减员(商业保险减员导入.xlsx)
- 复用 HR 登录态(app.service.hrbp.common.login 的缓存 cookies)
@Version: 1.0.0
@Version: 1.2.0
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
使用说明:
1. 首次运行会调用 HR 登录模块完成登录并缓存 cookies;后续自动复用,过期自动重新登录。
@@ -22,6 +24,7 @@
import_employee_change("增员", None, r"D:\\...\\xxx.xlsx") # 指定导入文件
"""
import json
import os
import sys
import time
@@ -70,6 +73,13 @@ WAIT_SHORT = 0.6
WAIT_MID = 2.0
WAIT_LONG = 4.0
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行异常信息
# (如「存在已参保的人员,不允许重复增员!」)。
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
# ---------------------------------------------------------------
# 1. 元素定位辅助(DrissionPage)
@@ -213,6 +223,87 @@ def _click_close(page):
time.sleep(WAIT_SHORT)
# ---------------------------------------------------------------
# 3.5 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
# ---------------------------------------------------------------
def _extract_json_response(req):
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
try:
return req.response.json()
except Exception:
body = getattr(req.response, "body", None)
if isinstance(body, (dict, list)):
return body
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
"""监听「第二个下一步:真正导入内容」结果接口(getTmpDataPage.mc),捕获返回的全部异常。
第一个「下一步」为格式校验(不监听);点击第二个「下一步」真正导入内容后,
HR 系统会 POST getTmpDataPage.mc 返回导入结果:
- state="1" 表示接口正常;meg 为全局提示;
- datas[].imp_fixed_msg 非空表示该行存在异常(如「存在已参保的人员,不允许重复增员!」)。
本函数合并该接口全部(含分页/多次)响应中的异常(不逐行单独处理),供流程统一上报。
Returns:
dict: {
"captured": bool, # 是否捕获到解析接口响应
"state": str, # 接口 state(未捕获到为空串)
"meg": str, # 全局提示
"exceptions": [ # 全部异常明细
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
],
}
"""
result = {"captured": False, "state": "", "meg": "", "exceptions": []}
deadline = time.time() + timeout
last_hit = time.time()
while time.time() < deadline:
try:
remain = max(0.0, deadline - time.time())
req = page.listen.wait(timeout=min(0.5, remain))
except Exception as e:
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
break
if req is None:
# 0.5s 无新响应:若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
if result["captured"] and time.time() - last_hit >= 1.0:
break
continue
if not hasattr(req, "url"):
continue
if TMP_DATA_API_MARK not in (req.url or ""):
continue
resp = _extract_json_response(req)
if not isinstance(resp, dict):
continue
result["captured"] = True
last_hit = time.time()
state = str(resp.get("state", "")).strip()
if state:
result["state"] = state
meg = str(resp.get("meg", "") or "").strip()
if meg:
result["meg"] = meg
for item in resp.get("datas") or []:
item = item or {}
msg = str(item.get("imp_fixed_msg", "") or "").strip()
if msg:
result["exceptions"].append({
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
"message": msg,
})
return result
# ---------------------------------------------------------------
# 4. 对外入口(函数传参调用)
# ---------------------------------------------------------------
@@ -228,12 +319,18 @@ _IMPORT_TYPE_MAP = {
def _import_one(page, category, menu_label, file_path=None):
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
第一个「下一步」为格式校验(不做处理);第二个「下一步」真正导入内容时会请求
getTmpDataPage.mc,监听该接口捕获导入返回的全部异常;异常仅记录并上报,不中断导入流程。
Args:
page: 已登录的 ChromiumPage 实例。
category: 类别配置 dict。
menu_label: 菜单文案(增员导入/减员导入)。
file_path: 显式上传文件;不传则按类别文件夹取默认导入文件。
Returns:
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
Raises:
FileNotFoundError: 导入文件不存在。
"""
@@ -246,10 +343,39 @@ def _import_one(page, category, menu_label, file_path=None):
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
_choose_import_menu(page, menu_label)
_upload_file(page, file_path)
_click_next(page) # 第一步:下一步(进入解析)
_click_next(page) # 第二步:下一步(进入确认/完成)
_click_next(page) # 第一步:下一步(格式校验,不做处理)
# 第二步:点击「下一步」真正导入内容;同时监听 getTmpDataPage.mc 接口,捕获导入返回的全部异常
try:
page.listen.start(TMP_DATA_API_MARK)
except Exception as e:
logger.warning("启动 %s 接口监听失败:%s", TMP_DATA_API_MARK, e)
try:
_click_next(page)
import_result = _capture_import_exceptions(page)
finally:
try:
page.listen.stop()
except Exception:
pass
# 上报:全部异常逐条打日志
if import_result["exceptions"]:
logger.error("类别[%s] %s:导入返回 %d 条异常:",
category["name"], menu_label, len(import_result["exceptions"]))
for exc in import_result["exceptions"]:
logger.error(" - [%s/%s] 方案[%s]:%s",
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
elif import_result["captured"] and import_result["state"] != "1":
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
category["name"], menu_label, import_result["state"], import_result["meg"])
else:
logger.info("类别[%s] %s:导入正常,无异常", category["name"], menu_label)
_click_close(page) # 第三步:关闭
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
return import_result
def import_employee_change(import_type="增员", category_names=None, file_path=None):
@@ -263,7 +389,13 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
不传则按各类别文件夹取 商业保险增员导入.xlsx / 商业保险减员导入.xlsx。
Returns:
bool: 全部类别均成功返回 True;任一类别失败返回 False(失败已逐类打日志,不中断)。
dict: {
"success": bool, # 全部类别流程是否均完成
"import_type": str, # 菜单文案(增员导入/减员导入)
"categories": [str], # 类别名列表
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions)
"exception_count": int, # 上传表格返回的异常总条数
}
Raises:
ValueError: import_type 非法。
@@ -297,14 +429,29 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
_ensure_logged_in(page)
ok = 0
results = []
for category in categories:
try:
_import_one(page, category, menu_label, file_path)
res = _import_one(page, category, menu_label, file_path)
results.append(res)
ok += 1
except Exception:
except Exception as e:
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
logger.info("===== %s 全部完成(成功 %d/%d) =====", menu_label, ok, len(categories))
return ok == len(categories)
results.append({
"category": category["name"], "menu": menu_label,
"captured": False, "state": "", "meg": "", "exceptions": [],
"error": str(e),
})
exception_count = sum(len(r.get("exceptions") or []) for r in results)
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
menu_label, ok, len(categories), exception_count)
return {
"success": ok == len(categories),
"import_type": menu_label,
"categories": [c["name"] for c in categories],
"results": results,
"exception_count": exception_count,
}
finally:
try:
page.quit()
@@ -319,17 +466,46 @@ def main(category_names=None):
category_names: 类别名列表,空/None=全部类别。
Returns:
{"success": bool, "categories": [...], "details": {"增员导入": bool, "减员导入": bool}}
dict: {
"success": bool, # 增员+减员全部类别是否均完成
"categories": [str],
"details": {"增员导入": bool, "减员导入": bool},
"exceptions": [dict], # 上传表格返回的全部异常明细(合并增/减员)
"exception_count": int, # 异常总条数
}
"""
categories = [get_category(n)["name"] for n in category_names] if category_names \
else [c["name"] for c in CATEGORIES]
details = {}
exceptions = []
ok_all = True
for import_type in ("增员", "减员"):
success = import_employee_change(import_type, category_names)
details[_IMPORT_TYPE_MAP[import_type]] = success
ok_all = ok_all and success
return {"success": ok_all, "categories": categories, "details": details}
result = import_employee_change(import_type, category_names)
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
ok_all = ok_all and result["success"]
for r in result["results"]:
for exc in r.get("exceptions") or []:
exceptions.append({
"category": r["category"],
"menu": r["menu"],
"staff_code": exc["staff_code"],
"staff_name": exc["staff_name"],
"insurance_name": exc["insurance_name"],
"message": exc["message"],
})
if exceptions:
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
for exc in exceptions:
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
exc["category"], exc["staff_code"], exc["staff_name"],
exc["insurance_name"], exc["message"])
return {
"success": ok_all,
"categories": categories,
"details": details,
"exceptions": exceptions,
"exception_count": len(exceptions),
}
if __name__ == "__main__":
@@ -115,6 +115,11 @@ def category_output_backup(category):
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
def category_change_sheet_workbook(category):
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
def category_change_sheet_name(category):
"""类别「变更清单」sheet 名称。"""
return f"{category['change_sheet_prefix']}-{DATE_SHORT}"
@@ -48,7 +48,7 @@ if _root not in sys.path:
sys.path.insert(0, _root)
import pandas as pd
from openpyxl import load_workbook
from openpyxl import Workbook, load_workbook
from copy import copy
from app.utils.logger import get_logger, setup_logging # noqa: E402
@@ -70,6 +70,7 @@ from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
get_category,
category_target_file,
category_output_backup,
category_change_sheet_workbook,
category_change_sheet_name,
category_import_add_file,
category_import_sub_file,
@@ -923,6 +924,63 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
logger.info("备份新在参名单已保存:%s", output_backup)
# ============================================================
# 五点四、复制变更清单为独立工作簿
# ============================================================
def export_change_sheet_workbook(target_file, change_sheet_name, out_path):
"""将目标文件中「变更清单」sheet 单独复制一份,另存为独立工作簿。
保留公式与样式(C~L/O 等公式列随行保留,Excel/WPS 打开时自动重算),
供提交保险公司等场景直接使用,不改动原目标文件。
Args:
target_file: 目标文件路径(已含更新后的变更清单 sheet)。
change_sheet_name: 变更清单 sheet 名(如「37度-雇员变更清单8.26」)。
out_path: 独立工作簿保存路径。
Returns:
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
"""
if not os.path.isfile(target_file):
logger.warning("目标文件不存在,跳过复制变更清单工作簿:%s", target_file)
return False
wb = load_workbook(target_file)
if change_sheet_name not in wb.sheetnames:
logger.warning("工作簿中不存在变更清单 sheet [%s],跳过复制", 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(sheet:%s)", out_path, change_sheet_name)
return True
# ============================================================
# 五点五、生成增减员导入文件(阶段4:步骤3上传素材)
# ============================================================
@@ -1163,6 +1221,14 @@ def schedule_category(category):
name_corrections
)
# ---------- 阶段3.5:复制变更清单为独立工作簿 ----------
logger.info("复制变更清单为独立工作簿...")
export_change_sheet_workbook(
target_file,
change_sheet_name,
category_change_sheet_workbook(category),
)
# ---------- 阶段4:生成增减员导入文件(步骤3上传素材) ----------
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
@@ -50,6 +50,10 @@ logger = get_logger(__name__)
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
# N列 姓名在数据切片(B~O)内的 0-based 索引
NAME_COL = 12
# 源表统一格式规范(roster_export._merge_roster_files 输出):
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
@@ -103,9 +107,10 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
data = data[data.iloc[:, 0].notna()]
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 ----------
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
dept = data.iloc[:, 0].astype(str).str.strip()
region = data.iloc[:, 1].astype(str).str.strip()
name = data.iloc[:, NAME_COL].astype(str).str.strip()
include_dept = category.get("include_dept") or []
exclude_dept = category.get("exclude_dept") or []
mask = ~(region == EXCLUDE_REGION)
@@ -113,10 +118,13 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
mask &= dept.isin(include_dept)
if exclude_dept:
mask &= ~dept.isin(exclude_dept)
for kw in EXCLUDE_NAME_KEYWORDS:
mask &= ~name.str.contains(kw, na=False)
filtered = data[mask]
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」)",
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
category_name, len(data), len(filtered),
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION)
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
" / ".join(EXCLUDE_NAME_KEYWORDS))
if len(filtered) == 0:
logger.warning("类别[%s] 筛选后没有数据!", category_name)
+1
View File
@@ -186,6 +186,7 @@ def _set_glv(name, value):
| 考勤异常 `hr/attendance_abnormal` | `messages` | 元组列表 `[(search_keyword, text, verify_keyword), ...]` | 「37du钉钉推送」指令 |
| 考勤异常月度 `hr/attendance_abnormal_monthly` | `attendance_check_save_path` | 文件路径 | 流程后续处理 |
| 缺勤分析 `hr/absence_analysis` | `absence_save_path` | 文件路径 | 流程后续处理 |
| 雇主险增减员导入 `employer_insurance/add_sub_import` | `messages` | **块格式分组列表** `[{title, blocks, status}]`(有异常:异常明细 error;无异常:完成提示 success) | 「37du钉钉群机器人推送」指令 |
| 登录指令(oa/hr) | `login_state` | 布尔 | 流程判断是否继续 |
### 5.3 消息推送完整链路(请假脚本范例)
+280 -14
View File
@@ -7,7 +7,10 @@
执行增员/减员导入(复刻 aa.md 与 app 版 add_sub_import 的操作流程):
访问页面 -> 更多操作 -> 增员导入/减员导入 -> 上传文件 -> 下一步 -> 下一步 -> 关闭。
登录态复用「37duHR登录」写入的共享 hr_cookies.json(只读不补登)。
@Version: 1.0.0
@Version: 1.3.0
- v1.3.0:导入异常消息写入影刀全局变量 messages(块格式分组列表),供「37du钉钉群机器人推送」指令直接推送;无异常时写入完成提示。
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
设计说明(与 yingdao 下其它单文件版一致):
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
@@ -29,6 +32,7 @@
import json
import os
import time
import traceback
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
@@ -58,10 +62,25 @@ class _PrintLogger:
def error(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def exception(self, msg, *args, **kwargs):
print(msg % args if args else msg)
traceback.print_exc()
logger = _PrintLogger()
# ==================== 影刀全局变量(消息/结果写 glv,生成与发送解耦) ====================
# 约定见 yingdao/README.md 5.2:业务脚本只生成消息文本写全局变量,
# 发送一律由「37du钉钉群机器人推送」指令(yingdao/share/dingtalk_robot.py)完成。
def _set_glv(name, value):
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
# ==================== 路径 & 常量配置(与 app 版 config 一致) ====================
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
@@ -135,6 +154,13 @@ WAIT_SHORT = 0.6
WAIT_MID = 2.0
WAIT_LONG = 4.0
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行异常信息
# (如「存在已参保的人员,不允许重复增员!」)。
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
class LoginRequiredError(Exception):
"""打开页面被重定向到登录页(cookies 缺失或失效)。"""
@@ -282,8 +308,96 @@ def _click_close(page):
time.sleep(WAIT_SHORT)
# ---------------------------------------------------------------
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
# ---------------------------------------------------------------
def _extract_json_response(req):
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
try:
return req.response.json()
except Exception:
body = getattr(req.response, "body", None)
if isinstance(body, (dict, list)):
return body
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
"""监听「第二个下一步:真正导入内容」结果接口(getTmpDataPage.mc),捕获返回的全部异常。
第一个「下一步」为格式校验(不监听);点击第二个「下一步」真正导入内容后,
HR 系统会 POST getTmpDataPage.mc 返回导入结果:
- state="1" 表示接口正常;meg 为全局提示;
- datas[].imp_fixed_msg 非空表示该行存在异常(如「存在已参保的人员,不允许重复增员!」)。
本函数合并该接口全部(含分页/多次)响应中的异常(不逐行单独处理),供流程统一上报。
Returns:
dict: {
"captured": bool, # 是否捕获到解析接口响应
"state": str, # 接口 state(未捕获到为空串)
"meg": str, # 全局提示
"exceptions": [ # 全部异常明细
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
],
}
"""
result = {"captured": False, "state": "", "meg": "", "exceptions": []}
deadline = time.time() + timeout
last_hit = time.time()
while time.time() < deadline:
try:
remain = max(0.0, deadline - time.time())
req = page.listen.wait(timeout=min(0.5, remain))
except Exception as e:
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
break
if req is None:
# 0.5s 无新响应:若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
if result["captured"] and time.time() - last_hit >= 1.0:
break
continue
if not hasattr(req, "url"):
continue
if TMP_DATA_API_MARK not in (req.url or ""):
continue
resp = _extract_json_response(req)
if not isinstance(resp, dict):
continue
result["captured"] = True
last_hit = time.time()
state = str(resp.get("state", "")).strip()
if state:
result["state"] = state
meg = str(resp.get("meg", "") or "").strip()
if meg:
result["meg"] = meg
for item in resp.get("datas") or []:
item = item or {}
msg = str(item.get("imp_fixed_msg", "") or "").strip()
if msg:
result["exceptions"].append({
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
"message": msg,
})
return result
def _import_one(page, category, menu_label, file_path=None):
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。"""
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
第一个「下一步」为格式校验(不做处理);第二个「下一步」真正导入内容时会请求
getTmpDataPage.mc,监听该接口捕获导入返回的全部异常;异常仅记录并上报,不中断导入流程。
Returns:
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
"""
file_path = file_path or (
category_import_add_file(category) if menu_label == MENU_ADD
else category_import_sub_file(category))
@@ -293,10 +407,98 @@ def _import_one(page, category, menu_label, file_path=None):
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
_choose_import_menu(page, menu_label)
_upload_file(page, file_path)
_click_next(page) # 第一步:下一步(进入解析)
_click_next(page) # 第二步:下一步(进入确认/完成)
_click_next(page) # 第一步:下一步(格式校验,不做处理)
# 第二步:点击「下一步」真正导入内容;同时监听 getTmpDataPage.mc 接口,捕获导入返回的全部异常
try:
page.listen.start(TMP_DATA_API_MARK)
except Exception as e:
logger.warning("启动 %s 接口监听失败:%s", TMP_DATA_API_MARK, e)
try:
_click_next(page)
import_result = _capture_import_exceptions(page)
finally:
try:
page.listen.stop()
except Exception:
pass
# 上报:全部异常逐条打日志
if import_result["exceptions"]:
logger.error("类别[%s] %s:导入返回 %d 条异常:",
category["name"], menu_label, len(import_result["exceptions"]))
for exc in import_result["exceptions"]:
logger.error(" - [%s/%s] 方案[%s]:%s",
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
elif import_result["captured"] and import_result["state"] != "1":
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
category["name"], menu_label, import_result["state"], import_result["meg"])
else:
logger.info("类别[%s] %s:导入正常,无异常", category["name"], menu_label)
_click_close(page) # 第三步:关闭
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
return import_result
# ==================== 钉钉群消息生成(写入全局变量,由「37du钉钉群机器人推送」指令发送) ====================
def _build_group_messages(import_type, categories, results, exception_count):
"""构建钉钉群机器人推送消息(块格式分组列表 [{title, blocks, status}])。
有异常:每个「类别 + 导入类型」一组,blocks 为该组全部异常明细(红色 error);
无异常:生成一条完成提示(绿色 success)。格式兼容 yingdao/share/dingtalk_robot.py 的 main()。
results 每项可带 "menu" 字段覆盖分组标题(main() 合并增/减员时使用)。
"""
items = []
for r in results:
name = r.get("category") or ""
menu = r.get("menu") or import_type
excs = r.get("exceptions") or []
if not excs:
continue
blocks = []
for exc in excs:
blocks.append(
"**🔹 {} / {}**\n\n"
"> 工号:{}\n\n"
"> 姓名:{}\n\n"
"> 方案:{}\n\n"
"> 异常:{}".format(
name,
exc.get("staff_name", ""),
exc.get("staff_code", ""),
exc.get("staff_name", ""),
exc.get("insurance_name", "") or "-",
exc.get("message", ""),
)
)
items.append({"title": f"【雇主险{menu}】异常", "blocks": blocks, "status": "error"})
if not items:
blocks = []
for r in results:
name = r.get("category") or ""
menu = r.get("menu") or import_type
blocks.append("**🔹 {}**\n\n> {}正常,无异常".format(name, menu))
if not blocks:
blocks = ["**🔹 全部类别**\n\n> {}正常,无异常".format(import_type)]
items.append({
"title": f"【雇主险{import_type}】完成",
"blocks": blocks,
"status": "success",
})
return items
def _write_group_messages_glv(import_type, categories, results, exception_count):
"""把增/减员导入结果写入影刀全局变量 messages,供「37du钉钉群机器人推送」指令读取推送。"""
messages = _build_group_messages(import_type, categories, results, exception_count)
_set_glv("messages", messages)
if exception_count:
logger.error("异常消息已写入全局变量 messages:共 %d 条异常(由「37du钉钉群机器人推送」指令发送)",
exception_count)
else:
logger.info("完成消息已写入全局变量 messages(由「37du钉钉群机器人推送」指令发送)")
# ==================== 对外入口(函数传参调用,支持多类别) ====================
@@ -320,7 +522,13 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
不传则按类别文件夹取 schedule 步骤生成的 商业保险增员/减员导入.xlsx。
Returns:
bool: 全部类别均成功返回 True;任一类别失败返回 False(失败已逐类打日志)。
dict: {
"success": bool, # 全部类别流程是否均完成
"import_type": str, # 菜单文案(增员导入/减员导入)
"categories": [str], # 类别名列表
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions)
"exception_count": int, # 上传表格返回的异常总条数
}
Raises:
LoginRequiredError: 共享 HR 登录态缺失/失效,需先运行「37duHR登录」指令。
@@ -346,14 +554,38 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
_ensure_logged_in(page)
ok = 0
results = []
for category in categories:
try:
_import_one(page, category, menu_label, file_path)
res = dict(_import_one(page, category, menu_label, file_path))
res["category"] = category["name"]
res["menu"] = menu_label
results.append(res)
ok += 1
except Exception:
except Exception as e:
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
logger.info("===== %s 全部完成(成功 %d/%d) =====", menu_label, ok, len(categories))
return ok == len(categories)
results.append({
"category": category["name"], "menu": menu_label,
"captured": False, "state": "", "meg": "", "exceptions": [],
"error": str(e),
})
exception_count = sum(len(r.get("exceptions") or []) for r in results)
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
menu_label, ok, len(categories), exception_count)
# 异常/完成消息写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
_write_group_messages_glv(
menu_label,
[c["name"] for c in categories],
results,
exception_count,
)
return {
"success": ok == len(categories),
"import_type": menu_label,
"categories": [c["name"] for c in categories],
"results": results,
"exception_count": exception_count,
}
finally:
try:
page.quit()
@@ -368,18 +600,52 @@ def main(category_names=None):
category_names: 类别名列表,空/None=全部类别。
Returns:
{"success": bool, "categories": [...], "details": {"增员导入": bool, "减员导入": bool}}
dict: {
"success": bool, # 增员+减员全部类别是否均完成
"categories": [str],
"details": {"增员导入": bool, "减员导入": bool},
"exceptions": [dict], # 上传表格返回的全部异常明细(合并增/减员)
"exception_count": int, # 异常总条数
}
"""
load_dotenv()
categories = [get_category(n)["name"] for n in category_names] if category_names \
else [c["name"] for c in CATEGORIES]
details = {}
exceptions = []
all_results = []
ok_all = True
for import_type in ("增员", "减员"):
success = import_employee_change(import_type, category_names)
details[_IMPORT_TYPE_MAP[import_type]] = success
ok_all = ok_all and success
return {"success": ok_all, "categories": categories, "details": details}
result = import_employee_change(import_type, category_names)
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
ok_all = ok_all and result["success"]
for r in result["results"]:
r["menu"] = r.get("menu") or _IMPORT_TYPE_MAP[import_type]
all_results.append(r)
for exc in r.get("exceptions") or []:
exceptions.append({
"category": r.get("category", ""),
"menu": r.get("menu", ""),
"staff_code": exc["staff_code"],
"staff_name": exc["staff_name"],
"insurance_name": exc["insurance_name"],
"message": exc["message"],
})
if exceptions:
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
for exc in exceptions:
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
exc["category"], exc["staff_code"], exc["staff_name"],
exc["insurance_name"], exc["message"])
# 合并增/减员结果,覆盖写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
_write_group_messages_glv("增员/减员", categories, all_results, len(exceptions))
return {
"success": ok_all,
"categories": categories,
"details": details,
"exceptions": exceptions,
"exception_count": len(exceptions),
}
if __name__ == "__main__":
@@ -20,6 +20,7 @@
import numbers
import os
import re
import traceback
from collections import defaultdict
from copy import copy
from datetime import datetime, date
@@ -28,7 +29,7 @@ from datetime import datetime, date
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
try:
import pandas as pd
from openpyxl import load_workbook
from openpyxl import Workbook, load_workbook
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
@@ -52,6 +53,10 @@ class _PrintLogger:
def error(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def exception(self, msg, *args, **kwargs):
print(msg % args if args else msg)
traceback.print_exc()
logger = _PrintLogger()
@@ -186,6 +191,11 @@ def category_output_backup(category):
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
def category_change_sheet_workbook(category):
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
def category_change_sheet_name(category):
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
return f"{category['change_sheet_prefix']}{DATE_SHORT}"
@@ -1082,6 +1092,63 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
logger.info("备份新在参名单已保存:%s", output_backup)
# ============================================================
# 五点四、复制变更清单为独立工作簿
# ============================================================
def export_change_sheet_workbook(target_file, change_sheet_name, out_path):
"""将目标文件中「变更清单」sheet 单独复制一份,另存为独立工作簿。
保留公式与样式(C~L/O 等公式列随行保留,Excel/WPS 打开时自动重算),
供提交保险公司等场景直接使用,不改动原目标文件。
Args:
target_file: 目标文件路径(已含更新后的变更清单 sheet)。
change_sheet_name: 变更清单 sheet 名(如「37度-雇员变更清单8.26」)。
out_path: 独立工作簿保存路径。
Returns:
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
"""
if not os.path.isfile(target_file):
logger.warning("目标文件不存在,跳过复制变更清单工作簿:%s", target_file)
return False
wb = load_workbook(target_file)
if change_sheet_name not in wb.sheetnames:
logger.warning("工作簿中不存在变更清单 sheet [%s],跳过复制", 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(sheet:%s)", out_path, change_sheet_name)
return True
# ============================================================
# 五点五、生成增员/减员导入文件(步骤3:HR「待增减人员」页面上传素材)
# ============================================================
@@ -1322,6 +1389,14 @@ def schedule_category(category):
name_corrections
)
# ---------- 阶段3.5:复制变更清单为独立工作簿 ----------
logger.info("复制变更清单为独立工作簿...")
export_change_sheet_workbook(
target_file,
change_sheet_name,
category_change_sheet_workbook(category),
)
# ---------- 阶段4:生成增员/减员导入文件(步骤3:HR 上传素材) ----------
logger.info("生成增员/减员导入文件...")
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
+16 -3
View File
@@ -30,6 +30,7 @@
import numbers
import os
import re
import traceback
from datetime import datetime
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
@@ -60,6 +61,10 @@ class _PrintLogger:
def error(self, msg, *args, **kwargs):
print(msg % args if args else msg)
def exception(self, msg, *args, **kwargs):
print(msg % args if args else msg)
traceback.print_exc()
logger = _PrintLogger()
@@ -186,6 +191,10 @@ def find_latest_target(folder):
# 过滤规则(与 aa.md 宏一致)
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
# N列 姓名在数据切片(B~O)内的 0-based 索引
NAME_COL = 12
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
@@ -264,9 +273,10 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
data = data[data.iloc[:, 0].notna()]
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 ----------
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
dept = data.iloc[:, 0].astype(str).str.strip()
region = data.iloc[:, 1].astype(str).str.strip()
name = data.iloc[:, NAME_COL].astype(str).str.strip()
include_dept = category.get("include_dept") or []
exclude_dept = category.get("exclude_dept") or []
mask = ~(region == EXCLUDE_REGION)
@@ -274,10 +284,13 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
mask &= dept.isin(include_dept)
if exclude_dept:
mask &= ~dept.isin(exclude_dept)
for kw in EXCLUDE_NAME_KEYWORDS:
mask &= ~name.str.contains(kw, na=False)
filtered = data[mask]
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」)",
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
category_name, len(data), len(filtered),
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION)
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
" / ".join(EXCLUDE_NAME_KEYWORDS))
if len(filtered) == 0:
logger.warning("类别[%s] 筛选后没有数据!", category_name)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long