feat: 完成插件管理系统产品化P0闭环落地

此提交实现完整的插件管理产品化闭环:
1. 中心机新增Ed25519密钥、审计/运行上报表、插件扩展字段,实现票据/管控清单签发、鉴权下载能力
2. 部署端新增设备级单活调度器、用户私有插件库、离线/联网校验链、插件下载安装流程
3. 控制面与部署前端同步更新UI与接口适配,新增审计页、插件管理增强功能
4. 修复两个工作流脚本的过滤与Excel导出问题,优化打包依赖与日志面板
5. 新增完整架构设计与实施文档
This commit is contained in:
2026-09-11 09:08:40 +08:00
parent 863f818740
commit 81c456c35a
51 changed files with 11037 additions and 6237 deletions
+283
View File
@@ -0,0 +1,283 @@
# -*- coding: utf-8 -*-
"""部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
职责(对应架构设计七、八节):
- 以 %LOCALAPPDATA%\\37duAutomation 为根,缓存:
license.json (离线授权票据,Ed25519 签名,离线一直有效)
control.json (管控清单缓存:revoked/disabled/forcedUpdates + updatedAt)
keys\\pub.pem (中心机公钥,首次联网拉取缓存,供离线验签)
- is_online() —— 收敛的单一联网判定:最近一次成功拉取/心跳时间戳 + 失败二次确认。
离线只豁免「强制更新 deadline」,票据验签/授权/下架禁用离线仍生效。
- verify_license() / verify_control() —— 用缓存公钥离线验签。
- report() —— 运行上报到中心机(联网时实时上报;离线记录暂存,重连后补报)。
"""
from __future__ import annotations
import base64
import json
import logging
import os
import time
from datetime import datetime
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
_LOGGER = logging.getLogger(__name__)
# 数据根目录:与影刀版共享 %LOCALAPPDATA%\37duAutomation
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
or Path.home(), "37duAutomation")
KEYS_DIR = _APP_DATA / "keys"
license_path = _APP_DATA / "license.json"
control_path = _APP_DATA / "control.json"
reports_path = _APP_DATA / "offline_reports.jsonl" # 离线上报暂存,重连后补报
# 联网判定阈值:超过此秒数未成功拉取/心跳即视为离线
_ONLINE_TTL = 180
_last_sync = 0.0
_sync_lock = None # 由 import 后注入 threading.Lock(避免循环依赖按模块初始化)
_CONTROLPLANE_URL = "" # 由 main.py 注入
def init(controlplane_url: str, sync_lock) -> None:
"""注入控制面地址与同步锁(main.py 启动时调用)。"""
global _CONTROLPLANE_URL, _sync_lock
_CONTROLPLANE_URL = (controlplane_url or "").rstrip("/")
_sync_lock = sync_lock
_APP_DATA.mkdir(exist_ok=True)
KEYS_DIR.mkdir(exist_ok=True)
# ==================== 联网判定 ====================
def touch_sync() -> None:
"""标记最近一次与控制面成功同步的时点(拉票/清单/心跳成功后调用)。"""
global _last_sync
with _sync_lock:
_last_sync = time.time()
def is_online() -> bool:
"""收敛的单一联网判定:默认联网(无缓存/从未同步视联网),最大 _ONLINE_TTL 未同步判离线。"""
with _sync_lock:
return (time.time() - _last_sync) <= _ONLINE_TTL
# ==================== 公钥缓存与验签 ====================
def _pub_pem_path() -> Path:
return KEYS_DIR / "pub.pem"
def cache_public_key(pem_text: str) -> None:
"""缓存中心机公钥(首次联网拉取)。用于后续离线验签。"""
pem_text = (pem_text or "").strip()
if not pem_text:
return
_pub_pem_path().write_text(pem_text, encoding="ascii")
touch_sync()
def _load_public_key() -> Ed25519PublicKey | None:
try:
return serialization.load_pem_public_key(_pub_pem_path().read_bytes())
except Exception: # noqa: BLE001 无缓存/损坏视为无公钥
return None
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
"""验签返回 payload;签名非法抛 ValueError。"""
if "." not in blob:
raise ValueError("bad blob")
b64, sig64 = blob.rsplit(".", 1)
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
if len(sig) != 64:
raise ValueError("bad signature len")
pub.verify(sig, canon)
return json.loads(canon)
def verify_license() -> dict:
"""验签本地缓存授权票据,返回 payload;无缓存/验签失败抛异常。"""
if not license_path.is_file():
raise ValueError("无本地授权票据(license.json)")
pub = _load_public_key()
if pub is None:
raise ValueError("缺少中心机公钥,无法验签授权票据")
data = json.loads(license_path.read_text(encoding="utf-8"))
return _verify_blob(data["ticket"], pub)
def verify_control() -> dict:
"""验签本地缓存管控清单,返回 payload;无缓存时返回空管控(不禁止任何插件)。"""
if not control_path.is_file():
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
pub = _load_public_key()
if pub is None:
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
try:
data = json.loads(control_path.read_text(encoding="utf-8"))
payload = _verify_blob(data["ticket"], pub)
return payload if isinstance(payload, dict) else {}
except Exception: # noqa: BLE001 缓存损坏按"不禁止"兜底,联网后会重新拉取
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
# ==================== 缓存写读 ====================
def save_license(ticket_json: dict | str) -> None:
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
if isinstance(ticket_json, dict):
text = json.dumps(ticket_json, ensure_ascii=False)
else:
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
license_path.write_text(text, encoding="utf-8")
touch_sync()
def save_control(ticket_json: dict | str) -> None:
"""持久化管控清单缓存。"""
if isinstance(ticket_json, dict):
text = json.dumps(ticket_json, ensure_ascii=False)
else:
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
control_path.write_text(text, encoding="utf-8")
touch_sync()
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
- 验签授权票据,校验该插件 canRun。
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
"""
control = verify_control()
if plugin_id in control.get("revokedPlugins", []):
return "插件已被下架(revoked),禁止运行"
if plugin_id in control.get("disabledPlugins", []):
return "插件已被禁用(disabled),禁止运行"
# 授权:先验签本地授权票据(离线可用)
try:
lic = verify_license()
except Exception as _exc: # noqa: BLE001 授权票据不可用
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
grant = lic_plugins.get(plugin_id)
if not grant:
return f"账号 {account} 无插件「{plugin_id}」的授权"
if not grant.get("canRun"):
return f"账号 {account} 无「{plugin_id}」的运行授权"
# 强制更新:仅联网时严格校验 deadline;离线跳过(核心规则)
if online:
forced = next((f for f in control.get("forcedUpdates", [])
if f.get("pluginId") == plugin_id), None)
if forced:
min_ver = forced.get("minVersion", "")
deadline = forced.get("deadline", "")
if min_ver and deadline and _deadline_passed(deadline):
installed = _installed_version(plugin_id)
if installed and _version_lt(installed, min_ver):
return (f"插件需强制升级到 v{min_ver} 以上(deadline 已过),"
f"当前 v{installed} 已禁止启动,请先更新")
return None
def _installed_version(plugin_id: str) -> str:
"""读取本机当前已装版本(active.json 或插件目录)。有则不返回最新,供强制更新判断。"""
act = _APP_DATA / "active.json"
try:
d = json.loads(act.read_text(encoding="utf-8")) if act.is_file() else {}
return d.get("version", "") if d.get("pluginId") == plugin_id else ""
except Exception: # noqa: BLE001
return ""
def _deadline_passed(deadline: str) -> bool:
try:
dt = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
return datetime.now(dt.tzinfo) > dt
except Exception: # noqa: BLE001
# 解析失败时按未过期兜底(不误伤在线用户)
return False
def _version_lt(a: str, b: str) -> bool:
"""版本比较:数字段按 int,非数字段按 str 小写。"""
def _k(s):
try:
return (1, int(s))
except ValueError:
return (0, str(s).lower())
return tuple(_k(x) for x in str(a).split(".")) < tuple(_k(x) for x in str(b).split("."))
# ==================== 运行上报 ====================
def report(account: str, device_id: str, plugin_id: str, version: str,
status: str, msg: str = "", duration_sec: int = 0) -> None:
"""运行上报:联网实时 POST;离线暂存 jsonl,重连后补报。失败不阻断主流程。"""
rec = {"account": account, "device_id": device_id, "plugin_id": plugin_id,
"version": version, "status": status, "msg": msg,
"duration_sec": int(duration_sec),
"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
if not _CONTROLPLANE_URL:
return
if _push_report(rec):
touch_sync()
return
# 离线:暂存待补报
try:
with open(reports_path, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
except OSError:
pass
def _push_report(rec: dict) -> bool:
"""同步上报一条到中心机;成功返回 True。"""
try:
_push_via_tempfile(rec) # 用 go-offset 方式直连
return True
except Exception: # noqa: BLE001
return False
def _push_via_tempfile(rec: dict) -> None:
"""向 /api/runtime/report 的同步 POST(requests)。"""
import requests
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
json=rec, timeout=5)
r.raise_for_status()
def flush_offline_reports() -> int:
"""重连后补报此前暂存的离线记录;返回补报条数。"""
if not reports_path.is_file():
return 0
sent = 0
pending = []
try:
lines = [l for l in reports_path.read_text(encoding="utf-8").splitlines() if l.strip()]
for ln in lines:
try:
rec = json.loads(ln)
except ValueError:
continue
try:
_push_via_tempfile(rec)
sent += 1
except Exception: # noqa: BLE001
pending.append(ln) # 仍失败则保留下次再补
if not pending:
reports_path.unlink(missing_ok=True) # 全部成功则清空
else:
reports_path.write_text("\n".join(pending) + "\n", encoding="utf-8")
except OSError:
pass
return sent
+270 -5
View File
@@ -25,9 +25,13 @@ from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from urllib.parse import urlencode
from webhost.backend import auth as platform_auth
from webhost.backend import licensing
from webhost.backend import scheduler as _scheduler
from webhost.backend import winjob as _winjob
from webhost.backend.hub import HUB
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
@@ -64,6 +68,10 @@ PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
@@ -183,6 +191,30 @@ def _cp_call(method: str, path: str, **kw) -> dict:
return body
# ==================== 产品化:离线授权同步 + 单活调度终止注册表 ====================
def _sync_licensing(account: str) -> None:
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
"""
if not CONTROLPLANE_URL or not account:
return
import requests
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
r = requests.get(f"{CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
r.raise_for_status()
licensing.cache_public_key(r.json().get("pub", ""))
r = requests.get(f"{CONTROLPLANE_URL}/api/me/license",
params={"account": account}, headers=headers, timeout=5)
r.raise_for_status()
licensing.save_license(r.json())
r = requests.get(f"{CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
r.raise_for_status()
licensing.save_control(r.json())
licensing.flush_offline_reports()
@asynccontextmanager
async def lifespan(app: FastAPI):
HUB.bind(asyncio.get_running_loop())
@@ -190,6 +222,15 @@ async def lifespan(app: FastAPI):
global ALLOWED
ALLOWED = _resolve_allowed()
load_plugins(ALLOWED)
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
licensing.init(CONTROLPLANE_URL, threading.Lock())
_scheduler.init_active()
if CONTROLPLANE_URL:
try:
_sync_licensing(CONTROLPLANE_ACCOUNT)
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", CONTROLPLANE_ACCOUNT)
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
yield
@@ -231,9 +272,135 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
with _SESS_LOCK:
_SESS[token] = (b.account.strip(), time.time())
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
if CONTROLPLANE_URL:
try:
_sync_licensing(b.account.strip())
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {**r, "account": b.account.strip()}
class _DingTalkIn(BaseModel):
account: str # 钉钉工号(作为统一账号)
nickname: str = "" # 钉钉姓名
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
@app.post("/api/admin/dingtalk/login")
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
if not d.account:
raise HTTPException(400, "工号不能为空")
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
"""
r = _cp_call(
"POST", "/api/admin/dingtalk/auth",
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
acct = r.get("account") or account
token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[token] = (acct, time.time())
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
if CONTROLPLANE_URL:
try:
_sync_licensing(acct)
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
class _InlineIn(BaseModel):
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
@app.post("/api/admin/dingtalk/inline")
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
"""
if not d.code.strip():
raise HTTPException(400, "缺少扫码截图码")
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
info = _cp_call(
"POST", "/api/admin/dingtalk/sns",
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
json={"code": d.code.strip()})
account = (info.get("account") or "").strip()
if not account:
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
@app.get("/api/admin/dingtalk/inline_qr")
def admin_dingtalk_inline_qr(request: Request) -> dict:
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return _cp_call(
"GET", "/api/admin/dingtalk/inline_qr",
params={"back": back},
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}))
# ==================== 钉钉真实扫码:扫码URL + 静默回调页 ====================
# 扫码 URL 指向中心机 /api/admin/dingtalk/scan(back 回跳到本机 /cb);
# 扫码成功 → 中心机 /cb 302 回本机 /cb?account=&nickname= → 本页静默调 dingtalk/login 建会话
# → 刷新父窗口(登录完成)。身份源为钉钉+中心机(可信),与账号密码登录同会话机制。
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
<script>
(async function(){
var q = new URLSearchParams(location.search);
var account = q.get('account') || '';
var nickname = q.get('nickname') || '';
if (account) {
try {
await fetch('/api/admin/dingtalk/login', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({ account: account, nickname: nickname })
});
} catch (e) {}
}
try { window.opener && window.opener.location.reload(); } catch (e) {}
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
})();
</script></body></html>"""
@app.get("/api/admin/dingtalk/qr")
def dingtalk_qr(request: Request) -> dict:
"""返回中心机扫码登录 URL。
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
"""
if not CONTROLPLANE_URL:
return {"url": ""}
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return {"url": f"{CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
@app.get("/api/admin/dingtalk/cb")
def dingtalk_cb() -> HTMLResponse:
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
return HTMLResponse(_DINGTALK_CB_HTML)
@app.post("/api/admin/logout")
def admin_logout(request: Request, response: Response) -> dict:
"""登出:清除会话 cookie 与内存会话。"""
@@ -264,9 +431,59 @@ def admin_overview(request: Request) -> dict:
def _plugin_schema(p) -> dict:
return {"id": p.id, "name": p.name, "version": p.version,
"description": p.description, "uses_month": getattr(p, "uses_month", False),
"fields": p.fields}
"""组装插件元数据(manifest 驱动)。
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
"""
manifest = _read_own_manifest(p)
name = (manifest or {}).get("name") or p.name
description = (manifest or {}).get("description")
if description is None:
description = p.description
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
if fields is None:
fields = p.fields
caps = (manifest or {}).get("capabilities") or p.capabilities
perms = (manifest or {}).get("permissions") or p.permissions
return {"id": p.id, "name": name, "version": p.version,
"description": description, "uses_month": getattr(p, "uses_month", False),
"capabilities": caps, "permissions": perms, "fields": fields}
def _read_own_manifest(p) -> dict | None:
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
try:
mod = sys.modules.get(type(p).__module__)
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
if not jar or not jar.is_file():
return None
return json.loads(jar.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return None
def _fields_from_schema(schema: dict) -> list | None:
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
if not schema or schema.get("type") != "object" or not schema.get("properties"):
return None
out = []
for key, prop in schema["properties"].items():
item = {"key": key, "label": prop.get("title", key),
"default": prop.get("default", "")}
t = prop.get("type", "string")
if t == "integer" or t == "number":
item["type"] = "int"
elif t == "string" and "enum" in prop:
item["type"] = "select"
item["options"] = prop["enum"]
else:
item["type"] = "text"
d = prop.get("description")
if d:
item["description"] = d
out.append(item)
return out
def _account_allowed_platforms(account: str) -> set | None:
@@ -296,7 +513,14 @@ def meta(request: Request) -> dict:
# 已登录时按账号白名单;未登录/中心机不可达默认展示
"allowed": (pid in allowed) if allowed is not None else True}
for pid, m in PLATFORMS.items()]
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
return {
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
"controlplane": CONTROLPLANE_URL,
"appName": "37du 业务场景工具集",
"dingtalkScan": bool(DINGTALK_APP_KEY),
"platforms": platforms,
"plugins": plugins,
}
@app.post("/api/platforms/{pid}/login")
@@ -429,9 +653,28 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
_set_run(run_id, status="error", result=None, error=msg)
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
finally:
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
def _report_run(plugin_id: str, run_id: str) -> None:
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
try:
with RUN_LOCK:
run = RUNS.get(run_id) or {}
account = run.get("account", "")
status = "done" if run.get("status") == "done" else \
("running" if run.get("status") == "running" else "error")
msg = run.get("error") or ""
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
licensing.report(account=account, device_id="",
plugin_id=plugin_id, version=run.get("version", ""),
status=status, msg=msg, duration_sec=duration)
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
_LOGGER.warning("运行上报失败:%s", _exc)
@app.post("/api/runs", status_code=202)
def start_run(req: RunReq, request: Request) -> dict:
account = _require_login(request)
@@ -439,14 +682,24 @@ def start_run(req: RunReq, request: Request) -> dict:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
raise HTTPException(404, "插件不存在")
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
online = licensing.is_online()
deny = licensing.run_check_allowed(plugin.id, account, online)
if deny:
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
raise HTTPException(403, deny)
run_id = uuid.uuid4().hex
with RUN_LOCK:
if len(RUNS) >= MAX_RUNS:
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
RUNS[run_id] = {"status": "running", "account": account,
"version": getattr(plugin, "version", "0"),
"started": time.time(),
"result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
licensing.report(account=account, device_id="", plugin_id=plugin.id,
version=getattr(plugin, "version", "0"), status="start")
def _queued():
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
@@ -456,7 +709,19 @@ def start_run(req: RunReq, request: Request) -> dict:
"level": "INFO",
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
with gate:
_run_target(plugin, req.fields, run_id)
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
if _scheduler._is_busy():
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "INFO",
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
def _start(_run_id):
threading.Thread(target=_run_target,
args=(plugin, req.fields, _run_id),
daemon=True, name=f"exec-{plugin.id}").start()
return _run_id
_scheduler.request_start(account, plugin.id,
getattr(plugin, "version", "0"), _start)
threading.Thread(target=_queued, daemon=True,
name=f"run-{plugin.id}").start()
+4
View File
@@ -54,6 +54,10 @@ class ScenePlugin:
# 表单字段定义:[{key,label,type,default,options}]
# type ∈ int | text | select
fields: List[dict] = []
# 声明式能力/权限(manifest 驱动):与插件包 plugin.json 保持一致;
# 缺省场景可用本地类补充,plugin.json 存在时以其为权威。
capabilities: List[str] = []
permissions: dict = {}
def run(self, fields: dict, ctx: RunContext) -> dict:
raise NotImplementedError(f"插件 {self.id} 未实现 run")
@@ -0,0 +1,24 @@
{
"schema_version": 1,
"id": "seal_check",
"name": "考勤月报封存检查",
"version": "1.0.0",
"description": "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告",
"category": "考勤",
"icon": "",
"platform": "hr",
"uses_month": true,
"capabilities": ["seal_check", "hr.seal_check"],
"permissions": {
"platforms": ["hr"]
},
"fields": {
"type": "object",
"properties": {
"fixed_rest_days": { "type": "integer", "title": "固休应休天数", "default": 5, "description": "" },
"size_rest_days": { "type": "integer", "title": "大小休应休天数", "default": 6, "description": "" },
"quota_rest_days": { "type": "integer", "title": "限额排休上限", "default": 8, "description": "" }
},
"required": []
}
}
+112
View File
@@ -0,0 +1,112 @@
# -*- coding: utf-8 -*-
"""设备级单活调度器:整机同一时刻只运行一个插件进程。
- active.json 记录设备级当前运行 {userId, pluginId, version, status, startedAt}。
- 模块级锁 + 磁盘状态双重保证单活:同一时刻只有一个插件在跑,与用户无关。
- 用户切换插件/切换用户 = 停旧插件(整树终止) → 清理 → 启动新插件 → 健康检查 → 激活;
启动失败回滚到"空闲",不让半激活状态阻塞后续启动。
"""
from __future__ import annotations
import json
import logging
import os
import subprocess
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
_LOGGER = logging.getLogger(__name__)
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
or Path.home(), "37duAutomation")
ACTIVE_PATH = _APP_DATA / "active.json"
# 全局单活条件变量:同一时刻只能有一个插件进程。请求先等待当前插件执行完成(完全不能并发)。
_SCHED_COND = threading.Condition()
def init_active() -> None:
"""初始化 active.json(无则写入空闲态),并确保数据目录可写。"""
_APP_DATA.mkdir(exist_ok=True)
if not ACTIVE_PATH.is_file():
write_active(user="", plugin="", version="", status="idle")
def read_active() -> dict:
try:
d = json.loads(ACTIVE_PATH.read_text(encoding="utf-8")) if ACTIVE_PATH.is_file() else {}
return d if isinstance(d, dict) else {}
except Exception: # noqa: BLE001
return {}
def _is_busy() -> bool:
return read_active().get("status") in ("running", "switching")
def write_active(**kw) -> None:
"""写回 active.json(保留既有键,仅更新传入字段)。"""
d = read_active()
d.update(kw)
d.setdefault("userId", "")
d.setdefault("pluginId", "")
d.setdefault("version", "")
d.setdefault("status", "idle")
d.setdefault("startedAt", "")
d.setdefault("runId", "")
try:
ACTIVE_PATH.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("写 active.json 失败:%s", _exc)
def current() -> dict:
"""当前活动插件(空闲则返回空映射)。"""
return read_active()
def is_active(plugin_id: str) -> bool:
"""当前设备是否正在跑该插件。"""
a = read_active()
return bool(a.get("status") == "running" and a.get("pluginId") == plugin_id)
def request_start(user: str, plugin_id: str, version: str, start_fn) -> dict:
"""设备级单活启动:阻塞等待当前插件执行完成后再启动目标(完全不能并发)。
- 若设备正有插件在跑(running/switching),本请求会在此等待,直至该插件执行结束。
- `start_fn` 负责拉起子进程并返回 run_id(不可阻塞),即视为占用单活槽位。
- 启动失败回滚到"空闲"并唤醒等待者。
"""
with _SCHED_COND:
while _is_busy():
_SCHED_COND.wait()
write_active(status="switching", startedAt=_now())
try:
run_id = start_fn()
except Exception as _exc: # noqa: BLE001
write_active(status="idle")
_SCHED_COND.notify_all()
return {"ok": False, "error": f"启动失败:{_exc}"}
write_active(userId=user, pluginId=plugin_id, version=version,
status="running", runId=run_id, startedAt=_now())
return {"ok": True, "run_id": run_id}
def mark_done(plugin_id: str, run_id: str) -> None:
"""运行结束:若 active 仍是该插件则回空闲,并唤醒等待的后续请求(幂等)。"""
with _SCHED_COND:
a = read_active()
if a.get("pluginId") == plugin_id and a.get("runId") == run_id:
write_active(status="idle")
_SCHED_COND.notify_all()
elif a.get("pluginId") == plugin_id:
write_active(status="idle")
_SCHED_COND.notify_all()
def _now() -> str:
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+194
View File
@@ -8,6 +8,8 @@
"name": "37du-webhost-frontend",
"version": "0.1.0",
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"element-plus": "^2.14.5",
"vue": "^3.5.13"
},
"devDependencies": {
@@ -61,6 +63,24 @@
"node": ">=6.9.0"
}
},
"node_modules/@ctrl/tinycolor": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.1.tgz",
"integrity": "sha512-Vh5uy9Y1JBMId6J1f68TMXnZrTCvNdo9Fu2k0d1YnJngR+sM5kWTKl441c/3TFs+cG0NWOjRWgQ/iaWhbYx+7A==",
"license": "MIT",
"engines": {
"node": ">=14"
}
},
"node_modules/@element-plus/icons-vue": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/@element-plus/icons-vue/-/icons-vue-2.3.2.tgz",
"integrity": "sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==",
"license": "MIT",
"peerDependencies": {
"vue": "^3.2.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
@@ -503,6 +523,31 @@
"node": ">=18"
}
},
"node_modules/@floating-ui/core": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
"license": "MIT",
"dependencies": {
"@floating-ui/utils": "^0.2.12"
}
},
"node_modules/@floating-ui/dom": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
"license": "MIT",
"dependencies": {
"@floating-ui/core": "^1.8.0",
"@floating-ui/utils": "^0.2.12"
}
},
"node_modules/@floating-ui/utils": {
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
@@ -529,6 +574,17 @@
"node": "^22.20 || ^24.12 || >=25"
}
},
"node_modules/@popperjs/core": {
"name": "@sxzz/popperjs-es",
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@sxzz/popperjs-es/-/popperjs-es-2.11.8.tgz",
"integrity": "sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.63.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz",
@@ -925,6 +981,27 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/lodash": {
"version": "4.17.25",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz",
"integrity": "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==",
"license": "MIT"
},
"node_modules/@types/lodash-es": {
"version": "4.17.12",
"resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
"license": "MIT",
"dependencies": {
"@types/lodash": "*"
}
},
"node_modules/@types/web-bluetooth": {
"version": "0.0.21",
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
"integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-vue": {
"version": "5.2.4",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz",
@@ -1037,12 +1114,88 @@
"integrity": "sha512-2rPxex1jQf4jvl9MOHl6YaXCPcrNqz/FstMOEh3QWY+/OME9nQTvl9WYeCwhW7AFjaR0SnngZGlp/wkR6rkI6g==",
"license": "MIT"
},
"node_modules/@vueuse/core": {
"version": "14.4.0",
"resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.4.0.tgz",
"integrity": "sha512-X4WHz1HlCzCBoYXesUkifzzWBAcZgXG8Fi5iNPQg/epdzOB3gu8Fawj3hvuwYR1nGcXGnvxwYYcUC/71++svtQ==",
"license": "MIT",
"dependencies": {
"@types/web-bluetooth": "^0.0.21",
"@vueuse/metadata": "14.4.0",
"@vueuse/shared": "14.4.0"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"vue": "^3.5.0"
}
},
"node_modules/@vueuse/metadata": {
"version": "14.4.0",
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.4.0.tgz",
"integrity": "sha512-swx/255R6JyHZFJhx845iz5CRWDZdCfvkZOpACWc5+c5WHcG24mv8gUT1WIdFQaHt6dq79rvILd9QnCWiyVm9g==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/shared": {
"version": "14.4.0",
"resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.4.0.tgz",
"integrity": "sha512-JRgY90Sz8DDtPMsaDflvPMp9xYk69JZAmbuDvAquUVXKr2gEjqtzGNTTthLfckH0BzBqvnu31gb4a8TGLRe79g==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"vue": "^3.5.0"
}
},
"node_modules/async-validator": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz",
"integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT"
},
"node_modules/dayjs": {
"version": "1.11.23",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
"license": "MIT"
},
"node_modules/element-plus": {
"version": "2.14.5",
"resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.14.5.tgz",
"integrity": "sha512-bghYy/S+qg87enHPXELirhEdDqsVAUGcGpbGIeG8dz0kwpIkGz7gYsifulBshXX74iRtHib85XWQj0uSH2A1Yg==",
"license": "MIT",
"dependencies": {
"@ctrl/tinycolor": "^4.2.0",
"@element-plus/icons-vue": "^2.3.2",
"@floating-ui/dom": "^1.8.0",
"@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.8",
"@types/lodash": "^4.17.24",
"@types/lodash-es": "^4.17.12",
"@vueuse/core": "14.4.0",
"async-validator": "^4.2.5",
"dayjs": "^1.11.20",
"lodash": "^4.18.1",
"lodash-es": "^4.18.1",
"lodash-unified": "^1.0.3",
"memoize-one": "^6.0.0",
"normalize-wheel-es": "^1.2.0",
"vue-component-type-helpers": "^3.3.9"
},
"peerDependencies": {
"vue": "^3.3.7"
}
},
"node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
@@ -1136,6 +1289,29 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
},
"node_modules/lodash-es": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",
"integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",
"license": "MIT"
},
"node_modules/lodash-unified": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/lodash-unified/-/lodash-unified-1.0.3.tgz",
"integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==",
"license": "MIT",
"peerDependencies": {
"@types/lodash-es": "*",
"lodash": "*",
"lodash-es": "*"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -1145,6 +1321,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/memoize-one": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz",
"integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==",
"license": "MIT"
},
"node_modules/nanoid": {
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
@@ -1163,6 +1345,12 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/normalize-wheel-es": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz",
"integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==",
"license": "BSD-3-Clause"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -1377,6 +1565,12 @@
"optional": true
}
}
},
"node_modules/vue-component-type-helpers": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz",
"integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==",
"license": "MIT"
}
}
}
+2
View File
@@ -9,6 +9,8 @@
"preview": "vite preview"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"element-plus": "^2.14.5",
"vue": "^3.5.13"
},
"devDependencies": {
+112 -67
View File
@@ -11,41 +11,66 @@
</div>
</div>
<div class="divider"></div>
<el-divider direction="vertical" class="vdiv" />
<div class="band">
<span class="band-label">平台登录态</span>
<button
<el-tooltip
v-for="p in store.platforms"
:key="p.id"
class="chip"
:class="{ online: p.online, locked: p.allowed === false }"
:disabled="busyLogin === p.id || p.allowed === false"
@click="login(p.id)"
:title="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
:content="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
placement="bottom"
:disabled="p.online && p.allowed !== false"
>
<i class="dot"></i>
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
</button>
<el-button
class="chip"
:class="{ online: p.online, locked: p.allowed === false }"
:disabled="busyLogin === p.id || p.allowed === false"
:loading="busyLogin === p.id"
round
@click="login(p.id)"
>
<i class="dot"></i>
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
</el-button>
</el-tooltip>
</div>
<div class="spacer"></div>
<div class="run-state">
<span v-if="store.running" class="run-label">{{ store.progress }}%</span>
<div v-show="store.running" class="progress"><div :style="{ width: store.progress + '%' }"></div></div>
<template v-if="store.running">
<span class="run-pct">{{ store.progress }}%</span>
<el-progress
:percentage="store.progress"
:show-text="false"
:stroke-width="8"
color="#3b6cff"
class="run-bar"
/>
</template>
</div>
<div class="acct">
<button class="acct-btn" title="个人中心" @click="profileOpen = true">
<span class="acct-avatar">
<img v-if="store.avatarUrl" :src="store.avatarUrl" alt="" @error="clearAvatarCache">
<span v-else class="acct-avatar-fb">{{ store.current.slice(0, 1).toUpperCase() }}</span>
</span>
<span class="acct-name">{{ store.current }}</span>
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
<el-avatar :size="26" class="acct-avatar" :src="store.avatarUrl" :key="store.avatarUrl" @error="onAvatarError">
<span class="acct-avatar-fb">{{ store.current.slice(0, 1).toUpperCase() }}</span>
</el-avatar>
<span class="acct-name">{{ store.nickname ? store.nickname : store.current }}</span>
<span v-if="store.nickname" class="acct-sub">{{ store.current }}</span>
<el-tag v-if="store.isAdmin" size="small" type="primary" effect="light" round>管理员</el-tag>
</button>
<button class="chip" @click="logout">登出</button>
<el-button
v-if="store.isAdmin"
v-show="store.controlplane"
class="chip admin-chip"
title="打开中心机控制面进行插件/账号/授权管理"
round
@click="openConsole"
>
<el-icon class="geo"><Setting /></el-icon>管理控制台
</el-button>
<el-button class="chip" round @click="logout">登出</el-button>
</div>
</header>
@@ -70,6 +95,7 @@
<em>v{{ p.version }}</em>
</li>
</ul>
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员在控制面授权</span></div>
<div class="side-foot">场景以插件方式接入</div>
</aside>
@@ -82,20 +108,30 @@
</div>
</div>
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
<div v-if="toast" class="toast">{{ toast }}</div>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PluginPage from './components/PluginPage.vue'
import LogPanel from './components/LogPanel.vue'
import LoginPage from './components/LoginPage.vue'
import ProfilePanel from './components/ProfilePanel.vue'
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache } from './store'
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe } from './api'
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe, adminPassword } from './api'
function openConsole() {
if (!store.controlplane) return
window.open(store.controlplane, '_blank', 'noopener')
}
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
// 顶栏头像加载失败:清除缓存返回首字符兜底
function onAvatarError() {
clearAvatarCache()
}
const wsText = computed(() =>
store.wsOn ? '服务已连接' : '连接中断,正在重连…')
@@ -119,6 +155,7 @@ function openWS() {
onMounted(async () => {
const meta = await fetchMeta()
store.appName = meta.appName
store.controlplane = meta.controlplane || ''
store.platforms = meta.platforms
store.plugins = meta.plugins || []
store.selectedId = store.plugins[0]?.id || ''
@@ -131,13 +168,9 @@ onMounted(async () => {
const profileOpen = ref(false)
const busyLogin = ref('')
// 极简顶部 toast:平台登录等轻量操作反馈
const toast = ref('')
let toastTimer = null
function showToast(msg) {
toast.value = msg
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => (toast.value = ''), 2200)
// 平台登录等轻量操作反馈:统一走 element-plus 全局消息
function showToast(msg, type = 'info') {
ElMessage({ message: msg, type, duration: 2200 })
}
async function checkSession() {
@@ -145,10 +178,11 @@ async function checkSession() {
if (!store.current) return
try {
const me = await adminMe()
if (!me.account) { store.current = ''; store.isAdmin = false; store.dept = '' }
if (!me.account) { store.current = ''; store.isAdmin = false; store.dept = ''; store.nickname = '' }
else {
store.isAdmin = !!me.is_admin
store.dept = me.dept || ''
store.nickname = me.nickname || ''
// 会话有效:补拉插件清单(未登录时 meta 不返回插件)
await refreshMeta()
}
@@ -158,6 +192,7 @@ async function checkSession() {
async function refreshMeta() {
try {
const meta = await fetchMeta()
store.controlplane = meta.controlplane || ''
store.platforms = meta.platforms
store.plugins = meta.plugins || []
if (!store.selectedId) store.selectedId = store.plugins[0]?.id || ''
@@ -168,16 +203,36 @@ async function onLogin(ok) {
store.current = ok.account
store.isAdmin = !!ok.is_admin
store.dept = ok.dept || ''
store.nickname = ok.nickname || ''
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
// 登录后:刷新平台权限与插件清单,并用带会话的连接重建 WS
await refreshMeta()
openWS()
loadAvatar()
// 首次登录/钉钉自动建号的默认密码:提示立即改密
if (ok.must_change_pwd) { promptChangePwd(ok.account) }
}
async function promptChangePwd(account) {
try {
const { value: np } = await ElMessageBox.prompt(
'当前账号正使用默认密码,请立即设置新密码(至少 6 位),避免他人误登录',
'首次登录 · 修改密码',
{ inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说' })
try {
await adminPassword({ account, old_password: '', new_password: np })
ElMessage.success('密码已更新')
} catch (e) {
ElMessage.warning('改密失败:' + (e.message || e))
}
} catch (_) { /* 用户取消 */ }
}
async function logout() {
try { await adminLogout() } catch (_) {}
store.current = ''
store.isAdmin = false
store.nickname = ''
store.avatarUrl = ''
try { localStorage.removeItem('cp_account') } catch (_) {}
}
@@ -187,7 +242,7 @@ async function login(id) {
const p = store.platforms.find((x) => x.id === id)
const label = p?.label || id
if (p?.online) {
showToast(`${label} 已登录`)
showToast(`${label} 已登录`, 'success')
return
}
busyLogin.value = id
@@ -197,10 +252,10 @@ async function login(id) {
if (p) p.online = ok
log(ok ? 'INFO' : 'ERROR',
ok ? `平台 ${label} 登录成功` : `平台 ${label} 登录未生效:${(r && r.message) || ''}`)
showToast(ok ? `${label} 登录成功` : `${label} 登录失败:${(r && r.message) || '登录态未生效'}`)
showToast(ok ? `${label} 登录成功` : `${label} 登录失败:${(r && r.message) || '登录态未生效'}`, ok ? 'success' : 'error')
} catch (e) {
log('ERROR', `平台 ${label} 登录失败:${e.message || e}`)
showToast(`登录失败:${e.message || e}`)
showToast(`登录失败:${e.message || e}`, 'error')
} finally {
busyLogin.value = ''
}
@@ -225,27 +280,24 @@ async function login(id) {
.brand-meta strong { font-size: 14px; }
.brand-meta span { font-size: 11px; color: var(--text-faint); }
.divider { width: 1px; height: 26px; background: var(--border); }
.vdiv { height: 26px; margin: 0 2px; }
.band { display: flex; align-items: center; gap: 6px; }
.band { display: flex; align-items: center; gap: 8px; }
.band-label { font-size: 12px; color: var(--text-faint); margin-right: 4px; }
.chip {
display: inline-flex; align-items: center; gap: 7px;
border: 1px solid var(--border-strong); background: var(--surface);
color: var(--text-sub); padding: 5px 12px; border-radius: 999px;
cursor: pointer; font-size: 12.5px; transition: all .15s;
}
.chip .dot { width: 9px; height: 9px; border-radius: 50%; background: #c6ccdc; }
.chip { padding: 5px 14px; border-radius: 999px; }
.chip .dot { width: 9px; height: 9px; border-radius: 50%; background: #c6ccdc; margin-right: 6px; display: inline-block; }
.chip.online { border-color: transparent; background: var(--ok-weak); color: #1a8f63; }
.chip.online .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(34,176,122,.18); }
.chip:hover { border-color: var(--primary); color: var(--primary); }
.chip:disabled { opacity: .55; cursor: not-allowed; }
.chip:disabled:hover { border-color: var(--border-strong); color: var(--text-sub); }
.chip.locked { border-style: dashed; opacity: .5; }
.admin-chip { border-color: rgba(59,108,255,.45); color: var(--primary); background: var(--primary-weak-2); margin-left: 4px; }
.admin-chip:hover { border-color: var(--primary); }
.admin-chip .geo { margin-right: 4px; }
.spacer { flex: 1; }
.run-state { display: flex; align-items: center; gap: 10px; }
.run-label { font-size: 12px; color: var(--primary); font-weight: 600; min-width: 38px; text-align: right; }
.run-bar { width: 180px; flex-shrink: 0; }
.run-pct { font-size: 12px; font-weight: 700; color: var(--primary); font-variant-numeric: tabular-nums; }
.acct { display: flex; align-items: center; gap: 8px; margin-left: 12px; }
.acct-btn {
@@ -255,18 +307,10 @@ async function login(id) {
font: inherit; transition: background .13s;
}
.acct-btn:hover { background: var(--surface-2); }
.acct-avatar {
width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0;
position: relative; overflow: hidden;
display: grid; place-items: center;
background: var(--primary-grad); color: #fff;
font-size: 12px; font-weight: 700;
}
.acct-avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.acct-avatar-fb { line-height: 1; }
.acct-avatar { flex-shrink: 0; }
.acct-avatar-fb { font-size: 12px; font-weight: 700; }
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
.acct-tag { font-style: normal; font-size: 10px; color: var(--primary);
border: 1px solid var(--primary-weak); background: var(--primary-weak); border-radius: 999px; padding: 1px 7px; }
.acct-sub { font-size: 11px; color: var(--text-faint); margin-left: 1px; font-weight: 400; }
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
@@ -277,10 +321,15 @@ async function login(id) {
.scene-list li {
display: flex; align-items: center; gap: 10px;
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
transition: background .13s;
position: relative;
transition: background .13s, transform .13s ease;
}
.scene-list li:hover { background: var(--surface-2); }
.scene-list li:hover { background: var(--surface-2); transform: translateX(2px); }
.scene-list li.active { background: var(--primary-weak); }
.scene-list li.active::before {
content: ''; position: absolute; left: 0; top: 9px; bottom: 9px;
width: 3px; border-radius: 3px; background: var(--primary);
}
.scene-list li.active .scene-name { color: var(--primary); font-weight: 600; }
.scene-icon {
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
@@ -288,17 +337,13 @@ async function login(id) {
}
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
.scene-empty {
flex: 1; display: grid; place-items: center; text-align: center;
font-size: 12.5px; color: var(--text-sub); line-height: 1.9; padding: 20px 12px;
}
.scene-empty span { font-size: 11px; color: var(--text-faint); }
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; }
.main { flex: 1; display: flex; flex-direction: column; gap: 14px; min-width: 0; }
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; }
.toast {
position: fixed; top: 18px; left: 50%; transform: translateX(-50%);
background: rgba(24, 39, 75, .92); color: #fff;
padding: 8px 18px; border-radius: 999px; font-size: 12.5px;
z-index: 60; animation: toast-in .15s ease;
box-shadow: 0 8px 24px -8px rgba(24, 39, 75, .4);
}
@keyframes toast-in { from { opacity: 0; transform: translate(-50%, -6px); } to { opacity: 1; transform: translate(-50%, 0); } }
</style>
+13
View File
@@ -50,6 +50,19 @@ export async function adminMe() {
export async function adminLogin(account, password) {
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
}
export async function adminDingtalkLogin(account, nickname, dingtalk_uid = '') {
return j('/api/admin/dingtalk/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, nickname, dingtalk_uid }) })
}
export async function adminDingtalkQr() {
return j('/api/admin/dingtalk/qr')
}
// 内嵌二维码(DDLogin):拿 goto 参数 + 用 loginTmpCode 登录
export async function adminDingtalkInlineQr() {
return j('/api/admin/dingtalk/inline_qr')
}
export async function adminDingtalkInlineLogin(code) {
return j('/api/admin/dingtalk/inline', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })
}
export async function adminLogout() {
return j('/api/admin/logout', { method: 'POST' })
}
+61 -16
View File
@@ -2,15 +2,27 @@
<div class="panel log-wrap">
<div class="log-head">
<div class="log-title">
<i class="status" :class="store.wsOn ? 'on' : 'off'"></i>
<i class="status" :class="store.wsOn ? 'on' : 'off'" :title="store.wsOn ? '实时连接正常' : '连接已中断'"></i>
<span>运行日志</span>
<span v-if="store.running" class="live">●</span>
<span v-if="store.running" class="live">● LIVE</span>
<span v-else-if="store.logs.length" class="count">{{ visibleLogs.length }} 条</span>
</div>
<div class="log-tools">
<el-radio-group v-model="level" size="small">
<el-radio-button v-for="l in LEVELS" :key="l" :value="l">{{ l }}</el-radio-button>
</el-radio-group>
<el-button size="small" :icon="CopyDocument" circle title="复制日志" :disabled="!visibleLogs.length" @click="copy" />
<el-button size="small" :icon="pause ? VideoPlay : VideoPause" circle :title="pause ? '继续滚动' : '暂停滚动'" @click="pause = !pause" />
<el-button size="small" plain :disabled="!store.logs.length" @click="confirmClear">清空</el-button>
</div>
<button class="btn mini" @click="clear">清空</button>
</div>
<div ref="box" class="log-box">
<div v-if="store.logs.length === 0" class="log-empty">暂无日志,点击「一键执行」开始</div>
<div v-for="(l, i) in store.logs" :key="i" class="log-line">
<div v-if="!visibleLogs.length" class="log-empty">
<template v-if="store.logs.length">当前级别无日志</template>
<template v-else>暂无日志,点击「一键执行」开始</template>
</div>
<div v-for="(l, i) in visibleLogs" :key="i" class="log-line">
<span class="t">{{ l.time }}</span>
<span class="lv" :class="'s-' + (l.level || 'INFO')">[{{ l.level || 'INFO' }}]</span>
<span>{{ l.msg }}</span>
@@ -20,34 +32,67 @@
</template>
<script setup>
import { nextTick, ref, watch } from 'vue'
import { nextTick, ref, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CopyDocument, VideoPause, VideoPlay } from '@element-plus/icons-vue'
import { store, clearLogs } from '../store'
const LEVELS = ['全部', 'INFO', 'WARN', 'ERROR']
const level = ref('全部')
const pause = ref(false)
const box = ref(null)
const visibleLogs = computed(() => {
if (level.value === '全部') return store.logs
return store.logs.filter((l) => l.level === level.value)
})
// 日志变化或过滤切换时,若未暂停则自动滚到最新
watch(
() => store.logs.length,
[() => store.logs.length, level],
async () => {
if (pause.value) return
await nextTick()
if (box.value) box.value.scrollTop = box.value.scrollHeight
}
},
{ immediate: true }
)
function clear() {
clearLogs()
function confirmClear() {
ElMessageBox.confirm('确认清空全部运行日志?', '清空日志', {
confirmButtonText: '清空',
cancelButtonText: '取消',
type: 'warning',
})
.then(() => { clearLogs(); ElMessage.success('日志已清空') })
.catch(() => {})
}
async function copy() {
const text = visibleLogs.value.map((l) => `[${l.time}] [${l.level || 'INFO'}] ${l.msg}`).join('\n')
try {
await navigator.clipboard.writeText(text)
ElMessage.success(`已复制 ${visibleLogs.value.length} 条日志`)
} catch (_) {
ElMessage.error('复制失败')
}
}
</script>
<style scoped>
.log-wrap { display: flex; flex-direction: column; height: 190px; flex-shrink: 0; overflow: hidden; position: relative; }
.log-wrap { display: flex; flex-direction: column; height: 216px; flex-shrink: 0; overflow: hidden; position: relative; }
.log-head {
display: flex; align-items: center; justify-content: space-between;
padding: 9px 14px; border-bottom: 1px solid var(--border);
padding: 8px 12px 8px 14px; border-bottom: 1px solid var(--border); gap: 10px;
}
.log-title { display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text); }
.status { width: 9px; height: 9px; border-radius: 50%; }
.log-title { display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text); white-space: nowrap; }
.log-tools { display: flex; align-items: center; gap: 6px; }
.log-tools .el-button + .el-button { margin-left: 0; }
.status { width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0; }
.status.on { background: var(--ok); box-shadow: 0 0 0 3px var(--ok-weak); }
.status.off { background: #c6ccdc; }
.live { color: var(--ok); font-size: 10px; animation: blink 1s infinite; }
.live { color: var(--ok); font-size: 10px; animation: blink 1s infinite; letter-spacing: .04em; }
.count { font-size: 11px; color: var(--text-faint); font-weight: 500; }
@keyframes blink { 50% { opacity: .2; } }
.log-empty { color: var(--text-faint); padding: 14px; font-family: var(--mono); font-size: 12px; }
.btn.mini { padding: 4px 12px; font-size: 12px; }
</style>
+217 -137
View File
@@ -13,62 +13,229 @@
</div>
</div>
<div class="row">
<label class="field">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="8" r="3.6" />
<path d="M4.5 20a7.5 7.5 0 0 1 15 0" />
</svg>
<input v-model="account" placeholder="账号" autocomplete="username" @keyup.enter="doLogin">
</label>
<el-form label-position="top" @submit.prevent="doLogin">
<el-form-item label="账号">
<el-input
v-model="account"
placeholder="账号"
autocomplete="username"
size="large"
:prefix-icon="User"
clearable
@keyup.enter="doLogin"
/>
</el-form-item>
<el-form-item label="密码">
<el-input
v-model="password"
type="password"
placeholder="密码"
autocomplete="current-password"
size="large"
:prefix-icon="Lock"
show-password
@keyup.enter="doLogin"
/>
</el-form-item>
<el-button type="primary" size="large" class="primary" :loading="busy" @click="doLogin">
{{ busy ? '校验中…' : '登 录' }}
</el-button>
</el-form>
<label class="field">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="4.5" y="10.5" width="15" height="9.5" rx="2.5" />
<path d="M8 10.5V7.8a4 4 0 0 1 8 0v2.7" />
</svg>
<input v-model="password" type="password" placeholder="密码" autocomplete="current-password" @keyup.enter="doLogin">
</label>
<div class="divider"><span>或使用钉钉登录</span></div>
<el-button size="large" class="dingtalk" :loading="dingBusy" :icon="ChatDotRound" @click="openDing">钉钉扫码登录</el-button>
<!-- 内嵌二维码:本页内渲染钉钉二维码,扫码即登录(不弹浏览器) -->
<div v-if="inlineOpen" class="inline-qr">
<div ref="qrBoxEl" class="qr-box"><div id="ding_qr_container"></div></div>
<p class="ding-tip">用钉钉 App 扫码,自动登录 / 自动建号(新账号首次登录请改密)</p>
<div class="qr-actions">
<el-link type="primary" :underline="false" @click="openDingWindow">改用浏览器窗口授权</el-link>
</div>
</div>
<button class="primary" :disabled="busy" @click="doLogin">
<span v-if="busy" class="spinner"></span>
{{ busy ? '校验中…' : '登录' }}
</button>
<transition name="fade">
<p class="msg" v-if="msg">{{ msg }}</p>
</transition>
</div>
<!-- 真实钉钉扫码(配置了开放平台应用时 window.open 扫码页;否则回落到工号录入) -->
<el-dialog v-model="dingOpen" title="钉钉登录" width="360px" align-center>
<p class="ding-tip">完成钉钉扫码后,填入工号与姓名即自动建立/匹配账号。<br>新账号默认无插件权限,首次登录请改密。</p>
<el-form label-position="top" @submit.prevent="doDing">
<el-form-item label="工号(作为账号)">
<el-input v-model="dingAccount" placeholder="钉钉工号" size="large" :disabled="dingBusy" @keyup.enter="doDing" />
</el-form-item>
<el-form-item label="姓名">
<el-input v-model="dingName" placeholder="钉钉姓名" size="large" :disabled="dingBusy" @keyup.enter="doDing" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dingOpen = false">取消</el-button>
<el-button type="primary" :loading="dingBusy" @click="doDing">确认登录</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { adminLogin } from '../api'
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, ChatDotRound } from '@element-plus/icons-vue'
import { adminLogin, adminDingtalkLogin, adminDingtalkQr, adminPassword, adminDingtalkInlineQr, adminDingtalkInlineLogin } from '../api'
const props = defineProps({ appName: { type: String, default: '' } })
const emit = defineEmits(['ok'])
const account = ref('')
const password = ref('')
const busy = ref(false)
const msg = ref('')
const dingOpen = ref(false)
const dingBusy = ref(false)
const dingAccount = ref('')
const dingName = ref('')
const dingUrl = ref('')
// 内嵌二维码状态
const inlineOpen = ref(false)
const qrBoxEl = ref(null)
const dingGoto = ref('')
let ddMsgHandler = null
onMounted(async () => {
try { const r = await adminDingtalkQr(); dingUrl.value = r.url || '' } catch (_) {}
})
async function doLogin() {
if (!account.value || !password.value) return (msg.value = '请输入账号和密码')
if (busy.value) return
if (!account.value.trim() || !password.value) { ElMessage.warning('请输入账号和密码'); return }
busy.value = true
msg.value = ''
try {
const r = await adminLogin(account.value, password.value)
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin, dept: r.dept || '' })
ElMessage.success('登录成功')
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin, dept: r.dept || '', must_change_pwd: !!r.must_change_pwd })
} catch (e) {
msg.value = '登录失败:' + (e.message || e)
ElMessage.error('登录失败:' + (e.message || e))
} finally {
busy.value = false
}
}
async function openDing() {
// 优先内嵌二维码:本页内渲染钉钉二维码,扫码即登录;失败则回落浏览器窗口授权 / 工号录入。
try {
const r = await adminDingtalkInlineQr()
if (r && r.goto) {
dingGoto.value = r.goto
inlineOpen.value = true
await nextTick()
loadDdLogin()
return
}
} catch (_) { /* 中心机未配置钉钉应用或无中心机时走回退 */ }
openDingWindow()
}
function openDingWindow() {
// 链接授权:新窗口打开钉钉二维码页(中心机换取身份后回跳建会话)
if (dingUrl.value) {
const w = window.open(dingUrl.value, 'dingLogin', 'width=460,height=560,menubar=no,toolbar=no,status=no')
if (w) return
}
if (!dingAccount.value) dingAccount.value = account.value.trim()
dingOpen.value = true // 工号录入兜底
}
function loadDdLogin() {
if (window.DDLogin) { renderDdLogin(); return }
const s = document.createElement('script')
s.src = 'https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js'
s.async = true
s.onload = renderDdLogin
s.onerror = () => {
ElMessage.error('加载钉钉二维码组件失败,已改用浏览器窗口授权')
inlineOpen.value = false
openDingWindow()
}
document.head.appendChild(s)
if (!ddMsgHandler) {
ddMsgHandler = (ev) => {
if (ev.origin && /(?:^|\.)(?:login|oapi|qr|auth|api)\.dingtalk\.com$/.test(
new URL(ev.origin).hostname || ev.origin)) {
const code = ev.data && ev.data.loginTmpCode ? ev.data.loginTmpCode : ev.data
if (code && typeof code === 'string') loginInline(code)
}
}
window.addEventListener('message', ddMsgHandler)
}
}
function renderDdLogin() {
if (!window.DDLogin || !document.getElementById('ding_qr_container')) return
new window.DDLogin({
id: 'ding_qr_container',
goto: dingGoto.value,
style: 'border:none;background:#fff;',
width: '260',
height: '260',
})
}
async function loginInline(code) {
if (dingBusy.value) return
dingBusy.value = true
try {
const r = await adminDingtalkInlineLogin(code)
ElMessage.success(r.created ? '已自动建立账号,登录成功' : '登录成功')
inlineOpen.value = false
if (r.must_change_pwd) {
await promptChangePwd(r.account || account.value, r)
} else {
emit('ok', { account: r.account, is_admin: !!r.is_admin, dept: '', created: !!r.created, nickname: r.nickname || '' })
}
} catch (e) {
ElMessage.error('登录失败:' + (e.message || e))
} finally {
dingBusy.value = false
}
}
onUnmounted(() => {
if (ddMsgHandler) window.removeEventListener('message', ddMsgHandler)
})
async function doDing() {
if (dingBusy.value) return
if (!dingAccount.value.trim()) { ElMessage.warning('请输入钉钉工号'); return }
if (!dingName.value.trim()) { ElMessage.warning('请输入钉钉姓名'); return }
dingBusy.value = true
const acc = dingAccount.value.trim()
try {
const r = await adminDingtalkLogin(acc, dingName.value.trim())
ElMessage.success(r.created ? '已自动建立账号,登录成功' : '登录成功')
dingOpen.value = false
if (r.must_change_pwd) {
await promptChangePwd(acc, r)
} else {
emit('ok', { account: acc, is_admin: !!r.is_admin, dept: '', created: !!r.created, nickname: r.nickname || '' })
}
} catch (e) {
ElMessage.error('登录失败:' + (e.message || e))
} finally {
dingBusy.value = false
}
}
async function promptChangePwd(acc, r) {
try {
const { value: np } = await ElMessageBox.prompt(
'当前为系统默认密码,请立即设置新密码(至少 6 位)',
'首次登录 · 修改密码',
{ inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说' })
try {
await adminPassword({ account: acc, old_password: '', new_password: np })
ElMessage.success('密码已更新')
} catch (e2) {
ElMessage.warning('改密失败:' + (e2.message || e2))
}
} catch (_) { /* 用户取消 */ }
emit('ok', { account: acc, is_admin: !!r.is_admin, dept: '', created: !!r.created, nickname: r.nickname || '' })
}
</script>
<style scoped>
@@ -108,7 +275,7 @@ async function doLogin() {
max-width: 100%;
display: flex;
flex-direction: column;
gap: 16px;
gap: 18px;
padding: 32px 32px 26px;
border: 1px solid var(--border);
border-radius: 20px;
@@ -153,113 +320,26 @@ async function doLogin() {
}
.brand-meta span { font-size: 11.5px; color: var(--text-faint); letter-spacing: .02em; }
/* ---------- 输入框 ---------- */
.row { display: flex; flex-direction: column; gap: 10px; }
.field {
display: flex;
align-items: center;
gap: 10px;
padding: 0 13px;
border: 1px solid var(--border-strong);
border-radius: 12px;
background: var(--surface);
transition: border-color .18s, box-shadow .18s;
}
.field:hover { border-color: var(--primary); }
.field:focus-within {
border-color: var(--primary);
box-shadow: 0 0 0 4px var(--primary-weak);
}
.field svg {
width: 16px;
height: 16px;
flex: none;
color: var(--text-faint);
transition: color .18s;
}
.field:focus-within svg { color: var(--primary); }
.field input {
flex: 1;
min-width: 0;
padding: 12px 0;
border: none;
outline: none;
background: transparent;
font: inherit;
color: inherit;
}
.field input::placeholder { color: var(--text-faint); }
/* 干掉 Chrome 自动填充的黄色底色 */
.field input:-webkit-autofill {
-webkit-text-fill-color: currentColor;
transition: background-color 9999s ease-in-out 0s;
}
/* ---------- 主按钮 ---------- */
button.primary {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 12px;
margin-top: 2px;
border: none;
border-radius: 12px;
cursor: pointer;
background: var(--primary-grad);
color: #fff;
font: inherit;
font-weight: 600;
letter-spacing: .06em;
box-shadow: 0 8px 20px -7px rgba(59, 108, 255, .65);
transition: box-shadow .18s, transform .12s, filter .18s;
}
button.primary:hover:not(:disabled) {
filter: brightness(1.05);
box-shadow: 0 12px 28px -9px rgba(59, 108, 255, .75);
}
button.primary:active:not(:disabled) {
transform: translateY(1px);
box-shadow: 0 5px 14px -7px rgba(59, 108, 255, .65);
}
button.primary:focus-visible {
outline: none;
box-shadow: 0 0 0 4px var(--primary-weak), 0 8px 20px -7px rgba(59, 108, 255, .65);
}
button.primary:disabled { opacity: .6; cursor: not-allowed; box-shadow: none; }
.primary { width: 100%; margin-top: 2px; letter-spacing: .06em; font-weight: 600; }
.spinner {
width: 13px;
height: 13px;
border: 2px solid rgba(255, 255, 255, .38);
border-top-color: #fff;
border-radius: 50%;
animation: spin .7s linear infinite;
/* ---------- 钉钉登录区 ---------- */
.divider {
display: flex; align-items: center; gap: 10px;
color: var(--text-faint); font-size: 11px; letter-spacing: .02em;
margin: 6px 0 2px;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ---------- 提示信息 ---------- */
.msg {
margin: 0;
padding: 8px 12px;
border: 1px solid rgba(229, 72, 77, .18);
border-radius: 10px;
background: rgba(229, 72, 77, .08);
color: #e5484d;
font-size: 12.5px;
line-height: 1.5;
text-align: center;
.divider::before, .divider::after {
content: ''; height: 1px; flex: 1; background: var(--border);
}
.fade-enter-active,
.fade-leave-active { transition: opacity .2s, transform .2s; }
.fade-enter-from,
.fade-leave-to { opacity: 0; transform: translateY(-4px); }
.dingtalk { width: 100%; color: #0aa9f4; border-color: rgba(10,169,244,.35); letter-spacing: .04em; }
.dingtalk:hover, .dingtalk:focus { border-color: #0aa9f4; color: #0aa9f4; background: rgba(10,169,244,.06); }
.ding-tip { margin: 0 0 14px; font-size: 12px; line-height: 1.7; color: var(--text-faint); }
.inline-qr { margin-top: 14px; text-align: center; }
.qr-box { width: 240px; height: 240px; margin: 0 auto 6px; border: 1px solid rgba(0,0,0,.06); border-radius: 10px; overflow: hidden; background: #fff; display: flex; align-items: center; justify-content: center; }
.qr-box :deep(#ding_qr_container) { margin: 0 auto; }
.qr-actions { margin-top: 4px; }
.qr-actions .el-link { font-size: 12px; }
/* ---------- 自适应 & 降级 ---------- */
@media (max-width: 420px) {
+82 -68
View File
@@ -5,70 +5,88 @@
<div class="ident">
<span class="avatar" :style="{ background: avatarBg }">{{ plugin.name.slice(0, 1) }}</span>
<div class="ident-meta">
<h2>{{ plugin.name }}</h2>
<p>{{ plugin.description }}</p>
<h2>{{ plugin.name }} <span class="ver-tag">v{{ plugin.version }}</span></h2>
<p>{{ plugin.description || '暂无描述' }}</p>
</div>
</div>
<div v-if="plugin?.uses_month" class="month">
<span class="field-label">执行月份</span>
<select v-model="month" class="input month-sel">
<option v-for="m in months" :key="m" :value="m">{{ m }}</option>
</select>
<el-select v-model="month" class="month-sel" :disabled="store.running">
<el-option v-for="m in months" :key="m" :value="m" :label="m" />
</el-select>
</div>
</div>
<!-- 结果横幅 -->
<transition name="fade">
<div v-if="store.lastResult" class="banner" :class="store.lastResult.ok ? 'ok' : 'err'">
<span class="b-ic">{{ store.lastResult.ok ? '✓' : '✕' }}</span>
<span class="b-text">
<el-alert
v-if="store.lastResult"
:type="store.lastResult.ok ? 'success' : 'error'"
:closable="true"
:close-text="null"
class="banner"
@close="closeBanner"
show-icon
>
<template #title>
<span>
{{ store.lastResult.ok ? (store.lastSummary || '执行完成') : '执行失败:' + store.lastResult.error }}
</span>
<button class="b-close" @click="closeBanner">×</button>
</div>
</transition>
</template>
</el-alert>
<!-- 参数 -->
<div class="sec-title">参数配置</div>
<div class="form-card">
<div class="sec-head">
<span class="sec-title">参数配置</span>
<el-button
v-if="Object.keys(form).length"
size="small"
text
:disabled="store.running"
:icon="RefreshLeft"
@click="resetForm"
>恢复默认</el-button>
</div>
<el-form label-width="auto" class="form-card">
<div class="fields">
<div v-for="f in plugin.fields" :key="f.key" class="fgroup">
<label class="field-label">{{ f.label }}</label>
<input
v-if="f.type === 'int'"
class="input"
type="number"
v-model.number="form[f.key]"
:placeholder="String(f.default ?? 0)"
/>
<input
<el-form-item v-for="f in plugin.fields" :key="f.key" :label="f.label">
<template v-if="f.type === 'int'">
<el-input-number v-model="form[f.key]" :controls="false" placeholder="0" :disabled="store.running" />
</template>
<el-input
v-else-if="f.type === 'text'"
class="input"
type="text"
v-model="form[f.key]"
:placeholder="f.default || ''"
/>
<select v-else class="input" v-model="form[f.key]">
<option v-for="opt in f.options" :key="opt" :value="opt">{{ opt }}</option>
</select>
</div>
:placeholder="String(f.default ?? '')"
:disabled="store.running"
>
<template v-if="f.help" #suffix>
<el-tooltip :content="f.help" placement="bottom"><el-icon class="help-ic"><QuestionFilled /></el-icon></el-tooltip>
</template>
</el-input>
<el-select v-else v-model="form[f.key]" :disabled="store.running">
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
</el-select>
</el-form-item>
</div>
<div class="actions">
<button class="btn primary run-btn" :disabled="store.running" @click="run">
<span v-if="store.running" class="spin"></span>
{{ store.running ? '执行中…' : '一键执行' }}
</button>
<span v-if="store.running" class="run-ind">
<el-progress :percentage="store.progress" :show-text="false" color="#3b6cff" />
</span>
<el-button type="primary" size="large" :loading="store.running" @click="run">
{{ store.running ? '执行中 ' + store.progress + '%' : '一键执行' }}
</el-button>
</div>
</div>
</el-form>
<p class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
</div>
<div v-else class="empty">未选择场景</div>
<el-empty v-else-if="!store.plugins.length" description="当前账号暂无可用场景" />
<el-empty v-else description="未选择场景" />
</template>
<script setup>
import { computed, ref, watch } from 'vue'
import { QuestionFilled, RefreshLeft } from '@element-plus/icons-vue'
import { store, log } from '../store'
import { startRun, getRun } from '../api'
@@ -90,18 +108,30 @@ const avatarBg = computed(() => PALETTE[idx.value % PALETTE.length])
const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null)
const form = ref({})
function buildFormDefaults(p) {
const f = {}
if (p) p.fields.forEach((x) => (f[x.key] = x.default ?? (x.type === 'int' ? 0 : '')))
return f
}
watch(
() => plugin.value?.id,
(id) => {
form.value = {}
const p = store.plugins.find((x) => x.id === id)
if (p) p.fields.forEach((f) => (form.value[f.key] = f.default ?? (f.type === 'int' ? 0 : '')))
form.value = buildFormDefaults(store.plugins.find((x) => x.id === id))
},
{ immediate: true }
)
function resetForm() {
form.value = buildFormDefaults(plugin.value)
}
async function run() {
if (!plugin.value || store.running) return
if (plugin.value.platform && !(store.platforms.find((p) => p.id === plugin.value.platform)?.online)) {
log('WARN', `插件「${plugin.value.name}」需要先登录平台「${store.platforms.find((p) => p.id === plugin.value.platform)?.label || plugin.value.platform}」才能正确执行`)
}
store.running = true
store.progress = 0
store.currentRun = ''
@@ -141,41 +171,25 @@ function closeBanner() {
.plugin-page { display: flex; flex-direction: column; gap: 18px; min-height: 100%; }
.head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.ident { display: flex; align-items: center; gap: 14px; }
.ident { display: flex; align-items: center; gap: 14px; min-width: 0; }
.avatar {
width: 44px; height: 44px; border-radius: 13px; flex-shrink: 0;
display: grid; place-items: center; color: #fff; font-size: 18px; font-weight: 700;
box-shadow: var(--shadow-md);
}
.ident-meta { display: flex; flex-direction: column; gap: 2px; }
.ident-meta h2 { margin: 0; font-size: 17px; }
.ident-meta p { margin: 0; font-size: 12px; color: var(--text-sub); }
.ident-meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.ident-meta h2 { margin: 0; font-size: 17px; display: flex; align-items: center; gap: 8px; }
.ident-meta p { margin: 0; font-size: 12px; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 520px; }
.ver-tag { font-size: 11px; font-weight: 500; color: var(--text-faint); background: var(--surface-2); border: 1px solid var(--border); padding: 1px 7px; border-radius: 999px; }
.month { display: flex; align-items: center; gap: 8px; }
.month-sel { min-width: 110px; }
.month-sel { width: 120px; }
.banner {
display: flex; align-items: center; gap: 10px;
padding: 11px 14px; border-radius: var(--radius-sm); font-size: 13px;
}
.banner.ok { background: var(--ok-weak); color: #156d4e; border: 1px solid #bfe8d5; }
.banner.err { background: var(--err-weak); color: #a83a3e; border: 1px solid #f3c4c5; }
.b-ic { font-weight: 800; font-size: 15px; }
.b-text { flex: 1; }
.b-close { border: none; background: transparent; font-size: 18px; line-height: 1; cursor: pointer; color: inherit; opacity: .5; }
.b-close:hover { opacity: 1; }
.form-card {
display: flex; flex-direction: column; gap: 16px;
padding: 2px 0 0;
}
.sec-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 2px; }
.fields { display: flex; gap: 24px; flex-wrap: wrap; }
.fgroup { display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
.fgroup .input { width: 150px; }
.actions { display: flex; justify-content: flex-end; border-top: 1px dashed var(--border); padding-top: 14px; }
.run-btn { min-width: 128px; height: 38px; font-size: 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
.spin { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.7s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.form-card .el-form-item { margin-bottom: 0; }
.help-ic { color: var(--text-faint); cursor: help; }
.actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; border-top: 1px dashed var(--border); padding-top: 14px; margin-top: 6px; }
.run-ind { flex: 1; max-width: 220px; }
.hint { font-size: 12px; color: var(--text-faint); margin: 0; padding-left: 2px; }
.empty { color: var(--text-faint); padding: 40px; }
</style>
+132 -145
View File
@@ -1,95 +1,114 @@
<template>
<div class="mask" @click.self="emit('close')">
<aside class="profile">
<header class="head">
<div class="avatar" aria-hidden="true">
<img v-if="store.avatarUrl && !avatarFailed" :src="store.avatarUrl" alt="" @error="onAvatarError">
<span v-else>{{ store.current.slice(0, 1).toUpperCase() }}</span>
</div>
<div class="meta">
<div class="name-line">
<strong>{{ store.current }}</strong>
<em v-if="store.isAdmin" class="tag">管理员</em>
</div>
<span class="dept">{{ store.dept || '未设置部门' }}</span>
</div>
<button class="close" title="关闭" @click="emit('close')">✕</button>
</header>
<div class="body">
<!-- 分节:平台登录态 -->
<div class="sec">
<div class="sec-title">平台登录态</div>
<div v-for="p in store.platforms" :key="p.id" class="prow">
<i class="dot" :class="{ on: p.online }"></i>
<span class="pname">{{ p.label }}</span>
<span class="pstat">{{ p.online ? '已登录' : '未登录' }}</span>
<button class="btn mini" :disabled="busy === p.id" @click="relogin(p.id)">
{{ busy === p.id ? '处理中…' : '重新登录' }}
</button>
<button class="btn mini" :disabled="busy === p.id || !p.online" @click="logout(p.id)">登出</button>
</div>
</div>
<!-- 分节:我的插件 -->
<div class="sec">
<div class="sec-title">我的插件</div>
<div v-if="store.plugins.length" class="plist">
<div v-for="p in store.plugins" :key="p.id" class="prow flat">
<span class="pname">{{ p.name }}</span>
<span class="ver">v{{ p.version }}</span>
<el-drawer
v-model="visible"
title="个人中心"
direction="rtl"
size="350px"
:with-header="true"
@close="emit('close')"
>
<!-- 个人信息卡片 -->
<el-card class="info-card" shadow="never">
<template #header>
<div class="info-head">
<el-avatar :size="46" :src="store.avatarUrl" @error="onAvatarError" class="avatar">
<span>{{ store.current.slice(0, 1).toUpperCase() }}</span>
</el-avatar>
<div class="info-meta">
<div class="name-line">
<strong>{{ store.current }}</strong>
<el-tag v-if="store.isAdmin" size="small" type="primary" effect="light" round>管理员</el-tag>
</div>
<span class="dept">{{ store.dept || '未设置部门' }}</span>
</div>
<p v-else class="empty">当前账号暂无可用插件</p>
</div>
</template>
</el-card>
<!-- 分节:修改密码 -->
<div class="sec">
<div class="sec-title">修改密码</div>
<input class="input" v-model="oldPwd" type="password" placeholder="旧密码">
<input class="input" v-model="newPwd" type="password" placeholder="新密码">
<input class="input" v-model="againPwd" type="password" placeholder="确认新密码">
<button class="btn primary block" :disabled="pwdBusy" @click="changePwd">
{{ pwdBusy ? '提交中…' : '保存新密码' }}
</button>
<p v-if="pwdMsg" class="msg" :class="{ ok: pwdOk }">{{ pwdMsg }}</p>
<!-- 平台登录态 -->
<el-collapse v-model="activeNames">
<el-collapse-item name="platforms">
<template #title>
<div class="panel-title">
<el-icon><Connection /></el-icon>
<span>平台登录态</span>
</div>
</template>
<div v-for="p in store.platforms" :key="p.id" class="prow">
<i class="dot" :class="{ on: p.online }"></i>
<span class="pname">{{ p.label }}</span>
<span class="pstat">{{ p.online ? '已登录' : '未登录' }}</span>
<el-button size="small" :disabled="busy === p.id" @click="relogin(p.id)">
{{ busy === p.id ? '处理中…' : '重新登录' }}
</el-button>
<el-button size="small" :disabled="busy === p.id || !p.online" @click="logout(p.id)">登出</el-button>
</div>
</div>
<transition name="fade">
<div v-if="tipMsg" class="tip">{{ tipMsg }}</div>
</transition>
</aside>
</div>
</el-collapse-item>
<!-- 我的插件 -->
<el-collapse-item name="plugins">
<template #title>
<div class="panel-title">
<el-icon><Box /></el-icon>
<span>我的插件 ({{ store.plugins.length }})</span>
</div>
</template>
<el-empty v-if="!store.plugins.length" description="当前账号暂无可用插件" />
<div v-else class="plist">
<div v-for="p in store.plugins" :key="p.id" class="prow flat">
<span class="pname">{{ p.name }}</span>
<span class="ver">v{{ p.version }}</span>
</div>
</div>
</el-collapse-item>
</el-collapse>
<!-- 修改密码 -->
<el-card class="pwd-card" shadow="never" title="修改密码">
<el-form label-position="top" :model="form" :rules="rules" ref="formRef">
<el-form-item label="旧密码" prop="oldPwd">
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
</el-form-item>
<el-form-item label="新密码" prop="newPwd">
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
</el-form-item>
<el-form-item label="确认新密码" prop="newPwd2">
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="pwdBusy" @click="changePwd" style="width: 100%">
{{ pwdBusy ? '提交中…' : '保存新密码' }}
</el-button>
</el-form-item>
</el-form>
</el-card>
</el-drawer>
</template>
<script setup>
import { ref } from 'vue'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Connection, Box } from '@element-plus/icons-vue'
import { store, log, clearAvatarCache } from '../store'
import { loginPlatform, logoutPlatform, adminPassword } from '../api'
const emit = defineEmits(['close'])
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
const visible = ref(true)
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
const avatarFailed = ref(false)
function onAvatarError() {
avatarFailed.value = true
clearAvatarCache()
}
const activeNames = ref(['platforms', 'plugins'])
const busy = ref('')
// 面板内轻提示:已登录再点击等操作反馈
const tipMsg = ref('')
let tipTimer = null
function tip(m) {
tipMsg.value = m
if (tipTimer) clearTimeout(tipTimer)
tipTimer = setTimeout(() => (tipMsg.value = ''), 2000)
}
async function relogin(id) {
if (busy.value) return
const p = store.platforms.find((x) => x.id === id)
if (p?.online) {
tip(`${p.label} 已登录`)
ElMessage.success(`${p.label} 已登录`)
return
}
busy.value = id
@@ -98,10 +117,11 @@ async function relogin(id) {
if (p) {
p.online = !!r.online
log('INFO', `平台 ${p.label} 登录成功`)
ElMessage.success(`平台 ${p.label} 登录成功`)
}
} catch (e) {
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
alert('登录失败:' + (e.message || e))
ElMessage.error(`登录失败:${e.message || e}`)
} finally {
busy.value = ''
}
@@ -114,39 +134,54 @@ async function logout(id) {
if (p) {
p.online = !!r.online
log('INFO', `平台 ${p.label} 已登出`)
ElMessage.success(`平台 ${p.label} 已登出`)
}
} catch (e) {
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
tip('登出失败:' + (e.message || e))
ElMessage.error(`登出失败:${e.message || e}`)
} finally {
busy.value = ''
}
}
const oldPwd = ref('')
const newPwd = ref('')
const againPwd = ref('')
// 修改密码
const formRef = ref()
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
const rules = {
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
newPwd: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
{
validator: (_, v, cb) => (v && v === form.oldPwd
? cb(new Error('新密码不能与原密码相同')) : cb()),
trigger: 'blur'
},
],
newPwd2: [
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
{
validator: (_, v, cb) => (v !== form.newPwd
? cb(new Error('两次输入的密码不一致')) : cb()),
trigger: 'blur'
},
],
}
const pwdBusy = ref(false)
const pwdMsg = ref('')
const pwdOk = ref(false)
async function changePwd() {
pwdMsg.value = ''
if (!oldPwd.value || !newPwd.value) return (pwdMsg.value = '请填写完整密码')
if (newPwd.value !== againPwd.value) return (pwdMsg.value = '两次新密码不一致')
await formRef.value.validate().catch(() => Promise.reject())
pwdBusy.value = true
try {
await adminPassword({
account: store.current,
old_password: oldPwd.value,
new_password: newPwd.value,
old_password: form.oldPwd,
new_password: form.newPwd,
})
pwdMsg.value = '密码已修改'
pwdOk.value = true
oldPwd.value = newPwd.value = againPwd.value = ''
ElMessage.success('密码已修改,下次登录请使用新密码')
form.oldPwd = form.newPwd = form.newPwd2 = ''
setTimeout(() => emit('close'), 800)
} catch (e) {
pwdOk.value = false
pwdMsg.value = '修改失败:' + (e.message || e)
ElMessage.error('修改失败:' + (e.message || e))
} finally {
pwdBusy.value = false
}
@@ -154,76 +189,28 @@ async function changePwd() {
</script>
<style scoped>
.mask {
position: fixed; inset: 0; z-index: 50;
background: rgba(31, 38, 51, 0.35);
display: flex; justify-content: flex-end;
animation: fade .18s ease;
}
.tip {
position: absolute; top: 18px; left: 50%; transform: translateX(-50%);
background: rgba(24, 39, 75, .92); color: #fff;
padding: 8px 18px; border-radius: 999px; font-size: 12.5px;
z-index: 5; box-shadow: 0 8px 24px -8px rgba(24, 39, 75, .4);
animation: fade .15s ease;
}
.profile {
width: 320px; height: 100%;
background: var(--surface);
display: flex; flex-direction: column;
box-shadow: -12px 0 34px -12px rgba(24, 39, 75, 0.3);
animation: slide .2s ease;
}
@keyframes slide { from { transform: translateX(100%); } to { transform: translateX(0); } }
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
.head {
display: flex; align-items: center; gap: 12px;
padding: 18px 20px 14px;
border-bottom: 1px solid var(--border);
}
.avatar {
width: 46px; height: 46px; border-radius: 50%;
position: relative; overflow: hidden; flex-shrink: 0;
display: grid; place-items: center;
color: #fff; font-size: 18px; font-weight: 700;
background: var(--primary-grad);
}
.avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.meta { flex: 1; min-width: 0; }
.info-card { margin-bottom: 16px; }
.info-head { display: flex; align-items: center; gap: 12px; }
.avatar { flex-shrink: 0; }
.info-meta { flex: 1; min-width: 0; }
.name-line { display: flex; align-items: center; gap: 8px; }
.name-line strong { font-size: 15px; }
.tag { font-style: normal; font-size: 10px; color: var(--primary);
background: var(--primary-weak); border-radius: 999px; padding: 1px 8px; }
.dept { font-size: 11.5px; color: var(--text-faint); }
.close {
border: none; background: transparent; cursor: pointer;
color: var(--text-faint); font-size: 14px; padding: 6px; border-radius: 8px;
}
.close:hover { color: var(--text); background: var(--surface-2); }
.body { flex: 1; overflow: auto; padding: 4px 20px 20px; }
.sec { padding: 14px 0 4px; }
.sec + .sec { border-top: 1px dashed var(--border); margin-top: 6px; }
.sec-title {
font-size: 11px; font-weight: 700; letter-spacing: 0.04em;
color: var(--text-faint); margin-bottom: 10px;
}
.panel-title { display: flex; align-items: center; gap: 8px; }
.prow { display: flex; align-items: center; gap: 8px; padding: 7px 0; }
.prow {
display: flex; align-items: center; gap: 8px;
padding: 8px 0;
}
.prow.flat { padding: 6px 0; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: #c6ccdc; flex-shrink: 0; }
.dot.on { background: var(--ok); box-shadow: 0 0 0 3px rgba(34, 176, 122, 0.18); }
.pname { flex: 1; color: var(--text-sub); font-size: 13px;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pname { flex: 1; color: var(--text-sub); font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.pstat { font-size: 11px; color: var(--text-faint); }
.ver { font-size: 11px; color: var(--text-faint); }
.plist { display: flex; flex-direction: column; }
.empty { color: var(--text-faint); font-size: 12px; margin: 4px 0; }
.btn.mini { padding: 3px 10px; font-size: 12px; }
.input { width: 100%; margin-bottom: 10px; }
.btn.block { width: 100%; margin-top: 2px; }
.msg { font-size: 12px; color: var(--err); margin: 8px 0 0; }
.msg.ok { color: var(--ok); }
</style>
.pwd-card { margin-top: 16px; }
</style>
+10 -1
View File
@@ -1,5 +1,14 @@
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import App from './App.vue'
import './style.css'
createApp(App).mount('#app')
const app = createApp(App)
// 全量注册图标,模板中可直接 <component :is="XxxIcon"> 使用
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.use(ElementPlus, { locale: zhCn }).mount('#app')
+2
View File
@@ -2,6 +2,7 @@ import { reactive } from 'vue'
export const store = reactive({
appName: '',
controlplane: '', // 控制面地址(管理员跳转用),来自 /api/meta
platforms: [],
plugins: [],
selectedId: '',
@@ -16,6 +17,7 @@ export const store = reactive({
// 控制面管理视图(统一后端数据库 API)
isAdmin: false,
dept: '',
nickname: '', // 真实姓名(中心机 accounts.nickname,钉钉登录时自动带入)
avatarUrl: '', // 在线头像(localStorage 缓存,避免每次刷新都请求)
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
view: 'plugin', // 'plugin' | 'admin'
+12
View File
@@ -28,6 +28,18 @@
--radius: 14px;
--radius-sm: 9px;
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
/* element-plus 主题与品牌蓝统一 */
--el-color-primary: #3b6cff;
--el-color-primary-light-3: #6f8dff;
--el-color-primary-light-5: #a3b7ff;
--el-color-primary-light-7: #d0dcff;
--el-color-primary-light-8: #e2e9ff;
--el-color-primary-light-9: #eef2ff;
--el-color-primary-dark-2: #2f56d6;
--el-border-radius-base: 8px;
--el-border-radius-small: 6px;
--el-border-radius-round: 20px;
}
* { box-sizing: border-box; }