feat(employer-insurance): 新增雇主险增减员导入功能与流程优化
本次提交完成雇主险增减员导入全流程升级,包括: 1. 新增姓名关键字过滤规则,自动剔除测试/人资账号数据 2. 新增变更清单独立工作簿导出功能,保留格式与公式 3. 重构增减员导入流程,监听接口捕获全量导入异常 4. 新增影刀版钉钉推送异常消息适配,支持块格式分组推送 5. 更新文档与配置项,同步维护app与影刀双版本代码
This commit is contained in:
@@ -9,7 +9,9 @@
|
||||
- 前置:步骤2 调度(employer_insurance.py)完成,并准备好增员/减员导入文件
|
||||
- 传入参数:增员(默认商业保险增员导入.xlsx)或 减员(商业保险减员导入.xlsx)
|
||||
- 复用 HR 登录态(app.service.hrbp.common.login 的缓存 cookies)
|
||||
@Version: 1.0.0
|
||||
@Version: 1.2.0
|
||||
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
|
||||
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块完成登录并缓存 cookies;后续自动复用,过期自动重新登录。
|
||||
@@ -22,6 +24,7 @@
|
||||
import_employee_change("增员", None, r"D:\\...\\xxx.xlsx") # 指定导入文件
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
@@ -70,6 +73,13 @@ WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
|
||||
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
|
||||
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行异常信息
|
||||
# (如「存在已参保的人员,不允许重复增员!」)。
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 元素定位辅助(DrissionPage)
|
||||
@@ -213,6 +223,87 @@ def _click_close(page):
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3.5 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听「第二个下一步:真正导入内容」结果接口(getTmpDataPage.mc),捕获返回的全部异常。
|
||||
|
||||
第一个「下一步」为格式校验(不监听);点击第二个「下一步」真正导入内容后,
|
||||
HR 系统会 POST getTmpDataPage.mc 返回导入结果:
|
||||
- state="1" 表示接口正常;meg 为全局提示;
|
||||
- datas[].imp_fixed_msg 非空表示该行存在异常(如「存在已参保的人员,不允许重复增员!」)。
|
||||
本函数合并该接口全部(含分页/多次)响应中的异常(不逐行单独处理),供流程统一上报。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"captured": bool, # 是否捕获到解析接口响应
|
||||
"state": str, # 接口 state(未捕获到为空串)
|
||||
"meg": str, # 全局提示
|
||||
"exceptions": [ # 全部异常明细
|
||||
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
|
||||
],
|
||||
}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": []}
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if req is None:
|
||||
# 0.5s 无新响应:若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if msg:
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 对外入口(函数传参调用)
|
||||
# ---------------------------------------------------------------
|
||||
@@ -228,12 +319,18 @@ _IMPORT_TYPE_MAP = {
|
||||
def _import_one(page, category, menu_label, file_path=None):
|
||||
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
第一个「下一步」为格式校验(不做处理);第二个「下一步」真正导入内容时会请求
|
||||
getTmpDataPage.mc,监听该接口捕获导入返回的全部异常;异常仅记录并上报,不中断导入流程。
|
||||
|
||||
Args:
|
||||
page: 已登录的 ChromiumPage 实例。
|
||||
category: 类别配置 dict。
|
||||
menu_label: 菜单文案(增员导入/减员导入)。
|
||||
file_path: 显式上传文件;不传则按类别文件夹取默认导入文件。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 导入文件不存在。
|
||||
"""
|
||||
@@ -246,10 +343,39 @@ def _import_one(page, category, menu_label, file_path=None):
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
_click_next(page) # 第一步:下一步(进入解析)
|
||||
_click_next(page) # 第二步:下一步(进入确认/完成)
|
||||
|
||||
_click_next(page) # 第一步:下一步(格式校验,不做处理)
|
||||
|
||||
# 第二步:点击「下一步」真正导入内容;同时监听 getTmpDataPage.mc 接口,捕获导入返回的全部异常
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
logger.warning("启动 %s 接口监听失败:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 上报:全部异常逐条打日志
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
|
||||
elif import_result["captured"] and import_result["state"] != "1":
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入正常,无异常", category["name"], menu_label)
|
||||
|
||||
_click_close(page) # 第三步:关闭
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
def import_employee_change(import_type="增员", category_names=None, file_path=None):
|
||||
@@ -263,7 +389,13 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
|
||||
不传则按各类别文件夹取 商业保险增员导入.xlsx / 商业保险减员导入.xlsx。
|
||||
|
||||
Returns:
|
||||
bool: 全部类别均成功返回 True;任一类别失败返回 False(失败已逐类打日志,不中断)。
|
||||
dict: {
|
||||
"success": bool, # 全部类别流程是否均完成
|
||||
"import_type": str, # 菜单文案(增员导入/减员导入)
|
||||
"categories": [str], # 类别名列表
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions)
|
||||
"exception_count": int, # 上传表格返回的异常总条数
|
||||
}
|
||||
|
||||
Raises:
|
||||
ValueError: import_type 非法。
|
||||
@@ -297,14 +429,29 @@ def import_employee_change(import_type="增员", category_names=None, file_path=
|
||||
_ensure_logged_in(page)
|
||||
|
||||
ok = 0
|
||||
results = []
|
||||
for category in categories:
|
||||
try:
|
||||
_import_one(page, category, menu_label, file_path)
|
||||
res = _import_one(page, category, menu_label, file_path)
|
||||
results.append(res)
|
||||
ok += 1
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||
logger.info("===== %s 全部完成(成功 %d/%d) =====", menu_label, ok, len(categories))
|
||||
return ok == len(categories)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"error": str(e),
|
||||
})
|
||||
exception_count = sum(len(r.get("exceptions") or []) for r in results)
|
||||
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
|
||||
menu_label, ok, len(categories), exception_count)
|
||||
return {
|
||||
"success": ok == len(categories),
|
||||
"import_type": menu_label,
|
||||
"categories": [c["name"] for c in categories],
|
||||
"results": results,
|
||||
"exception_count": exception_count,
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
@@ -319,17 +466,46 @@ def main(category_names=None):
|
||||
category_names: 类别名列表,空/None=全部类别。
|
||||
|
||||
Returns:
|
||||
{"success": bool, "categories": [...], "details": {"增员导入": bool, "减员导入": bool}}
|
||||
dict: {
|
||||
"success": bool, # 增员+减员全部类别是否均完成
|
||||
"categories": [str],
|
||||
"details": {"增员导入": bool, "减员导入": bool},
|
||||
"exceptions": [dict], # 上传表格返回的全部异常明细(合并增/减员)
|
||||
"exception_count": int, # 异常总条数
|
||||
}
|
||||
"""
|
||||
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||
else [c["name"] for c in CATEGORIES]
|
||||
details = {}
|
||||
exceptions = []
|
||||
ok_all = True
|
||||
for import_type in ("增员", "减员"):
|
||||
success = import_employee_change(import_type, category_names)
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = success
|
||||
ok_all = ok_all and success
|
||||
return {"success": ok_all, "categories": categories, "details": details}
|
||||
result = import_employee_change(import_type, category_names)
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
|
||||
ok_all = ok_all and result["success"]
|
||||
for r in result["results"]:
|
||||
for exc in r.get("exceptions") or []:
|
||||
exceptions.append({
|
||||
"category": r["category"],
|
||||
"menu": r["menu"],
|
||||
"staff_code": exc["staff_code"],
|
||||
"staff_name": exc["staff_name"],
|
||||
"insurance_name": exc["insurance_name"],
|
||||
"message": exc["message"],
|
||||
})
|
||||
if exceptions:
|
||||
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
|
||||
for exc in exceptions:
|
||||
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
|
||||
exc["category"], exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
return {
|
||||
"success": ok_all,
|
||||
"categories": categories,
|
||||
"details": details,
|
||||
"exceptions": exceptions,
|
||||
"exception_count": len(exceptions),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -115,6 +115,11 @@ 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}"
|
||||
|
||||
@@ -48,7 +48,7 @@ if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from copy import copy
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
@@ -70,6 +70,7 @@ from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_output_backup,
|
||||
category_change_sheet_workbook,
|
||||
category_change_sheet_name,
|
||||
category_import_add_file,
|
||||
category_import_sub_file,
|
||||
@@ -923,6 +924,63 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五点四、复制变更清单为独立工作簿
|
||||
# ============================================================
|
||||
def export_change_sheet_workbook(target_file, change_sheet_name, out_path):
|
||||
"""将目标文件中「变更清单」sheet 单独复制一份,另存为独立工作簿。
|
||||
|
||||
保留公式与样式(C~L/O 等公式列随行保留,Excel/WPS 打开时自动重算),
|
||||
供提交保险公司等场景直接使用,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
target_file: 目标文件路径(已含更新后的变更清单 sheet)。
|
||||
change_sheet_name: 变更清单 sheet 名(如「37度-雇员变更清单8.26」)。
|
||||
out_path: 独立工作簿保存路径。
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("目标文件不存在,跳过复制变更清单工作簿:%s", target_file)
|
||||
return False
|
||||
wb = load_workbook(target_file)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("工作簿中不存在变更清单 sheet [%s],跳过复制", change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值/公式 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("已复制变更清单为独立工作簿:%s(sheet:%s)", out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五点五、生成增减员导入文件(阶段4:步骤3上传素材)
|
||||
# ============================================================
|
||||
@@ -1163,6 +1221,14 @@ def schedule_category(category):
|
||||
name_corrections
|
||||
)
|
||||
|
||||
# ---------- 阶段3.5:复制变更清单为独立工作簿 ----------
|
||||
logger.info("复制变更清单为独立工作簿...")
|
||||
export_change_sheet_workbook(
|
||||
target_file,
|
||||
change_sheet_name,
|
||||
category_change_sheet_workbook(category),
|
||||
)
|
||||
|
||||
# ---------- 阶段4:生成增减员导入文件(步骤3上传素材) ----------
|
||||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||||
|
||||
|
||||
@@ -50,6 +50,10 @@ logger = get_logger(__name__)
|
||||
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
|
||||
|
||||
# N列 姓名在数据切片(B~O)内的 0-based 索引
|
||||
NAME_COL = 12
|
||||
|
||||
# 源表统一格式规范(roster_export._merge_roster_files 输出):
|
||||
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||||
@@ -103,9 +107,10 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 ----------
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~(region == EXCLUDE_REGION)
|
||||
@@ -113,10 +118,13 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」)",
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION)
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS))
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user