refactor(tests): 归档旧版HRBP测试文件,新增新版测试辅助脚本和雇主险WPS可行性验证
本次提交主要包含以下内容: 1. 归档tests/hrbp目录下的旧版测试文件至tests/_app_蓝图版归档目录 2. 新增tests/_app_蓝图版归档/hrbp目录下的新版测试辅助脚本和测试用例 3. 新增雇主险场景下的WPS COM可行性验证脚本 4. 更新README.md中关于tests目录的说明,明确各子目录用途 5. 更新XQ0035工作流相关文件中的操作人UnionID,更换为人资专用号 6. 修复试用期变更脚本中日期转换的问题,确保AI表格时间戳正确转换为日期格式 7. 归档XQ0035工作流下的旧版测试脚本至测试归档目录
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,846 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
雇主险名额调度系统(完整版)
|
||||
================================================================================
|
||||
【功能概述】
|
||||
1. 读取花名册业务数据(增加投保/要替换)
|
||||
2. 结合在参名单(空闲名额池、当前参保状态)
|
||||
3. 三阶段调度:初始化 → 处理业务 → 分配名额
|
||||
4. 输出:
|
||||
a. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
b. 精细更新"37度-雇员变更清单-MM.DD"(仅清空并重写B/N/P~S列数据)
|
||||
c. 备份新在参名单
|
||||
|
||||
【输入文件】
|
||||
三十七度-雇主险变更记录-YYYY.MM.DD.xlsx
|
||||
- Sheet1: 花名册导出-雇主险使用基础信息 (表头第4行)
|
||||
- Sheet2: 手动维护-在参名单 (表头第6行)
|
||||
- Sheet3: 37度-雇员变更清单-月.日 (已有模板,表头2行,第3行起数据)
|
||||
|
||||
【输出】
|
||||
- 原文件原地更新 (在参名单第17行起B~N列;变更清单清空并重写B/N/P~S列)
|
||||
- 备份: 新在参名单-YYYY.MM.DD.xlsx
|
||||
|
||||
【开关】
|
||||
ENABLE_VALIDATION = True # True: 启用数据校验, False: 跳过校验
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime, date
|
||||
from collections import defaultdict
|
||||
from openpyxl import load_workbook
|
||||
from copy import copy
|
||||
|
||||
# ============================================================
|
||||
# 一、全局配置
|
||||
# ============================================================
|
||||
BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# ★★★ 功能开关 ★★★
|
||||
ENABLE_VALIDATION = False # True: 启用数据校验, False: 跳过校验(测试模式)
|
||||
|
||||
# 输入/输出文件路径
|
||||
TARGET_FILE = os.path.join(BASE_DIR, f"三十七度-雇主险变更记录-{DATE_STR}.xlsx")
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# 固定Sheet名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
CHANGE_SHEET_PREFIX = "37度-雇员变更清单"
|
||||
CHANGE_SHEET_NAME = f"{CHANGE_SHEET_PREFIX}-{DATE_SHORT}"
|
||||
|
||||
# ============================================================
|
||||
# 二、列名映射(用于从花名册读取业务数据)
|
||||
# ============================================================
|
||||
# 花名册导出-雇主险使用基础信息 列名(表头在第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万"]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、数据校验函数
|
||||
# ============================================================
|
||||
def validate_biz_data(biz_df):
|
||||
"""
|
||||
校验花名册业务数据的合法性
|
||||
|
||||
校验规则:
|
||||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:
|
||||
人保-20万 / 人保-50万 / 人保-80万
|
||||
|
||||
参数:
|
||||
biz_df: 花名册业务数据DataFrame
|
||||
|
||||
返回:
|
||||
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": "证件号"}, ...]}
|
||||
按优先级排序:离职减少(1) > 参保减少(2)
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 六、阶段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 output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, in_param_sheet):
|
||||
"""
|
||||
输出三部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
"""
|
||||
from openpyxl import load_workbook
|
||||
from copy import copy
|
||||
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ---------- 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)
|
||||
|
||||
# ---------- 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)))
|
||||
)
|
||||
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:
|
||||
print(f"⚠️ 警告:员工 {emp_id} 在花名册中找不到,跳过")
|
||||
continue
|
||||
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": row_biz.get("工号"),
|
||||
"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 = []
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_info["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 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
|
||||
for idx in range(1, 14):
|
||||
ws.cell(row=row_idx, column=idx + 1).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列... 使用enumerate正确
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
ws.cell(row=row_idx, column=col_idx).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 == 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:
|
||||
# 收集所有以"37度-雇员变更清单"开头、且不是当前目标名的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
|
||||
print(f"📋 已从模板 [{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]
|
||||
|
||||
# 清空B列(第2列)、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=14).value = None # N列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 构建初始参保映射
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
handle = str(row.iloc[17]).strip()
|
||||
if handle in ["无需", "档次替换"]:
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 收集变更记录
|
||||
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(("删除", name, emp_id, category, scheme))
|
||||
else:
|
||||
records.append(("删除", "未知", emp_id, "未知", "未知"))
|
||||
|
||||
# 2. 增加记录(原「修改」拆分为「删除原名额 + 增加新名额」两条,体现完整变更)
|
||||
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:
|
||||
# 原已参保(档次替换):先删除原名额(用原姓名/类别/方案),再增加新名额
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row_orig = row_match.iloc[0]
|
||||
records.append(("删除", row_orig.iloc[9], emp_id,
|
||||
row_orig.iloc[11], row_orig.iloc[12]))
|
||||
records.append(("增加", name, emp_id, category, scheme))
|
||||
else:
|
||||
records.append(("增加", name, emp_id, category, scheme))
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for op, name, emp_id, category, scheme in records:
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
print(f"⚠️ 跳过变更记录:{op} {emp_id} 信息不完整")
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=14).value = TODAY_DATE # N列
|
||||
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
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
print(f"✅ 手动维护-在参名单已更新(保留 {len(kept_emp_ids)} 个原有员工,清空 {len(emp_ids_to_clear)} 个旧员工行,新增 {len(new_records)} 条参保记录)")
|
||||
print(f"✅ 变更清单已精细更新(共 {len(records)} 条变更记录)")
|
||||
print(f"✅ 备份新在参名单已保存:{output_backup}")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 九、主函数
|
||||
# ============================================================
|
||||
def main():
|
||||
"""
|
||||
执行完整的三阶段调度流程
|
||||
"""
|
||||
print(f"📂 目标文件:{TARGET_FILE}")
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(TARGET_FILE):
|
||||
print(f"❌ 文件不存在,请先运行 WPS 宏生成该文件。")
|
||||
return
|
||||
|
||||
# 检查必需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:
|
||||
print(f"❌ 缺少必需 Sheet:{s}")
|
||||
return
|
||||
print("✅ 文件结构检查通过。")
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
biz_df = pd.read_excel(TARGET_FILE, sheet_name=SHEET_BIZ, header=3)
|
||||
print(f"原始花名册数据:{len(biz_df)} 行")
|
||||
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
biz_df = biz_df[
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||||
]
|
||||
print(f"清洗后花名册数据:{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()
|
||||
print(f"✅ 在参名单:{len(in_param_df)} 行")
|
||||
|
||||
# ---------- 数据校验 ----------
|
||||
if ENABLE_VALIDATION:
|
||||
print("🔍 正在校验数据...")
|
||||
errors = validate_biz_data(biz_df)
|
||||
if errors:
|
||||
print(f"❌ 发现 {len(errors)} 个校验错误:")
|
||||
for e in errors:
|
||||
print(f" 行{e['行号']} 员工{e['员工ID']}:{e['错误类型']} - {e['详情']}")
|
||||
print("\n⚠️ 数据校验失败,请修正后重新运行!")
|
||||
return
|
||||
else:
|
||||
print("✅ 数据校验通过!")
|
||||
else:
|
||||
print("⚠️ 已跳过数据校验(ENABLE_VALIDATION = False)")
|
||||
|
||||
# ---------- 阶段0:初始化 ----------
|
||||
print("🔄 初始化状态...")
|
||||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||||
print(f" 空闲名额池:{sum(len(v) for v in idle_pools.values())} 个")
|
||||
print(f" 当前参保员工:{len(employee_map)} 人")
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
print("🔄 处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
biz_df, idle_pools, employee_map, pending_queues)
|
||||
print(f" 待转入总人数:{sum(len(v) for v in pending_queues.values())} 人")
|
||||
print(f" 变更日志条数:{len(change_log)}")
|
||||
|
||||
# ---------- 阶段2:分配名额 ----------
|
||||
print("🔄 分配名额...")
|
||||
final_records, change_log, reused_source_employees = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log)
|
||||
print(f" 最终参保记录:{len(final_records)} 人")
|
||||
print(f" 变更日志条数(最终):{len(change_log)}")
|
||||
|
||||
# ---------- 阶段3:输出 ----------
|
||||
print("🔄 输出结果...")
|
||||
output_results(
|
||||
final_records,
|
||||
change_log,
|
||||
reused_source_employees,
|
||||
biz_df,
|
||||
in_param_df,
|
||||
column_names,
|
||||
TARGET_FILE,
|
||||
OUTPUT_IN_PARAM,
|
||||
CHANGE_SHEET_NAME,
|
||||
SHEET_IN_PARAM
|
||||
)
|
||||
|
||||
print("🎉 全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 十、程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Description: WPS COM 可行性验证(雇主险场景)——
|
||||
模拟「openpyxl 写入业务数据 → 目标表公式列缓存丢失 → WPS COM 打开重算保存 → openpyxl 读回公式结果」。
|
||||
验证 WPS 个人版 Ket.Application 是否满足 XQ0002 插件版「自动化替代人工 Ctrl+S 刷新公式」的需求。
|
||||
不触碰真实业务文件,全部在 %TEMP%\\wps_com_feasibility\\ 下完成。
|
||||
@Run: d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests\\wps_com_feasibility.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import tempfile
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
import openpyxl
|
||||
from openpyxl import load_workbook
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
|
||||
WORK_DIR = os.path.join(tempfile.gettempdir(), "wps_com_feasibility")
|
||||
TEST_FILE = os.path.join(WORK_DIR, "雇主险验证-重算公式.xlsx")
|
||||
|
||||
|
||||
def step1_write_data_via_openpyxl():
|
||||
"""openpyxl 模拟雇主险写入:业务值 + 目标表已有公式列(openpyxl 不计算,缓存留空)"""
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "花名册导出-雇主险使用基础信息"
|
||||
# 业务数据(模拟 B~O 列一部分)
|
||||
ws["B4"] = "三十七度"
|
||||
ws["O5"] = "5101**********1234"
|
||||
ws["P5"] = "一类"
|
||||
ws["Q5"] = "人保-20万"
|
||||
ws["W5"] = "增加投保"
|
||||
# 模拟目标表里的公式列:V5 = 证件号长度(真实业务里是公式),openpyxl 只写公式不计算
|
||||
ws["V5"] = '=IF(LEN(O5)>0,"有证","无证")'
|
||||
# 模拟跨 sheet 公式(变更清单场景)
|
||||
ws2 = wb.create_sheet("37度-雇员变更清单-9.22")
|
||||
ws2["B3"] = 100
|
||||
ws2["C3"] = 200
|
||||
ws2["D3"] = "=B3+C3" # 公式列,openpyxl 写后缓存为空
|
||||
ws2["E3"] = '=IF(D3>0,"OK","-")'
|
||||
wb.save(TEST_FILE)
|
||||
wb.close()
|
||||
print(f"[1] openpyxl 写入完成: {TEST_FILE}")
|
||||
|
||||
# 证明:data_only 读公式列缓存为空(这就是业务里"必须人工 Ctrl+S"的原因)
|
||||
wb_r = load_workbook(TEST_FILE, data_only=True)
|
||||
v1 = wb_r["花名册导出-雇主险使用基础信息"]["V5"].value
|
||||
v2 = wb_r["37度-雇员变更清单-9.22"]["D3"].value
|
||||
v3 = wb_r["37度-雇员变更清单-9.22"]["E3"].value
|
||||
wb_r.close()
|
||||
print(f" 写后缓存值(应为 None): V5={v1!r} D3={v2!r} E3={v3!r}")
|
||||
assert v1 is None and v2 is None and v3 is None, "openpyxl 写后公式缓存应全空"
|
||||
|
||||
|
||||
def step2_recalc_via_wps_com():
|
||||
"""WPS COM 打开 → 全量重算 → 保存(替代人工 Ctrl+S)"""
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
try:
|
||||
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
wb = app.Workbooks.Open(os.path.abspath(TEST_FILE), UpdateLinks=2)
|
||||
wb.Application.CalculateFullRebuild()
|
||||
wb.Save()
|
||||
wb.Close()
|
||||
print("[2] WPS COM 重算并保存成功")
|
||||
finally:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
|
||||
def step3_read_back():
|
||||
"""openpyxl data_only 读回公式结果,验证缓存已落盘"""
|
||||
wb = load_workbook(TEST_FILE, data_only=True)
|
||||
v1 = wb["花名册导出-雇主险使用基础信息"]["V5"].value
|
||||
v2 = wb["37度-雇员变更清单-9.22"]["D3"].value
|
||||
v3 = wb["37度-雇员变更清单-9.22"]["E3"].value
|
||||
wb.close()
|
||||
print(f"[3] 重算后缓存值: V5={v1!r} D3={v2!r} E3={v3!r}")
|
||||
assert v1 == "有证" and v2 == 300 and v3 == "OK", f"公式结果不符: {v1=} {v2=} {v3=}"
|
||||
print(" ✅ 全部公式结果已计算并缓存落盘,openpyxl 可直接读取")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
shutil.rmtree(WORK_DIR, ignore_errors=True)
|
||||
os.makedirs(WORK_DIR, exist_ok=True)
|
||||
step1_write_data_via_openpyxl()
|
||||
step2_recalc_via_wps_com()
|
||||
step3_read_back()
|
||||
print("\n结论:WPS 个人版 Ket.Application COM 可行 —— 可替代雇主险人工刷新公式(Ctrl+S)环节")
|
||||
except Exception:
|
||||
print("\n结论:验证失败,详情如下")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,341 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险插件 全链路冒烟自测(本机 .venv 执行)。
|
||||
|
||||
覆盖链路:花名册筛选复制 → WPS/Excel COM 后台重算(可选)→ 三阶段名额调度
|
||||
(更新在参名单 / 精细更新变更清单 / 备份新在参名单)→ 增/减员导入文件 → 变更清单独立工作簿。
|
||||
|
||||
测试数据(临时目录):
|
||||
- 员工花名册.xlsx:表头行 B 列=「所属单位」,B~O 14 列;8 名员工,含各类被过滤样本
|
||||
(金色湖畔事业部 / 虚拟大区 / 姓名含测试 / 未来入职 / 方案处理=/)。
|
||||
- 三十七度-雇主险变更记录-测试.xlsx:SHEET_BIZ 表头第4行(P/Q/V/W 为公式列)、
|
||||
SHEET_IN_PARAM 表头第6行(数据第17行起)、历史变更清单模板 sheet。
|
||||
- 商业保险增/减员导入模板.xlsx(第1~3行固定,第4行起填数据)。
|
||||
|
||||
预期(业务场景):
|
||||
- 花名册过滤后 4 人(张三/李四/王五/赵六),赵六方案处理=/ 在调度阶段被过滤。
|
||||
- 在参名单:王五(20万,要替换→80万) 迁出;钱十离职减少名额被李四(20万)复用;
|
||||
张三(50万) 全新新增;王五(80万) 全新新增;陈十一(50万) 保留。
|
||||
- 变更清单 4 条:删除钱十 / 增加张三(带四级部门) / 增加李四 / 修改王五。
|
||||
- 减员导入 2 条(钱十、王五);增员导入 3 条(张三/李四/王五)。
|
||||
|
||||
用法(仓库根目录执行):
|
||||
.venv\\Scripts\\python.exe tests\\xq0002_plugin_smoke.py
|
||||
"""
|
||||
import importlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import date
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "desktop", "electron-shell", "python")) # 壳内置 webhost 运行时子集
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "plugins", "XQ0001-0100")) # 插件包
|
||||
|
||||
# 通过 importlib 导入包名含空格/中文的插件模块
|
||||
cfg = importlib.import_module("XQ0002 雇主险增减操作.config")
|
||||
roster_filter = importlib.import_module("XQ0002 雇主险增减操作.logic.roster_filter")
|
||||
schedule_mod = importlib.import_module("XQ0002 雇主险增减操作.logic.schedule")
|
||||
wps_recalc = importlib.import_module("XQ0002 雇主险增减操作.logic.wps_recalc")
|
||||
report_output = importlib.import_module("XQ0002 雇主险增减操作.report.output")
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
# ==================== 测试目录与结果收集 ====================
|
||||
WORK_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_xq0002_smoke_data")
|
||||
if os.path.isdir(WORK_DIR):
|
||||
shutil.rmtree(WORK_DIR)
|
||||
CATEGORY_DIR = os.path.join(WORK_DIR, "三十七度")
|
||||
os.makedirs(CATEGORY_DIR, exist_ok=True)
|
||||
|
||||
RESULTS = [] # (名称, 通过?, 说明)
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append((name, bool(ok), detail))
|
||||
print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" -> {detail}" if detail and not ok else ""))
|
||||
|
||||
|
||||
def _sheet(wb, title):
|
||||
if title in wb.sheetnames:
|
||||
return wb[title]
|
||||
return wb.create_sheet(title)
|
||||
|
||||
|
||||
# ==================== 1. 构建测试数据 ====================
|
||||
def build_source(path):
|
||||
"""员工花名册:表头行 B 列=「所属单位」,B~O 14 列。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "花名册"
|
||||
headers = ["类型", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
|
||||
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号"]
|
||||
for i, h in enumerate(headers, start=1):
|
||||
ws.cell(row=1, column=i, value=h)
|
||||
rows = [
|
||||
# 所属单位 一级部门 工号 年龄 性别 岗位 职位序列 参保 交通 入职日期 姓名 证件号
|
||||
["三十七度", "三十七度大区", "10001", 30, "男", "厨师", "厨师长", "全职", "班车", date(2020, 1, 1), "张三", "110101199001010001"],
|
||||
["三十七度", "三十七度大区", "10002", 29, "女", "服务员", "服务员", "全职", "班车", date(2021, 1, 1), "李四", "110101199002010002"],
|
||||
["三十七度", "三十七度大区", "10003", 35, "男", "领班", "领班", "全职", "班车", date(2019, 6, 1), "王五", "110101198906010003"],
|
||||
["三十七度", "三十七度大区", "10004", 28, "男", "传菜", "传菜员", "全职", "班车", date(2022, 1, 1), "赵六", "110101199301010004"],
|
||||
["金色湖畔事业部", "金色湖畔大区", "10005", 26, "女", "前台", "前台", "全职", "班车", date(2020, 5, 1), "孙七", "110101199405010005"],
|
||||
["三十七度", "三十七度大区", "10006", 24, "女", "实习", "实习生", "兼职", "班车", date(2020, 1, 1), "测试员", "110101199601010006"],
|
||||
["三十七度", "虚拟大区", "10007", 27, "男", "杂工", "杂工", "全职", "班车", date(2020, 1, 1), "周八", "110101199701010007"],
|
||||
["三十七度", "三十七度大区", "10008", 25, "男", "帮厨", "帮厨", "全职", "班车", date(2099, 1, 1), "吴九", "110101199801010008"],
|
||||
]
|
||||
for r, row in enumerate(rows, start=2):
|
||||
ws.cell(row=r, column=2, value=row[0]) # B 所属单位
|
||||
ws.cell(row=r, column=3, value=row[1]) # C 一级部门
|
||||
ws.cell(row=r, column=6, value=row[2]) # F 工号
|
||||
ws.cell(row=r, column=7, value=row[3]) # G 年龄
|
||||
ws.cell(row=r, column=8, value=row[4]) # H 性别
|
||||
ws.cell(row=r, column=9, value=row[5]) # I 岗位
|
||||
ws.cell(row=r, column=10, value=row[6]) # J 职位序列
|
||||
ws.cell(row=r, column=11, value=row[7]) # K 参保类型
|
||||
ws.cell(row=r, column=12, value=row[8]) # L 上下班交通方式
|
||||
ws.cell(row=r, column=13, value=row[9]) # M 入职时间
|
||||
ws.cell(row=r, column=14, value=row[10]) # N 姓名
|
||||
ws.cell(row=r, column=15, value=row[11]) # O 证件号
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def build_target(path):
|
||||
"""类别目标表:SHEET_BIZ(表头第4行) + SHEET_IN_PARAM(表头第6行,数据第17行起) + 历史变更清单模板。"""
|
||||
wb = Workbook()
|
||||
|
||||
# ---- SHEET_BIZ:表头第4行 ----
|
||||
ws = _sheet(wb, cfg.SHEET_BIZ)
|
||||
biz_headers = ["序号", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
|
||||
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号",
|
||||
"工种类别", "投保方案", "方案组别编号", "是否有工伤保险", "工作单位",
|
||||
"新增费用会馆", "四级部门", "方案处理"]
|
||||
for i, h in enumerate(biz_headers, start=1):
|
||||
ws.cell(row=4, column=i, value=h)
|
||||
# 模拟真实模板:P/Q/W/V 为公式/待填列(数据行5~8 与花名册筛选结果对应)
|
||||
# 公式列需经 WPS/Excel 重算才有缓存值;重算不可用时测试兜底直接填值
|
||||
# 赵六 为「方案处理=/」的占位员工(调度阶段被过滤,不参与参保)
|
||||
formulas = {
|
||||
5: ("=\"一类\"", "=\"人保-50万\"", "=\"增加投保\"", "三十七度-后厨"),
|
||||
6: ("=\"二类\"", "=\"人保-20万\"", "=\"增加投保\"", "三十七度-前厅"),
|
||||
7: ("=\"三类\"", "=\"人保-80万\"", "=\"要替换\"", "三十七度-后勤"),
|
||||
8: ("=\"一类\"", "=\"人保-20万\"", "=\"/\"", None),
|
||||
}
|
||||
for r, (p, q, w, v) in formulas.items():
|
||||
ws.cell(row=r, column=16, value=p) # P 工种类别
|
||||
ws.cell(row=r, column=17, value=q) # Q 投保方案
|
||||
ws.cell(row=r, column=23, value=w) # W 方案处理
|
||||
ws.cell(row=r, column=22, value=v) # V 四级部门
|
||||
|
||||
# ---- SHEET_IN_PARAM:表头第6行,数据第17行起 ----
|
||||
ws2 = _sheet(wb, cfg.SHEET_IN_PARAM)
|
||||
in_headers = ["序号", "工号", "年龄", "性别", "岗位", "职位序列", "参保类型", "上下班交通方式",
|
||||
"入职时间", "姓名", "证件号", "工种类别", "投保方案", "投保日期",
|
||||
"方案组别编号", "每人责任限额", "是否有工伤保险", "方案处理"]
|
||||
for i, h in enumerate(in_headers, start=1):
|
||||
ws2.cell(row=6, column=i, value=h)
|
||||
# 王五(要替换: 20万→80万) / 钱十(离职减少: 20万) / 陈十一(无需: 50万)
|
||||
in_rows = {
|
||||
17: (1, "10003", "王五", "110101198906010003", "三类", "人保-20万", date(2020, 1, 1), "档次替换"),
|
||||
18: (2, "10009", "钱十", "110101199009010009", "一类", "人保-20万", date(2021, 1, 1), "离职减少"),
|
||||
19: (3, "10010", "陈十一", "110101199110100010", "一类", "人保-50万", date(2020, 6, 1), "无需"),
|
||||
}
|
||||
for r, (seq, code, name, emp_id, cat, scheme, join_date, handle) in in_rows.items():
|
||||
ws2.cell(row=r, column=1, value=seq) # A 序号
|
||||
ws2.cell(row=r, column=2, value=code) # B 工号
|
||||
ws2.cell(row=r, column=10, value=name) # J 姓名
|
||||
ws2.cell(row=r, column=11, value=emp_id) # K 证件号
|
||||
ws2.cell(row=r, column=12, value=cat) # L 工种类别
|
||||
ws2.cell(row=r, column=13, value=scheme) # M 投保方案
|
||||
ws2.cell(row=r, column=14, value=join_date) # N 投保日期
|
||||
ws2.cell(row=r, column=18, value=handle) # R 方案处理
|
||||
|
||||
# ---- 历史变更清单模板 sheet(供复制)----
|
||||
ws3 = _sheet(wb, "37度-雇员变更清单9.1")
|
||||
chg_headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄", "员工职业类别",
|
||||
"每人责任限额", "方案组别编号", "是否有工伤保险", "工作单位", "", "备注",
|
||||
"批改日期", "新增费用会馆\n(自留后续划成本用)", "姓名", "证件号", "工种类别", "投保方案"]
|
||||
for i, h in enumerate(chg_headers, start=1):
|
||||
ws3.cell(row=1, column=i, value=h)
|
||||
ws3.cell(row=2, column=1, value="公式")
|
||||
ws3.cell(row=2, column=15, value="公式")
|
||||
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def build_templates(base_dir):
|
||||
"""增/减员导入模板:第1~3行固定,第4行起填数据。"""
|
||||
for name in (cfg.ADD_IMPORT_TEMPLATE, cfg.SUB_IMPORT_TEMPLATE):
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "导入模板"
|
||||
ws.cell(row=1, column=1, value=f"{name} 标题")
|
||||
ws.cell(row=2, column=1, value="序号")
|
||||
ws.cell(row=2, column=2, value="工号/证件号")
|
||||
ws.cell(row=2, column=3, value="姓名")
|
||||
ws.cell(row=3, column=1, value="示例说明行(保留)")
|
||||
wb.save(os.path.join(base_dir, name))
|
||||
|
||||
|
||||
# ==================== 2. 冒烟流程 ====================
|
||||
def main():
|
||||
today = date.today()
|
||||
cfg.set_base_dir(WORK_DIR)
|
||||
cfg.set_ref_date(today.strftime("%Y-%m-%d"))
|
||||
category = cfg.get_category("三十七度")
|
||||
|
||||
source_path = cfg.employee_file()
|
||||
target_path = os.path.join(CATEGORY_DIR, "三十七度-雇主险变更记录-测试.xlsx")
|
||||
|
||||
print("== 构建测试数据 ==")
|
||||
build_source(source_path)
|
||||
build_target(target_path)
|
||||
build_templates(WORK_DIR)
|
||||
|
||||
# ---------- 2.1 WPS/Excel COM 重算能力探测 ----------
|
||||
print("\n== Part A:WPS/Excel COM 公式重算 ==")
|
||||
probe = os.path.join(WORK_DIR, "recalc_probe.xlsx")
|
||||
pb = Workbook()
|
||||
pws = pb.active
|
||||
pws["A1"] = 2
|
||||
pws["B1"] = 3
|
||||
pws["C1"] = "=A1+B1"
|
||||
pb.save(probe)
|
||||
|
||||
com_ok = False
|
||||
try:
|
||||
wps_recalc.recalc_target(probe)
|
||||
cached = load_workbook(probe, data_only=True)["Sheet"]["C1"].value
|
||||
com_ok = (cached == 5)
|
||||
check("PartA 公式重算(Ket/Excel COM)", com_ok,
|
||||
f"期望 C1=5,实际 {cached!r}")
|
||||
except Exception as e:
|
||||
check("PartA 公式重算(Ket/Excel COM)", False, str(e))
|
||||
|
||||
# ---------- 2.2 筛选复制 ----------
|
||||
print("\n== 步骤1:花名册筛选复制 ==")
|
||||
n_copied = roster_filter.filter_and_copy_roster(category, employee_path=source_path,
|
||||
target_file=target_path)
|
||||
check("筛选复制行数=4(张三/李四/王五/赵六)", n_copied == 4, f"实际 {n_copied} 行")
|
||||
# F 列工号强制文本
|
||||
wb0 = load_workbook(target_path)
|
||||
f_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=6).value
|
||||
check("F列工号文本格式", isinstance(f_val, str) and f_val == "10001", repr(f_val))
|
||||
# O 列证件号强制文本(18位身份证号防浮点截断)
|
||||
o_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=15).value
|
||||
check("O列证件号文本格式", isinstance(o_val, str) and o_val == "110101199001010001", repr(o_val))
|
||||
|
||||
# ---------- 2.3 公式重算(可用则走真实链路,否则兜底填值) ----------
|
||||
print("\n== 步骤2:公式重算 ==")
|
||||
if com_ok:
|
||||
try:
|
||||
wps_recalc.recalc_target(target_path)
|
||||
check("目标表公式重算", True)
|
||||
except Exception as e:
|
||||
com_ok = False
|
||||
check("目标表公式重算", False, str(e))
|
||||
if not com_ok:
|
||||
# 兜底:把 P/Q/W 直接填为值(模拟已重算的公式缓存),保证调度链路可继续
|
||||
wb1 = load_workbook(target_path)
|
||||
ws1 = wb1[cfg.SHEET_BIZ]
|
||||
for r, (p, q, w, v) in {
|
||||
5: ("一类", "人保-50万", "增加投保", "三十七度-后厨"),
|
||||
6: ("二类", "人保-20万", "增加投保", "三十七度-前厅"),
|
||||
7: ("三类", "人保-80万", "要替换", "三十七度-后勤"),
|
||||
8: ("一类", "人保-20万", "/", None),
|
||||
}.items():
|
||||
ws1.cell(row=r, column=16, value=p)
|
||||
ws1.cell(row=r, column=17, value=q)
|
||||
ws1.cell(row=r, column=23, value=w)
|
||||
ws1.cell(row=r, column=22, value=v)
|
||||
wb1.save(target_path)
|
||||
print("(提示:本机 COM 重算不可用,已兜底直接填公式列值)")
|
||||
|
||||
# ---------- 2.4 三阶段名额调度 ----------
|
||||
print("\n== 步骤3:三阶段名额调度 ==")
|
||||
final_records = schedule_mod.schedule_category(category,
|
||||
enable_validation=True,
|
||||
gen_import_files=True)
|
||||
check("调度生成参保记录=3", len(final_records) == 3, f"实际 {len(final_records)}")
|
||||
|
||||
# ---------- 2.5 断言在参名单更新 ----------
|
||||
wb2 = load_workbook(target_path)
|
||||
ws_in = wb2[cfg.SHEET_IN_PARAM]
|
||||
expect_in = {
|
||||
17: ("10001", "110101199001010001", "人保-50万"), # 张三 全新新增
|
||||
18: ("10002", "110101199002010002", "人保-20万"), # 李四 复用钱十名额
|
||||
19: ("10010", "110101199110100010", "人保-50万"), # 陈十一 保留
|
||||
20: ("10003", "110101198906010003", "人保-80万"), # 王五 追加新行
|
||||
}
|
||||
for row_idx, (code, emp_id, scheme) in expect_in.items():
|
||||
c_b = ws_in.cell(row=row_idx, column=2).value
|
||||
c_k = ws_in.cell(row=row_idx, column=11).value
|
||||
c_m = ws_in.cell(row=row_idx, column=13).value
|
||||
check(f"在参名单第{row_idx}行: {code}/{emp_id}/{scheme}",
|
||||
str(c_b) == code and str(c_k) == emp_id and c_m == scheme,
|
||||
f"实际 B={c_b!r} K={c_k!r} M={c_m!r}")
|
||||
|
||||
# ---------- 2.6 断言变更清单 ----------
|
||||
chg_name = cfg.category_change_sheet_name(category)
|
||||
ws_chg = wb2[chg_name]
|
||||
expect_chg = {
|
||||
3: ("删除", "钱十", "110101199009010009", "人保-20万"),
|
||||
4: ("增加", "张三", "110101199001010001", "人保-50万"),
|
||||
5: ("增加", "李四", "110101199002010002", "人保-20万"),
|
||||
6: ("修改", "王五", "110101198906010003", "人保-80万"),
|
||||
}
|
||||
for row_idx, (op, name, emp_id, scheme) in expect_chg.items():
|
||||
got = (ws_chg.cell(row=row_idx, column=2).value,
|
||||
ws_chg.cell(row=row_idx, column=16).value,
|
||||
ws_chg.cell(row=row_idx, column=17).value,
|
||||
ws_chg.cell(row=row_idx, column=19).value)
|
||||
check(f"变更清单第{row_idx}行: {op} {name}",
|
||||
got == (op, name, emp_id, scheme), f"实际 {got}")
|
||||
check("变更清单 张三 带四级部门", ws_chg.cell(row=4, column=15).value == "三十七度-后厨",
|
||||
repr(ws_chg.cell(row=4, column=15).value))
|
||||
check("变更清单 王五 备注替换说明",
|
||||
ws_chg.cell(row=6, column=13).value == "由人保-20万替换为人保-80万",
|
||||
repr(ws_chg.cell(row=6, column=13).value))
|
||||
|
||||
# ---------- 2.7 断言备份 ----------
|
||||
backup = cfg.category_output_backup(category)
|
||||
check("备份新在参名单存在", os.path.isfile(backup))
|
||||
if os.path.isfile(backup):
|
||||
df_backup = pd.read_excel(backup)
|
||||
check("备份含 3 条参保记录", len(df_backup) == 3, f"实际 {len(df_backup)}")
|
||||
|
||||
# ---------- 2.8 断言增/减员导入 ----------
|
||||
add_file = cfg.category_import_add_file(category)
|
||||
sub_file = cfg.category_import_sub_file(category)
|
||||
df_add = pd.read_excel(add_file, header=2)
|
||||
df_sub = pd.read_excel(sub_file, header=2)
|
||||
check("增员导入=3 条", len(df_add) == 3, f"实际 {len(df_add)}")
|
||||
check("减员导入=2 条", len(df_sub) == 2, f"实际 {len(df_sub)}")
|
||||
add_codes = [str(v) for v in df_add.iloc[:, 1].tolist()]
|
||||
sub_codes = [str(v) for v in df_sub.iloc[:, 1].tolist()]
|
||||
check("增员含 张三/李四/王五", sorted(add_codes) == ["10001", "10002", "10003"], repr(add_codes))
|
||||
check("减员含 钱十/王五", sorted(sub_codes) == ["10003", "10009"], repr(sub_codes))
|
||||
|
||||
# ---------- 2.9 断言变更清单独立工作簿 ----------
|
||||
ok_wb = report_output.export_change_sheet_workbook(category)
|
||||
wb_out = cfg.category_change_sheet_workbook(category)
|
||||
check("导出变更清单独立工作簿", ok_wb and os.path.isfile(wb_out))
|
||||
if os.path.isfile(wb_out):
|
||||
wb3 = load_workbook(wb_out, data_only=True)
|
||||
ws3 = wb3[chg_name]
|
||||
check("独立工作簿 保留 4 条变更", ws3.cell(row=3, column=2).value == "删除"
|
||||
and ws3.cell(row=6, column=2).value == "修改",
|
||||
f"第3行={ws3.cell(row=3, column=2).value!r} 第6行={ws3.cell(row=6, column=2).value!r}")
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
print("\n" + "=" * 60)
|
||||
failed = [r for r in RESULTS if not r[1]]
|
||||
print(f"共 {len(RESULTS)} 项检查,通过 {len(RESULTS) - len(failed)} 项,失败 {len(failed)} 项")
|
||||
for name, ok, detail in RESULTS:
|
||||
if not ok:
|
||||
print(f" FAIL {name}: {detail}")
|
||||
print(f"测试数据目录(可人工核查):{WORK_DIR}")
|
||||
sys.exit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user