build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置
- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间 - 新增插件根目录迁移逻辑,解决旧版权限问题 - 新增多个服务端实体、DTO、配置模块等基础代码 - 新增插件 UI 模板及相关静态资源
This commit is contained in:
@@ -1,815 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""告知书制作与下发(XQ0015/XQ0016 notice_mail_merge.py 移植,统一目录版)。
|
||||
|
||||
与名单制作/系统办理共用同一 base_dir 根目录:
|
||||
- 数据源:{base_dir}/*社保变更及增减名单*.xlsx(当前月文件;参保名单 sheet / 变更-* sheet)
|
||||
- 模板:{base_dir}/告知书下发/模板/员工参与社会保险告知书模板.docx、
|
||||
{base_dir}/告知书下发/模板/参保异常告知模板.docx、{base_dir}/告知书下发/模板/社保转移告知模板.docx
|
||||
- 花名册:{base_dir}/员工花名册.xlsx(二级部门解析 + OA 接收人查找)
|
||||
- 输出:{base_dir}/告知书下发/输出/YYYYMM/<告知书类型>/ 下 docx + pdf,并按(二级部门,参保单位)分组合并
|
||||
|
||||
三类告知书:
|
||||
- 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保 & 参保告知空)
|
||||
- 参保异常告知书(办理状态=参保失败 & 参保类型=新参保 & 参保告知空)
|
||||
- 社保转移告知书(变更-* sheet 中 是否变更=是)
|
||||
|
||||
OA 工作沟通推送数据:build_work_communication_data 构造后落盘到
|
||||
{输出}/YYYYMM/oa_messages.json;真实 OA 推送由 __init__ 阶段(启用推送开关时)调 oa_push 完成。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import shutil
|
||||
import random
|
||||
import functools
|
||||
import subprocess
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
|
||||
logger = config.logger
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局重试3次,AGENTS.md) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
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
|
||||
|
||||
|
||||
# ==================== 路径(统一目录 = base_dir) ====================
|
||||
def _base_dir():
|
||||
return config.get_base_dir()
|
||||
|
||||
|
||||
def _output_root():
|
||||
return config.notice_output_root()
|
||||
|
||||
|
||||
def _roster_path():
|
||||
return os.path.join(_base_dir(), "员工花名册.xlsx")
|
||||
|
||||
|
||||
def _template_path(rule_name):
|
||||
rel = config.NOTICE_TEMPLATES[rule_name]["file"]
|
||||
return os.path.join(config.notice_template_dir(), rel)
|
||||
|
||||
|
||||
def _find_current_month_excel(dir_path):
|
||||
"""在目录内查找文件名月份=当月的源名单 xlsx(历史月份/缺失均报错)。"""
|
||||
if not os.path.isdir(dir_path):
|
||||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||||
now = datetime.now()
|
||||
current_ym = (now.year, now.month)
|
||||
kw = config.SOURCE_KEYWORD
|
||||
found = [n for n in os.listdir(dir_path)
|
||||
if kw in n and n.lower().endswith(".xlsx") and not n.startswith("~$")]
|
||||
if not found:
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{kw}」的 xlsx 文件")
|
||||
current = sorted(
|
||||
(n for n in found if _extract_ym(n) == current_ym),
|
||||
key=lambda n: os.path.getmtime(os.path.join(dir_path, n)))
|
||||
if not current:
|
||||
raise FileNotFoundError(
|
||||
f"目录 {dir_path} 下包含「{kw}」的文件均非当前月份 "
|
||||
f"{now.year}年{now.month}月:{found}")
|
||||
return os.path.join(dir_path, current[-1])
|
||||
|
||||
|
||||
# ==================== 基础工具 ====================
|
||||
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:
|
||||
"""按模板规则 + 参保告知为空 判断记录是否命中。"""
|
||||
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月' 两种格式;失败返回 None。"""
|
||||
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)))
|
||||
return None
|
||||
|
||||
|
||||
def _read_insurance_records(excel_path: str) -> list:
|
||||
"""读取「参保名单」sheet,返回人员记录列表(dict,key=表头字段名)。"""
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheet = None
|
||||
for ws in wb.worksheets:
|
||||
if config.SHEET_KEY_ADD in ws.title:
|
||||
sheet = ws
|
||||
break
|
||||
if sheet is None:
|
||||
raise ValueError(f"工作簿 {excel_path} 中未找到包含「{config.SHEET_KEY_ADD}」的 sheet")
|
||||
header = [c.value for c in next(sheet.iter_rows(
|
||||
min_row=config.NOTICE_HEADER_ROW, max_row=config.NOTICE_HEADER_ROW,
|
||||
max_col=config.NOTICE_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}」第{config.NOTICE_HEADER_ROW}行未解析到标准表头")
|
||||
records = []
|
||||
for row in sheet.iter_rows(min_row=config.NOTICE_HEADER_ROW + 1,
|
||||
max_row=sheet.max_row, max_col=config.NOTICE_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,
|
||||
"{{当前月}}": f"{m}",
|
||||
"{{下月}}": f"{next_m}",
|
||||
"{{当月15日}}": f"{m}月15日",
|
||||
"{{制作日年份}}": str(today.year),
|
||||
"{{制作日月份}}": str(today.month),
|
||||
"{{制作日天}}": str(today.day),
|
||||
}
|
||||
|
||||
|
||||
# ==================== Word 占位符替换 ====================
|
||||
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
|
||||
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
|
||||
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 对象(不保存)。"""
|
||||
from docx import Document
|
||||
if not os.path.exists(template_path):
|
||||
raise FileNotFoundError(f"模板不存在:{template_path}")
|
||||
doc = Document(template_path)
|
||||
norm = dict(config.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):
|
||||
"""把多份已填充的告知书 Document 合并为一份(每份之间插入分页符)。"""
|
||||
from docx.enum.text import WD_BREAK
|
||||
from docx.oxml.ns import qn
|
||||
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 "未命名"
|
||||
|
||||
|
||||
# ==================== PDF 转换(优先 WPS COM,失败回退 kwpsconvert 命令行) ====================
|
||||
def _find_kwpsconvert() -> str:
|
||||
"""定位 WPS 自带转换器 kwpsconvert.exe。"""
|
||||
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(兼容 32 位 WPS)。"""
|
||||
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=3)
|
||||
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
|
||||
"""导出 target_pdf:优先 WPS 文字 COM(Kwps.Application),失败自动回退 kwpsconvert。"""
|
||||
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)
|
||||
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:
|
||||
try:
|
||||
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
|
||||
except Exception:
|
||||
doc.SaveAs(target_docx, 12)
|
||||
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
|
||||
finally:
|
||||
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)
|
||||
|
||||
|
||||
# ==================== 花名册与接收人解析 ====================
|
||||
def _norm_code(value):
|
||||
"""工号统一转文本:浮点整数去掉小数部分。"""
|
||||
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:
|
||||
"""读取花名册,返回 {工号: {姓名, 二级部门, 四级部门, 岗位}}。"""
|
||||
import openpyxl
|
||||
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:
|
||||
"""读取社保转移数据(变更-职能及干部/变更-门店 sheet,是否变更=是)。"""
|
||||
import openpyxl
|
||||
roster_map = roster_map or {}
|
||||
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 config.TRANSFER_SHEET_GENERATE):
|
||||
continue
|
||||
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 config.TRANSFER_CHANGE_COL in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
continue
|
||||
|
||||
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, config.TRANSFER_CHANGE_COL) or "").strip() != config.TRANSFER_CHANGE_VALUE:
|
||||
continue
|
||||
rec = {}
|
||||
for src, std in config.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:
|
||||
"""取记录参保单位标识:优先「参保单位」简称,其次全称/当前参保单位。"""
|
||||
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):
|
||||
"""解析记录的正确二级部门(经营中心),优先数据源内参保单位聚合,兜底记录自身/花名册反查。"""
|
||||
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):
|
||||
"""查店长(同四级部门岗位含「店长」,按行序取第一个)。"""
|
||||
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 直接返回;其次石桥铺会馆固定;再兜底岗位含人事。"""
|
||||
info = roster_map.get(code)
|
||||
if not info:
|
||||
return []
|
||||
dept2 = dept2 or info["二级部门"]
|
||||
if dept2 in config.DEPT2_PUSH_OVERRIDE:
|
||||
return list(config.DEPT2_PUSH_OVERRIDE[dept2])
|
||||
if dept2 in config.DEPT2_HR_OVERRIDE:
|
||||
return list(config.DEPT2_HR_OVERRIDE[dept2])
|
||||
if "经营中心" not in dept2:
|
||||
return []
|
||||
return [c for c, it in roster_map.items()
|
||||
if it["二级部门"] == dept2 and "人事" in it["岗位"]]
|
||||
|
||||
|
||||
def _resolve_receivers(roster_map: dict, codes: list, dept2_map: dict = None) -> list:
|
||||
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重。"""
|
||||
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
|
||||
|
||||
|
||||
# ==================== OA 推送数据构造 ====================
|
||||
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(@@R 前缀=右对齐落款)。"""
|
||||
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:
|
||||
"""给文案关键词加颜色高亮(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;
|
||||
接收人=店长+人事并统一追加抄送人)。返回 messages 列表,并落盘 oa_messages.json。"""
|
||||
import json as _json
|
||||
if branch not in config.NOTICE_BRANCHES:
|
||||
raise ValueError(f"未知分支:{branch},可选 {list(config.NOTICE_BRANCHES)}")
|
||||
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())
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,二级部门解析/接收人查找将受限:%s", e)
|
||||
roster_map = {}
|
||||
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
|
||||
|
||||
matched_by_rule = {}
|
||||
if branch == "转移参保":
|
||||
transfer_records = _read_transfer_records(excel_path, roster_map)
|
||||
matched_by_rule["社保转移"] = [
|
||||
r for r in transfer_records if config.TRANSFER_SHEET_PUSH in str(r.get("_source") or "")]
|
||||
logger.info("[社保转移] 命中 %d 人", len(matched_by_rule["社保转移"]))
|
||||
all_records = transfer_records
|
||||
rule_keys = ("社保转移",)
|
||||
else:
|
||||
records = _read_insurance_records(excel_path)
|
||||
all_records = records
|
||||
rule_keys = ("新参保", "参保异常")
|
||||
for rule_name in rule_keys:
|
||||
rule = config.NOTICE_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 config.NOTICE_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, []))
|
||||
attachment_paths = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
attachment_paths.extend(_collect_rule_pdfs(month_dir, config.NOTICE_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:
|
||||
logger.error("员工「%s」无法解析二级部门(参保单位=%s),不推送该员工",
|
||||
r.get("姓名"), _ins_org_of(r))
|
||||
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 config.get_notice_test_mode():
|
||||
receivers = list(config.NOTICE_OA_TEST_RECEIVERS)
|
||||
logger.info("[测试模式] [%s] 接收人覆盖为测试接收人:%s", tpl["key"], receivers)
|
||||
if config.CC_RECEIVER_ID not in receivers:
|
||||
receivers.append(config.CC_RECEIVER_ID)
|
||||
if not receivers:
|
||||
logger.warning("[%s] 未解析到任何接收人(店长/人事),跳过该推送", tpl["key"])
|
||||
continue
|
||||
push_date = datetime.today().strftime("%Y年%m月%d日")
|
||||
content = _highlight_text(
|
||||
tpl["content"].format(y=y, m=m, push_date=push_date),
|
||||
config.NOTICE_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))
|
||||
|
||||
# 落盘推送数据(真实推送由 __init__ 阶段按开关调 oa_push)
|
||||
try:
|
||||
os.makedirs(month_dir, exist_ok=True)
|
||||
json_path = os.path.join(month_dir, "oa_messages.json")
|
||||
with open(json_path, "w", encoding="utf-8") as f:
|
||||
_json.dump(messages, f, ensure_ascii=False, indent=1)
|
||||
logger.info("OA 推送数据已落盘:%s(%d 条)", json_path, len(messages))
|
||||
except Exception as e:
|
||||
logger.warning("OA 推送数据落盘失败(不影响告知书生成):%s", e)
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 主流程:告知书生成 ====================
|
||||
def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""按分支生成告知书(Word + PDF)。返回 {模板名: [输出文件路径, ...]}。"""
|
||||
if branch not in config.NOTICE_BRANCHES:
|
||||
raise ValueError(f"未知分支:{branch},可选 {list(config.NOTICE_BRANCHES)}")
|
||||
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())
|
||||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||||
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or _roster_path())
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,二级部门解析将受限:%s", e)
|
||||
roster_map = {}
|
||||
if branch == "转移参保":
|
||||
transfer_records = _read_transfer_records(excel_path, roster_map)
|
||||
logger.info("社保转移命中 %d 人:%s", len(transfer_records), excel_path)
|
||||
records, all_records = [], transfer_records
|
||||
rule_keys = ("社保转移",)
|
||||
else:
|
||||
records = _read_insurance_records(excel_path)
|
||||
logger.info("「参保名单」共 %d 条记录", len(records))
|
||||
all_records, rule_keys = records, ("新参保", "参保异常")
|
||||
|
||||
results = {}
|
||||
for rule_name in rule_keys:
|
||||
rule = config.NOTICE_TEMPLATES[rule_name]
|
||||
tpl_path = _template_path(rule_name)
|
||||
if not os.path.exists(tpl_path):
|
||||
raise FileNotFoundError(f"模板不存在:{tpl_path}")
|
||||
matched = (transfer_records if rule_name == "社保转移"
|
||||
else [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 人", rule_name, len(matched))
|
||||
groups = {}
|
||||
for rec in matched:
|
||||
dept2 = _resolve_dept2(rec, all_records, roster_map)
|
||||
if not dept2:
|
||||
logger.error("员工「%s」无法解析二级部门(参保单位=%s),跳过生成",
|
||||
rec.get("姓名"), _ins_org_of(rec))
|
||||
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 make_notices():
|
||||
"""告知书制作阶段入口:按配置分支生成告知书 + 构造 OA 推送数据落盘 JSON。
|
||||
|
||||
返回 dict {branch_run, files: {branch: {rule: [files]}}, total,
|
||||
messages, messages_count}。
|
||||
"""
|
||||
branch_cfg = config.get_notice_branch()
|
||||
branches = list(config.NOTICE_BRANCHES) if branch_cfg == "all" else [branch_cfg]
|
||||
results = {}
|
||||
all_messages = []
|
||||
for branch in branches:
|
||||
logger.info("===== 告知书分支:%s =====", branch)
|
||||
files = generate_notices(branch)
|
||||
results[branch] = files
|
||||
try:
|
||||
msgs = build_work_communication_data(branch)
|
||||
all_messages.extend(msgs)
|
||||
except Exception as e:
|
||||
logger.warning("分支[%s] OA 推送数据构造失败(不影响告知书生成):%s", branch, e)
|
||||
total = sum(len(fs) for v in results.values() for fs in v.values())
|
||||
return {"branch_run": branches, "files": results, "total": total,
|
||||
"messages": all_messages, "messages_count": len(all_messages)}
|
||||
Reference in New Issue
Block a user