feat: 新增社保告知书制作下发全流程模块
1. 新增参保/停保告知书生成模块,支持按模板批量生成Word+PDF 2. 新增社保转移告知书独立数据源处理逻辑 3. 新增OA工作沟通推送数据自动构造能力 4. 重构雇主险模块,拆分变更清单导出为独立文件 5. 新增花名册查询工具模块,支持店长/人事批量查询 6. 更新项目文档与README说明
This commit is contained in:
@@ -35,6 +35,8 @@ yingdao/
|
||||
│ ├── roster_filter.py # 步骤2:筛选复制(源表缺失时复用「37du花名册导出」)
|
||||
│ ├── employer_insurance_schedule.py # 步骤2:调度(生成增员/减员导入文件)
|
||||
│ └── add_sub_import.py # 步骤3:增减员导入(HR「待增减人员」页面上传)
|
||||
├── notice/ # 告知书制作与下发(单文件自包含)
|
||||
│ └── notice_mail_merge.py # 参保/停保名单 → 按模板批量生成告知书 Word+PDF
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
@@ -107,6 +109,28 @@ yingdao/
|
||||
- OCR 视觉方案:查找钉钉窗口 → 多策略激活前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框 → 粘贴 → 回车
|
||||
- 依赖:`pyautogui pywin32 pyperclip psutil Pillow numpy rapidocr-onnxruntime`
|
||||
|
||||
### 4.6 notice_mail_merge.py(「告知书制作与下发」)
|
||||
|
||||
- 独立模块(`yingdao/notice/`,对应 app 版 `app/service/hrbp/oa/social_notice/`),单文件自包含,不 import 共享模块
|
||||
- 读取 `D:\资料\人资\告知书制作与下发` 下包含「参保与停保名单」的 xlsx(表头第 3 行,主表字段到「费用」列为止 49 列),筛选「参保名单」sheet
|
||||
- 按三类模板规则逐人生成 Word 告知书并转 PDF(WPS 文字 COM):
|
||||
- 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
|
||||
- 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
|
||||
- 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
|
||||
- 公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月
|
||||
- 入口:`main()`(生成当月全部 + 构造 OA 工作沟通数据)、`generate_notices(excel_path, output_dir, ym)`(函数传参)、`build_work_communication_data(excel_path, output_dir, ym, roster_path)`(数据构造)
|
||||
- 输出:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份;
|
||||
文件名 = `二级部门_四级部门_告知书类型.docx/pdf`,同一部门内多人逐页排列
|
||||
- 环境变量:`notice_base_dir`(默认 `D:\资料\人资\告知书制作与下发`)、`notice_output_dir`(默认 `{notice_base_dir}\输出`)
|
||||
- 输出目录写入影刀全局变量 `notice_output_dir`;异常时写 `notice_error`
|
||||
- **OA 工作沟通数据构造**:根据命中员工工号查询店长/人事(花名册 `{notice_base_dir}\员工花名册.xlsx`,石桥铺会馆人事固定 37001302 梁敏),构造 2 条推送数据:
|
||||
1. 员工参与社会保险 + 参保异常合并一条;
|
||||
2. 社保转移单独一条;
|
||||
每条含 `subject/content(HTML)/attachment_paths(仅PDF)/receivers(店长+人事工号去重)/category`,
|
||||
正文月份按名单年月动态替换,关键词(告知书名、期限日期)自动标红;写入影刀全局变量 `oa_work_communications`(列表),供「OA工作沟通推送」指令逐条循环发送(`yingdao/oa/work_communication.py`)
|
||||
- 占位符仅允许纯变量(如 `{{姓名}}`、`{{下月}}`、`{{一次性扣款}}`),脚本自动兼容旧写法(`{{当前月+1}}`/`{{费用*2}}`)
|
||||
- 依赖:`openpyxl python-docx pywin32`
|
||||
|
||||
## 5. 模块通信(弱耦合:文件 + 全局变量)
|
||||
|
||||
### 5.1 登录态通信(文件级,登录一次全局复用)
|
||||
@@ -187,6 +211,8 @@ def _set_glv(name, value):
|
||||
| 考勤异常月度 `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钉钉群机器人推送」指令 |
|
||||
| 告知书制作与下发 `notice/notice_mail_merge` | `notice_output_dir` | 告知书输出目录路径(当月目录) | 流程后续处理 |
|
||||
| 告知书制作与下发 `notice/notice_mail_merge` | `oa_work_communications` | **工作沟通推送数据列表**(每条含 subject/content/attachment_paths/receivers/category) | 「OA工作沟通推送」指令逐条循环发送 |
|
||||
| 登录指令(oa/hr) | `login_state` | 布尔 | 流程判断是否继续 |
|
||||
|
||||
### 5.3 消息推送完整链路(请假脚本范例)
|
||||
@@ -263,3 +289,4 @@ build_session(纯 SessionPage,不开浏览器)
|
||||
| HR 滑块验证码 | 另加 `opencv-python numpy Pillow` |
|
||||
| OCR 钉钉单聊推送 | `pyautogui pywin32 pyperclip psutil Pillow numpy rapidocr-onnxruntime` |
|
||||
| 钉钉群机器人推送 | 无(仅标准库) |
|
||||
| 告知书制作与下发 | `openpyxl python-docx pywin32` |
|
||||
|
||||
@@ -1092,63 +1092,6 @@ 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「待增减人员」页面上传素材)
|
||||
# ============================================================
|
||||
@@ -1389,14 +1332,6 @@ 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)
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统「步骤2.5:导出变更清单独立工作簿」(影刀版,单文件自包含)
|
||||
前置:先运行 employer_insurance_schedule.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选,与 employer_insurance_schedule.py 一致):
|
||||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
|
||||
运行:直接执行本文件即可处理全部类别;仅处理部分类别时以列表传参调用
|
||||
main(category_names=['湖畔酒店'])
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from copy import copy
|
||||
from datetime import datetime, date
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from openpyxl import Workbook, load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,与 employer_insurance_schedule.py 一致) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
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()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 employer_insurance_schedule.py 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
# 变更清单 sheet 名沿用历史模板命名:无横线、月/日不补前导零(如 8.19 / 8.1)
|
||||
DATE_SHORT = f"{datetime.now().month}.{datetime.now().day}"
|
||||
|
||||
# ---------- 四大类别(与 employer_insurance_schedule.py 的 CATEGORIES 一致) ----------
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(与 employer_insurance_schedule.py 一致) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。
|
||||
|
||||
Args:
|
||||
filename: 目标文件名,如「三十七度-雇主险变更记录-2026.08.20.xlsx」/
|
||||
「水庄餐饮-雇主险变更记录-7.23.xlsx」
|
||||
|
||||
Returns:
|
||||
date 对象;无法解析返回 None
|
||||
"""
|
||||
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(datetime.now().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
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_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
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}"
|
||||
|
||||
|
||||
# ==================== 步骤2.5:导出变更清单独立工作簿 ====================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_names: list[str] = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance_schedule.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口(与调度步骤保持一致,默认处理三十七度)
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
@@ -0,0 +1,936 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: notice_mail_merge.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发(影刀版,单文件自包含)——读取《{YYYYMM}参保与停保名单.xlsx》
|
||||
中「参保名单」sheet(表头第3行),按三类模板规则筛选当月人员,逐人生成
|
||||
Word 告知书并转 PDF:
|
||||
- 模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
|
||||
- 模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
|
||||
- 模板3 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
|
||||
公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月。
|
||||
输出命名:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份,
|
||||
文件名 = 二级部门_四级部门_告知书类型.docx/pdf,同一部门内多人逐页排列。
|
||||
OA 工作沟通推送:根据命中员工工号查询店长/人事,构造 2 条推送数据
|
||||
(员工参与社会保险+参保异常合并一条、社保转移单独一条),
|
||||
写入影刀全局变量 messages(列表),供「OA工作沟通推送」指令逐条调用。
|
||||
业务判定及占位符约定见 aa.md、docs/参保成功及异常告知书、docs/社保转移告知书。
|
||||
@Version: 1.1.0
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 不 import 任何共享指令模块、不做 sys.path 注入、不做目录向上查找。
|
||||
- 占位符约定:模板中仅允许纯变量占位符(如 {{姓名}}、{{下月}}、{{一次性扣款}}),
|
||||
不支持 {{当前月+1}} / {{费用*2}} 这类带表达式的写法(脚本会自动兼容旧写法)。
|
||||
- PDF 转换走 WPS 文字 COM(Kwps.Application),兼容未安装 MS Word 的环境;
|
||||
另存/导出失败自动重试 3 次(AGENTS.md 全局重试约定)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install openpyxl python-docx pywin32
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
notice_base_dir = 告知书目录(默认 D:\\资料\\人资\\告知书制作与下发)
|
||||
notice_output_dir = 输出根目录(默认 {notice_base_dir}\\输出)
|
||||
|
||||
运行:直接执行本文件即可生成当月全部三类告知书;
|
||||
也可用函数传参调用 generate_notices(excel_path=..., output_dir=..., ym=(2026,8))
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import random
|
||||
import functools
|
||||
import traceback
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import openpyxl
|
||||
from docx import Document
|
||||
from docx.enum.text import WD_BREAK
|
||||
from docx.oxml.ns import qn
|
||||
import win32com.client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install openpyxl python-docx pywin32\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
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()
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局重试3次,AGENTS.md) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
def decorator(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
logger.error("%s 连续 %d 次尝试失败: %s", func.__name__, max_attempts, e)
|
||||
break
|
||||
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== 影刀全局变量(写入 glv[name]=value) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
BASE_DIR = os.getenv("notice_base_dir") or r"D:\资料\人资\告知书制作与下发"
|
||||
OUTPUT_ROOT = os.getenv("notice_output_dir") or os.path.join(BASE_DIR, "输出")
|
||||
|
||||
# 模板清单:folder=输出子目录名;status/type=该类告知书的办理状态与参保类型过滤条件
|
||||
TEMPLATES = {
|
||||
"新参保": {
|
||||
"file": os.path.join(BASE_DIR, "参保状态告知", "员工参与社会保险告知书模板.docx"),
|
||||
"folder": "员工参与社会保险告知书",
|
||||
"status": "已参",
|
||||
"type": "新参保",
|
||||
},
|
||||
"参保异常": {
|
||||
"file": os.path.join(BASE_DIR, "参保状态告知", "参保异常告知模板.docx"),
|
||||
"folder": "参保异常告知书",
|
||||
"status": "参保失败",
|
||||
"type": "新参保",
|
||||
},
|
||||
"社保转移": {
|
||||
"file": os.path.join(BASE_DIR, "社保转移告知书", "社保转移告知模板.docx"),
|
||||
"folder": "社保转移告知书",
|
||||
"status": "已参",
|
||||
"type": "转移参保",
|
||||
},
|
||||
}
|
||||
|
||||
EXCEL_KEYWORD = "参保与停保名单" # 表格文件名关键字
|
||||
SHEET_KEYWORD = "参保名单" # sheet 名关键字
|
||||
HEADER_ROW = 3 # 表头所在行
|
||||
MAIN_COLS = 49 # 主表字段到「费用」列为止(AX 为空列,其后为粘贴重复区)
|
||||
EXCLUDE_TYPE_KEYWORDS = ("职能",) # 人员类型排除关键字
|
||||
DEPT_KEYWORDS = ("经营中心", "石桥铺会馆") # 二级部门需包含的关键字(任一命中即可)
|
||||
RETRY_TIMES = 3 # 全局重试次数
|
||||
|
||||
# 社保转移数据源(社保变更人员名单):替代「参保与停保名单」中的转移参保
|
||||
TRANSFER_EXCEL_KEYWORD = "社保变更人员名单" # 数据源文件名关键字
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
|
||||
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
|
||||
TRANSFER_CHANGE_COL = "是否变更" # 筛选列
|
||||
TRANSFER_CHANGE_VALUE = "是" # 筛选值
|
||||
# 列名映射:社保变更名单列名 -> 标准列名(模板占位符依赖标准列名)
|
||||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||||
|
||||
# ---- OA 工作沟通推送数据构造 ----
|
||||
ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx" # 员工花名册路径
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]} # 二级部门 -> 固定人事工号(梁敏)
|
||||
OA_GLV_NAME = "messages" # 影刀全局变量名(列表:工作沟通推送数据)
|
||||
|
||||
# 测试模式:True=推送接收人统一覆盖为测试接收人(不推真实店长/人事);正式运行请改为 False
|
||||
TEST_MODE = True
|
||||
TEST_RECEIVER = ["37036361", "37001166"] # 测试接收人(多人):37036361 夏一平 + 37001166
|
||||
|
||||
# 工作沟通推送配置:rule_keys=参与该条推送的模板名;subject/content 支持 {y}/{m} 动态月份替换
|
||||
OA_MESSAGE_TEMPLATES = (
|
||||
{
|
||||
"key": "参保类",
|
||||
"rule_keys": ("新参保", "参保异常"),
|
||||
"subject": "{y}年{m}月员工参保结果告知书",
|
||||
"content": (
|
||||
"各位店长、人行伙伴:\n"
|
||||
"重庆区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,\n"
|
||||
"现需涉及的门店对员工本人进行传达告知(下载并签收);其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
|
||||
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报表至人资周卫,以便下月再参;\n"
|
||||
"请门店在{m}月26日前完成签署并将《签收回执》传递人行,"
|
||||
"人行跟进本经营中心所有人员的告知书回收,{m}月28日前传递人资周卫。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"key": "社保转移",
|
||||
"rule_keys": ("社保转移",),
|
||||
"subject": "{y}年{m}月员工参保单位变更确认",
|
||||
"content": (
|
||||
"各位领导/同事:\n"
|
||||
"根据《社保执行细则》,本月人力资源部已输出“工作与参保单位不一致”的人员,"
|
||||
"现需要涉及门店/经营中心与员工本人进行转移确认(下载变更告知书、打印并与员工清晰讲解),"
|
||||
"在{m}月25日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月27日内传递人资周卫处。\n"
|
||||
"特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。"
|
||||
"员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
)
|
||||
|
||||
# 正文关键词高亮(红色):keyword 支持 {m} 月份占位符,format 后替换为 <span style="color:#c0392b">
|
||||
OA_HIGHLIGHTS = {
|
||||
"参保类": [
|
||||
("《参保成功告知书》", "#c0392b"),
|
||||
("《参保异常告知书》", "#c0392b"),
|
||||
("《签收回执》", "#c0392b"),
|
||||
("{m}月26日前", "#c0392b"),
|
||||
("{m}月28日前", "#c0392b"),
|
||||
],
|
||||
"社保转移": [
|
||||
("《社保缴纳确认单》", "#c0392b"),
|
||||
("{m}月25日下班前", "#c0392b"),
|
||||
("27日内", "#c0392b"),
|
||||
("特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。", "#c0392b"),
|
||||
],
|
||||
}
|
||||
|
||||
# 旧占位符 → 新占位符(模板兼容旧写法,自动归一化)
|
||||
LEGACY_PLACEHOLDERS = {
|
||||
"{{当前月15日}}": "{{当月15日}}",
|
||||
"{{重庆}}": "{{区域}}",
|
||||
"{{当前月+1}}": "{{下月}}",
|
||||
"{{费用*2}}": "{{一次性扣款}}",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 基础工具 ====================
|
||||
def _fmt_num(value) -> str:
|
||||
"""金额格式化:509 -> '509';467.42 -> '467.42';#N/A 等错误值返回 ''。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
if s in ("", "#N/A", "#REF!", "#VALUE!", "NA", "None"):
|
||||
return ""
|
||||
try:
|
||||
f = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return s
|
||||
if f == int(f):
|
||||
return str(int(f))
|
||||
return ("%.2f" % f).rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def _month_of(value):
|
||||
"""把单元格值解析为 (年, 月);无法解析返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return (value.year, value.month)
|
||||
if isinstance(value, str):
|
||||
m = re.search(r"(20\d{2})[年\-/\.]?(\d{1,2})", value.strip())
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)))
|
||||
return None
|
||||
|
||||
|
||||
def _extract_ym(filename: str):
|
||||
"""从文件名解析 YYYYMM;失败返回当月。"""
|
||||
m = re.search(r"(20\d{2})(\d{2})", filename)
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)))
|
||||
now = datetime.now()
|
||||
return (now.year, now.month)
|
||||
|
||||
|
||||
def _find_excel(dir_path: str) -> str:
|
||||
"""在目录内查找包含「参保与停保名单」的 xlsx 文件。"""
|
||||
if not os.path.isdir(dir_path):
|
||||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||||
for name in os.listdir(dir_path):
|
||||
if EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||||
return os.path.join(dir_path, name)
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{EXCEL_KEYWORD}」的 xlsx 文件")
|
||||
|
||||
|
||||
def _find_transfer_excel(dir_path: str = None) -> str:
|
||||
"""在目录内查找包含「社保变更人员名单」的 xlsx 文件(社保转移数据源)。"""
|
||||
dir_path = dir_path or BASE_DIR
|
||||
if not os.path.isdir(dir_path):
|
||||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||||
for name in os.listdir(dir_path):
|
||||
if TRANSFER_EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||||
return os.path.join(dir_path, name)
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{TRANSFER_EXCEL_KEYWORD}」的 xlsx 文件")
|
||||
|
||||
|
||||
def _read_insurance_records(excel_path: str) -> list:
|
||||
"""读取「参保名单」sheet,返回人员记录列表(dict,key=表头字段名)。"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheet = None
|
||||
for ws in wb.worksheets:
|
||||
if SHEET_KEYWORD in ws.title:
|
||||
sheet = ws
|
||||
break
|
||||
if sheet is None:
|
||||
raise ValueError(f"工作簿 {excel_path} 中未找到包含「{SHEET_KEYWORD}」的 sheet")
|
||||
|
||||
# 表头第 HEADER_ROW 行,只取主表字段(到「费用」列为止)
|
||||
header = [c.value for c in next(sheet.iter_rows(min_row=HEADER_ROW, max_row=HEADER_ROW, max_col=MAIN_COLS))]
|
||||
col_names = {i: str(h).strip() for i, h in enumerate(header) if h}
|
||||
if "姓名" not in col_names.values() or "办理状态" not in col_names.values():
|
||||
raise ValueError(f"「{sheet.title}」第{HEADER_ROW}行未解析到标准表头(缺少姓名/办理状态等)")
|
||||
|
||||
records = []
|
||||
for row in sheet.iter_rows(min_row=HEADER_ROW + 1, max_row=sheet.max_row, max_col=MAIN_COLS):
|
||||
values = [c.value for c in row]
|
||||
if all(v is None for v in values):
|
||||
continue
|
||||
rec = {name: values[i] for i, name in col_names.items() if i < len(values)}
|
||||
if rec.get("姓名") is not None:
|
||||
records.append(rec)
|
||||
return records
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _match_rule(rec: dict, status: str, ins_type: str, ym: tuple) -> bool:
|
||||
"""按模板规则 + 公共过滤条件判断记录是否命中。"""
|
||||
if str(rec.get("办理状态") or "").strip() != status:
|
||||
return False
|
||||
if str(rec.get("参保类型") or "").strip() != ins_type:
|
||||
return False
|
||||
ptype = str(rec.get("人员类型") or "").strip()
|
||||
if any(kw in ptype for kw in EXCLUDE_TYPE_KEYWORDS):
|
||||
return False
|
||||
dept2 = str(rec.get("二级部门") or "")
|
||||
if not any(kw in dept2 for kw in DEPT_KEYWORDS):
|
||||
return False
|
||||
return _month_of(rec.get("办理时间")) == ym
|
||||
|
||||
|
||||
def _build_placeholders(rec: dict, ym: tuple) -> dict:
|
||||
"""根据记录与目标月份计算占位符替换值。"""
|
||||
y, m = ym
|
||||
next_y, next_m = (y, m + 1) if m < 12 else (y + 1, 1)
|
||||
today = datetime.now()
|
||||
|
||||
fee_txt = _fmt_num(rec.get("费用"))
|
||||
try:
|
||||
fee_num = float(rec.get("费用"))
|
||||
once_txt = _fmt_num(fee_num * 2)
|
||||
except (TypeError, ValueError):
|
||||
once_txt = ""
|
||||
|
||||
return {
|
||||
"{{姓名}}": str(rec.get("姓名") or ""),
|
||||
"{{四级部门}}": str(rec.get("四级部门") or ""),
|
||||
"{{参保单位全称}}": str(rec.get("参保单位全称") or ""),
|
||||
"{{区域}}": str(rec.get("区域") or ""),
|
||||
"{{费用}}": fee_txt,
|
||||
"{{备注}}": str(rec.get("备注") or ""),
|
||||
"{{一次性扣款}}": once_txt,
|
||||
# 模板文案已自带「月」字(如「{{当前月}} 月工资」「{{下月}}月15日」),故取纯数字
|
||||
"{{当前月}}": f"{m}",
|
||||
"{{下月}}": f"{next_m}",
|
||||
"{{当月15日}}": f"{m}月15日",
|
||||
"{{制作日年份}}": str(today.year),
|
||||
"{{制作日月份}}": str(today.month),
|
||||
"{{制作日天}}": str(today.day),
|
||||
}
|
||||
|
||||
|
||||
# ==================== Word 占位符替换(兼容占位符被 Word 拆成多个 run) ====================
|
||||
def _replace_in_paragraph(p, mapping: dict) -> None:
|
||||
runs = p.runs
|
||||
if not runs:
|
||||
return
|
||||
full = "".join(r.text for r in runs)
|
||||
if not any(k in full for k in mapping):
|
||||
return
|
||||
|
||||
# 1) 替换单个 run 内完整的占位符(保留 run 原格式)
|
||||
for r in runs:
|
||||
t = r.text
|
||||
for k, v in mapping.items():
|
||||
if k in t:
|
||||
t = t.replace(k, v)
|
||||
r.text = t
|
||||
|
||||
# 2) 处理跨 run 占位符(合并所在 run 区间,格式取起始 run)
|
||||
for k, v in mapping.items():
|
||||
if k in full and not any(k in r.text for r in runs):
|
||||
for i in range(len(runs)):
|
||||
rt = runs[i].text
|
||||
if k in rt:
|
||||
continue
|
||||
start = None
|
||||
for L in range(min(len(rt), len(k)), 0, -1):
|
||||
if rt[-L:] == k[:L]:
|
||||
start = len(rt) - L
|
||||
break
|
||||
if start is None:
|
||||
continue
|
||||
acc = rt
|
||||
j = i
|
||||
while k not in acc and j + 1 < len(runs):
|
||||
j += 1
|
||||
acc += runs[j].text
|
||||
if k in acc:
|
||||
runs[i].text = acc.replace(k, v)
|
||||
for x in range(i + 1, j + 1):
|
||||
runs[x].text = ""
|
||||
break
|
||||
|
||||
|
||||
def _fill_doc(template_path: str, mapping: dict):
|
||||
"""读取模板并替换占位符,返回内存中的 Document 对象(不保存)。"""
|
||||
if not os.path.exists(template_path):
|
||||
raise FileNotFoundError(f"模板不存在:{template_path}")
|
||||
doc = Document(template_path)
|
||||
|
||||
# 旧占位符统一归一化为新占位符
|
||||
norm = dict(LEGACY_PLACEHOLDERS)
|
||||
norm.update(mapping)
|
||||
|
||||
for para in doc.paragraphs:
|
||||
_replace_in_paragraph(para, norm)
|
||||
for tbl in doc.tables:
|
||||
for row in tbl.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
_replace_in_paragraph(para, norm)
|
||||
return doc
|
||||
|
||||
|
||||
def _leftover_placeholders(doc) -> set:
|
||||
"""统计文档(含表格)中残留的 {{...}} 占位符。"""
|
||||
leftover = set()
|
||||
for para in doc.paragraphs:
|
||||
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
|
||||
for tbl in doc.tables:
|
||||
for row in tbl.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
|
||||
return leftover
|
||||
|
||||
|
||||
def _merge_notice_docs(docs) -> object:
|
||||
"""把多份已填充的告知书 Document 合并为一份(每份之间插入分页符)。"""
|
||||
base = docs[0]
|
||||
body = base.element.body
|
||||
sect_pr = body.find(qn("w:sectPr"))
|
||||
for d in docs[1:]:
|
||||
# 分页符段落
|
||||
p = base.add_paragraph()
|
||||
p.add_run().add_break(WD_BREAK.PAGE)
|
||||
# 将该份告知书的段落与表格追加到正文末尾(跳过节属性)
|
||||
for child in list(d.element.body):
|
||||
if child.tag == qn("w:sectPr"):
|
||||
continue
|
||||
if sect_pr is not None:
|
||||
sect_pr.addprevious(deepcopy(child))
|
||||
else:
|
||||
body.append(deepcopy(child))
|
||||
return base
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
"""过滤 Windows 文件名非法字符,避免路径/分隔符冲突。"""
|
||||
for ch in '\\/:*?"<>|':
|
||||
name = name.replace(ch, "_")
|
||||
return name.strip() or "未命名"
|
||||
|
||||
|
||||
def _fill_template(template_path: str, mapping: dict, out_path: str) -> int:
|
||||
"""读取模板并替换占位符,保存为 out_path。返回残留占位符数量。"""
|
||||
doc = _fill_doc(template_path, mapping)
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
doc.save(out_path)
|
||||
return len(_leftover_placeholders(doc))
|
||||
|
||||
|
||||
# ==================== PDF 转换(WPS 文字 COM,兼容无 MS Word 环境) ====================
|
||||
@retry(max_attempts=RETRY_TIMES)
|
||||
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
|
||||
"""用 WPS 打开 src_docx,另存为 target_docx 并导出 target_pdf。失败自动重试 3 次。"""
|
||||
os.makedirs(os.path.dirname(target_docx), exist_ok=True)
|
||||
src_docx = os.path.abspath(src_docx)
|
||||
target_docx = os.path.abspath(target_docx)
|
||||
target_pdf = os.path.abspath(target_pdf)
|
||||
|
||||
app = None
|
||||
try:
|
||||
app = win32com.client.Dispatch("Kwps.Application")
|
||||
app.Visible = False
|
||||
try:
|
||||
app.DisplayAlerts = 0
|
||||
except Exception:
|
||||
pass
|
||||
doc = app.Documents.Open(src_docx)
|
||||
try:
|
||||
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
|
||||
except Exception:
|
||||
doc.SaveAs(target_docx, 12)
|
||||
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
|
||||
doc.Close(False)
|
||||
finally:
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== OA 工作沟通推送数据构造 ====================
|
||||
def _norm_code(value):
|
||||
"""工号统一转文本:浮点整数(37036835.0)去掉小数部分,与花名册文本工号保持一致。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _read_roster_map(roster_path: str) -> dict:
|
||||
"""读取花名册,返回 {工号: {姓名, 二级部门, 四级部门, 岗位}};表头行自动定位(含「工号」列)。"""
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
wb = openpyxl.load_workbook(roster_path, read_only=True, data_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
col_idx, header_row = {}, None
|
||||
for row in ws.iter_rows():
|
||||
if header_row is None:
|
||||
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
|
||||
if "工号" in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「工号」字段):{roster_path}")
|
||||
need = ("工号", "姓名", "二级部门", "四级部门", "岗位")
|
||||
missing = [c for c in need if c not in col_idx]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}")
|
||||
|
||||
def _cell(vals, key):
|
||||
i = col_idx[key]
|
||||
return vals[i] if i < len(vals) else None
|
||||
|
||||
result = {}
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
vals = [c.value for c in row]
|
||||
code = _norm_code(_cell(vals, "工号"))
|
||||
if not code:
|
||||
continue
|
||||
result[code] = {
|
||||
"姓名": str(_cell(vals, "姓名") or ""),
|
||||
"二级部门": str(_cell(vals, "二级部门") or ""),
|
||||
"四级部门": str(_cell(vals, "四级部门") or ""),
|
||||
"岗位": str(_cell(vals, "岗位") or ""),
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _fill_dept4(rec: dict, roster_map: dict) -> str:
|
||||
"""四级部门:源数据缺失时查花名册(按37工号),仍缺失 fallback 二级部门。"""
|
||||
dept4 = str(rec.get("四级部门") or "").strip()
|
||||
if dept4:
|
||||
return dept4
|
||||
code = _norm_code(rec.get("37工号"))
|
||||
if code and roster_map and code in roster_map:
|
||||
dept4 = str(roster_map[code].get("四级部门") or "").strip()
|
||||
if dept4:
|
||||
return dept4
|
||||
return str(rec.get("二级部门") or "").strip() or "未知"
|
||||
|
||||
|
||||
def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
|
||||
"""读取社保变更人员名单,返回「是否变更」=是 的记录列表。
|
||||
|
||||
每条 rec 带标准列名(新区域->区域、个人费用->费用)与 _source=sheet 名(区分职能/门店);
|
||||
四级部门缺失时用花名册补全,仍缺失 fallback 二级部门。
|
||||
"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
records = []
|
||||
for ws in wb.worksheets:
|
||||
if not any(kw in ws.title for kw in TRANSFER_SHEET_GENERATE):
|
||||
continue # 仅处理配置范围内的 sheet(职能及干部/门店)
|
||||
# 自动定位表头行:同时含「37工号」与「是否变更」列
|
||||
col_idx, header_row = None, None
|
||||
for row in ws.iter_rows():
|
||||
if header_row is None:
|
||||
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
|
||||
if "37工号" in names and TRANSFER_CHANGE_COL in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
continue # 非目标 sheet(如说明/汇总页)
|
||||
|
||||
def _cell(vals, key):
|
||||
i = col_idx.get(key)
|
||||
return vals[i] if i is not None and i < len(vals) else None
|
||||
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
vals = [c.value for c in row]
|
||||
if all(v is None for v in vals):
|
||||
continue
|
||||
if str(_cell(vals, TRANSFER_CHANGE_COL) or "").strip() != TRANSFER_CHANGE_VALUE:
|
||||
continue
|
||||
rec = {}
|
||||
for src, std in TRANSFER_COL_MAP.items():
|
||||
if src in col_idx:
|
||||
rec[std] = _cell(vals, src)
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "参保单位全称", "备注"):
|
||||
if key in col_idx:
|
||||
rec[key] = _cell(vals, key)
|
||||
if rec.get("姓名") is None:
|
||||
continue
|
||||
rec["_source"] = ws.title
|
||||
rec["四级部门"] = _fill_dept4(rec, roster_map)
|
||||
if not rec.get("工号") and rec.get("37工号") is not None:
|
||||
rec["工号"] = rec["37工号"]
|
||||
records.append(rec)
|
||||
return records
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _find_store_manager_in_map(roster_map: dict, code: str):
|
||||
"""在已读花名册中查店长(同四级部门岗位含「店长」,按行序取第一个),返回店长工号或 None。"""
|
||||
info = roster_map.get(code)
|
||||
if not info or not info["四级部门"]:
|
||||
return None
|
||||
for c, it in roster_map.items():
|
||||
if it["四级部门"] == info["四级部门"] and "店长" in it["岗位"]:
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def _find_hr_personnel_in_map(roster_map: dict, code: str) -> list:
|
||||
"""在已读花名册中查人事:二级部门为「石桥铺会馆」固定返回;经营中心下岗位含「人事」全量返回。"""
|
||||
info = roster_map.get(code)
|
||||
if not info:
|
||||
return []
|
||||
dept2 = info["二级部门"]
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
return list(DEPT2_HR_OVERRIDE[dept2])
|
||||
if "经营中心" not in dept2:
|
||||
return []
|
||||
return [c for c, it in roster_map.items() if it["二级部门"] == dept2 and "人事" in it["岗位"]]
|
||||
|
||||
|
||||
def _resolve_receivers(roster_map: dict, codes: list) -> list:
|
||||
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。"""
|
||||
receivers = []
|
||||
for code in codes:
|
||||
mgr = _find_store_manager_in_map(roster_map, code)
|
||||
if mgr and mgr not in receivers:
|
||||
receivers.append(mgr)
|
||||
for hr in _find_hr_personnel_in_map(roster_map, code):
|
||||
if hr and hr not in receivers:
|
||||
receivers.append(hr)
|
||||
return receivers
|
||||
|
||||
|
||||
def _collect_rule_pdfs(month_dir: str, rule_folder: str, matched_recs: list) -> list:
|
||||
"""按命中员工的(二级部门,四级部门)分组,收集对应告知书 PDF 附件路径(仅 PDF)。"""
|
||||
folder = os.path.join(month_dir, rule_folder)
|
||||
if not os.path.isdir(folder):
|
||||
return []
|
||||
wanted = {
|
||||
_safe_filename(
|
||||
f"{str(r.get('二级部门') or '未知').strip()}_{str(r.get('四级部门') or '未知').strip()}_{rule_folder}"
|
||||
) + ".pdf"
|
||||
for r in matched_recs
|
||||
}
|
||||
return [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f in wanted]
|
||||
|
||||
|
||||
def _text_to_html(text: str) -> str:
|
||||
"""多行纯文本转 HTML:
|
||||
- 普通段落用 <p style="text-indent:2em"> 首行缩进 2 字符;
|
||||
- 行以 @@R 前缀标记右对齐(落款),输出时去除前缀并用 <p style="text-align:right">。
|
||||
"""
|
||||
parts = []
|
||||
for ln in str(text).splitlines():
|
||||
ln = ln.strip()
|
||||
if not ln:
|
||||
continue
|
||||
if ln.startswith("@@R"):
|
||||
parts.append(f'<p style="text-align:right">{ln[3:]}</p>')
|
||||
else:
|
||||
parts.append(f'<p style="text-indent:2em">{ln}</p>')
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _highlight_text(text: str, highlights: tuple, m: int = None) -> str:
|
||||
"""给文案关键词加颜色高亮(<span style="color:...">),keyword 支持 {m} 月份占位符。"""
|
||||
for keyword, color in highlights:
|
||||
kw = keyword.format(m=m) if m is not None else keyword
|
||||
text = text.replace(kw, f'<span style="color:{color}">{kw}</span>')
|
||||
return text
|
||||
|
||||
|
||||
def build_work_communication_data(excel_path: str = None, output_dir: str = None,
|
||||
ym: tuple = None, roster_path: str = None) -> list:
|
||||
"""
|
||||
构造 OA 工作沟通推送数据:员工参与社会保险+参保异常合并一条、社保转移单独一条。
|
||||
每条含 subject/content(HTML)/attachment_paths(仅PDF)/receivers(店长+人事工号)/category,
|
||||
并写入影刀全局变量 messages(列表),供「OA工作沟通推送」指令逐条调用。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT(须先执行 generate_notices 生成 PDF)
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径,默认 ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
list: [{"subject", "content", "attachment_paths", "receivers", "category"}, ...]
|
||||
"""
|
||||
excel_path = excel_path or _find_excel(BASE_DIR)
|
||||
ym = ym or _extract_ym(os.path.basename(excel_path))
|
||||
output_dir = output_dir or OUTPUT_ROOT
|
||||
roster_path = roster_path or ROSTER_PATH
|
||||
y, m = ym
|
||||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||||
|
||||
logger.info("构造 OA 工作沟通数据:%s(%d-%02d)", excel_path, y, m)
|
||||
records = _read_insurance_records(excel_path)
|
||||
|
||||
# 社保转移:独立数据源(社保变更人员名单),推送仅限「变更-门店」sheet
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
|
||||
roster_map = {}
|
||||
transfer_excel = _find_transfer_excel(BASE_DIR)
|
||||
transfer_records = _read_transfer_records(transfer_excel, roster_map)
|
||||
|
||||
# 按模板规则筛出命中员工
|
||||
matched_by_rule = {}
|
||||
for rule_name, rule in TEMPLATES.items():
|
||||
if rule_name == "社保转移":
|
||||
matched = [r for r in transfer_records if TRANSFER_SHEET_PUSH in str(r.get("_source") or "")]
|
||||
else:
|
||||
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
|
||||
matched_by_rule[rule_name] = matched
|
||||
logger.info("[%s] 命中 %d 人", rule_name, len(matched))
|
||||
|
||||
roster_map = _read_roster_map(roster_path)
|
||||
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
|
||||
|
||||
messages = []
|
||||
for tpl in OA_MESSAGE_TEMPLATES:
|
||||
matched_recs = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
matched_recs.extend(matched_by_rule.get(rn, []))
|
||||
if not matched_recs:
|
||||
logger.info("[%s] 无命中人员,跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 附件:仅 PDF,按命中员工(二级部门,四级部门)分组收集
|
||||
attachment_paths = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
attachment_paths.extend(
|
||||
_collect_rule_pdfs(month_dir, TEMPLATES[rn]["folder"], matched_by_rule.get(rn, []))
|
||||
)
|
||||
# 同一二级部门的所有告知书挨着排列(文件名首段=二级部门,段内按文件名排)
|
||||
attachment_paths = sorted(
|
||||
attachment_paths,
|
||||
key=lambda p: (os.path.basename(p).split("_", 1)[0], os.path.basename(p)),
|
||||
)
|
||||
if not attachment_paths:
|
||||
logger.warning("[%s] 未收集到告知书 PDF(请先执行告知书生成),跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 接收人:店长 + 人事(工号去重)
|
||||
codes = []
|
||||
for r in matched_recs:
|
||||
c = _norm_code(r.get("工号"))
|
||||
if c:
|
||||
codes.append(c)
|
||||
else:
|
||||
logger.warning("员工「%s」无工号,跳过接收人解析", r.get("姓名"))
|
||||
receivers = _resolve_receivers(roster_map, codes)
|
||||
if TEST_MODE:
|
||||
receivers = list(TEST_RECEIVER)
|
||||
logger.info("[测试模式] [%s] 接收人覆盖为测试接收人:%s", tpl["key"], TEST_RECEIVER)
|
||||
if not receivers:
|
||||
logger.warning("[%s] 未解析到任何接收人(店长/人事),跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 落款日期 = 实际推送当天日期(如 2026年08月26日,带前导0)
|
||||
push_date = datetime.today().strftime("%Y年%m月%d日")
|
||||
content = _highlight_text(tpl["content"].format(y=y, m=m, push_date=push_date), OA_HIGHLIGHTS.get(tpl["key"], ()), m=m)
|
||||
|
||||
messages.append({
|
||||
"subject": tpl["subject"].format(y=y, m=m),
|
||||
"content": _text_to_html(content),
|
||||
"attachment_paths": attachment_paths,
|
||||
"receivers": receivers,
|
||||
"category": tpl["category"],
|
||||
})
|
||||
logger.info("[%s] 附件 %d 份,接收人 %d 人:%s",
|
||||
tpl["key"], len(attachment_paths), len(receivers), ", ".join(receivers))
|
||||
|
||||
_set_glv(OA_GLV_NAME, messages)
|
||||
logger.info("构造完成:%d 条工作沟通推送数据,已写入全局变量 %s", len(messages), OA_GLV_NAME)
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def generate_notices(excel_path: str = None, output_dir: str = None, ym: tuple = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""
|
||||
生成三类告知书(Word + PDF)。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径(社保转移四级部门补全用),默认 ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
{模板名: [输出文件路径, ...]}
|
||||
"""
|
||||
excel_path = excel_path or _find_excel(BASE_DIR)
|
||||
ym = ym or _extract_ym(os.path.basename(excel_path))
|
||||
output_dir = output_dir or OUTPUT_ROOT
|
||||
y, m = ym
|
||||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||||
|
||||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||||
records = _read_insurance_records(excel_path)
|
||||
logger.info("「参保名单」共 %d 条记录", len(records))
|
||||
|
||||
# 社保转移:独立数据源(社保变更人员名单),生成覆盖职能及干部+门店两个 sheet
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
|
||||
roster_map = {}
|
||||
transfer_excel = _find_transfer_excel(BASE_DIR)
|
||||
transfer_records = _read_transfer_records(transfer_excel, roster_map)
|
||||
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), transfer_excel)
|
||||
|
||||
results = {}
|
||||
for rule_name, rule in TEMPLATES.items():
|
||||
tpl_path = rule["file"]
|
||||
if not os.path.exists(tpl_path):
|
||||
raise FileNotFoundError(f"模板不存在:{tpl_path}")
|
||||
if rule_name == "社保转移":
|
||||
matched = transfer_records
|
||||
else:
|
||||
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
|
||||
if not matched:
|
||||
logger.info("[%s] 无命中人员,跳过", rule_name)
|
||||
results[rule_name] = []
|
||||
continue
|
||||
|
||||
out_folder = os.path.join(month_dir, rule["folder"])
|
||||
os.makedirs(out_folder, exist_ok=True)
|
||||
files = []
|
||||
logger.info("=" * 70)
|
||||
logger.info("[%s] 命中 %d 人(%s)", rule_name, len(matched), ", ".join(str(r.get("姓名")) for r in matched))
|
||||
|
||||
# 按(二级部门,四级部门)分组合并,生成一份告知书
|
||||
groups = {}
|
||||
for rec in matched:
|
||||
key = (str(rec.get("二级部门") or "未知").strip(), str(rec.get("四级部门") or "未知").strip())
|
||||
groups.setdefault(key, []).append(rec)
|
||||
|
||||
for (dept2, dept4), recs in groups.items():
|
||||
# 每人生成一份已填充的内存文档,再合并(每份之间分页)
|
||||
docs = [_fill_doc(tpl_path, _build_placeholders(r, ym)) for r in recs]
|
||||
doc = _merge_notice_docs(docs) if len(docs) > 1 else docs[0]
|
||||
base_name = _safe_filename(f"{dept2}_{dept4}_{rule['folder']}")
|
||||
docx_path = os.path.join(out_folder, base_name + ".docx")
|
||||
pdf_path = docx_path[:-5] + ".pdf"
|
||||
|
||||
doc.save(docx_path)
|
||||
leftover = _leftover_placeholders(doc)
|
||||
if leftover:
|
||||
logger.warning("[%s] %s 模板存在未替换占位符:%s", rule_name, base_name, sorted(leftover))
|
||||
_publish_via_wps(docx_path, docx_path, pdf_path)
|
||||
logger.info("已生成:%s(%d 人)", os.path.basename(docx_path), len(recs))
|
||||
files.append(docx_path)
|
||||
results[rule_name] = files
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("全部完成,输出目录:%s", month_dir)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> list:
|
||||
"""告知书制作与下发(影刀入口):生成当月三类告知书,并构造 OA 工作沟通推送数据。
|
||||
|
||||
Returns:
|
||||
工作沟通推送数据列表(每条含 receivers/subject/content/attachment_paths/category),
|
||||
与影刀全局变量 messages 内容一致;即使无影刀环境,调用方也可直接用返回值推送。
|
||||
"""
|
||||
try:
|
||||
results = generate_notices()
|
||||
messages = build_work_communication_data()
|
||||
_set_glv("notice_output_dir", os.path.join(OUTPUT_ROOT, datetime.now().strftime("%Y%m")))
|
||||
_set_glv(OA_GLV_NAME, messages)
|
||||
total = sum(len(files) for files in results.values())
|
||||
logger.info("共生成 %d 份告知书(docx+pdf),构造 %d 条工作沟通推送数据", total, len(messages))
|
||||
return messages
|
||||
except Exception:
|
||||
logger.exception("告知书制作与下发失败")
|
||||
_set_glv("notice_error", traceback.format_exc())
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -558,22 +558,9 @@ def send_work_communication(
|
||||
)
|
||||
|
||||
|
||||
# ==================== 主入口(影刀指令) ====================
|
||||
def main(receiver_keywords, subject, content, attachment_paths="", creator_id="", category="工作安排"):
|
||||
"""
|
||||
影刀指令入口:发送工作沟通推送。
|
||||
|
||||
Args:
|
||||
receiver_keywords: 接收人工号或姓名(列表或字符串)
|
||||
subject: 沟通标题
|
||||
content: 沟通内容(支持 HTML 富文本)
|
||||
attachment_paths: 附件文件路径(列表或字符串,可空)
|
||||
creator_id: 创建人(当前操作人)用户 ID;为空则尝试从新建页自动提取
|
||||
category: 沟通类型(默认 工作安排)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "message": str, "doc_id": str};并写入影刀全局变量 push_result。
|
||||
"""
|
||||
def _send_work_communication_wrapped(receiver_keywords, subject, content, attachment_paths="",
|
||||
creator_id="", category="工作安排"):
|
||||
"""单条工作沟通推送(捕获异常,返回 result dict)。"""
|
||||
try:
|
||||
doc_id = send_work_communication(
|
||||
receiver_keywords=receiver_keywords,
|
||||
@@ -583,25 +570,81 @@ def main(receiver_keywords, subject, content, attachment_paths="", creator_id=""
|
||||
creator_id=creator_id or None,
|
||||
category=category,
|
||||
)
|
||||
result = {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
|
||||
return {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
|
||||
except SystemExit as e:
|
||||
result = {"success": False, "message": str(e), "doc_id": ""}
|
||||
return {"success": False, "message": str(e), "doc_id": ""}
|
||||
except Exception as e:
|
||||
logger.error("工作沟通推送失败: %s", e)
|
||||
result = {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
|
||||
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
|
||||
|
||||
|
||||
# ==================== 主入口(影刀指令) ====================
|
||||
def main(messages=None, receiver_keywords=None, subject=None, content=None,
|
||||
attachment_paths="", creator_id="", category="工作安排"):
|
||||
"""
|
||||
影刀指令入口:发送工作沟通推送。
|
||||
|
||||
支持两种调用方式:
|
||||
1) main(messages):messages 为列表,每条含字段
|
||||
{receivers, subject, content, attachment_paths, creator_id, category},
|
||||
对应 notice 模块 oa_work_communications 全局变量结构,逐条推送
|
||||
2) main(receiver_keywords=..., subject=..., content=..., ...):单条推送(向后兼容)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "message": str, "doc_id": str};并写入影刀全局变量 push_result。
|
||||
"""
|
||||
if isinstance(messages, list) and messages:
|
||||
results = []
|
||||
for i, msg in enumerate(messages, 1):
|
||||
r = _send_work_communication_wrapped(
|
||||
receiver_keywords=msg.get("receivers", []),
|
||||
subject=msg.get("subject", ""),
|
||||
content=msg.get("content", ""),
|
||||
attachment_paths=msg.get("attachment_paths", ""),
|
||||
creator_id=msg.get("creator_id", ""),
|
||||
category=msg.get("category", "工作安排"),
|
||||
)
|
||||
results.append(r)
|
||||
logger.info("[%d/%d] %s", i, len(messages), r.get("message"))
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
result = {
|
||||
"success": ok == len(results),
|
||||
"message": f"共推送 {len(results)} 条,成功 {ok} 条",
|
||||
"doc_id": ",".join(r.get("doc_id", "") for r in results if r.get("doc_id")),
|
||||
}
|
||||
else:
|
||||
result = _send_work_communication_wrapped(
|
||||
receiver_keywords=receiver_keywords or [],
|
||||
subject=subject or "",
|
||||
content=content or "",
|
||||
attachment_paths=attachment_paths,
|
||||
creator_id=creator_id,
|
||||
category=category,
|
||||
)
|
||||
_set_glv("push_result", result)
|
||||
logger.info("推送结果: %s", result)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 本地独立运行调试示例(影刀中由指令参数传入)
|
||||
result = main(
|
||||
receiver_keywords=["37036361"],
|
||||
subject="【RPA自动化】影刀版工作沟通推送测试",
|
||||
content="<p>影刀单文件版工作沟通推送测试。</p>",
|
||||
attachment_paths="",
|
||||
creator_id="",
|
||||
category="工作安排",
|
||||
)
|
||||
# 本地独立运行调试示例:messages 结构同 notice 模块的 oa_work_communications 全局变量,
|
||||
# 逐条调用 main 推送(影刀中同样按该结构循环推送)。
|
||||
messages = [
|
||||
{
|
||||
"receivers": ["37036361", "37001166"], # 测试接收人(多人)
|
||||
"subject": "2026年8月员工参保结果告知书",
|
||||
"content": "<p>【测试】重庆区域门店8月新参保已完成,请各门店传达告知。</p>",
|
||||
"attachment_paths": [],
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"receivers": ["37036361", "37001166"],
|
||||
"subject": "2026年8月员工参保单位变更确认",
|
||||
"content": "<p>【测试】本月人力资源部已输出“工作与参保单位不一致”人员,请完成转移确认。</p>",
|
||||
"attachment_paths": [],
|
||||
"category": "工作安排",
|
||||
},
|
||||
]
|
||||
main(messages)
|
||||
result = main(messages)
|
||||
print("RESULT:", result)
|
||||
|
||||
Reference in New Issue
Block a user