feat(xq0002): 完成雇主险增减操作插件开发并补齐配套资源
- 新增XQ0002雇主险增减操作插件完整实现,包含数据层、逻辑层、UI界面 - 新增测试用的样板数据文件与插件打包脚本 - 更新文档说明插件当前状态与使用方式 - 新增收银系统登录共享模块供业务流程复用
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件入口。
|
||||
|
||||
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
|
||||
1) 花名册确保:源表缺失且开启 auto_export 时自动从 HR 接口导出(TTL 15 分钟复用);
|
||||
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
|
||||
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。
|
||||
字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path /
|
||||
auto_export / enable_validation / wps_recalc / export_change_sheet / gen_import_files。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import roster_filter, schedule
|
||||
from .logic.wps_recalc import recalc_target, ComRecalcError
|
||||
from .report import output
|
||||
|
||||
|
||||
class EmployerInsurancePlugin(ScenePlugin):
|
||||
"""雇主险名额调度(需求 XQ0002)。"""
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.0"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件,"
|
||||
"替代人工 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()
|
||||
auto_export = bool(fields.get("auto_export", True))
|
||||
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))
|
||||
|
||||
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, auto_export, 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:三阶段名额调度(60% ~ 88%) ----
|
||||
scheduled = []
|
||||
for i, category in enumerate(to_schedule):
|
||||
ctx.progress(60 + int(28 * 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(88)
|
||||
|
||||
# ---- 步骤5:再次重算公式(88% ~ 95%,刷新变更清单/在参名单公式列缓存) ----
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(88 + int(7 * 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(95)
|
||||
|
||||
# ---- 步骤6:导出变更清单独立工作簿(95% ~ 100%) ----
|
||||
if export_change_sheet:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(95 + int(5 * 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(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
detail = {
|
||||
"处理类别": len(categories),
|
||||
"筛选复制成功": len(ok_categories),
|
||||
"调度成功": len(scheduled),
|
||||
}
|
||||
summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、"
|
||||
"调度成功 {scheduled} 个。增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
|
||||
"请先执行【减员】导入再执行【增员】导入。").format(
|
||||
date=config.today_date(), total=len(categories),
|
||||
filtered=len(ok_categories), scheduled=len(scheduled))
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
return {"summary": summary, "notes": notes, "detail": detail,
|
||||
"path": base_dir, "date": config.today_date()}
|
||||
|
||||
|
||||
PLUGINS.append(EmployerInsurancePlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件打包脚本(统一规范版,与 xq0011/xq0031 一致)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||
|
||||
用法(任意 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 \
|
||||
dist-plugin\\xq0002_v<版本>.zip --id xq0002 --version <版本>
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_REPO_ROOT = _HERE.parents[2]
|
||||
_OUT_DIR = _REPO_ROOT / "dist-plugin"
|
||||
|
||||
# 排除项:打包脚本自身 / 前端源码与依赖 / 缓存 / 调试文件
|
||||
_EXCLUDE_DIRS = {"ui-src", "node_modules", "__pycache__", ".git", ".idea", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid = manifest["id"]
|
||||
ver = manifest["version"]
|
||||
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
|
||||
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
count = 0
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
|
||||
or p.suffix in _EXCLUDE_SUFFIXES:
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
count += 1
|
||||
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,404 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log()/logger 输出日志、config.get_session()/get_user_id() 取登录态;
|
||||
运行参数(根目录 / 业务日期)由 __init__.py 的 run() 解析 fields 后注入(set_base_dir/set_ref_date)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
|
||||
# ==================== 共享目录(登录态/缓存,与影刀版同路径) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache')
|
||||
|
||||
# ==================== 默认根目录与业务日期(run() 注入覆盖) ====================
|
||||
DEFAULT_BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
|
||||
# ==================== 固定 Sheet 名称 ====================
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
|
||||
# ==================== 四大类别(合并调度/筛选口径,与 app 版 config 一致) ====================
|
||||
# 每类一个独立文件夹;include_dept/exclude_dept 用于筛选复制;
|
||||
# change_sheet_prefix 为各类「变更清单」sheet 名称前缀;scheme_suffix 为增员导入方案后缀。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# 过滤规则(与 aa.md 宏一致)
|
||||
EXCLUDE_REGIONS = ["虚拟大区"] # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"] # 姓名(N列)含这些关键字的行剔除
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
EXPORT_STATUSES = ["在职"]
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 数据切片(B~O)内 0-based 列索引
|
||||
CODE_COL = 4 # F列 工号(必须文本格式)
|
||||
JOIN_DATE_COL = 11 # M列 入职时间
|
||||
NAME_COL = 12 # N列 姓名
|
||||
ID_COL = 13 # O列 证件号(18位身份证号超出浮点精度,必须文本格式)
|
||||
|
||||
# ==================== 花名册列名映射(表头在第4行) ====================
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 在参名单数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ==================== 校验常量 ====================
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
# ==================== 增减员导入模板(雇主险根目录下官方模板) ====================
|
||||
ADD_IMPORT_TEMPLATE = "商业保险增员导入模板.xlsx"
|
||||
SUB_IMPORT_TEMPLATE = "商业保险减员导入模板.xlsx"
|
||||
|
||||
|
||||
# ==================== 运行参数钩子(run() 注入) ====================
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ref_date = None # datetime.date;None 表示今天
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
|
||||
def get_base_dir():
|
||||
return _base_dir
|
||||
|
||||
|
||||
def parse_ref_date(value):
|
||||
"""把 fields.ref_date(YYYY-MM-DD / YYYY.M.D 等)解析为 date;空返回今天。"""
|
||||
if not value:
|
||||
return date.today()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[-./年](\d{1,2})[-./月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
pass
|
||||
return date.today()
|
||||
|
||||
|
||||
def set_ref_date(value):
|
||||
global _ref_date
|
||||
_ref_date = parse_ref_date(value)
|
||||
|
||||
|
||||
def ref_date():
|
||||
"""业务日期(默认今天)。"""
|
||||
return _ref_date or date.today()
|
||||
|
||||
|
||||
def date_str():
|
||||
"""YYYY.M.D(目标表/备份文件名,如 2026.9.22)。"""
|
||||
return ref_date().strftime("%Y.%m.%d")
|
||||
|
||||
|
||||
def date_short():
|
||||
"""M.D(变更清单 sheet 后缀,不补前导零,如 9.22 / 9.1)。"""
|
||||
return f"{ref_date().month}.{ref_date().day}"
|
||||
|
||||
|
||||
def today_date():
|
||||
"""YYYY-MM-DD(批改日期/增员减员日期/投保日期)。"""
|
||||
return ref_date().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 类别辅助函数 ====================
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(ref_date().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||||
os.path.getmtime(path))
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
def _category_dir(category):
|
||||
"""类别文件夹(base_dir 运行时可能被覆盖,须实时拼接而非 import 时固化)。"""
|
||||
return os.path.join(get_base_dir(), category["name"])
|
||||
|
||||
|
||||
def category_folder(category):
|
||||
return _category_dir(category)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(_category_dir(category))
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"新在参名单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"{category['name']}-雇员变更清单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
|
||||
return f"{category['change_sheet_prefix']}{date_short()}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险减员导入.xlsx")
|
||||
|
||||
|
||||
def add_import_template():
|
||||
return os.path.join(get_base_dir(), ADD_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def sub_import_template():
|
||||
return os.path.join(get_base_dir(), SUB_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def employee_file(path=""):
|
||||
"""花名册路径:传入优先,否则 {base_dir}\\员工花名册.xlsx。"""
|
||||
return (path or "").strip() or os.path.join(get_base_dir(), "员工花名册.xlsx")
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
# ==================== 文本/日期辅助函数(logic/report 层共用) ====================
|
||||
def to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||||
|
||||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||||
"""
|
||||
import numbers
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def clean_text(value):
|
||||
"""转可写文本;None/NaN/空白返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def parse_join_date(value):
|
||||
"""解析入职时间为 date 对象(兼容 datetime/字符串「YYYY-MM-DD」「YYYY.M.D」等)。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[.\-/年](\d{1,2})[.\-/月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return _dt(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def to_date(value):
|
||||
"""将日期/日期字符串统一转为 date 对象;无法解析时返回 None。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"):
|
||||
try:
|
||||
return _dt.strptime(s, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 data 层:花名册导出(接口版)。"""
|
||||
@@ -0,0 +1,453 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 员工花名册导出(接口版,由 xq0011 插件同模块内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
|
||||
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 内置「雇主险增减员导出模板」(B~O 共 14 列:所属单位→证件号,与 app 版 roster_template 一致);
|
||||
3. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, EXPORT_TEMPLATE, EXPORT_STATUSES
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
# 「雇主险增减员导出模板」(14 列 + 序号,B~O:所属单位→证件号,与 app 版 roster_template 一致)
|
||||
ROSTER_TEMPLATE_FILTERS_EMPLOYER = ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
])
|
||||
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数 ----------
|
||||
DEFAULT_TEMPLATE = EXPORT_TEMPLATE # 雇主险增减员导出模板
|
||||
DEFAULT_STATUSES = list(EXPORT_STATUSES) # ["在职"]
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
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 = 64
|
||||
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 build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
|
||||
def _build_session(session=None):
|
||||
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
|
||||
if session is not None:
|
||||
return session
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name):
|
||||
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
|
||||
try:
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
|
||||
return None
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先在插件界面重新完成 HR 登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
|
||||
_bind_session(session)
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
|
||||
单 sheet,表头在第1行,数据第2行起。
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None,
|
||||
ttl=DEFAULT_TTL_SECONDS, session=None):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_roster 一致。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
"""
|
||||
download_dir = download_dir or os.path.dirname(output_path or "") or "."
|
||||
output_path = output_path or "花名册.xlsx"
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None:
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
|
||||
template_name, statuses, leave_desc)
|
||||
|
||||
session = _build_session(session)
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 logic 层:筛选复制 + 三阶段名额调度 + WPS/Excel 重算。"""
|
||||
@@ -0,0 +1,162 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 筛选复制(由影刀版 roster_filter.py v2.0.0 移植)。
|
||||
|
||||
从员工花名册按类别 include/exclude 所属单位筛选数据,复制到各自类别目标表
|
||||
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
|
||||
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
|
||||
|
||||
源表缺失时调用 data.roster_export_api.export_roster 自动导出(auto_export 开关),
|
||||
替代影刀版对 share/roster_export.py 的懒加载;登录态经底座注入的 session。
|
||||
"""
|
||||
import os
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SOURCE_HEADER_MARK, EXPORT_TEMPLATE, EXPORT_STATUSES,
|
||||
TARGET_HEADER_ROW, DATA_COLUMNS, CODE_COL, ID_COL, JOIN_DATE_COL, NAME_COL,
|
||||
EXCLUDE_REGIONS, EXCLUDE_NAME_KEYWORDS, category_folder, employee_file,
|
||||
find_latest_target, to_text, parse_join_date, ref_date, CACHE_DIR,
|
||||
)
|
||||
from ..data.roster_export_api import export_roster
|
||||
|
||||
|
||||
def _read_source(employee_path):
|
||||
"""读取源表(员工花名册):自动定位表头行(B 列=「所属单位」),返回 B~O 14 列切片。"""
|
||||
probe = pd.read_excel(employee_path, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_path, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
return data[data.iloc[:, 0].notna()]
|
||||
|
||||
|
||||
def filter_and_copy_roster(category, employee_path="", target_file=None):
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(含 name/include_dept/exclude_dept)
|
||||
employee_path: 源表路径,默认 {base_dir}\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_path = os.path.abspath(employee_path or employee_file())
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category_folder(category)))
|
||||
|
||||
if not os.path.exists(employee_path):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_path}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表并过滤 ----------
|
||||
data = _read_source(employee_path)
|
||||
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.isin(EXCLUDE_REGIONS)
|
||||
if include_dept:
|
||||
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)
|
||||
|
||||
# 入职时间 > 业务日期 的行剔除(未来才入职的员工暂不纳入,留到当天再筛选出来)
|
||||
today = ref_date()
|
||||
join_dates = data.iloc[:, JOIN_DATE_COL].map(parse_join_date)
|
||||
future_mask = join_dates.map(lambda d: d is not None and d > today)
|
||||
n_future = int(future_mask.sum())
|
||||
mask &= ~future_mask
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除 %s,姓名剔除含 %s,剔除未来入职 %d 人)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", " / ".join(EXCLUDE_REGIONS),
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS), n_future)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 2. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据;F列工号 / O列证件号 强制文本格式)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
c = cell(row=i, column=j)
|
||||
# 工号/证件号为主键:18位身份证号超出浮点精度,文本化避免截断,保证公式/映射匹配
|
||||
if j - 2 in (CODE_COL, ID_COL):
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ensure_employee_file(employee_path="", auto_export=True, session=None):
|
||||
"""确保花名册源表存在:缺失且 auto_export 时自动调用 HR 接口导出,否则抛错。
|
||||
|
||||
Args:
|
||||
employee_path: 花名册路径(留空=默认根目录/员工花名册.xlsx)
|
||||
auto_export: 源表缺失时是否自动导出
|
||||
session: 底座注入的 HR 会话(导出时使用)
|
||||
|
||||
Returns:
|
||||
源表绝对路径
|
||||
"""
|
||||
path = os.path.abspath(employee_path or employee_file())
|
||||
if os.path.exists(path):
|
||||
logger.info("源表已存在:%s,跳过导出", path)
|
||||
return path
|
||||
if not auto_export:
|
||||
raise FileNotFoundError(f"源表不存在:{path}")
|
||||
logger.info("源表不存在:%s,自动调用花名册导出...", path)
|
||||
export_roster(
|
||||
download_dir=os.path.join(CACHE_DIR, "roster_tmp"),
|
||||
output_path=path,
|
||||
template_name=EXPORT_TEMPLATE,
|
||||
statuses=EXPORT_STATUSES,
|
||||
session=session,
|
||||
)
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"花名册导出完成但源表仍不存在:{path}")
|
||||
return path
|
||||
@@ -0,0 +1,559 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 三阶段名额调度(由影刀版 employer_insurance_schedule.py v1.3.0 移植)。
|
||||
|
||||
阶段0 初始化(空闲名额池 / 当前参保映射 / 待转入队列)→
|
||||
阶段1 处理业务(增加投保批量 / 要替换逐行)→
|
||||
阶段2 分配名额(复用空闲名额 / 全新新增);
|
||||
含姓名核对修正(J列)、特殊情况槽位追踪(离职/参保减少被复用后保留占位)、
|
||||
以及类别级编排 schedule_category(读取目标文件 → 各阶段 → 输出)。
|
||||
|
||||
文件路径/日期/常量统一来自 config 层;输出(在参名单/变更清单/备份/增减员导入)
|
||||
由 report.output 负责(本模块在编排处懒加载,避免与 report 相互 import 成环)。
|
||||
"""
|
||||
import os
|
||||
from collections import defaultdict
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SHEET_IN_PARAM, DATA_START_ROW,
|
||||
BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME, BIZ_COL_HANDLE,
|
||||
VALID_CATEGORIES, VALID_SCHEMES, category_target_file,
|
||||
category_output_backup, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, to_text, today_date,
|
||||
)
|
||||
|
||||
|
||||
class DataValidationError(Exception):
|
||||
"""数据校验失败异常:直接中断调度,禁止继续往后跑。"""
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、数据校验
|
||||
# ============================================================
|
||||
def validate_biz_data(biz_df):
|
||||
"""校验花名册业务数据的合法性。
|
||||
|
||||
校验规则:
|
||||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:人保-20万 / 50万 / 80万
|
||||
|
||||
返回 errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过。
|
||||
"""
|
||||
errors = []
|
||||
for idx, row in biz_df.iterrows():
|
||||
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
category = row[BIZ_COL_CATEGORY]
|
||||
scheme = row[BIZ_COL_SCHEME]
|
||||
handle = row[BIZ_COL_HANDLE]
|
||||
|
||||
if pd.isna(category) or category not in VALID_CATEGORIES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "工种类别非法",
|
||||
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}",
|
||||
})
|
||||
|
||||
if str(handle).strip() == "增加投保":
|
||||
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "投保方案非法",
|
||||
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}",
|
||||
})
|
||||
return errors
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、阶段0:初始化(从在参名单构建状态)
|
||||
# ============================================================
|
||||
def initialize(in_param_df):
|
||||
"""从「手动维护-在参名单」构建三个核心数据结构。
|
||||
|
||||
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
|
||||
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
|
||||
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
|
||||
|
||||
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
|
||||
"""
|
||||
idle_pools = defaultdict(list)
|
||||
employee_map = {}
|
||||
pending_queues = defaultdict(list)
|
||||
|
||||
IDX_EMP_ID = 10
|
||||
IDX_CUR_SCHEME = 12
|
||||
IDX_HANDLE = 17
|
||||
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[IDX_EMP_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
|
||||
handle = str(row.iloc[IDX_HANDLE]).strip()
|
||||
scheme = row.iloc[IDX_CUR_SCHEME]
|
||||
|
||||
if handle in ["无需", "档次替换"]:
|
||||
# 正常参保或待替换,都视为当前已参保
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
employee_map[emp_id] = scheme
|
||||
elif handle == "离职减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "离职减少", "employee_id": emp_id})
|
||||
elif handle == "参保减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "参保减少", "employee_id": emp_id})
|
||||
# 其他值(如'/')忽略
|
||||
|
||||
# 按优先级排序(离职减少优先)
|
||||
for scheme in idle_pools:
|
||||
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
|
||||
|
||||
return idle_pools, employee_map, pending_queues
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二点五、姓名核对修正(在参名单 J列 与 花名册 姓名比对)
|
||||
# ============================================================
|
||||
def collect_name_corrections(in_param_df, biz_df):
|
||||
"""核对「手动维护-在参名单」J列姓名与花名册「姓名」是否一致,并就地修正。
|
||||
|
||||
以证件号(在参名单 K列 / 花名册 O列)为关联键:
|
||||
- 在参名单中证件号存在、且花名册中能查到该证件号(覆盖离职减少/参保减少等全部行)
|
||||
- 两者姓名不一致且花名册姓名非空 → 记录一条修正,并把 in_param_df J列改为花名册姓名,
|
||||
使后续「删除记录 / 在参名单输出 / 减员导入」统一使用修正后姓名。
|
||||
- 花名册查不到(如已离职)无法核对,跳过不处理。
|
||||
|
||||
Returns:
|
||||
corrections: 修正列表,每项 {emp_id, old_name, new_name, category, scheme}
|
||||
"""
|
||||
biz_dict = {}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
corrections = []
|
||||
for idx, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
biz_row = biz_dict.get(emp_id)
|
||||
if biz_row is None:
|
||||
continue # 花名册查不到,无法核对,跳过
|
||||
new_name = biz_row.get("姓名")
|
||||
if new_name is None or pd.isna(new_name) or str(new_name).strip() == "":
|
||||
continue
|
||||
new_name = str(new_name).strip()
|
||||
old_name = row.iloc[9]
|
||||
old_name_txt = "" if pd.isna(old_name) else str(old_name).strip()
|
||||
if old_name_txt == new_name:
|
||||
continue # 姓名一致,无需修正
|
||||
# 就地修正 in_param_df J列(姓名),供后续统一使用
|
||||
in_param_df.at[idx, in_param_df.columns[9]] = new_name
|
||||
corrections.append({
|
||||
"emp_id": emp_id,
|
||||
"old_name": old_name_txt or "未知",
|
||||
"new_name": new_name,
|
||||
"category": biz_row.get(BIZ_COL_CATEGORY),
|
||||
"scheme": biz_row.get(BIZ_COL_SCHEME),
|
||||
})
|
||||
|
||||
if corrections:
|
||||
logger.info("姓名核对修正:共 %d 条", len(corrections))
|
||||
for c in corrections:
|
||||
logger.info(" %s:%s → %s", c["emp_id"], c["old_name"], c["new_name"])
|
||||
else:
|
||||
logger.info("姓名核对完成:在参名单与花名册姓名全部一致")
|
||||
return corrections
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、阶段1:处理花名册业务
|
||||
# ============================================================
|
||||
def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
"""遍历花名册业务数据,产生待转入队列和额外空闲名额。
|
||||
|
||||
业务类型:
|
||||
1. 增加投保 → 批量加入待转入队列
|
||||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||||
3. 其他 → 记录"非法事件跳过"
|
||||
|
||||
返回:idle_pools, employee_map, pending_queues, change_log
|
||||
"""
|
||||
change_log = []
|
||||
now = today_date()
|
||||
|
||||
# ---------- 1. 增加投保(批量处理) ----------
|
||||
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
|
||||
if not df_add.empty:
|
||||
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
|
||||
if pd.isna(scheme) or scheme == "":
|
||||
for _, row in group.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "投保方案为空,无法增加投保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
|
||||
pending_queues[scheme].extend(emp_ids)
|
||||
for emp_id in emp_ids:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "增加投保",
|
||||
"详情": f"加入 {scheme} 待转入队列",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
|
||||
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
|
||||
for _, row in df_replace.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
target_scheme = row[BIZ_COL_SCHEME]
|
||||
|
||||
# 校验:员工必须当前已参保
|
||||
origin_scheme = employee_map.get(emp_id)
|
||||
if origin_scheme is None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "员工当前未参保,无法进行档次替换",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pd.isna(target_scheme) or target_scheme == "":
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "目标方案为空",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
# 产生"档次替换迁出"名额
|
||||
idle_pools[origin_scheme].append({"type": "档次替换迁出", "employee_id": emp_id})
|
||||
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
|
||||
idle_pools[origin_scheme].sort(
|
||||
key=lambda x: 1 if x["type"] == "离职减少"
|
||||
else 2 if x["type"] == "参保减少"
|
||||
else 3)
|
||||
|
||||
# 员工置为未参保
|
||||
employee_map[emp_id] = None
|
||||
pending_queues[target_scheme].append(emp_id)
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "档次替换迁出",
|
||||
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 3. 其他未知类型 ----------
|
||||
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
|
||||
for _, row in df_other.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return idle_pools, employee_map, pending_queues, change_log
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、阶段2:分配名额
|
||||
# ============================================================
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
"""逐个方案处理待转入队列,分配空闲名额或创建新名额。
|
||||
|
||||
逻辑:
|
||||
1. 队列中的每个员工必须未参保
|
||||
2. 有空闲名额 → 复用(记录来源)
|
||||
3. 无空闲名额 → 全新新增
|
||||
|
||||
返回:final_records, change_log, reused_source_employees
|
||||
"""
|
||||
final_records = []
|
||||
reused_source_employees = []
|
||||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||||
now = today_date()
|
||||
|
||||
for scheme in all_schemes:
|
||||
queue = pending_queues.get(scheme, [])
|
||||
pool = idle_pools.get(scheme, [])
|
||||
|
||||
for emp_id in queue:
|
||||
# 校验:员工必须未参保
|
||||
if employee_map.get(emp_id) is not None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pool:
|
||||
# 复用空闲名额(取出优先级最高的)
|
||||
slot = pool.pop(0)
|
||||
reused_source_employees.append(slot["employee_id"])
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": slot["type"],
|
||||
"来源员工ID": slot["employee_id"],
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "复用空闲名额参保",
|
||||
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
|
||||
"来源员工ID": slot["employee_id"],
|
||||
"时间": now,
|
||||
})
|
||||
else:
|
||||
# 全新新增
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": "全新新增",
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "全新新增名额参保",
|
||||
"详情": f"新增名额,方案 {scheme}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return final_records, change_log, reused_source_employees
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四点半、特殊情况槽位追踪(report 层共用)
|
||||
# ============================================================
|
||||
def _find_special_slots(final_records, in_param_df):
|
||||
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
|
||||
|
||||
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
|
||||
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
|
||||
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
|
||||
|
||||
Returns:
|
||||
special_slots: [{source_id, source_name, source_category, new_scheme}, ...]
|
||||
"""
|
||||
# 初始参保映射:在参名单 M列(投保方案)非空视为"原已参保"
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
|
||||
slot_network = {}
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
slot_network[str(_sid).strip()] = _rec
|
||||
|
||||
# 链条追踪:离职/参保减少释放的名额被老员工复用后,沿"来源员工ID"网络一路追踪,
|
||||
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
|
||||
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
|
||||
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
|
||||
special_slots = []
|
||||
for rec in final_records:
|
||||
if rec.get("名额来源") not in ("离职减少", "参保减少"):
|
||||
continue
|
||||
source_id = rec.get("来源员工ID")
|
||||
# 源员工自身也参保则跳过,避免同一个人出现两条名单
|
||||
if source_id is None or pd.isna(source_id) or source_id in final_emp_ids:
|
||||
continue
|
||||
source_id = str(source_id).strip()
|
||||
# 沿链条追踪,找到末端"未被复用的旧方案"(空闲名额 X档)
|
||||
current_owner = source_id
|
||||
visited = set()
|
||||
loose_end_scheme = None
|
||||
while current_owner not in visited:
|
||||
visited.add(current_owner)
|
||||
next_rec = slot_network.get(current_owner)
|
||||
if next_rec is None:
|
||||
break # 链条断裂
|
||||
receiver_id = str(next_rec["证件号"]).strip()
|
||||
# 接收者不是原已参保老员工(全新新员工)-> 无旧方案可释放,链条自然结束
|
||||
if receiver_id not in initial_employee_map:
|
||||
break
|
||||
# 接收者是老员工:释放自己的旧方案(X档);若该旧名额无人复用则即为空闲名额
|
||||
if receiver_id not in slot_network:
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == receiver_id]
|
||||
if not row_match.empty:
|
||||
loose_end_scheme = row_match.iloc[0].iloc[12]
|
||||
break
|
||||
current_owner = receiver_id # 旧名额被复用,继续追踪下一环
|
||||
if not loose_end_scheme:
|
||||
continue
|
||||
src_match = in_param_df[in_param_df.iloc[:, 10] == source_id]
|
||||
if src_match.empty:
|
||||
continue
|
||||
src_row = src_match.iloc[0]
|
||||
special_slots.append({
|
||||
"source_id": source_id,
|
||||
"source_name": src_row.iloc[9],
|
||||
"source_category": src_row.iloc[11],
|
||||
"new_scheme": loose_end_scheme,
|
||||
})
|
||||
return special_slots
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五、类别级编排(读取目标文件 → 三阶段 → 输出)
|
||||
# ============================================================
|
||||
def _check_import_templates():
|
||||
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
|
||||
|
||||
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
|
||||
才发现模板缺失、需要重做的浪费。
|
||||
"""
|
||||
missing = [
|
||||
path for path in (add_import_template(), sub_import_template())
|
||||
if not os.path.isfile(path)
|
||||
]
|
||||
if missing:
|
||||
raise FileNotFoundError(
|
||||
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
|
||||
|
||||
|
||||
def schedule_category(category, enable_validation=True, gen_import_files=True):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
Args:
|
||||
category: 类别配置
|
||||
enable_validation: 是否启用数据校验(校验失败抛 DataValidationError 中断)
|
||||
gen_import_files: 是否生成增员/减员导入文件
|
||||
|
||||
前置:目标文件已完成筛选复制(roster_filter)并经 WPS/Excel 重算公式。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
output_backup = category_output_backup(category)
|
||||
change_sheet_prefix = category["change_sheet_prefix"]
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
logger.info("=" * 70)
|
||||
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
|
||||
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file},请先完成筛选复制步骤")
|
||||
|
||||
# 检查必需 Sheet
|
||||
xl = pd.ExcelFile(target_file)
|
||||
for s in (SHEET_BIZ, SHEET_IN_PARAM):
|
||||
if s not in xl.sheet_names:
|
||||
raise ValueError(f"目标表缺少必需 Sheet:{s}")
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
if gen_import_files:
|
||||
_check_import_templates()
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
# O列(索引14)证件号强制 dtype=str:含空行的列会被 pandas 推断为 float64,
|
||||
# 18 位身份证号读取即截断(如 ...0009 -> ...0000),导致与在参名单匹配失败
|
||||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3, dtype={14: str})
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
biz_df = biz_df[
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||||
]
|
||||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# ---------- 读取在参名单 ----------
|
||||
# K列(索引10)证件号同样强制 dtype=str,避免 float64 截断 18 位身份证号
|
||||
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5,
|
||||
dtype={10: str})
|
||||
logger.info("在参名单:%d 行", len(in_param_df))
|
||||
|
||||
# 主键文本化:证件号统一转文本(pandas 会把纯数字证件号读为 int64,openpyxl 落盘时
|
||||
# 转浮点会截断 18 位身份证号;统一文本化后匹配/输出全部一致且不丢精度)
|
||||
# 用整列赋值(允许自动升级 dtype),避免 float64 列 iloc 赋值报 LossySetitemError
|
||||
biz_df = biz_df.copy()
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID] = biz_df[BIZ_COL_EMPLOYEE_ID].map(to_text)
|
||||
in_param_df = in_param_df.copy()
|
||||
_id_col = in_param_df.columns[10]
|
||||
in_param_df[_id_col] = in_param_df[_id_col].map(to_text)
|
||||
column_names = in_param_df.columns.tolist()
|
||||
|
||||
# ---------- 姓名核对修正 ----------
|
||||
logger.info("核对在参名单与花名册姓名...")
|
||||
name_corrections = collect_name_corrections(in_param_df, biz_df)
|
||||
|
||||
# ---------- 数据校验 ----------
|
||||
if enable_validation:
|
||||
logger.info("正在校验数据...")
|
||||
errors = validate_biz_data(biz_df)
|
||||
if errors:
|
||||
for e in errors:
|
||||
logger.error(" 行%s 员工%s:%s - %s",
|
||||
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
|
||||
raise DataValidationError(
|
||||
f"类别[{category_name}] 数据校验失败,共 {len(errors)} 个错误,已中断调度")
|
||||
logger.info("数据校验通过!")
|
||||
|
||||
# ---------- 阶段0:初始化 ----------
|
||||
logger.info("初始化状态...")
|
||||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||||
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
|
||||
logger.info(" 当前参保员工:%d 人", len(employee_map))
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
logger.info("处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
biz_df, idle_pools, employee_map, pending_queues)
|
||||
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
|
||||
logger.info(" 变更日志条数:%d", len(change_log))
|
||||
|
||||
# ---------- 阶段2:分配名额 ----------
|
||||
logger.info("分配名额...")
|
||||
final_records, change_log, reused_source_employees = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log)
|
||||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||||
|
||||
# ---------- 阶段3+4:输出(懒加载 report,避免 import 成环) ----------
|
||||
from ..report.output import output_results, export_add_sub_import
|
||||
logger.info("输出结果...")
|
||||
output_results(
|
||||
final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, SHEET_IN_PARAM,
|
||||
name_corrections)
|
||||
|
||||
if gen_import_files:
|
||||
logger.info("生成增员/减员导入文件...")
|
||||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||||
|
||||
logger.info("类别[%s] 调度完成!", category_name)
|
||||
return final_records
|
||||
@@ -0,0 +1,76 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - WPS/Excel COM 后台重算工具。
|
||||
|
||||
替代雇主险流程中「人工打开目标文件刷新公式(Ctrl+S 保存)」环节:
|
||||
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘。
|
||||
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → CalculateFullRebuild →
|
||||
Save;WPS 不可用时回退 MS Excel(Excel.Application)。全程后台静默(Visible=False)。
|
||||
"""
|
||||
import os
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
class ComRecalcError(RuntimeError):
|
||||
"""公式重算失败(文件被占用 / 本机无 WPS 专业版或 MS Excel / COM 异常)。"""
|
||||
|
||||
|
||||
def recalc_target(file_path):
|
||||
"""对单个 xlsx 执行「打开 → 全量重算 → 保存」。
|
||||
|
||||
Args:
|
||||
file_path: 目标文件绝对路径。
|
||||
|
||||
Raises:
|
||||
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / 文件正被 WPS 打开等)。
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.isfile(file_path):
|
||||
raise ComRecalcError(f"待重算文件不存在:{file_path}")
|
||||
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
engine = ""
|
||||
try:
|
||||
# 优先 WPS 表格 COM(Ket.Application);失败回退 MS Excel
|
||||
try:
|
||||
app = win32com.client.Dispatch("Ket.Application")
|
||||
engine = "WPS"
|
||||
except Exception:
|
||||
try:
|
||||
app = win32com.client.Dispatch("Excel.Application")
|
||||
engine = "Excel"
|
||||
except Exception as e:
|
||||
raise ComRecalcError(
|
||||
"本机未检测到可用的 WPS 表格 COM / MS Excel COM,无法自动重算公式。\n"
|
||||
"请安装 WPS 专业版/企业版或 MS Excel 后重试,或关闭「WPS/Excel 后台重算公式」开关后人工打开文件 Ctrl+S 刷新公式。"
|
||||
) from e
|
||||
|
||||
app.Visible = False # 后台不显示窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告
|
||||
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
|
||||
wb.Application.CalculateFullRebuild() # 强制完整重算全部公式
|
||||
wb.Save() # 把计算结果缓存写入 xlsx 磁盘
|
||||
wb.Close()
|
||||
logger.info("公式重算完成(%s COM):%s", engine, file_path)
|
||||
except ComRecalcError:
|
||||
raise
|
||||
except Exception as e:
|
||||
# 文件被用户手动打开时 COM 打开会失败/冲突,给出可操作提示
|
||||
raise ComRecalcError(
|
||||
f"公式重算失败({engine or 'COM'}):{e}\n"
|
||||
"请确认该目标文件未被 WPS/Excel 手动打开(关闭后再试)。"
|
||||
) from e
|
||||
finally:
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.0",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件,替代人工 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(源表缺失且开启自动导出时自动从 HR 导出)"
|
||||
},
|
||||
"auto_export": {
|
||||
"type": "boolean",
|
||||
"title": "源表缺失时自动导出",
|
||||
"default": true,
|
||||
"description": "勾选=花名册缺失时自动调用 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 待增减人员页面上传素材)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 report 层:在参名单更新/变更清单/备份/增减员导入输出。"""
|
||||
@@ -0,0 +1,664 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 结果输出层(由影刀版 employer_insurance_schedule.py 阶段3/五点五 与
|
||||
export_change_sheet.py 合并移植)。
|
||||
|
||||
包含:
|
||||
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
|
||||
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
|
||||
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
|
||||
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
|
||||
(值+样式,公式转缓存结果,避免 #REF!)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from copy import copy
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, DATA_START_ROW, BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME,
|
||||
category_import_add_file, category_import_sub_file, category_target_file,
|
||||
category_change_sheet_workbook, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, today_date,
|
||||
to_text, clean_text, to_date,
|
||||
)
|
||||
from ..logic.schedule import _find_special_slots, scheme_with_suffix
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、输出结果(在参名单 + 变更清单 + 备份 + 姓名修正)
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, in_param_sheet,
|
||||
name_corrections=None):
|
||||
"""输出四部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
"""
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
for rec in final_records:
|
||||
emp_ids_to_clear.add(rec["证件号"])
|
||||
emp_ids_to_clear.update(reused_source_employees)
|
||||
|
||||
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
|
||||
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录)
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
special_source_ids = set(s["source_id"] for s in special_slots)
|
||||
special_src_scheme = {s["source_id"]: s["new_scheme"] for s in special_slots}
|
||||
if special_slots:
|
||||
logger.info("特殊情况:离职/参保减少名额被老员工复用,链条末端空闲名额 %d 例(源员工改为空闲方案保留)",
|
||||
len(special_slots))
|
||||
for s in special_slots:
|
||||
logger.info(" 源 %s -> 改为方案 %s", s["source_id"], s["new_scheme"])
|
||||
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
keep_mask = (
|
||||
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
|
||||
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees))) |
|
||||
(in_param_df[emp_id_col].isin(special_source_ids)) # 特殊情况源员工保留(改M列为老员工旧方案)
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
|
||||
# ---------- 3. 构建员工信息字典 ----------
|
||||
biz_dict = {}
|
||||
for idx, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
# ---------- 4. 构建新参保记录(B~N列) ----------
|
||||
new_records = []
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id not in biz_dict:
|
||||
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
|
||||
continue
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": to_text(row_biz.get("工号")), # B列工号必须为文本
|
||||
"C": row_biz.get("年龄"),
|
||||
"D": row_biz.get("性别"),
|
||||
"E": row_biz.get("岗位"),
|
||||
"F": row_biz.get("职位序列"),
|
||||
"G": row_biz.get("参保类型"),
|
||||
"H": row_biz.get("上下班交通方式"),
|
||||
"I": row_biz.get("入职时间"),
|
||||
"J": row_biz.get("姓名"),
|
||||
"K": row_biz.get("证件号"),
|
||||
"L": row_biz.get("工种类别"),
|
||||
"M": row_biz.get("投保方案"),
|
||||
"N": today_date(),
|
||||
})
|
||||
|
||||
# ---------- 5. 打开工作簿 ----------
|
||||
wb = load_workbook(target_file)
|
||||
ws = wb[in_param_sheet]
|
||||
max_row = ws.max_row
|
||||
|
||||
# ---------- 6. 读取现有数据 ----------
|
||||
existing_rows = []
|
||||
for row_idx in range(DATA_START_ROW, max_row + 1):
|
||||
row_data = []
|
||||
for col in range(1, 27):
|
||||
row_data.append(ws.cell(row=row_idx, column=col).value)
|
||||
existing_rows.append({
|
||||
"row_idx": row_idx,
|
||||
"data": row_data,
|
||||
"emp_id": ws.cell(row=row_idx, column=11).value, # K列
|
||||
})
|
||||
|
||||
# ---------- 7. 构建新数据列表 ----------
|
||||
new_rows = []
|
||||
|
||||
# 姓名修正映射(证件号 -> 新姓名),保留行 J列姓名统一改为花名册姓名
|
||||
corr_by_id = {c["emp_id"]: c["new_name"] for c in (name_corrections or [])}
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
row_data = row_info["data"]
|
||||
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),N列投保日期更新为今天
|
||||
if emp_id in special_src_scheme:
|
||||
row_data[12] = special_src_scheme[emp_id]
|
||||
row_data[13] = today_date() # N列 投保日期
|
||||
# 姓名核对修正:J列姓名改为花名册姓名
|
||||
if emp_id in corr_by_id:
|
||||
row_data[9] = corr_by_id[emp_id]
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": emp_id,
|
||||
"action": "keep",
|
||||
})
|
||||
|
||||
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动;特殊情况源员工已保留,此处不清空)
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if (emp_id in emp_ids_to_clear and emp_id not in special_source_ids) or emp_id is None:
|
||||
row_data = row_info["data"].copy()
|
||||
for i in range(1, 14):
|
||||
row_data[i] = None
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": None,
|
||||
"action": "clear",
|
||||
})
|
||||
|
||||
# 7.3 填充新记录到空行
|
||||
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
|
||||
empty_slots.sort(key=lambda x: x["row_idx"])
|
||||
|
||||
def _fill(row_data, rec):
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
|
||||
for rec in new_records:
|
||||
if empty_slots:
|
||||
slot = empty_slots.pop(0)
|
||||
row_data = slot["data"]
|
||||
_fill(row_data, rec)
|
||||
slot["emp_id"] = rec["K"]
|
||||
slot["action"] = "filled"
|
||||
else:
|
||||
# 追加新行(复制上一行样式)
|
||||
row_data = [None] * 26
|
||||
if existing_rows:
|
||||
src_row_idx = existing_rows[-1]["row_idx"]
|
||||
for col in range(1, 27):
|
||||
src_cell = ws.cell(row=src_row_idx, column=col)
|
||||
dst_cell = ws.cell(row=max_row + 1, column=col)
|
||||
if src_cell.has_style:
|
||||
dst_cell.font = copy(src_cell.font)
|
||||
dst_cell.border = copy(src_cell.border)
|
||||
dst_cell.fill = copy(src_cell.fill)
|
||||
dst_cell.number_format = src_cell.number_format
|
||||
dst_cell.alignment = copy(src_cell.alignment)
|
||||
last_row_data = existing_rows[-1]["data"]
|
||||
for i in range(14, 26):
|
||||
row_data[i] = last_row_data[i]
|
||||
_fill(row_data, rec)
|
||||
new_rows.append({
|
||||
"row_idx": None,
|
||||
"data": row_data,
|
||||
"emp_id": rec["K"],
|
||||
"action": "append",
|
||||
})
|
||||
|
||||
# ---------- 8. 更新现有行(B~N列,列号=索引+1;B列工号强制文本) ----------
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is not None:
|
||||
row_idx = row_info["row_idx"]
|
||||
row_data = row_info["data"]
|
||||
for idx in range(1, 14):
|
||||
c = ws.cell(row=row_idx, column=idx + 1)
|
||||
if idx == 1:
|
||||
c.value = to_text(row_data[idx])
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = row_data[idx]
|
||||
|
||||
# ---------- 9. 追加新行 ----------
|
||||
current_row = max_row + 1
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is None:
|
||||
row_idx = current_row
|
||||
row_data = row_info["data"]
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
c = ws.cell(row=row_idx, column=col_idx)
|
||||
if col_idx == 2:
|
||||
c.value = to_text(value)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = value
|
||||
current_row += 1
|
||||
|
||||
# ---------- 9.5 紧凑化:消除中间空行(只搬移 B~O 数据列,公式列 R/S/T/U/V/W 不动) ----------
|
||||
data_values = []
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
has_data = any(
|
||||
ws.cell(row=row_idx, column=c).value not in (None, "")
|
||||
for c in range(2, 16)
|
||||
)
|
||||
if has_data:
|
||||
data_values.append([ws.cell(row=row_idx, column=c).value for c in range(2, 16)])
|
||||
target_row = DATA_START_ROW
|
||||
for vals in data_values:
|
||||
for col, v in enumerate(vals, start=2):
|
||||
cell = ws.cell(row=target_row, column=col)
|
||||
if col == 2: # B列 工号 强制文本
|
||||
cell.value = to_text(v)
|
||||
cell.number_format = "@"
|
||||
elif col == 14: # N列 投保日期 -> 日期类型 + yyyy-mm-dd
|
||||
cell.value = to_date(v)
|
||||
if cell.value is not None:
|
||||
cell.number_format = "yyyy-mm-dd"
|
||||
else:
|
||||
cell.value = v
|
||||
target_row += 1
|
||||
# 清空多出部分的 B~O 列(公式列不动)
|
||||
for row_idx in range(target_row, current_row):
|
||||
for col in range(2, 16):
|
||||
ws.cell(row=row_idx, column=col).value = None
|
||||
|
||||
# ---------- 10. 重新编号A列 ----------
|
||||
seq = 1
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
if ws.cell(row=row_idx, column=11).value is not None:
|
||||
ws.cell(row=row_idx, column=1).value = seq
|
||||
seq += 1
|
||||
else:
|
||||
ws.cell(row=row_idx, column=1).value = None
|
||||
|
||||
# ============================================================
|
||||
# ★★★ 11. 精细更新变更清单 ★★★
|
||||
# ============================================================
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
# 收集所有以类别变更清单前缀开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(change_sheet_prefix) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
|
||||
|
||||
template_name = max(candidates, key=_template_sort_key) if candidates else None
|
||||
|
||||
if template_name is not None:
|
||||
# 复制最近一次的历史模板Sheet(保留公式与样式)
|
||||
source = wb[template_name]
|
||||
target = wb.copy_worksheet(source)
|
||||
target.title = change_sheet_name
|
||||
logger.info("已从模板 [%s] 复制变更清单", template_name)
|
||||
else:
|
||||
# 没有任何历史模板,创建新Sheet(兜底)
|
||||
ws_change = wb.create_sheet(change_sheet_name)
|
||||
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
|
||||
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
|
||||
"工作单位", "", "备注", "批改日期", "新增费用会馆",
|
||||
"姓名", "证件号", "工种类别", "投保方案"]
|
||||
for col_idx, h in enumerate(headers, start=1):
|
||||
ws_change.cell(row=1, column=col_idx).value = h
|
||||
ws_change.cell(row=2, column=1).value = "公式"
|
||||
ws_change = wb[change_sheet_name]
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
|
||||
DEPT_COL_MARK = "费用会馆"
|
||||
dept_col = 15
|
||||
for _col in range(1, 21):
|
||||
if any(DEPT_COL_MARK in str(ws_change.cell(row=_row, column=_col).value or "")
|
||||
for _row in (1, 2)):
|
||||
dept_col = _col
|
||||
break
|
||||
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
|
||||
|
||||
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
|
||||
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
|
||||
|
||||
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
|
||||
max_row_change = ws_change.max_row
|
||||
if max_row_change >= 3:
|
||||
for row in range(3, max_row_change + 1):
|
||||
ws_change.cell(row=row, column=2).value = None # B列
|
||||
ws_change.cell(row=row, column=13).value = None # M列 备注
|
||||
ws_change.cell(row=row, column=14).value = None # N列
|
||||
ws_change.cell(row=row, column=dept_col).value = None # 四级部门列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 收集变更记录
|
||||
records = []
|
||||
|
||||
# 1. 删除记录(特殊情况源员工一并输出"增加老员工旧方案",保证增减平衡)
|
||||
for emp_id in emp_ids_to_clear:
|
||||
if emp_id in final_emp_ids:
|
||||
continue
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row = row_match.iloc[0]
|
||||
name = row.iloc[9]
|
||||
category = row.iloc[11]
|
||||
scheme = row.iloc[12]
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
# 特殊情况:源员工名额被老员工复用且老员工旧名额无人复用 -> 源员工改为该旧方案
|
||||
if emp_id in special_src_scheme:
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": special_src_scheme[emp_id]})
|
||||
else:
|
||||
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
|
||||
"category": "未知", "scheme": "未知"})
|
||||
|
||||
# 2. 增加记录。档次替换仅当「自己的名额档次替换、不涉及其他人」时合并为一条「修改」
|
||||
# 收集「自己的旧名额被他人复用」的员工集合(来源员工ID)
|
||||
reused_by_others = set()
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
reused_by_others.add(_sid)
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
row_biz = biz_dict[emp_id]
|
||||
name = row_biz.get("姓名")
|
||||
category = row_biz.get("工种类别")
|
||||
scheme = row_biz.get("投保方案")
|
||||
else:
|
||||
name = category = scheme = None
|
||||
if emp_id in initial_employee_map:
|
||||
# 原已参保(档次替换):仅"自己的名额档次替换、不涉及其他人"才合并为「修改」
|
||||
pure_self_replace = (
|
||||
rec.get("名额来源") == "全新新增" and
|
||||
emp_id not in reused_by_others
|
||||
)
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
old_scheme = None
|
||||
if not row_match.empty:
|
||||
old_scheme = row_match.iloc[0].iloc[12]
|
||||
if pure_self_replace:
|
||||
remark = None
|
||||
if old_scheme is not None and str(old_scheme).strip() != "" and \
|
||||
scheme is not None and str(scheme).strip() != "":
|
||||
remark = f"由{old_scheme}替换为{scheme}"
|
||||
records.append({"op": "修改", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme, "remark": remark})
|
||||
else:
|
||||
# 涉及其他人的档次替换:正常两条(删除旧方案 + 增加新方案)
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": old_scheme})
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
else:
|
||||
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 O列 填四级部门
|
||||
new_rec = {"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme}
|
||||
if rec.get("名额来源") == "全新新增":
|
||||
biz_row_dept = biz_dict.get(emp_id)
|
||||
dept = clean_text(biz_row_dept.get(biz_dept_col)) if biz_row_dept is not None else None
|
||||
if dept is None:
|
||||
# 四级部门为空:回退填所属单位,并记录日志供人工核对
|
||||
dept = clean_text(biz_row_dept.get("所属单位")) if biz_row_dept is not None else None
|
||||
logger.warning("员工 %s(%s) 花名册四级部门为空,O列回退填所属单位:%s",
|
||||
name, emp_id, dept)
|
||||
new_rec["dept"] = dept
|
||||
records.append(new_rec)
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for rec in records:
|
||||
op = rec.get("op")
|
||||
name = rec.get("name")
|
||||
emp_id = rec.get("emp_id")
|
||||
category = rec.get("category")
|
||||
scheme = rec.get("scheme")
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=13).value = rec.get("remark") # M列 备注
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date() # N列
|
||||
# 四级部门列:仅纯新增名额(全新新增)的「增加」记录才填
|
||||
if op == "增加" and rec.get("dept") is not None:
|
||||
ws_change.cell(row=current_row_change, column=dept_col).value = rec.get("dept")
|
||||
ws_change.cell(row=current_row_change, column=16).value = name # P列
|
||||
ws_change.cell(row=current_row_change, column=17).value = emp_id # Q列
|
||||
ws_change.cell(row=current_row_change, column=18).value = category # R列
|
||||
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
|
||||
current_row_change += 1
|
||||
|
||||
# 3. 姓名修正记录(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
for corr in (name_corrections or []):
|
||||
ws_change.cell(row=current_row_change, column=2).value = "修改"
|
||||
ws_change.cell(row=current_row_change, column=13).value = \
|
||||
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}"
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date()
|
||||
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"]
|
||||
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"]
|
||||
ws_change.cell(row=current_row_change, column=18).value = corr.get("category")
|
||||
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme")
|
||||
current_row_change += 1
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
|
||||
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
|
||||
logger.info("变更清单已精细更新(共 %d 条变更记录,含 %d 条姓名修正)",
|
||||
len(records) + len(name_corrections or []), len(name_corrections or []))
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、生成增员/减员导入文件(HR「待增减人员」页面上传素材)
|
||||
# ============================================================
|
||||
def _write_import_file(template_path, out_path, rows):
|
||||
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。"""
|
||||
if not os.path.isfile(template_path):
|
||||
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
|
||||
wb = load_workbook(template_path)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for i, row_vals in enumerate(rows):
|
||||
excel_row = 4 + i
|
||||
for col_idx, val in enumerate(row_vals, start=1):
|
||||
c = ws.cell(row=excel_row, column=col_idx)
|
||||
if col_idx == 2: # 工号/身份证列强制文本
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
wb.save(out_path)
|
||||
logger.info("已生成导入文件:%s(%d 条)", out_path, len(rows))
|
||||
|
||||
|
||||
def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees):
|
||||
"""生成各类别「商业保险增员导入.xlsx / 商业保险减员导入.xlsx」(HR 上传素材)。
|
||||
|
||||
集合差模型:按「人 + 投保方案」记录级做差:
|
||||
- 减员 = 原参保记录 − 新参保记录
|
||||
- 增员 = 新参保记录 − 原参保记录
|
||||
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
|
||||
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
|
||||
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
|
||||
|
||||
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错。
|
||||
"""
|
||||
# ---------- 1. 原参保记录集合 ----------
|
||||
orig_records = {} # to_text(证件号) -> 方案
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
scheme = row.iloc[12]
|
||||
if pd.isna(scheme) or str(scheme).strip() == "":
|
||||
continue
|
||||
orig_records[to_text(emp_id)] = scheme
|
||||
|
||||
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录 + 特殊情况保留源员工) ----------
|
||||
cleared_ids = set(to_text(e) for e in reused_source_employees)
|
||||
cleared_ids.update(to_text(rec["证件号"]) for rec in final_records)
|
||||
new_records_map = {
|
||||
emp_id: scheme for emp_id, scheme in orig_records.items()
|
||||
if emp_id not in cleared_ids
|
||||
}
|
||||
for rec in final_records:
|
||||
new_records_map[to_text(rec["证件号"])] = rec["投保方案"]
|
||||
# 特殊情况源员工(离职/参保减少名额被复用后保留在参名单,方案改为空闲方案):
|
||||
# 纳入"新参保记录"参与集合差,保证减员/增员对称、不漏人
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
for _s in special_slots:
|
||||
new_records_map[to_text(_s["source_id"])] = _s["new_scheme"]
|
||||
|
||||
# ---------- 3. 记录级集合差:减员名单 ----------
|
||||
sub_ids = [
|
||||
emp_id for emp_id, orig_scheme in orig_records.items()
|
||||
if emp_id not in new_records_map or new_records_map[emp_id] != orig_scheme
|
||||
]
|
||||
|
||||
# ---------- 4. 员工信息查询(biz_df 优先,其次 in_param_df) ----------
|
||||
emp_info = {} # to_text(证件号) -> {"工号": ..., "姓名": ...}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.iloc[1]), "姓名": row.iloc[9]}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.get("工号")), "姓名": row.get("姓名")}
|
||||
|
||||
def _code(emp_id):
|
||||
"""工号/身份证列:优先工号,空则回退证件号。"""
|
||||
return clean_text(emp_info.get(emp_id, {}).get("工号")) or clean_text(emp_id)
|
||||
|
||||
def _name(emp_id):
|
||||
return clean_text(emp_info.get(emp_id, {}).get("姓名"))
|
||||
|
||||
# ---------- 5. 组装行数据 ----------
|
||||
sub_rows, skipped_sub = [], 0
|
||||
for i, emp_id in enumerate(sub_ids, start=1):
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_sub += 1
|
||||
logger.warning("减员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
sub_rows.append([i, _code(emp_id), name, today_date()])
|
||||
|
||||
add_rows, skipped_add, seq = [], 0, 0
|
||||
for rec in final_records:
|
||||
emp_id = to_text(rec["证件号"])
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, rec["投保方案"]), today_date(),
|
||||
rec.get("名额来源") or "新增"])
|
||||
# 特殊情况源员工(保留在参名单,方案改为空闲方案)也需增员(新增该方案),不漏人
|
||||
for _s in special_slots:
|
||||
emp_id = to_text(_s["source_id"])
|
||||
new_scheme = _s["new_scheme"]
|
||||
# 方案未变(极少见边界)则无需增员
|
||||
if emp_id in orig_records and orig_records[emp_id] == new_scheme:
|
||||
continue
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:特殊情况源员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, new_scheme), today_date(),
|
||||
"特殊情况保留名额"])
|
||||
|
||||
# ---------- 6. 写入模板(保留第1~3行,第4行起填数据) ----------
|
||||
_write_import_file(sub_import_template(), category_import_sub_file(category), sub_rows)
|
||||
_write_import_file(add_import_template(), category_import_add_file(category), add_rows)
|
||||
|
||||
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
|
||||
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
|
||||
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、导出变更清单独立工作簿(值 + 样式,公式转缓存结果)
|
||||
# ============================================================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, 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] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
@@ -0,0 +1,5 @@
|
||||
requests
|
||||
pandas
|
||||
openpyxl
|
||||
websocket-client
|
||||
pywin32
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>雇主险增减操作</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1585
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0002-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 执行配置 -->
|
||||
<el-card shadow="never" class="card">
|
||||
<template #header>
|
||||
<span class="card-title">执行配置</span>
|
||||
<span v-if="lastSavedAt" class="saved">已保存 {{ lastSavedAt }}</span>
|
||||
</template>
|
||||
<el-form label-width="130px" label-position="right">
|
||||
<div class="grid">
|
||||
<el-form-item label="雇主险根目录">
|
||||
<el-input v-model="form.base_dir" :disabled="running" clearable placeholder="四类各占一个子文件夹,增/减员导入模板放在根目录" />
|
||||
</el-form-item>
|
||||
<el-form-item label="业务日期">
|
||||
<el-date-picker v-model="form.ref_date" type="date" value-format="YYYY-MM-DD" :disabled="running"
|
||||
clearable placeholder="留空=今天" class="wide" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="处理类别">
|
||||
<el-select v-model="form.categories" multiple :disabled="running" class="wide"
|
||||
placeholder="可多选,留空=全部类别">
|
||||
<el-option v-for="c in CATEGORIES" :key="c" :value="c" :label="c" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="花名册路径">
|
||||
<el-input v-model="form.roster_path" :disabled="running" clearable
|
||||
placeholder="留空 = 根目录/员工花名册.xlsx(缺失且开启自动导出时自动从 HR 导出)" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="执行开关">
|
||||
<div class="switches">
|
||||
<el-switch v-model="form.auto_export" :disabled="running" active-text="源表缺失自动导出" />
|
||||
<el-switch v-model="form.enable_validation" :disabled="running" active-text="启用数据校验" />
|
||||
<el-switch v-model="form.wps_recalc" :disabled="running" active-text="WPS/Excel后台重算公式" />
|
||||
<el-switch v-model="form.export_change_sheet" :disabled="running" active-text="导出变更清单独立工作簿" />
|
||||
<el-switch v-model="form.gen_import_files" :disabled="running" active-text="生成增/减员导入文件" />
|
||||
</div>
|
||||
<div class="tip">「WPS/Excel后台重算公式」替代人工 Ctrl+S 刷新公式,需本机装 WPS 专业版/企业版或 MS Excel;关闭后须确保目标文件公式已人工刷新</div>
|
||||
</el-form-item>
|
||||
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态:进度条 + 日志位置提示(日志实时显示在壳子下方日志区) -->
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="8" class="status-bar" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { connectWS, getRun, loadConfig, saveConfig, startRun, stopRun } from './api'
|
||||
|
||||
const CATEGORIES = ['三十七度', '水庄餐饮', '湖畔酒店', '秒创传媒']
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
base_dir: 'D:\\资料\\人资\\雇主险',
|
||||
ref_date: '',
|
||||
categories: [...CATEGORIES],
|
||||
roster_path: '',
|
||||
auto_export: true,
|
||||
enable_validation: true,
|
||||
wps_recalc: true,
|
||||
export_change_sheet: true,
|
||||
gen_import_files: true,
|
||||
})
|
||||
|
||||
const form = reactive(DEFAULTS())
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 配置加载 / 保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
Object.keys(form).forEach((k) => {
|
||||
if (saved[k] !== undefined && saved[k] !== null && saved[k] !== '') form[k] = saved[k]
|
||||
if (k === 'categories' && Array.isArray(saved[k]) && saved[k].length) form.categories = saved[k]
|
||||
})
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖),执行中不改存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(JSON.parse(JSON.stringify(form)))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, DEFAULTS())
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
function validate() {
|
||||
if (!form.base_dir.trim()) { ElMessage.warning('请填写雇主险根目录'); return false }
|
||||
if (!form.categories.length) { ElMessage.warning('请至少选择一个处理类别'); return false }
|
||||
if (form.ref_date && !/^\d{4}-\d{2}-\d{2}$/.test(form.ref_date)) {
|
||||
ElMessage.warning('业务日期格式应为 YYYY-MM-DD,或留空使用今天'); return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (!validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(JSON.parse(JSON.stringify(form)))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 强制停止(整树强杀执行子进程) ----------
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示) ----------
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
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 || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null } // 断开后由轮询兜底
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
async function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 4px 2px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
float: right;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
color: #67c23a;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
flex: 1;
|
||||
min-width: 300px;
|
||||
}
|
||||
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.switches {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 18px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 1.6;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 16px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,50 @@
|
||||
// 与壳子后端交互(同源,统一账户会话 cookie 自动携带)+ WebSocket 实时流
|
||||
export const PLUGIN_ID = 'xq0002'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子(工作台)登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
export function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
export function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0002/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0002/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5181,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<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-b6COCLM2.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-DkUqd0or.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user