feat: 新增定性评价推送插件 v1.1.1
This commit is contained in:
@@ -33,11 +33,11 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.8"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→"
|
||||
version = "1.0.9"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,"
|
||||
"替代人工 Ctrl+S 刷新公式与人工上传导入环节")
|
||||
"替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0002"]
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - WPS/Excel COM 后台重算工具。
|
||||
"""XQ0002 插件 - WPS/Excel COM 后台重算 + 取消筛选工具。
|
||||
|
||||
替代雇主险流程中「人工打开目标文件刷新公式(Ctrl+S 保存)」环节:
|
||||
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘。
|
||||
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → CalculateFullRebuild →
|
||||
Save;WPS 不可用时回退 MS Excel(Excel.Application)。全程后台静默(Visible=False)。
|
||||
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘;
|
||||
同时移除所有 sheet 的 AutoFilter,保证每次处理结束文件以无筛选状态保存,
|
||||
后续人工「删除重新粘贴花名册」不再受筛选残留导致数据错位。
|
||||
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → 取消筛选 →
|
||||
CalculateFullRebuild → Save;WPS 不可用时回退 MS Excel(Excel.Application)。
|
||||
目标文件若已被用户在 WPS/Excel 中打开则复用该工作簿,不打断用户会话。
|
||||
"""
|
||||
import os
|
||||
|
||||
@@ -16,13 +19,16 @@ class ComRecalcError(RuntimeError):
|
||||
|
||||
|
||||
def recalc_target(file_path):
|
||||
"""对单个 xlsx 执行「打开 → 全量重算 → 保存」。
|
||||
"""对单个 xlsx 执行「取消全部筛选 → 全量重算公式 → 保存」。
|
||||
|
||||
目标文件已在 WPS/Excel 中打开时复用该工作簿(不关闭,保留用户会话);
|
||||
由本函数自行打开的工作簿在保存后关闭;仅当实例已无其他工作簿时才退出 COM。
|
||||
|
||||
Args:
|
||||
file_path: 目标文件绝对路径。
|
||||
|
||||
Raises:
|
||||
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / 文件正被 WPS 打开等)。
|
||||
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / COM 异常等)。
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.isfile(file_path):
|
||||
@@ -34,6 +40,8 @@ def recalc_target(file_path):
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
engine = ""
|
||||
wb = None
|
||||
already_open = False
|
||||
try:
|
||||
# 优先 WPS 表格 COM(Ket.Application);失败回退 MS Excel
|
||||
try:
|
||||
@@ -49,25 +57,63 @@ def recalc_target(file_path):
|
||||
"请安装 WPS 专业版/企业版或 MS Excel 后重试,或关闭「WPS/Excel 后台重算公式」开关后人工打开文件 Ctrl+S 刷新公式。"
|
||||
) from e
|
||||
|
||||
app.Visible = False # 后台不显示窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告
|
||||
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
|
||||
wb.Application.CalculateFullRebuild() # 强制完整重算全部公式
|
||||
wb.Save() # 把计算结果缓存写入 xlsx 磁盘
|
||||
wb.Close()
|
||||
logger.info("公式重算完成(%s COM):%s", engine, file_path)
|
||||
# 不设置 Visible=False:Dispatch 可能附着到用户已打开的实例,隐藏其窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告(finally 恢复)
|
||||
try:
|
||||
# 目标文件已在 WPS/Excel 中打开时复用该工作簿
|
||||
for w in app.Workbooks:
|
||||
try:
|
||||
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(file_path):
|
||||
wb = w
|
||||
already_open = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if wb is None:
|
||||
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
|
||||
|
||||
# 1. 取消所有 sheet 的筛选(筛选只是隐藏行,但会干扰人工维护花名册)
|
||||
removed = 0
|
||||
for ws in wb.Worksheets:
|
||||
try:
|
||||
if ws.AutoFilterMode:
|
||||
ws.AutoFilterMode = False
|
||||
removed += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. 强制完整重算全部公式(openpyxl 写入后公式列缓存丢失)
|
||||
wb.Application.CalculateFullRebuild()
|
||||
|
||||
# 3. 把计算结果缓存写入 xlsx 磁盘
|
||||
wb.Save()
|
||||
logger.info("公式重算完成(%s COM):取消 %d 个 sheet 筛选%s:%s",
|
||||
engine, removed,
|
||||
"(复用已打开的工作簿)" if already_open else "", file_path)
|
||||
finally:
|
||||
try:
|
||||
app.DisplayAlerts = True
|
||||
except Exception:
|
||||
pass
|
||||
if wb is not None and not already_open:
|
||||
try:
|
||||
wb.Close(SaveChanges=False)
|
||||
except Exception:
|
||||
pass
|
||||
except ComRecalcError:
|
||||
raise
|
||||
except Exception as e:
|
||||
# 文件被用户手动打开时 COM 打开会失败/冲突,给出可操作提示
|
||||
# 打开失败通常仍是文件被占用/锁定,给出可操作提示
|
||||
raise ComRecalcError(
|
||||
f"公式重算失败({engine or 'COM'}):{e}\n"
|
||||
"请确认该目标文件未被 WPS/Excel 手动打开(关闭后再试)。"
|
||||
"请确认该目标文件未被 WPS/Excel 以受保护/只读视图打开(关闭后再试)。"
|
||||
) from e
|
||||
finally:
|
||||
if app is not None:
|
||||
# 仅当实例已无其他工作簿时才退出,避免关掉用户正在使用的 WPS/Excel
|
||||
try:
|
||||
app.Quit()
|
||||
if app.Workbooks.Count == 0:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.8",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工 Ctrl+S 刷新公式与人工上传导入环节",
|
||||
"version": "1.0.9",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
@@ -54,7 +54,7 @@
|
||||
"type": "boolean",
|
||||
"title": "WPS/Excel 后台重算公式",
|
||||
"default": true,
|
||||
"description": "筛选复制后/调度后自动打开目标文件全量重算并保存,替代人工 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
|
||||
"description": "筛选复制后/调度后自动打开目标文件取消全部筛选并全量重算公式保存,替代人工取消筛选与 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
|
||||
},
|
||||
"export_change_sheet": {
|
||||
"type": "boolean",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送 插件入口。
|
||||
|
||||
需求 XQ0038:定性评价(绩效定性考评)批量推送。读取《定性评价导入明细.xlsx》的
|
||||
「加工辅助表」,按 定性发起标记(序号-部门-序列)+ 部门负责人工号 分组,每组在 OA
|
||||
蓝凌 EKP 批量创建绩效评价发起单;默认仅暂存草稿,开启 send_mode 真实发起流程
|
||||
(含子流程启动、通知复核人),真实发送后可勾选自动导出当天定性评价单核对当前
|
||||
处理人(异常标记)。总编排见 logic.run(),本入口只做 ctx 注入与 fields 解析。
|
||||
|
||||
运行上下文:platform = "oa"(需底座注入 OA 登录态)。字段由 plugin.json 权威定义:
|
||||
data_file / send_mode / test_mode / export_check / export_date / out_dir。
|
||||
"""
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config, logic
|
||||
|
||||
|
||||
class DingXingEvalPushPlugin(ScenePlugin):
|
||||
"""定性评价推送(需求 XQ0038)。"""
|
||||
|
||||
id = "xq0038"
|
||||
name = "定性评价推送"
|
||||
version = "1.1.1"
|
||||
description = ("定性评价(绩效定性考评)批量推送:读取《定性评价导入明细.xlsx》加工辅助表,"
|
||||
"按定性发起标记+部门负责人分组,在 OA 蓝凌 EKP 批量创建绩效评价发起单;"
|
||||
"默认仅暂存草稿,开启真实发送后发起流程(含子流程启动、通知复核人),"
|
||||
"发完可自动导出当天定性评价单并核对当前处理人(异常标记)。")
|
||||
platform = "oa"
|
||||
uses_month = False
|
||||
ui = True
|
||||
capabilities = ["xq0038"]
|
||||
permissions = {"platforms": ["oa"]}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / 运行参数 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_data_file(fields.get("data_file") or "")
|
||||
config.set_send_mode(bool(fields.get("send_mode", False)))
|
||||
config.set_test_mode(bool(fields.get("test_mode", True)))
|
||||
config.set_export_check(bool(fields.get("export_check", True)))
|
||||
config.set_export_date(fields.get("export_date") or "")
|
||||
config.set_out_dir(fields.get("out_dir") or "")
|
||||
|
||||
# ---- 注入 OA 登录态(底座共享会话,含 cookies)----
|
||||
session = ctx.get_session("oa")
|
||||
session.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Referer": config.BASE_URL + "/km/review/km_review_main/kmReviewMain.do",
|
||||
"Origin": config.BASE_URL,
|
||||
})
|
||||
config.set_oa_session(session)
|
||||
|
||||
ctx.log("===== 定性评价推送启动:%s%s =====" % (
|
||||
'真实发送' if config.get_send_mode() else '仅暂存草稿',
|
||||
'(测试模式)' if config.get_test_mode() else ''), "INFO")
|
||||
return logic.run()
|
||||
|
||||
|
||||
PLUGINS.append(DingXingEvalPushPlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送 插件打包脚本(统一规范版,与 xq0002/xq0011/xq0008 一致)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0038 定性评价推送\\_pack.py"
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0038_v<版本>.zip --id xq0038 --version <版本>
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_REPO_ROOT = _HERE.parents[2]
|
||||
_OUT_DIR = _REPO_ROOT / "dist-plugin"
|
||||
|
||||
# 排除项:打包脚本自身 / 前端源码与依赖 / 缓存 / 调试文件
|
||||
_EXCLUDE_DIRS = {"ui-src", "node_modules", "__pycache__", ".git", ".idea", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid = manifest["id"]
|
||||
ver = manifest["version"]
|
||||
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
|
||||
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
count = 0
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
|
||||
or p.suffix in _EXCLUDE_SUFFIXES:
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
count += 1
|
||||
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,231 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志、config.progress() 上报进度、config.get_oa_session()
|
||||
获取底座注入的 OA requests.Session(不读 cookie 文件)。
|
||||
运行参数由 __init__.py 的 run() 解析 fields 后注入(set_data_file / set_send_mode /
|
||||
set_test_mode / set_export_check / set_export_date / set_out_dir)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from collections import OrderedDict
|
||||
|
||||
# ==================== 请求默认头(底座 session 可能不带,统一补齐) ====================
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
# ==================== OA / 门户地址 ====================
|
||||
BASE_URL = 'https://oa.37du.co'
|
||||
TEMPLATE_FD_ID = '1994af414ec11b46ca19109447fb6fb6' # 绩效评价单模板
|
||||
ADD_URL = (BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=add&fdTemplateId='
|
||||
+ TEMPLATE_FD_ID)
|
||||
EDIT_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=edit&fdId='
|
||||
VIEW_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=view&fdId='
|
||||
POST_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do'
|
||||
SEARCH_URL = BASE_URL + '/sys/search/search.do'
|
||||
DATAXML_URL = BASE_URL + '/sys/common/dataxml.jsp'
|
||||
PORTAL_URL = (BASE_URL + '/sys/portal/page.jsp'
|
||||
'?portalId=174c4a7ebfac0e2a320e0474539b1251')
|
||||
|
||||
# ==================== 默认数据文件 / 导出配置 ====================
|
||||
DEFAULT_DATA_FILE = r'D:\资料\人资\定性评价推送\定性评价导入明细.xlsx'
|
||||
DATA_SHEET = '加工辅助表'
|
||||
DATA_HEADER_ROW = 2 # 表头所在行(首行为提示语)
|
||||
MAX_RETRY = 3 # 单组失败重试次数
|
||||
DEBUG = False # True 时输出调试信息
|
||||
|
||||
MODEL_NAME = 'com.landray.kmss.km.review.model.KmReviewMain'
|
||||
SEARCH_PLANS = OrderedDict([ # 门户查询方案(管理/专业序列定性评价)
|
||||
('管理序列(新)', '199bd93c6d6998ef08fc293409cbc6a7'),
|
||||
('专业序列(新)', '199bd9679aebbf36aab8e224cd698d2b'),
|
||||
])
|
||||
EXPORT_KEYWORDS = ( # 导出列:按字段字典中文名「包含」匹配,两方案各自命中(如专业序列无「定性得分」)
|
||||
'KPI考核得分', 'KPI系数', '被评价人', '部门', '创建时间', '定性得分',
|
||||
'定性考评系数', '定性考评占比', '考核月份', '文档状态',
|
||||
'员工工号', '员工姓名显示值', '最终绩效等级', '最终绩效系数',
|
||||
)
|
||||
|
||||
# ==================== 表单字段(逆向结论固化,勿改) ====================
|
||||
# 单头字段
|
||||
FD_REPORTER = 'fd_3b07f5cf6764ec' # 提报人(new_address,页面 JS 自动填当前用户)
|
||||
FD_CATEGORY = 'fd_3b07f60887a0e0' # 人员类别(单选)
|
||||
FD_EVAL_USER = 'fd_3b3ed9a88d549a' # 被评价人(relation_choose 单选)
|
||||
FD_MONTH = 'fd_3e7d96f3848888' # 考核月份
|
||||
FD_REVIEWER = 'fd_3e798512bd3dd8' # 绩效复核人(address 多选)
|
||||
|
||||
# 明细表(模板 fd_3b07f63c1975a2.<行号>.<fd>)字段 → 加工辅助表 A-N 列名
|
||||
DET_PREFIX = 'fd_3b07f63c1975a2'
|
||||
DET_USER_FD = 'fd_3e92ac2eabd704' # 明细行被评价人(address)
|
||||
DET_FIELDS = OrderedDict([
|
||||
('月份', 'fd_3b07f66df3dddc'),
|
||||
('工号', 'fd_3b07f66b2fd146'),
|
||||
('部门1', 'fd_3b07f6961e2d74'),
|
||||
('是否参与强制分布', 'fd_3e859de2c946a4'),
|
||||
('定性得分', 'fd_3e74f39c387020'),
|
||||
('定性系数', 'fd_3e74f39f1d12bc'),
|
||||
('定性占比', 'fd_3e74f3a1ee9b0e'),
|
||||
('KPI系数', 'fd_3b1bced70cac6e'),
|
||||
('KPI得分', 'fd_3b07f65f9c0cba'),
|
||||
('KPI占比', 'fd_3b07f65cbc2212'),
|
||||
('绩效系数', 'fd_3e74f39dcd3e78'),
|
||||
('绩效等级', 'fd_3e74f3a729b0b2'),
|
||||
('评价说明', 'fd_3e7b401a25c082'),
|
||||
])
|
||||
|
||||
SERIES_MAP = {'管理': '管理序列', '专业': '专业序列'}
|
||||
|
||||
TAG_RE = re.compile(r'<input\b[^>]*>|<textarea\b[^>]*>.*?</textarea>', re.S | re.I)
|
||||
ATTR_RE = re.compile(r'''(name|value|type|checked|selected)\s*=\s*("([^"]*)"|'([^']*)')''', re.I)
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_progress_base = 0 # 进度重映射基点(多阶段编排:子流程 0-100 → 总进度 base..base+span)
|
||||
_progress_span = 100
|
||||
_oa_session = None
|
||||
_data_file = DEFAULT_DATA_FILE
|
||||
_send_mode = False
|
||||
_test_mode = True
|
||||
_export_check = True
|
||||
_export_date = ''
|
||||
_out_dir = ''
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log() 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress(RunContext.progress),各模块可上报细粒度进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def set_progress_range(base, span):
|
||||
"""设置进度重映射区间(多阶段编排时,把子流程 0-100 映射到总进度 base..base+span)。"""
|
||||
global _progress_base, _progress_span
|
||||
_progress_base, _progress_span = int(base), int(span)
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(_progress_base + pct * _progress_span / 100.0))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log(f"进度 {pct}%", "DEBUG")
|
||||
|
||||
|
||||
def set_oa_session(session):
|
||||
"""注入底座 ctx.get_session('oa') 返回的 requests.Session(已带 OA cookies)。"""
|
||||
global _oa_session
|
||||
_oa_session = session
|
||||
|
||||
|
||||
def get_oa_session():
|
||||
"""取底座注入的 OA requests.Session;未注入时抛友好错误。"""
|
||||
if _oa_session is None:
|
||||
raise RuntimeError("未注入 OA 登录态,请先在工作台(壳子)登录 OA 系统再运行")
|
||||
return _oa_session
|
||||
|
||||
|
||||
def set_export_check(flag):
|
||||
global _export_check
|
||||
_export_check = bool(flag)
|
||||
|
||||
|
||||
def get_export_check():
|
||||
return _export_check
|
||||
|
||||
|
||||
def set_data_file(path):
|
||||
global _data_file
|
||||
_data_file = (path or '').strip().strip('"') or DEFAULT_DATA_FILE
|
||||
|
||||
|
||||
def get_data_file():
|
||||
return _data_file
|
||||
|
||||
|
||||
def set_send_mode(flag):
|
||||
global _send_mode
|
||||
_send_mode = bool(flag)
|
||||
|
||||
|
||||
def get_send_mode():
|
||||
return _send_mode
|
||||
|
||||
|
||||
def set_test_mode(flag):
|
||||
global _test_mode
|
||||
_test_mode = bool(flag)
|
||||
|
||||
|
||||
def get_test_mode():
|
||||
return _test_mode
|
||||
|
||||
|
||||
def set_export_date(value):
|
||||
global _export_date
|
||||
_export_date = (value or '').strip()
|
||||
|
||||
|
||||
def get_export_date():
|
||||
return _export_date
|
||||
|
||||
|
||||
def set_out_dir(path):
|
||||
global _out_dir
|
||||
_out_dir = (path or '').strip().strip('"')
|
||||
|
||||
|
||||
def get_out_dir():
|
||||
return _out_dir
|
||||
|
||||
|
||||
def export_output_dir():
|
||||
"""导出输出目录:优先 out_dir,否则数据文件同目录。"""
|
||||
return _out_dir or os.path.dirname(get_data_file())
|
||||
@@ -0,0 +1,77 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送 插件 - 数据层:OA 接口请求。
|
||||
|
||||
只依赖 Python 标准库 / config(常量与钩子)。会话一律经 config.get_oa_session()
|
||||
获取底座注入的 requests.Session(已带 OA cookies),不在本层读 cookie 文件。
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def org_search(s, key):
|
||||
"""通讯录查询(orgType=8 人员):key 支持工号精确/姓名模糊,返回 (id, name)。"""
|
||||
resp = s.post(config.DATAXML_URL,
|
||||
data={"s_bean": "organizationDialogSearch", "key": key,
|
||||
"startWith": "", "orgType": "8", "times": "2"}, timeout=20)
|
||||
m = re.search(r'<data\b[^>]*>', resp.text)
|
||||
if not m:
|
||||
return None, None
|
||||
tag = m.group(0)
|
||||
i = re.search(r'''\bid="([^"]+)"''', tag)
|
||||
n = re.search(r'''\bname="([^"]+)"''', tag)
|
||||
return (i.group(1) if i else None, n.group(1) if n else None)
|
||||
|
||||
|
||||
def get_login_user(s):
|
||||
"""门户页内嵌登录信息,返回 (姓名 userName, 登录名/工号 loginName)。"""
|
||||
resp = s.get(config.PORTAL_URL, timeout=30)
|
||||
name = re.search(r"var\s+userName\s*=\s*'([^']*)'", resp.text)
|
||||
no = re.search(r"var\s+loginName\s*=\s*'([^']*)'", resp.text)
|
||||
return (name.group(1) if name else '', no.group(1) if no else '')
|
||||
|
||||
|
||||
def get_export_columns(s, search_id):
|
||||
"""查询方案字段字典,返回 [(fd, 中文名), ...]。"""
|
||||
resp = s.get(config.DATAXML_URL,
|
||||
params={"s_bean": "sysSearchResultExportDictService",
|
||||
"fdModelName": config.MODEL_NAME, "searchId": search_id,
|
||||
"type": "opt"}, timeout=20)
|
||||
return re.findall(r'<data\s+key0="([^"]+)"\s+key1="([^"]*)"', resp.text)
|
||||
|
||||
|
||||
def export_plan_once(s, search_id, day, out_path):
|
||||
"""单次导出一个查询方案,返回 (行数, 错误信息);错误信息为空即成功。"""
|
||||
ts = str(int(time.time() * 1000))
|
||||
# 条件槽位与门户抓包一致:v0_2=eq & v1_2=创建时间(当天)
|
||||
base = {"method": "result", "fdModelName": config.MODEL_NAME,
|
||||
"searchId": search_id, "canClose": "false", "isNew": "true",
|
||||
"j_aside": "false", "j_rIframe": "true", "j_iframe": "true",
|
||||
"v0_2": "eq", "v1_2": day, "j_timestamp": ts}
|
||||
resp = s.get(config.SEARCH_URL, params=base, timeout=30,
|
||||
headers={"Referer": config.SEARCH_URL})
|
||||
m = re.search(r'exportNum:\s*"(\d+)"', resp.text)
|
||||
if not m:
|
||||
return None, '结果页未取得 exportNum(OA 登录态可能失效,请重新登录)'
|
||||
total = int(m.group(1))
|
||||
if total == 0:
|
||||
return 0, ''
|
||||
cols = [fd for fd, name in get_export_columns(s, search_id)
|
||||
if any(kw in name for kw in config.EXPORT_KEYWORDS)]
|
||||
if not cols:
|
||||
return None, '字段字典未匹配到导出列'
|
||||
data = dict(base)
|
||||
data["method"] = "exportResult"
|
||||
data.update({"fdColumns": ';'.join(cols), "fdNum": str(total),
|
||||
"fdNumStart": "1", "fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true", "checkIdValues": ""})
|
||||
resp = s.post(config.SEARCH_URL, data=data, timeout=120,
|
||||
headers={"Referer": config.SEARCH_URL})
|
||||
ctype = resp.headers.get('Content-Type', '')
|
||||
if 'application/vnd.ms-excel' not in ctype:
|
||||
text = re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', resp.text))
|
||||
return None, '导出返回非 xls(%s):%s' % (ctype, text[:150])
|
||||
with open(out_path, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
return total, ''
|
||||
@@ -0,0 +1,373 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送 插件 - 业务逻辑层:读分组、OA 填表提交、回验、推送编排。
|
||||
|
||||
只依赖 Python 标准库 / config(常量与钩子)/ data(通讯录查询)。
|
||||
会话统一经 config.get_oa_session() 获取(底座注入)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
from collections import OrderedDict
|
||||
|
||||
from .. import config
|
||||
from ..data import org_search
|
||||
|
||||
|
||||
# ==================== 页面表单解析(模拟浏览器整表提交) ====================
|
||||
|
||||
def get_attrs(tag):
|
||||
out = {}
|
||||
for m in config.ATTR_RE.finditer(tag):
|
||||
val = m.group(3) if m.group(3) is not None else m.group(4)
|
||||
out[m.group(1).lower()] = val
|
||||
for flag in ('checked', 'selected'):
|
||||
if re.search(r'\b%s\b' % flag, tag, re.I) and flag not in out:
|
||||
out[flag] = flag
|
||||
return out
|
||||
|
||||
|
||||
def parse_fields(page):
|
||||
"""解析 add 页全部 input/textarea 为 (name, value) 保序列表(模拟浏览器整表提交)。"""
|
||||
fields = []
|
||||
for tag in config.TAG_RE.findall(page):
|
||||
low = tag.lower()
|
||||
if low.startswith('<textarea'):
|
||||
m = re.search(r'name\s*=\s*("([^"]*)"|\'([^\']*)\')', tag, re.I)
|
||||
if not m:
|
||||
continue
|
||||
name = m.group(2) if m.group(2) is not None else m.group(3)
|
||||
body = re.match(r'<textarea\b[^>]*>(.*?)</textarea>', tag, re.S | re.I)
|
||||
fields.append((name, body.group(1) if body else ''))
|
||||
continue
|
||||
a = get_attrs(tag)
|
||||
name = a.get('name')
|
||||
if name is None:
|
||||
continue
|
||||
itype = (a.get('type') or 'text').lower()
|
||||
if itype in ('submit', 'button', 'image', 'file', 'reset'):
|
||||
continue
|
||||
if itype in ('checkbox', 'radio') and 'checked' not in a:
|
||||
continue
|
||||
fields.append((name, a.get('value', '')))
|
||||
return fields
|
||||
|
||||
|
||||
# ==================== 数据读取与分组 ====================
|
||||
|
||||
def clean_header(h):
|
||||
"""列名清洗:去掉 (*) 与尾部中文括号注记。"""
|
||||
h = re.sub(r'\(\*\)\s*$', '', h.strip())
|
||||
h = re.sub(r'([^)]*)\s*$', '', h)
|
||||
return h.strip()
|
||||
|
||||
|
||||
def read_groups():
|
||||
"""读取加工辅助表并按(标记序号, 序列, 部门负责人工号串)分组。
|
||||
|
||||
返回 (总行数, OrderedDict{key: [行记录,...]}),组内行序=Excel 行序。
|
||||
行记录 = {明细列名: 值}(A-N 原样)。
|
||||
"""
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(config.get_data_file(), read_only=True, data_only=True)
|
||||
if config.DATA_SHEET not in wb.sheetnames:
|
||||
raise ValueError('数据文件缺少 sheet:%s(现有:%s)'
|
||||
% (config.DATA_SHEET, '/'.join(wb.sheetnames)))
|
||||
ws = wb[config.DATA_SHEET]
|
||||
it = ws.iter_rows(values_only=True)
|
||||
for _ in range(config.DATA_HEADER_ROW - 1):
|
||||
next(it, None)
|
||||
header = [clean_header('' if h is None else str(h)) for h in next(it)]
|
||||
col = {}
|
||||
for i, h in enumerate(header):
|
||||
if h and h not in col:
|
||||
col[h] = i
|
||||
need = list(config.DET_FIELDS.keys()) + ['定性发起标记', '部门负责人工号']
|
||||
miss = [c for c in need if c not in col]
|
||||
if miss:
|
||||
raise ValueError('加工辅助表缺少列:%s' % '、'.join(miss))
|
||||
|
||||
rows = []
|
||||
for vals in it:
|
||||
if vals is None or all(v is None or str(v).strip() == '' for v in vals):
|
||||
continue
|
||||
r = {}
|
||||
for c in need:
|
||||
i = col[c]
|
||||
v = vals[i] if i < len(vals) else None
|
||||
r[c] = '' if v is None else str(v).strip()
|
||||
if not r['工号'] or not r['定性发起标记']:
|
||||
continue
|
||||
rows.append(r)
|
||||
wb.close()
|
||||
|
||||
groups = OrderedDict()
|
||||
for r in rows:
|
||||
parts = [p.strip() for p in r['定性发起标记'].split('-')]
|
||||
if len(parts) < 3:
|
||||
raise ValueError('定性发起标记格式异常:%s(工号 %s)'
|
||||
% (r['定性发起标记'], r['工号']))
|
||||
series = parts[-1]
|
||||
if series not in config.SERIES_MAP:
|
||||
raise ValueError('未知序列:%s(标记 %s,工号 %s)'
|
||||
% (series, r['定性发起标记'], r['工号']))
|
||||
owner_nos = tuple(n for n in re.split(r'[、,,;;\s]+', r['部门负责人工号']) if n)
|
||||
if not owner_nos:
|
||||
raise ValueError('部门负责人工号为空(工号 %s)' % r['工号'])
|
||||
key = (parts[0], series, owner_nos)
|
||||
groups.setdefault(key, []).append(r)
|
||||
return len(rows), groups
|
||||
|
||||
|
||||
# ==================== 单据创建 ====================
|
||||
|
||||
def fill_and_post(s, group):
|
||||
"""推送一组(一张单,明细多行),返回 (fdId, 是否成功, 说明)。失败由调用方重试。"""
|
||||
seq_no, series, owner_nos = group['key']
|
||||
rows = group['rows']
|
||||
send_mode = config.get_send_mode()
|
||||
test_mode = config.get_test_mode()
|
||||
|
||||
# 1) 解析部门负责人(多选,按工号列顺序)
|
||||
owners = []
|
||||
for no in owner_nos:
|
||||
o_id, o_name = org_search(s, no)
|
||||
if not o_id:
|
||||
return '', False, '通讯录未查到部门负责人工号 %s' % no
|
||||
owners.append((o_id, o_name))
|
||||
|
||||
# 2) 解析组内成员(按 Excel 行序,同工号复用)
|
||||
members = OrderedDict()
|
||||
for r in rows:
|
||||
no = r['工号']
|
||||
if no in members:
|
||||
continue
|
||||
m_id, m_name = org_search(s, no)
|
||||
if not m_id:
|
||||
return '', False, '通讯录未查到工号 %s' % no
|
||||
members[no] = (m_id, m_name)
|
||||
|
||||
# 3) 取 add 页(每次独立,fdId 服务端预生成)
|
||||
resp = s.get(config.ADD_URL, timeout=30)
|
||||
page = resp.text
|
||||
if 'kmReviewMainForm' not in page:
|
||||
return '', False, 'add 页加载异常(OA 登录态可能失效,请重新登录)'
|
||||
data = dict(parse_fields(page))
|
||||
fd_id = data.get('fdId', '')
|
||||
|
||||
# 4) 单头
|
||||
data['method'] = 'saveDraft' if not send_mode else 'save'
|
||||
data['docStatus'] = '10'
|
||||
if not send_mode:
|
||||
# 暂存开关(浏览器"暂存"按钮行为):服务端走仅保存分支、不启动流程
|
||||
data['sysWfBusinessForm.canStartProcess'] = 'false'
|
||||
data['extendDataFormInfo.value(%s)' % config.FD_CATEGORY] = config.SERIES_MAP[series]
|
||||
# 被评价人(人员类别2,relationChoose 关联工号串):实测手动发起的成功单据该字段为空,
|
||||
# 子流程(N7 启动子流程)数据映射依赖它;若填入"工号字符串"会使子流程被评价人解析失效,
|
||||
# 报"启动子流程失败,存在处理人为空或失效"。故留空(与手动发起一致)。
|
||||
for suffix in ('', '_text', '_dataFdId', '_dataSourceId', '_dataModelName',
|
||||
'_selectedDatas'):
|
||||
data['extendDataFormInfo.value(%s%s)' % (config.FD_EVAL_USER, suffix)] = ''
|
||||
# 考核月份(取组内首行月份,与明细一致)
|
||||
data['extendDataFormInfo.value(%s)' % config.FD_MONTH] = rows[0]['月份']
|
||||
# 绩效复核人(多选地址本,分号分隔、按工号列顺序)
|
||||
data['extendDataFormInfo.value(%s.id)' % config.FD_REVIEWER] = ';'.join(o[0] for o in owners)
|
||||
data['extendDataFormInfo.value(%s.name)' % config.FD_REVIEWER] = ';'.join(o[1] for o in owners)
|
||||
|
||||
# 5) 明细多行(A-N 列原样,行序=Excel 行序)
|
||||
det_prefix = 'extendDataFormInfo.value(%s.' % config.DET_PREFIX
|
||||
data = {k: v for k, v in data.items() if not k.startswith(det_prefix)}
|
||||
row_pairs = []
|
||||
for i, r in enumerate(rows):
|
||||
m_id, m_name = members[r['工号']]
|
||||
row_pairs.append(('%s%d.fdId)' % (det_prefix, i), ''))
|
||||
for col_name, fd in config.DET_FIELDS.items():
|
||||
val = r.get(col_name, '')
|
||||
if col_name == '评价说明' and test_mode:
|
||||
val = val + '【测试】' if val else '【测试】'
|
||||
row_pairs.append(('%s%d.%s)' % (det_prefix, i, fd), val))
|
||||
row_pairs.append(('%s%d.%s.id)' % (det_prefix, i, config.DET_USER_FD), m_id))
|
||||
row_pairs.append(('%s%d.%s.name)' % (det_prefix, i, config.DET_USER_FD), m_name))
|
||||
|
||||
# 6) 流程参数(严格还原 add 页 /sys/lbpmservice/include/syslbpmprocess_submit.js
|
||||
# 中 lbpm.globals.setParameterOnSubmit() + 起草提交操作 operation_drafter_submit.js
|
||||
# 的 setOperationParam() 的组装结果):
|
||||
# taskId = lbpm.nowProcessorInfoObj.id → fdCurNodeXML 中 draftWorkitem 任务 id
|
||||
# processId = $("input[name='sysWfBusinessForm.fdProcessId']").val()
|
||||
# activityType = lbpm.nowProcessorInfoObj.type → "draftWorkitem"
|
||||
# operationType= lbpm.currentOperationType → 选中 oprGroup=drafter_submit:提交文档
|
||||
# param.operationName = 当前操作名(提交文档)
|
||||
# param.identityId = rolesSelectObj 选中值 → 提交人身份(fdIdentityId/fdDefaultIdentity)
|
||||
# 注意 activityType 必须是 draftWorkitem:若误传 draftNode,引擎会在 draftNode
|
||||
# 活动里按 taskId 找不到工作项,抛 TaskRefExecutionIsNullException(页面提示
|
||||
# "当前处理的流程已被其他人抢先一步提交")。
|
||||
# 提交人身份/操作(浏览器真实提交参数,经 agent-browser 抓包验证):
|
||||
# 表单字段 oprGroup=drafter_submit:提交文档、rolesSelectObj=<身份id>、
|
||||
# sysWfBusinessForm.fdSystemNotifyType={}、提报人 extendDataFormInfo.value(fd_xxx.id)
|
||||
# param 内 identityId、operationName。这些缺一不可:引擎读 oprGroup/身份来确定
|
||||
# "提交人/启动人",漏传会导致子流程启动节点解析启动人身份为空/失效,
|
||||
# 报"启动子流程失败,存在处理人为空或失效"(对应启动人策略③提示错误)。
|
||||
param_json = {
|
||||
"taskId": "", "processId": fd_id, "activityType": "draftWorkitem",
|
||||
"param": {"notifyType": "{}",
|
||||
"notifyLevel": data.get('sysWfBusinessForm.fdNotifyLevel', '3'),
|
||||
"notifyOnFinish": True, "notifyForFollow": False,
|
||||
"auditNote": "",
|
||||
"auditNoteFdId": data.get('sysWfBusinessForm.fdAuditNoteFdId', ''),
|
||||
"dayOfNotifyDrafter": "0", "hourOfNotifyDrafter": "0",
|
||||
"minuteOfNotifyDrafter": "0"},
|
||||
}
|
||||
if send_mode:
|
||||
# 真实发起:taskId 必须指向 fdCurNodeXML 中注册了 drafter_submit 操作的
|
||||
# draftWorkitem 任务(taskId 为空会默认落到 draftNode 任务,而该任务只注册
|
||||
# drafter_abandon 操作,报"drafter_submit操作未授权")。该隐藏域 value 在
|
||||
# HTML 中整体转义(< " 等),需先反转义再解析。
|
||||
m_xml = re.search(
|
||||
r'name="sysWfBusinessForm\.fdCurNodeXML"[^>]*value="([^"]*)"', page)
|
||||
raw = m_xml.group(1) if m_xml else ''
|
||||
raw = raw.replace('"', '"').replace('<', '<').replace('>', '>')
|
||||
m_task = re.search(r'<task type="draftWorkitem"[^>]*id="([^"]+)"', raw)
|
||||
param_json["taskId"] = m_task.group(1) if m_task else ''
|
||||
param_json["operationType"] = "drafter_submit"
|
||||
param_json["processId"] = data.get('sysWfBusinessForm.fdProcessId', '') or fd_id
|
||||
# 提交人身份(弹窗选中值=rolesSelectObj;页面默认 fdIdentityId/fdDefaultIdentity)
|
||||
identity_id = (data.get('sysWfBusinessForm.fdIdentityId', '')
|
||||
or data.get('sysWfBusinessForm.fdDefaultIdentity', '') or '')
|
||||
param_json["param"]["identityId"] = identity_id
|
||||
param_json["param"]["operationName"] = "提交文档"
|
||||
# 浏览器真实提交的流程相关表单字段(引擎据 oprGroup/rolesSelectObj 确定操作人与身份)
|
||||
data['oprGroup'] = 'drafter_submit:提交文档'
|
||||
data['rolesSelectObj'] = identity_id
|
||||
data['handlerIds[0]'] = ''
|
||||
data['handlerNames[0]'] = ''
|
||||
data['commonUsages'] = ''
|
||||
data['fdCanCircularize'] = 'true'
|
||||
data['sysWfBusinessForm.fdSystemNotifyType'] = '{}'
|
||||
if identity_id:
|
||||
data['extendDataFormInfo.value(%s.id)' % config.FD_REPORTER] = identity_id
|
||||
config.log('[DEBUG] 发起参数 fdId=%s taskId=%s processId=%s identityId=%s'
|
||||
% (fd_id, param_json['taskId'], param_json['processId'], identity_id))
|
||||
data['sysWfBusinessForm.fdParameterJson'] = json.dumps(
|
||||
param_json, separators=(',', ':'), ensure_ascii=False)
|
||||
|
||||
payload = list(data.items()) + row_pairs
|
||||
if config.DEBUG:
|
||||
config.log('[DEBUG] payload 字段数=%d fdId=%s 明细行数=%d 复核人=%s'
|
||||
% (len(payload), fd_id, len(rows), [o[1] for o in owners]))
|
||||
|
||||
# 7) 提交
|
||||
post = s.post(config.POST_URL, data=payload, timeout=30, allow_redirects=True)
|
||||
body = post.text
|
||||
if send_mode:
|
||||
# 成功会返回 edit 页(含 ResourceStringCache 等内联 JS,其中可能有
|
||||
# "Exception"字样,不能用它判断失败);服务端错误页固定含"很抱歉,
|
||||
# 操作失败"。提交是否真正落库交由下方 edit 页回验兜底。
|
||||
ok = (post.status_code == 200 and '很抱歉,操作失败' not in body)
|
||||
else:
|
||||
ok = ('您的操作已成功' in body) or ('method=edit&fdId=' in body)
|
||||
if ok:
|
||||
# 8) edit 页回验:明细每人工号、复核人姓名是否落库
|
||||
miss = verify_draft(s, fd_id, rows, owners)
|
||||
if miss:
|
||||
return fd_id, False, '已提交但回验缺失:%s' % '、'.join(miss)
|
||||
return fd_id, True, ('发送成功' if send_mode else '草稿成功')
|
||||
text = re.sub(r'<[^>]+>', ' ', body)
|
||||
text = re.sub(r'\s+', ' ', text)
|
||||
m = re.search(r'(很抱歉,操作失败.*?)(?:</|$)', text)
|
||||
return fd_id, False, (m.group(1)[:200] if m else text[:200])
|
||||
|
||||
|
||||
def verify_draft(s, fd_id, rows, owners):
|
||||
"""回验落库,返回缺失项列表(空=通过)。
|
||||
|
||||
暂存走 edit 页(起草人可编辑);真实发送后单据已进入复核人待办、起草人失去
|
||||
编辑权(edit 返回 403),须改走 view 页(提交后仍可只读查看)。
|
||||
"""
|
||||
resp = s.get((config.VIEW_URL if config.get_send_mode() else config.EDIT_URL)
|
||||
+ fd_id, timeout=30)
|
||||
body = resp.text
|
||||
miss = [r['工号'] for r in rows if r['工号'] not in body]
|
||||
miss += ['复核人' + o[1] for o in owners if o[1] and o[1] not in body]
|
||||
return miss
|
||||
|
||||
|
||||
def process_one(s, group, seq):
|
||||
"""单组处理,含全局重试,返回 (是否成功, fdId/错误)。"""
|
||||
seq_no, series, owner_nos = group['key']
|
||||
label = '组%d %s-%s 负责人[%s] %d人' % (
|
||||
seq, seq_no, series, '/'.join(owner_nos), len(group['rows']))
|
||||
last_err = ''
|
||||
for attempt in range(1, config.MAX_RETRY + 1):
|
||||
try:
|
||||
fd_id, ok, msg = fill_and_post(s, group)
|
||||
except Exception:
|
||||
last_err = '异常: ' + traceback.format_exc(limit=1).replace('\n', ' ')
|
||||
fd_id, ok, msg = '', False, last_err
|
||||
if ok:
|
||||
config.log('%s -> %s fdId=%s' % (label, msg, fd_id))
|
||||
return True, {'fdId': fd_id, 'message': msg}
|
||||
last_err = msg
|
||||
config.log('%s -> 第%d次失败:%s' % (label, attempt, msg))
|
||||
time.sleep(1)
|
||||
config.log('%s -> 已重试%d次仍失败' % (label, config.MAX_RETRY))
|
||||
return False, last_err
|
||||
|
||||
|
||||
# ==================== 推送编排 ====================
|
||||
|
||||
def run_push():
|
||||
"""批量推送编排:读分组 → 逐组提交(含重试)→ 汇总。返回 {summary, detail, path}。"""
|
||||
row_cnt, groups = read_groups()
|
||||
config.log('读取 %d 行,分 %d 组(%s | 模式=%s)' % (
|
||||
row_cnt, len(groups), os.path.basename(config.get_data_file()),
|
||||
'真实发送' if config.get_send_mode() else '仅暂存'))
|
||||
s = config.get_oa_session()
|
||||
items = list(groups.items())
|
||||
n = len(items)
|
||||
ok_cnt, fail_list, detail = 0, [], {}
|
||||
for i, (seq, (key, grp_rows)) in enumerate(items, 1):
|
||||
config.progress(int(100 * (i - 1) / n) if n else 0)
|
||||
group = {'key': key, 'rows': grp_rows}
|
||||
ok, info = process_one(s, group, seq)
|
||||
label = '组%d %s-%s 负责人[%s]' % (seq, key[0], key[1], '/'.join(key[2]))
|
||||
detail[label] = {
|
||||
'seq': seq, 'series': key[1], 'owners': list(key[2]),
|
||||
'rows': len(grp_rows), 'success': ok, 'result': info,
|
||||
}
|
||||
if ok:
|
||||
ok_cnt += 1
|
||||
else:
|
||||
fail_list.append((seq, key, len(grp_rows), info))
|
||||
config.progress(int(100 * i / n) if n else 100)
|
||||
config.progress(100)
|
||||
config.log('==== 完成:成功 %d 组 / 失败 %d 组 ====' % (ok_cnt, len(fail_list)))
|
||||
for seq, key, cnt, err in fail_list:
|
||||
config.log('失败 组%d %s-%s 负责人[%s] %d人:%s'
|
||||
% (seq, key[0], key[1], '/'.join(key[2]), cnt, err))
|
||||
summary = '定性评价推送完成:成功 %d 组 / 失败 %d 组%s' % (
|
||||
ok_cnt, len(fail_list),
|
||||
'(%s)' % '、'.join(str(f[0]) for f in fail_list) if fail_list else '')
|
||||
return {'summary': summary, 'detail': detail, 'path': config.get_data_file()}
|
||||
|
||||
|
||||
# ==================== 总编排(入口 __init__.py 委托至此) ====================
|
||||
|
||||
def run():
|
||||
"""总编排:批量推送(0-80%)→ 真实发送且勾选核对时追加导出核对(80-100%)。
|
||||
|
||||
暂存草稿不发起流程、无可核对单据,故仅 send_mode 且 export_check 时执行第二阶段。
|
||||
返回 {summary, detail, path}。
|
||||
"""
|
||||
config.set_progress_range(0, 80)
|
||||
result = run_push()
|
||||
if config.get_send_mode() and config.get_export_check():
|
||||
from .. import report # 插件内互引,延迟导入避免环
|
||||
config.set_progress_range(80, 20)
|
||||
config.log('---- 推送完成,开始导出核对 ----', 'INFO')
|
||||
export_result = report.run_export()
|
||||
result['summary'] += ';' + export_result['summary']
|
||||
result['detail'] = {'推送': result['detail'], '导出核对': export_result['detail']}
|
||||
result['path'] = [result['path'], export_result['path']]
|
||||
config.set_progress_range(0, 100)
|
||||
return result
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0038",
|
||||
"name": "定性评价推送",
|
||||
"version": "1.1.1",
|
||||
"description": "定性评价(绩效定性考评)批量推送:读取《定性评价导入明细.xlsx》加工辅助表,按定性发起标记+部门负责人分组,在 OA 蓝凌 EKP 批量创建绩效评价发起单;默认仅暂存草稿,开启真实发送后发起流程(含子流程启动、通知复核人),发完可自动导出当天定性评价单并核对当前处理人(异常标记)。",
|
||||
"category": "人事绩效",
|
||||
"icon": "",
|
||||
"platform": "oa",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0038"],
|
||||
"permissions": {
|
||||
"platforms": ["oa"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data_file": {
|
||||
"type": "string",
|
||||
"title": "数据文件",
|
||||
"default": "D:\\资料\\人资\\定性评价推送\\定性评价导入明细.xlsx",
|
||||
"description": "加工辅助表所在 xlsx"
|
||||
},
|
||||
"send_mode": {
|
||||
"type": "boolean",
|
||||
"title": "真实发送",
|
||||
"default": false,
|
||||
"description": "关=仅暂存草稿(不发起流程、零通知);开=真实发起流程并通知复核人(不可逆)"
|
||||
},
|
||||
"test_mode": {
|
||||
"type": "boolean",
|
||||
"title": "测试模式",
|
||||
"default": true,
|
||||
"description": "开=明细「评价说明」末尾附加【测试】标志,便于负责人识别"
|
||||
},
|
||||
"export_check": {
|
||||
"type": "boolean",
|
||||
"title": "推送后导出核对",
|
||||
"default": true,
|
||||
"description": "真实发送完成后自动导出当天定性评价单并核对当前处理人(仅真实发送时生效;暂存草稿无单据可核对)"
|
||||
},
|
||||
"export_date": {
|
||||
"type": "string",
|
||||
"title": "导出日期",
|
||||
"default": "",
|
||||
"description": "导出核对的单据创建时间条件(YYYY-MM-DD);空=运行当天"
|
||||
},
|
||||
"out_dir": {
|
||||
"type": "string",
|
||||
"title": "导出输出目录",
|
||||
"default": "",
|
||||
"description": "导出核对输出目录(含 xls 与核对 xlsx);空=数据文件同目录"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送 插件 - 报告层:导出当天定性评价单并核对当前处理人。
|
||||
|
||||
导出按门户查询方案(管理/专业序列,searchId 固化),以 创建时间=EXPORT_DATE(空=当天)
|
||||
为条件,走 search.do 结构化导出接口;导出后按「当前处理人」含登录账号姓名的行判为
|
||||
「异常」,生成 *_核对.xlsx(末列「异常标记」)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from .. import config
|
||||
from ..data import export_plan_once, get_login_user
|
||||
|
||||
|
||||
def audit_xls(path, user_name):
|
||||
"""核对导出 xls:「当前处理人」含登录账号姓名 -> 异常,生成 *_核对.xlsx。
|
||||
|
||||
返回异常行数(user_name 为空时跳过核对返回 -1)。
|
||||
导出表只有姓名文本、无处理人工号列(字段字典无此字段),故按姓名匹配。
|
||||
"""
|
||||
import openpyxl
|
||||
import xlrd
|
||||
wb = xlrd.open_workbook(path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
head = [str(sh.cell_value(0, c)) for c in range(sh.ncols)]
|
||||
if '当前处理人' not in head:
|
||||
config.log(' 核对跳过:导出表无「当前处理人」列')
|
||||
return -1
|
||||
proc_idx = head.index('当前处理人')
|
||||
key_idx = {n: (head.index(n) if n in head else -1)
|
||||
for n in ('员工工号', '被评价人', '当前环节')}
|
||||
rows_out, bad = [], []
|
||||
for r in range(sh.nrows):
|
||||
vals = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if isinstance(v, float) and '时间' in head[c]:
|
||||
try:
|
||||
v = xlrd.xldate.xldate_as_datetime(v, wb.datemode).strftime(
|
||||
'%Y-%m-%d %H:%M')
|
||||
except Exception:
|
||||
pass
|
||||
vals.append('' if v is None else str(v))
|
||||
if r == 0:
|
||||
vals.append('异常标记')
|
||||
else:
|
||||
handlers = [x.strip() for x in re.split(r'[;;,,]', vals[proc_idx])
|
||||
if x.strip()]
|
||||
mark = '异常:当前处理人含登录账号' if user_name and user_name in handlers else ''
|
||||
if mark:
|
||||
bad.append(vals)
|
||||
vals.append(mark)
|
||||
rows_out.append(vals)
|
||||
out_path = re.sub(r'\.xls$', '_核对.xlsx', path)
|
||||
owb = openpyxl.Workbook()
|
||||
osh = owb.active
|
||||
osh.title = '核对结果'
|
||||
for vals in rows_out:
|
||||
osh.append(vals)
|
||||
owb.save(out_path)
|
||||
config.log(' sheet=%s 行=%d(含表头) 列=%d -> %s'
|
||||
% (sh.name, sh.nrows, sh.ncols, os.path.basename(out_path)))
|
||||
config.log(' 异常 %d 行(当前处理人=%s)' % (len(bad), user_name or '未知,未核对'))
|
||||
for vals in bad[:20]:
|
||||
config.log(' %s | %s | %s | 处理人=%s' % (
|
||||
vals[key_idx['员工工号']], vals[key_idx['被评价人']],
|
||||
vals[key_idx['当前环节']], vals[proc_idx]))
|
||||
return len(bad)
|
||||
|
||||
|
||||
def run_export():
|
||||
"""导出编排:逐方案导出 + 核对。返回 {summary, detail, path}。"""
|
||||
day = config.get_export_date() or time.strftime('%Y-%m-%d')
|
||||
out_dir = config.export_output_dir()
|
||||
s = config.get_oa_session()
|
||||
config.log('导出模式:创建时间=%s,方案 %d 个' % (day, len(config.SEARCH_PLANS)))
|
||||
user_name, login_no = get_login_user(s)
|
||||
if user_name:
|
||||
config.log('登录账号:%s(%s),将核对当前处理人' % (user_name, login_no))
|
||||
else:
|
||||
config.log('警告:未取得门户登录账号,跳过当前处理人核对')
|
||||
fail = []
|
||||
detail = {}
|
||||
for idx, (name, sid) in enumerate(config.SEARCH_PLANS.items()):
|
||||
config.progress(int(100 * idx / len(config.SEARCH_PLANS)))
|
||||
label = name.split('(')[0]
|
||||
out_path = os.path.join(out_dir, '定性评价结果_%s_%s.xls'
|
||||
% (label, day.replace('-', '')))
|
||||
last_err = ''
|
||||
for attempt in range(1, config.MAX_RETRY + 1):
|
||||
try:
|
||||
total, err = export_plan_once(s, sid, day, out_path)
|
||||
except Exception:
|
||||
total, err = None, '异常: ' + traceback.format_exc(limit=1).replace('\n', ' ')
|
||||
if not err:
|
||||
config.log('%s -> %d 条 -> %s' % (name, total, out_path))
|
||||
bad = 0
|
||||
if total:
|
||||
bad = audit_xls(out_path, user_name)
|
||||
detail[label] = {'total': total, 'path': out_path,
|
||||
'audit': bad if total else 0}
|
||||
break
|
||||
last_err = err
|
||||
config.log('%s -> 第%d次失败:%s' % (name, attempt, err))
|
||||
time.sleep(1)
|
||||
else:
|
||||
fail.append((name, last_err))
|
||||
detail[label] = {'success': False, 'error': last_err}
|
||||
config.progress(int(100 * (idx + 1) / len(config.SEARCH_PLANS)))
|
||||
config.progress(100)
|
||||
config.log('==== 导出完成:成功 %d / 失败 %d ====' % (len(config.SEARCH_PLANS) - len(fail),
|
||||
len(fail)))
|
||||
for name, err in fail:
|
||||
config.log('失败 %s:%s' % (name, err))
|
||||
summary = '定性评价导出核对完成:成功 %d 个方案 / 失败 %d 个%s' % (
|
||||
len(config.SEARCH_PLANS) - len(fail), len(fail),
|
||||
'(%s)' % '、'.join(f[0] for f in fail) if fail else '')
|
||||
return {'summary': summary, 'detail': detail, 'path': out_dir}
|
||||
@@ -0,0 +1,3 @@
|
||||
requests
|
||||
openpyxl
|
||||
xlrd
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>定性评价推送</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1585
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0038-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
<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>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<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="m22 2-7 20-4-9-9-4Z" />
|
||||
<path d="M22 2 11 13" />
|
||||
</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>
|
||||
|
||||
<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>
|
||||
<div class="grid">
|
||||
<el-form-item label="数据文件">
|
||||
<el-input v-model="form.data_file" :disabled="running" clearable
|
||||
placeholder="加工辅助表所在 xlsx,按 定性发起标记+部门负责人 分组推送" />
|
||||
</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>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="真实发送">
|
||||
<el-switch v-model="form.send_mode" :disabled="running"
|
||||
active-text="真实发起" inactive-text="仅暂存草稿" />
|
||||
</el-form-item>
|
||||
<el-form-item label="测试模式">
|
||||
<el-switch v-model="form.test_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item v-if="form.send_mode" label="推送后导出核对">
|
||||
<el-switch v-model="form.export_check" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">「真实发送」关闭时仅暂存草稿,不发起流程、零通知,草稿可在 OA 待办中人工确认后再提交;开启后执行即真实发起流程(含子流程启动、通知复核人),不可逆,请谨慎操作。「测试模式」在明细「评价说明」末尾附加【测试】标志,便于负责人识别。「推送后导出核对」仅真实发送时可选:发完自动导出当天定性评价单并核对当前处理人(当前处理人=登录账号的单据标记异常)</div>
|
||||
</section>
|
||||
|
||||
<!-- 导出核对设置(仅真实发送且勾选核对时展示) -->
|
||||
<section v-if="form.send_mode && form.export_check" 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">
|
||||
<el-form-item label="导出日期">
|
||||
<el-date-picker v-model="form.export_date" type="date" value-format="YYYY-MM-DD"
|
||||
placeholder="留空=运行当天" :disabled="running" clearable class="wide" />
|
||||
<div class="tip">导出核对的单据创建时间条件</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="导出输出目录">
|
||||
<el-input v-model="form.out_dir" :disabled="running" clearable
|
||||
placeholder="留空 = 数据文件同目录(输出 xls 与核对 xlsx)" />
|
||||
</el-form-item>
|
||||
</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>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
data_file: 'D:\\资料\\人资\\定性评价推送\\定性评价导入明细.xlsx',
|
||||
send_mode: false,
|
||||
test_mode: true,
|
||||
export_check: true,
|
||||
export_date: '',
|
||||
out_dir: '',
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.data_file.trim()) { ElMessage.warning('请填写数据文件路径'); return false }
|
||||
if (form.export_date && !/^\d{4}-\d{2}-\d{2}$/.test(form.export_date)) {
|
||||
ElMessage.warning('导出日期格式应为 YYYY-MM-DD,或留空使用当天'); return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
buildPayload(form) {
|
||||
// 暂存草稿不发起流程、无可核对单据,提交参数强制关掉核对(防止定时任务引用残留勾选)
|
||||
const payload = { ...form }
|
||||
if (!payload.send_mode) payload.export_check = false
|
||||
return payload
|
||||
},
|
||||
})
|
||||
</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%;
|
||||
}
|
||||
/* 开关区:列宽压到「真实发送」开关带 active/inactive 文案所需下限 */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
|
||||
row-gap: 14px;
|
||||
}
|
||||
.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;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit,各插件 ui-src 只需声明自己的 id)
|
||||
export const PLUGIN_ID = 'xq0038'
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,327 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
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' })
|
||||
}
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 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 running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0038/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0038/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5188,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>定性评价推送</title>
|
||||
<script type="module" crossorigin src="/pui/xq0038/assets/index-D1df0DCu.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0038/assets/index-UXhZH9an.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user