Files
37duAutomation/plugins/xq0002/report/output.py
T
puddy 843ff244a6 feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
2026-10-26 15:42:50 +08:00

665 lines
31 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0002 插件 - 结果输出层(由影刀版 employer_insurance_schedule.py 阶段3/五点五 与
export_change_sheet.py 合并移植)。
包含:
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
(值+样式,公式转缓存结果,避免 #REF!)。
"""
import os
import re
from copy import copy
import pandas as pd
from openpyxl import Workbook, load_workbook
from ..config import (
logger, DATA_START_ROW, BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME,
category_import_add_file, category_import_sub_file, category_target_file,
category_change_sheet_workbook, category_change_sheet_name,
add_import_template, sub_import_template, today_date,
to_text, clean_text, to_date,
)
from ..logic.schedule import _find_special_slots, scheme_with_suffix
# ============================================================
# 一、输出结果(在参名单 + 变更清单 + 备份 + 姓名修正)
# ============================================================
def output_results(final_records, change_log, reused_source_employees, biz_df,
in_param_df, column_names, target_file, output_backup,
change_sheet_name, change_sheet_prefix, in_param_sheet,
name_corrections=None):
"""输出四部分内容:
1. 更新"手动维护-在参名单"(第17行起B~N列)
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
3. 备份新在参名单
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
"""
# ---------- 1. 构建需要清空的员工ID集合 ----------
emp_ids_to_clear = set()
for rec in final_records:
emp_ids_to_clear.add(rec["证件号"])
emp_ids_to_clear.update(reused_source_employees)
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录)
initial_employee_map = {}
for _, row in in_param_df.iterrows():
emp_id = row.iloc[10]
if pd.isna(emp_id):
continue
orig_scheme = row.iloc[12]
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
initial_employee_map[emp_id] = True
final_emp_ids = set(rec["证件号"] for rec in final_records)
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
special_slots = _find_special_slots(final_records, in_param_df)
special_source_ids = set(s["source_id"] for s in special_slots)
special_src_scheme = {s["source_id"]: s["new_scheme"] for s in special_slots}
if special_slots:
logger.info("特殊情况:离职/参保减少名额被老员工复用,链条末端空闲名额 %d 例(源员工改为空闲方案保留)",
len(special_slots))
for s in special_slots:
logger.info(" 源 %s -> 改为方案 %s", s["source_id"], s["new_scheme"])
# ---------- 2. 保留的行 ----------
handle_col = column_names[17]
emp_id_col = column_names[10]
keep_mask = (
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees))) |
(in_param_df[emp_id_col].isin(special_source_ids)) # 特殊情况源员工保留(改M列为老员工旧方案)
)
kept_df = in_param_df[keep_mask].copy()
kept_emp_ids = set(kept_df[emp_id_col].tolist())
# ---------- 3. 构建员工信息字典 ----------
biz_dict = {}
for idx, row in biz_df.iterrows():
emp_id = row[BIZ_COL_EMPLOYEE_ID]
if pd.notna(emp_id):
biz_dict[emp_id] = row
# ---------- 4. 构建新参保记录(B~N列) ----------
new_records = []
for rec in final_records:
emp_id = rec["证件号"]
if emp_id not in biz_dict:
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
continue
row_biz = biz_dict[emp_id]
new_records.append({
"B": to_text(row_biz.get("工号")), # B列工号必须为文本
"C": row_biz.get("年龄"),
"D": row_biz.get("性别"),
"E": row_biz.get("岗位"),
"F": row_biz.get("职位序列"),
"G": row_biz.get("参保类型"),
"H": row_biz.get("上下班交通方式"),
"I": row_biz.get("入职时间"),
"J": row_biz.get("姓名"),
"K": row_biz.get("证件号"),
"L": row_biz.get("工种类别"),
"M": row_biz.get("投保方案"),
"N": today_date(),
})
# ---------- 5. 打开工作簿 ----------
wb = load_workbook(target_file)
ws = wb[in_param_sheet]
max_row = ws.max_row
# ---------- 6. 读取现有数据 ----------
existing_rows = []
for row_idx in range(DATA_START_ROW, max_row + 1):
row_data = []
for col in range(1, 27):
row_data.append(ws.cell(row=row_idx, column=col).value)
existing_rows.append({
"row_idx": row_idx,
"data": row_data,
"emp_id": ws.cell(row=row_idx, column=11).value, # K列
})
# ---------- 7. 构建新数据列表 ----------
new_rows = []
# 姓名修正映射(证件号 -> 新姓名),保留行 J列姓名统一改为花名册姓名
corr_by_id = {c["emp_id"]: c["new_name"] for c in (name_corrections or [])}
# 7.1 保留行
for row_info in existing_rows:
emp_id = row_info["emp_id"]
if emp_id in kept_emp_ids:
row_data = row_info["data"]
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),N列投保日期更新为今天
if emp_id in special_src_scheme:
row_data[12] = special_src_scheme[emp_id]
row_data[13] = today_date() # N列 投保日期
# 姓名核对修正:J列姓名改为花名册姓名
if emp_id in corr_by_id:
row_data[9] = corr_by_id[emp_id]
new_rows.append({
"row_idx": row_info["row_idx"],
"data": row_data,
"emp_id": emp_id,
"action": "keep",
})
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动;特殊情况源员工已保留,此处不清空)
for row_info in existing_rows:
emp_id = row_info["emp_id"]
if (emp_id in emp_ids_to_clear and emp_id not in special_source_ids) or emp_id is None:
row_data = row_info["data"].copy()
for i in range(1, 14):
row_data[i] = None
new_rows.append({
"row_idx": row_info["row_idx"],
"data": row_data,
"emp_id": None,
"action": "clear",
})
# 7.3 填充新记录到空行
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
empty_slots.sort(key=lambda x: x["row_idx"])
def _fill(row_data, rec):
row_data[1] = rec["B"]
row_data[2] = rec["C"]
row_data[3] = rec["D"]
row_data[4] = rec["E"]
row_data[5] = rec["F"]
row_data[6] = rec["G"]
row_data[7] = rec["H"]
row_data[8] = rec["I"]
row_data[9] = rec["J"]
row_data[10] = rec["K"]
row_data[11] = rec["L"]
row_data[12] = rec["M"]
row_data[13] = rec["N"]
for rec in new_records:
if empty_slots:
slot = empty_slots.pop(0)
row_data = slot["data"]
_fill(row_data, rec)
slot["emp_id"] = rec["K"]
slot["action"] = "filled"
else:
# 追加新行(复制上一行样式)
row_data = [None] * 26
if existing_rows:
src_row_idx = existing_rows[-1]["row_idx"]
for col in range(1, 27):
src_cell = ws.cell(row=src_row_idx, column=col)
dst_cell = ws.cell(row=max_row + 1, column=col)
if src_cell.has_style:
dst_cell.font = copy(src_cell.font)
dst_cell.border = copy(src_cell.border)
dst_cell.fill = copy(src_cell.fill)
dst_cell.number_format = src_cell.number_format
dst_cell.alignment = copy(src_cell.alignment)
last_row_data = existing_rows[-1]["data"]
for i in range(14, 26):
row_data[i] = last_row_data[i]
_fill(row_data, rec)
new_rows.append({
"row_idx": None,
"data": row_data,
"emp_id": rec["K"],
"action": "append",
})
# ---------- 8. 更新现有行(B~N列,列号=索引+1;B列工号强制文本) ----------
for row_info in new_rows:
if row_info["row_idx"] is not None:
row_idx = row_info["row_idx"]
row_data = row_info["data"]
for idx in range(1, 14):
c = ws.cell(row=row_idx, column=idx + 1)
if idx == 1:
c.value = to_text(row_data[idx])
c.number_format = "@"
else:
c.value = row_data[idx]
# ---------- 9. 追加新行 ----------
current_row = max_row + 1
for row_info in new_rows:
if row_info["row_idx"] is None:
row_idx = current_row
row_data = row_info["data"]
for col_idx, value in enumerate(row_data, start=1):
c = ws.cell(row=row_idx, column=col_idx)
if col_idx == 2:
c.value = to_text(value)
c.number_format = "@"
else:
c.value = value
current_row += 1
# ---------- 9.5 紧凑化:消除中间空行(只搬移 B~O 数据列,公式列 R/S/T/U/V/W 不动) ----------
data_values = []
for row_idx in range(DATA_START_ROW, current_row):
has_data = any(
ws.cell(row=row_idx, column=c).value not in (None, "")
for c in range(2, 16)
)
if has_data:
data_values.append([ws.cell(row=row_idx, column=c).value for c in range(2, 16)])
target_row = DATA_START_ROW
for vals in data_values:
for col, v in enumerate(vals, start=2):
cell = ws.cell(row=target_row, column=col)
if col == 2: # B列 工号 强制文本
cell.value = to_text(v)
cell.number_format = "@"
elif col == 14: # N列 投保日期 -> 日期类型 + yyyy-mm-dd
cell.value = to_date(v)
if cell.value is not None:
cell.number_format = "yyyy-mm-dd"
else:
cell.value = v
target_row += 1
# 清空多出部分的 B~O 列(公式列不动)
for row_idx in range(target_row, current_row):
for col in range(2, 16):
ws.cell(row=row_idx, column=col).value = None
# ---------- 10. 重新编号A列 ----------
seq = 1
for row_idx in range(DATA_START_ROW, current_row):
if ws.cell(row=row_idx, column=11).value is not None:
ws.cell(row=row_idx, column=1).value = seq
seq += 1
else:
ws.cell(row=row_idx, column=1).value = None
# ============================================================
# ★★★ 11. 精细更新变更清单 ★★★
# ============================================================
if change_sheet_name not in wb.sheetnames:
# 收集所有以类别变更清单前缀开头、且不是当前目标名的Sheet作为候选模板
candidates = [
name for name in wb.sheetnames
if name.startswith(change_sheet_prefix) and name != change_sheet_name
]
def _template_sort_key(name):
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
template_name = max(candidates, key=_template_sort_key) if candidates else None
if template_name is not None:
# 复制最近一次的历史模板Sheet(保留公式与样式)
source = wb[template_name]
target = wb.copy_worksheet(source)
target.title = change_sheet_name
logger.info("已从模板 [%s] 复制变更清单", template_name)
else:
# 没有任何历史模板,创建新Sheet(兜底)
ws_change = wb.create_sheet(change_sheet_name)
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
"工作单位", "", "备注", "批改日期", "新增费用会馆",
"姓名", "证件号", "工种类别", "投保方案"]
for col_idx, h in enumerate(headers, start=1):
ws_change.cell(row=1, column=col_idx).value = h
ws_change.cell(row=2, column=1).value = "公式"
ws_change = wb[change_sheet_name]
else:
ws_change = wb[change_sheet_name]
# ---------- 定位 O列(费用会馆/四级部门列)----------
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
DEPT_COL_MARK = "费用会馆"
dept_col = 15
for _col in range(1, 21):
if any(DEPT_COL_MARK in str(ws_change.cell(row=_row, column=_col).value or "")
for _row in (1, 2)):
dept_col = _col
break
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
max_row_change = ws_change.max_row
if max_row_change >= 3:
for row in range(3, max_row_change + 1):
ws_change.cell(row=row, column=2).value = None # B列
ws_change.cell(row=row, column=13).value = None # M列 备注
ws_change.cell(row=row, column=14).value = None # N列
ws_change.cell(row=row, column=dept_col).value = None # 四级部门列
for col in range(16, 20): # P~S列
ws_change.cell(row=row, column=col).value = None
# 收集变更记录
records = []
# 1. 删除记录(特殊情况源员工一并输出"增加老员工旧方案",保证增减平衡)
for emp_id in emp_ids_to_clear:
if emp_id in final_emp_ids:
continue
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
if not row_match.empty:
row = row_match.iloc[0]
name = row.iloc[9]
category = row.iloc[11]
scheme = row.iloc[12]
records.append({"op": "删除", "name": name, "emp_id": emp_id,
"category": category, "scheme": scheme})
# 特殊情况:源员工名额被老员工复用且老员工旧名额无人复用 -> 源员工改为该旧方案
if emp_id in special_src_scheme:
records.append({"op": "增加", "name": name, "emp_id": emp_id,
"category": category, "scheme": special_src_scheme[emp_id]})
else:
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
"category": "未知", "scheme": "未知"})
# 2. 增加记录。档次替换仅当「自己的名额档次替换、不涉及其他人」时合并为一条「修改」
# 收集「自己的旧名额被他人复用」的员工集合(来源员工ID)
reused_by_others = set()
for _rec in final_records:
_sid = _rec.get("来源员工ID")
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
reused_by_others.add(_sid)
for rec in final_records:
emp_id = rec["证件号"]
if emp_id in biz_dict:
row_biz = biz_dict[emp_id]
name = row_biz.get("姓名")
category = row_biz.get("工种类别")
scheme = row_biz.get("投保方案")
else:
name = category = scheme = None
if emp_id in initial_employee_map:
# 原已参保(档次替换):仅"自己的名额档次替换、不涉及其他人"才合并为「修改」
pure_self_replace = (
rec.get("名额来源") == "全新新增" and
emp_id not in reused_by_others
)
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
old_scheme = None
if not row_match.empty:
old_scheme = row_match.iloc[0].iloc[12]
if pure_self_replace:
remark = None
if old_scheme is not None and str(old_scheme).strip() != "" and \
scheme is not None and str(scheme).strip() != "":
remark = f"由{old_scheme}替换为{scheme}"
records.append({"op": "修改", "name": name, "emp_id": emp_id,
"category": category, "scheme": scheme, "remark": remark})
else:
# 涉及其他人的档次替换:正常两条(删除旧方案 + 增加新方案)
records.append({"op": "删除", "name": name, "emp_id": emp_id,
"category": category, "scheme": old_scheme})
records.append({"op": "增加", "name": name, "emp_id": emp_id,
"category": category, "scheme": scheme})
else:
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 O列 填四级部门
new_rec = {"op": "增加", "name": name, "emp_id": emp_id,
"category": category, "scheme": scheme}
if rec.get("名额来源") == "全新新增":
biz_row_dept = biz_dict.get(emp_id)
dept = clean_text(biz_row_dept.get(biz_dept_col)) if biz_row_dept is not None else None
if dept is None:
# 四级部门为空:回退填所属单位,并记录日志供人工核对
dept = clean_text(biz_row_dept.get("所属单位")) if biz_row_dept is not None else None
logger.warning("员工 %s(%s) 花名册四级部门为空,O列回退填所属单位:%s",
name, emp_id, dept)
new_rec["dept"] = dept
records.append(new_rec)
# 写入新记录
current_row_change = 3
for rec in records:
op = rec.get("op")
name = rec.get("name")
emp_id = rec.get("emp_id")
category = rec.get("category")
scheme = rec.get("scheme")
if name is None or emp_id is None or category is None or scheme is None:
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
continue
ws_change.cell(row=current_row_change, column=2).value = op # B列
ws_change.cell(row=current_row_change, column=13).value = rec.get("remark") # M列 备注
ws_change.cell(row=current_row_change, column=14).value = today_date() # N列
# 四级部门列:仅纯新增名额(全新新增)的「增加」记录才填
if op == "增加" and rec.get("dept") is not None:
ws_change.cell(row=current_row_change, column=dept_col).value = rec.get("dept")
ws_change.cell(row=current_row_change, column=16).value = name # P列
ws_change.cell(row=current_row_change, column=17).value = emp_id # Q列
ws_change.cell(row=current_row_change, column=18).value = category # R列
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
current_row_change += 1
# 3. 姓名修正记录(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
for corr in (name_corrections or []):
ws_change.cell(row=current_row_change, column=2).value = "修改"
ws_change.cell(row=current_row_change, column=13).value = \
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}"
ws_change.cell(row=current_row_change, column=14).value = today_date()
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"]
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"]
ws_change.cell(row=current_row_change, column=18).value = corr.get("category")
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme")
current_row_change += 1
# ---------- 12. 保存工作簿 ----------
wb.save(target_file)
# ---------- 13. 备份新在参名单 ----------
df_final = pd.DataFrame(final_records)
df_final.to_excel(output_backup, index=False)
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
logger.info("变更清单已精细更新(共 %d 条变更记录,含 %d 条姓名修正)",
len(records) + len(name_corrections or []), len(name_corrections or []))
logger.info("备份新在参名单已保存:%s", output_backup)
# ============================================================
# 二、生成增员/减员导入文件(HR「待增减人员」页面上传素材)
# ============================================================
def _write_import_file(template_path, out_path, rows):
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。"""
if not os.path.isfile(template_path):
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
wb = load_workbook(template_path)
ws = wb[wb.sheetnames[0]]
for i, row_vals in enumerate(rows):
excel_row = 4 + i
for col_idx, val in enumerate(row_vals, start=1):
c = ws.cell(row=excel_row, column=col_idx)
if col_idx == 2: # 工号/身份证列强制文本
c.value = to_text(val)
c.number_format = "@"
else:
c.value = val
wb.save(out_path)
logger.info("已生成导入文件:%s(%d 条)", out_path, len(rows))
def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees):
"""生成各类别「商业保险增员导入.xlsx / 商业保险减员导入.xlsx」(HR 上传素材)。
集合差模型:按「人 + 投保方案」记录级做差:
- 减员 = 原参保记录 − 新参保记录
- 增员 = 新参保记录 − 原参保记录
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
若先增员会因人员方案冲突直接报错。
"""
# ---------- 1. 原参保记录集合 ----------
orig_records = {} # to_text(证件号) -> 方案
for _, row in in_param_df.iterrows():
emp_id = row.iloc[10]
if pd.isna(emp_id):
continue
scheme = row.iloc[12]
if pd.isna(scheme) or str(scheme).strip() == "":
continue
orig_records[to_text(emp_id)] = scheme
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录 + 特殊情况保留源员工) ----------
cleared_ids = set(to_text(e) for e in reused_source_employees)
cleared_ids.update(to_text(rec["证件号"]) for rec in final_records)
new_records_map = {
emp_id: scheme for emp_id, scheme in orig_records.items()
if emp_id not in cleared_ids
}
for rec in final_records:
new_records_map[to_text(rec["证件号"])] = rec["投保方案"]
# 特殊情况源员工(离职/参保减少名额被复用后保留在参名单,方案改为空闲方案):
# 纳入"新参保记录"参与集合差,保证减员/增员对称、不漏人
special_slots = _find_special_slots(final_records, in_param_df)
for _s in special_slots:
new_records_map[to_text(_s["source_id"])] = _s["new_scheme"]
# ---------- 3. 记录级集合差:减员名单 ----------
sub_ids = [
emp_id for emp_id, orig_scheme in orig_records.items()
if emp_id not in new_records_map or new_records_map[emp_id] != orig_scheme
]
# ---------- 4. 员工信息查询(biz_df 优先,其次 in_param_df) ----------
emp_info = {} # to_text(证件号) -> {"工号": ..., "姓名": ...}
for _, row in in_param_df.iterrows():
emp_id = row.iloc[10]
if pd.isna(emp_id):
continue
emp_info[to_text(emp_id)] = {"工号": to_text(row.iloc[1]), "姓名": row.iloc[9]}
for _, row in biz_df.iterrows():
emp_id = row[BIZ_COL_EMPLOYEE_ID]
if pd.isna(emp_id):
continue
emp_info[to_text(emp_id)] = {"工号": to_text(row.get("工号")), "姓名": row.get("姓名")}
def _code(emp_id):
"""工号/身份证列:优先工号,空则回退证件号。"""
return clean_text(emp_info.get(emp_id, {}).get("工号")) or clean_text(emp_id)
def _name(emp_id):
return clean_text(emp_info.get(emp_id, {}).get("姓名"))
# ---------- 5. 组装行数据 ----------
sub_rows, skipped_sub = [], 0
for i, emp_id in enumerate(sub_ids, start=1):
name = _name(emp_id)
if not name:
skipped_sub += 1
logger.warning("减员:员工 %s 缺少姓名,跳过", emp_id)
continue
sub_rows.append([i, _code(emp_id), name, today_date()])
add_rows, skipped_add, seq = [], 0, 0
for rec in final_records:
emp_id = to_text(rec["证件号"])
name = _name(emp_id)
if not name:
skipped_add += 1
logger.warning("增员:员工 %s 缺少姓名,跳过", emp_id)
continue
seq += 1
add_rows.append([seq, _code(emp_id), name,
scheme_with_suffix(category, rec["投保方案"]), today_date(),
rec.get("名额来源") or "新增"])
# 特殊情况源员工(保留在参名单,方案改为空闲方案)也需增员(新增该方案),不漏人
for _s in special_slots:
emp_id = to_text(_s["source_id"])
new_scheme = _s["new_scheme"]
# 方案未变(极少见边界)则无需增员
if emp_id in orig_records and orig_records[emp_id] == new_scheme:
continue
name = _name(emp_id)
if not name:
skipped_add += 1
logger.warning("增员:特殊情况源员工 %s 缺少姓名,跳过", emp_id)
continue
seq += 1
add_rows.append([seq, _code(emp_id), name,
scheme_with_suffix(category, new_scheme), today_date(),
"特殊情况保留名额"])
# ---------- 6. 写入模板(保留第1~3行,第4行起填数据) ----------
_write_import_file(sub_import_template(), category_import_sub_file(category), sub_rows)
_write_import_file(add_import_template(), category_import_add_file(category), add_rows)
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
# ============================================================
# 三、导出变更清单独立工作簿(值 + 样式,公式转缓存结果)
# ============================================================
def export_change_sheet_workbook(category):
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
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
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