- 新增 HR 花名册接口拉取逻辑,优先从 HR 接口获取花名册,失败回退源表/本地文件 - 新增推送人映射支持所属单位回退值,新增「水庄大鹅事业部」映射 - 修复 OA 推送附件上传时清除默认 Content-Type,避免 multipart 请求被服务端拒绝 - 优化二级部门解析逻辑,为空时用所属单位替代,避免中断流程 - 新增 store_point_api.py 和 attendance_points_push.py 积分推送模块,新增 store_login_api.py 门店登录模块 - 新增 notice_gen.py 中 HR 接口加密逻辑及多数据源 fallback 处理
1191 lines
53 KiB
Python
1191 lines
53 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: notice_mail_merge.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-26
|
||
@Description: 告知书制作与下发(影刀版,单文件自包含)——按分支读取当月数据源,
|
||
生成 Word 告知书并转 PDF:
|
||
- 分支「新参保」:读取《社保变更及增减名单.xlsx》中「参保名单」sheet(表头第3行),
|
||
模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保 & 参保告知空)
|
||
模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保 & 参保告知空)
|
||
- 分支「转移参保」:读取《社保变更人员名单.xlsx》,生成
|
||
模板3 社保转移告知书(是否变更=是)
|
||
数据源文件必须为当月(文件名月份=当前月),历史月份文件或缺失均报错。
|
||
输出命名:按(二级部门,参保单位)分组合并,同一二级部门+参保单位+类型的所有员工合并为一份,
|
||
文件名 = 二级部门_参保单位_告知书类型.docx/pdf,同组多人逐页排列。
|
||
二级部门解析:优先按该行「参保单位」(R 列)在数据源全量记录中聚合取唯一二级部门(经营中心);
|
||
不唯一/缺失时兜底把参保单位作为四级部门在花名册反查二级部门;
|
||
仍解析不到则报错并跳过该员工(不生成/不推送)。
|
||
OA 工作沟通推送:新参保分支=员工参与社会保险+参保异常合并一条、
|
||
转移参保分支=社保转移单独一条;各类型输出目录下全部告知书 PDF 均作为附件推送(不筛选),
|
||
接收人=店长+经营中心人行(按解析后的二级部门匹配),统一追加固定抄送人周卫;写入影刀全局变量 messages(列表),
|
||
供「OA工作沟通推送」指令逐条调用。
|
||
业务判定及占位符约定见 aa.md、docs/参保成功及异常告知书、docs/社保转移告知书。
|
||
@Version: 1.5.0
|
||
|
||
设计说明(与 workflows 下其它单文件版一致):
|
||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||
- 不 import 任何共享指令模块、不做 sys.path 注入、不做目录向上查找。
|
||
- 占位符约定:模板中仅允许纯变量占位符(如 {{姓名}}、{{下月}}、{{一次性扣款}}),
|
||
不支持 {{当前月+1}} / {{费用*2}} 这类带表达式的写法(脚本会自动兼容旧写法)。
|
||
- PDF 转换优先 WPS 文字 COM(Kwps.Application),失败自动回退 WPS 命令行
|
||
kwpsconvert.exe word2pdf(兼容 32 位 WPS / 未安装 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 shutil
|
||
import random
|
||
import functools
|
||
import subprocess
|
||
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 = "社保变更及增减名单" # 表格文件名关键字(表结构更新后新命名:2026年9月社保变更及增减名单及人数统计.xlsx)
|
||
SHEET_KEYWORD = "参保名单" # sheet 名关键字
|
||
HEADER_ROW = 3 # 表头所在行
|
||
MAIN_COLS = 51 # 主表字段到「费用」列(AY)为止(AZ 为空列,其后为粘贴重复区)
|
||
RETRY_TIMES = 3 # 全局重试次数
|
||
|
||
# 社保转移数据源:转移参保数据已并入「社保变更及增减名单」文件的「变更-职能及干部/变更-门店」sheet
|
||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
|
||
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
|
||
TRANSFER_CHANGE_COL = "是否变更" # 筛选列
|
||
TRANSFER_CHANGE_VALUE = "是" # 筛选值
|
||
# 列名映射:社保变更名单列名 -> 标准列名(模板占位符依赖标准列名)
|
||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||
|
||
# 执行分支:'新参保'=员工参保+参保异常(数据源:社保变更及增减名单);'转移参保'=社保转移(数据源:社保变更人员名单)
|
||
BRANCHES = {
|
||
"新参保": {
|
||
"rule_keys": ("新参保", "参保异常"), # 参与生成的模板名
|
||
"excel_keyword": "社保变更及增减名单", # 数据源文件名关键字
|
||
},
|
||
"转移参保": {
|
||
"rule_keys": ("社保转移",),
|
||
"excel_keyword": "社保变更及增减名单", # 与「新参保」同源文件,读其「变更-*」sheet
|
||
},
|
||
}
|
||
|
||
# ---- OA 工作沟通推送数据构造 ----
|
||
ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx" # 员工花名册路径
|
||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]} # 二级部门 -> 固定人事工号(梁敏)
|
||
|
||
# 推送人映射:键可为「二级部门(经营中心)」或「二级部门为空时的所属单位回退值」(如 水庄大鹅事业部)。
|
||
# 优先于花名册人事查找(覆盖映射不依赖员工是否在花名册)。
|
||
DEPT2_PUSH_OVERRIDE = {
|
||
"金色印象海口经营中心": ["37000700"], # 李明姣 财务专员
|
||
"金色印象昆明经营中心": ["37002511"], # 陈青 财务专员
|
||
"金色印象南宁经营中心": ["37009626"], # 石梦 财务专员
|
||
"金色印象深圳经营中心": ["37018211"], # 倪萍 财务专员
|
||
"金色印象郑州经营中心": ["37006992"], # 张勤 财务专员
|
||
"水庄大鹅事业部": ["37036104"], # 所属单位回退值(非二级部门),直接推送 37036104 唐佳膑
|
||
}
|
||
OA_GLV_NAME = "messages" # 影刀全局变量名(列表:工作沟通推送数据)
|
||
|
||
# 测试模式:True=推送接收人统一覆盖为测试接收人(不推真实店长/人事);正式运行请改为 False
|
||
TEST_MODE = True
|
||
TEST_RECEIVER = ["37036361", "37001166"] # 测试接收人(多人):37036361 夏一平 + 37001166
|
||
|
||
# 固定抄送人:统一加入每条工作沟通推送的接收人(周卫)
|
||
CC_RECEIVER_NAME = "周卫"
|
||
CC_RECEIVER_ID = "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}月27日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||
"在{m}月29日内传递人资周卫处。\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 _match_rule(rec: dict, status: str, ins_type: str) -> bool:
|
||
"""按模板规则 + 参保告知为空 判断记录是否命中。
|
||
|
||
三项筛选:办理状态、参保类型、参保告知(AT 列)为空。
|
||
表结构更新后不再按人员类型/二级部门/办理时间过滤(见 aa.md 变更说明)。
|
||
"""
|
||
if str(rec.get("办理状态") or "").strip() != status:
|
||
return False
|
||
if str(rec.get("参保类型") or "").strip() != ins_type:
|
||
return False
|
||
# 参保告知为空才命中(未下发过的员工),避免重复下发
|
||
return not str(rec.get("参保告知") or "").strip()
|
||
|
||
|
||
def _extract_ym(filename: str):
|
||
"""从文件名解析 (年, 月);支持 '202609' 与 '2026年9月' 两种格式;失败返回当月。"""
|
||
m = re.search(r"(20\d{2})年(\d{1,2})月", filename)
|
||
if m:
|
||
return (int(m.group(1)), int(m.group(2)))
|
||
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_current_month_excel(dir_path: str, keyword: str) -> str:
|
||
"""在目录内查找包含 keyword 且文件名月份=当月的 xlsx 文件。
|
||
|
||
只取当前月份的文件:命中历史月份文件或未找到均报错,避免使用过期数据源。
|
||
"""
|
||
if not os.path.isdir(dir_path):
|
||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||
now = datetime.now()
|
||
current_ym = (now.year, now.month)
|
||
found = []
|
||
for name in os.listdir(dir_path):
|
||
if keyword in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||
found.append(name)
|
||
if not found:
|
||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{keyword}」的 xlsx 文件")
|
||
for name in found:
|
||
if _extract_ym(name) == current_ym:
|
||
return os.path.join(dir_path, name)
|
||
raise FileNotFoundError(
|
||
f"目录 {dir_path} 下包含「{keyword}」的文件均非当前月份 {now.year}年{now.month}月:{found}"
|
||
)
|
||
|
||
|
||
def _find_excel(dir_path: str) -> str:
|
||
"""在目录内查找包含「社保变更及增减名单」且月份=当月的 xlsx 文件。"""
|
||
return _find_current_month_excel(dir_path, EXCEL_KEYWORD)
|
||
|
||
|
||
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 _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,失败自动回退 kwpsconvert 命令行) ====================
|
||
def _find_kwpsconvert() -> str:
|
||
"""定位 WPS 自带转换器 kwpsconvert.exe(wpscli word2pdf,不依赖 COM)。
|
||
|
||
本机 WPS 为 32 位时,COM 类 Kwps.Application 仅注册在 32 位注册表视图,
|
||
64 位 Python 无法调用(报 -2147221005 无效的类字符串),需回退命令行转换。
|
||
依次尝试:环境变量 wps_kwpsconvert 指定路径 -> 常见安装目录 -> PATH。
|
||
"""
|
||
env = os.getenv("wps_kwpsconvert")
|
||
if env and os.path.isfile(env):
|
||
return env
|
||
bases = [
|
||
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Kingsoft", "WPS Office"),
|
||
os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Kingsoft", "WPS Office"),
|
||
os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Kingsoft", "WPS Office"),
|
||
]
|
||
for base in bases:
|
||
if not base or not os.path.isdir(base):
|
||
continue
|
||
for ver_dir in os.listdir(base):
|
||
cand = os.path.join(base, ver_dir, "office6", "kwpsconvert.exe")
|
||
if os.path.isfile(cand):
|
||
return cand
|
||
exe = shutil.which("kwpsconvert")
|
||
return exe or ""
|
||
|
||
|
||
def _publish_via_kwpsconvert(src_docx: str, target_pdf: str) -> None:
|
||
"""用 WPS 命令行 kwpsconvert.exe word2pdf 把 docx 转 PDF(不依赖 COM,兼容 32 位 WPS)。
|
||
|
||
目标 PDF 已存在时 kwpsconvert 会自动改名(不覆盖),故先删除旧文件确保落到目标路径。
|
||
"""
|
||
exe = _find_kwpsconvert()
|
||
if not exe:
|
||
raise RuntimeError("未找到 kwpsconvert.exe(WPS 命令行转换器),可设置环境变量 wps_kwpsconvert 指定路径")
|
||
src_docx = os.path.abspath(src_docx)
|
||
target_pdf = os.path.abspath(target_pdf)
|
||
os.makedirs(os.path.dirname(target_pdf), exist_ok=True)
|
||
if os.path.exists(target_pdf):
|
||
os.remove(target_pdf)
|
||
cmd = [exe, "word2pdf", src_docx, "-o", target_pdf]
|
||
kwargs = {}
|
||
if os.name == "nt":
|
||
kwargs["creationflags"] = 0x08000000 # CREATE_NO_WINDOW,避免弹出命令行窗口
|
||
proc = subprocess.run(cmd, capture_output=True, timeout=300, **kwargs)
|
||
if proc.returncode != 0:
|
||
err = (proc.stderr or proc.stdout or b"").decode("gbk", errors="ignore").strip()
|
||
raise RuntimeError(f"kwpsconvert 转换失败(exit={proc.returncode}): {err or target_pdf}")
|
||
if not os.path.exists(target_pdf):
|
||
raise RuntimeError(f"kwpsconvert 转换后未生成 PDF:{target_pdf}")
|
||
logger.info("kwpsconvert 转换成功:%s", os.path.basename(target_pdf))
|
||
|
||
|
||
@retry(max_attempts=RETRY_TIMES)
|
||
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
|
||
"""导出 target_pdf:优先 WPS 文字 COM(Kwps.Application),失败自动回退 kwpsconvert 命令行。
|
||
|
||
兼容 32 位 WPS(COM 类仅注册 32 位视图,64 位 Python 调不到)+ 未安装 MS Word 的环境。
|
||
"""
|
||
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)
|
||
|
||
try:
|
||
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
|
||
except Exception as e:
|
||
logger.warning("WPS COM 转换失败(%s),自动回退 kwpsconvert 命令行", e)
|
||
_publish_via_kwpsconvert(src_docx, target_pdf)
|
||
|
||
|
||
# ==================== 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 _read_roster_from_source_sheet(excel_path: str) -> dict:
|
||
"""读取数据源 Excel 内嵌「附-在职花名册」sheet 构建 roster_map(与业务同文件同月份,数据可靠)。
|
||
花名册单独文件缺失/损坏时兜底用,避免接收人解析受限。"""
|
||
if not excel_path or not os.path.exists(excel_path):
|
||
return {}
|
||
try:
|
||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||
except Exception as e:
|
||
logger.warning("源表读取失败,无法用「附-在职花名册」构建花名册:%s", e)
|
||
return {}
|
||
try:
|
||
ws = next((s for s in wb.worksheets if "在职花名册" in s.title), None)
|
||
if ws is None:
|
||
return {}
|
||
rows = list(ws.iter_rows(min_row=1, max_row=1, max_col=60))
|
||
cols = {}
|
||
for i, h in enumerate(rows[0]):
|
||
v = h.value
|
||
name = str(v).strip() if v is not None else ""
|
||
if name and name not in cols:
|
||
cols[name] = i
|
||
if "工号" not in cols or "姓名" not in cols:
|
||
logger.warning("「附-在职花名册」缺少工号/姓名列,无法构建花名册")
|
||
return {}
|
||
result = {}
|
||
code_col = cols["工号"]
|
||
for row in ws.iter_rows(min_row=2, max_col=60):
|
||
vals = [c.value for c in row]
|
||
if all(v is None for v in vals):
|
||
continue
|
||
code = _norm_code(vals[code_col] if code_col < len(vals) else None)
|
||
if not code or code == "0":
|
||
continue
|
||
|
||
def _cell(key):
|
||
i = cols.get(key)
|
||
return vals[i] if i is not None and i < len(vals) else None
|
||
|
||
result[code] = {
|
||
"姓名": str(_cell("姓名") or ""),
|
||
"二级部门": str(_cell("二级部门") or ""),
|
||
"四级部门": str(_cell("四级部门") or ""),
|
||
"岗位": str(_cell("岗位") or ""),
|
||
"所属单位": str(_cell("所属单位") or ""),
|
||
}
|
||
return result
|
||
finally:
|
||
wb.close()
|
||
|
||
|
||
def _load_roster_map(excel_path: str = None, roster_path: str = None) -> dict:
|
||
"""加载花名册 roster_map:源表「附-在职花名册」→ 本地 员工花名册.xlsx。
|
||
全部失败返回 {}(接收人解析受限但不中断流程)。"""
|
||
excel_path = excel_path or ""
|
||
roster_path = roster_path or ROSTER_PATH
|
||
if excel_path:
|
||
m = _read_roster_from_source_sheet(excel_path)
|
||
if m:
|
||
logger.info("花名册经源表「附-在职花名册」获取:共 %d 人", len(m))
|
||
return m
|
||
try:
|
||
m = _read_roster_map(roster_path)
|
||
logger.info("花名册经本地文件读取:共 %d 人", len(m))
|
||
return m
|
||
except Exception as e:
|
||
logger.warning("本地花名册读取失败,接收人解析受限:%s", e)
|
||
return {}
|
||
|
||
|
||
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)
|
||
# 参保单位全称:优先「全称」列(转移后单位全称),缺失回退「参保单位全称」列
|
||
full_key = "全称" if "全称" in col_idx else "参保单位全称"
|
||
if full_key in col_idx:
|
||
rec["参保单位全称"] = _cell(vals, full_key)
|
||
# 转移参保单位:告知书文件名第二段用(门店=门店名/职能=公司简称)
|
||
if "转移参保单位" in col_idx:
|
||
rec["转移参保单位"] = _cell(vals, "转移参保单位")
|
||
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 _ins_org_of(rec: dict) -> str:
|
||
"""取记录参保单位标识:优先 R 列「参保单位」(简称),其次「参保单位全称」「当前参保单位」。"""
|
||
for key in ("参保单位", "参保单位全称", "当前参保单位"):
|
||
v = str(rec.get(key) or "").strip()
|
||
if v:
|
||
return v
|
||
return ""
|
||
|
||
|
||
def _trans_org_of(rec: dict) -> str:
|
||
"""取记录转移参保单位(告知书文件名第二段用):优先「转移参保单位」列,缺失回退参保单位标识。"""
|
||
v = str(rec.get("转移参保单位") or "").strip()
|
||
return v or _ins_org_of(rec)
|
||
|
||
|
||
def _resolve_dept2(rec: dict, all_records: list, roster_map: dict):
|
||
"""解析记录的正确二级部门(经营中心),优先数据源内参保单位聚合,兜底记录自身/花名册反查。
|
||
|
||
1) 主查:数据源全量记录中按「参保单位」聚合,同参保单位记录的二级部门应唯一(一个经营中心);
|
||
2) 次查:记录自身「二级部门」字段(非空直接采用,覆盖职能/干部等与门店同参保单位但归属不同的人员);
|
||
3) 兜底:主查/次查均无时,把参保单位作为四级部门在花名册反查其二级部门;
|
||
4) 仍解析不到返回 None,由调用方报错并跳过该记录(不推送)。
|
||
"""
|
||
ins = _ins_org_of(rec)
|
||
if not ins:
|
||
return None
|
||
dept2s = {
|
||
str(r.get("二级部门") or "").strip()
|
||
for r in all_records if _ins_org_of(r) == ins
|
||
}
|
||
dept2s.discard("")
|
||
if len(dept2s) == 1:
|
||
return dept2s.pop()
|
||
own = str(rec.get("二级部门") or "").strip()
|
||
if own:
|
||
return own
|
||
dept2s = {
|
||
str(it.get("二级部门") or "").strip()
|
||
for it in roster_map.values()
|
||
if str(it.get("四级部门") or "").strip() == ins
|
||
}
|
||
dept2s.discard("")
|
||
if len(dept2s) == 1:
|
||
return dept2s.pop()
|
||
return None
|
||
|
||
|
||
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, dept2: str = None) -> list:
|
||
"""查人事/推送人:二级部门(含所属单位回退值)命中 DEPT2_PUSH_OVERRIDE 直接返回;
|
||
其次「石桥铺会馆」固定返回;经营中心下岗位含「人事」全量返回(兜底花名册查找)。
|
||
覆盖映射不依赖员工是否在花名册。
|
||
|
||
dept2: 外部解析出的正确二级部门(经营中心)/所属单位回退值,缺省用员工本人花名册二级部门。
|
||
"""
|
||
info = roster_map.get(code) or {}
|
||
dept2 = dept2 or info.get("二级部门") or ""
|
||
if dept2 in DEPT2_PUSH_OVERRIDE:
|
||
return list(DEPT2_PUSH_OVERRIDE[dept2])
|
||
if dept2 in DEPT2_HR_OVERRIDE:
|
||
return list(DEPT2_HR_OVERRIDE[dept2])
|
||
if not info:
|
||
return []
|
||
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, dept2_map: dict = None) -> list:
|
||
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。
|
||
|
||
dept2_map: 工号 -> 修正后的二级部门(经营中心),用于人事匹配(缺省用花名册本人二级部门)。
|
||
"""
|
||
dept2_map = dept2_map or {}
|
||
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, dept2_map.get(code)):
|
||
if hr and hr not in receivers:
|
||
receivers.append(hr)
|
||
return receivers
|
||
|
||
|
||
def _collect_rule_pdfs(month_dir: str, rule_folder: str) -> list:
|
||
"""收集该类型输出目录下全部告知书 PDF 附件路径(不按命中人员筛选,全部推送)。"""
|
||
folder = os.path.join(month_dir, rule_folder)
|
||
if not os.path.isdir(folder):
|
||
return []
|
||
return [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f.lower().endswith(".pdf")]
|
||
|
||
|
||
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(branch: str, output_dir: str = None, ym: tuple = None,
|
||
roster_path: str = None) -> list:
|
||
"""
|
||
按分支构造 OA 工作沟通推送数据:新参保分支=员工参与社会保险+参保异常合并一条;
|
||
转移参保分支=社保转移单独一条。附件为该类型输出目录下全部告知书 PDF(不筛选);
|
||
接收人为店长+人事工号并统一追加固定抄送人周卫(37001166)。每条含
|
||
subject/content(HTML)/attachment_paths/receivers/category,
|
||
并写入影刀全局变量 messages(列表),供「OA工作沟通推送」指令逐条调用。
|
||
|
||
Args:
|
||
branch: 执行分支,'新参保' 或 '转移参保'(显式传参,不使用环境变量/命令行)
|
||
output_dir: 输出目录,默认 OUTPUT_ROOT(须先执行 generate_notices 生成 PDF)
|
||
ym: 目标年月 (year, month),默认当月(数据源文件须为当月,历史月份文件会报错)
|
||
roster_path: 员工花名册路径,默认 ROSTER_PATH
|
||
|
||
Returns:
|
||
list: [{"subject", "content", "attachment_paths", "receivers", "category"}, ...]
|
||
"""
|
||
if branch not in BRANCHES:
|
||
raise ValueError(f"未知分支:{branch},可选 {list(BRANCHES)}")
|
||
rule_keys = BRANCHES[branch]["rule_keys"]
|
||
excel_keyword = BRANCHES[branch]["excel_keyword"]
|
||
output_dir = output_dir or OUTPUT_ROOT
|
||
ym = ym or (datetime.now().year, datetime.now().month)
|
||
y, m = ym
|
||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||
roster_path = roster_path or ROSTER_PATH
|
||
|
||
logger.info("构造 OA 工作沟通数据:分支=%s(%d-%02d)", branch, y, m)
|
||
|
||
# 数据源:按分支关键字查找当月文件(历史月份/缺失均报错)
|
||
excel_path = _find_current_month_excel(BASE_DIR, excel_keyword)
|
||
|
||
# 花名册(二级部门解析/店长人事查找用):源表「附-在职花名册」→ 本地文件,失败置空
|
||
roster_map = _load_roster_map(excel_path, roster_path)
|
||
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
|
||
|
||
# 按分支筛出命中员工(all_records 供参保单位聚合二级部门用)
|
||
matched_by_rule = {}
|
||
if branch == "转移参保":
|
||
transfer_records = _read_transfer_records(excel_path, roster_map)
|
||
matched_by_rule["社保转移"] = [
|
||
r for r in transfer_records if TRANSFER_SHEET_PUSH in str(r.get("_source") or "")
|
||
]
|
||
logger.info("[社保转移] 命中 %d 人", len(matched_by_rule["社保转移"]))
|
||
all_records = transfer_records
|
||
else:
|
||
records = _read_insurance_records(excel_path)
|
||
all_records = records
|
||
for rule_name in rule_keys:
|
||
rule = TEMPLATES[rule_name]
|
||
matched_by_rule[rule_name] = [r for r in records if _match_rule(r, rule["status"], rule["type"])]
|
||
logger.info("[%s] 命中 %d 人", rule_name, len(matched_by_rule[rule_name]))
|
||
|
||
messages = []
|
||
for tpl in OA_MESSAGE_TEMPLATES:
|
||
if not any(rn in rule_keys for rn in tpl["rule_keys"]):
|
||
continue # 只构造本分支对应的推送
|
||
matched_recs = []
|
||
for rn in tpl["rule_keys"]:
|
||
matched_recs.extend(matched_by_rule.get(rn, []))
|
||
|
||
# 附件:仅 PDF,收集该类型输出目录下全部告知书(不筛选,全部推送)
|
||
attachment_paths = []
|
||
for rn in tpl["rule_keys"]:
|
||
attachment_paths.extend(_collect_rule_pdfs(month_dir, TEMPLATES[rn]["folder"]))
|
||
# 同一二级部门的所有告知书挨着排列(文件名首段=二级部门,段内按文件名排)
|
||
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
|
||
|
||
# 接收人:店长 + 人事(工号去重),并统一加上固定抄送人(周卫)
|
||
# 二级部门按「参保单位」解析修正(数据源聚合/花名册兜底),解析不到报错并跳过该员工
|
||
dept2_by_code, codes = {}, []
|
||
for r in matched_recs:
|
||
c = _norm_code(r.get("工号"))
|
||
if not c:
|
||
logger.warning("员工「%s」无工号,跳过接收人解析", r.get("姓名"))
|
||
continue
|
||
d2 = _resolve_dept2(r, all_records, roster_map)
|
||
if not d2:
|
||
# 二级部门为空时不跳过:用「所属单位」列替代作为推送分组依据
|
||
d2 = str(r.get("所属单位") or "").strip()
|
||
if not d2:
|
||
logger.error("员工「%s」无法解析二级部门且无所属单位,不推送该员工",
|
||
r.get("姓名"))
|
||
continue
|
||
dept2_by_code[c] = d2
|
||
codes.append(c)
|
||
if not codes:
|
||
logger.warning("[%s] 命中员工均无法解析二级部门,跳过该推送", tpl["key"])
|
||
continue
|
||
receivers = _resolve_receivers(roster_map, codes, dept2_by_code)
|
||
if TEST_MODE:
|
||
receivers = list(TEST_RECEIVER)
|
||
logger.info("[测试模式] [%s] 接收人覆盖为测试接收人:%s", tpl["key"], TEST_RECEIVER)
|
||
if CC_RECEIVER_ID not in receivers:
|
||
receivers.append(CC_RECEIVER_ID) # 固定抄送人:周卫
|
||
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(branch: str, output_dir: str = None, ym: tuple = None,
|
||
roster_path: str = None) -> dict:
|
||
"""
|
||
按分支生成告知书(Word + PDF)。
|
||
|
||
Args:
|
||
branch: 执行分支,'新参保' 或 '转移参保'(显式传参,不使用环境变量/命令行)
|
||
output_dir: 输出目录,默认 OUTPUT_ROOT
|
||
ym: 目标年月 (year, month),默认当月(数据源文件须为当月,历史月份文件会报错)
|
||
roster_path: 员工花名册路径(社保转移四级部门补全用),默认 ROSTER_PATH
|
||
|
||
Returns:
|
||
{模板名: [输出文件路径, ...]}
|
||
"""
|
||
if branch not in BRANCHES:
|
||
raise ValueError(f"未知分支:{branch},可选 {list(BRANCHES)}")
|
||
rule_keys = BRANCHES[branch]["rule_keys"]
|
||
excel_keyword = BRANCHES[branch]["excel_keyword"]
|
||
output_dir = output_dir or OUTPUT_ROOT
|
||
ym = ym or (datetime.now().year, datetime.now().month)
|
||
y, m = ym
|
||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||
|
||
# 数据源:按分支关键字查找当月文件(历史月份/缺失均报错)
|
||
excel_path = _find_current_month_excel(BASE_DIR, excel_keyword)
|
||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||
|
||
transfer_records, records = [], []
|
||
roster_map = _load_roster_map(excel_path, roster_path or ROSTER_PATH)
|
||
if branch == "转移参保":
|
||
transfer_records = _read_transfer_records(excel_path, roster_map)
|
||
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), excel_path)
|
||
else:
|
||
records = _read_insurance_records(excel_path)
|
||
logger.info("「参保名单」共 %d 条记录", len(records))
|
||
all_records = transfer_records if branch == "转移参保" else records
|
||
|
||
results = {}
|
||
for rule_name in rule_keys:
|
||
rule = TEMPLATES[rule_name]
|
||
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"])]
|
||
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:
|
||
dept2 = _resolve_dept2(rec, all_records, roster_map)
|
||
if not dept2:
|
||
# 二级部门为空时不跳过生成:用「所属单位」列替代作为分组/命名依据
|
||
dept2 = str(rec.get("所属单位") or "").strip()
|
||
if not dept2:
|
||
logger.error("员工「%s」无法解析二级部门且无所属单位,跳过生成",
|
||
rec.get("姓名"))
|
||
continue
|
||
rec["二级部门"] = dept2
|
||
key = (dept2, _trans_org_of(rec))
|
||
groups.setdefault(key, []).append(rec)
|
||
|
||
for (dept2, ins_org), 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}_{ins_org}_{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(branch: str) -> list:
|
||
"""告知书制作与下发(影刀入口):按分支生成当月告知书,并构造 OA 工作沟通推送数据。
|
||
|
||
Args:
|
||
branch: 执行分支,'新参保' 或 '转移参保'(显式传参,不使用环境变量/命令行输入)
|
||
仅接受函数参数显式传递,数据源文件名须为当月(历史月份文件会报错)。
|
||
|
||
Returns:
|
||
工作沟通推送数据列表(每条含 receivers/subject/content/attachment_paths/category),
|
||
与影刀全局变量 messages 内容一致;即使无影刀环境,调用方也可直接用返回值推送。
|
||
"""
|
||
try:
|
||
results = generate_notices(branch)
|
||
messages = build_work_communication_data(branch)
|
||
_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("分支[%s] 共生成 %d 份告知书(docx+pdf),构造 %d 条工作沟通推送数据",
|
||
branch, total, len(messages))
|
||
return messages
|
||
except Exception:
|
||
logger.exception("告知书制作与下发失败")
|
||
_set_glv("notice_error", traceback.format_exc())
|
||
raise
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# 显式指定执行分支:'新参保' 或 '转移参保'(二选一,分别对应不同数据源文件)
|
||
main("转移参保")
|