Files
37duAutomation/plugins/XQ0001-0100/XQ0002 雇主险增减操作/__init__.py
T
puddy 4941e8b6c0 feat(plugin): 新增 XQ0006 周考勤异常处理、XQ0083 调动流程生效确认;其余插件累积改动
XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
2026-11-18 18:55:59 +08:00

291 lines
16 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 -*-
"""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「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别;
不依赖「生成导入文件」开关,文件缺失/0 条的类别自动跳过);
8) 钉钉群通知(可选开关,默认开启):汇总 + 增/减员导入异常名单推送到钉钉群
(失败不影响主流程)。
仅导入模式(only_import=True):以上 1)~6) 全部跳过,只执行 7)(导入文件须已生成)。
运行上下文:底座注入 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 /
only_import / 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.21"
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))
only_import = bool(fields.get("only_import", False))
# 导入方式:api=纯接口(默认,无浏览器弹窗);ui=浏览器自动化兜底
config.set_import_mode(fields.get("import_mode", "api"))
# 仅导入模式:跳过前置全部步骤,只把已有导入文件导进 HR
if only_import:
import_to_hr = True
# 自动导入只看本开关:导入素材为各类别文件夹中已有的增/减员导入文件
# (本次生成或此前已生成),文件缺失/无待导入条目的类别由 hr_import 预检跳过
import_on = import_to_hr
if import_to_hr and not only_import and not gen_import_files:
ctx.log("已关闭「生成增/减员导入文件」:将直接导入各类别文件夹中已有的导入文件"
"(文件不存在或 0 条的类别自动跳过)", "INFO")
if not categories:
raise ValueError("未选择任何类别")
notes: list = []
if only_import:
return self._run_import_only(categories, ctx, notes, base_dir, dingtalk_notify)
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)
# ---- 步骤1.5:职位序列补全(所属单位=灸生生事业部 且 职位序列为空 → 按岗位映射回填花名册) ----
try:
_, unmatched = roster_filter.fill_post_sequence(roster_path)
if unmatched:
notes.append(f"花名册职位序列补全:以下「{config.POST_SEQ_FILL_UNIT}」员工职位序列为空"
f"且岗位不在映射表内,请核对:{';'.join(unmatched)}")
except Exception as e:
notes.append(f"花名册职位序列补全失败(不影响后续流程):{e}")
ctx.log(f"花名册职位序列补全失败:{e}", "WARN")
# ---- 步骤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 自动导入中断(登录态失效,已提交的部分请在 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()}
def _run_import_only(self, categories, ctx, notes, base_dir, dingtalk_notify):
"""仅导入模式:跳过花名册导出/筛选复制/公式重算/名额调度/文件生成,
直接把各类别文件夹中已有的增/减员导入文件导进 HR(先减员后增员)。"""
ctx.log("===== 仅导入HR系统:跳过花名册导出、筛选复制、公式重算、名额调度、"
"变更清单导出与导入文件生成,只导入已有增/减员导入文件 =====", "INFO")
ctx.progress(5)
def _on_progress(done, total):
ctx.progress(5 + int(93 * done / max(total, 1)))
import_results = []
try:
import_results = hr_import.import_all(categories, on_progress=_on_progress)
except hr_import.LoginRequiredError as e:
notes.append(f"HR 自动导入中断(登录态失效,已提交的部分请在 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)
import_lines = hr_import.summarize_results(import_results) if import_results else []
import_text = ";".join(import_lines) if import_lines else \
"无可导入条目(各类别导入文件不存在或 A 列无序号)"
summary = ("雇主险仅导入HR系统完成({date}):处理 {total} 个类别。"
"HR 导入结果:{text}。(本次未执行花名册导出/筛选复制/公式重算/"
"名额调度/变更清单导出与导入文件生成)").format(
date=config.today_date(), total=len(categories), text=import_text)
if notes:
summary += "\n注意事项:\n- " + "\n- ".join(notes)
if dingtalk_notify:
notify.push_run_result(total=len(categories), filtered=0,
scheduled=len(categories), import_on=True,
import_lines=import_lines,
import_results=import_results, notes=notes,
only_import=True)
else:
ctx.log("钉钉群通知已关闭,跳过推送", "INFO")
return {"summary": summary, "notes": notes,
"detail": {"处理类别": len(categories), "仅导入": True},
"path": base_dir, "date": config.today_date()}
PLUGINS.append(EmployerInsurancePlugin())