feat: 新增EHR系统花名册检查插件及多个插件版本更新
This commit is contained in:
@@ -8,15 +8,17 @@
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值);
|
||||
7) HR 自动导入(可选开关,默认开启):浏览器自动化把调度生成的导入文件导入
|
||||
HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别);
|
||||
7) HR 自动导入(可选开关,默认开启):浏览器自动化把类别文件夹中已有的导入文件
|
||||
导入 HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别;
|
||||
不依赖「生成导入文件」开关,文件缺失/0 条的类别自动跳过);
|
||||
8) 钉钉群通知(可选开关,默认开启):汇总 + 增/减员导入异常名单推送到钉钉群
|
||||
(失败不影响主流程)。
|
||||
仅导入模式(only_import=True):以上 1)~6) 全部跳过,只执行 7)(导入文件须已生成)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。
|
||||
字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path /
|
||||
enable_validation / wps_recalc / export_change_sheet / gen_import_files / import_to_hr /
|
||||
dingtalk_notify。
|
||||
only_import / dingtalk_notify。
|
||||
"""
|
||||
import os
|
||||
|
||||
@@ -33,7 +35,7 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.9"
|
||||
version = "1.0.16"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,"
|
||||
@@ -67,14 +69,26 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
gen_import_files = bool(fields.get("gen_import_files", True))
|
||||
import_to_hr = bool(fields.get("import_to_hr", True))
|
||||
dingtalk_notify = bool(fields.get("dingtalk_notify", True))
|
||||
import_on = import_to_hr and gen_import_files
|
||||
if import_to_hr and not gen_import_files:
|
||||
ctx.log("已开启「自动导入HR系统」但「生成导入文件」未开启,本次无可导入文件,导入步骤将跳过", "WARN")
|
||||
only_import = bool(fields.get("only_import", False))
|
||||
# 导入方式:api=纯接口(默认,无浏览器弹窗);ui=浏览器自动化兜底
|
||||
config.set_import_mode(fields.get("import_mode", "api"))
|
||||
# 仅导入模式:跳过前置全部步骤,只把已有导入文件导进 HR
|
||||
if only_import:
|
||||
import_to_hr = True
|
||||
# 自动导入只看本开关:导入素材为各类别文件夹中已有的增/减员导入文件
|
||||
# (本次生成或此前已生成),文件缺失/无待导入条目的类别由 hr_import 预检跳过
|
||||
import_on = import_to_hr
|
||||
if import_to_hr and not only_import and not gen_import_files:
|
||||
ctx.log("已关闭「生成增/减员导入文件」:将直接导入各类别文件夹中已有的导入文件"
|
||||
"(文件不存在或 0 条的类别自动跳过)", "INFO")
|
||||
|
||||
if not categories:
|
||||
raise ValueError("未选择任何类别")
|
||||
|
||||
notes: list = []
|
||||
if only_import:
|
||||
return self._run_import_only(categories, ctx, notes, base_dir, dingtalk_notify)
|
||||
|
||||
ctx.log(f"===== 雇主险增减操作启动:业务日期 {config.today_date()},根目录 {base_dir} =====", "INFO")
|
||||
|
||||
# ---- 步骤1:花名册确保(5% ~ 10%) ----
|
||||
@@ -217,5 +231,49 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
return {"summary": summary, "notes": notes, "detail": detail,
|
||||
"path": base_dir, "date": config.today_date()}
|
||||
|
||||
def _run_import_only(self, categories, ctx, notes, base_dir, dingtalk_notify):
|
||||
"""仅导入模式:跳过花名册导出/筛选复制/公式重算/名额调度/文件生成,
|
||||
直接把各类别文件夹中已有的增/减员导入文件导进 HR(先减员后增员)。"""
|
||||
ctx.log("===== 仅导入HR系统:跳过花名册导出、筛选复制、公式重算、名额调度、"
|
||||
"变更清单导出与导入文件生成,只导入已有增/减员导入文件 =====", "INFO")
|
||||
ctx.progress(5)
|
||||
|
||||
def _on_progress(done, total):
|
||||
ctx.progress(5 + int(93 * done / max(total, 1)))
|
||||
|
||||
import_results = []
|
||||
try:
|
||||
import_results = hr_import.import_all(categories, on_progress=_on_progress)
|
||||
except hr_import.LoginRequiredError as e:
|
||||
notes.append(f"HR 自动导入未执行(登录态缺失):{e}")
|
||||
ctx.log(f"HR 自动导入未执行:{e}", "ERROR")
|
||||
except Exception as e:
|
||||
notes.append(f"HR 自动导入整体失败:{e}")
|
||||
ctx.log(f"HR 自动导入整体失败:{e}", "ERROR")
|
||||
ctx.progress(100)
|
||||
|
||||
import_lines = hr_import.summarize_results(import_results) if import_results else []
|
||||
import_text = ";".join(import_lines) if import_lines else \
|
||||
"无可导入条目(各类别导入文件不存在或 A 列无序号)"
|
||||
summary = ("雇主险仅导入HR系统完成({date}):处理 {total} 个类别。"
|
||||
"HR 导入结果:{text}。(本次未执行花名册导出/筛选复制/公式重算/"
|
||||
"名额调度/变更清单导出与导入文件生成)").format(
|
||||
date=config.today_date(), total=len(categories), text=import_text)
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
|
||||
if dingtalk_notify:
|
||||
notify.push_run_result(total=len(categories), filtered=0,
|
||||
scheduled=len(categories), import_on=True,
|
||||
import_lines=import_lines,
|
||||
import_results=import_results, notes=notes,
|
||||
only_import=True)
|
||||
else:
|
||||
ctx.log("钉钉群通知已关闭,跳过推送", "INFO")
|
||||
|
||||
return {"summary": summary, "notes": notes,
|
||||
"detail": {"处理类别": len(categories), "仅导入": True},
|
||||
"path": base_dir, "date": config.today_date()}
|
||||
|
||||
|
||||
PLUGINS.append(EmployerInsurancePlugin())
|
||||
|
||||
@@ -103,11 +103,23 @@ SUB_IMPORT_TEMPLATE = "商业保险减员导入模板.xlsx"
|
||||
# ==================== 运行参数钩子(run() 注入) ====================
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ref_date = None # datetime.date;None 表示今天
|
||||
_import_mode = "api" # api=纯接口导入(默认,无浏览器);ui=浏览器自动化兜底
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_import_mode(value):
|
||||
"""设置 HR 导入方式:api(纯接口,默认)/ ui(浏览器自动化兜底),非法值回落 api。"""
|
||||
global _import_mode
|
||||
mode = str(value or "").strip().lower()
|
||||
_import_mode = mode if mode in ("api", "ui") else "api"
|
||||
|
||||
|
||||
def import_mode():
|
||||
return _import_mode
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - HR「待增减人员」增/减员导入(纯接口版,无浏览器)。
|
||||
|
||||
逆向来源(2026-10-30,全程只 GET 页面与前端 JS,未做任何写入探测):
|
||||
待增减人员列表页按钮配置 + /RedseaPlatform/jsp/hr/custommodule/dataimport/js/
|
||||
hr_module_base_import_do.js
|
||||
|
||||
链路(与前端 checkFileType / submit 完全一致,全为 multipart/form-data):
|
||||
1. GET hr/module/base/import/do/<importId>/toImpPage.mc 取弹窗配置 hrModuleBaseImport
|
||||
(importId、fieldJson 表头映射模板、maxNum 等)
|
||||
2. POST .../checkFileType.mc 文件格式校验,返回 Excel 实际表头
|
||||
(result[].excelColName / excelColNum),不写库
|
||||
3. 同名匹配 columnDisplay == excelColName 回填 excelColNum(前端 setDefaultMatchTitle)
|
||||
4. POST .../uploadData.mc 真正导入(异步,服务端后台跑,响应无业务结果)
|
||||
5. POST .../getImportResult.mc 轮询取结果(前端靠 WebSocket 主题 EXCEL_COMMON_IMPORT
|
||||
的 done 消息触发,接口版改为轮询,等价且不依赖 ws)
|
||||
6. POST .../getTmpDataPage.mc 失败明细分页(固定 15 条/页)
|
||||
|
||||
关键事实(决定了不需要抓包、也没有一次性 token 门槛):
|
||||
- importId 是导入模板的固定配置 id,写死在弹窗页 hidden input 中;
|
||||
- businessId 由前端 guid() 生成、每次导入唯一,接口版自行 uuid4();
|
||||
- titleList 是字段映射数组 JSON 的 base64,无签名;
|
||||
- 写库只发生在 uploadData,checkFileType 纯校验(读文件比对表头)。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, get_session
|
||||
|
||||
# ==================== 常量 ====================
|
||||
BASE_URL = "https://hr.37du.co"
|
||||
CONTEXT_PATH = "/RedseaPlatform"
|
||||
IMP_DO = CONTEXT_PATH + "/hr/module/base/import/do"
|
||||
TO_IMP_PAGE_URL = IMP_DO + "/{import_id}/toImpPage.mc?pageType=1&importTitle={title}&struTreeCode="
|
||||
CHECK_FILE_TYPE_URL = BASE_URL + IMP_DO + "/checkFileType.mc"
|
||||
UPLOAD_DATA_URL = BASE_URL + IMP_DO + "/uploadData.mc"
|
||||
GET_IMPORT_RESULT_URL = BASE_URL + IMP_DO + "/getImportResult.mc"
|
||||
GET_TMP_DATA_PAGE_URL = BASE_URL + IMP_DO + "/getTmpDataPage.mc"
|
||||
|
||||
# 两个导入模板的固定配置 id(取自「待增减人员」页按钮配置,勿改)
|
||||
IMPORT_MENUS = {
|
||||
"add": {"import_id": "12eecb13-78b0-4fac-a865-10c3043a33e1",
|
||||
"title": "商业保险增员导入", "label": "增员导入"},
|
||||
"sub": {"import_id": "22e180f9-476b-412d-b68b-bbed8393dba6",
|
||||
"title": "商业保险减员导入", "label": "减员导入"},
|
||||
}
|
||||
|
||||
# 弹窗默认行号(页面 select 默认值:列标题行号=2、内容开始行号=4)
|
||||
TITLE_ROW_NUM = "2"
|
||||
CONTENT_ROW_NUM = "4"
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
RETRY_TIMES = 3 # 只读接口重试次数(项目级规范)
|
||||
RETRY_INTERVAL = 1.0
|
||||
PAGE_SIZE = 15 # getTmpDataPage 固定 15 条/页
|
||||
POLL_TIMEOUT_SECONDS = 300 # 导入结果轮询上限(与前端"排队等候"提示口径一致)
|
||||
POLL_INTERVAL_SECONDS = 2.0
|
||||
|
||||
# 弹窗配置缓存(importId -> hrModuleBaseImport dict,进程内复用)
|
||||
_CONF_CACHE = {}
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失/失效(页面被重定向到登录页或 cookies 为空)。"""
|
||||
|
||||
|
||||
# ==================== 会话 ====================
|
||||
def _session_from_cookie_file():
|
||||
"""兜底:用共享 cookies 文件构建 requests.Session(底座未注入会话时)。"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
|
||||
cookies = json.load(f) or []
|
||||
except Exception as e:
|
||||
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
|
||||
return None
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": USER_AGENT})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in str(c["domain"]):
|
||||
try:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"],
|
||||
path=c.get("path", "/"))
|
||||
except Exception:
|
||||
continue
|
||||
return s
|
||||
|
||||
|
||||
def build_session():
|
||||
"""取可用 HR 会话:底座注入 session 优先,缺失时兜底共享 cookies 文件。"""
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
return session
|
||||
session = _session_from_cookie_file()
|
||||
if session is None:
|
||||
raise LoginRequiredError(
|
||||
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
|
||||
"请先在插件界面完成 HR 登录后再执行导入。")
|
||||
return session
|
||||
|
||||
|
||||
# ==================== HTTP 基础 ====================
|
||||
def _parse_json(resp, desc):
|
||||
"""解析接口响应;返回登录页等非 JSON 内容时判定登录态失效。"""
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
if "j_username" in text or "login" in text.lower()[:2000]:
|
||||
raise LoginRequiredError(
|
||||
f"{desc} 返回登录页,HR 登录态已失效,请在插件界面重新登录 HR。")
|
||||
raise RuntimeError(f"{desc} 响应非 JSON(HTTP {resp.status_code}):{text[:200]}")
|
||||
|
||||
|
||||
def _multipart_post(session, url, data, file_path=None, timeout=120):
|
||||
"""以 multipart/form-data 提交(上传文件)。
|
||||
|
||||
底座注入的共享 session 默认带 Content-Type: application/x-www-form-urlencoded,
|
||||
会让 requests 不再自动生成 multipart 边界头而被服务端拒绝;上传前临时清除、随后恢复
|
||||
(同 XQ0008 oa_push.py 的处理)。
|
||||
"""
|
||||
saved_ct = session.headers.pop("Content-Type", None)
|
||||
headers = {"X-Requested-With": "XMLHttpRequest", "Referer": BASE_URL + CONTEXT_PATH + "/"}
|
||||
fh = None
|
||||
try:
|
||||
files = None
|
||||
if file_path:
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
fh = open(file_path, "rb")
|
||||
files = {"file": (os.path.basename(file_path), fh, XLSX_MIME)}
|
||||
return session.post(url, data=data, files=files, headers=headers, timeout=timeout)
|
||||
finally:
|
||||
if fh is not None:
|
||||
fh.close()
|
||||
if saved_ct is not None:
|
||||
session.headers["Content-Type"] = saved_ct
|
||||
|
||||
|
||||
def _get_text(session, url, desc, timeout=30):
|
||||
"""GET 文本(只读,带重试)。"""
|
||||
last = None
|
||||
for attempt in range(RETRY_TIMES):
|
||||
try:
|
||||
resp = session.get(url, timeout=timeout,
|
||||
headers={"X-Requested-With": "XMLHttpRequest"})
|
||||
text = resp.content.decode("utf-8", "ignore")
|
||||
if "j_username" in text[:5000] and "RedSea" not in text[:2000]:
|
||||
raise LoginRequiredError(
|
||||
f"{desc} 被重定向到登录页,HR 登录态已失效,请重新登录 HR。")
|
||||
return text
|
||||
except LoginRequiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last = e
|
||||
logger.warning("%s 第 %s/%s 次失败:%s", desc, attempt + 1, RETRY_TIMES, e)
|
||||
time.sleep(RETRY_INTERVAL)
|
||||
raise RuntimeError(f"{desc} 请求失败(已重试 {RETRY_TIMES} 次):{last}")
|
||||
|
||||
|
||||
def _post_json(session, url, data, desc, file_path=None, timeout=120):
|
||||
"""POST 并解析 JSON(只读接口使用,带重试)。写接口请勿用本函数。"""
|
||||
last = None
|
||||
for attempt in range(RETRY_TIMES):
|
||||
try:
|
||||
resp = _multipart_post(session, url, data, file_path=file_path, timeout=timeout)
|
||||
return _parse_json(resp, desc)
|
||||
except LoginRequiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last = e
|
||||
logger.warning("%s 第 %s/%s 次失败:%s", desc, attempt + 1, RETRY_TIMES, e)
|
||||
time.sleep(RETRY_INTERVAL)
|
||||
raise RuntimeError(f"{desc} 请求失败(已重试 {RETRY_TIMES} 次):{last}")
|
||||
|
||||
|
||||
def _b64(value):
|
||||
"""与前端 Base64.tranCode.encode 等价(标准 base64,UTF-8)。"""
|
||||
return base64.b64encode(str(value).encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
# ==================== 1. 弹窗配置 ====================
|
||||
def load_import_conf(session, menu):
|
||||
"""取导入模板配置 hrModuleBaseImport(含 importId、fieldJson 表头映射模板)。"""
|
||||
info = IMPORT_MENUS[menu]
|
||||
if menu in _CONF_CACHE:
|
||||
return _CONF_CACHE[menu]
|
||||
url = BASE_URL + TO_IMP_PAGE_URL.format(
|
||||
import_id=info["import_id"],
|
||||
title=quote(info["title"], safe=""),
|
||||
)
|
||||
html = _get_text(session, url, f"{info['label']}弹窗页")
|
||||
idx = html.find("var hrModuleBaseImport =")
|
||||
if idx < 0:
|
||||
raise RuntimeError(f"{info['label']}弹窗页未找到模板配置 hrModuleBaseImport(页面结构可能变化)")
|
||||
start = html.find("{", idx)
|
||||
try:
|
||||
conf, _ = json.JSONDecoder().raw_decode(html[start:])
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"{info['label']}弹窗页模板配置解析失败:{e}")
|
||||
if str(conf.get("id") or "") != info["import_id"]:
|
||||
logger.warning("%s弹窗页 importId=%s 与预期 %s 不一致(沿用页面返回值)",
|
||||
info["label"], conf.get("id"), info["import_id"])
|
||||
logger.info("%s模板:%s(最多 %s 行)", info["label"],
|
||||
conf.get("title") or info["title"], conf.get("maxNum") or "-")
|
||||
_CONF_CACHE[menu] = conf
|
||||
return conf
|
||||
|
||||
|
||||
def _field_list(conf):
|
||||
"""解析 fieldJson 为表头映射数组(columnName 模板字段名 / columnDisplay 中文名)。"""
|
||||
raw = conf.get("fieldJson") or "[]"
|
||||
try:
|
||||
data = json.loads(raw.replace("\n", "\\n").replace("\r", "\\r"))
|
||||
except Exception:
|
||||
data = json.loads(raw)
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
|
||||
def match_titles(field_list, excel_titles):
|
||||
"""前端 setDefaultMatchTitle 等价实现:同名列 -> 回填 excelColNum。
|
||||
|
||||
Returns:
|
||||
(title_list, matched):回填后的字段数组与成功匹配的列数。
|
||||
"""
|
||||
by_name = {}
|
||||
for t in excel_titles or []:
|
||||
if not isinstance(t, dict):
|
||||
continue
|
||||
name = str(t.get("excelColName") or "").strip()
|
||||
if name:
|
||||
by_name[name] = t.get("excelColNum")
|
||||
title_list = [dict(f) for f in field_list if isinstance(f, dict)]
|
||||
matched = 0
|
||||
for f in title_list:
|
||||
disp = str(f.get("columnDisplay") or "").strip()
|
||||
if disp in by_name and by_name[disp] is not None:
|
||||
f["excelColNum"] = by_name[disp]
|
||||
matched += 1
|
||||
return title_list, matched
|
||||
|
||||
|
||||
# ==================== 2~5. 校验 / 导入 / 结果 ====================
|
||||
def _form_base(conf, title_list):
|
||||
"""构造弹窗表单公共字段(与前端 FormData 一致)。"""
|
||||
return {
|
||||
"importId": conf["id"],
|
||||
"titleRowNum": TITLE_ROW_NUM,
|
||||
"contentRowNum": CONTENT_ROW_NUM,
|
||||
"titleList": _b64(json.dumps(title_list, ensure_ascii=False,
|
||||
separators=(",", ":"))),
|
||||
"name": "test", # 前端为兼容 IE 固定附加,照传
|
||||
}
|
||||
|
||||
|
||||
def check_file_type(session, conf, file_path, field_list):
|
||||
"""第 1 步「下一步」:文件格式校验(不写库)。返回 Excel 实际表头列表。"""
|
||||
data = _form_base(conf, field_list)
|
||||
result = _post_json(session, CHECK_FILE_TYPE_URL, data, "文件格式校验",
|
||||
file_path=file_path, timeout=180)
|
||||
if str(result.get("state")) != "1":
|
||||
raise RuntimeError(f"文件格式校验失败:{result.get('meg') or '未知原因'}")
|
||||
titles = result.get("result") or []
|
||||
logger.info("文件格式校验通过,Excel 表头 %d 列", len(titles) if isinstance(titles, list) else 0)
|
||||
return titles
|
||||
|
||||
|
||||
def submit_upload(session, conf, file_path, title_list, business_id):
|
||||
"""第 2 步「下一步」:真正导入(异步,服务端后台执行)。
|
||||
|
||||
本步骤是唯一写库动作,**不做请求重试**:重试可能造成重复导入。
|
||||
请求异常时结果未知,交由 get_import_result 轮询判定(服务端若已受理仍可查到结果)。
|
||||
"""
|
||||
data = _form_base(conf, title_list)
|
||||
data["businessId"] = business_id
|
||||
try:
|
||||
resp = _multipart_post(session, UPLOAD_DATA_URL, data, file_path=file_path, timeout=180)
|
||||
logger.info("导入请求已提交(businessId=%s,HTTP %s)", business_id, resp.status_code)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("导入请求提交异常(结果未知,转轮询判定):%s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_import_result(session, import_id, business_id):
|
||||
"""轮询导入结果(替代前端 WebSocket 的 done 回调)。
|
||||
|
||||
Returns:
|
||||
dict:{isSuccess, success, checkFail, saveFail, other, ...};超时返回 None。
|
||||
"""
|
||||
deadline = time.time() + POLL_TIMEOUT_SECONDS
|
||||
waited = 0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
resp = _multipart_post(session, GET_IMPORT_RESULT_URL,
|
||||
{"importId": import_id, "businessId": business_id},
|
||||
timeout=30)
|
||||
data = _parse_json(resp, "导入结果查询")
|
||||
state = str(data.get("state") or "").strip()
|
||||
res = data.get("result")
|
||||
if state == "1" and isinstance(res, dict) and (
|
||||
"isSuccess" in res or "success" in res):
|
||||
return res
|
||||
meg = str(data.get("meg") or "").strip()
|
||||
if meg:
|
||||
waited += POLL_INTERVAL_SECONDS
|
||||
if waited % 30 == 0:
|
||||
logger.info("导入处理中:%s(已等待 %ss)", meg, waited)
|
||||
except LoginRequiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.warning("导入结果查询失败(继续轮询):%s", e)
|
||||
time.sleep(POLL_INTERVAL_SECONDS)
|
||||
return None
|
||||
|
||||
|
||||
def fetch_exceptions(session, import_id, business_id):
|
||||
"""分页拉取失败明细(getTmpDataPage.mc,15 条/页),返回异常行列表。"""
|
||||
exceptions = []
|
||||
page_no = 1
|
||||
page_count = 1
|
||||
while page_no <= page_count:
|
||||
data = {
|
||||
"importId": import_id,
|
||||
"imp_fixed_businessid": business_id,
|
||||
"start": str((page_no - 1) * PAGE_SIZE),
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(PAGE_SIZE),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
try:
|
||||
result = _post_json(session, GET_TMP_DATA_PAGE_URL, data,
|
||||
f"导入明细第 {page_no} 页", timeout=30)
|
||||
except Exception as e:
|
||||
logger.warning("导入明细第 %s 页拉取失败:%s", page_no, e)
|
||||
break
|
||||
if str(result.get("state")) != "1":
|
||||
if page_no == 1:
|
||||
logger.info("导入明细接口无结果(state=%s,多为全部成功)", result.get("state"))
|
||||
break
|
||||
try:
|
||||
page_count = max(1, int(result.get("pageCount") or 1))
|
||||
except (TypeError, ValueError):
|
||||
page_count = 1
|
||||
for item in result.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
# 成功行返回「导入成功;」固定文案,不纳入异常
|
||||
if "导入成功" in msg:
|
||||
continue
|
||||
exceptions.append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
page_no += 1
|
||||
return exceptions
|
||||
|
||||
|
||||
def import_one_file(session, menu, file_path):
|
||||
"""对单个导入文件执行完整接口导入(校验 -> 导入 -> 结果 -> 明细)。
|
||||
|
||||
Args:
|
||||
session: HR 会话(build_session() 返回)
|
||||
menu: "add"(增员)/ "sub"(减员)
|
||||
file_path: 导入文件路径
|
||||
|
||||
Returns:
|
||||
dict:{menu, ok, stage, state, meg, is_success, success, check_fail,
|
||||
save_fail, other, exceptions, business_id, assumed_all_success}
|
||||
stage 表示失败发生的环节:conf/check/upload/result/''(成功)
|
||||
"""
|
||||
info = IMPORT_MENUS[menu]
|
||||
label = info["label"]
|
||||
out = {"menu": menu, "ok": False, "stage": "", "state": "", "meg": "",
|
||||
"is_success": False, "success": 0, "check_fail": 0, "save_fail": 0,
|
||||
"other": 0, "exceptions": [], "business_id": "",
|
||||
"assumed_all_success": False}
|
||||
|
||||
# 1) 模板配置 + 表头映射模板
|
||||
try:
|
||||
conf = load_import_conf(session, menu)
|
||||
field_list = _field_list(conf)
|
||||
except Exception as e:
|
||||
out.update(stage="conf", meg=str(e))
|
||||
return out
|
||||
|
||||
# 2) 格式校验(读文件比对表头,不写库)
|
||||
try:
|
||||
excel_titles = check_file_type(session, conf, file_path, field_list)
|
||||
except Exception as e:
|
||||
out.update(stage="check", meg=str(e))
|
||||
return out
|
||||
|
||||
# 3) 表头同名匹配(前端 setDefaultMatchTitle)
|
||||
title_list, matched = match_titles(field_list, excel_titles)
|
||||
if matched <= 0:
|
||||
out.update(stage="check",
|
||||
meg=f"导入文件表头与「{conf.get('title') or info['title']}」模板不匹配(0 列匹配)")
|
||||
return out
|
||||
logger.info("%s表头匹配 %d/%d 列", label, matched, len(title_list))
|
||||
|
||||
# 4) 提交导入(唯一写操作,businessId 每次唯一)
|
||||
business_id = uuid.uuid4().hex
|
||||
out["business_id"] = business_id
|
||||
submit_upload(session, conf, file_path, title_list, business_id)
|
||||
|
||||
# 5) 轮询结果
|
||||
result = get_import_result(session, conf["id"], business_id)
|
||||
if result is None:
|
||||
out.update(stage="result",
|
||||
meg=f"导入结果轮询超时({POLL_TIMEOUT_SECONDS}s),结果待人工确认")
|
||||
return out
|
||||
|
||||
def _int(key):
|
||||
try:
|
||||
return int(result.get(key) or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
out["is_success"] = str(result.get("isSuccess")) == "1"
|
||||
out["success"] = _int("success")
|
||||
out["check_fail"] = _int("checkFail")
|
||||
out["save_fail"] = _int("saveFail")
|
||||
out["other"] = _int("other")
|
||||
out["meg"] = str(result.get("meg") or "")
|
||||
|
||||
# 6) 失败明细
|
||||
if not out["is_success"]:
|
||||
out["exceptions"] = fetch_exceptions(session, conf["id"], business_id)
|
||||
out["ok"] = True
|
||||
return out
|
||||
@@ -1,7 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
|
||||
"""XQ0002 插件 - HR「待增减人员」增减员导入(双模式:纯接口 / 浏览器自动化)。
|
||||
|
||||
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||||
模式由 config.import_mode() 决定(plugin.json 字段 import_mode):
|
||||
- api(默认):纯接口导入,实现见 data/hr_import_api.py(逆向 HR 前端
|
||||
hr_module_base_import_do.js:checkFileType -> uploadData -> getImportResult ->
|
||||
getTmpDataPage),不启动浏览器、无弹窗,可无人值守;本文件的浏览器实现保留作兜底;
|
||||
- ui:以下浏览器自动化流程(移植影刀版 add_sub_import v1.8.0)。
|
||||
|
||||
流程(ui 模式):访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||||
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
|
||||
|
||||
插件化改造点(相对影刀版):
|
||||
@@ -28,7 +34,9 @@ import time
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
from ..config import logger, SESSIONS_DIR, get_session
|
||||
from ..data import hr_import_api
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
@@ -533,6 +541,131 @@ def _skipped_result(category, menu, reason):
|
||||
|
||||
|
||||
def import_all(categories, on_progress=None):
|
||||
"""对指定类别执行 HR 导入(对外入口,按 config.import_mode() 分流)。
|
||||
|
||||
api(默认):纯接口导入(data/hr_import_api.py),不启动浏览器、无弹窗;
|
||||
ui:浏览器自动化(_import_all_ui),保留作兜底。
|
||||
"""
|
||||
get_mode = getattr(config, "import_mode", None)
|
||||
mode = get_mode() if callable(get_mode) else "ui"
|
||||
if mode != "api":
|
||||
return _import_all_ui(categories, on_progress)
|
||||
try:
|
||||
return _import_all_api(categories, on_progress)
|
||||
except hr_import_api.LoginRequiredError as e:
|
||||
raise LoginRequiredError(str(e))
|
||||
|
||||
|
||||
def _import_all_api(categories, on_progress=None):
|
||||
"""纯接口版导入:★先全部类别【减员】再【增员】(顺序不可换,理由同 UI 版)。
|
||||
|
||||
预检/跳过语义与 UI 版完全一致(文件缺失或 0 条不启动导入、不报流程失败),
|
||||
单次导入走 hr_import_api.import_one_file()。
|
||||
"""
|
||||
if not categories:
|
||||
logger.info("无待导入类别,跳过 HR 导入")
|
||||
return []
|
||||
|
||||
results = []
|
||||
units = []
|
||||
for c in categories:
|
||||
for menu in (MENU_SUB, MENU_ADD):
|
||||
label = "减员" if menu == MENU_SUB else "增员"
|
||||
file_path = _import_file_path(c, menu)
|
||||
if not os.path.isfile(file_path):
|
||||
logger.warning("类别[%s] %s导入文件不存在,视为无需导入:%s",
|
||||
c["name"], label, file_path)
|
||||
results.append(_skipped_result(c, menu, "导入文件不存在"))
|
||||
continue
|
||||
expected_total = _count_import_rows(file_path)
|
||||
if expected_total <= 0:
|
||||
logger.info("类别[%s] %s导入文件无待导入条目,跳过导入:%s",
|
||||
c["name"], label, file_path)
|
||||
results.append(_skipped_result(c, menu, "无待导入条目"))
|
||||
continue
|
||||
units.append((c, menu, expected_total))
|
||||
|
||||
if not units:
|
||||
logger.info("各类别增/减员导入文件均无待导入条目,跳过 HR 自动导入")
|
||||
return results
|
||||
|
||||
session = hr_import_api.build_session()
|
||||
total_units = len(units)
|
||||
done = 0
|
||||
for category, menu_label, expected_total in units:
|
||||
menu_key = "sub" if menu_label == MENU_SUB else "add"
|
||||
file_path = _import_file_path(category, menu_label)
|
||||
logger.info("===== 类别[%s] 开始%s(接口版),文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
try:
|
||||
res = hr_import_api.import_one_file(session, menu_key, file_path)
|
||||
except hr_import_api.LoginRequiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"error": str(e), "error_type": type(e).__name__,
|
||||
})
|
||||
else:
|
||||
results.append(_map_api_result(category, menu_label, expected_total, res))
|
||||
done += 1
|
||||
if on_progress:
|
||||
try:
|
||||
on_progress(done, total_units)
|
||||
except Exception:
|
||||
pass
|
||||
return results
|
||||
|
||||
|
||||
def _map_api_result(category, menu_label, expected_total, res):
|
||||
"""把接口单次导入结果映射为与 UI 版一致的结构(供 summarize_results 汇总)。"""
|
||||
name = category["name"]
|
||||
base = {"category": name, "menu": menu_label, "listen_ok": True,
|
||||
"expected_total": expected_total, "meg": res.get("meg") or ""}
|
||||
|
||||
if not res.get("ok"):
|
||||
stage = res.get("stage") or "conf"
|
||||
if stage == "result":
|
||||
# 已提交导入但结果轮询超时:按「待人工确认」上报,不算流程失败
|
||||
logger.warning("类别[%s] %s:%s", name, menu_label, res.get("meg"))
|
||||
base.update({"captured": False, "state": "0", "exceptions": [],
|
||||
"success_count": 0, "total_count": 0})
|
||||
return base
|
||||
logger.error("类别[%s] %s 接口导入失败(%s):%s",
|
||||
name, menu_label, stage, res.get("meg"))
|
||||
base.update({"captured": False, "state": "", "exceptions": [],
|
||||
"success_count": 0, "total_count": 0,
|
||||
"error": res.get("meg") or stage, "error_type": f"api_{stage}"})
|
||||
return base
|
||||
|
||||
success = int(res.get("success") or 0)
|
||||
fail = (int(res.get("check_fail") or 0) + int(res.get("save_fail") or 0)
|
||||
+ int(res.get("other") or 0))
|
||||
exceptions = res.get("exceptions") or []
|
||||
for exc in exceptions:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s", exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
base.update({
|
||||
"captured": True,
|
||||
"state": TMP_DATA_STATE_OK if res.get("is_success") else "0",
|
||||
"exceptions": exceptions,
|
||||
"success_count": success,
|
||||
"total_count": success + fail or expected_total,
|
||||
"assumed_all_success": bool(res.get("is_success")),
|
||||
})
|
||||
if res.get("is_success"):
|
||||
logger.info("类别[%s] %s:接口导入成功 %d 人,无异常", name, menu_label, success)
|
||||
else:
|
||||
logger.error("类别[%s] %s:接口导入未全部成功(成功 %d,失败 %d,异常明细 %d 条)",
|
||||
name, menu_label, success, fail, len(exceptions))
|
||||
return base
|
||||
|
||||
|
||||
def _import_all_ui(categories, on_progress=None):
|
||||
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
|
||||
|
||||
预检:仅「导入文件存在且实际有待导入条目」的单元才会启动浏览器执行导入;
|
||||
|
||||
@@ -9,8 +9,12 @@
|
||||
|
||||
文件路径/日期/常量统一来自 config 层;输出(在参名单/变更清单/备份/增减员导入)
|
||||
由 report.output 负责(本模块在编排处懒加载,避免与 report 相互 import 成环)。
|
||||
|
||||
名额调度补充规则:降档(如 80万→50万、50万→20万)先复用目标档空闲名额,
|
||||
目标档实在没有空闲名额则不处理(员工保持原方案,不产生任何变更)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
import pandas as pd
|
||||
@@ -41,6 +45,26 @@ def scheme_with_suffix(category, scheme):
|
||||
return scheme
|
||||
|
||||
|
||||
_SCHEME_LEVEL_RE = re.compile(r"(\d+)\s*万")
|
||||
|
||||
|
||||
def scheme_level(scheme):
|
||||
"""方案档位数值(人保-20万→20 / 50万→50 / 80万→80);识别不了返回 None。
|
||||
|
||||
兼容带厂区后缀的方案名(如「人保-50万-水庄」),按「X万」里的数字判定档位。
|
||||
"""
|
||||
m = _SCHEME_LEVEL_RE.search(str(scheme or ""))
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
def is_downgrade(origin_scheme, target_scheme):
|
||||
"""是否降档(目标档位低于原档位,如 80万→50万);任一侧识别不了都不算降档。"""
|
||||
origin, target = scheme_level(origin_scheme), scheme_level(target_scheme)
|
||||
if origin is None or target is None:
|
||||
return False
|
||||
return target < origin
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、数据校验
|
||||
# ============================================================
|
||||
@@ -194,9 +218,11 @@ def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||||
3. 其他 → 记录"非法事件跳过"
|
||||
|
||||
返回:idle_pools, employee_map, pending_queues, change_log
|
||||
返回:idle_pools, employee_map, pending_queues, change_log, replace_intents
|
||||
(replace_intents:证件号 → {origin 原方案, target 目标方案},供分配阶段判定降档)
|
||||
"""
|
||||
change_log = []
|
||||
replace_intents = {}
|
||||
now = today_date()
|
||||
|
||||
# ---------- 1. 增加投保(批量处理) ----------
|
||||
@@ -259,6 +285,7 @@ def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
# 员工置为未参保
|
||||
employee_map[emp_id] = None
|
||||
pending_queues[target_scheme].append(emp_id)
|
||||
replace_intents[emp_id] = {"origin": origin_scheme, "target": target_scheme}
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
@@ -277,28 +304,48 @@ def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return idle_pools, employee_map, pending_queues, change_log
|
||||
return idle_pools, employee_map, pending_queues, change_log, replace_intents
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、阶段2:分配名额
|
||||
# ============================================================
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
def _revert_replace_slot(emp_id, origin_scheme, idle_pools, employee_map):
|
||||
"""回退「档次替换迁出」:把员工自己的迁出名额放回(移出空闲池),恢复其原方案参保。
|
||||
|
||||
仅在原迁出名额仍在池中未被他人复用时生效;已被复用则返回 False,
|
||||
调用方须按「全新新增」继续(否则该名额已被占用、员工会凭空消失)。
|
||||
"""
|
||||
key = to_text(emp_id)
|
||||
pool = idle_pools.get(origin_scheme) or []
|
||||
for idx, slot in enumerate(pool):
|
||||
if slot.get("type") == "档次替换迁出" and to_text(slot.get("employee_id")) == key:
|
||||
pool.pop(idx)
|
||||
employee_map[emp_id] = origin_scheme
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log, replace_intents=None):
|
||||
"""逐个方案处理待转入队列,分配空闲名额或创建新名额。
|
||||
|
||||
逻辑:
|
||||
1. 队列中的每个员工必须未参保
|
||||
2. 有空闲名额 → 复用(记录来源)
|
||||
3. 无空闲名额 → 全新新增
|
||||
3. 无空闲名额 → 降档(如 80万→50万、50万→20万)且目标档确实没有空闲名额
|
||||
→ 不处理(员工保持原方案,回退迁出名额,不产生变更记录)
|
||||
4. 其余(新参保 / 升档 / 平级)无空闲名额 → 全新新增
|
||||
|
||||
返回:final_records, change_log, reused_source_employees
|
||||
返回:final_records, change_log, reused_source_employees, skipped_downgrades
|
||||
"""
|
||||
final_records = []
|
||||
reused_source_employees = []
|
||||
skipped_downgrades = []
|
||||
replace_intents = replace_intents or {}
|
||||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||||
now = today_date()
|
||||
|
||||
for scheme in all_schemes:
|
||||
for scheme in sorted(all_schemes, key=str):
|
||||
queue = pending_queues.get(scheme, [])
|
||||
pool = idle_pools.get(scheme, [])
|
||||
|
||||
@@ -313,6 +360,30 @@ def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
})
|
||||
continue
|
||||
|
||||
intent = replace_intents.get(emp_id) or {}
|
||||
origin_scheme = intent.get("origin")
|
||||
downgrade = bool(origin_scheme) and is_downgrade(origin_scheme, scheme)
|
||||
if not pool and downgrade:
|
||||
# 降档但目标档没有空闲名额:不处理(名额不够,保持原方案)
|
||||
if _revert_replace_slot(emp_id, origin_scheme, idle_pools, employee_map):
|
||||
skipped_downgrades.append({
|
||||
"证件号": emp_id,
|
||||
"原方案": origin_scheme,
|
||||
"目标方案": scheme,
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "降档名额不足跳过",
|
||||
"详情": f"{origin_scheme}→{scheme} 降档,但 {scheme} 无空闲名额,保持原方案不处理",
|
||||
"时间": now,
|
||||
})
|
||||
logger.warning("降档跳过:%s %s→%s(目标档无空闲名额,保持原方案)",
|
||||
emp_id, origin_scheme, scheme)
|
||||
continue
|
||||
# 原迁出名额已被他人复用,无法回退,只能按全新新增完成降档
|
||||
logger.warning("降档 %s %s→%s 的原名额已被复用,无法回退,按全新新增处理",
|
||||
emp_id, origin_scheme, scheme)
|
||||
|
||||
if pool:
|
||||
# 复用空闲名额(取出优先级最高的)
|
||||
slot = pool.pop(0)
|
||||
@@ -348,7 +419,7 @@ def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return final_records, change_log, reused_source_employees
|
||||
return final_records, change_log, reused_source_employees, skipped_downgrades
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -531,16 +602,18 @@ def schedule_category(category, enable_validation=True, gen_import_files=True):
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
logger.info("处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
idle_pools, employee_map, pending_queues, change_log, replace_intents = 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)
|
||||
final_records, change_log, reused_source_employees, skipped_downgrades = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log, replace_intents)
|
||||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||||
if skipped_downgrades:
|
||||
logger.warning(" 降档名额不足未处理:%d 人(保持原方案)", len(skipped_downgrades))
|
||||
|
||||
# ---------- 阶段3+4:输出(懒加载 report,避免 import 成环) ----------
|
||||
from ..report.output import output_results, export_add_sub_import
|
||||
@@ -549,7 +622,7 @@ def schedule_category(category, enable_validation=True, gen_import_files=True):
|
||||
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)
|
||||
name_corrections, skipped_downgrades)
|
||||
|
||||
if gen_import_files:
|
||||
logger.info("生成增员/减员导入文件...")
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.10",
|
||||
"version": "1.0.16",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
@@ -68,11 +68,24 @@
|
||||
"default": true,
|
||||
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
|
||||
},
|
||||
"only_import": {
|
||||
"type": "boolean",
|
||||
"title": "运行模式·仅导入HR系统(跳过前置步骤)",
|
||||
"default": false,
|
||||
"description": "开启后跳过花名册导出、筛选复制、公式重算、名额调度、变更清单导出与导入文件生成,只用各类别文件夹中已有(已生成好)的增/减员导入文件执行 HR 导入;此模式下「自动导入HR系统」恒为开启(无其他动作)"
|
||||
},
|
||||
"import_to_hr": {
|
||||
"type": "boolean",
|
||||
"title": "自动导入HR系统",
|
||||
"default": true,
|
||||
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(浏览器自动化,先减员后增员,仅导入本次调度成功的类别);需本机 Chrome/Edge 且执行中会弹出浏览器窗口;须同时开启「生成增员/减员导入文件」"
|
||||
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(先减员后增员,仅导入本次调度成功的类别);导入素材为各类别文件夹中已有的导入文件(本次生成或此前生成均可,文件缺失/0 条的类别自动跳过)"
|
||||
},
|
||||
"import_mode": {
|
||||
"type": "string",
|
||||
"title": "HR 导入方式",
|
||||
"enum": ["api", "ui"],
|
||||
"default": "api",
|
||||
"description": "api=纯接口导入(默认,不打开浏览器、无弹窗,可无人值守);ui=浏览器自动化(旧实现,保留作兜底,需本机 Chrome/Edge)"
|
||||
},
|
||||
"dingtalk_notify": {
|
||||
"type": "boolean",
|
||||
|
||||
@@ -44,16 +44,19 @@ def _import_issues(import_results):
|
||||
|
||||
|
||||
def _build_messages(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
import_results, notes, only_import=False):
|
||||
"""构建待推送消息列表(汇总 + 异常名单),块格式交由 dingtalk_robot 分批发送。"""
|
||||
issues = _import_issues(import_results)
|
||||
issue_total = sum(len(v) for v in issues.values())
|
||||
|
||||
# ---- 1. 汇总消息 ----
|
||||
summary_lines = [
|
||||
"**处理类别 {} 个:筛选复制成功 {} 个、调度成功 {} 个**".format(
|
||||
total, filtered, scheduled),
|
||||
]
|
||||
if only_import:
|
||||
summary_lines = ["**仅导入模式:处理类别 {} 个(未执行筛选复制/名额调度)**".format(total)]
|
||||
else:
|
||||
summary_lines = [
|
||||
"**处理类别 {} 个:筛选复制成功 {} 个、调度成功 {} 个**".format(
|
||||
total, filtered, scheduled),
|
||||
]
|
||||
if import_on:
|
||||
summary_lines.extend(import_lines or ["HR 导入未执行(登录态缺失或整体失败,详见注意事项与日志)"])
|
||||
else:
|
||||
@@ -98,7 +101,7 @@ def _build_messages(total, filtered, scheduled, import_on, import_lines,
|
||||
|
||||
|
||||
def push_run_result(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
import_results, notes, only_import=False):
|
||||
"""把本次运行结果推送到钉钉群(环境取 config.DINGTALK_ENV),失败不影响主流程。
|
||||
|
||||
Args:
|
||||
@@ -107,10 +110,12 @@ def push_run_result(total, filtered, scheduled, import_on, import_lines,
|
||||
import_lines: hr_import.summarize_results 的可读文本行(未执行时传 [])
|
||||
import_results: hr_import.import_all 的逐单元结果(未执行时传 [])
|
||||
notes: 本次运行的注意事项列表
|
||||
only_import: 仅导入模式(汇总文案不展示筛选复制/调度数量)
|
||||
"""
|
||||
try:
|
||||
messages = _build_messages(total, filtered, scheduled, import_on,
|
||||
import_lines, import_results, notes)
|
||||
import_lines, import_results, notes,
|
||||
only_import=only_import)
|
||||
result = dingtalk_robot.main(messages, env=DINGTALK_ENV)
|
||||
if result.get("success"):
|
||||
log(f"钉钉群通知已推送:{result.get('message', '')}", "INFO")
|
||||
|
||||
@@ -4,7 +4,8 @@ export_change_sheet.py 合并移植)。
|
||||
|
||||
包含:
|
||||
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
|
||||
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
|
||||
(清空并重写 B/M/N/P~S 列,M列备注=「新增」标记本次全新名额)+ 姓名修正记录
|
||||
+ 备份新在参名单;
|
||||
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
|
||||
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
|
||||
(值+样式,公式转缓存结果,避免 #REF!)。
|
||||
@@ -32,12 +33,14 @@ 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):
|
||||
name_corrections=None, skipped_downgrades=None):
|
||||
"""输出四部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据;M列备注标记「新增」= 本次全新名额)
|
||||
3. 备份新在参名单
|
||||
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
|
||||
skipped_downgrades:降档但目标档无空闲名额、本次不处理的人员(在参名单保留原行不变)
|
||||
"""
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
@@ -71,10 +74,20 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
# 降档名额不足被跳过的人员(R列多为「档次替换」):本次不处理,原样保留在参名单
|
||||
skipped_ids = set()
|
||||
for _s in (skipped_downgrades or []):
|
||||
_sid = _s.get("证件号")
|
||||
if _sid is not None and not pd.isna(_sid):
|
||||
skipped_ids.add(_sid)
|
||||
if skipped_ids:
|
||||
logger.warning("以下 %d 人降档因目标档无空闲名额本次不处理,在参名单保持原方案:%s",
|
||||
len(skipped_ids), " / ".join(str(x) for x in skipped_ids))
|
||||
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列为老员工旧方案)
|
||||
(in_param_df[emp_id_col].isin(special_source_ids)) | # 特殊情况源员工保留(改M列为老员工旧方案)
|
||||
(in_param_df[emp_id_col].isin(skipped_ids)) # 降档跳过:保持原方案不动
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
@@ -318,7 +331,9 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||||
# ---------- 定位 O列(新增费用会馆列,仅用于清空历史值)----------
|
||||
# 该列已不再由插件填写(原先把花名册四级部门写进来,现改为 M列备注标「新增」),
|
||||
# 但变更清单多由历史模板复制而来,需清掉上一版遗留的四级部门值。
|
||||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
|
||||
DEPT_COL_MARK = "费用会馆"
|
||||
dept_col = 15
|
||||
@@ -327,19 +342,16 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
for _row in (1, 2)):
|
||||
dept_col = _col
|
||||
break
|
||||
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
|
||||
logger.info("变更清单费用会馆列定位:第%d列(不再填写,仅清空历史值)", dept_col)
|
||||
|
||||
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
|
||||
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
|
||||
|
||||
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
|
||||
# 清空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 # 四级部门列
|
||||
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
|
||||
|
||||
@@ -373,6 +385,11 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
reused_by_others.add(_sid)
|
||||
|
||||
def _new_slot_remark(rec):
|
||||
"""本次拿到全新名额(名额来源=全新新增)→ M列备注「新增」,用于成本归集。"""
|
||||
return "新增" if rec.get("名额来源") == "全新新增" else None
|
||||
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
@@ -393,32 +410,22 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
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})
|
||||
"category": category, "scheme": scheme,
|
||||
"remark": _new_slot_remark(rec)})
|
||||
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})
|
||||
"category": category, "scheme": scheme,
|
||||
"remark": _new_slot_remark(rec)})
|
||||
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)
|
||||
# 新参保人员:全新新增名额的「增加」行 M列备注「新增」
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme,
|
||||
"remark": _new_slot_remark(rec)})
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
@@ -434,9 +441,6 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
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列
|
||||
|
||||
@@ -1,442 +1,250 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<transition name="fade-slide">
|
||||
<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>
|
||||
</transition>
|
||||
<!-- 方案工具条:方案供「定时任务」按 config_id 引用,到点自动取方案最新参数 -->
|
||||
<div class="toolbar">
|
||||
<span class="spacer" />
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" />
|
||||
<path d="m9 12 2 2 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span v-if="lastSavedAt" class="saved">
|
||||
<i class="dot" />已保存 {{ lastSavedAt }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
@change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<!-- 内联提示 -->
|
||||
<div v-if="needLogin" class="notice is-warn">
|
||||
<span class="n-ico">!</span><span>未登录:请先在壳子(工作台)登录统一账户</span>
|
||||
</div>
|
||||
<div v-else-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<el-form label-position="top">
|
||||
<!-- 基本设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">基本设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<!-- 01 目录与日期 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">目录与日期</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="雇主险根目录">
|
||||
<el-input v-model="form.base_dir" :disabled="running" clearable
|
||||
placeholder="四类各占一个子文件夹,增/减员导入模板放在根目录" />
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.base_dir" class="dir-input" :disabled="running" clearable
|
||||
placeholder="四类各一个子文件夹,增/减员导入模板放根目录" />
|
||||
<el-button class="dir-btn" :disabled="running || picking" :loading="picking"
|
||||
@click="pickDir">选择</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="业务日期">
|
||||
<el-date-picker v-model="form.ref_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="留空=今天" :disabled="running" clearable class="wide" />
|
||||
<div class="tip">影响变更清单/在参名单/导入文件中的日期与备份文件名</div>
|
||||
:disabled="running" clearable placeholder="留空 = 今天" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 处理范围 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">处理范围</span>
|
||||
<span class="sec-line" />
|
||||
<div class="tip">
|
||||
根目录下四类各占一个子文件夹(三十七度 / 水庄餐饮 / 湖畔酒店 / 秒创传媒),
|
||||
「商业保险增员导入模板.xlsx」「商业保险减员导入模板.xlsx」放在根目录。<br>
|
||||
花名册固定使用根目录下的《员工花名册.xlsx》,缺失或超过 15 分钟时自动从 HR 导出,无需手动指定;
|
||||
业务日期影响变更清单、在参名单、导入文件内的日期与备份文件名,留空即今天。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 处理范围 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">处理范围</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="处理类别">
|
||||
<el-select v-model="form.categories" multiple :disabled="running" class="wide"
|
||||
placeholder="可多选,留空=全部类别">
|
||||
<el-form-item label="处理类别(可多选,留空 = 全部)">
|
||||
<el-select v-model="form.categories" multiple :disabled="running"
|
||||
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>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 执行开关 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">执行开关</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="启用数据校验">
|
||||
<el-switch v-model="form.enable_validation" :disabled="running" />
|
||||
<el-switch v-model="form.enable_validation" :disabled="running || form.only_import" />
|
||||
</el-form-item>
|
||||
<el-form-item label="WPS/Excel后台重算公式">
|
||||
<el-switch v-model="form.wps_recalc" :disabled="running" />
|
||||
<el-switch v-model="form.wps_recalc" :disabled="running || form.only_import" />
|
||||
</el-form-item>
|
||||
<el-form-item label="导出变更清单独立工作簿">
|
||||
<el-switch v-model="form.export_change_sheet" :disabled="running" />
|
||||
<el-switch v-model="form.export_change_sheet" :disabled="running || form.only_import" />
|
||||
</el-form-item>
|
||||
<el-form-item label="生成增/减员导入文件">
|
||||
<el-switch v-model="form.gen_import_files" :disabled="running" />
|
||||
<el-switch v-model="form.gen_import_files" :disabled="running || form.only_import" />
|
||||
</el-form-item>
|
||||
<el-form-item label="自动导入HR系统">
|
||||
</div>
|
||||
<div class="tip">
|
||||
「启用数据校验」校验工种类别与投保方案合法性,失败终止调度;「WPS/Excel后台重算公式」
|
||||
替代人工取消筛选与 Ctrl+S 刷新公式,需本机装 WPS 专业版/企业版或 MS Excel;
|
||||
「导出变更清单独立工作簿」把各类别变更清单 sheet 复制为独立文件(公式转值,保留样式)。
|
||||
运行模式选「仅导入」时,本区开关不生效。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 03 HR 导入与通知 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">HR 导入与通知</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="运行模式">
|
||||
<el-radio-group v-model="form.only_import" :disabled="running">
|
||||
<el-radio-button :value="false">完整流程</el-radio-button>
|
||||
<el-radio-button :value="true">仅导入</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="!form.only_import" label="自动导入HR系统">
|
||||
<el-switch v-model="form.import_to_hr" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item v-if="form.only_import || form.import_to_hr" label="HR导入方式">
|
||||
<el-radio-group v-model="form.import_mode" :disabled="running">
|
||||
<el-radio-button value="api">接口</el-radio-button>
|
||||
<el-radio-button value="ui">浏览器</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉群通知">
|
||||
<el-switch v-model="form.dingtalk_notify" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">「WPS/Excel后台重算公式」替代人工 Ctrl+S 刷新公式,需本机装 WPS 专业版/企业版或 MS Excel;关闭后须确保目标文件公式已人工刷新;「自动导入HR系统」会在执行中弹出浏览器窗口自动完成增/减员导入(先减员后增员),需本机 Chrome/Edge 且保持 HR 登录态;「钉钉群通知」执行完成后推送汇总与增/减员导入异常名单到钉钉群</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<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>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<transition name="fade-slide">
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
<div class="tip">
|
||||
「完整流程」按 花名册 → 筛选复制 → 重算 → 调度 → 导入 顺序执行;
|
||||
「仅导入」跳过全部前置步骤,只把各类别文件夹里已有的增/减员导入文件导入 HR(先减员后增员)。<br>
|
||||
「HR导入方式」默认「接口」:直接调 HR 导入接口,不弹浏览器、可无人值守,只需保持 HR 登录态;
|
||||
切到「浏览器」才走页面自动化(执行中会弹出浏览器窗口,需本机 Chrome/Edge)。
|
||||
文件缺失或无待导入条目的类别自动跳过;「钉钉群通知」推送结果汇总与导入异常名单。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</transition>
|
||||
</section>
|
||||
|
||||
<!-- 流程说明:大段说明收进折叠区 -->
|
||||
<details class="help">
|
||||
<summary><span>流程说明</span><span class="h-arrow">▾</span></summary>
|
||||
<div class="help-body">
|
||||
<div class="hb-line"><b>① 花名册</b>:根目录 / 指定路径的员工花名册缺失或超过 15 分钟时,自动从 HR 导出。</div>
|
||||
<div class="hb-line"><b>② 筛选复制</b>:按类别过滤事业部与虚拟大区,写入各文件夹的「雇主险变更记录」目标表。</div>
|
||||
<div class="hb-line"><b>③ 重算与调度</b>:后台取消筛选并重算公式后,执行三阶段名额调度(增加投保 / 要替换 / 减员)。</div>
|
||||
<div class="hb-line"><b>④ 输出</b>:更新在参名单与变更清单,生成各类别增员/减员导入文件,可选导出独立变更清单工作簿。</div>
|
||||
<div class="hb-line"><b>⑤ 导入</b>:先全部类别减员、再全部类别增员(替换人员必须先撤旧方案再上新方案)。</div>
|
||||
<div class="hb-line"><b>⑥ 通知</b>:推送结果汇总与增/减员导入异常名单到钉钉群,推送失败不影响主流程。</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- 操作区 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping" @click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 运行态:只留一行文字,进度与日志由壳子展示 -->
|
||||
<div v-if="running" class="runline">
|
||||
<span class="pulse" />
|
||||
<span>正在执行,日志与进度实时显示在工作台下方「运行日志」区</span>
|
||||
<span class="pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 与 plugin.json.fields.categories.items.enum 逐字一致
|
||||
const CATEGORIES = ['三十七度', '水庄餐饮', '湖畔酒店', '秒创传媒']
|
||||
|
||||
// 与 plugin.json.fields 的 default 逐项一致
|
||||
const DEFAULTS = () => ({
|
||||
base_dir: 'D:\\资料\\人资\\雇主险',
|
||||
ref_date: '',
|
||||
categories: [...CATEGORIES],
|
||||
roster_path: '',
|
||||
// 花名册路径不在界面暴露:固定用根目录/员工花名册.xlsx(缺失或过期自动从 HR 导出)
|
||||
enable_validation: true,
|
||||
wps_recalc: true,
|
||||
export_change_sheet: true,
|
||||
gen_import_files: true,
|
||||
only_import: false,
|
||||
import_to_hr: true,
|
||||
import_mode: 'api',
|
||||
dingtalk_notify: true,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
form, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.base_dir.trim()) { ElMessage.warning('请填写雇主险根目录'); return false }
|
||||
if (!form.categories.length) { ElMessage.warning('请至少选择一个处理类别'); return false }
|
||||
if (!String(form.base_dir || '').trim()) {
|
||||
ElMessage.warning('请填写雇主险根目录')
|
||||
return false
|
||||
}
|
||||
if (!form.categories || !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
|
||||
ElMessage.warning('业务日期格式应为 YYYY-MM-DD,或留空使用今天')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框(壳子 /api/dialog/directory,仅返回路径)
|
||||
const picking = ref(false)
|
||||
async function pickDir() {
|
||||
picking.value = true
|
||||
try {
|
||||
const r = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择雇主险根目录', current: form.base_dir || '' }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.base_dir = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('打开文件夹选择失败:' + e.message)
|
||||
} finally {
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ---------- 页面骨架 ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 6px 4px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: opacity 0.25s ease, transform 0.25s ease;
|
||||
}
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
/* ---------- 主容器(无边框平铺:外层由壳子 iframe 的边框统一包裹) ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
.panel :deep(.el-card__header) {
|
||||
padding: 6px 2px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
background: transparent;
|
||||
}
|
||||
.panel :deep(.el-card__body) {
|
||||
padding: 16px 2px 2px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.title-ico {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-6));
|
||||
box-shadow: inset 0 0 0 1px var(--el-color-primary-light-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.title-txt {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
line-height: 1.2;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.title-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.3;
|
||||
}
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: #2ea44f;
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
border: 1px solid rgba(46, 164, 79, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.saved .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #2ea44f;
|
||||
}
|
||||
|
||||
/* ---------- 表单分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.sec-badge {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.sec-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--el-border-color-lighter), transparent);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
.grid :deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.grid :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.grid :deep(.el-date-editor) {
|
||||
width: 100%;
|
||||
}
|
||||
/* 开关区:列宽压到最长 label(WPS/Excel后台重算公式 ≈152px)所需下限,
|
||||
6 个开关一行放下;容器过窄时仍自动换行 */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(152px, 1fr));
|
||||
gap: 14px 12px;
|
||||
}
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 18px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
letter-spacing: 2px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
box-shadow: 0 6px 16px var(--el-color-primary-light-6);
|
||||
transition: filter 0.2s, box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
.btn-run:hover {
|
||||
filter: brightness(1.06);
|
||||
box-shadow: 0 8px 20px var(--el-color-primary-light-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.btn-run:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
|
||||
border: 1px solid var(--el-color-primary-light-6);
|
||||
box-shadow: 0 2px 10px var(--el-color-primary-light-7);
|
||||
}
|
||||
.status-bar :deep(.el-progress-bar__outer) {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
.status-bar :deep(.el-progress-bar__inner) {
|
||||
background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
}
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--el-color-primary);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--el-color-primary-light-6);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.status-pct {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
/* 插件差异样式:只用壳子 token,不写字面色值;左右内边距由壳子提供 */
|
||||
.dir-ctrl { display: flex; align-items: center; gap: var(--space-2); width: 100%; }
|
||||
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
|
||||
.dir-ctrl .dir-btn { flex: 0 0 auto; }
|
||||
.grid :deep(.el-date-editor) { width: 100%; }
|
||||
</style>
|
||||
|
||||
@@ -2,6 +2,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 './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v3 · 对齐壳子「白底面板 + 描边卡」)
|
||||
- token 与壳子 frontend/src/style.css 同源(权威源 design-app/styles.css)
|
||||
- Element Plus 变量映射到壳子 token
|
||||
- 版式类:page / toolbar / notice / sec / grid / tip / actions / badge / table
|
||||
规则:插件内只用 var(--xxx),不写字面色值;左右内边距由壳子提供,不要重复加
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* 底色与卡面 */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* 描边 */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* 文字五阶 */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* 主色(靛蓝) */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-track: #DDE1F8;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* 语义色 */
|
||||
--good: #0E9F76; --good-ink: #0B8A66; --good-soft: #EBF7F2; --good-line: #D3EDE3;
|
||||
--warn: #D98218; --warn-ink: #B4700F; --warn-soft: #FDF3E4; --warn-line: rgba(217, 130, 24, .28);
|
||||
--danger: #E5484D; --danger-ink: #CC3B40; --danger-soft: #FDEDED; --danger-line: #F6D7D8;
|
||||
|
||||
/* 圆角 */
|
||||
--r-row: 8px;
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* 阴影(插件内基本不用,保持与壳子同值) */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-float: 0 8px 24px rgba(18, 20, 31, .10);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* 字体 */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--f-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
|
||||
|
||||
/* 间距 */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 28px;
|
||||
|
||||
--dur: .15s;
|
||||
--ease: cubic-bezier(.22, 1, .36, 1);
|
||||
}
|
||||
|
||||
/* ---------- Element Plus → 壳子 token ---------- */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ---------- 基础重置 ---------- */
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app { padding: 0; }
|
||||
|
||||
/* ---------- 页面:只排垂直节奏(左右 24px 由壳子给) ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
padding: 2px 0 20px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
min-height: 32px;
|
||||
}
|
||||
.toolbar .spacer { flex: 1; }
|
||||
.scheme-sel { width: 200px; }
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good-ink);
|
||||
font: 500 11px/1 var(--f-cn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.saved i { width: 5px; height: 5px; border-radius: 50%; background: var(--good); }
|
||||
.saved.is-idle { background: var(--field); border-color: var(--line); color: var(--t4); }
|
||||
.saved.is-idle i { background: var(--t5); }
|
||||
|
||||
/* ---------- 提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 9px 12px;
|
||||
border-radius: var(--r-sub);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
.notice .n-ico { flex: 0 0 auto; font-weight: 700; }
|
||||
.notice.is-warn { background: var(--warn-soft); border-color: var(--warn-line); color: var(--warn-ink); }
|
||||
.notice.is-error { background: var(--danger-soft); border-color: var(--danger-line); color: var(--danger-ink); }
|
||||
.notice.is-ok { background: var(--good-soft); border-color: var(--good-line); color: var(--good-ink); }
|
||||
|
||||
/* ---------- 分区卡:与壳子列表卡/表格卡同一套 ---------- */
|
||||
.sec {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 14px;
|
||||
background: var(--subtle);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.sec-badge {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 6px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
font: 600 10.5px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.sec-name { font: 600 13px/18px var(--f-cn); color: var(--t1); white-space: nowrap; }
|
||||
.sec-line { flex: 1; height: 1px; background: var(--line-soft); }
|
||||
.sec-body { padding: 14px 14px 6px; }
|
||||
|
||||
/* ---------- 栅格与表单 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 0 16px;
|
||||
}
|
||||
.grid-switch { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
|
||||
/* 日期行紧跟在开关行后,补一点呼吸 */
|
||||
.grid-date { margin-top: 4px; }
|
||||
.grid .el-form-item { margin-bottom: 12px; }
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-date-editor,
|
||||
.grid .el-input-number { width: 100% !important; }
|
||||
|
||||
/* ---------- 说明文字 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font: 400 11.5px/1.65 var(--f-cn);
|
||||
color: var(--t3);
|
||||
}
|
||||
.tip b { color: var(--t2); font-weight: 600; }
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan { display: flex; align-items: baseline; gap: var(--space-2); font-size: 11.5px; line-height: 1.6; color: var(--t3); }
|
||||
.plan .p-tag { flex: 0 0 auto; font-weight: 600; color: var(--brand-ink); }
|
||||
.plan .p-text { min-width: 0; }
|
||||
.plan.is-empty .p-text { color: var(--warn); }
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--line-soft);
|
||||
}
|
||||
.actions .spacer { flex: 1; }
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background var(--dur), box-shadow var(--dur), transform .06s;
|
||||
}
|
||||
.btn-run:hover { background: var(--brand-hover); }
|
||||
.btn-run:active { transform: translateY(1px); box-shadow: var(--sh-brand-sm); }
|
||||
.btn-run.is-loading { pointer-events: none; }
|
||||
|
||||
/* ---------- 状态胶囊(与壳子表格状态列同款) ---------- */
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
font: 500 11px/1 var(--f-cn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge i { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; }
|
||||
.badge.ok { color: var(--good-ink); background: var(--good-soft); border-color: var(--good-line); }
|
||||
.badge.ok i { background: var(--good); }
|
||||
.badge.warn { color: var(--warn-ink); background: var(--warn-soft); border-color: var(--warn-line); }
|
||||
.badge.warn i { background: var(--warn); }
|
||||
.badge.bad { color: var(--danger-ink); background: var(--danger-soft); border-color: var(--danger-line); }
|
||||
.badge.bad i { background: var(--danger); }
|
||||
.badge.idle { color: var(--t3); background: var(--field); border-color: var(--line); }
|
||||
.badge.idle i { background: var(--t5); }
|
||||
|
||||
/* ---------- 表格(插件内需要列表时用;与壳子表格同口径) ---------- */
|
||||
.table-card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.table-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: 12px 16px;
|
||||
background: var(--subtle);
|
||||
border-bottom: 1px solid var(--line);
|
||||
font: 600 13.5px/20px var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
.table { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
||||
.table th {
|
||||
padding: 10px 16px;
|
||||
text-align: center;
|
||||
font: 500 11px/16px var(--f-cn);
|
||||
color: var(--t3);
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.table td {
|
||||
padding: 10px 16px;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
font: 400 12px/18px var(--f-cn);
|
||||
color: var(--t2);
|
||||
}
|
||||
.table tr:last-child td { border-bottom: 0; }
|
||||
.table tbody tr { transition: background var(--dur); }
|
||||
.table tbody tr:hover { background: var(--field); }
|
||||
.table td.is-name { text-align: left; font-weight: 600; color: var(--t1); }
|
||||
.table th.is-name { text-align: left; }
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline { display: flex; align-items: center; gap: var(--space-2); font-size: 12px; color: var(--t3); }
|
||||
.runline .pct { font: 600 12px/1 var(--f-num); color: var(--brand-ink); font-variant-numeric: tabular-nums; }
|
||||
.pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--brand); animation: pulse 1.4s ease-out infinite; }
|
||||
@keyframes pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--brand-soft); }
|
||||
70% { box-shadow: 0 0 0 7px transparent; }
|
||||
100% { box-shadow: 0 0 0 0 transparent; }
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
v3.1 扩展:步骤卡 / 行式设置项 / 折叠说明
|
||||
- 适用于「互斥步骤」「开关+联动下拉」「大段流程说明」
|
||||
- 仍然只用 token,不写字面色值
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 步骤卡(互斥单选,≤4 项) ---------- */
|
||||
.step-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: var(--space-2-5);
|
||||
}
|
||||
.step-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
padding: 11px 32px 11px 13px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
cursor: pointer;
|
||||
transition: border-color var(--dur), background var(--dur), box-shadow var(--dur);
|
||||
}
|
||||
.step-card:hover { border-color: var(--brand-track); background: var(--subtle); }
|
||||
.step-card.on {
|
||||
border-color: var(--brand);
|
||||
background: var(--brand-soft);
|
||||
box-shadow: inset 0 0 0 1px var(--brand-soft);
|
||||
}
|
||||
.step-card .sc-title { font: 600 13px/18px var(--f-cn); color: var(--t1); }
|
||||
.step-card.on .sc-title { color: var(--brand-ink); }
|
||||
.step-card .sc-desc { font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
|
||||
.step-card .sc-check {
|
||||
position: absolute; top: 10px; right: 10px;
|
||||
width: 16px; height: 16px; color: var(--brand);
|
||||
}
|
||||
.step-cards.is-disabled .step-card { opacity: .55; pointer-events: none; }
|
||||
.sr-only {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
|
||||
}
|
||||
|
||||
/* ---------- 行式设置项(标题+说明在左,控件在右) ---------- */
|
||||
.rows {
|
||||
display: flex; flex-direction: column; gap: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
background: var(--subtle);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
}
|
||||
.row {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
gap: var(--space-4);
|
||||
padding: 9px 12px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: var(--r-field);
|
||||
}
|
||||
.row .r-main { min-width: 0; }
|
||||
.row .r-title { font: 500 12.5px/18px var(--f-cn); color: var(--t1); }
|
||||
.row .r-desc { margin-top: 1px; font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
|
||||
.row .r-ctrl { flex: 0 0 auto; }
|
||||
.row.is-hidden { display: none; }
|
||||
|
||||
/* ---------- 折叠说明(流程说明气泡卡片) ---------- */
|
||||
.help {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--r-sub);
|
||||
overflow: hidden;
|
||||
}
|
||||
.help > summary {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
gap: var(--space-2); padding: 10px 14px;
|
||||
background: var(--subtle);
|
||||
font: 600 12.5px/18px var(--f-cn); color: var(--t2);
|
||||
cursor: pointer; list-style: none;
|
||||
}
|
||||
.help > summary::-webkit-details-marker { display: none; }
|
||||
.help[open] > summary { border-bottom: 1px solid var(--line); }
|
||||
.help .h-arrow { color: var(--t4); transition: transform var(--dur); font-size: 11px; }
|
||||
.help[open] .h-arrow { transform: rotate(180deg); }
|
||||
.help-body {
|
||||
padding: 12px 14px;
|
||||
font: 400 12px/1.8 var(--f-cn); color: var(--t3);
|
||||
}
|
||||
.help-body b { color: var(--t2); font-weight: 600; }
|
||||
.help-body .hb-line + .hb-line { margin-top: 6px; }
|
||||
@@ -1,9 +1,14 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
@@ -15,58 +20,37 @@ async function j(url, opts) {
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
try {
|
||||
msg = (await res.json()).detail || msg
|
||||
} catch (_) { /* 保留默认 */ }
|
||||
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
@@ -78,8 +62,18 @@ function connectWS(onEvent) {
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
@@ -88,22 +82,14 @@ function mergeSaved(form, saved) {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
@@ -113,20 +99,23 @@ export function usePluginUI(opts = {}) {
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
@@ -137,6 +126,7 @@ export function usePluginUI(opts = {}) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
@@ -146,12 +136,30 @@ export function usePluginUI(opts = {}) {
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
const schemeSel = ref('')
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
@@ -161,15 +169,11 @@ export function usePluginUI(opts = {}) {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
if (!id) return
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
@@ -189,10 +193,10 @@ export function usePluginUI(opts = {}) {
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
},
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
return
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
@@ -202,10 +206,10 @@ export function usePluginUI(opts = {}) {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return // 用户取消覆盖
|
||||
return
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -226,7 +230,7 @@ export function usePluginUI(opts = {}) {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
@@ -242,38 +246,45 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
@@ -287,11 +298,10 @@ export function usePluginUI(opts = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
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 || '执行失败')
|
||||
})
|
||||
@@ -304,7 +314,7 @@ export function usePluginUI(opts = {}) {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
if (r.status === 'done') finished(r.result?.summary)
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
@@ -318,23 +328,20 @@ export function usePluginUI(opts = {}) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+23
-23
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<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-CAJDpQI-.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-klWce3Ko.css">
|
||||
<script type="module" crossorigin src="/pui/xq0002/assets/index-CrTAowxb.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-BPnwGsXm.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Reference in New Issue
Block a user