Files
37duAutomation/plugins/XQ0001-0100/XQ0008 重庆社保增减员办理/logic/roster_gen.py
T

286 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0008 重庆社保增减员导入名单制作(generate_add.py / generate_stop.py 移植)。
- make_add_lists():按参保类型(转移参保 / 新参保)分组生成《XX增员导入名单.xls》,
分别输出到 转移参保-增员 / 新参保-增员 子目录(xlrd 读取 + xlutils 复制模板保留下拉字典);
日期规则:首次参加工作日期=本月1号、个人身份=24.工人、工伤参保时间=当日、其余参保时间=本月1号。
- make_stop_lists():按参保单位生成《XX减员导入名单.xls》到 停保-减员 子目录;
减少时间=离职日期(当月)否则=当天、减少原因=在职人员主动解除劳动合同、
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职。
"""
import os
from datetime import datetime
from .. import config
from ..data import source_reader
# ==================== 翻译映射 ====================
def _translate_education(val):
if val is None:
return '90.其他'
try:
import pandas as pd
if pd.isna(val):
return '90.其他'
except (TypeError, ValueError):
pass
return config.EDU_MAP.get(str(val).strip(), '90.其他')
def _translate_nation(val):
if val is None:
return '99.其他'
try:
import pandas as pd
if pd.isna(val):
return '99.其他'
except (TypeError, ValueError):
pass
return config.NATION_MAP.get(str(val).strip(), '99.其他')
def _translate_residence(val):
if val is None:
return ''
try:
import pandas as pd
if pd.isna(val):
return ''
except (TypeError, ValueError):
pass
return config.RESIDENCE_MAP.get(str(val).strip(), '')
# ==================== 增员名单制作 ====================
def _write_template_add(template_file, output_path, unit_no, unit_name, records):
"""复制《增员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留 Sheet2 下拉字典;
B1=社保号,D1=参保单位全称;数据从模板第4行起,按 TPL_COLS_ADD 顺序写入 B~U 列;
日期列以 yyyy/m/d 文本写入(工伤=当日,其余已填本月1日);多余示例行清空。
"""
import xlrd
from xlutils.copy import copy as xl_copy
rb = xlrd.open_workbook(template_file, formatting_info=True)
orig_rows = rb.sheet_by_index(0).nrows
wb = xl_copy(rb)
ws = wb.get_sheet(0) # 批量导入
ws.write(0, 1, config._clean_value(unit_no)) # B1 社保号
ws.write(0, 3, config._clean_value(unit_name)) # D1 参保单位全称
for i, rec in enumerate(records):
r = config.TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
for c, col in enumerate(config.TPL_COLS_ADD):
val = rec.get(col)
if col in config.DATE_COLS_ADD and val is not None:
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
else:
ws.write(r, c + 1, config._clean_value(val))
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
for c in range(1, len(config.TPL_COLS_ADD) + 1):
ws.write(r, c, "")
os.makedirs(os.path.dirname(output_path), exist_ok=True)
wb.save(output_path)
def _find_template_add():
"""定位《增员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *增员模版*.xls)。"""
from glob import glob
tpl_dir = config.roster_template_dir()
exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
if os.path.isfile(exact):
return exact
candidates = glob(os.path.join(tpl_dir, "*增员模版*.xls"))
if not candidates:
raise FileNotFoundError(
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_ADD}》,请先准备增员导入模板。")
return max(candidates, key=os.path.getmtime)
def _add_output_dir(operation_type):
"""按参保类型取输出目录(社保增减名单制作/新参保-增员 或 转移参保-增员)。"""
sub = {"新参保": config.OUTPUT_DIR_ADD_NEW,
"转移参保": config.OUTPUT_DIR_ADD_TRANS}.get(operation_type)
if not sub:
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.ADD_TYPES)})")
out_dir = config.roster_output_dir(sub)
os.makedirs(out_dir, exist_ok=True)
return out_dir
def process_add_members(operation_type):
"""生成增员导入名单(operation_type: '新参保' 或 '转移参保')。返回生成的份数。"""
sub, source_file, _sheet, _ = source_reader.load_records(
"add", operation_type=operation_type, status_filter="empty")
config.log(f"源表:{os.path.basename(source_file)}")
if sub.empty:
config.log(f"没有找到【{operation_type}】的数据({config.TARGET_REGION}区域,办理状态为空)")
return 0
today, first_day = datetime.now(), datetime.now().replace(day=1)
config.log(f"今日日期:{today:%Y-%m-%d};本月1日:{first_day:%Y-%m-%d}"
f"(首次参加/养老/失业/医疗/生育参保时间);工伤参保时间=当日")
template_file = _find_template_add()
output_dir = _add_output_dir(operation_type)
config.log(f"输出目录:{output_dir}")
n_files = 0
for store_name, group in sub.groupby(config.COLUMN_MAP_ADD['单位名称']):
config.log(f" 正在处理:{store_name},共 {len(group)} 人")
first_row = group.iloc[0]
unit_no = first_row[config.COLUMN_MAP_ADD['社保号']]
unit_full_name = first_row[config.COLUMN_MAP_ADD['参保单位全称']]
records = []
for _, row in group.iterrows():
rec = {
'证件号码': config._to_text(row[config.COLUMN_MAP_ADD['证件号码']]),
'姓名': row[config.COLUMN_MAP_ADD['姓名']],
'民族': _translate_nation(row[config.COLUMN_MAP_ADD['民族']]),
'首次参加工作日期': first_day,
'月基本工资额': config._clean_value(row[config.COLUMN_MAP_ADD['月基本工资额']]),
'工种': config.DEFAULT_VALUES_ADD['工种'],
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
'户口性质': _translate_residence(row[config.COLUMN_MAP_ADD['户口性质']]),
'联系电话': config._to_text(row[config.COLUMN_MAP_ADD['联系电话']]),
'文化程度': _translate_education(row[config.COLUMN_MAP_ADD['文化程度']]),
'养老保险参保时间': first_day,
'失业保险参保时间': first_day,
'医疗保险参保时间': first_day,
'工伤保险参保时间': today,
'生育保险参保时间': first_day,
'证件类型': config.DEFAULT_VALUES_ADD['证件类型'],
'国籍': config.DEFAULT_VALUES_ADD['国籍'],
'备注': config.DEFAULT_VALUES_ADD['备注'],
'专职技能': config.DEFAULT_VALUES_ADD['专职技能'],
'技能等级': config.DEFAULT_VALUES_ADD['技能等级'],
}
records.append(rec)
output_path = os.path.join(output_dir,
f"{config._safe_name(store_name)}增员导入名单.xls")
_write_template_add(template_file, output_path, unit_no, unit_full_name, records)
config.log(f" 已生成:{output_path}")
n_files += 1
config.log(f"所有【{operation_type}】导入名单生成完成!")
return n_files
def make_add_lists():
"""增员名单制作:依次生成 转移参保 / 新参保 两类名单。返回 (总份数, 结果明细)。"""
total, detail = 0, {}
for op_type in config.ADD_TYPES:
n = process_add_members(op_type)
total += n
detail[op_type] = n
return total, detail
# ==================== 减员名单制作 ====================
def _write_template_stop(template_file, output_path, unit_no, unit_full_name, records):
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。"""
import xlrd
from xlutils.copy import copy as xl_copy
rb = xlrd.open_workbook(template_file, formatting_info=True)
orig_rows = rb.sheet_by_index(0).nrows
wb = xl_copy(rb)
ws = wb.get_sheet(0) # 批量导入
ws.write(0, 1, config._clean_value(unit_no)) # B1 单位社保号
ws.write(0, 3, config._clean_value(unit_full_name)) # D1 单位全称
for i, rec in enumerate(records):
r = config.TPL_DATA_START_ROW - 1 + i
for c, col in enumerate(config.TPL_COLS_STOP):
val = rec.get(col)
if col in config.DATE_COLS_STOP and val is not None:
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
else:
ws.write(r, c + 1, config._clean_value(val))
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
for c in range(1, len(config.TPL_COLS_STOP) + 1):
ws.write(r, c, "")
os.makedirs(os.path.dirname(output_path), exist_ok=True)
wb.save(output_path)
def _find_template_stop():
"""定位《减员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *减员模版*.xls)。"""
from glob import glob
tpl_dir = config.roster_template_dir()
exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
if os.path.isfile(exact):
return exact
candidates = glob(os.path.join(tpl_dir, "*减员模版*.xls"))
if not candidates:
raise FileNotFoundError(
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_STOP}》,请先准备停保导入模板。")
return max(candidates, key=os.path.getmtime)
def _resolve_reduce_time(raw, today):
"""减少时间取值规则:离职日期为当月日期 → 减少时间=离职日期;否则=当天。"""
try:
import pandas as pd
dt = pd.to_datetime(raw, errors='coerce')
except (TypeError, ValueError):
dt = None
if dt is not None and getattr(dt, 'year', None) == today.year and dt.month == today.month:
return dt, True
return today, False
def process_stop_members():
"""生成停保导入名单。返回生成的份数。"""
sub, source_file, _sheet, _ = source_reader.load_records(
"stop", status_filter="empty")
config.log(f"源表:{os.path.basename(source_file)}")
if sub.empty:
config.log(f"没有筛选到数据(类型 ∈ {'/'.join(config.STOP_TYPES)} ∩ "
f"区域={config.TARGET_REGION} ∩ 办理停保为空)")
return 0
today = datetime.now()
config.log(f"制作日期:{today:%Y-%m-%d}")
template_file = _find_template_stop()
output_dir = config.roster_output_dir(config.OUTPUT_DIR_STOP)
os.makedirs(output_dir, exist_ok=True)
config.log(f"输出目录:{output_dir}")
n_files, n_leave_date = 0, 0
for group_key, group in sub.groupby(config.COLUMN_MAP_STOP['单位名称']):
config.log(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
first_row = group.iloc[0]
unit_no = first_row[config.COLUMN_MAP_STOP['单位社保号']]
unit_full_name = first_row[config.COLUMN_MAP_STOP['单位全称']]
records = []
for _, row in group.iterrows():
reduce_time, from_leave = _resolve_reduce_time(
row[config.STOP_LEAVE_DATE_COL], today)
if from_leave:
n_leave_date += 1
rec = {
'个人编号': config._clean_value(row[config.COLUMN_MAP_STOP['个人编号']]),
'证件号码': config._clean_value(row[config.COLUMN_MAP_STOP['证件号码']]),
'姓名': config._clean_value(row[config.COLUMN_MAP_STOP['姓名']]),
'减少时间': reduce_time,
'减少原因': config.DEFAULT_VALUES_STOP['减少原因'],
'养老保险减少标志': config.DEFAULT_VALUES_STOP['养老保险减少标志'],
'失业保险减少标志': config.DEFAULT_VALUES_STOP['失业保险减少标志'],
'医疗保险减少标志': config.DEFAULT_VALUES_STOP['医疗保险减少标志'],
'工伤保险减少标志': config.DEFAULT_VALUES_STOP['工伤保险减少标志'],
'生育保险减少标志': config.DEFAULT_VALUES_STOP['生育保险减少标志'],
'失业原因': config.DEFAULT_VALUES_STOP['失业原因'],
}
records.append(rec)
output_path = os.path.join(output_dir,
f"{config._safe_name(group_key)}减员导入名单.xls")
_write_template_stop(template_file, output_path, unit_no, unit_full_name, records)
config.log(f" 已生成:{output_path}")
n_files += 1
config.log(f"所有停保导入名单生成完成!共 {len(sub[config.COLUMN_MAP_STOP['单位名称']].unique())} 个单位")
config.log(f"减少时间取值:{n_leave_date} 人取离职日期,"
f"{len(sub) - n_leave_date} 人取当天({today:%Y-%m-%d})")
return n_files
def make_stop_lists():
"""减员名单制作。返回 (份数, 结果明细)。"""
n = process_stop_members()
return n, {"停保-减员": n}