docs: 更新 AGENTS/README 平台架构说明与月度总结,运行日志视图支持已取消状态

This commit is contained in:
2026-10-31 17:55:25 +08:00
parent e1b4097573
commit b976b80d9d
201 changed files with 11049 additions and 7398 deletions
@@ -1,279 +1,279 @@
# -*- 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.16"
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)
# ---- 步骤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()}
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 自动导入未执行(登录态缺失):{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())
# -*- 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.18"
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)
# ---- 步骤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())
@@ -7,7 +7,7 @@ zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插
用法(任意 cwd 均可):
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0002 雇主险增减操作\\_pack.py"
随后发布:
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
.venv\\Scripts\\python.exe tools\\agent_cli.py publish \
dist-plugin\\xq0002_v<版本>.zip --id xq0002 --version <版本>
"""
import json
@@ -18,16 +18,18 @@
关键事实(决定了不需要抓包、也没有一次性 token 门槛):
- importId 是导入模板的固定配置 id,写死在弹窗页 hidden input 中;
- businessId 由前端 guid() 生成、每次导入唯一,接口版自行 uuid4();
- titleList 是字段映射数组 JSON 的 base64,无签名;
- businessId 由前端 guid() 生成(36 位带连字符)、每次导入唯一,接口版用 uuid4();
- titleList 是字段映射数组 JSON 经「前端 Base64.tranCode.encode」编码的结果:自定义字符表
Base64 + 固定盐 + 首尾重排(非标准 base64;编码错会让服务端 uploadDataSax 抛空指针、
任务根本不入队,后续只能查到全 0 的结果);
- 写库只发生在 uploadData,checkFileType 纯校验(读文件比对表头)。
"""
import base64
import json
import os
import time
import uuid
from urllib.parse import quote
from datetime import datetime, timedelta
from urllib.parse import quote, unquote
import requests
@@ -42,6 +44,19 @@ CHECK_FILE_TYPE_URL = BASE_URL + IMP_DO + "/checkFileType.mc"
UPLOAD_DATA_URL = BASE_URL + IMP_DO + "/uploadData.mc"
GET_IMPORT_RESULT_URL = BASE_URL + IMP_DO + "/getImportResult.mc"
GET_TMP_DATA_PAGE_URL = BASE_URL + IMP_DO + "/getTmpDataPage.mc"
# 失败数据页(注意:这两个不在 /do 下,是导入模块的列表/明细接口)
IMP_BASE = CONTEXT_PATH + "/hr/module/base/import"
GET_IMPORT_FAILURE_LIST_URL = BASE_URL + IMP_BASE + "/getImportFailurePageAjax.mc"
GET_FAIL_PAGE_URL = BASE_URL + IMP_BASE + "/getFailPage.mc"
# 「待增减人员」列表(核对本次入库用:导入成功的人会带当天 ext_operate_time 留在列表里)
PENDING_ROSTER_ID = "7984ae1a-16ec-11ed-bea9-822ff8ed5b28"
PENDING_LIST_URL = (BASE_URL + CONTEXT_PATH + "/hrRoster/"
+ PENDING_ROSTER_ID + "/queryRealTimeData.mc")
GET_CUR_USER_INFO_URL = BASE_URL + CONTEXT_PATH + "/PtUsers.mc?method=getCurUserInfo"
PENDING_ORG_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28" # 集团节点(页面固定值)
PENDING_ROLE_IDS = "POST_SYS_ADMIN,renshi" # 与花名册查询口径一致
PENDING_PAGE_SIZE = 100
# 两个导入模板的固定配置 id(取自「待增减人员」页按钮配置,勿改)
IMPORT_MENUS = {
@@ -63,6 +78,7 @@ XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
RETRY_TIMES = 3 # 只读接口重试次数(项目级规范)
RETRY_INTERVAL = 1.0
PAGE_SIZE = 15 # getTmpDataPage 固定 15 条/页
FAIL_LIST_PAGE_SIZE = 50 # 导入失败批次列表每页条数(同一天可能有多个批次)
POLL_TIMEOUT_SECONDS = 300 # 导入结果轮询上限(与前端"排队等候"提示口径一致)
POLL_INTERVAL_SECONDS = 2.0
@@ -111,16 +127,39 @@ def build_session():
# ==================== HTTP 基础 ====================
# HR 会话失效有两种表现:① 页面被重定向到登录页(HTML);② 接口返回 HTTP 200 +
# JSON {"state":"Nosession","meg":"会话过期,请重新登录!"}。后者不是 HTTP 错误,
# 不识别就会被当成"导入处理中/无结果"一直轮询到 POLL_TIMEOUT,最终误报"待人工确认"。
SESSION_EXPIRED_STATES = ("nosession", "no_session", "sessiontimeout", "session_timeout")
SESSION_EXPIRED_KEYWORDS = ("会话过期", "会话已失效", "重新登录", "登录已超时", "登录超时")
def _raise_if_session_expired(data, desc):
"""识别「会话失效」类响应并抛 LoginRequiredError(HTTP 200 也会出现,必须按业务字段判定)。"""
if not isinstance(data, dict):
return
state = str(data.get("state") or "").strip()
meg = str(data.get("meg") or "").strip()
expired = state.lower() in SESSION_EXPIRED_STATES \
or any(k in meg for k in SESSION_EXPIRED_KEYWORDS)
if expired:
raise LoginRequiredError(
f"{desc} 提示会话失效(state={state or '-'},meg={meg or '-'}),"
"HR 登录态已失效,请在插件界面重新登录 HR 后重试。")
def _parse_json(resp, desc):
"""解析接口响应;返回登录页等非 JSON 内容时判定登录态失效。"""
"""解析接口响应;登录页 HTML 或会话失效 JSON 均判定为登录态失效。"""
text = resp.text or ""
try:
return resp.json()
data = resp.json()
except Exception:
if "j_username" in text or "login" in text.lower()[:2000]:
raise LoginRequiredError(
f"{desc} 返回登录页,HR 登录态已失效,请在插件界面重新登录 HR。")
raise RuntimeError(f"{desc} 响应非 JSON(HTTP {resp.status_code}):{text[:200]}")
_raise_if_session_expired(data, desc)
return data
def _multipart_post(session, url, data, file_path=None, timeout=120):
@@ -185,9 +224,75 @@ def _post_json(session, url, data, desc, file_path=None, timeout=120):
raise RuntimeError(f"{desc} 请求失败(已重试 {RETRY_TIMES} 次):{last}")
# titleList 提交前要用前端 Base64.tranCode.encode 编码:自定义字符表 Base64 + 固定盐 +
# 首尾重排(与 commonQuery 同源,仅少一步 URI 编码)。用标准 base64 会导致服务端解不出
# 字段映射(titleList 为 null),uploadDataSax 直接抛 NullPointerException、任务不入队。
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
_TITLE_SALT = "yyryrtweasdasd"
def _custom_base64_encode(data):
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列,'7' 对应填充位)。"""
result = []
for i in range(0, len(data), 3):
chunk = data[i:i + 3]
b1 = chunk[0] if len(chunk) > 0 else 0
b2 = chunk[1] if len(chunk) > 1 else 0
b3 = chunk[2] if len(chunk) > 2 else 0
enc1 = (b1 >> 2) & 0x3F
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
enc4 = b3 & 0x3F
if len(chunk) == 1:
enc3 = enc4 = 64
elif len(chunk) == 2:
enc4 = 64
result.append(_CUSTOM_CHARS[enc1])
result.append(_CUSTOM_CHARS[enc2])
result.append(_CUSTOM_CHARS[enc3])
result.append(_CUSTOM_CHARS[enc4])
return "".join(result)
def _custom_base64_decode(enc_str):
"""自定义字符表 Base64 解码('7' 为填充符),与 _custom_base64_encode 互逆。"""
index = {c: i for i, c in enumerate(_CUSTOM_CHARS)}
pad = enc_str.count("7")
enc_str = enc_str.replace("7", "")
data = bytearray()
for i in range(0, len(enc_str), 4):
chunk = enc_str[i:i + 4].ljust(4, "7")
n = ((index[chunk[0]] << 18) | (index[chunk[1]] << 12)
| (index[chunk[2]] << 6) | index[chunk[3]])
data.extend([(n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF])
if pad:
data = data[:-pad]
return bytes(data)
def _b64(value):
"""与前端 Base64.tranCode.encode 等价(标准 base64,UTF-8)。"""
return base64.b64encode(str(value).encode("utf-8")).decode("ascii")
"""等价前端 Base64.tranCode.encode:自定义 Base64 + 盐值 + 首尾重排(titleList 专用)。"""
raw = str(value).encode("utf-8")
en_str = _custom_base64_encode(raw) + _TITLE_SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
def _decode_hr_text(value):
"""解码 HR 接口返回的加密文案(uploadData 的 des / meg),失败返回原文。
入参/文件异常时 uploadData 返回 {"state":"0","meg":null,"des":"<加密串>"},
解密后才是真正的错误(如服务端异常堆栈),不解码只能看到一串乱码。
"""
text = str(value or "").strip()
if len(text) < 8:
return text
try:
en_str = text[:2] + text[5:] + text[2:5]
if en_str.endswith(_TITLE_SALT):
en_str = en_str[:-len(_TITLE_SALT)]
return unquote(_custom_base64_decode(en_str).decode("utf-8", errors="replace"))
except Exception:
return text
# ==================== 1. 弹窗配置 ====================
@@ -286,11 +391,25 @@ def submit_upload(session, conf, file_path, title_list, business_id):
data["businessId"] = business_id
try:
resp = _multipart_post(session, UPLOAD_DATA_URL, data, file_path=file_path, timeout=180)
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
return True
except Exception as e:
logger.warning("导入请求提交异常(结果未知,转轮询判定):%s", e)
return False
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
# 会话失效时上传同样返回 HTTP 200 + state=Nosession(任务并未受理):
# 这里立即判定登录态,避免"其实没受理"却继续轮询到超时、误报待人工确认
try:
payload = resp.json()
except Exception:
payload = None
_raise_if_session_expired(payload, f"{conf.get('title') or ''}导入提交")
if isinstance(payload, dict) and str(payload.get("state")) != "1":
# 服务端受理失败(多为入参/文件让它抛异常):des/meg 是加密文案,解码后写日志,
# 否则后续只会轮询到全 0 结果、报"待人工确认",真正原因看不到
detail = _decode_hr_text(payload.get("des")) or _decode_hr_text(payload.get("meg"))
logger.error("导入提交未被受理(state=%s):%s", payload.get("state"),
detail.replace("\n", " ")[:500] if detail else "-")
return False
return True
def get_import_result(session, import_id, business_id):
@@ -343,6 +462,8 @@ def fetch_exceptions(session, import_id, business_id):
try:
result = _post_json(session, GET_TMP_DATA_PAGE_URL, data,
f"导入明细第 {page_no} 页", timeout=30)
except LoginRequiredError:
raise # 登录态失效必须上报,不能当成"无异常行"吞掉
except Exception as e:
logger.warning("导入明细第 %s 页拉取失败:%s", page_no, e)
break
@@ -372,6 +493,247 @@ def fetch_exceptions(session, import_id, business_id):
return exceptions
def query_fail_batches(session, import_id, date_begin=None, date_end=None):
"""查某模板在指定时间段内的导入失败批次(「导入失败记录」列表接口)。
业务语义:导入提交后系统自动把校验通过的数据入库、把失败的返回明细;
只有存在失败数据时才会在此列表里生成批次(全成功的批次不会出现)。
Returns:
list[dict]:{business_id, operator_time, total}(total 为该批次失败条数);无记录返回 []。
"""
today = date_begin or time.strftime("%Y-%m-%d")
data = {
"root_id": "",
"excelImpVersion": "2",
"functionCode": import_id,
"date_begin": today,
"date_end": date_end or (today + " 23:59:59"),
"start": "0",
"sortType": "",
"sortName": "",
"pageNo": "1",
"pageSize": str(FAIL_LIST_PAGE_SIZE),
}
result = _post_json(session, GET_IMPORT_FAILURE_LIST_URL, data,
"导入失败批次列表", timeout=30)
if str(result.get("state")) != "1":
logger.info("导入失败批次列表无结果(state=%s)", result.get("state"))
return []
batches = []
for item in result.get("datas") or []:
item = item or {}
bid = str(item.get("businessid") or "").strip()
if not bid:
continue
try:
total = int(item.get("total") or 0)
except (TypeError, ValueError):
total = 0
batches.append({"business_id": bid,
"operator_time": str(item.get("operator_time") or ""),
"total": total})
return batches
def fetch_fail_page(session, import_id, business_id):
"""分页拉取某批次的失败明细(官方「失败数据」页接口 getFailPage.mc)。
字段口径与 getTmpDataPage 一致(imp_fixed_msg / 工号 / 姓名 / 方案),
「导入成功」行不计入异常。
"""
exceptions = []
page_no = 1
page_count = 1
while page_no <= page_count:
data = {
"excelImpVersion": "2",
"functionCode": import_id,
"businessId": business_id,
"start": str((page_no - 1) * PAGE_SIZE),
"pageNo": str(page_no),
"pageSize": str(PAGE_SIZE),
"commonQuery": "[]",
"sortType": "",
"sortName": "",
}
try:
result = _post_json(session, GET_FAIL_PAGE_URL, data,
f"失败数据第 {page_no} 页", timeout=30)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("失败数据第 %s 页拉取失败:%s", page_no, e)
break
if str(result.get("state")) != "1":
break
try:
page_count = max(1, int(result.get("pageCount") or 1))
except (TypeError, ValueError):
page_count = 1
for item in result.get("datas") or []:
item = item or {}
msg = str(item.get("imp_fixed_msg", "") or "").strip()
if not msg or "导入成功" in msg:
continue
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 item.get("sicut_o_rel_ext_insurance_name") or ""),
"message": msg,
})
page_no += 1
return exceptions
# ==================== 8. 入库核对(待增减人员列表 · 操作时间) ====================
def _date_params():
"""列表查询需要的动态日期参数(当月/上月/当年首月),与花名册查询口径一致。"""
now = datetime.now()
last = now.replace(day=1) - timedelta(days=1)
return {
"currentDate": now.strftime("%Y-%m-%d"),
"currentMonth": now.strftime("%Y%m"),
"currentMonthBar": now.strftime("%Y-%m"),
"lastMonth": last.strftime("%Y%m"),
"lastMonFirstDay": last.strftime("%Y-%m-01"),
"lastMonLastDay": last.strftime("%Y-%m-%d"),
"curYearFirstMon": f"{now.year}01",
"curYearFirstMonBar": f"{now.year}-01",
}
def _encode_common_query(conditions):
"""查询条件列表 -> commonQuery(JSON -> URI 编码 -> 自定义 Base64 + 盐 -> 首尾重排)。"""
json_str = json.dumps(conditions, ensure_ascii=False, separators=(",", ":"))
en_str = _custom_base64_encode(quote(json_str, safe="-_.~!*'()").encode("utf-8")) + _TITLE_SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
def _current_user_id(session):
"""取当前登录用户 userId/staffId(列表查询参数用),失败返回空 dict。"""
try:
data = _post_json(session, GET_CUR_USER_INFO_URL, {}, "当前用户信息", timeout=30)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("取当前用户信息失败(沿用内置参数):%s", e)
return {}
return data if isinstance(data, dict) else {}
def query_operated_staff(session, started_at, end_at=None, max_pages=80):
"""查「待增减人员」列表里商业保险操作时间落在 [started_at, end_at] 的人员。
业务含义:导入提交后系统自动把成功数据入库,这些人会带着本次的
si_add_cut_person_sp_cq37du.ext_operate_time 留在列表中;失败的人不会带上本次操作时间。
据此可与导入文件工号比对,确认"本次到底入库了哪些人"。
Args:
started_at: "YYYY-MM-DD HH:MM:SS"(导入提交前的时间点)
end_at: 结束时间,默认现在
Returns:
list[dict]:{staff_code, staff_name, scheme, operate_time, add_date, cut_date}
"""
end_at = end_at or time.strftime("%Y-%m-%d %H:%M:%S")
field = "`si_add_cut_person_sp_cq37du.ext_operate_time`"
conditions = [
{"queryField": field, "leftBracket": "(", "queryType": ">=", "queryValue": started_at,
"queryText": started_at, "rightBracket": "", "logic": "AND", "inputType": "date"},
{"queryField": field, "leftBracket": "", "queryType": "<=", "queryValue": end_at,
"queryText": end_at, "rightBracket": ")", "logic": "AND", "inputType": "date"},
]
info = _current_user_id(session)
root = info.get("rootId") or "cq37du"
params = {
"menuName": "待增减人员",
"_t": str(int(time.time() * 1000)),
"in_use": "1",
"commonQuery": _encode_common_query(conditions),
"newCondition": "",
"urlConditions": "",
"exportConfig": "",
"tableId": "assemble-hr_staff_base",
"rosterId": PENDING_ROSTER_ID,
"includeChildrenSetting": "",
"struTreeCode": root,
"djStruTreeCode": "", "djStruId": "", "djOrgName": "",
"struId": PENDING_ORG_STRU_ID,
"belongUnitStruId": PENDING_ORG_STRU_ID,
"rootId": root,
"isVirtual": "0",
"currentUserRootId": root,
"currentUserId": info.get("userId") or "",
"currentRoleIds": PENDING_ROLE_IDS,
"currentStaffId": info.get("staffId") or "",
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
"qrCodeUrl": "jspresumepage-01.jsp",
"orgName": "集团", "belongUnitOrgName": "集团",
"throughParam": "",
"start": "0", "sortType": "", "sortName": "",
"pageNo": "1", "pageSize": str(PENDING_PAGE_SIZE),
}
params.update(_date_params())
rows = []
page_no = 1
while page_no <= max_pages:
params["pageNo"] = str(page_no)
params["start"] = str((page_no - 1) * PENDING_PAGE_SIZE)
data = _post_json(session, PENDING_LIST_URL, params,
f"待增减人员操作记录第 {page_no} 页", timeout=60)
if str(data.get("state")) != "1":
logger.info("待增减人员列表无结果(state=%s)", data.get("state"))
break
datas = data.get("datas") or []
for item in datas:
item = item or {}
code = str(item.get("a_sp_cq37du.base_code") or "").strip()
if not code:
continue
rows.append({
"staff_code": code,
"staff_name": str(item.get("hr_staff_base.staff_name") or ""),
"scheme": str(item.get("si_add_cut_person_sp_cq37du.ext_insurance_name") or ""),
"operate_time": str(item.get("si_add_cut_person_sp_cq37du.ext_operate_time") or ""),
"add_date": str(item.get("si_add_cut_person_sp_cq37du.ext_add_per_date") or ""),
"cut_date": str(item.get("si_add_cut_person_sp_cq37du.ext_cut_per_date") or ""),
})
try:
page_count = int(data.get("pageCount") or 1)
except (TypeError, ValueError):
page_count = 1
if page_no >= page_count or not datas:
break
page_no += 1
return rows
def _read_import_codes(file_path):
"""读导入文件里的工号集合(第 4 行起 A 列序号非空视为有效数据行,取 B 列)。"""
from openpyxl import load_workbook
codes = set()
try:
wb = load_workbook(file_path, read_only=True, data_only=True)
except Exception as e:
logger.warning("读取导入文件失败(跳过入库核对):%s", e)
return codes
try:
ws = wb[wb.sheetnames[0]]
for row in ws.iter_rows(min_row=4, max_col=2, values_only=True):
if not row:
continue
seq, code = (list(row) + [None, None])[:2]
if seq in (None, "") or code in (None, ""):
continue
codes.add(str(code).strip())
finally:
wb.close()
return codes
def import_one_file(session, menu, file_path):
"""对单个导入文件执行完整接口导入(校验 -> 导入 -> 结果 -> 明细)。
@@ -416,8 +778,11 @@ def import_one_file(session, menu, file_path):
logger.info("%s表头匹配 %d/%d 列", label, matched, len(title_list))
# 4) 提交导入(唯一写操作,businessId 每次唯一)
business_id = uuid.uuid4().hex
# 必须与前端 guid() 同格式(36 位带连字符):HR 的失败记录/ws 消息 key 都按该字符串关联,
# 用 uuid4().hex(32 位无连字符)会导致服务端任务与查询对不上号
business_id = str(uuid.uuid4())
out["business_id"] = business_id
started_at = time.strftime("%Y-%m-%d %H:%M:%S") # 入库核对的时间起点(提交前)
submit_upload(session, conf, file_path, title_list, business_id)
# 5) 轮询结果
@@ -440,8 +805,71 @@ def import_one_file(session, menu, file_path):
out["other"] = _int("other")
out["meg"] = str(result.get("meg") or "")
# 6) 失败明细
# 6) 失败明细:官方「失败数据」页接口优先,弹窗明细接口兜底
if not out["is_success"]:
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
out["exceptions"] = fetch_fail_page(session, conf["id"], business_id)
if not out["exceptions"]:
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
# 7) 当天失败批次核对:列表里能看到本批次的失败条数(全成功的批次不会出现在这里),
# 既验证"这批确实被受理并处理过",也能和明细条数互校
try:
batches = query_fail_batches(session, conf["id"])
hit = next((b for b in batches if b["business_id"] == business_id), None)
out["batch_found"] = bool(hit)
out["batch_total"] = hit["total"] if hit else 0
if hit:
logger.info("%s当天失败批次已确认:%s(操作时间 %s,失败 %s 条)",
label, business_id, hit["operator_time"], hit["total"])
if out["exceptions"] and len(out["exceptions"]) != hit["total"]:
logger.warning("%s失败明细条数(%d)与批次统计(%d)不一致,请人工核对",
label, len(out["exceptions"]), hit["total"])
elif out["is_success"]:
logger.info("%s全部成功,当天失败批次列表无本批次记录(符合预期)", label)
else:
logger.warning("%s未在当天失败批次列表中找到本批次(%s),结果请人工核对",
label, business_id)
except LoginRequiredError:
raise
except Exception as e:
logger.warning("%s当天失败批次核对失败(不影响主流程):%s", label, e)
# 8) 入库核对:本次成功入库的人会带本次操作时间出现在「待增减人员」列表,
# 用导入文件工号做交集,确认"到底哪些人入库了"(失败的人不会带本次操作时间)
try:
codes = _read_import_codes(file_path)
if codes:
operated = query_operated_staff(session, started_at)
op_codes = {o["staff_code"] for o in operated}
if menu == "sub":
# 减员成功表现为"人员从待增减列表移除",因此仍在列表的人才是需要核对的;
# 例外:同一人也在本批增员文件里(换方案替换)→ 增员后会重新出现在列表,属正常
still = codes & op_codes
out["operated_count"] = len(codes) - len(still)
out["operated_missing"] = sorted(still)
logger.info("%s减员核对:文件 %d 人,已从待增减列表移除 %d 人(操作时间 ≥ %s)",
label, len(codes), len(codes) - len(still), started_at)
if still:
logger.info("%s仍在待增减列表 %d 人(同时在本批增员文件中的属正常替换,余者请核对):%s",
label, len(still), "、".join(sorted(still)[:20]))
else:
# 增员成功表现为"带本次操作时间出现在待增减列表"
hit = codes & op_codes
out["operated_count"] = len(hit)
out["operated_missing"] = sorted(codes - hit)
logger.info("%s入库核对:文件 %d 人,列表命中 %d 人(操作时间 ≥ %s)",
label, len(codes), len(hit), started_at)
if out["operated_missing"]:
logger.warning("%s未在列表命中 %d 人:%s", label,
len(out["operated_missing"]),
"、".join(out["operated_missing"][:20]))
if out["is_success"] and len(hit) < len(codes):
logger.warning("%s接口返回全部成功,但列表只命中 %d/%d 人,请人工核对",
label, len(hit), len(codes))
except LoginRequiredError:
raise
except Exception as e:
logger.warning("%s入库核对失败(不影响主流程):%s", label, e)
out["ok"] = True
return out
@@ -568,8 +568,10 @@ def _import_all_api(categories, on_progress=None):
results = []
units = []
for c in categories:
for menu in (MENU_SUB, MENU_ADD):
# ★ 顺序不可换:先全部类别【减员】,再全部类别【增员】
# (替换/改方案人员必须先撤旧方案再上新方案,否则会因方案冲突报错)
for menu in (MENU_SUB, MENU_ADD):
for c in categories:
label = "减员" if menu == MENU_SUB else "增员"
file_path = _import_file_path(c, menu)
if not os.path.isfile(file_path):
@@ -645,6 +647,10 @@ def _map_api_result(category, menu_label, expected_total, res):
success = int(res.get("success") or 0)
fail = (int(res.get("check_fail") or 0) + int(res.get("save_fail") or 0)
+ int(res.get("other") or 0))
# 系统会把校验通过的数据自动入库:isSuccess=1 但接口未回填条数时按文件条数推定,
# 避免汇总里出现"全部成功却显示成功 0 条"(与 UI 版 assume 口径一致)
if res.get("is_success") and success <= 0:
success = expected_total
exceptions = res.get("exceptions") or []
for exc in exceptions:
logger.error(" - [%s/%s] 方案[%s]:%s", exc["staff_code"], exc["staff_name"],
@@ -698,8 +704,10 @@ def _import_all_ui(categories, on_progress=None):
# ---- 预检:按导入文件实际条数过滤出真正需要导入的单元(类别×菜单) ----
results = []
units = []
for c in categories:
for menu in (MENU_SUB, MENU_ADD):
# ★ 顺序不可换:先全部类别【减员】,再全部类别【增员】
# (替换/改方案人员必须先撤旧方案再上新方案,否则会因方案冲突报错)
for menu in (MENU_SUB, MENU_ADD):
for c in categories:
label = "减员" if menu == MENU_SUB else "增员"
file_path = _import_file_path(c, menu)
if not os.path.isfile(file_path):
@@ -763,6 +771,8 @@ def summarize_results(results):
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
业务规则:提交后系统自动把校验通过的数据入库、失败的数据返回明细,因此
「成功 N 条」即已入库条数,「异常 M 条」即被退回条数,两者相加应等于需导入条数;
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败;
跳过单元(skipped,无待导入条目)正常纳入统计(需导入 0 条),不报失败/待确认。
"""
@@ -775,9 +785,12 @@ def summarize_results(results):
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
flow_failed = [r["category"] for r in rs if r.get("error")]
# 有成功条数说明这批数据已按业务规则入库(系统自动入库成功部分、失败部分返回明细),
# 即便 isSuccess 不为 1 也无需人工确认,直接按「成功 N 条 + 异常明细」汇报
unconfirmed = [r["category"] for r in rs
if not r.get("error") and not r.get("exceptions")
and not r.get("assumed_all_success") and not r.get("skipped")
and not (r.get("success_count") or 0)
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
extras = []
@@ -1,99 +1,116 @@
{
"schema_version": 1,
"id": "xq0002",
"name": "雇主险增减操作",
"version": "1.0.16",
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
"category": "人事",
"icon": "",
"platform": "hr",
"uses_month": false,
"ui": true,
"capabilities": ["xq0002"],
"permissions": {
"platforms": ["hr"]
},
"fields": {
"type": "object",
"properties": {
"base_dir": {
"type": "string",
"title": "雇主险根目录",
"default": "D:\\资料\\人资\\雇主险",
"description": "四类各占一个子文件夹(三十七度/水庄餐饮/湖畔酒店/秒创传媒),增/减员导入模板放在根目录"
},
"ref_date": {
"type": "string",
"title": "业务日期",
"default": "",
"description": "留空=今天;影响变更清单/在参名单/导入文件中的日期与备份文件名"
},
"categories": {
"type": "array",
"title": "处理类别(可多选)",
"items": {
"type": "string",
"enum": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"]
},
"default": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"],
"description": "留空=全部类别"
},
"roster_path": {
"type": "string",
"title": "花名册路径",
"default": "",
"description": "留空=根目录/员工花名册.xlsx(源表缺失或超过 15 分钟 TTL 时自动从 HR 导出)"
},
"enable_validation": {
"type": "boolean",
"title": "启用数据校验",
"default": true,
"description": "校验工种类别与投保方案合法性,校验失败终止调度"
},
"wps_recalc": {
"type": "boolean",
"title": "WPS/Excel 后台重算公式",
"default": true,
"description": "筛选复制后/调度后自动打开目标文件取消全部筛选并全量重算公式保存,替代人工取消筛选与 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
},
"export_change_sheet": {
"type": "boolean",
"title": "导出变更清单独立工作簿",
"default": true,
"description": "调度后将各类别变更清单 sheet 复制为独立工作簿(公式转值,保留样式)"
},
"gen_import_files": {
"type": "boolean",
"title": "生成增员/减员导入文件",
"default": true,
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
},
"only_import": {
"type": "boolean",
"title": "运行模式·仅导入HR系统(跳过前置步骤)",
"default": false,
"description": "开启后跳过花名册导出、筛选复制、公式重算、名额调度、变更清单导出与导入文件生成,只用各类别文件夹中已有(已生成好)的增/减员导入文件执行 HR 导入;此模式下「自动导入HR系统」恒为开启(无其他动作)"
},
"import_to_hr": {
"type": "boolean",
"title": "自动导入HR系统",
"default": true,
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(先减员后增员,仅导入本次调度成功的类别);导入素材为各类别文件夹中已有的导入文件(本次生成或此前生成均可,文件缺失/0 条的类别自动跳过)"
},
"import_mode": {
"type": "string",
"title": "HR 导入方式",
"enum": ["api", "ui"],
"default": "api",
"description": "api=纯接口导入(默认,不打开浏览器、无弹窗,可无人值守);ui=浏览器自动化(旧实现,保留作兜底,需本机 Chrome/Edge)"
},
"dingtalk_notify": {
"type": "boolean",
"title": "钉钉群通知",
"default": true,
"description": "执行完成后推送结果汇总与增/减员导入异常名单到钉钉群(推送失败不影响主流程)"
}
},
"required": []
}
}
{
"schema_version": 1,
"id": "xq0002",
"name": "雇主险增减操作",
"version": "1.0.18",
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
"category": "人事",
"icon": "",
"platform": "hr",
"uses_month": false,
"ui": true,
"capabilities": [
"xq0002"
],
"permissions": {
"platforms": [
"hr"
]
},
"fields": {
"type": "object",
"properties": {
"base_dir": {
"type": "string",
"title": "雇主险根目录",
"default": "D:\\资料\\人资\\雇主险",
"description": "四类各占一个子文件夹(三十七度/水庄餐饮/湖畔酒店/秒创传媒),增/减员导入模板放在根目录"
},
"ref_date": {
"type": "string",
"title": "业务日期",
"default": "",
"description": "留空=今天;影响变更清单/在参名单/导入文件中的日期与备份文件名"
},
"categories": {
"type": "array",
"title": "处理类别(可多选)",
"items": {
"type": "string",
"enum": [
"三十七度",
"水庄餐饮",
"湖畔酒店",
"秒创传媒"
]
},
"default": [
"三十七度",
"水庄餐饮",
"湖畔酒店",
"秒创传媒"
],
"description": "留空=全部类别"
},
"roster_path": {
"type": "string",
"title": "花名册路径",
"default": "",
"description": "留空=根目录/员工花名册.xlsx(源表缺失或超过 15 分钟 TTL 时自动从 HR 导出)"
},
"enable_validation": {
"type": "boolean",
"title": "启用数据校验",
"default": true,
"description": "校验工种类别与投保方案合法性,校验失败终止调度"
},
"wps_recalc": {
"type": "boolean",
"title": "WPS/Excel 后台重算公式",
"default": true,
"description": "筛选复制后/调度后自动打开目标文件取消全部筛选并全量重算公式保存,替代人工取消筛选与 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
},
"export_change_sheet": {
"type": "boolean",
"title": "导出变更清单独立工作簿",
"default": true,
"description": "调度后将各类别变更清单 sheet 复制为独立工作簿(公式转值,保留样式)"
},
"gen_import_files": {
"type": "boolean",
"title": "生成增员/减员导入文件",
"default": true,
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
},
"only_import": {
"type": "boolean",
"title": "运行模式·仅导入HR系统(跳过前置步骤)",
"default": false,
"description": "开启后跳过花名册导出、筛选复制、公式重算、名额调度、变更清单导出与导入文件生成,只用各类别文件夹中已有(已生成好)的增/减员导入文件执行 HR 导入;此模式下「自动导入HR系统」恒为开启(无其他动作)"
},
"import_to_hr": {
"type": "boolean",
"title": "自动导入HR系统",
"default": true,
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(先减员后增员,仅导入本次调度成功的类别);导入素材为各类别文件夹中已有的导入文件(本次生成或此前生成均可,文件缺失/0 条的类别自动跳过)"
},
"import_mode": {
"type": "string",
"title": "HR 导入方式",
"enum": [
"api",
"ui"
],
"default": "api",
"description": "api=纯接口导入(默认,不打开浏览器、无弹窗,可无人值守);ui=浏览器自动化(旧实现,保留作兜底,需本机 Chrome/Edge)"
},
"dingtalk_notify": {
"type": "boolean",
"title": "钉钉群通知",
"default": true,
"description": "执行完成后推送结果汇总与增/减员导入异常名单到钉钉群(推送失败不影响主流程)"
}
},
"required": []
}
}
@@ -99,7 +99,7 @@ export function usePluginUI(opts = {}) {
let pollTimer = null
let saveTimer = null
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
const notify = (type, text) => { notice.value = type ? { type, text } : null }
// ---------- 当前配置:加载 / 防抖自动保存 ----------
@@ -303,7 +303,8 @@ export function usePluginUI(opts = {}) {
ws = connectWS((ev) => {
if (ev.run_id && ev.run_id !== runId) return
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
// 用户强制停止 / 排队取消 / 排队超时 → 「已取消」,不显示成「执行失败」
else if (ev.t === 'run_done') ev.ok ? finished() : (ev.status === 'cancelled' ? cancelled(ev.error) : failed(ev.error || '执行失败'))
})
ws.onclose = () => { ws = null }
}
@@ -315,6 +316,7 @@ export function usePluginUI(opts = {}) {
try {
const r = await getRun(runId)
if (r.status === 'done') finished(r.result?.summary)
else if (r.status === 'cancelled') cancelled(r.error)
else if (r.status === 'error') failed(r.error || '执行失败')
} catch (_) { /* 下轮再试 */ }
}, 5000)
@@ -332,6 +334,13 @@ export function usePluginUI(opts = {}) {
if (summary) notify('ok', summary)
}
// 用户主动停止 / 排队取消 / 排队超时:不算失败,给中性的「已取消」提示
function cancelled(err) {
stopPolling()
running.value = false
notify('warn', '任务已取消:' + (err || '用户已停止'))
}
function failed(err) {
stopPolling()
running.value = false
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>雇主险增减操作</title>
<script type="module" crossorigin src="/pui/xq0002/assets/index-CrTAowxb.js"></script>
<script type="module" crossorigin src="/pui/xq0002/assets/index-qdX0x8H0.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-BPnwGsXm.css">
</head>
<body>