# -*- coding: utf-8 -*- """XQ0002 雇主险增减操作 插件入口。 流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式): 1) 花名册确保:源表缺失或超过 TTL(15 分钟)时自动从 HR 接口导出,新鲜度内复用; 2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本); 3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值); 4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份; 5) 再次重算公式(刷新变更清单/在参名单公式列缓存); 6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值); 7) HR 自动导入(可选开关,默认开启):浏览器自动化把调度生成的导入文件导入 HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别); 8) 钉钉群通知(可选开关,默认开启):汇总 + 增/减员导入异常名单推送到钉钉群 (失败不影响主流程)。 运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。 字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path / enable_validation / wps_recalc / export_change_sheet / gen_import_files / import_to_hr / dingtalk_notify。 """ import os from webhost.backend.plugins.base import ScenePlugin, PLUGINS from . import config from .logic import roster_filter, schedule, hr_import from .logic.wps_recalc import recalc_target, ComRecalcError from .report import notify, output class EmployerInsurancePlugin(ScenePlugin): """雇主险名额调度(需求 XQ0002)。""" id = "xq0002" name = "雇主险增减操作" version = "1.0.8" description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→" "三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件" "(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单," "替代人工 Ctrl+S 刷新公式与人工上传导入环节") platform = "hr" uses_month = False capabilities = ["xq0002"] permissions = {"platforms": ["hr"]} def run(self, fields: dict, ctx): # ---- 注入运行上下文:日志 / HR 会话 / userId ---- config.set_log(ctx.log) config.set_user_id(ctx.get_user_id("hr")) session = None try: session = ctx.get_session("hr") except Exception as e: ctx.log(f"HR 会话获取失败(花名册自动导出将回退共享 cookies):{e}", "WARN") config.set_session(session) # ---- 解析运行参数 ---- base_dir = (fields.get("base_dir") or "").strip() or config.DEFAULT_BASE_DIR config.set_base_dir(base_dir) config.set_ref_date(fields.get("ref_date") or "") cat_names = fields.get("categories") or [] categories = [config.get_category(n) for n in cat_names] if cat_names else list(config.CATEGORIES) roster_path = (fields.get("roster_path") or "").strip() enable_validation = bool(fields.get("enable_validation", True)) wps_recalc = bool(fields.get("wps_recalc", True)) export_change_sheet = bool(fields.get("export_change_sheet", True)) gen_import_files = bool(fields.get("gen_import_files", True)) import_to_hr = bool(fields.get("import_to_hr", True)) dingtalk_notify = bool(fields.get("dingtalk_notify", True)) import_on = import_to_hr and gen_import_files if import_to_hr and not gen_import_files: ctx.log("已开启「自动导入HR系统」但「生成导入文件」未开启,本次无可导入文件,导入步骤将跳过", "WARN") if not categories: raise ValueError("未选择任何类别") notes: list = [] ctx.log(f"===== 雇主险增减操作启动:业务日期 {config.today_date()},根目录 {base_dir} =====", "INFO") # ---- 步骤1:花名册确保(5% ~ 10%) ---- ctx.progress(5) try: roster_path = roster_filter.ensure_employee_file(roster_path, session) ctx.log(f"源表就绪:{roster_path}", "INFO") except Exception as e: notes.append(f"花名册准备失败(筛选复制与调度将受影响):{e}") ctx.log(f"花名册准备失败:{e}", "WARN") ctx.progress(10) # ---- 步骤2:筛选复制(10% ~ 45%) ---- ok_categories = [] n = len(categories) for i, category in enumerate(categories): ctx.progress(10 + int(35 * i / n)) try: roster_filter.filter_and_copy_roster(category, employee_path=roster_path) ok_categories.append(category) except Exception as e: notes.append(f"类别[{category['name']}] 筛选复制失败:{e}") ctx.log(f"类别[{category['name']}] 筛选复制失败:{e}", "WARN") ctx.progress(45) # ---- 步骤3:WPS/Excel 后台重算公式(45% ~ 60%,替代人工 Ctrl+S) ---- recalc_ok = {} if wps_recalc: for i, category in enumerate(ok_categories): ctx.progress(45 + int(15 * i / max(n, 1))) try: recalc_target(config.category_target_file(category)) recalc_ok[category["name"]] = True except ComRecalcError as e: notes.append(f"类别[{category['name']}] 公式重算失败(跳过该类别调度):{e}") ctx.log(f"类别[{category['name']}] 公式重算失败:{e}", "WARN") # 重算失败的类别不进入调度(公式缓存缺失会导致读取不到工种类别/投保方案/方案处理) to_schedule = [c for c in ok_categories if recalc_ok.get(c["name"])] else: ctx.log("已关闭 WPS/Excel 后台重算:请确认目标文件公式已人工刷新(打开保存过)," "否则调度将读取不到公式计算结果", "WARN") to_schedule = ok_categories ctx.progress(60) # ---- 步骤4:三阶段名额调度 ---- # 进度边界:开启 HR 导入时压缩为 60~80(步骤5/6/7 依次 80~84 / 84~90 / 90~100), # 关闭时沿用原 60~88 / 88~95 / 95~100 s4_end, s4_span = (80, 20) if import_on else (88, 28) s5_end, s5_span = (84, 4) if import_on else (95, 7) s6_end, s6_span = (90, 6) if import_on else (100, 5) scheduled = [] for i, category in enumerate(to_schedule): ctx.progress(60 + int(s4_span * i / max(len(to_schedule), 1))) try: schedule.schedule_category(category, enable_validation=enable_validation, gen_import_files=gen_import_files) scheduled.append(category) except schedule.DataValidationError: ctx.log("数据校验失败,已中断后续类别调度,请修正数据后重试", "ERROR") raise except Exception as e: notes.append(f"类别[{category['name']}] 调度失败:{e}") ctx.log(f"类别[{category['name']}] 调度失败:{e}", "WARN") ctx.progress(s4_end) # ---- 步骤5:再次重算公式(刷新变更清单/在参名单公式列缓存) ---- if wps_recalc: for i, category in enumerate(scheduled): ctx.progress(s5_end - s5_span + int(s5_span * i / max(len(scheduled), 1))) try: recalc_target(config.category_target_file(category)) except ComRecalcError as e: notes.append(f"类别[{category['name']}] 调度后重算失败(变更清单独立工作簿将取不到公式值):{e}") ctx.log(f"类别[{category['name']}] 调度后重算失败:{e}", "WARN") ctx.progress(s5_end) # ---- 步骤6:导出变更清单独立工作簿 ---- if export_change_sheet: for i, category in enumerate(scheduled): ctx.progress(s6_end - s6_span + int(s6_span * i / max(len(scheduled), 1))) try: output.export_change_sheet_workbook(category) except Exception as e: notes.append(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}") ctx.log(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}", "WARN") ctx.progress(s6_end) # ---- 步骤7:HR 自动导入(90% ~ 100%,仅本次调度成功的类别;先全部减员再全部增员) ---- import_results = [] if import_on: if not scheduled: ctx.log("无调度成功的类别,跳过 HR 自动导入", "WARN") else: def _on_import_progress(done, total): ctx.progress(90 + int(10 * done / max(total, 1))) ctx.log(f"开始 HR 自动导入:先全部【减员】后【增员】,共 {len(scheduled) * 2} 个导入单元") try: import_results = hr_import.import_all(scheduled, on_progress=_on_import_progress) except hr_import.LoginRequiredError as e: notes.append(f"HR 自动导入未执行(登录态缺失):{e}") ctx.log(f"HR 自动导入未执行:{e}", "ERROR") except Exception as e: notes.append(f"HR 自动导入整体失败:{e}") ctx.log(f"HR 自动导入整体失败:{e}", "ERROR") ctx.progress(100) # ---- 汇总 ---- detail = { "处理类别": len(categories), "筛选复制成功": len(ok_categories), "调度成功": len(scheduled), } import_lines = hr_import.summarize_results(import_results) \ if import_on and import_results else [] if import_on: import_text = ";".join(import_lines) if import_lines else "无导入结果" tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹。" f"HR 导入结果:{import_text}。") else: tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹," "请先执行【减员】导入再执行【增员】导入。") summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、" "调度成功 {scheduled} 个。{tail}").format( date=config.today_date(), total=len(categories), filtered=len(ok_categories), scheduled=len(scheduled), tail=tail) if notes: summary += "\n注意事项:\n- " + "\n- ".join(notes) # ---- 步骤8:钉钉群通知(汇总 + 导入异常名单;失败不影响主流程) ---- if dingtalk_notify: notify.push_run_result(total=len(categories), filtered=len(ok_categories), scheduled=len(scheduled), import_on=import_on, import_lines=import_lines, import_results=import_results, notes=notes) else: ctx.log("钉钉群通知已关闭,跳过推送", "INFO") return {"summary": summary, "notes": notes, "detail": detail, "path": base_dir, "date": config.today_date()} PLUGINS.append(EmployerInsurancePlugin())