feat: 新增3个EHR流程审核插件:请假、加班、离职电子签
新增XQ0003请假流程审核、XQ0004加班流程审核、XQ0020离职电子签流程审核插件 包含Python后端逻辑、Vite+Vue3前端工程、打包脚本及依赖配置 支持假期校验、加班时长核对、电子签状态核验及自动审批提交 新增rapidocr依赖及OCR附件核验逻辑
This commit is contained in:
@@ -49,6 +49,12 @@ $Pinned = @(
|
||||
"lxml==6.1.1", "psutil==7.2.2", "tldextract==5.3.2", "cssselect==1.5.0", "click==8.4.2",
|
||||
"ddddocr==1.6.1", "onnxruntime==1.28.0", "Pillow==12.3.0",
|
||||
"opencv-python-headless==5.0.0.93", "flatbuffers==25.12.19", "protobuf==7.35.1",
|
||||
# OCR(XQ0003 请假附件:病假/结婚证/产检关键词与登记日期核验)
|
||||
# rapidocr>=3 必须显式固定,连同 opencv_python/omegaconf 等运行依赖,否则
|
||||
# 走 embeddable+pip 模式时该栈不会装、插件 OCR 全面降级为人工复核。
|
||||
"rapidocr==3.9.2", "opencv-python==5.0.0.93",
|
||||
"omegaconf==2.3.1", "antlr4-python3-runtime==4.9.3", "colorlog==6.12.0",
|
||||
"pyclipper==1.4.0", "Shapely==2.1.2", "PyYAML==6.0.3", "tqdm==4.70.1",
|
||||
"pywin32==312",
|
||||
"urllib3==2.7.0", "certifi==2026.7.22", "idna==3.18",
|
||||
"charset-normalizer==3.4.9", "six==1.17.0", "packaging==26.3"
|
||||
@@ -196,6 +202,8 @@ if ($LASTEXITCODE -ne 0) { throw "core deps import failed" }
|
||||
& $PyExe -c "import DrissionPage; print(' DrissionPage', DrissionPage.__version__)" | Out-Host
|
||||
& $PyExe -c "import ddddocr; print(' ddddocr ok')" | Out-Host
|
||||
& $PyExe -c "import onnxruntime; print(' onnxruntime', onnxruntime.__version__)" | Out-Host
|
||||
& $PyExe -c "from rapidocr import RapidOCR; import rapidocr; print(' rapidocr ok')" | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "rapidocr import failed (XQ0003 附件 OCR 依赖缺失)" }
|
||||
& $PyExe -c "import win32com.client; print(' win32com ok')" | Out-Host
|
||||
Push-Location $PyDir
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 leave_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「请假」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:Group1 仅比对排班上班天数与填报天数;Group2 另需附件
|
||||
(病假/结婚证/产检 OCR,特殊事假/产假/丧假仅需附件);小时特假校验请假时段
|
||||
是否落在排班班段内(含前一天跨天夜班)+ 已上传附件;
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
|
||||
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .logic import leave_rules
|
||||
from .report import leave_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class LeaveApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统请假流程审核(需求 XQ0003)。"""
|
||||
|
||||
id = "xq0003"
|
||||
name = "EHR系统请假流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 请假待办:按假期类型校验排班上班天数与填报天数是否一致,"
|
||||
"病假/结婚证/产检按附件 OCR 关键词核验,小时特假校验请假时段是否落在排班班段内;"
|
||||
"校验通过自动提交审批,并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0003"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出 OCR 识别明细等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 请假审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取请假待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = leave_rules.validate_doc(detail, session)
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = leave_report.generate_report(results)
|
||||
report_path = leave_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送 ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = leave_report.build_push_summary(results, subject)
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
|
||||
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
|
||||
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
|
||||
if counts["abnormal"]:
|
||||
summary += f",审批异常 {counts['abnormal']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(LeaveApprovalPlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件打包脚本(统一规范版)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0003 EHR系统请假流程审核\\_pack.py"
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0003_v<版本>.zip --id xq0003 --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", "__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,203 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session()/require_user_id() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\请假流程审批"
|
||||
ATTACHMENT_DIR_NAME = "附件"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
ATTACHMENT_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
PAGE_MAX_SIZE = 500
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
DEFAULT_SUBJECT = "请假"
|
||||
|
||||
# 审批按钮:决策 -> (选择器, 按钮文案);仅「通过」会自动提交
|
||||
APPROVE_BUTTONS = {"通过": ("#chooseSubmit", "同意")}
|
||||
|
||||
# ==================== 假期类型编码 → 名称 ====================
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def get_attachment_dir():
|
||||
"""服务端附件本地保存目录:<save_dir>\\附件。"""
|
||||
return os.path.join(_save_dir, ATTACHMENT_DIR_NAME)
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 数据层。"""
|
||||
@@ -0,0 +1,356 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - HR 接口层(由影刀版 leave_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查请假流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId(待办行缺失时兜底)
|
||||
3) WorkformEngine getBusinessDate 取请假表单数据
|
||||
4) rf_p_kq_count_SelectBanci 按工号+日期范围取排班(动态列 YYYY-MM-DD_bc_name/bc_time)
|
||||
5) fjkFileDownload.mob 下载表单附件
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
from urllib.parse import unquote
|
||||
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, SHIFT_URL, ATTACHMENT_URL,
|
||||
DEFAULT_PAGE_SIZE, PAGE_MAX_SIZE, DEFAULT_TREE_CODE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 请假流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取请假表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 排班查询 ====================
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode=DEFAULT_TREE_CODE, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据(按工号 base_code 查询)。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date,
|
||||
treecode=DEFAULT_TREE_CODE):
|
||||
"""分页抓取指定工号、日期范围内的全部排班记录。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("排班接口 HR 登录态失效,请重新登录 HR 后再执行") from None
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def get_day_shift(shift_rows, date_str):
|
||||
"""从排班记录中提取指定日期的班次信息(动态列 YYYY-MM-DD_bc_name/bc_time)。"""
|
||||
info = {"bc_name": "", "bc_time": ""}
|
||||
for rec in shift_rows:
|
||||
name = rec.get(f"{date_str}_bc_name")
|
||||
time_ = rec.get(f"{date_str}_bc_time")
|
||||
if name or time_:
|
||||
info = {
|
||||
"bc_name": str(name if name is not None else ""),
|
||||
"bc_time": str(time_ if time_ is not None else ""),
|
||||
}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
# ==================== 附件下载 ====================
|
||||
def download_attachment(session, file_id, save_dir):
|
||||
"""按附件 fileId 下载(兼容逗号分隔多附件),返回逗号拼接路径串;全失败返回 None。"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(session, file_id, save_dir):
|
||||
"""下载单个附件 fileId,返回本地保存路径;失败返回 None。"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
download_url = f"{ATTACHMENT_URL}?fileId={file_id}"
|
||||
try:
|
||||
resp = session.get(download_url, timeout=60)
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
return None
|
||||
if resp is None or resp.status_code != 200:
|
||||
logger.warning("附件下载失败: HTTP %s (fileId=%s)",
|
||||
getattr(resp, "status_code", "?"), file_id)
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
else:
|
||||
try:
|
||||
raw = raw.encode('latin-1').decode('utf-8')
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
pass
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 业务规则层。"""
|
||||
@@ -0,0 +1,375 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 请假校验规则(由影刀版移植)。
|
||||
|
||||
校验分组:
|
||||
Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过
|
||||
Group 2(病假/产假等):天数一致 + 附件(OCR/仅附件)-> 通过
|
||||
小时特假:请假时段须完整落在排班班段内(含前一天跨天夜班)+ 已上传附件
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from ..config import logger, require_session, require_user_id, get_attachment_dir, VACATION_TYPE_MAP
|
||||
from ..data.hr_api import fetch_all_shift, get_day_shift, download_attachment
|
||||
from .ocr import check_leave_attachment, check_leave_attachment_detail, marriage_within_one_year
|
||||
|
||||
# 按小时请假的假期类型:不比对天数,按请假时段判断是否落在排班班段内
|
||||
HOURLY_LEAVE_TYPES = {
|
||||
"小时特假",
|
||||
}
|
||||
|
||||
# Group 1:仅校验排班上班天数与填报天数一致
|
||||
LEAVE_TYPE_GROUP_1 = {
|
||||
"事假", "调休假", "半天休(仅限人资专用)",
|
||||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||||
"年度福利假",
|
||||
}
|
||||
|
||||
# Group 2:校验天数一致 + 需上传附件
|
||||
LEAVE_TYPE_GROUP_2 = {
|
||||
"病假", "特别福利假", "特殊事假", "产假",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 表单解析 ====================
|
||||
def _first_non_null(result, *keys):
|
||||
"""返回第一个值非 None 的字段(不能用 or 链:0 / 0.0 / "" 是合法值但为 falsy)。"""
|
||||
for k in keys:
|
||||
v = result.get(k)
|
||||
if v is not None:
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_vacation_type(result):
|
||||
raw = _first_non_null(result, "vacation_type", "leave_type", "sub_type")
|
||||
raw = str(raw).strip() if raw is not None else ""
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def parse_leave_form(result):
|
||||
"""把 WorkformEngine 表单数据解析为统一的中文键字典。"""
|
||||
return {
|
||||
"请假人员ID": result.get("staff_id"),
|
||||
"工号": result.get("staff_code"),
|
||||
"请假人员": result.get("staff_name"),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"假期类型": _resolve_vacation_type(result),
|
||||
# 开始日期优先 start_date(跨天/夜班场景 begin_date 可能取成申请日导致起止倒挂)
|
||||
"开始日期": result.get("start_date") or result.get("begin_date"),
|
||||
"开始时间": result.get("start_time"),
|
||||
"开始段": result.get("begin_other_name"),
|
||||
"结束日期": result.get("end_date"),
|
||||
"结束时间": result.get("end_time"),
|
||||
"结束段": result.get("end_other_name"),
|
||||
"请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"),
|
||||
"请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"),
|
||||
"请假原因": result.get("leave_reason"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def _get_hr_context():
|
||||
"""取注入的 HR 会话与 userId(失败抛错提示重新登录)。"""
|
||||
return require_session(), require_user_id()
|
||||
|
||||
|
||||
# ==================== 天数校验 ====================
|
||||
def _get_date_range(begin_date, end_date):
|
||||
start_date = begin_date[:10] if begin_date else None
|
||||
end_date = end_date[:10] if end_date else None
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
def _get_work_days_count(start_date, end_date, staff_code):
|
||||
"""获取请假区间内实际上班天数(休息与否只以 bc_name 为准)。"""
|
||||
session, user_id = _get_hr_context()
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
if not rows:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
info = get_day_shift(rows, day)
|
||||
bc_name = info["bc_name"]
|
||||
if bc_name and not bc_name.startswith("休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
# ==================== 小时假校验 ====================
|
||||
def _parse_leave_time(value):
|
||||
"""解析 "YYYY-MM-DD HH:MM[:SS]" -> (date, 当日分钟数);解析失败返回 None。"""
|
||||
if not value:
|
||||
return None
|
||||
m = re.search(r"(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2})", str(value))
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
day = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return day, int(m.group(4)) * 60 + int(m.group(5))
|
||||
|
||||
|
||||
def _shift_min_range(bc_time):
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);跨天夜班 end<start。"""
|
||||
if not bc_time:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2)), int(m.group(3)) * 60 + int(m.group(4))
|
||||
|
||||
|
||||
def _fmt_min(m):
|
||||
return f"{m // 60:02d}:{m % 60:02d}"
|
||||
|
||||
|
||||
def _hourly_leave_within_shift(shift_rows, leave_date, leave_end_date, start_min, end_min):
|
||||
"""判断小时假请假时段是否完整落在某天排班班段内(含前一天跨天夜班)。
|
||||
|
||||
返回 (是否通过, 命中班段日期, 命中bc_time)。
|
||||
"""
|
||||
end_abs = end_min + (leave_end_date - leave_date).days * 1440
|
||||
if end_abs < start_min:
|
||||
end_abs += 1440 # 请假自身跨天兜底
|
||||
for delta in (0, -1):
|
||||
day = (leave_date + timedelta(days=delta)).strftime("%Y-%m-%d")
|
||||
info = get_day_shift(shift_rows, day)
|
||||
r = _shift_min_range(info["bc_time"])
|
||||
if r is None:
|
||||
continue
|
||||
s, e = r
|
||||
base = delta * 1440
|
||||
if s == 0 and e == 0:
|
||||
iv = (base, base + 1440) # 全天班(罕见)
|
||||
elif e < s:
|
||||
iv = (base + s, base + e + 1440) # 跨天夜班
|
||||
else:
|
||||
iv = (base + s, base + e) # 当日班段
|
||||
if iv[0] <= start_min and end_abs <= iv[1]:
|
||||
return True, day, info["bc_time"]
|
||||
return False, None, None
|
||||
|
||||
|
||||
def _validate_hourly_leave(result, session, leave_info, staff_code, attachment, vacation_type):
|
||||
"""小时特假校验:请假时段完整落在排班班段内(含前一天跨天夜班)+ 已上传附件。"""
|
||||
leave_hours = leave_info.get("请假小时")
|
||||
leave_start = _parse_leave_time(leave_info.get("开始时间"))
|
||||
leave_end = _parse_leave_time(leave_info.get("结束时间"))
|
||||
|
||||
if leave_start is None:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法解析请假开始时间"
|
||||
return result
|
||||
if leave_end is None:
|
||||
leave_end = leave_start
|
||||
|
||||
try:
|
||||
hr_session, user_id = _get_hr_context()
|
||||
query_start = (leave_start[0] - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
query_end = leave_end[0].strftime("%Y-%m-%d")
|
||||
shift_rows = fetch_all_shift(hr_session, user_id, staff_code, query_start, query_end)
|
||||
except Exception as e:
|
||||
logger.warning("小时假获取排班数据失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
ok, hit_day, hit_bc = _hourly_leave_within_shift(
|
||||
shift_rows, leave_start[0], leave_end[0], leave_start[1], leave_end[1])
|
||||
|
||||
if not ok:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = (
|
||||
f"请假时段 {_fmt_min(leave_start[1])}~{_fmt_min(leave_end[1])} "
|
||||
f"未落在请假当天({query_end})或前一天({query_start})的排班班段内"
|
||||
)
|
||||
return result
|
||||
|
||||
if not attachment:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "未上传附件"
|
||||
return result
|
||||
|
||||
result["decision"] = "通过"
|
||||
result["附件路径"] = download_attachment(session, attachment, get_attachment_dir())
|
||||
result["leave_info"]["排班班段"] = f"{hit_day} {hit_bc}"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||||
f"请假时段 {_fmt_min(leave_start[1])}~{_fmt_min(leave_end[1])} 落在排班班段 "
|
||||
f"{hit_day} {hit_bc} 内,附件已上传)"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 附件校验 ====================
|
||||
def _verify_attachment(session, vacation_type, reason, file_id):
|
||||
"""按假期类型校验附件内容,返回 (decision, note, attachment_path)。"""
|
||||
path = download_attachment(session, file_id, get_attachment_dir())
|
||||
if not path:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
paths = [p for p in path.split(",") if p]
|
||||
if not paths:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
logger.info("附件校验开始: vacation_type=%s, 附件数=%d, 路径=%s", vacation_type, len(paths), paths)
|
||||
|
||||
def _first_hit(checker):
|
||||
return next((p for p in paths if checker(p)), None)
|
||||
|
||||
def _kw_hint(p, leave_type):
|
||||
"""返回该附件 OCR 命中的关键词列表(顿号拼接),用于备注便于人工判断。"""
|
||||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||||
return "、".join(hits) if hits else ""
|
||||
|
||||
if vacation_type == "病假":
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||||
|
||||
if vacation_type == "特别福利假":
|
||||
reason = reason or ""
|
||||
if "婚" in reason:
|
||||
hit = None
|
||||
reg_kw = ""
|
||||
for p in paths:
|
||||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||||
if ok:
|
||||
hit = p
|
||||
reg_kw = "、".join(hits)
|
||||
break
|
||||
if hit is None:
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||||
ok, reg_date = marriage_within_one_year(hit)
|
||||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||||
if ok:
|
||||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||||
if "产" in reason or "孕" in reason:
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||||
if "丧" in reason:
|
||||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||||
|
||||
# 特殊事假 / 产假:有附件即通过
|
||||
return "通过", f"附件已上传({len(paths)}份)", path
|
||||
|
||||
|
||||
# ==================== 单据校验入口 ====================
|
||||
def validate_doc(doc, session):
|
||||
"""校验单张请假单据,返回审批决策字典。"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
leave_info = parse_leave_form(form_data)
|
||||
|
||||
staff_id = leave_info.get("请假人员ID")
|
||||
staff_code = leave_info.get("工号")
|
||||
vacation_type = leave_info.get("假期类型")
|
||||
begin_date = leave_info.get("开始日期")
|
||||
end_date = leave_info.get("结束日期")
|
||||
leave_days = leave_info.get("请假天数")
|
||||
attachment = leave_info.get("附件")
|
||||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||||
|
||||
result = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "通过",
|
||||
"note": "",
|
||||
"leave_info": leave_info,
|
||||
}
|
||||
|
||||
if not vacation_type:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法识别假期类型"
|
||||
return result
|
||||
|
||||
if not staff_id:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人员ID缺失"
|
||||
return result
|
||||
|
||||
if not staff_code:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人工号缺失"
|
||||
return result
|
||||
|
||||
# 小时假(如小时特假)不走天数比对,提前按请假时段校验排班班段
|
||||
if is_hourly:
|
||||
return _validate_hourly_leave(result, session, leave_info, staff_code, attachment, vacation_type)
|
||||
|
||||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||||
if not start_date or not end_date:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假起止日期缺失"
|
||||
return result
|
||||
|
||||
try:
|
||||
actual_work_days = _get_work_days_count(start_date, end_date, staff_code)
|
||||
except Exception as e:
|
||||
logger.warning("计算上班天数失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
try:
|
||||
fill_days = float(leave_days) if leave_days else 0
|
||||
except (TypeError, ValueError):
|
||||
fill_days = 0
|
||||
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
if vacation_type in LEAVE_TYPE_GROUP_1:
|
||||
if days_mismatch:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||||
f"填报天数: {fill_days})"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_2:
|
||||
# 需附件的假期:天数一致 + 附件内容校验(OCR/仅附件);无法确认 -> 人工复核
|
||||
reasons = []
|
||||
if days_mismatch:
|
||||
reasons.append(f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致")
|
||||
if not attachment:
|
||||
reasons.append("未上传附件")
|
||||
|
||||
if reasons:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = ";".join(reasons)
|
||||
else:
|
||||
result["decision"], result["note"], result["附件路径"] = _verify_attachment(
|
||||
session, vacation_type, leave_info.get("请假原因"), attachment
|
||||
)
|
||||
else:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,265 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 附件 OCR 校验(可选依赖,懒初始化)。
|
||||
|
||||
行为与影刀版一致:病假/婚假/产检假按关键词命中检测,结婚证按登记日期判断 1 年内。
|
||||
插件化差异:rapidocr/onnxruntime 属可选依赖,首次使用时才初始化引擎;
|
||||
缺库或初始化失败时优雅降级(返回 False / 空),由上层转为「人工复核」,不崩溃。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger, is_debug
|
||||
|
||||
_OCR_LEAVE_KEYWORDS = {
|
||||
# 病假/医疗类:对应医院诊断证明、病历、检验单等
|
||||
"sick": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
},
|
||||
# 婚假类:对应结婚证、婚姻登记证明
|
||||
"marriage": {
|
||||
"结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关",
|
||||
"婚姻证", "中华人民共和国结婚证",
|
||||
},
|
||||
# 产检假类:对应产检报告、B超单、妊娠诊断证明
|
||||
"maternity": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
"产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期",
|
||||
"超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心",
|
||||
},
|
||||
}
|
||||
_OCR_CONFIDENCE_THRESHOLD = 0.5
|
||||
_OCR_VALID_TYPES = set(_OCR_LEAVE_KEYWORDS.keys()) | {"all"}
|
||||
|
||||
_ocr_engine = None # 已初始化的引擎
|
||||
_ocr_init_failed = False # 初始化失败标记:避免每张附件重复尝试导入/初始化
|
||||
_ocr_legacy = False # True = rapidocr_onnxruntime(返回 (结果列表, 耗时) 元组)
|
||||
|
||||
|
||||
def ocr_available():
|
||||
"""OCR 是否可用(可触发懒初始化)。"""
|
||||
return _ensure_engine() is not None
|
||||
|
||||
|
||||
def _ensure_engine():
|
||||
"""懒初始化 OCR 引擎;缺库或失败返回 None(上层降级为人工复核)。
|
||||
|
||||
优先 rapidocr(>=3.x,影刀版同款,结果对象带 boxes/txts/scores),
|
||||
其次 rapidocr_onnxruntime(老包,返回 (结果列表, 耗时) 元组)。
|
||||
"""
|
||||
global _ocr_engine, _ocr_init_failed, _ocr_legacy
|
||||
if _ocr_engine is not None:
|
||||
return _ocr_engine
|
||||
if _ocr_init_failed:
|
||||
return None
|
||||
try:
|
||||
from rapidocr import RapidOCR
|
||||
_ocr_engine = RapidOCR()
|
||||
_ocr_legacy = False
|
||||
logger.info("OCR 引擎初始化成功(rapidocr)")
|
||||
return _ocr_engine
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
_ocr_engine = RapidOCR()
|
||||
_ocr_legacy = True
|
||||
logger.info("OCR 引擎初始化成功(rapidocr_onnxruntime)")
|
||||
except Exception as e:
|
||||
_ocr_init_failed = True
|
||||
_ocr_engine = None
|
||||
logger.warning("OCR 引擎不可用(附件转人工复核): %s", e)
|
||||
return _ocr_engine
|
||||
|
||||
|
||||
def _ocr_read_text(file_path, debug=False):
|
||||
"""OCR 识别图片,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
engine = _ensure_engine()
|
||||
if engine is None:
|
||||
logger.warning("OCR 引擎未初始化,跳过识别: %s", file_path)
|
||||
raise RuntimeError("OCR 引擎未初始化(rapidocr 缺失或初始化失败)")
|
||||
if not os.path.isfile(file_path):
|
||||
logger.warning("OCR 附件文件不存在,跳过识别: %s", file_path)
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
|
||||
with Image.open(file_path) as img:
|
||||
# 应用 EXIF 方向信息,修正手机横拍导致的旋转
|
||||
img = ImageOps.exif_transpose(img)
|
||||
gray_img = img.convert("L")
|
||||
enhancer = ImageEnhance.Contrast(gray_img)
|
||||
enhanced_img = enhancer.enhance(2.0)
|
||||
img_array = np.array(enhanced_img)
|
||||
|
||||
result = engine(img_array)
|
||||
if _ocr_legacy or isinstance(result, tuple):
|
||||
# rapidocr_onnxruntime: ([ [box, text, score], ... ], 耗时)
|
||||
res_list = result[0] if isinstance(result, tuple) else result
|
||||
txts, scores = [], []
|
||||
for item in (res_list or []):
|
||||
try:
|
||||
txts.append(str(item[1]))
|
||||
scores.append(float(item[2]))
|
||||
except (IndexError, TypeError, ValueError):
|
||||
continue
|
||||
else:
|
||||
txts = getattr(result, "txts", None)
|
||||
scores = getattr(result, "scores", None)
|
||||
if txts is None:
|
||||
txts = ()
|
||||
if scores is None:
|
||||
scores = ()
|
||||
|
||||
logger.info("【OCR识别结果】文件: %s, 识别到 %d 个文本块", os.path.basename(file_path), len(txts))
|
||||
if debug or is_debug():
|
||||
for idx, (txt, score) in enumerate(zip(txts, scores)):
|
||||
logger.info(" [%02d] 置信度:%.3f | 文本: %s", idx, score, txt)
|
||||
|
||||
raw_text = ""
|
||||
full_text = ""
|
||||
for text, score in zip(txts, scores):
|
||||
if score < _OCR_CONFIDENCE_THRESHOLD:
|
||||
continue
|
||||
raw_text += text
|
||||
full_text += text.replace(" ", "").replace("\u3000", "")
|
||||
|
||||
# 过滤乱码特殊符号,保留常用字符
|
||||
clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]')
|
||||
full_text = clean_pattern.sub('', full_text)
|
||||
return full_text, raw_text
|
||||
|
||||
|
||||
def _target_keywords(leave_type):
|
||||
if leave_type == "all":
|
||||
target = set()
|
||||
for kw_set in _OCR_LEAVE_KEYWORDS.values():
|
||||
target.update(kw_set)
|
||||
return target
|
||||
return _OCR_LEAVE_KEYWORDS[leave_type]
|
||||
|
||||
|
||||
def check_leave_attachment(file_path, leave_type="sick", debug=False):
|
||||
"""检测附件图片是否包含对应假期关键词;文件异常/识别失败/未命中均返回 False。"""
|
||||
if leave_type not in _OCR_VALID_TYPES:
|
||||
return False
|
||||
if not os.path.isfile(file_path):
|
||||
return False
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,附件转人工复核: %s", file_path)
|
||||
return False
|
||||
|
||||
try:
|
||||
full_text, _ = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
|
||||
return False
|
||||
|
||||
if debug:
|
||||
logger.info("【清洗后匹配文本】\n%s\n%s", full_text, "=" * 60)
|
||||
|
||||
hit_words = [kw for kw in _target_keywords(leave_type) if kw in full_text]
|
||||
if debug:
|
||||
logger.info("【命中关键词】: %s", hit_words)
|
||||
return len(hit_words) > 0
|
||||
|
||||
|
||||
def check_leave_attachment_detail(file_path, leave_type="sick", debug=False):
|
||||
"""检测附件是否命中关键词,返回 (是否命中, 命中关键词列表, OCR全文)。"""
|
||||
if leave_type not in _OCR_VALID_TYPES:
|
||||
return False, [], ""
|
||||
if not os.path.isfile(file_path):
|
||||
return False, [], ""
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,附件转人工复核: %s", file_path)
|
||||
return False, [], ""
|
||||
|
||||
try:
|
||||
full_text, raw_text = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
|
||||
return False, [], ""
|
||||
|
||||
hit_words = [kw for kw in _target_keywords(leave_type) if kw in full_text]
|
||||
logger.info("【OCR关键词匹配】假期类型: %s, 命中: %s", leave_type, hit_words if hit_words else "无")
|
||||
return len(hit_words) > 0, hit_words, raw_text
|
||||
|
||||
|
||||
def _ocr_extract_dates(text):
|
||||
"""从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。"""
|
||||
dates = []
|
||||
patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in patterns:
|
||||
for m in re.finditer(pat, text):
|
||||
try:
|
||||
dates.append(datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date())
|
||||
except ValueError:
|
||||
continue
|
||||
return dates
|
||||
|
||||
|
||||
def _ocr_extract_registration_date(text):
|
||||
"""从结婚证文本中提取"登记日期"字段对应的日期;找不到返回 None。"""
|
||||
reg_match = re.search(r'登记日期', text)
|
||||
if not reg_match:
|
||||
return None
|
||||
|
||||
text_after = text[reg_match.end():]
|
||||
date_patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in date_patterns:
|
||||
m = re.search(pat, text_after)
|
||||
if m:
|
||||
try:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def marriage_within_one_year(file_path, today=None, debug=False):
|
||||
"""识别结婚证登记日期并判断是否在当前日期 1 年内。
|
||||
|
||||
优先查找"登记日期"关键词附近的日期,找不到则取识别到的最大日期兜底。
|
||||
返回 (是否1年内, 登记日期)。
|
||||
"""
|
||||
if today is None:
|
||||
today = datetime.now().date()
|
||||
if not os.path.isfile(file_path):
|
||||
return False, None
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,结婚证登记日期转人工复核: %s", file_path)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
full_text, _ = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
if debug:
|
||||
logger.warning("[识别异常] %s", e)
|
||||
return False, None
|
||||
|
||||
dates = _ocr_extract_dates(full_text)
|
||||
if not dates:
|
||||
if debug:
|
||||
logger.info("【未识别到任何日期】")
|
||||
return False, None
|
||||
|
||||
reg_date = _ocr_extract_registration_date(full_text)
|
||||
if reg_date is None:
|
||||
reg_date = max(dates)
|
||||
if debug:
|
||||
logger.info("【未找到登记日期关键词,使用最大日期兜底】")
|
||||
|
||||
ok = reg_date <= today and (today - reg_date).days <= 365
|
||||
if debug:
|
||||
logger.info("【识别日期】: %s", dates)
|
||||
logger.info("【登记日期】: %s,1年内: %s", reg_date, ok)
|
||||
return ok, reg_date
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0003",
|
||||
"name": "EHR系统请假流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 请假待办:拉取待办与请假表单,按假期类型校验排班上班天数与填报天数是否一致,病假/产假等按附件 OCR 关键词核验(病假/结婚证/产检),小时特假校验请假时段是否落在排班班段内;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0003"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\请假流程审批",
|
||||
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出 OCR 识别明细等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 报告与推送层。"""
|
||||
@@ -0,0 +1,230 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 钉钉群机器人推送(自 XQ0034 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,205 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("请假人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _vtype(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始日期", "开始日期"),
|
||||
("开始段", "开始段"),
|
||||
("结束日期", "结束日期"),
|
||||
("结束段", "结束段"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("排班班段", "排班班段"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+异常/失败)。"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"请假审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
if rejected:
|
||||
lines.append("《请假审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
path = r.get("附件路径") or "下载失败"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}")
|
||||
lines.append("")
|
||||
|
||||
if abnormal:
|
||||
lines.append("《请假审批异常待人工确认清单》")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 原因: {r.get('note') or r.get('error') or ''} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_leave_block(r):
|
||||
"""将单条请假审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
name = info.get("请假人员") or r.get("creator") or "未知"
|
||||
vtype = info.get("假期类型") or ""
|
||||
lines = [f"**🔹 {name}‑{vtype}**"]
|
||||
label_map = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
]
|
||||
for key, label in label_map:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
start = info.get("开始日期")
|
||||
start_seg = info.get("开始段")
|
||||
if start:
|
||||
if start_seg:
|
||||
lines.append(f"> 开始日期:{start}|开始段:{start_seg}")
|
||||
else:
|
||||
lines.append(f"> 开始日期:{start}")
|
||||
end = info.get("结束日期")
|
||||
end_seg = info.get("结束段")
|
||||
if end:
|
||||
if end_seg:
|
||||
lines.append(f"> 结束日期:{end}|结束段:{end_seg}")
|
||||
else:
|
||||
lines.append(f"> 结束日期:{end}")
|
||||
for key, label in [("请假天数", "请假天数"), ("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"), ("填报天数", "填报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行分隔才会换行
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""按结果类型生成块格式 Markdown 推送分组(通过的单据仅计数,不逐条推送)。"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not rejected and not review and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_leave_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("校验不通过未处理", len(rejected)),
|
||||
("需人工复核", len(review)),
|
||||
("审批异常", len(abnormal)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/请假审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"请假审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,6 @@
|
||||
requests
|
||||
DrissionPage
|
||||
rapidocr
|
||||
onnxruntime
|
||||
Pillow
|
||||
numpy
|
||||
@@ -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>EHR系统请假流程审核</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0003-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,475 @@
|
||||
<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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<path d="M14 2v6h6" />
|
||||
<path d="m9 15 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>
|
||||
|
||||
<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.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\人资\请假流程审批(报告与附件统一存放)" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">审批报告保存为「请假审批报告_时间戳.txt」,服务端附件下载到其下「附件」子目录。</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">
|
||||
<el-form-item label="自动提交审批">
|
||||
<el-switch v-model="form.approve_enabled" :disabled="running"
|
||||
active-text="校验通过自动点同意" inactive-text="仅校验不提交" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉群推送">
|
||||
<el-switch v-model="form.push_enabled" :disabled="running"
|
||||
active-text="推送汇总与待人工明细" inactive-text="不推送" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉 Webhook">
|
||||
<el-input v-model="form.dingtalk_webhook" :disabled="running || !form.push_enabled" clearable
|
||||
placeholder="留空 = 内置默认机器人;发其他群时填完整地址" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉加签密钥">
|
||||
<el-input v-model="form.dingtalk_secret" :disabled="running || !form.push_enabled" clearable
|
||||
placeholder="留空 = 不加签" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running"
|
||||
active-text="输出 OCR 识别明细等调试信息" inactive-text="关闭" />
|
||||
</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="checks static">
|
||||
<div v-for="c in RULES" :key="c.num" class="check-tile">
|
||||
<span class="tile-num">{{ c.num }}</span>
|
||||
<span class="tile-label">{{ c.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tip">仅「通过」的单据会自动提交审批;校验不通过、人工复核、审批提交失败的单据均保留待办,并写入报告与钉钉推送,由人工跟进。</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'
|
||||
|
||||
// 校验规则(与后端 logic/leave_rules.py 分组一一对应,仅展示说明)
|
||||
const RULES = [
|
||||
{ num: '1', label: 'Group1(事假/调休假/普通事假/年度福利假等):排班上班天数与填报天数一致' },
|
||||
{ num: '2', label: 'Group2(病假/特别福利假/特殊事假/产假):天数一致 + 必须上传附件(病假/结婚证/产检做 OCR 关键词核验)' },
|
||||
{ num: '3', label: '小时特假:请假时段须完整落在排班班段内(含前一天跨天夜班),且已上传附件' },
|
||||
]
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
save_dir: 'D:\\资料\\人资\\请假流程审批',
|
||||
approve_enabled: true,
|
||||
push_enabled: true,
|
||||
dingtalk_webhook: '',
|
||||
dingtalk_secret: '',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (form.push_enabled && form.dingtalk_webhook && !/^https?:\/\//.test(form.dingtalk_webhook)) {
|
||||
ElMessage.warning('钉钉 Webhook 应为 http(s):// 开头的完整地址,或留空使用内置机器人')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
// 仅提交后端 run() 读取的字段
|
||||
buildPayload(f) {
|
||||
return {
|
||||
save_dir: f.save_dir,
|
||||
approve_enabled: f.approve_enabled,
|
||||
push_enabled: f.push_enabled,
|
||||
dingtalk_webhook: f.dingtalk_webhook,
|
||||
dingtalk_secret: f.dingtalk_secret,
|
||||
debug_mode: f.debug_mode,
|
||||
}
|
||||
},
|
||||
})
|
||||
</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: 16px 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%;
|
||||
}
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---------- 检查项说明(静态,只读) ---------- */
|
||||
.checks {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.check-tile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
background: var(--el-fill-color-blank);
|
||||
}
|
||||
.tile-num {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
background: var(--el-color-primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tile-label {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.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 = 'xq0003'
|
||||
@@ -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,340 @@
|
||||
// 插件 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
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 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
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
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/xq0003/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0003/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5183,
|
||||
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>EHR系统请假流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0003/assets/index-B2Ej4o3H.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0003/assets/index-Ka-PutnU.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,207 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 overtime_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「加班」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班
|
||||
与打卡区间,延时加班另做提前到岗型与弹性到岗兑换校验;
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
|
||||
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .data.hr_api import HRSessionExpiredError
|
||||
from .logic import overtime_rules
|
||||
from .report import overtime_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class OvertimeApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统加班流程审核(需求 XQ0004)。"""
|
||||
|
||||
id = "xq0004"
|
||||
name = "EHR系统加班流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)"
|
||||
"校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,"
|
||||
"并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0004"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string", "title": "推送环境", "default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出接口返回等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
push_env = (fields.get("push_env") or "dev").strip().lower() or "dev"
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 加班审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取加班待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = overtime_rules.validate_doc(detail, session)
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = overtime_report.generate_report(results)
|
||||
report_path = overtime_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送 ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = overtime_report.build_push_summary(results, subject)
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret, env=push_env)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
|
||||
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
|
||||
"overdue": sum(1 for r in results if r.get("decision") == "超期"),
|
||||
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
|
||||
if counts["overdue"]:
|
||||
summary += f",超期待人资处理 {counts['overdue']}"
|
||||
if counts["abnormal"]:
|
||||
summary += f",审批异常 {counts['abnormal']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
except HRSessionExpiredError as e:
|
||||
# 与影刀版 run_flow 一致:中途 HR 会话失效时给出明确提示,而非原始异常冒泡
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再执行: {e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(OvertimeApprovalPlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件打包脚本(统一规范版)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0004 EHR系统加班流程审核\\_pack.py"
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0004_v<版本>.zip --id xq0004 --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", "__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,213 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\加班流程审批"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
DEFAULT_SUBJECT = "加班"
|
||||
|
||||
# ==================== 加班审批规则常量 ====================
|
||||
WORK_START_TIME = "09:00"
|
||||
WORK_END_TIME = "18:00"
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
|
||||
# 次日弹性上班扣减时扣除的中午休息时长(小时)
|
||||
LUNCH_BREAK_HOURS = 1
|
||||
OT_MIN_HOURS = 1
|
||||
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
# 职能排班半天加班时长:上午3.5小时、下午4.5小时(休息日/节假日加班整天仍为9小时)
|
||||
ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ==================== 审批提交 ====================
|
||||
# 仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
# ==================== 编码 → 名称 ====================
|
||||
OT_TYPE_MAP = {"1": "延时加班", "2": "法定假日加班", "3": "休息日加班"}
|
||||
SUBSIDY_TYPE_MAP = {"1": "转调休", "2": "转补贴"}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 数据层。"""
|
||||
@@ -0,0 +1,348 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - HR 接口层(由影刀版 overtime_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查加班流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId
|
||||
3) WorkformEngine getBusinessDate 取加班表单数据
|
||||
4) rf_s_kq_count_leave_yc_day_all 按员工+日期范围取每日考勤(班次名/班次起止)
|
||||
5) rf_s_kq_leave_record_SelectByStaffID 取请假记录(弹性兑换前置校验)
|
||||
6) rf_s_kq_data_queryByStaffId 取打卡明细(kq_time/bc_date/time_order)
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, ATTENDANCE_DAILY_URL, LEAVE_RECORD_URL, PUNCH_RECORD_URL,
|
||||
DEFAULT_PAGE_SIZE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON 或 Nosession,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 加班流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 每日考勤(排班 + 班次时段) ====================
|
||||
def get_attendance_daily(session, staff_id, start_date, end_date):
|
||||
"""按员工+日期范围查询每日考勤(含班次起止时间与上下班打卡)。
|
||||
|
||||
kq_status_total 按考勤状态分类返回记录:0=休息日、1=正常班、9=未打卡、11=异常,
|
||||
需四种状态各查一次,再按 work_day 合并去重,才能同时拿到班次名/班次时段与休息日记录。
|
||||
"""
|
||||
by_day = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"考勤逐日接口请求失败: {e}") from e
|
||||
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
|
||||
|
||||
# ==================== 请假记录 ====================
|
||||
def fetch_leave_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
data = {
|
||||
"sub_type": sub_type,
|
||||
"staff_id": staff_id,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"pageSize": str(page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
}
|
||||
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"请假记录接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_leave_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
all_records = []
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
|
||||
|
||||
# ==================== 打卡明细 ====================
|
||||
def fetch_punch_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""请求单页员工打卡明细(kq_time 真实打卡时间 / bc_date 考勤归属日 / time_order 1上2下)。"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"打卡明细接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_punch_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""查询员工某时间段内的全部打卡明细(自动分页)。"""
|
||||
all_records = []
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 业务规则层。"""
|
||||
@@ -0,0 +1,598 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 加班校验规则层。
|
||||
|
||||
迁移自 workflows/XQ0001-0100/XQ0004 EHR系统加班流程审核/overtime_approval.py:
|
||||
- 登录态改造:SessionPage → 底座注入 requests.Session(data.hr_api.get_* 接口)
|
||||
- 日志改造:print 输出与进程退出提示 → config.logger
|
||||
- 规则逻辑(时长取整/弹性兑换/休息日法定假日加班/审核周期)原样保留
|
||||
"""
|
||||
import calendar
|
||||
import math
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from chinese_calendar import get_holiday_detail, is_in_lieu
|
||||
|
||||
from ..config import (
|
||||
logger,
|
||||
WORK_START_TIME,
|
||||
WORK_END_TIME,
|
||||
FLEX_TRIGGER_TIME,
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME,
|
||||
LUNCH_BREAK_HOURS,
|
||||
OT_MIN_HOURS,
|
||||
CROSS_DAY_BEFORE_HOUR,
|
||||
OT_REVIEW_DAYS,
|
||||
MONTH_CUTOFF_DAY,
|
||||
MONTH_CUTOFF_HOUR,
|
||||
ZHINENG_HALF_MORNING_HOURS,
|
||||
ZHINENG_HALF_AFTERNOON_HOURS,
|
||||
ZHINENG_HALF_CUTOFF_HOUR,
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES,
|
||||
OT_TYPE_MAP,
|
||||
SUBSIDY_TYPE_MAP,
|
||||
)
|
||||
from ..data.hr_api import get_attendance_daily, get_leave_records, get_punch_records
|
||||
|
||||
|
||||
# ==================== 加班表单解析 ====================
|
||||
def parse_overtime_form(result):
|
||||
ot_type_code = result.get("ot_type")
|
||||
subsidy_type_code = result.get("subsidy_type")
|
||||
|
||||
overtime_info = {
|
||||
"加班人员ID": result.get("staff_id"),
|
||||
"加班人员": result.get("staff_name"),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
||||
"加班日期": result.get("ot_date"),
|
||||
"加班开始时间": result.get("start_time"),
|
||||
"加班结束时间": result.get("end_time"),
|
||||
"加班时长(小时)": result.get("ot_hour") or result.get("expect_hour"),
|
||||
"加班天数(天)": result.get("ot_day"),
|
||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
judge_start = result.get("judge_start_time")
|
||||
judge_end = result.get("judge_end_time")
|
||||
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
|
||||
if (judge_start and judge_end
|
||||
and "无" not in str(judge_start) and "无" not in str(judge_end)):
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ==================== 加班校验规则 ====================
|
||||
def _parse_dt(value):
|
||||
if not value:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
|
||||
try:
|
||||
return datetime.strptime(str(value), fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _calc_delayed_hours(start, end):
|
||||
total = (end - start).total_seconds() / 3600
|
||||
if total < 1:
|
||||
return 0.0
|
||||
return 1.0 + math.floor((total - 1) / 0.5) * 0.5
|
||||
|
||||
|
||||
def _calc_flex_d(actual_checkout, flex_trigger):
|
||||
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
|
||||
|
||||
|
||||
def _calc_day_ot_threshold(days):
|
||||
return 8.0 * days + int(days)
|
||||
|
||||
|
||||
def _next_day(date_str):
|
||||
d = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _is_within_arrival_window(punch_str, start_dt,
|
||||
before_hours=OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
after_minutes=OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES):
|
||||
"""提前到岗型加班:判断打卡时间是否落在加班开始时间附近的到岗证据窗口内。"""
|
||||
p = _parse_dt(punch_str)
|
||||
if p is None:
|
||||
return False
|
||||
return (start_dt - timedelta(hours=before_hours)) <= p <= (start_dt + timedelta(minutes=after_minutes))
|
||||
|
||||
|
||||
def _is_spring_festival(date_str):
|
||||
try:
|
||||
date = datetime.strptime(date_str, "%Y-%m-%d").date()
|
||||
is_holiday, holiday_name = get_holiday_detail(date)
|
||||
return (is_holiday and holiday_name == 'Spring Festival'
|
||||
and not is_in_lieu(date) and date.weekday() < 5)
|
||||
except Exception as e:
|
||||
logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _get_shift(session, staff_id, date_str):
|
||||
if not date_str or not staff_id:
|
||||
return "未知"
|
||||
try:
|
||||
records = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
for r in records:
|
||||
if str(r.get("work_day", "")) == date_str:
|
||||
bc = r.get("bc_name")
|
||||
if bc:
|
||||
return str(bc)
|
||||
# 休息日记录 bc_name 为空,以异常状态标识判断(abnormal_name/kq_status_name1);
|
||||
# 用前缀"休息"匹配,兼容"休息"/"休息(调)"/"休息(补)"等变体
|
||||
if str(r.get("abnormal_name") or r.get("kq_status_name1") or "").startswith("休息"):
|
||||
return "休息"
|
||||
return "无排班"
|
||||
return "无排班"
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s): %s", date_str, str(e))
|
||||
return "获取失败"
|
||||
|
||||
|
||||
def _is_zhineng_schedule(session, staff_id, date_str):
|
||||
"""
|
||||
判断员工是否为职能排班(休息日/节假日加班半天规则专用)。
|
||||
|
||||
不看加班当天(当天排班通常显示'休息'),而是查看当月每日考勤中的其他天:
|
||||
只要任一天班次包含'职能'(如 职能正班A),即按职能排班处理。
|
||||
排班获取失败时优雅降级返回 False,沿用默认半天4小时规则。
|
||||
"""
|
||||
if not date_str or not staff_id:
|
||||
return False
|
||||
try:
|
||||
year = int(date_str[:4])
|
||||
month = int(date_str[5:7])
|
||||
first_day = f"{year:04d}-{month:02d}-01"
|
||||
last_day = f"{year:04d}-{month:02d}-{calendar.monthrange(year, month)[1]:02d}"
|
||||
records = get_attendance_daily(session, staff_id, first_day, last_day)
|
||||
return any("职能" in (r.get("bc_name") or "") for r in records)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班判断职能失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _check_attendance(session, staff_id, ot_date):
|
||||
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
|
||||
|
||||
|
||||
def _extract_shift_times(daily_records, date_str):
|
||||
"""从每日考勤记录中提取指定日期的班次起止时间("HH:MM"),无则返回 (None, None)。
|
||||
|
||||
数据源为 rf_s_kq_count_leave_yc_day_all 接口返回的每日记录
|
||||
(字段 work_day + bc_begin_time/bc_end_time),据此可拿到员工当天实际排班的
|
||||
下班时间(如维护早班 08:00-17:00),避免延时加班校验错误使用默认 18:00。
|
||||
"""
|
||||
for r in daily_records:
|
||||
if str(r.get("work_day", "")) != date_str:
|
||||
continue
|
||||
b = r.get("bc_begin_time")
|
||||
e = r.get("bc_end_time")
|
||||
return (str(b).strip()[:5] if b else None,
|
||||
str(e).strip()[:5] if e else None)
|
||||
return None, None
|
||||
|
||||
|
||||
def _check_punch_records(session, staff_id, ot_date):
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": "缺少加班日期或员工ID"}
|
||||
|
||||
start = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
prev_day = (start - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
# 打卡明细接口返回 kq_time=真实打卡时间 与 bc_date=考勤归属日,
|
||||
# 跨天打卡(次日0点~6点)由系统归入加班当天,无需人工拼接/修正日期;
|
||||
# 范围扩到前一天是为了兼容提前到岗型加班(开始<=6点)到岗打卡被归到前一天的情况。
|
||||
punches = get_punch_records(session, staff_id, prev_day, next_day)
|
||||
if not punches:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": "当天及次日无打卡记录"}
|
||||
# 按考勤归属日 bc_date 分组;time_order:1=上班打卡、2=下班打卡
|
||||
arrivals = {}
|
||||
checkouts = {}
|
||||
all_by_date = {}
|
||||
for r in punches:
|
||||
bd = str(r.get("bc_date", "")).strip()
|
||||
t = str(r.get("kq_time", "")).strip()
|
||||
if not bd or not t:
|
||||
continue
|
||||
all_by_date.setdefault(bd, []).append(t)
|
||||
if str(r.get("time_order", "")).strip() == "1":
|
||||
arrivals.setdefault(bd, []).append(t)
|
||||
elif str(r.get("time_order", "")).strip() == "2":
|
||||
checkouts.setdefault(bd, []).append(t)
|
||||
# 班次起止时间仍由考勤逐日接口提供;未获取到时由上层回退默认 09:00/18:00
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
|
||||
# 次日班次开始时间:弹性到岗兑换计算晚到时长时,次日上班时间优先取排班开始时间
|
||||
next_shift_begin, _ = _extract_shift_times(daily, next_day)
|
||||
|
||||
def _sorted(date_str):
|
||||
return sorted(all_by_date.get(date_str, []))
|
||||
|
||||
# 当日最早/最晚打卡:优先按上下班类型取,缺该类型时回退取当天全部打卡
|
||||
day_all = _sorted(ot_date)
|
||||
day_arrivals = sorted(arrivals.get(ot_date, []))
|
||||
day_checkouts = sorted(checkouts.get(ot_date, []))
|
||||
day_first = day_arrivals[0] if day_arrivals else (day_all[0] if day_all else None)
|
||||
day_last = day_checkouts[-1] if day_checkouts else (day_all[-1] if day_all else None)
|
||||
# 次日最早打卡(弹性兑换用)
|
||||
next_arrivals = sorted(arrivals.get(next_day, []))
|
||||
next_all = _sorted(next_day)
|
||||
next_first = next_arrivals[0] if next_arrivals else (next_all[0] if next_all else None)
|
||||
# 前一天最晚打卡(提前到岗型加班用)
|
||||
prev_all = _sorted(prev_day)
|
||||
prev_last = prev_all[-1] if prev_all else None
|
||||
return {
|
||||
"当日最早打卡": day_first,
|
||||
"当日最晚打卡": day_last,
|
||||
"次日最早打卡": next_first,
|
||||
"前一天最晚打卡": prev_last,
|
||||
"班次开始时间": shift_begin,
|
||||
"班次结束时间": shift_end,
|
||||
"次日班次开始时间": next_shift_begin,
|
||||
"打卡备注": "",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("获取打卡明细失败: %s", str(e))
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": f"获取失败: {e}"}
|
||||
|
||||
|
||||
def _check_leave_covers_morning(session, staff_id, date_str):
|
||||
prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
records = get_leave_records(session, staff_id, prev_day, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取请假记录失败: %s", str(e))
|
||||
return False
|
||||
|
||||
# 上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
|
||||
shift_begin = None
|
||||
try:
|
||||
daily = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
shift_begin, _ = _extract_shift_times(daily, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班时段失败(%s): %s", date_str, str(e))
|
||||
morning_time = shift_begin or WORK_START_TIME
|
||||
morning = datetime.strptime(f"{date_str} {morning_time}", "%Y-%m-%d %H:%M")
|
||||
for r in records:
|
||||
start = _parse_dt(r.get("start_time"))
|
||||
end = _parse_dt(r.get("end_time"))
|
||||
if start and end and start <= morning <= end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _validate_delayed(info, punch, session, staff_id):
|
||||
ot_date = info.get("加班日期")
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
|
||||
reasons = []
|
||||
# 申请结束时间晚于实际下班打卡、但实际在岗时长(按系统取整)仍满足申请时长时,用于附加到通过备注
|
||||
end_checkout_note = ""
|
||||
|
||||
# 1. 日期校验:加班开始日期与申请加班日期不一致时直接校验不通过未处理,
|
||||
# 无需再校验后续的时长、区间合规等内容
|
||||
if start is None:
|
||||
reasons.append("加班开始时间缺失")
|
||||
elif start.strftime("%Y-%m-%d") != ot_date:
|
||||
reason = f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致"
|
||||
info["计算加班时长(小时)"] = None
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = 0
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "校验不通过未处理", reason
|
||||
|
||||
# 2. 时长校验
|
||||
hours = None
|
||||
if end is None:
|
||||
reasons.append("加班结束时间缺失")
|
||||
elif start is not None:
|
||||
hours = _calc_delayed_hours(start, end)
|
||||
if hours < OT_MIN_HOURS:
|
||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
||||
|
||||
# 3. 区间合规校验
|
||||
# 班次起止时间优先用打卡明细携带的班次时段(bc_begin_time/bc_end_time),
|
||||
# 未获取到时回退默认 09:00/18:00(常规班次),避免非18点下班班次被误判。
|
||||
shift_begin = punch.get("班次开始时间") or WORK_START_TIME
|
||||
shift_end = punch.get("班次结束时间") or WORK_END_TIME
|
||||
work_start = datetime.strptime(f"{ot_date} {shift_begin}", "%Y-%m-%d %H:%M")
|
||||
work_end = datetime.strptime(f"{ot_date} {shift_end}", "%Y-%m-%d %H:%M")
|
||||
# 提前到岗型延时加班:加班开始时间早于当天班次开始时间。
|
||||
# 常规"晚于规定下班时间""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||||
# - 开始<=6点时,到岗打卡可能被系统归到前一天(跨天打卡),需回看前一天记录;
|
||||
# - 6点~9点开始的,到岗打卡归属当天,只看当天记录。
|
||||
is_pre_shift = start is not None and start < work_start
|
||||
if is_pre_shift:
|
||||
candidates = [punch.get("当日最早打卡")]
|
||||
cross_cutoff = start.replace(hour=CROSS_DAY_BEFORE_HOUR, minute=0, second=0, microsecond=0)
|
||||
if start <= cross_cutoff:
|
||||
candidates.append(punch.get("前一天最晚打卡"))
|
||||
arrival_punch = next(
|
||||
(c for c in candidates if _is_within_arrival_window(c, start)),
|
||||
None,
|
||||
)
|
||||
if arrival_punch is None:
|
||||
reasons.append(f"提前到岗型加班,未找到加班开始时间({start:%H:%M})附近的到岗打卡")
|
||||
else:
|
||||
info["到岗打卡"] = arrival_punch
|
||||
else:
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({shift_end})")
|
||||
if end is not None:
|
||||
if actual_checkout is None:
|
||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
||||
elif start is not None and hours is not None:
|
||||
# 核心原则:申请的加班时长必须与打卡可支撑的实际在岗时长相符。
|
||||
# 按系统取整规则(_calc_delayed_hours),用实际打卡区间(申请开始->实际下班打卡)
|
||||
# 计算实际在岗时长,>= 申请时长即通过(申请结束时间比打卡晚几分钟也属正常)。
|
||||
# 例:申请 18:00-23:05(取整5h),实际打卡23:00:45,实际在岗取整后也是5h,应通过
|
||||
actual_hours = _calc_delayed_hours(start, actual_checkout)
|
||||
if actual_hours >= hours:
|
||||
if end > actual_checkout:
|
||||
end_checkout_note = (
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按系统取整为{actual_hours:g}小时,满足申请时长"
|
||||
)
|
||||
else:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按取整仅{actual_hours:g}小时,不足申请{hours:g}小时"
|
||||
)
|
||||
|
||||
info["计算加班时长(小时)"] = hours
|
||||
if reasons:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "校验不通过未处理", ";".join(reasons)
|
||||
|
||||
# 4. 弹性到岗兑换
|
||||
deduction = 0.0
|
||||
flex_note = ""
|
||||
d_hours = 0.0
|
||||
flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M")
|
||||
|
||||
if actual_checkout is not None and actual_checkout >= flex_trigger:
|
||||
d_hours = _calc_flex_d(actual_checkout, flex_trigger)
|
||||
next_day = _next_day(ot_date)
|
||||
next_shift = _get_shift(session, staff_id, next_day)
|
||||
|
||||
if next_shift in ("休息", "无排班"):
|
||||
flex_note = f"次日({next_day})为休息日,不触发弹性兑换"
|
||||
elif next_shift in ("获取失败", "未知"):
|
||||
flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换"
|
||||
elif _check_leave_covers_morning(session, staff_id, next_day):
|
||||
flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换"
|
||||
else:
|
||||
# 次日上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
|
||||
next_shift_begin = punch.get("次日班次开始时间") or WORK_START_TIME
|
||||
work_start = datetime.strptime(f"{next_day} {next_shift_begin}", "%Y-%m-%d %H:%M")
|
||||
p = _parse_dt(punch.get("次日最早打卡"))
|
||||
|
||||
if p is None:
|
||||
flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换"
|
||||
elif p <= work_start:
|
||||
flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换"
|
||||
else:
|
||||
# 有晚到,校验:加班时长 + 晚到 <= 实际在岗时长(按系统取整)
|
||||
# 实际在岗时长 = 加班开始->实际下班打卡 按延时取整(1h起算0.5h累加)
|
||||
actual_work = _calc_delayed_hours(start, actual_checkout)
|
||||
lunch_trigger = datetime.strptime(
|
||||
f"{next_day} {FLEX_LATE_LUNCH_TRIGGER_TIME}", "%Y-%m-%d %H:%M"
|
||||
)
|
||||
|
||||
if p <= work_start + timedelta(hours=d_hours):
|
||||
# T < P <= T+D:晚到时长 = P-T,次日打卡超过13:00时
|
||||
# 再扣1小时午餐,按1小时起算向上取整(不足1小时不扣)
|
||||
late_raw = (p - work_start).total_seconds() / 3600
|
||||
if p > lunch_trigger:
|
||||
late_raw -= LUNCH_BREAK_HOURS
|
||||
late_hours = math.ceil(late_raw) if late_raw >= OT_MIN_HOURS else 0
|
||||
if late_hours < 1:
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到不足1小时,不触发弹性兑换"
|
||||
else:
|
||||
if hours + late_hours > actual_work:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "校验不通过未处理", (
|
||||
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 晚到{late_hours}h "
|
||||
f"> 实际在岗时长{actual_work:g}h"
|
||||
)
|
||||
deduction = float(late_hours)
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
|
||||
else:
|
||||
if hours + d_hours > actual_work:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "校验不通过未处理", (
|
||||
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
|
||||
f"> 实际在岗时长{actual_work:g}h"
|
||||
)
|
||||
deduction = float(d_hours)
|
||||
flex_note = (
|
||||
f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h),"
|
||||
f"按D兑换,超出部分交考勤处理"
|
||||
)
|
||||
else:
|
||||
if actual_checkout is not None:
|
||||
flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0"
|
||||
|
||||
effective = max(0.0, float(hours) - deduction)
|
||||
info["弹性扣减(小时)"] = deduction
|
||||
info["有效加班时长(小时)"] = effective
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
note = f"审批通过,有效加班时长{effective:g}小时"
|
||||
extra_parts = [end_checkout_note, flex_note]
|
||||
extra = ";".join(p for p in extra_parts if p)
|
||||
if extra:
|
||||
note += f"({extra})"
|
||||
return "通过", note
|
||||
|
||||
|
||||
def _validate_day_ot(info, punch, session, staff_id, require_holiday):
|
||||
ot_date = info.get("加班日期")
|
||||
reasons = []
|
||||
|
||||
shift = info.get("加班当天班次", "")
|
||||
if shift not in ("休息", "获取失败", "未知", "无排班"):
|
||||
reasons.append(f"当天排班为'{shift}',非休息日")
|
||||
|
||||
if require_holiday and not _is_spring_festival(ot_date):
|
||||
reasons.append(f"{ot_date}不在春节法定节假日列表中")
|
||||
|
||||
# 加班时长 > 0:休息日加班按天计,表单 ot_hour 常为 0(aa.md 中 ot_hours=0.0、ot_days=1.00),
|
||||
# 此时用申报起止时间推算实际加班时长,避免误校验不通过未处理
|
||||
ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)")
|
||||
try:
|
||||
ot_hour = float(ot_hour)
|
||||
except (TypeError, ValueError):
|
||||
ot_hour = 0.0
|
||||
if ot_hour <= 0:
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
if start and end and end > start:
|
||||
ot_hour = (end - start).total_seconds() / 3600
|
||||
if ot_hour <= 0:
|
||||
reasons.append("加班时长为0或缺失")
|
||||
|
||||
first = _parse_dt(punch.get("当日最早打卡"))
|
||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
||||
interval = None
|
||||
# 打卡明细接口已按考勤归属日 bc_date 分组,跨天打卡(次日0点~6点)归入加班当天,
|
||||
# 因此当日最早/最晚打卡已包含跨天下班打卡,无需再参考次日打卡补全。
|
||||
if first is None or last is None:
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
else:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
|
||||
apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)")
|
||||
try:
|
||||
apply_days = float(apply_days)
|
||||
except (TypeError, ValueError):
|
||||
apply_days = 0.0
|
||||
if apply_days <= 0:
|
||||
reasons.append("申报天数缺失或为0")
|
||||
elif interval is not None:
|
||||
threshold = _calc_day_ot_threshold(apply_days)
|
||||
# 职能排班半天(0.5天)加班:上午3.5小时、下午4.5小时,不再统一按4小时半天处理;
|
||||
# 上/下午按申请加班开始时间判定(早于12:00视为上午半天)
|
||||
if abs(apply_days - 0.5) < 1e-9 and _is_zhineng_schedule(session, staff_id, ot_date):
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
if start is not None and start.hour < ZHINENG_HALF_CUTOFF_HOUR:
|
||||
threshold = ZHINENG_HALF_MORNING_HOURS
|
||||
else:
|
||||
threshold = ZHINENG_HALF_AFTERNOON_HOURS
|
||||
if interval < threshold:
|
||||
reasons.append(
|
||||
f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时"
|
||||
)
|
||||
|
||||
info["打卡时间间隔(小时)"] = interval
|
||||
info["申报天数(天)"] = apply_days
|
||||
if reasons:
|
||||
return "校验不通过未处理", ";".join(reasons)
|
||||
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
|
||||
|
||||
|
||||
def check_review_period(ot_date, today=None):
|
||||
"""
|
||||
加班日期有效性前置校验,返回 (是否可审核, 原因)。
|
||||
|
||||
规则:
|
||||
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
|
||||
2. 月度截止:每月 MONTH_CUTOFF_DAY 号 MONTH_CUTOFF_HOUR:00 之后,
|
||||
不再审核上一个月的加班流程。
|
||||
"""
|
||||
if not ot_date:
|
||||
return False, "加班日期缺失,无法校验审核周期"
|
||||
try:
|
||||
ot_day = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
except (TypeError, ValueError):
|
||||
return False, f"加班日期格式非法: {ot_date}"
|
||||
|
||||
today = today or datetime.now()
|
||||
today_date = today.date()
|
||||
|
||||
# 规则1:8天审核周期
|
||||
if (today_date - ot_day.date()).days > OT_REVIEW_DAYS:
|
||||
return False, f"加班日期({ot_date})距今超过{OT_REVIEW_DAYS}天审核周期,不再审核"
|
||||
|
||||
# 规则2:每月2号12点之后不再审核上月加班
|
||||
if ot_day.date() < today_date.replace(day=1):
|
||||
if today.day > MONTH_CUTOFF_DAY or (today.day == MONTH_CUTOFF_DAY and today.hour >= MONTH_CUTOFF_HOUR):
|
||||
return False, (f"加班日期({ot_date})属于上月或更早,已超过本月{MONTH_CUTOFF_DAY}号"
|
||||
f"{MONTH_CUTOFF_HOUR}点,不再审核上月加班流程")
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_doc(doc, session):
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
overtime_info = parse_overtime_form(form_data)
|
||||
|
||||
# 前置校验:加班日期有效性(8天审核周期 + 每月2号12点后不再审核上月加班)
|
||||
valid, period_reason = check_review_period(overtime_info.get("加班日期"))
|
||||
if not valid:
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "超期",
|
||||
"note": period_reason,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
|
||||
staff_id = overtime_info.get("加班人员ID")
|
||||
ot_date = overtime_info.get("加班日期")
|
||||
|
||||
attendance_info = _check_attendance(session, staff_id, ot_date)
|
||||
punch_info = _check_punch_records(session, staff_id, ot_date)
|
||||
overtime_info.update(attendance_info)
|
||||
overtime_info.update(punch_info)
|
||||
|
||||
ot_type_code = str(form_data.get("ot_type") or "")
|
||||
if ot_type_code == "1":
|
||||
decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id)
|
||||
elif ot_type_code == "3":
|
||||
decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=False)
|
||||
elif ot_type_code == "2":
|
||||
require_holiday = _is_spring_festival(ot_date)
|
||||
decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=require_holiday)
|
||||
else:
|
||||
decision, note = "校验不通过未处理", f"无法识别加班类型: {ot_type_code}"
|
||||
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": decision,
|
||||
"note": note,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0004",
|
||||
"name": "EHR系统加班流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0004"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\加班流程审批",
|
||||
"description": "加班审批报告存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人"
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string",
|
||||
"title": "推送环境",
|
||||
"default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出接口返回等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 报告与推送层。"""
|
||||
@@ -0,0 +1,230 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 钉钉群机器人推送(插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _otype(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("岗位", "岗位"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
输出:
|
||||
- 每条审批的完整明细(含加班日期、时长、打卡、排班等)
|
||||
- 《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因
|
||||
- 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接
|
||||
- 《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if overdue:
|
||||
summary += f",超期待人资处理 {len(overdue)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 超期待人资处理清单 -----
|
||||
if overdue:
|
||||
lines.append("《超期加班待人资处理清单》")
|
||||
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
|
||||
for i, r in enumerate(overdue, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《加班审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中单据状态未变,需人工跟进)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or "未知"
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_overtime_block(r):
|
||||
"""将单条加班审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
name = info.get("加班人员") or r.get("creator") or "未知"
|
||||
otype = info.get("加班类型") or ""
|
||||
lines = [f"**🔹 {name}‑{otype}**"]
|
||||
for key, label in [
|
||||
("加班人员", "加班人员"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
date = info.get("加班日期")
|
||||
if date:
|
||||
lines.append(f"> 加班日期:{date}")
|
||||
start = info.get("加班开始时间")
|
||||
end = info.get("加班结束时间")
|
||||
if start or end:
|
||||
lines.append(f"> 加班时段:{start or ''} ~ {end or ''}")
|
||||
for key, label in [("加班时长(小时)", "加班时长"), ("加班天数(天)", "加班天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("申报天数(天)", "申报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
按结果类型生成块格式 Markdown 推送分组。
|
||||
|
||||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]},
|
||||
分批/推送由机器人推送模块内部完成(调用方不关心批次)。
|
||||
"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not rejected and not review and not overdue and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_overtime_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
# 汇总消息先发:本次审批各类别数量(一条,含 0 的类别)
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("校验不通过未处理", len(rejected)),
|
||||
("需人工复核", len(review)),
|
||||
("超期待人资处理", len(overdue)),
|
||||
("审批异常", len(abnormal)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
# 通过的单据数量太多,不再逐条推送明细,只保留汇总计数与需人工处理的明细
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】超期待人资处理", overdue)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/加班审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"加班审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,3 @@
|
||||
requests
|
||||
DrissionPage
|
||||
chinese_calendar
|
||||
@@ -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>EHR系统加班流程审核</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0004-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,484 @@
|
||||
<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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<path d="M14 2v6h6" />
|
||||
<path d="m9 15 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>
|
||||
|
||||
<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.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\人资\加班流程审批" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">审批报告保存为「加班审批报告_时间戳.txt」。</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">
|
||||
<el-form-item label="自动提交审批">
|
||||
<el-switch v-model="form.approve_enabled" :disabled="running"
|
||||
active-text="校验通过自动点同意" inactive-text="仅校验不提交" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉群推送">
|
||||
<el-switch v-model="form.push_enabled" :disabled="running"
|
||||
active-text="推送汇总与待人工明细" inactive-text="不推送" />
|
||||
</el-form-item>
|
||||
<el-form-item label="推送环境">
|
||||
<el-radio-group v-model="form.push_env" :disabled="running || !form.push_enabled">
|
||||
<el-radio value="dev">测试群</el-radio>
|
||||
<el-radio value="prod">生产群</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉 Webhook">
|
||||
<el-input v-model="form.dingtalk_webhook" :disabled="running || !form.push_enabled" clearable
|
||||
placeholder="留空 = 内置默认机器人;发其他群时填完整地址" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉加签密钥">
|
||||
<el-input v-model="form.dingtalk_secret" :disabled="running || !form.push_enabled" clearable
|
||||
placeholder="留空 = 不加签" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running"
|
||||
active-text="输出接口返回等调试信息" inactive-text="关闭" />
|
||||
</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="checks static">
|
||||
<div v-for="c in RULES" :key="c.num" class="check-tile">
|
||||
<span class="tile-num">{{ c.num }}</span>
|
||||
<span class="tile-label">{{ c.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tip">仅「通过」的单据会自动提交审批;校验不通过、人工复核、超期待人资处理、审批提交失败的单据均保留待办,并写入报告与钉钉推送,由人工跟进。</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'
|
||||
|
||||
// 校验规则(与后端 logic/overtime_rules.py 一一对应,仅展示说明)
|
||||
const RULES = [
|
||||
{ num: '1', label: '前置:加班日期在 8 天审核周期内,且每月 2 号 12 点后不再审核上月加班' },
|
||||
{ num: '2', label: '延时加班:开始日期与加班日期一致、时长≥1 小时、区间合规(提前到岗型看到岗打卡),23 点后下班触发弹性到岗兑换' },
|
||||
{ num: '3', label: '休息日加班:当天排班为休息,打卡间隔达到申报天数对应阈值(职能半天 3.5/4.5 小时)' },
|
||||
{ num: '4', label: '法定假日加班:在春节法定节假日列表内 + 休息日规则' },
|
||||
]
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
save_dir: 'D:\\资料\\人资\\加班流程审批',
|
||||
approve_enabled: true,
|
||||
push_enabled: true,
|
||||
push_env: 'dev',
|
||||
dingtalk_webhook: '',
|
||||
dingtalk_secret: '',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (form.push_enabled && form.dingtalk_webhook && !/^https?:\/\//.test(form.dingtalk_webhook)) {
|
||||
ElMessage.warning('钉钉 Webhook 应为 http(s):// 开头的完整地址,或留空使用内置机器人')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
// 仅提交后端 run() 读取的字段
|
||||
buildPayload(f) {
|
||||
return {
|
||||
save_dir: f.save_dir,
|
||||
approve_enabled: f.approve_enabled,
|
||||
push_enabled: f.push_enabled,
|
||||
push_env: f.push_env,
|
||||
dingtalk_webhook: f.dingtalk_webhook,
|
||||
dingtalk_secret: f.dingtalk_secret,
|
||||
debug_mode: f.debug_mode,
|
||||
}
|
||||
},
|
||||
})
|
||||
</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: 16px 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%;
|
||||
}
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---------- 检查项说明(静态,只读) ---------- */
|
||||
.checks {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.check-tile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
background: var(--el-fill-color-blank);
|
||||
}
|
||||
.tile-num {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
background: var(--el-color-primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tile-label {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.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 = 'xq0004'
|
||||
@@ -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,340 @@
|
||||
// 插件 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
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 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
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
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/xq0004/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0004/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5184,
|
||||
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>EHR系统加班流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0004/assets/index-Br4JMqLc.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0004/assets/index-DYuos9Vi.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,250 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 resign_e_sign_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「改签离职电子签流程」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:是否已发起电子签、员工/企业签署状态三态均已完成 → 下载签章附件
|
||||
(解除确认书/报酬支付确认)并核验日期与离职原因与表单一致 → 通过;否则未完成(不管);
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并监听 sendWeTask 确认提交结果;
|
||||
5) 独立超期检查:完善信息(操作人)节点完成超 3 天仍未走完的流程,记入超期名单;
|
||||
6) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 提交失败 + 超期名单)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .data.hr_api import HRSessionExpiredError
|
||||
from .logic import resign_rules
|
||||
from .report import resign_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class ResignESignApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统离职电子签流程审核(需求 XQ0020)。"""
|
||||
|
||||
id = "xq0020"
|
||||
name = "EHR系统离职电子签流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 离职电子签待办:按是否已发起电子签、员工/企业签署状态三态校验;"
|
||||
"三态均已完成则下载签章附件(解除确认书/报酬支付确认)并核验日期与离职原因与表单一致,"
|
||||
"全部通过自动提交审批;同时检查「完善信息(操作人)」节点超期名单,"
|
||||
"并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0020"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告与签章附件(附件/ 子目录)统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总、提交失败与超期名单推送到钉钉群机器人",
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string", "title": "推送环境", "default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出接口返回等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
push_env = (fields.get("push_env") or "dev").strip().lower() or "dev"
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 离职电子签审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取离职电子签待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
overdue_list = [] # 超期名单:完善信息(操作人)完成超 3 天仍未走完的流程
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = resign_rules.validate_doc(detail, session)
|
||||
|
||||
# 超期检查(独立于审批校验,失败不影响主流程):
|
||||
# 完善信息(操作人)endTime 非空且距今超 3 天 -> 记入超期名单
|
||||
process_id = detail.get("processId") or ""
|
||||
if process_id:
|
||||
try:
|
||||
overdue = hr_api.check_process_overdue(session, process_id)
|
||||
if overdue:
|
||||
info = resign_rules.parse_resign_e_sign_form(detail.get("formData") or {})
|
||||
overdue_list.append({
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"staff_name": info.get("员工姓名") or "",
|
||||
"leaveoffice_time": info.get("离职日期") or "",
|
||||
"brand": info.get("原归属品牌") or "",
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
**overdue,
|
||||
})
|
||||
except Exception as e:
|
||||
ctx.log(f"超期检查失败(不影响主流程): {doc.get('title')}: {e}", "WARN")
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 审批结论与提交动作分离:提交失败不改审批结论(仍为"通过"),
|
||||
# 仅记录 submit_ok 供推送/报告单列提醒;OA 中状态未变,需人工跟进
|
||||
result["submit_ok"] = submit["ok"]
|
||||
if submit["ok"] == "false":
|
||||
result["note"] = (
|
||||
f"审批通过但自动提交失败(OA 中未生效,需人工跟进):{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(不管,待后续流转)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = resign_report.generate_report(results)
|
||||
report_path = resign_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送(汇总 + 提交失败 + 超期名单) ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = resign_report.build_push_summary(results, subject)
|
||||
# 超期名单:完善信息(操作人)完成超 3 天仍未走完的流程,单独分组推送
|
||||
if overdue_list:
|
||||
overdue_blocks = []
|
||||
for r in overdue_list:
|
||||
operator = r.get("operator") or ""
|
||||
who = f"办理人:{operator}" if operator else f"发起人:{r.get('creator') or ''}"
|
||||
lines = [f"**🔹 {r['staff_name'] or r['title']}**({who})"]
|
||||
if r.get("brand"):
|
||||
lines.append(f"> 原归属品牌:{r['brand']}")
|
||||
if r.get("leaveoffice_time"):
|
||||
lines.append(f"> 实际离职日期:{r['leaveoffice_time']}")
|
||||
lines.append(f"> 完善信息完成时间:{r['endTime']}(已超期 {r['days']} 天)")
|
||||
if r.get("detail_url"):
|
||||
lines.append(f"> 详情页:[查看详情]({r['detail_url']})")
|
||||
overdue_blocks.append("\n\n".join(lines))
|
||||
push_items.append({
|
||||
"title": f"【{subject}审批】超期名单(完善信息完成超 {config.OVERDUE_DAYS} 天)",
|
||||
"blocks": overdue_blocks,
|
||||
})
|
||||
ctx.log(f"超期名单 {len(overdue_list)} 条,已加入推送", "INFO")
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret, env=push_env)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"pending": sum(1 for r in results if r.get("decision") == "未完成"),
|
||||
"submit_failed": sum(1 for r in results if r.get("submit_ok") == "false"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
"overdue": len(overdue_list),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"未完成待跟进 {counts['pending']}")
|
||||
if counts["submit_failed"]:
|
||||
summary += f",提交失败待跟进 {counts['submit_failed']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
if counts["overdue"]:
|
||||
summary += f",超期名单 {counts['overdue']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
except HRSessionExpiredError as e:
|
||||
# 与影刀版 run_flow 一致:中途 HR 会话失效时给出明确提示,而非原始异常冒泡
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再执行: {e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(ResignESignApprovalPlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件打包脚本(统一规范版)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0020 EHR系统离职电子签流程审核\\_pack.py"
|
||||
随后发布:
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \
|
||||
dist-plugin\\xq0020_v<版本>.zip --id xq0020 --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", "__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,260 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
# 流程待办查询:数据行在响应 jsonList/datas(随服务端版本切换,已兼容),行内自带 taskId/businessKey/processId/formId
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
# 当前登录用户信息(轻量会话校验:返回顶层含 userId 的 JSON)
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
# 附件清单查询接口:按 ids(逗号分隔 fileId)查附件元信息(fileName 等)
|
||||
FJK_BY_IDS_URL = f"{HR_BASE_URL}/RedseaPlatform/PtFjk.mc?method=getFjkByIds"
|
||||
# 附件下载接口:按 fileId 下载(返回 PDF 流 + Content-Disposition);要求有效 EHR 会话
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 审批提交接口:点击"同意"确认后前端会调用 sendWeTask,监听其响应以区分提交成功/失败(state="1" 成功,"0" 失败)
|
||||
SEND_WE_TASK_URL = f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc"
|
||||
SEND_WE_TASK_MARK = "WeTask.mc?method=sendWeTask"
|
||||
# 流程节点列表查询接口:按 processId 查流程全部节点任务(activityName/createTime/endTime/currentState 等)
|
||||
WE_TASK_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc"
|
||||
# 电子签真实签署状态查询接口(按合同业务主键 main_id 查询)
|
||||
CONTRACT_SIGNATURE_SELECT_URL = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/getContentLinkage/redApi/"
|
||||
"rf_hr_staff_contract_signature_select_sp_cq37du/WorkformEngine.mc"
|
||||
)
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
DEFAULT_SUBJECT = "改签离职电子签流程"
|
||||
|
||||
# 超期检查:「完善信息(操作人)」节点 endTime 非空且距今超过该天数 -> 超期提醒
|
||||
OVERDUE_ACTIVITY_NAME = "完善信息(操作人)"
|
||||
OVERDUE_DAYS = 3
|
||||
|
||||
# ==================== 审批提交 ====================
|
||||
# 仅自动提交"同意"(校验通过);未完成一律不自动提交("不管"),保留待后续流转
|
||||
APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
# ==================== 编码 → 名称 ====================
|
||||
# 是否已发起电子签字典(hr_staff_contract.is_initiate_sign)
|
||||
INITIATE_SIGN_MAP = {
|
||||
"0": "未发起",
|
||||
"1": "已发起",
|
||||
"2": "已完成",
|
||||
"3": "已撤销",
|
||||
"5": "已过期",
|
||||
"7": "已拒签",
|
||||
"8": "已作废",
|
||||
}
|
||||
|
||||
# 员工/企业签署状态字典(esign_sigin_state)
|
||||
SIGN_STATE_MAP = {
|
||||
"1": "签署中",
|
||||
"2": "已完成",
|
||||
"3": "未完成",
|
||||
"4": "已作废",
|
||||
}
|
||||
|
||||
# 电子签三状态均须等于该编码(已完成)才同意
|
||||
SIGN_DONE_CODE = "2"
|
||||
|
||||
# 离职类型字典(hr_staff_contract.leaveoffice_type 编码 -> 展示文本)
|
||||
LEAVEOFFICE_TYPE_MAP = {
|
||||
"": "请选择",
|
||||
"0": "辞职",
|
||||
"1": "辞退",
|
||||
"4": "合同期内辞职",
|
||||
"9": "其他",
|
||||
"2": "进修学习",
|
||||
"3": "参军",
|
||||
"5": "除名",
|
||||
"6": "开除",
|
||||
"7": "死亡",
|
||||
"8": "失踪",
|
||||
"11": "协商一致解除",
|
||||
"12": "主动离职",
|
||||
"13": "非主动离职",
|
||||
"14": "自动离职(未办理离职手续)",
|
||||
"15": "开除人员",
|
||||
"16": "调出",
|
||||
"17": "合同到期未续签",
|
||||
"18": "解除合同",
|
||||
"ext_8": "个人申请辞职",
|
||||
"ext_1": "主动辞职",
|
||||
"ext_2": "到期个人不愿续签",
|
||||
"ext_3": "单位不续签",
|
||||
"ext_4": "劝退无证明",
|
||||
"ext_5": "劝退有证明",
|
||||
"ext_6": "自动离职",
|
||||
"ext_7": "双方协商一致解除",
|
||||
"10": "退休",
|
||||
}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def get_attachment_dir():
|
||||
"""签章附件(解除确认书/报酬支付确认)存放目录 = <save_dir>\\附件。"""
|
||||
return os.path.join(get_save_dir(), "附件")
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 接口层。"""
|
||||
@@ -0,0 +1,440 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - HR 接口层。
|
||||
|
||||
迁移自 workflows/XQ0001-0100/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py:
|
||||
- 登录态改造:SessionPage + 本地登录态文件 → 底座注入 requests.Session
|
||||
- 会话失效判定:非 JSON / state=Nosession → HRSessionExpiredError
|
||||
- 接口与参数(待办/表单/签署状态/节点超期/附件清单/附件下载)原样保留
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import (
|
||||
logger,
|
||||
WE_PROCESS_QUERY_URL,
|
||||
GET_CUR_USER_INFO_URL,
|
||||
WF_ACTIVITY_URL,
|
||||
WORKFORM_ENGINE_URL,
|
||||
FJK_BY_IDS_URL,
|
||||
FILE_DOWNLOAD_URL,
|
||||
WE_TASK_QUERY_URL,
|
||||
CONTRACT_SIGNATURE_SELECT_URL,
|
||||
DEFAULT_PAGE_SIZE,
|
||||
OVERDUE_ACTIVITY_NAME,
|
||||
OVERDUE_DAYS,
|
||||
HR_BASE_URL,
|
||||
retry,
|
||||
RetryExhaustedError, # noqa: F401 - 供调用方捕获重试耗尽
|
||||
require_session,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""统一 HR 接口请求:表单编码 POST,返回 JSON;非 JSON 抛会话失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""获取当前登录用户信息(含 userId),会话失效抛 HRSessionExpiredError。"""
|
||||
data = hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "getCurUserInfo")
|
||||
if not isinstance(data, dict) or not data.get("userId"):
|
||||
raise HRSessionExpiredError("getCurUserInfo 未返回 userId,HR 登录态已失效")
|
||||
return data
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验 HR 会话,返回当前登录用户 userId。"""
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = str(info.get("userId") or "").strip()
|
||||
if not user_id:
|
||||
raise HRSessionExpiredError("getCurUserInfo 未返回 userId,HR 登录态已失效")
|
||||
logger.info("HR 会话有效,当前用户 userId=%s", user_id)
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""调 WeProcess getProcessAndData 拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析 WeProcess 待办行为单据字典(taskId/businessKey/processId/formId 行内自带)。
|
||||
|
||||
detail_url 拼为 HR 流程详情页(goToWorkFlow, reqType=WAIT)供审批提交/推送链接用。
|
||||
数据行随服务端版本在 jsonList(total 型)与 datas(count 分页型)间切换,两种都兼容。
|
||||
"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉全部待办并去重(以 taskId 为键),分页上限 20 页。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20:
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
"""按 taskId 查流程活动(用于提取 formId)。"""
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
return hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
"""取表单业务数据(getBusinessDate)。"""
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取离职电子签表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
data = hr_request_json(
|
||||
session, "POST", url, {"businessKey": business_key, "formId": form_id}, "WorkformEngine"
|
||||
)
|
||||
result = data.get("result")
|
||||
if data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {data}")
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态 ====================
|
||||
def get_contract_sign_status(session, contract_id):
|
||||
"""查询电子签真实签署状态(按合同业务主键)。
|
||||
|
||||
返回 {"is_initiate_sign", "sign_status_yg", "sign_status_qy", "file"};
|
||||
业务异常(如该合同无电子签记录)按"查不到状态"处理,返回全 None。
|
||||
"""
|
||||
data = hr_request_json(
|
||||
session, "POST", CONTRACT_SIGNATURE_SELECT_URL,
|
||||
{"contract_id": contract_id, "inParamFormId": "", "colCode": "main_id"},
|
||||
"签署状态查询",
|
||||
)
|
||||
result = data.get("result")
|
||||
if data.get("state") != "1" or not isinstance(result, dict):
|
||||
logger.warning("签署状态查询业务异常(按未完成处理): contract_id=%s, meg=%s",
|
||||
contract_id, data.get("meg"))
|
||||
return {"is_initiate_sign": None, "sign_status_yg": None,
|
||||
"sign_status_qy": None, "file": None}
|
||||
logger.info("签署状态查询成功: contract_id=%s", contract_id)
|
||||
return {
|
||||
"is_initiate_sign": result.get("is_initiate_sign"),
|
||||
"sign_status_yg": result.get("sign_status_yg"),
|
||||
"sign_status_qy": result.get("sign_status_qy"),
|
||||
"file": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def enrich_form_sign_status(form_data, session):
|
||||
"""把 getBusinessData 返回的表单数据中的电子签三状态字段补上真实值。
|
||||
|
||||
表单 result 里 ext_is_initiate_sign/ext_staff_sign_status/ext_org_sign_status 恒为空串,
|
||||
需按 main_id 再调签署状态查询接口写回;签章附件 fileId 也从签署记录 file 字段获取。
|
||||
"""
|
||||
contract_id = form_data.get("main_id")
|
||||
if not contract_id:
|
||||
raise RuntimeError("表单数据缺少 main_id,无法查询电子签签署状态")
|
||||
sign_status = get_contract_sign_status(session, contract_id)
|
||||
form_data["ext_is_initiate_sign"] = sign_status["is_initiate_sign"]
|
||||
form_data["ext_staff_sign_status"] = sign_status["sign_status_yg"]
|
||||
form_data["ext_org_sign_status"] = sign_status["sign_status_qy"]
|
||||
form_data["contract_file"] = (
|
||||
(sign_status.get("file") or "").strip()
|
||||
or (form_data.get("contract_file") or "").strip()
|
||||
)
|
||||
return form_data
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey/processId 直接取自待办行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
# getBusinessData 返回的三个电子签状态字段恒为空串,需写回真实状态
|
||||
enrich_form_sign_status(form_data, session)
|
||||
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 流程节点与超期检查 ====================
|
||||
def get_activity_list(session, process_id):
|
||||
"""按 processId 查询流程全部节点任务(WeTask query)。
|
||||
|
||||
同一节点可能有多条记录(多候选人各一条,currentState 可能为 COMPLETED/OVERDUE/WAITING/ACCEPTED)。
|
||||
"""
|
||||
url = (
|
||||
f"{WE_TASK_QUERY_URL}?method=query"
|
||||
f"&sortName=create_time&sortType=asc&process_id={process_id}"
|
||||
)
|
||||
logger.info("查询流程节点列表: processId=%s", process_id)
|
||||
data = hr_request_json(session, "POST", url, {}, "WeTask query")
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"WeTask 接口返回失败: {data.get('meg')}")
|
||||
json_list = data.get("jsonList") or []
|
||||
logger.info("WeTask 返回成功,共 %d 条节点任务", len(json_list))
|
||||
return json_list
|
||||
|
||||
|
||||
def check_process_overdue(session, process_id, now=None):
|
||||
"""超期检查:取「完善信息(操作人)」节点 endTime 判断是否超期。
|
||||
|
||||
规则:endTime 为 null(节点未完成)-> 不算超期,返回 None;
|
||||
endTime 非空且距今超过 OVERDUE_DAYS 天 -> 返回 {"endTime", "days", "operator"}。
|
||||
"""
|
||||
activities = get_activity_list(session, process_id)
|
||||
matched = [a for a in activities if a.get("activityName") == OVERDUE_ACTIVITY_NAME]
|
||||
# 同一节点多条记录,优先取有审批意见(remark 非空)那条,其次 COMPLETED,最后第一条有 endTime 的
|
||||
target = next((a for a in matched if a.get("remark") and a.get("endTime")), None)
|
||||
if target is None:
|
||||
target = next((a for a in matched if a.get("currentState") == "COMPLETED" and a.get("endTime")), None)
|
||||
if target is None:
|
||||
target = next((a for a in matched if a.get("endTime")), None)
|
||||
if target is None:
|
||||
logger.warning("流程 %s 未找到「%s」节点,跳过超期检查", process_id, OVERDUE_ACTIVITY_NAME)
|
||||
return None
|
||||
|
||||
end_time = target.get("endTime")
|
||||
if not end_time:
|
||||
logger.info("流程 %s「%s」未完成(endTime=null),不检查超期", process_id, OVERDUE_ACTIVITY_NAME)
|
||||
return None
|
||||
|
||||
end_dt = datetime.strptime(str(end_time).strip(), "%Y-%m-%d %H:%M:%S")
|
||||
now = now or datetime.now()
|
||||
days = (now - end_dt).total_seconds() / 86400
|
||||
if days > OVERDUE_DAYS:
|
||||
logger.info("流程 %s 已超期:endTime=%s(%.1f 天)", process_id, end_time, days)
|
||||
return {
|
||||
"endTime": str(end_time),
|
||||
"days": int(days),
|
||||
"operator": target.get("participantName") or "",
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 签章附件(清单 + 下载) ====================
|
||||
def _ehr_resp_is_login(resp):
|
||||
"""判断响应体是否为登录页/错误 HTML(JSON/PDF/二进制流均判定为正常)。"""
|
||||
if resp is None:
|
||||
return True
|
||||
body = (resp.content or b"")[:512].lstrip().lower()
|
||||
return body.startswith(b"<!doctype") or body.startswith(b"<html")
|
||||
|
||||
|
||||
def _download_resp_is_file(resp):
|
||||
"""判断下载响应是否为真实文件流(Content-Disposition 或 %PDF 头)。"""
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
if resp.headers.get("Content-Disposition"):
|
||||
return True
|
||||
return (resp.content or b"")[:5] == b"%PDF-"
|
||||
|
||||
|
||||
def _rebuild_ehr_session(session, detail_url):
|
||||
"""EHR 会话失效时访问单据 SSO 详情链接重建会话(纯接口即可,无需浏览器)。"""
|
||||
if not detail_url:
|
||||
return False
|
||||
logger.warning("EHR 会话失效,访问单据详情链接重建会话")
|
||||
try:
|
||||
session.get(detail_url)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("重建 EHR 会话失败: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_contract_files(session, contract_file, detail_url=None):
|
||||
"""按 contract_file(逗号分隔 fileId)调 getFjkByIds 查询签章附件清单。
|
||||
|
||||
会话失效时先经 detail_url 重建 EHR 会话再重试一次。
|
||||
"""
|
||||
ids = [x.strip() for x in str(contract_file).split(",") if x.strip()]
|
||||
if not ids:
|
||||
return []
|
||||
for attempt in (1, 2):
|
||||
resp = session.request("POST", FJK_BY_IDS_URL, data={"ids": ",".join(ids)}, timeout=20)
|
||||
if resp is not None and resp.status_code == 200 and not _ehr_resp_is_login(resp):
|
||||
return resp.json().get("jsonList") or []
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
raise RuntimeError(
|
||||
f"getFjkByIds 接口响应异常: {resp.status_code if resp else '无响应'}"
|
||||
f"({((resp.text or '')[:80] if resp else '')})"
|
||||
)
|
||||
|
||||
|
||||
def _download_contract_file(session, file_id, save_dir, detail_url=None):
|
||||
"""下载单个签章附件 fileId(fjkFileDownload.mob),返回本地路径;失败返回 None。"""
|
||||
from urllib.parse import unquote
|
||||
import os
|
||||
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
download_url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||||
logger.info("下载签章附件: fileId=%s", file_id)
|
||||
resp = None
|
||||
for attempt in (1, 2):
|
||||
try:
|
||||
resp = session.request("GET", download_url, timeout=20)
|
||||
except Exception as e:
|
||||
logger.warning("签章附件请求失败(fileId=%s): %s", file_id, e)
|
||||
if _download_resp_is_file(resp):
|
||||
break
|
||||
logger.warning("签章附件响应异常(fileId=%s): HTTP %s, 内容: %s",
|
||||
file_id,
|
||||
resp.status_code if resp else "无响应",
|
||||
((resp.content or b"")[:60] if resp else b""))
|
||||
if attempt == 1 and _rebuild_ehr_session(session, detail_url):
|
||||
continue
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
else:
|
||||
try:
|
||||
raw = raw.encode('latin-1').decode('utf-8')
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
pass
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 同名文件追加 fileId 短后缀区分,避免覆盖
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("签章附件已下载: %s", path)
|
||||
return path
|
||||
|
||||
|
||||
def download_contract_files(session, contract_file, save_dir, detail_url=None):
|
||||
"""电子签完成后下载解除确认书/报酬支付确认,返回 {文件名: 本地路径};失败返回空 dict。"""
|
||||
files = get_contract_files(session, contract_file, detail_url=detail_url)
|
||||
saved = {}
|
||||
for f in files:
|
||||
fid = (f.get("id") or "").strip()
|
||||
if not fid:
|
||||
continue
|
||||
path = _download_contract_file(session, fid, save_dir, detail_url=detail_url)
|
||||
if path:
|
||||
saved[f.get("fileName") or fid] = path
|
||||
if not saved:
|
||||
logger.warning("签章附件下载为空: contract_file=%s", contract_file)
|
||||
return saved
|
||||
@@ -0,0 +1,190 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 浏览器审批层。
|
||||
|
||||
表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
提交结果依据监听的 sendWeTask 接口响应区分成功/失败(state="1" 成功,"0" 失败)。
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS, SEND_WE_TASK_MARK
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _wait_send_we_task_result(page, label, timeout=6.0):
|
||||
"""等待并捕获 sendWeTask 提交接口响应,据此区分提交成功/失败。
|
||||
|
||||
判断规则(业务接口约定):
|
||||
state="1" -> 提交成功
|
||||
state="0" -> 提交失败(页面不关闭)
|
||||
超时/监听异常未捕获到响应:提交成功后详情页会立即关闭/跳转,可能来不及监听,
|
||||
默认按成功处理(失败不会关闭页面,因此不会漏判失败)。
|
||||
"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.info("监听 sendWeTask 响应异常(页面可能已关闭),默认视为提交成功: %s", e)
|
||||
return {"action": label, "ok": "true", "message": "未捕获到 sendWeTask 响应,默认视为提交成功"}
|
||||
if req is None:
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
logger.info("监听返回非请求对象(页面可能已关闭),默认视为提交成功: %r", req)
|
||||
return {"action": label, "ok": "true", "message": "未捕获到 sendWeTask 响应,默认视为提交成功"}
|
||||
if SEND_WE_TASK_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state == "1":
|
||||
logger.info("审批提交成功(sendWeTask state=1)")
|
||||
return {"action": label, "ok": "true", "message": "提交成功(sendWeTask state=1)"}
|
||||
if state == "0":
|
||||
fail_reason = str(resp.get("meg", "")).strip() or "提交失败"
|
||||
logger.error("审批提交失败(sendWeTask state=0,原因:%s)", fail_reason)
|
||||
return {"action": label, "ok": "false", "message": fail_reason}
|
||||
return {"action": label, "ok": "true", "message": "未捕获到 sendWeTask 响应,默认视为提交成功"}
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
点击"同意"确认后监听 sendWeTask 提交接口响应区分成功/失败:
|
||||
监听响应 state="1" -> 提交成功;
|
||||
state="0" -> 提交失败(页面不关闭,必然能监听到);
|
||||
页面已关闭/超时未捕获到响应 -> 默认视为提交成功(成功才关闭页面)。
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
page.listen.start(SEND_WE_TASK_MARK)
|
||||
except Exception as e:
|
||||
logger.warning("启动 sendWeTask 监听失败,将无法识别提交结果: %s", e)
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
# 依据监听到的 sendWeTask 响应返回提交结果(成功/失败/默认成功)
|
||||
return _wait_send_we_task_result(page, label)
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 业务逻辑层。"""
|
||||
@@ -0,0 +1,326 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 校验规则层。
|
||||
|
||||
迁移自 workflows/XQ0001-0100/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py:
|
||||
- 登录态改造:SessionPage → 底座注入 requests.Session(data.hr_api 接口)
|
||||
- 日志改造:print 输出与进程退出提示 → config.logger
|
||||
- 规则逻辑(三态校验 + PDF 文书核验 + 未完成不处理)原样保留
|
||||
"""
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
from ..config import (
|
||||
logger,
|
||||
INITIATE_SIGN_MAP,
|
||||
SIGN_STATE_MAP,
|
||||
SIGN_DONE_CODE,
|
||||
LEAVEOFFICE_TYPE_MAP,
|
||||
get_attachment_dir,
|
||||
)
|
||||
from ..data.hr_api import download_contract_files
|
||||
|
||||
|
||||
def _sign_name(mapping, code):
|
||||
"""将状态编码转换为名称;空值返回空串,未知编码原样返回。"""
|
||||
if code is None or str(code).strip() == "":
|
||||
return ""
|
||||
return mapping.get(str(code).strip(), str(code))
|
||||
|
||||
|
||||
def parse_resign_e_sign_form(result):
|
||||
is_initiate = result.get("ext_is_initiate_sign")
|
||||
staff_state = result.get("ext_staff_sign_status")
|
||||
org_state = result.get("ext_org_sign_status")
|
||||
|
||||
return {
|
||||
"员工姓名": result.get("staff_name"),
|
||||
"工号": result.get("base_code"),
|
||||
"身份证号": result.get("idcard"),
|
||||
"所属事业部": result.get("belong_unit_org_name"),
|
||||
"原归属品牌": "-".join(
|
||||
v for v in (result.get("belong_unit_org_name"), result.get("dept_org_four")) if v
|
||||
),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"离职日期": result.get("leaveoffice_time"),
|
||||
"离职类型编码": result.get("leaveoffice_type"),
|
||||
"离职类型": _sign_name(LEAVEOFFICE_TYPE_MAP, result.get("leaveoffice_type")),
|
||||
"手机号": result.get("mobile_phone"),
|
||||
"合同类型": result.get("contract_type"),
|
||||
"合同开始日期": result.get("contract_start_date"),
|
||||
"合同结束日期": result.get("contract_end_date"),
|
||||
"是否已发起电子签编码": is_initiate,
|
||||
"是否已发起电子签": _sign_name(INITIATE_SIGN_MAP, is_initiate),
|
||||
"员工签署状态编码": staff_state,
|
||||
"员工签署状态": _sign_name(SIGN_STATE_MAP, staff_state),
|
||||
"企业签署状态编码": org_state,
|
||||
"企业签署状态": _sign_name(SIGN_STATE_MAP, org_state),
|
||||
}
|
||||
|
||||
|
||||
# ==================== 签章文书核验(PDF 比对表单字段) ====================
|
||||
# 1. 日期核验:报酬支付确认 / 解除确认书的识别日期 是否包含 表单实际离职日期(leaveoffice_time)
|
||||
# 2. 原因核验:解除确认书"因Xxx已于"提取的离职原因 最长匹配 离职类型 是否等于表单离职类型
|
||||
# 核验结论仅用于报告展示与人工复核,不影响审批决策。
|
||||
|
||||
|
||||
def parse_pdf(file_path):
|
||||
"""解析 PDF 并返回全文(文字型:逐页提取文本,无文本层则返回空串)。"""
|
||||
import fitz # PyMuPDF(函数内导入,避免拖慢插件启动)
|
||||
|
||||
doc = fitz.open(file_path)
|
||||
try:
|
||||
parts = []
|
||||
for page in doc:
|
||||
text = (page.get_text("text") or "").strip()
|
||||
if text:
|
||||
parts.append(text)
|
||||
return "\n".join(parts)
|
||||
finally:
|
||||
doc.close()
|
||||
|
||||
|
||||
def _norm_zh(s):
|
||||
"""只保留汉字(归一化匹配,兼容 OCR 各种标点/空格)。"""
|
||||
return re.sub(r"[^\u4e00-\u9fff]", "", s or "")
|
||||
|
||||
|
||||
# 离职类型展示文本(排除空/请选择),存 (归一化汉字, 原展示文本),按归一化长度降序做最长匹配
|
||||
_LEAVE_TEXT_SORTED = sorted(
|
||||
((_norm_zh(v), v) for v in LEAVEOFFICE_TYPE_MAP.values() if v and v != "请选择"),
|
||||
key=lambda pair: len(pair[0]),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
def extract_doc_reason(text):
|
||||
"""提取"因...已于"中间的离职原因,过滤非汉字(兼容 OCR 各种标点)。"""
|
||||
clean_text = re.sub(r"\s+", "", text)
|
||||
match = re.search(r"因(.*?)已于", clean_text)
|
||||
if not match:
|
||||
return None
|
||||
return _norm_zh(match.group(1)) or None
|
||||
|
||||
|
||||
def longest_match_leave_type(doc_reason):
|
||||
"""在离职类型展示文本列表做最长关键词匹配,返回命中的展示文本;无命中返回 None。"""
|
||||
if not doc_reason:
|
||||
return None
|
||||
norm = _norm_zh(doc_reason)
|
||||
for norm_opt, display in _LEAVE_TEXT_SORTED:
|
||||
if norm_opt and norm_opt in norm:
|
||||
return display
|
||||
return None
|
||||
|
||||
|
||||
def _extract_dates(text):
|
||||
"""提取文本中所有日期,支持 XXXX年X月X日 / XXXX-XX-XX / XXXX/XX/XX 等格式。"""
|
||||
dates = []
|
||||
patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in patterns:
|
||||
for m in re.finditer(pat, text):
|
||||
try:
|
||||
d = date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
continue
|
||||
if d not in dates:
|
||||
dates.append(d)
|
||||
return dates
|
||||
|
||||
|
||||
def _parse_form_date(value):
|
||||
"""把表单离职日期字符串(YYYY-MM-DD)解析为 date。"""
|
||||
if not value:
|
||||
return None
|
||||
m = re.match(r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?', str(value).strip())
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _find_by_name(pdf_paths, keyword):
|
||||
"""按文件名关键字从 {文件名: 路径} 中找对应的本地路径。"""
|
||||
for name, path in pdf_paths.items():
|
||||
if keyword in name:
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def verify_resign_docs(pdf_paths, resign_info):
|
||||
"""核验下载的签章文书(解除确认书 / 报酬支付确认)与表单字段是否一致。"""
|
||||
form_date = _parse_form_date(resign_info.get("离职日期"))
|
||||
form_type = resign_info.get("离职类型")
|
||||
|
||||
result = {
|
||||
"离职日期(表单)": resign_info.get("离职日期"),
|
||||
"离职类型(表单)": form_type,
|
||||
"报酬支付确认日期": None,
|
||||
"解除确认书日期": None,
|
||||
"文书离职原因": None,
|
||||
"文书命中离职类型": None,
|
||||
"日期是否一致": None,
|
||||
"原因是否一致": None,
|
||||
"is_pass": False,
|
||||
"msg": "",
|
||||
}
|
||||
issues = []
|
||||
|
||||
# ---- 日期核验:报酬支付确认 + 解除确认书 ----
|
||||
doc_dates = {}
|
||||
for keyword in ("报酬支付确认", "解除确认书"):
|
||||
path = _find_by_name(pdf_paths, keyword)
|
||||
if not path:
|
||||
issues.append(f"{keyword}文书缺失")
|
||||
continue
|
||||
try:
|
||||
dates = _extract_dates(parse_pdf(path))
|
||||
except Exception as e:
|
||||
logger.warning("解析%s失败: %s", keyword, e)
|
||||
issues.append(f"{keyword}解析失败({e})")
|
||||
continue
|
||||
result[f"{keyword}日期"] = ",".join(d.isoformat() for d in dates) or None
|
||||
doc_dates[keyword] = dates
|
||||
|
||||
if doc_dates:
|
||||
if form_date is not None:
|
||||
all_ok = True
|
||||
for keyword, dates in doc_dates.items():
|
||||
if form_date not in dates:
|
||||
all_ok = False
|
||||
issues.append(
|
||||
f"{keyword}日期[{result[f'{keyword}日期']}]≠表单离职日期[{form_date.isoformat()}]"
|
||||
)
|
||||
result["日期是否一致"] = all_ok
|
||||
else:
|
||||
issues.append("表单无离职日期,无法核验日期")
|
||||
else:
|
||||
issues.append("未获取到任何文书日期,无法核验日期")
|
||||
|
||||
# ---- 原因核验:解除确认书 ----
|
||||
relieve_path = _find_by_name(pdf_paths, "解除确认书")
|
||||
if relieve_path:
|
||||
try:
|
||||
reason = extract_doc_reason(parse_pdf(relieve_path))
|
||||
except Exception as e:
|
||||
logger.warning("解析解除确认书失败: %s", e)
|
||||
reason = None
|
||||
issues.append(f"解除确认书解析失败({e})")
|
||||
hit = longest_match_leave_type(reason)
|
||||
result["文书离职原因"] = reason
|
||||
result["文书命中离职类型"] = hit
|
||||
if hit and form_type:
|
||||
result["原因是否一致"] = (hit == form_type)
|
||||
if hit != form_type:
|
||||
issues.append(f"解除确认书原因[{hit}]≠表单离职类型[{form_type}]")
|
||||
elif not form_type:
|
||||
issues.append("表单无离职类型,无法核验原因")
|
||||
else:
|
||||
issues.append(f"解除确认书未命中任何离职类型(原因[{reason}])")
|
||||
|
||||
result["is_pass"] = result["日期是否一致"] is True and result["原因是否一致"] is True
|
||||
result["msg"] = ";".join(issues) if issues else "核验通过(日期与原因均与表单一致)"
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 离职电子签校验规则 ====================
|
||||
def _is_done(value):
|
||||
"""判断电子签状态编码是否为已完成(编码为字符串 "2")。"""
|
||||
return value is not None and str(value).strip() == SIGN_DONE_CODE
|
||||
|
||||
|
||||
def validate_doc(doc, session):
|
||||
"""
|
||||
校验单张离职电子签单据,返回审批决策(通过 / 未完成 / 失败)。
|
||||
|
||||
三者(是否已发起电子签/员工签署状态/企业签署状态)均已完成 -> 下载签章附件并核验文书:
|
||||
核验通过 -> 通过(同意);否则 -> 未完成(不管,留待人工复核)。
|
||||
三状态未全部完成 -> 未完成(不管,留给待办继续流转)。
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
resign_info = parse_resign_e_sign_form(form_data)
|
||||
|
||||
is_initiate = form_data.get("ext_is_initiate_sign")
|
||||
staff_state = form_data.get("ext_staff_sign_status")
|
||||
org_state = form_data.get("ext_org_sign_status")
|
||||
|
||||
result = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "未完成",
|
||||
"note": "",
|
||||
"resign_info": resign_info,
|
||||
}
|
||||
|
||||
def _label(value, mapping_name):
|
||||
"""取状态名称,缺失时回退为原始值/未知,便于人工判断。"""
|
||||
return resign_info.get(mapping_name) or (str(value).strip() if value is not None else "未知")
|
||||
|
||||
if all(_is_done(v) for v in (is_initiate, staff_state, org_state)):
|
||||
# 三状态均已完成:下载签章附件并核验文书。
|
||||
# 审批决策须「电子签三状态 + 文书核验」全部满足才通过;任一不满足均不审批。
|
||||
verify_result = None
|
||||
try:
|
||||
files = download_contract_files(
|
||||
session, form_data.get("contract_file"),
|
||||
save_dir=get_attachment_dir(),
|
||||
detail_url=doc.get("detail_url"),
|
||||
)
|
||||
if files:
|
||||
result["签章附件"] = " | ".join(f"{name}->{path}" for name, path in files.items())
|
||||
try:
|
||||
verify_result = verify_resign_docs(files, resign_info)
|
||||
except Exception as e:
|
||||
logger.warning("核验离职电子签文书失败[%s]: %s", doc.get("title", ""), e)
|
||||
verify_result = {"is_pass": False, "msg": f"文书核验失败: {e}"}
|
||||
result["文书核验"] = verify_result
|
||||
else:
|
||||
# 兜底:三状态均已完成却拿不到附件(接口异常/签署记录缺失),按失败处理,
|
||||
# 避免"已完成却无附件"被混入常规"未完成"而漏查
|
||||
result["签章附件"] = "无(未查询到签章附件)"
|
||||
result["decision"] = "失败"
|
||||
result["note"] = "电子签三状态均已完成,但未查询到签章附件,无法核验文书,需人工排查"
|
||||
logger.warning("三状态已完成但未查询到签章附件[%s]: contract_file=%s",
|
||||
doc.get("title", ""), form_data.get("contract_file"))
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.warning("下载离职电子签签章附件失败[%s]: %s", doc.get("title", ""), e)
|
||||
result["签章附件"] = f"下载失败: {e}"
|
||||
result["decision"] = "失败"
|
||||
result["note"] = f"电子签三状态均已完成,但签章附件下载失败,需人工排查: {e}"
|
||||
return result
|
||||
|
||||
if verify_result is not None and verify_result.get("is_pass"):
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
"审批通过(电子签三状态均为已完成,且文书核验通过:"
|
||||
"报酬支付确认/解除确认书日期与离职原因均与表单一致)"
|
||||
)
|
||||
else:
|
||||
result["decision"] = "未完成"
|
||||
result["note"] = (
|
||||
"电子签三状态均已完成,但文书核验未通过,暂不审批待人工复核:"
|
||||
f"{verify_result.get('msg', '') if verify_result else '核验结果缺失'}"
|
||||
)
|
||||
logger.info("核验不通过单据[%s] %s: %s",
|
||||
doc.get("title", ""), resign_info.get("员工姓名", ""),
|
||||
verify_result.get("msg", "") if verify_result else "核验结果缺失")
|
||||
else:
|
||||
result["decision"] = "未完成"
|
||||
result["note"] = (
|
||||
f"电子签未全部完成,暂不处理(是否已发起电子签: {_label(is_initiate, '是否已发起电子签')},"
|
||||
f"员工签署状态: {_label(staff_state, '员工签署状态')},"
|
||||
f"企业签署状态: {_label(org_state, '企业签署状态')})"
|
||||
)
|
||||
logger.info("未完成单据[%s] %s: 发起=%s, 员工=%s, 企业=%s",
|
||||
doc.get("title", ""), resign_info.get("员工姓名", ""),
|
||||
is_initiate, staff_state, org_state)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0020",
|
||||
"name": "EHR系统离职电子签流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 离职电子签待办:拉取待办与表单,按是否已发起电子签、员工/企业签署状态三态校验;三态均已完成则下载签章附件(解除确认书/报酬支付确认)并核验日期与离职原因是否与表单一致,全部通过自动提交审批;同时检查「完善信息(操作人)」节点超期名单,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0020"],
|
||||
"permissions": {"platforms": ["hr"]},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\离职电子签流程审核",
|
||||
"description": "审批报告与签章附件(附件/ 子目录)统一存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总、提交失败与超期名单推送到钉钉群机器人"
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string",
|
||||
"title": "推送环境",
|
||||
"default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出接口返回等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 报告与推送层。"""
|
||||
@@ -0,0 +1,230 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 钉钉群机器人推送(插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,206 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0020 EHR系统离职电子签流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
"""员工姓名:优先取表单里的员工姓名,缺失时回退到发起人。"""
|
||||
info = r.get("resign_info", {}) or {}
|
||||
return info.get("员工姓名") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 resign_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("员工姓名", "员工姓名"),
|
||||
("工号", "工号"),
|
||||
("所属事业部", "所属事业部"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("岗位", "岗位"),
|
||||
("离职日期", "离职日期"),
|
||||
("离职类型", "离职类型"),
|
||||
("合同类型", "合同类型"),
|
||||
("合同开始日期", "合同开始日期"),
|
||||
("合同结束日期", "合同结束日期"),
|
||||
("是否已发起电子签", "是否已发起电子签"),
|
||||
("员工签署状态", "员工签署状态"),
|
||||
("企业签署状态", "企业签署状态"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def _format_verify(verify):
|
||||
"""将文书核验结果格式化为易读摘要行。"""
|
||||
if not verify:
|
||||
return ""
|
||||
parts = [f"文书核验: {'通过' if verify.get('is_pass') else '不通过'}"]
|
||||
if verify.get("msg"):
|
||||
parts.append(str(verify["msg"]))
|
||||
for key in ("离职日期(表单)", "报酬支付确认日期", "解除确认书日期", "文书离职原因", "文书命中离职类型"):
|
||||
val = verify.get(key)
|
||||
if val:
|
||||
parts.append(f"{key}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""
|
||||
生成离职电子签审批报告:汇总行 + 每条明细 + 未完成待跟进清单(+提交失败/处理失败)。
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
pending = [r for r in results if r.get("decision") == "未完成"]
|
||||
submit_failed = [r for r in results if r.get("submit_ok") == "false"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},未完成待跟进 {len(pending)}"
|
||||
if submit_failed:
|
||||
summary += f",提交失败待跟进 {len(submit_failed)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"离职电子签审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("resign_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({info.get('工号', '')})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("签章附件"):
|
||||
lines.append(f" 签章附件: {r['签章附件']}")
|
||||
if r.get("文书核验"):
|
||||
lines.append(f" {_format_verify(r['文书核验'])}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 未完成(不管)待跟进清单 -----
|
||||
if pending:
|
||||
lines.append("《离职电子签未完成待跟进清单》")
|
||||
lines.append("(电子签未全部完成,或文书核验未通过,机器不处理,待后续流转/人工复核)")
|
||||
for i, r in enumerate(pending, 1):
|
||||
info = r.get("resign_info", {}) or {}
|
||||
note = r.get("note") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(
|
||||
f"{i}. 员工姓名: {_name(r)} | "
|
||||
f"发起: {info.get('是否已发起电子签', '未知')} | "
|
||||
f"员工: {info.get('员工签署状态', '未知')} | "
|
||||
f"企业: {info.get('企业签署状态', '未知')} | "
|
||||
f"原因: {note} | 详情页链接: {url}"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批结论通过但自动提交失败(OA 中未生效,需人工跟进) -----
|
||||
if submit_failed:
|
||||
lines.append("《离职电子签审批通过但提交失败待人工跟进清单》")
|
||||
lines.append("(审批结论为通过,但 sendWeTask 提交未成功,OA 中状态未变,待人工跟进处理)")
|
||||
for i, r in enumerate(submit_failed, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
action = r.get("审批动作") or "-"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 审批动作: {action} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_resign_block(r):
|
||||
"""将单条离职电子签审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("resign_info", {}) or {}
|
||||
name = info.get("员工姓名") or r.get("creator") or "未知"
|
||||
code = info.get("工号") or ""
|
||||
lines = [f"**🔹 {name}**" + (f"(工号 {code})" if code else "")]
|
||||
post = info.get("岗位") or ""
|
||||
if post:
|
||||
lines.append(f"> 岗位:{post}")
|
||||
for key, label in (("是否已发起电子签", "发起"), ("员工签署状态", "员工"), ("企业签署状态", "企业")):
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
action = r.get("审批动作")
|
||||
if action:
|
||||
lines.append(f"> 审批动作:{action}({r.get('审批结果', '')})")
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
if reason:
|
||||
lines.append(f"> 备注:{reason}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 markdown 中单换行会被合并成一个段落,块内各行之间须用双换行分隔
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
生成块格式 Markdown 推送分组(精简推送)。
|
||||
|
||||
推送规则:
|
||||
- 仅"通过但提交失败"单独推送明细(需人工跟进);
|
||||
- 通过/未完成/处理失败 不单独推送明细,只在汇总中统计数量;
|
||||
- 汇总消息始终推送。
|
||||
|
||||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]}。
|
||||
"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过" and r.get("submit_ok") != "false"]
|
||||
submit_failed = [r for r in results if r.get("submit_ok") == "false"]
|
||||
pending = [r for r in results if r.get("decision") == "未完成"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not submit_failed and not pending and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
if submit_failed:
|
||||
blocks = [_format_resign_block(r) for r in submit_failed]
|
||||
messages.append({"title": f"【{subject}审批】通过但提交失败,需人工跟进", "blocks": blocks})
|
||||
|
||||
# 汇总消息:本次审批各类别数量(一条,含 0 的类别)
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("未完成待跟进", len(pending)),
|
||||
("通过但提交失败", len(submit_failed)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/离职电子签审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"离职电子签审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,3 @@
|
||||
requests
|
||||
DrissionPage
|
||||
PyMuPDF
|
||||
@@ -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>EHR系统离职电子签流程审核</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0020-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,484 @@
|
||||
<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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<path d="M14 2v6h6" />
|
||||
<path d="m9 15 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>
|
||||
|
||||
<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.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\人资\离职电子签流程审核" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">审批报告保存为「离职电子签审批报告_时间戳.txt」,签章附件(解除确认书/报酬支付确认)下载到其下「附件」子目录。</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">
|
||||
<el-form-item label="自动提交审批">
|
||||
<el-switch v-model="form.approve_enabled" :disabled="running"
|
||||
active-text="校验通过自动点同意" inactive-text="仅校验不提交" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉群推送">
|
||||
<el-switch v-model="form.push_enabled" :disabled="running"
|
||||
active-text="推送汇总与提交失败/超期名单" inactive-text="不推送" />
|
||||
</el-form-item>
|
||||
<el-form-item label="推送环境">
|
||||
<el-radio-group v-model="form.push_env" :disabled="running || !form.push_enabled">
|
||||
<el-radio value="dev">测试群</el-radio>
|
||||
<el-radio value="prod">生产群</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉 Webhook">
|
||||
<el-input v-model="form.dingtalk_webhook" :disabled="running || !form.push_enabled" clearable
|
||||
placeholder="留空 = 内置默认机器人;发其他群时填完整地址" />
|
||||
</el-form-item>
|
||||
<el-form-item label="钉钉加签密钥">
|
||||
<el-input v-model="form.dingtalk_secret" :disabled="running || !form.push_enabled" clearable
|
||||
placeholder="留空 = 不加签" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running"
|
||||
active-text="输出接口返回等调试信息" inactive-text="关闭" />
|
||||
</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="checks static">
|
||||
<div v-for="c in RULES" :key="c.num" class="check-tile">
|
||||
<span class="tile-num">{{ c.num }}</span>
|
||||
<span class="tile-label">{{ c.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tip">仅「通过」的单据会自动提交审批;未完成(不管)与提交失败的单据保留待办并写入报告与钉钉推送,由人工跟进;完善信息(操作人)完成超 3 天的流程另行记入超期名单推送。</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'
|
||||
|
||||
// 校验规则(与后端 logic/resign_rules.py 一一对应,仅展示说明)
|
||||
const RULES = [
|
||||
{ num: '1', label: '三态校验:是否已发起电子签、员工签署状态、企业签署状态均须为「已完成」' },
|
||||
{ num: '2', label: '文书核验:三态完成后下载解除确认书/报酬支付确认,比对 PDF 中日期与离职原因是否与表单一致' },
|
||||
{ num: '3', label: '核验通过 → 自动同意;未完成/文书核验不通过 → 不管,待后续流转或人工复核' },
|
||||
{ num: '4', label: '超期检查:「完善信息(操作人)」节点完成超 3 天仍未走完的流程,记入超期名单' },
|
||||
]
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
save_dir: 'D:\\资料\\人资\\离职电子签流程审核',
|
||||
approve_enabled: true,
|
||||
push_enabled: true,
|
||||
push_env: 'dev',
|
||||
dingtalk_webhook: '',
|
||||
dingtalk_secret: '',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (form.push_enabled && form.dingtalk_webhook && !/^https?:\/\//.test(form.dingtalk_webhook)) {
|
||||
ElMessage.warning('钉钉 Webhook 应为 http(s):// 开头的完整地址,或留空使用内置机器人')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
// 仅提交后端 run() 读取的字段
|
||||
buildPayload(f) {
|
||||
return {
|
||||
save_dir: f.save_dir,
|
||||
approve_enabled: f.approve_enabled,
|
||||
push_enabled: f.push_enabled,
|
||||
push_env: f.push_env,
|
||||
dingtalk_webhook: f.dingtalk_webhook,
|
||||
dingtalk_secret: f.dingtalk_secret,
|
||||
debug_mode: f.debug_mode,
|
||||
}
|
||||
},
|
||||
})
|
||||
</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: 16px 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%;
|
||||
}
|
||||
.wide {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---------- 检查项说明(静态,只读) ---------- */
|
||||
.checks {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.check-tile {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
background: var(--el-fill-color-blank);
|
||||
}
|
||||
.tile-num {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
background: var(--el-color-primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tile-label {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.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 = 'xq0020'
|
||||
@@ -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,340 @@
|
||||
// 插件 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
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 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
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
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/xq0020/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0020/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5185,
|
||||
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>EHR系统离职电子签流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0020/assets/index-DoIzG_Ps.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0020/assets/index-5lKkQyP3.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user