feat: 新增社保告知书制作下发全流程模块
1. 新增参保/停保告知书生成模块,支持按模板批量生成Word+PDF 2. 新增社保转移告知书独立数据源处理逻辑 3. 新增OA工作沟通推送数据自动构造能力 4. 重构雇主险模块,拆分变更清单导出为独立文件 5. 新增花名册查询工具模块,支持店长/人事批量查询 6. 更新项目文档与README说明
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_notice
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发模块(读取参保/停保名单 → 按模板批量生成 Word 告知书并转 PDF)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +1,824 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.social_notice
|
||||
@FileName: notice_mail_merge.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发 —— 参保/停保名单 → 按模板生成告知书(Word + PDF)
|
||||
读取《{YYYYMM}参保与停保名单.xlsx》中「参保名单」sheet(表头第3行),
|
||||
按三类模板规则筛选当月人员,逐人生成 Word 告知书并转 PDF:
|
||||
- 模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
|
||||
- 模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
|
||||
- 模板3 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
|
||||
公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月。
|
||||
输出命名:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份,
|
||||
文件名 = 二级部门_四级部门_告知书类型.docx/pdf,同一部门内多人逐页排列。
|
||||
OA 工作沟通推送:根据命中员工工号查询店长/人事,构造 2 条推送数据
|
||||
(员工参与社会保险+参保异常合并一条、社保转移单独一条)。
|
||||
占位符约定:模板中仅允许纯变量占位符(如 {{姓名}}、{{下月}}、{{一次性扣款}}),
|
||||
不支持 {{当前月+1}} / {{费用*2}} 这类带表达式的写法(脚本会自动兼容旧写法)。
|
||||
PDF 转换:走 WPS 文字 COM(Kwps.Application),兼容未安装 MS Word 的环境。
|
||||
@Version: 1.4.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
# 保证无论以何种方式(直接运行 / IDE / 模块方式)运行都能导入 app 包:
|
||||
# 从脚本位置向上定位到项目根目录并注入 sys.path。
|
||||
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
|
||||
import openpyxl
|
||||
from docx import Document
|
||||
from docx.enum.text import WD_BREAK
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
DEFAULT_ROSTER_PATH,
|
||||
find_hr_personnel_batch,
|
||||
find_store_manager_batch,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("notice_mail_merge")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 配置区(按需修改,禁止命令行传参)
|
||||
# ------------------------------------------------------------------
|
||||
BASE_DIR = r"D:\资料\人资\告知书制作与下发"
|
||||
OUTPUT_ROOT = 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 # 全局重试次数(AGENTS.md:最大重试3次)
|
||||
|
||||
# 社保转移数据源(社保变更人员名单):替代「参保与停保名单」中的转移参保
|
||||
TRANSFER_EXCEL_KEYWORD = "社保变更人员名单" # 数据源文件名关键字
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
|
||||
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
|
||||
TRANSFER_CHANGE_COL = "是否变更" # 筛选列
|
||||
TRANSFER_CHANGE_VALUE = "是" # 筛选值
|
||||
# 列名映射:社保变更名单列名 -> 标准列名(模板占位符依赖标准列名)
|
||||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||||
|
||||
# ---- OA 工作沟通推送数据构造 ----
|
||||
# 二级部门 -> 固定人事工号(与 roster_query.DEPT2_HR_OVERRIDE 保持一致,石桥铺会馆不查花名册)
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]}
|
||||
|
||||
# 工作沟通推送配置: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 文件。"""
|
||||
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 对象(不保存)。"""
|
||||
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 环境)
|
||||
# ------------------------------------------------------------------
|
||||
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
|
||||
"""用 WPS 打开 src_docx,另存为 target_docx 并导出 target_pdf(可写入受限目录)。"""
|
||||
import win32com.client
|
||||
|
||||
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)
|
||||
|
||||
for attempt in range(1, RETRY_TIMES + 1):
|
||||
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)
|
||||
return
|
||||
except Exception:
|
||||
logger.exception("WPS 转换失败(第 %d/%d 次): %s -> %s", attempt, RETRY_TIMES, src_docx, target_pdf)
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == RETRY_TIMES:
|
||||
raise
|
||||
raise RuntimeError(f"WPS 转换失败:{src_docx}")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 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 _resolve_receivers_batch(roster_path, codes) -> list:
|
||||
"""用花名册批量查询为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。"""
|
||||
store_results = find_store_manager_batch(codes, roster_path)
|
||||
hr_results = find_hr_personnel_batch(codes, roster_path)
|
||||
receivers = []
|
||||
for code in codes:
|
||||
sr = store_results.get(code, {})
|
||||
mgr = sr.get("manager_code") if sr.get("success") else None
|
||||
if mgr and mgr not in receivers:
|
||||
receivers.append(mgr)
|
||||
for p in hr_results.get(code, {}).get("personnel", []):
|
||||
pc = p.get("工号")
|
||||
if pc and pc not in receivers:
|
||||
receivers.append(pc)
|
||||
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。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT(须先执行 generate_notices 生成 PDF)
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_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 DEFAULT_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 DEFAULT_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))
|
||||
|
||||
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_batch(roster_path, codes)
|
||||
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))
|
||||
|
||||
logger.info("构造完成:%d 条工作沟通推送数据", len(messages))
|
||||
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: 员工花名册路径(社保转移四级部门补全用),默认 DEFAULT_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 DEFAULT_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() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-7s | %(message)s")
|
||||
generate_notices()
|
||||
messages = build_work_communication_data()
|
||||
logger.info("共构造 %d 条工作沟通推送数据", len(messages))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user