feat: 新增社保告知书制作下发全流程模块
1. 新增参保/停保告知书生成模块,支持按模板批量生成Word+PDF 2. 新增社保转移告知书独立数据源处理逻辑 3. 新增OA工作沟通推送数据自动构造能力 4. 重构雇主险模块,拆分变更清单导出为独立文件 5. 新增花名册查询工具模块,支持店长/人事批量查询 6. 更新项目文档与README说明
This commit is contained in:
@@ -70,7 +70,6 @@ from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_output_backup,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
category_import_add_file,
|
||||
category_import_sub_file,
|
||||
@@ -924,63 +923,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
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五点五、生成增减员导入文件(阶段4:步骤3上传素材)
|
||||
# ============================================================
|
||||
@@ -1221,14 +1163,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上传素材) ----------
|
||||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.export_change_sheet
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统(app 版)「步骤2.5:导出变更清单独立工作簿」
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
【运行】python export_change_sheet.py [类别名]
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from copy import copy # noqa: E402
|
||||
from openpyxl import Workbook, load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
CATEGORIES,
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
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_name: str = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
@@ -0,0 +1,317 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.roster.roster_query
|
||||
@FileName: roster_query.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 花名册共享查询模块 —— 根据员工工号查询:
|
||||
1. 店长查询:返回其所在四级部门的店长工号与姓名(岗位含「店长」,多个取第一个);
|
||||
2. 人事查询:返回其所在经营中心(二级部门含「经营中心」)岗位含「人事」的全部名单;
|
||||
特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(梁敏/37001302),不查花名册。
|
||||
两类查询均支持批量(花名册只读一次)。供「告知书制作与下发」等业务流程复用。
|
||||
@Version: 1.2.0
|
||||
|
||||
使用方式(库函数,参数直接传):
|
||||
from app.service.hrbp.ehr.roster.roster_query import (
|
||||
find_store_manager, find_store_manager_batch,
|
||||
find_hr_personnel, find_hr_personnel_batch)
|
||||
- find_store_manager(工号, 花名册路径) -> {"success", "error", "manager_code", "manager_name"}
|
||||
- find_hr_personnel(工号, 花名册路径) -> {"success", "error", "dept", "personnel": [{"工号","姓名"}, ...]}
|
||||
- 批量:find_*_batch(工号列表, 花名册路径) -> {工号: 对应单查结果, ...}
|
||||
"""
|
||||
|
||||
import numbers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
from app.utils.logger import get_logger # noqa: E402
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 默认花名册路径(告知书制作与下发)
|
||||
DEFAULT_ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx"
|
||||
|
||||
# 花名册字段列名(与 aa.md 字段一致)
|
||||
COL_NAME = "姓名" # 姓名
|
||||
COL_CODE = "工号" # 工号
|
||||
COL_DEPT2 = "二级部门" # 二级部门(经营中心)
|
||||
COL_DEPT4 = "四级部门" # 四级部门
|
||||
COL_POSITION = "岗位" # 岗位
|
||||
|
||||
# 岗位关键字(岗位字段包含对应关键字即视为该岗位)
|
||||
MANAGER_KEYWORD = "店长" # 店长岗位关键字
|
||||
HR_KEYWORD = "人事" # 人事岗位关键字
|
||||
DEPT2_MARK = "经营中心" # 二级部门需包含的经营中心标记
|
||||
|
||||
# 人事查询特殊分支:二级部门为「石桥铺会馆」时,不查花名册,直接返回固定人事名单
|
||||
DEPT2_HR_OVERRIDE = {
|
||||
"石桥铺会馆": [{"工号": "37001302", "姓名": "梁敏"}],
|
||||
}
|
||||
|
||||
|
||||
# ==================== 工具函数 ====================
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致匹配失败。
|
||||
|
||||
整型 float(如 37036835.0)去掉小数点后转 str,保证与文本工号("37036835")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def _read_roster(roster_path):
|
||||
"""读取花名册,自动定位表头行(含「工号」列的行),返回 DataFrame(列名为字段名)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径
|
||||
|
||||
Returns:
|
||||
pd.DataFrame
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件不存在
|
||||
ValueError: 未找到表头行或缺少必需列(工号/姓名/二级部门/四级部门/岗位)
|
||||
"""
|
||||
roster_path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
|
||||
# 先不设表头读取前几行,定位含「工号」字段的表头行
|
||||
probe = pd.read_excel(roster_path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{roster_path}")
|
||||
|
||||
df = pd.read_excel(roster_path, header=header_row)
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT2, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({roster_path})")
|
||||
return df
|
||||
|
||||
|
||||
def _prepare_df(df):
|
||||
"""统一工号列文本格式并过滤空行,返回预处理后的 DataFrame(副本)。"""
|
||||
df = df.copy()
|
||||
df[COL_CODE] = df[COL_CODE].map(_to_text)
|
||||
return df[df[COL_CODE].notna()]
|
||||
|
||||
|
||||
# ==================== 核心查询 ====================
|
||||
def _find_store_manager_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询店长(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 2. 根据工号查四级部门
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
|
||||
# 3. 无四级部门 -> 返回查询失败、空结果
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门", code)
|
||||
return {"success": False, "error": f"员工(工号 {code})无四级部门",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 4. 在该四级部门内找岗位包含「店长」的人
|
||||
candidates = df[
|
||||
(df[COL_DEPT4].map(_to_text) == dept4)
|
||||
& (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))
|
||||
]
|
||||
if candidates.empty:
|
||||
logger.warning("四级部门「%s」内未找到店长(工号 %s)", dept4, code)
|
||||
return {"success": False, "error": f"四级部门「{dept4}」内未找到店长",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
# 5. 命中多个时取第一个(按花名册行序)
|
||||
first = candidates.iloc[0]
|
||||
manager_code = _to_text(first[COL_CODE])
|
||||
manager_name = _to_text(first[COL_NAME]) or ""
|
||||
logger.info("工号 %s -> 四级部门「%s」-> 店长 %s(工号 %s)",
|
||||
code, dept4, manager_name, manager_code)
|
||||
return {"success": True, "error": None,
|
||||
"manager_code": manager_code, "manager_name": manager_name}
|
||||
|
||||
|
||||
def _find_hr_personnel_in_df(df, code):
|
||||
"""在已读取的花名册 DataFrame 中查询经营中心人事名单(不读文件)。"""
|
||||
# 1. 校验工号是否存在
|
||||
row = df[df[COL_CODE] == code]
|
||||
if row.empty:
|
||||
logger.warning("工号不存在:%s", code)
|
||||
return {"success": False, "error": f"工号不存在:{code}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
# 2. 校验二级部门
|
||||
dept2 = _to_text(row.iloc[0][COL_DEPT2]) or ""
|
||||
|
||||
# 2.1 特殊分支:二级部门为「石桥铺会馆」时直接返回固定人事名单(不查花名册)
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
personnel = [dict(p) for p in DEPT2_HR_OVERRIDE[dept2]]
|
||||
logger.info("工号 %s -> 二级部门「%s」-> 固定人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
if DEPT2_MARK not in dept2:
|
||||
logger.warning("员工(工号 %s)二级部门「%s」不包含「%s」", code, dept2, DEPT2_MARK)
|
||||
return {"success": False, "error": f"员工(工号 {code})二级部门不包含「{DEPT2_MARK}」",
|
||||
"dept": dept2 or None, "personnel": []}
|
||||
|
||||
# 3. 查询该经营中心下岗位包含「人事」的所有名单
|
||||
candidates = df[
|
||||
(df[COL_DEPT2].map(_to_text) == dept2)
|
||||
& (df[COL_POSITION].astype(str).str.contains(HR_KEYWORD, na=False))
|
||||
]
|
||||
personnel = [
|
||||
{"工号": _to_text(r[COL_CODE]), "姓名": _to_text(r[COL_NAME]) or ""}
|
||||
for _, r in candidates.iterrows()
|
||||
]
|
||||
logger.info("工号 %s -> 经营中心「%s」-> 人事 %d 人", code, dept2, len(personnel))
|
||||
return {"success": True, "error": None, "dept": dept2, "personnel": personnel}
|
||||
|
||||
|
||||
def _error_result(code, e):
|
||||
"""读取花名册失败时的统一错误结果(店长/人事两种结构)。"""
|
||||
return {
|
||||
"store": {"success": False, "error": str(e),
|
||||
"manager_code": None, "manager_name": None},
|
||||
"hr": {"success": False, "error": str(e), "dept": None, "personnel": []},
|
||||
}
|
||||
|
||||
|
||||
def find_store_manager(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在四级部门的店长工号与姓名(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int,如 "37036835" / 37036835)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 无四级部门 / 部门内无店长 / 读取异常)
|
||||
manager_code: str|None 店长工号
|
||||
manager_name: str|None 店长姓名
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"manager_code": None, "manager_name": None}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["store"]
|
||||
return _find_store_manager_in_df(df, code)
|
||||
|
||||
|
||||
def find_store_manager_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号的店长(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_store_manager 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["store"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_store_manager_in_df(df, _to_text(c)) for c in codes}
|
||||
|
||||
|
||||
def find_hr_personnel(code, roster_path=None):
|
||||
"""根据员工工号,返回其所在经营中心(二级部门)岗位包含「人事」的全部名单(单查)。
|
||||
|
||||
Args:
|
||||
code: 员工工号(str 或 int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict:
|
||||
success: bool 是否查询成功
|
||||
error: str|None 失败原因(工号不存在 / 二级部门不包含经营中心 / 读取异常)
|
||||
dept: str|None 二级部门(经营中心)
|
||||
personnel: list 人事名单 [{"工号": str, "姓名": str}, ...]
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return {"success": False, "error": f"工号为空:{code!r}",
|
||||
"dept": None, "personnel": []}
|
||||
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
return _error_result(code, e)["hr"]
|
||||
return _find_hr_personnel_in_df(df, code)
|
||||
|
||||
|
||||
def find_hr_personnel_batch(codes, roster_path=None):
|
||||
"""批量查询多个工号所在经营中心的人事名单(花名册只读一次)。
|
||||
|
||||
Args:
|
||||
codes: 工号列表(str/int)
|
||||
roster_path: 员工花名册路径,默认 DEFAULT_ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
dict: {工号: find_hr_personnel 的返回结果, ...}
|
||||
"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
try:
|
||||
df = _prepare_df(_read_roster(roster_path))
|
||||
except Exception as e:
|
||||
logger.error("读取花名册失败:%s", e)
|
||||
err = _error_result(None, e)["hr"]
|
||||
return {_to_text(c): dict(err) for c in codes}
|
||||
return {_to_text(c): _find_hr_personnel_in_df(df, _to_text(c)) for c in codes}
|
||||
@@ -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