1650 lines
74 KiB
Python
1650 lines
74 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: employer_insurance_schedule.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-13
|
||
@Description: 雇主险名额调度系统「步骤2:调度」
|
||
@Version: 1.4.0
|
||
- v1.4.0:调度前自动前置处理——经 WPS/Excel COM 打开目标文件,取消所有 sheet 的
|
||
筛选(AutoFilterMode=False,杜绝筛选状态下人工删贴数据错位、筛选残留),
|
||
全量重算公式(CalculateFullRebuild,替代人工打开 Ctrl+S 刷新)后保存关闭。
|
||
新增依赖 pywin32;目标文件若已在 WPS/Excel 中打开则复用当前工作簿保存。
|
||
- v1.3.0:变更清单「费用会馆」列(表头含"费用会馆"即可,如 O列 新增费用会馆)
|
||
自动填充四级部门——按证件号关联「花名册导出-雇主险使用基础信息」中
|
||
表头含"四级部门"的列,仅「纯新增名额」(全新新增)的 增加 记录填写;
|
||
当日一增一减(复用离职/参保减少/替换迁出释放的名额)及名额替换
|
||
(修改/删除+增加对)均不填;四级部门为空时回退填「所属单位」并记日志。
|
||
- v1.2.0:
|
||
1) 变更清单「修改」仅用于"自己的名额档次替换、不涉及其他人"(未复用他人名额
|
||
且自己的旧名额未被他人复用);涉及他人的替换输出正常两条(删除+增加)。
|
||
2) 特殊情况源员工(离职/参保减少被复用后保留占位)写入参名单时补写 N列投保日期;
|
||
增员导入文件同样包含该源员工(新增空闲方案),不漏人。
|
||
3) 增减员执行顺序:必须先执行【减员】导入,再执行【增员】导入,否则替换/修改
|
||
人员先增员会因方案冲突直接报错。
|
||
- v1.1.0:增员导入「保险方案名称」按类别追加厂区后缀(秒创/湖畔/水庄,
|
||
三十七度无后缀),与 HR 侧带后缀方案列表对齐。
|
||
|
||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||
pip install pandas openpyxl pywin32
|
||
|
||
环境变量(.env 文件或系统变量,可选):
|
||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||
|
||
运行:直接执行本文件即可完成全部类别调度;仅处理部分类别时以列表传参调用
|
||
main(category_names=['湖畔酒店']) 或 schedule_category(category)
|
||
"""
|
||
|
||
# ==================== 标准库导入 ====================
|
||
import numbers
|
||
import os
|
||
import re
|
||
import traceback
|
||
from collections import defaultdict
|
||
from copy import copy
|
||
from datetime import datetime, date
|
||
|
||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||
try:
|
||
import pandas as pd
|
||
from openpyxl import Workbook, load_workbook
|
||
import pythoncom
|
||
import win32com.client
|
||
except ImportError as _import_err:
|
||
raise RuntimeError(
|
||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||
"请先执行安装:\n"
|
||
" pip install pandas openpyxl pywin32\n"
|
||
f"缺失依赖详情: {_import_err}"
|
||
)
|
||
|
||
|
||
# ==================== 日志(print 替代 logging) ====================
|
||
class _PrintLogger:
|
||
def debug(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def info(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def warning(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def error(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
|
||
def exception(self, msg, *args, **kwargs):
|
||
print(msg % args if args else msg)
|
||
traceback.print_exc()
|
||
|
||
|
||
logger = _PrintLogger()
|
||
|
||
|
||
# ==================== 路径 & 常量配置(与 app 版 config 一致) ====================
|
||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||
# 变更清单 sheet 名沿用历史模板命名:无横线、月/日不补前导零(如 8.19 / 8.1)
|
||
DATE_SHORT = f"{datetime.now().month}.{datetime.now().day}"
|
||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||
|
||
# 固定 Sheet 名称
|
||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||
|
||
# ---------- 四大类别(全流程按类别传参处理,与 app 版 config.CATEGORIES 一致) ----------
|
||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」;
|
||
# change_sheet_prefix: 各类「变更清单」sheet 名称前缀(须统一该命名规则);
|
||
# scheme_suffix: 增员导入时「保险方案名称」追加的厂区后缀(HR 侧方案含后缀,
|
||
# 如 人保-80万-秒创 / 人保-80万-湖畔 / 人保-80万-水庄;三十七度无后缀)。
|
||
CATEGORIES = [
|
||
{
|
||
"name": "三十七度",
|
||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||
"change_sheet_prefix": "37度-雇员变更清单",
|
||
"scheme_suffix": "",
|
||
},
|
||
{
|
||
"name": "水庄餐饮",
|
||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||
"scheme_suffix": "水庄",
|
||
},
|
||
{
|
||
"name": "湖畔酒店",
|
||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||
"scheme_suffix": "湖畔",
|
||
},
|
||
{
|
||
"name": "秒创传媒",
|
||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||
"scheme_suffix": "秒创",
|
||
},
|
||
]
|
||
|
||
|
||
# ---------- 类别辅助函数(全流程共用,与 app 版 config 一致) ----------
|
||
def get_category(name):
|
||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||
|
||
Args:
|
||
name: 类别名
|
||
|
||
Returns:
|
||
类别配置 dict
|
||
|
||
Raises:
|
||
ValueError: 未知名或前缀不唯一
|
||
"""
|
||
name = (name or "").strip()
|
||
for c in CATEGORIES:
|
||
if c["name"] == name:
|
||
return c
|
||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||
if len(matched) == 1:
|
||
return matched[0]
|
||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||
|
||
|
||
def _target_file_date(filename):
|
||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。
|
||
|
||
Args:
|
||
filename: 目标文件名,如「三十七度-雇主险变更记录-2026.08.20.xlsx」/
|
||
「水庄餐饮-雇主险变更记录-7.23.xlsx」
|
||
|
||
Returns:
|
||
date 对象;无法解析返回 None
|
||
"""
|
||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||
if m:
|
||
try:
|
||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||
except ValueError:
|
||
return None
|
||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||
if m:
|
||
try:
|
||
return date(datetime.now().year, int(m.group(1)), int(m.group(2)))
|
||
except ValueError:
|
||
return None
|
||
return None
|
||
|
||
|
||
def find_latest_target(folder):
|
||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||
|
||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||
|
||
Args:
|
||
folder: 类别文件夹路径
|
||
|
||
Returns:
|
||
最新目标文件绝对路径
|
||
|
||
Raises:
|
||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||
"""
|
||
if not os.path.isdir(folder):
|
||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||
candidates = [
|
||
os.path.join(folder, f)
|
||
for f in os.listdir(folder)
|
||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||
]
|
||
if not candidates:
|
||
raise FileNotFoundError(
|
||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||
|
||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||
def _sort_key(path):
|
||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||
os.path.getmtime(path))
|
||
|
||
return max(candidates, key=_sort_key)
|
||
|
||
|
||
def category_target_file(category):
|
||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||
return find_latest_target(category["folder"])
|
||
|
||
|
||
def category_output_backup(category):
|
||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
|
||
|
||
|
||
def category_change_sheet_workbook(category):
|
||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内,调度后复制变更清单 sheet)。"""
|
||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||
|
||
|
||
def category_change_sheet_name(category):
|
||
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
|
||
return f"{category['change_sheet_prefix']}{DATE_SHORT}"
|
||
|
||
|
||
# ---------- 增员/减员导入文件(步骤3:HR「待增减人员」页面上传素材) ----------
|
||
# 模板:雇主险根目录下的官方导入模板(第1行标题/第2行表头/第3行示例说明,第4行起填数据)
|
||
ADD_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险增员导入模板.xlsx")
|
||
SUB_IMPORT_TEMPLATE = os.path.join(BASE_DIR, "商业保险减员导入模板.xlsx")
|
||
|
||
|
||
def category_import_add_file(category):
|
||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||
|
||
|
||
def category_import_sub_file(category):
|
||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||
|
||
|
||
def _to_text(value):
|
||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||
|
||
在参名单 B列(工号)必须为文本:若为数字,与「花名册导出-雇主险使用基础信息」F列
|
||
(工号,已由 roster_filter 统一为文本)匹配时会对不上,公式无法计算。
|
||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||
"""
|
||
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)
|
||
|
||
# ---------- 花名册列名映射(表头在第4行) ----------
|
||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||
|
||
# 数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||
DATA_START_ROW = 17
|
||
|
||
# ---------- 校验常量 ----------
|
||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||
|
||
|
||
class DataValidationError(Exception):
|
||
"""数据校验失败异常:直接中断调度,禁止继续往后跑。"""
|
||
|
||
|
||
def scheme_with_suffix(category, scheme):
|
||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||
|
||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||
"""
|
||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||
scheme = str(scheme or "").strip()
|
||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||
return f"{scheme}-{suffix}"
|
||
return scheme
|
||
|
||
# ---------- 功能开关 ----------
|
||
ENABLE_VALIDATION = True # True: 启用数据校验, False: 跳过校验(测试模式)
|
||
|
||
|
||
# ============================================================
|
||
# 一、数据校验
|
||
# ============================================================
|
||
def validate_biz_data(biz_df):
|
||
"""
|
||
校验花名册业务数据的合法性
|
||
|
||
校验规则:
|
||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:
|
||
人保-20万 / 人保-50万 / 人保-80万
|
||
|
||
返回:errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过
|
||
"""
|
||
errors = []
|
||
|
||
for idx, row in biz_df.iterrows():
|
||
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
|
||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||
category = row[BIZ_COL_CATEGORY]
|
||
scheme = row[BIZ_COL_SCHEME]
|
||
handle = row[BIZ_COL_HANDLE]
|
||
|
||
# 校验1:工种类别必须合法
|
||
if pd.isna(category) or category not in VALID_CATEGORIES:
|
||
errors.append({
|
||
"行号": row_num,
|
||
"员工ID": emp_id,
|
||
"错误类型": "工种类别非法",
|
||
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}"
|
||
})
|
||
|
||
# 校验2:增加投保时,投保方案必须合法
|
||
if str(handle).strip() == "增加投保":
|
||
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
|
||
errors.append({
|
||
"行号": row_num,
|
||
"员工ID": emp_id,
|
||
"错误类型": "投保方案非法",
|
||
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}"
|
||
})
|
||
|
||
return errors
|
||
|
||
|
||
# ============================================================
|
||
# 二、阶段0:初始化(从在参名单构建状态)
|
||
# ============================================================
|
||
def initialize(in_param_df):
|
||
"""
|
||
从"手动维护-在参名单"构建三个核心数据结构:
|
||
|
||
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
|
||
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
|
||
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
|
||
|
||
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
|
||
"""
|
||
idle_pools = defaultdict(list)
|
||
employee_map = {}
|
||
pending_queues = defaultdict(list)
|
||
|
||
IDX_EMP_ID = 10
|
||
IDX_CUR_SCHEME = 12
|
||
IDX_HANDLE = 17
|
||
|
||
for _, row in in_param_df.iterrows():
|
||
emp_id = row.iloc[IDX_EMP_ID]
|
||
if pd.isna(emp_id):
|
||
continue
|
||
|
||
handle = str(row.iloc[IDX_HANDLE]).strip()
|
||
scheme = row.iloc[IDX_CUR_SCHEME]
|
||
|
||
if handle in ["无需", "档次替换"]:
|
||
# 正常参保或待替换,都视为当前已参保
|
||
if not pd.isna(scheme) and scheme != "":
|
||
employee_map[emp_id] = scheme
|
||
|
||
elif handle == "离职减少":
|
||
if not pd.isna(scheme) and scheme != "":
|
||
idle_pools[scheme].append({
|
||
"type": "离职减少",
|
||
"employee_id": emp_id
|
||
})
|
||
|
||
elif handle == "参保减少":
|
||
if not pd.isna(scheme) and scheme != "":
|
||
idle_pools[scheme].append({
|
||
"type": "参保减少",
|
||
"employee_id": emp_id
|
||
})
|
||
# 其他值(如'/')忽略
|
||
|
||
# 按优先级排序(离职减少优先)
|
||
for scheme in idle_pools:
|
||
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
|
||
|
||
return idle_pools, employee_map, pending_queues
|
||
|
||
|
||
# ============================================================
|
||
# 二点五、姓名核对修正(在参名单 J列 与 花名册 姓名比对)
|
||
# ============================================================
|
||
def collect_name_corrections(in_param_df, biz_df):
|
||
"""核对「手动维护-在参名单」J列姓名与花名册「姓名」是否一致,并就地修正。
|
||
|
||
以证件号(在参名单 K列 / 花名册 O列)为关联键:
|
||
- 在参名单中证件号存在、且花名册中能查到该证件号(覆盖离职减少/参保减少等全部行)
|
||
- 两者姓名不一致且花名册姓名非空 → 记录一条修正,并把 in_param_df J列改为花名册姓名,
|
||
使后续「删除记录 / 在参名单输出 / 减员导入」统一使用修正后姓名。
|
||
- 花名册查不到(如已离职)无法核对,跳过不处理。
|
||
|
||
Args:
|
||
in_param_df: 在参名单 DataFrame(J列=姓名,K列=证件号)
|
||
biz_df: 花名册业务 DataFrame(O列=证件号,含姓名/工种类别/投保方案)
|
||
|
||
Returns:
|
||
corrections: 修正列表,每项 {emp_id, old_name, new_name, category, scheme}
|
||
"""
|
||
biz_dict = {}
|
||
for _, row in biz_df.iterrows():
|
||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||
if pd.notna(emp_id):
|
||
biz_dict[emp_id] = row
|
||
|
||
corrections = []
|
||
for idx, row in in_param_df.iterrows():
|
||
emp_id = row.iloc[10]
|
||
if pd.isna(emp_id):
|
||
continue
|
||
biz_row = biz_dict.get(emp_id)
|
||
if biz_row is None:
|
||
continue # 花名册查不到,无法核对,跳过
|
||
new_name = biz_row.get("姓名")
|
||
if new_name is None or pd.isna(new_name) or str(new_name).strip() == "":
|
||
continue
|
||
new_name = str(new_name).strip()
|
||
old_name = row.iloc[9]
|
||
old_name_txt = "" if pd.isna(old_name) else str(old_name).strip()
|
||
if old_name_txt == new_name:
|
||
continue # 姓名一致,无需修正
|
||
# 就地修正 in_param_df J列(姓名),供后续统一使用
|
||
in_param_df.at[idx, in_param_df.columns[9]] = new_name
|
||
corrections.append({
|
||
"emp_id": emp_id,
|
||
"old_name": old_name_txt or "未知",
|
||
"new_name": new_name,
|
||
"category": biz_row.get(BIZ_COL_CATEGORY),
|
||
"scheme": biz_row.get(BIZ_COL_SCHEME),
|
||
})
|
||
|
||
if corrections:
|
||
logger.info("姓名核对修正:共 %d 条", len(corrections))
|
||
for c in corrections:
|
||
logger.info(" %s:%s → %s", c["emp_id"], c["old_name"], c["new_name"])
|
||
else:
|
||
logger.info("姓名核对完成:在参名单与花名册姓名全部一致")
|
||
return corrections
|
||
|
||
|
||
# ============================================================
|
||
# 三、阶段1:处理花名册业务
|
||
# ============================================================
|
||
def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||
"""
|
||
遍历花名册业务数据,产生待转入队列和额外空闲名额
|
||
|
||
业务类型:
|
||
1. 增加投保 → 批量加入待转入队列
|
||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||
3. 其他 → 记录"非法事件跳过"
|
||
|
||
返回:idle_pools, employee_map, pending_queues, change_log
|
||
"""
|
||
change_log = []
|
||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
# ---------- 1. 增加投保(批量处理) ----------
|
||
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
|
||
if not df_add.empty:
|
||
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
|
||
if pd.isna(scheme) or scheme == "":
|
||
for _, row in group.iterrows():
|
||
change_log.append({
|
||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||
"操作": "非法事件跳过",
|
||
"详情": "投保方案为空,无法增加投保",
|
||
"时间": now
|
||
})
|
||
continue
|
||
|
||
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
|
||
pending_queues[scheme].extend(emp_ids)
|
||
for emp_id in emp_ids:
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "增加投保",
|
||
"详情": f"加入 {scheme} 待转入队列",
|
||
"时间": now
|
||
})
|
||
|
||
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
|
||
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
|
||
for _, row in df_replace.iterrows():
|
||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||
target_scheme = row[BIZ_COL_SCHEME]
|
||
|
||
# 校验:员工必须当前已参保
|
||
origin_scheme = employee_map.get(emp_id)
|
||
if origin_scheme is None:
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "非法事件跳过",
|
||
"详情": "员工当前未参保,无法进行档次替换",
|
||
"时间": now
|
||
})
|
||
continue
|
||
|
||
if pd.isna(target_scheme) or target_scheme == "":
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "非法事件跳过",
|
||
"详情": "目标方案为空",
|
||
"时间": now
|
||
})
|
||
continue
|
||
|
||
# 产生"档次替换迁出"名额
|
||
idle_pools[origin_scheme].append({
|
||
"type": "档次替换迁出",
|
||
"employee_id": emp_id
|
||
})
|
||
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
|
||
idle_pools[origin_scheme].sort(
|
||
key=lambda x: 1 if x["type"] == "离职减少"
|
||
else 2 if x["type"] == "参保减少"
|
||
else 3
|
||
)
|
||
|
||
# 员工置为未参保
|
||
employee_map[emp_id] = None
|
||
pending_queues[target_scheme].append(emp_id)
|
||
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "档次替换迁出",
|
||
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
|
||
"时间": now
|
||
})
|
||
|
||
# ---------- 3. 其他未知类型 ----------
|
||
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
|
||
for _, row in df_other.iterrows():
|
||
change_log.append({
|
||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||
"操作": "非法事件跳过",
|
||
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
|
||
"时间": now
|
||
})
|
||
|
||
return idle_pools, employee_map, pending_queues, change_log
|
||
|
||
|
||
# ============================================================
|
||
# 四、阶段2:分配名额
|
||
# ============================================================
|
||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||
"""
|
||
逐个方案处理待转入队列,分配空闲名额或创建新名额
|
||
|
||
逻辑:
|
||
1. 队列中的每个员工必须未参保
|
||
2. 有空闲名额 → 复用(记录来源)
|
||
3. 无空闲名额 → 全新新增
|
||
|
||
返回:final_records, change_log, reused_source_employees
|
||
"""
|
||
final_records = []
|
||
reused_source_employees = []
|
||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
for scheme in all_schemes:
|
||
queue = pending_queues.get(scheme, [])
|
||
pool = idle_pools.get(scheme, [])
|
||
|
||
for emp_id in queue:
|
||
# 校验:员工必须未参保
|
||
if employee_map.get(emp_id) is not None:
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "非法事件跳过",
|
||
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
|
||
"时间": now
|
||
})
|
||
continue
|
||
|
||
if pool:
|
||
# 复用空闲名额(取出优先级最高的)
|
||
slot = pool.pop(0)
|
||
reused_source_employees.append(slot["employee_id"])
|
||
employee_map[emp_id] = scheme
|
||
|
||
final_records.append({
|
||
"证件号": emp_id,
|
||
"投保方案": scheme,
|
||
"参保状态": "正常参保",
|
||
"名额来源": slot["type"],
|
||
"来源员工ID": slot["employee_id"]
|
||
})
|
||
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "复用空闲名额参保",
|
||
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
|
||
"来源员工ID": slot["employee_id"],
|
||
"时间": now
|
||
})
|
||
else:
|
||
# 全新新增
|
||
employee_map[emp_id] = scheme
|
||
final_records.append({
|
||
"证件号": emp_id,
|
||
"投保方案": scheme,
|
||
"参保状态": "正常参保",
|
||
"名额来源": "全新新增"
|
||
})
|
||
|
||
change_log.append({
|
||
"员工ID": emp_id,
|
||
"操作": "全新新增名额参保",
|
||
"详情": f"新增名额,方案 {scheme}",
|
||
"时间": now
|
||
})
|
||
|
||
return final_records, change_log, reused_source_employees
|
||
|
||
|
||
# ============================================================
|
||
# 五、阶段3:输出(更新在参名单 + 精细更新变更清单 + 备份)
|
||
# ============================================================
|
||
|
||
def _to_date(value):
|
||
"""将日期/日期字符串统一转为 date 对象;无法解析时返回 None"""
|
||
if value is None:
|
||
return None
|
||
if isinstance(value, datetime):
|
||
return value.date()
|
||
if isinstance(value, date):
|
||
return value
|
||
s = str(value).strip()
|
||
if not s:
|
||
return None
|
||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"):
|
||
try:
|
||
return datetime.strptime(s, fmt).date()
|
||
except ValueError:
|
||
continue
|
||
return None
|
||
|
||
|
||
def _find_special_slots(final_records, in_param_df):
|
||
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
|
||
|
||
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
|
||
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
|
||
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
|
||
|
||
Args:
|
||
final_records: 最终参保记录列表(每条含 证件号/投保方案/名额来源/来源员工ID)
|
||
in_param_df: 在参名单 DataFrame(J列=姓名 K列=证件号 L列=类别 M列=方案)
|
||
|
||
Returns:
|
||
special_slots: [{source_id, source_name, source_category, new_scheme}, ...]
|
||
"""
|
||
# 初始参保映射:在参名单 M列(投保方案)非空视为"原已参保"
|
||
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)
|
||
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
|
||
slot_network = {}
|
||
for _rec in final_records:
|
||
_sid = _rec.get("来源员工ID")
|
||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||
slot_network[str(_sid).strip()] = _rec
|
||
|
||
# 链条追踪:离职/参保减少释放的名额被老员工复用后,沿"来源员工ID"网络一路追踪,
|
||
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
|
||
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
|
||
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
|
||
special_slots = []
|
||
for rec in final_records:
|
||
if rec.get("名额来源") not in ("离职减少", "参保减少"):
|
||
continue
|
||
source_id = rec.get("来源员工ID")
|
||
# 源员工自身也参保则跳过,避免同一个人出现两条名单
|
||
if source_id is None or pd.isna(source_id) or source_id in final_emp_ids:
|
||
continue
|
||
source_id = str(source_id).strip()
|
||
# 沿链条追踪,找到末端"未被复用的旧方案"(空闲名额 X档)
|
||
current_owner = source_id
|
||
visited = set()
|
||
loose_end_scheme = None
|
||
while current_owner not in visited:
|
||
visited.add(current_owner)
|
||
next_rec = slot_network.get(current_owner)
|
||
if next_rec is None:
|
||
break # 链条断裂
|
||
receiver_id = str(next_rec["证件号"]).strip()
|
||
# 接收者不是原已参保老员工(全新新员工)-> 无旧方案可释放,链条自然结束
|
||
if receiver_id not in initial_employee_map:
|
||
break
|
||
# 接收者是老员工:释放自己的旧方案(X档);若该旧名额无人复用则即为空闲名额
|
||
if receiver_id not in slot_network:
|
||
row_match = in_param_df[in_param_df.iloc[:, 10] == receiver_id]
|
||
if not row_match.empty:
|
||
loose_end_scheme = row_match.iloc[0].iloc[12]
|
||
break
|
||
current_owner = receiver_id # 旧名额被复用,继续追踪下一环
|
||
if not loose_end_scheme:
|
||
continue
|
||
src_match = in_param_df[in_param_df.iloc[:, 10] == source_id]
|
||
if src_match.empty:
|
||
continue
|
||
src_row = src_match.iloc[0]
|
||
special_slots.append({
|
||
"source_id": source_id,
|
||
"source_name": src_row.iloc[9],
|
||
"source_category": src_row.iloc[11],
|
||
"new_scheme": loose_end_scheme,
|
||
})
|
||
return special_slots
|
||
|
||
|
||
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列为空/其它值时漏掉"删除原方案"记录,
|
||
# 例如 A:20→50 与 B:50→20 交换时需输出 A删20+A增50+B删50+B增20 共4条)
|
||
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)
|
||
|
||
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
|
||
# -> 源员工名额改为该空闲方案保留在参名单,变更清单补一条"增加X档"
|
||
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列不动)
|
||
# 注意:特殊情况源员工已保留(改M列),此处不清空
|
||
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()
|
||
# 清空B~N列(索引1-13)
|
||
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"])
|
||
|
||
for rec in new_records:
|
||
if empty_slots:
|
||
slot = empty_slots.pop(0)
|
||
row_data = slot["data"]
|
||
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"]
|
||
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]
|
||
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"]
|
||
new_rows.append({
|
||
"row_idx": None,
|
||
"data": row_data,
|
||
"emp_id": rec["K"],
|
||
"action": "append"
|
||
})
|
||
|
||
# ---------- 8. 更新现有行(B~N列,列号=索引+1) ----------
|
||
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"]
|
||
# 写入B~N列:索引1~13 对应列号2~14(B列工号强制文本)
|
||
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"]
|
||
# 写入所有列:索引0对应A列,索引1对应B列...(B列工号强制文本)
|
||
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 不动) ----------
|
||
# 逐行收集有数据的行(B~O),按原顺序写回顶部连续位置,再把多出的尾部行清空。
|
||
# 公式列随所在行保留并基于行内新数据自动重算,因此结果不受搬移影响。
|
||
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. 精细更新变更清单(复制模板/清空指定列)★★★
|
||
# ============================================================
|
||
# 如果变更清单Sheet不存在,则复制历史模板
|
||
# (历史模板名带日期后缀,如"37度-雇员变更清单8.10",用前缀匹配并选最近一次)
|
||
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
|
||
ws_change = wb[change_sheet_name]
|
||
else:
|
||
ws_change = wb[change_sheet_name]
|
||
|
||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配;
|
||
# 扫描前20列表头(第1/2行都可能),匹配不到时兜底第15列
|
||
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列(第2列)、M列备注(第13列)、N列(第14列)、四级部门列、P~S列(第16~19列)从第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 # 四级部门列(如 O列 新增费用会馆)
|
||
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 = None
|
||
category = None
|
||
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列
|
||
# 四级部门列(如 O列 新增费用会馆):仅纯新增名额(全新新增)的「增加」记录才填,
|
||
# 当日一增一减(复用离职/参保减少/替换迁出释放的名额)及名额替换均不填
|
||
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 = "修改" # B列 批改标志
|
||
ws_change.cell(row=current_row_change, column=13).value = \
|
||
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}" # M列 备注
|
||
ws_change.cell(row=current_row_change, column=14).value = TODAY_DATE # N列 批改日期
|
||
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"] # P列 姓名
|
||
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"] # Q列 证件号
|
||
ws_change.cell(row=current_row_change, column=18).value = corr.get("category") # R列
|
||
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme") # S列
|
||
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)
|
||
|
||
|
||
# ============================================================
|
||
# 五点五、生成增员/减员导入文件(步骤3:HR「待增减人员」页面上传素材)
|
||
# ============================================================
|
||
def _clean_text(value):
|
||
"""转可写文本;None/NaN/空白返回 None。"""
|
||
if value is None:
|
||
return None
|
||
try:
|
||
if pd.isna(value):
|
||
return None
|
||
except (TypeError, ValueError):
|
||
pass
|
||
s = str(value).strip()
|
||
return s or None
|
||
|
||
|
||
def _write_import_file(template_path, out_path, rows):
|
||
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。
|
||
|
||
Args:
|
||
template_path: 官方导入模板路径。
|
||
out_path: 生成的目标文件路径(类别文件夹内)。
|
||
rows: 数据行列表,每行为 [序号, 工号/身份证, ...]。
|
||
|
||
Raises:
|
||
FileNotFoundError: 导入模板不存在(导入文件为硬前提,缺失必须报错而非静默跳过)。
|
||
"""
|
||
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」(步骤3上传素材)。
|
||
|
||
集合差模型(用户确认:名额都进池子,最终效果是从「原来的所有参保记录」经增减员
|
||
操作变为「新的所有参保记录」)。按「人 + 投保方案」记录级做差:
|
||
- 减员 = 原参保记录 − 新参保记录(离职减少/参保减少被复用的、档位替换遗留的原名额)
|
||
- 增员 = 新参保记录 − 原参保记录(全新新增、复用空闲名额、档位替换后的新方案)
|
||
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
|
||
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
|
||
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
|
||
|
||
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||
若先增员会因人员方案冲突直接报错(必须先撤下旧方案,再上新方案)。
|
||
|
||
模板结构:第1行标题、第2行表头、第3行示例说明(均保留),第4行起填数据。
|
||
- 减员:序号 | *工号/身份证 | *姓名 | *减员日期
|
||
- 增员:序号 | *工号/身份证 | *姓名 | *保险方案名称 | *增员日期 | 备注
|
||
增员方案名按类别追加厂区后缀(scheme_with_suffix),与 HR 侧带后缀方案对齐;
|
||
日期格式 yyyy-MM-dd;工号/身份证列优先工号、空则回退证件号。
|
||
"""
|
||
# ---------- 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("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||
|
||
|
||
# ============================================================
|
||
# 五点六、前置处理:取消筛选 + WPS COM 刷新公式并保存
|
||
# ============================================================
|
||
# WPS/Excel 表格组件 ProgID 依次尝试:WPS 表格 → 旧版 WPS(ET) → MS Excel
|
||
COM_PROG_IDS = ("Ket.Application", "et.Application", "Excel.Application")
|
||
|
||
|
||
def refresh_and_unfilter_via_com(target_file):
|
||
"""处理前经 WPS/Excel COM 打开目标文件:取消全部筛选 → 全量重算公式 → 保存关闭。
|
||
|
||
背景:
|
||
1) 筛选状态下人工删除/粘贴花名册会导致数据错位,且残留筛选会一直留在文件里,
|
||
后续在筛选状态下维护数据仍会出错——处理前统一 AutoFilterMode=False 彻底移除;
|
||
2) roster_filter.py 经 openpyxl 覆盖写入后 P~W 公式列缓存丢失,必须全量重算并保存,
|
||
pandas 才能读到公式计算结果(替代原「手动打开 Ctrl+S 刷新」步骤)。
|
||
|
||
ProgID 依次尝试 Ket.Application(WPS 表格)/ et.Application(旧版 WPS)/ Excel.Application;
|
||
目标文件若已在 WPS/Excel 中打开,则直接复用当前工作簿(保存即用户当前所见内容),
|
||
此时不会关闭该工作簿、也不会退出程序,避免影响用户正在使用的会话。
|
||
|
||
Raises:
|
||
FileNotFoundError: 目标文件不存在。
|
||
RuntimeError: 本机 WPS/Excel COM 均不可用(需安装 WPS 或 MS Excel,及 pip install pywin32)。
|
||
"""
|
||
abspath = os.path.abspath(target_file)
|
||
if not os.path.isfile(abspath):
|
||
raise FileNotFoundError(f"目标文件不存在:{abspath}")
|
||
|
||
pythoncom.CoInitialize()
|
||
try:
|
||
app = None
|
||
last_err = None
|
||
for prog_id in COM_PROG_IDS:
|
||
try:
|
||
app = win32com.client.Dispatch(prog_id)
|
||
break
|
||
except Exception as e:
|
||
last_err = e
|
||
if app is None:
|
||
raise RuntimeError(
|
||
"无法启动 WPS/Excel COM(依次尝试 "
|
||
+ " / ".join(COM_PROG_IDS)
|
||
+ f" 均失败):{last_err}。\n"
|
||
"请确认本机已安装 WPS 或 MS Excel,且已安装依赖:pip install pywin32")
|
||
|
||
wb = None
|
||
already_open = False
|
||
try:
|
||
app.DisplayAlerts = False
|
||
# 目标文件已在 WPS/Excel 中打开时复用该工作簿(保存即用户当前所见内容)
|
||
for w in app.Workbooks:
|
||
try:
|
||
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(abspath):
|
||
wb = w
|
||
already_open = True
|
||
break
|
||
except Exception:
|
||
continue
|
||
if wb is None:
|
||
wb = app.Workbooks.Open(abspath)
|
||
|
||
# 1. 取消所有 sheet 的筛选(彻底移除 AutoFilter,被隐藏的行全部恢复显示)
|
||
removed = 0
|
||
for ws in wb.Worksheets:
|
||
try:
|
||
if ws.AutoFilterMode:
|
||
ws.AutoFilterMode = False
|
||
removed += 1
|
||
except Exception:
|
||
pass
|
||
|
||
# 2. 全量重算公式(重建公式依赖,确保公式缓存全部刷新)
|
||
try:
|
||
app.CalculateFullRebuild()
|
||
except Exception:
|
||
try:
|
||
app.CalculateFull()
|
||
except Exception:
|
||
app.Calculate()
|
||
|
||
# 3. 保存(计算结果写入文件缓存,后续 pandas 才能读到)
|
||
wb.Save()
|
||
logger.info("前置处理完成:取消 %d 个 sheet 的筛选,公式全量重算并保存%s",
|
||
removed, "(复用 WPS 中已打开的工作簿)" if already_open else "")
|
||
finally:
|
||
try:
|
||
app.DisplayAlerts = True
|
||
except Exception:
|
||
pass
|
||
# 新开的工作簿用完关闭;用户会话中已打开的不动,避免打断用户操作
|
||
if wb is not None and not already_open:
|
||
try:
|
||
wb.Close(SaveChanges=False)
|
||
except Exception:
|
||
pass
|
||
# 仅当无其他工作簿打开时退出程序,避免误关用户正在使用的 WPS/Excel
|
||
try:
|
||
if app.Workbooks.Count == 0:
|
||
app.Quit()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
pythoncom.CoUninitialize()
|
||
|
||
|
||
# ============================================================
|
||
# 六、入口(步骤2:调度)
|
||
# ============================================================
|
||
def _check_import_templates():
|
||
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
|
||
|
||
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
|
||
才发现模板缺失、需要重做的浪费。_write_import_file 内的检查作为兜底保留。
|
||
"""
|
||
missing = [
|
||
path for path in (ADD_IMPORT_TEMPLATE, SUB_IMPORT_TEMPLATE)
|
||
if not os.path.isfile(path)
|
||
]
|
||
if missing:
|
||
raise FileNotFoundError(
|
||
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
|
||
|
||
|
||
def schedule_category(category):
|
||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||
|
||
前置:先运行 roster_filter.py(筛选复制)。本步骤开始时自动经 WPS/Excel COM
|
||
取消筛选、全量重算公式并保存,无需再手动打开目标文件刷新。
|
||
"""
|
||
category_name = category["name"]
|
||
target_file = category_target_file(category)
|
||
output_backup = category_output_backup(category)
|
||
change_sheet_prefix = category["change_sheet_prefix"]
|
||
change_sheet_name = category_change_sheet_name(category)
|
||
logger.info("=" * 70)
|
||
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
|
||
|
||
# 检查文件是否存在
|
||
if not os.path.exists(target_file):
|
||
logger.error("目标表不存在:%s,请先运行 roster_filter.py 步骤生成。", target_file)
|
||
return
|
||
|
||
# ★ 前置处理:取消筛选 + WPS/Excel COM 全量重算公式并保存(替代人工打开刷新步骤)
|
||
refresh_and_unfilter_via_com(target_file)
|
||
|
||
# 检查必需Sheet
|
||
xl = pd.ExcelFile(target_file)
|
||
required_sheets = [SHEET_BIZ, SHEET_IN_PARAM]
|
||
for s in required_sheets:
|
||
if s not in xl.sheet_names:
|
||
logger.error("缺少必需 Sheet:%s", s)
|
||
return
|
||
logger.info("文件结构检查通过。")
|
||
|
||
# 前置校验:增减员导入模板必须存在,避免调度全部完成后才发现模板缺失、需重做
|
||
_check_import_templates()
|
||
|
||
# ---------- 读取并清洗花名册数据 ----------
|
||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3)
|
||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||
|
||
# 过滤:证件号为空 或 方案处理为 "/"
|
||
biz_df = biz_df[
|
||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||
]
|
||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||
|
||
# ---------- 读取在参名单 ----------
|
||
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5)
|
||
column_names = in_param_df.columns.tolist()
|
||
logger.info("在参名单:%d 行", len(in_param_df))
|
||
|
||
# ---------- 姓名核对修正(在参名单 与 花名册 比对,就地修正并返回修正记录) ----------
|
||
logger.info("核对在参名单与花名册姓名...")
|
||
name_corrections = collect_name_corrections(in_param_df, biz_df)
|
||
if name_corrections:
|
||
logger.info("共 %d 条姓名不一致,将修正并在变更清单体现", len(name_corrections))
|
||
else:
|
||
logger.info("姓名全部一致,无需修正")
|
||
|
||
# ---------- 数据校验 ----------
|
||
if ENABLE_VALIDATION:
|
||
logger.info("正在校验数据...")
|
||
errors = validate_biz_data(biz_df)
|
||
if errors:
|
||
logger.error("发现 %d 个校验错误:", len(errors))
|
||
for e in errors:
|
||
logger.error(" 行%s 员工%s:%s - %s",
|
||
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
|
||
logger.error("数据校验失败,请修正后重新运行!")
|
||
raise DataValidationError(
|
||
f"类别[{category_name}] 数据校验失败,共 {len(errors)} 个错误,已中断调度")
|
||
else:
|
||
logger.info("数据校验通过!")
|
||
else:
|
||
logger.info("已跳过数据校验(ENABLE_VALIDATION = False)")
|
||
|
||
# ---------- 阶段0:初始化 ----------
|
||
logger.info("初始化状态...")
|
||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
|
||
logger.info(" 当前参保员工:%d 人", len(employee_map))
|
||
|
||
# ---------- 阶段1:处理业务 ----------
|
||
logger.info("处理花名册业务...")
|
||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||
biz_df, idle_pools, employee_map, pending_queues)
|
||
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
|
||
logger.info(" 变更日志条数:%d", len(change_log))
|
||
|
||
# ---------- 阶段2:分配名额 ----------
|
||
logger.info("分配名额...")
|
||
final_records, change_log, reused_source_employees = allocate_slots(
|
||
idle_pools, employee_map, pending_queues, change_log)
|
||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||
logger.info(" 变更日志条数(最终):%d", len(change_log))
|
||
|
||
# ---------- 阶段3:输出 ----------
|
||
logger.info("输出结果...")
|
||
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,
|
||
SHEET_IN_PARAM,
|
||
name_corrections
|
||
)
|
||
|
||
# ---------- 阶段4:生成增员/减员导入文件(步骤3:HR 上传素材) ----------
|
||
logger.info("生成增员/减员导入文件...")
|
||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||
|
||
logger.info("类别[%s] 调度完成!", category_name)
|
||
|
||
|
||
def main(category_names: list[str] = None):
|
||
"""步骤2:调度(读取已刷新公式的目标文件,输出结果)。
|
||
|
||
Args:
|
||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||
空列表 / None 表示处理全部类别。
|
||
|
||
前置:先运行 roster_filter.py(筛选复制)。本步骤开始时自动经 WPS/Excel COM
|
||
取消筛选、全量重算公式并保存,无需再手动打开目标文件刷新。
|
||
"""
|
||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||
for category in categories:
|
||
try:
|
||
schedule_category(category)
|
||
except (DataValidationError, RuntimeError):
|
||
# 数据校验失败 / COM 前置处理失败(如本机无 WPS/Excel):整批中断,不再处理后续类别
|
||
raise
|
||
except Exception:
|
||
logger.exception("类别[%s] 调度失败", category["name"])
|
||
|
||
logger.info("全部完成!")
|
||
|
||
|
||
# ============================================================
|
||
# 七、程序入口
|
||
# ============================================================
|
||
if __name__ == "__main__":
|
||
main(category_names=["三十七度"])
|