refactor: 整体迁移控制面至MySQL + 替换UI框架为Element Plus
1. 移除naive-ui依赖,迁移前端至Element Plus 2. 重构后端数据库层,切换为MySQL替代SQLite 3. 调整项目部署架构,停止exe打包改为源码部署 4. 新增设备上报接口与相关数据库模型 5. 优化配置路径与SQL语法,替换为MySQL占位符格式 6. 调整站点名称与文案,统一为「37du 插件管理平台」 7. 新增SQLite到MySQL迁移脚本
This commit is contained in:
@@ -38,12 +38,12 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
"FROM accounts ORDER BY id")]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
a["grants"] = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
|
||||
"SELECT plugin_id, can_download, can_run FROM account_plugins WHERE account = %s",
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@@ -57,13 +57,13 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if exists:
|
||||
raise HTTPException(400, f"账号 {account} 已存在")
|
||||
_hex, _salt = _hash_password(a.password)
|
||||
with _db() as conn:
|
||||
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||
"created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
"created_at) VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||||
(a.nickname or "").strip(), _now()))
|
||||
conn.commit()
|
||||
@@ -81,26 +81,26 @@ def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
if a.dept is not None:
|
||||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET dept = %s WHERE account = %s",
|
||||
((a.dept or "").strip(), account))
|
||||
if a.nickname is not None:
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||||
((a.nickname or "").strip(), account))
|
||||
if a.is_admin is not None:
|
||||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||||
if a.is_admin:
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = %s", (account,))
|
||||
else:
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = %s AND account <> %s",
|
||||
(account, login))
|
||||
if a.status is not None:
|
||||
# 禁止停用自己,避免把自己锁在门外
|
||||
if not a.status and account == login:
|
||||
raise HTTPException(400, "不能停用当前登录的账号")
|
||||
conn.execute("UPDATE accounts SET status = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
|
||||
(int(bool(a.status)), account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
@@ -116,10 +116,10 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
_hex, _salt = _hash_password(r.new_password)
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
@@ -137,10 +137,10 @@ def admin_account_delete(d: schemas.AccountDelIn,
|
||||
if account == login:
|
||||
raise HTTPException(400, "不能删除当前登录的账号")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||||
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||||
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
@@ -172,9 +172,9 @@ def admin_avatar_upload(file: UploadFile = File(...),
|
||||
if not content or len(content) > 2 * 1024 * 1024:
|
||||
raise HTTPException(400, "头像文件为空或超过 2MB")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
old = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
old = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
old_name = (old["avatar"] if old else "") or ""
|
||||
config.AVATAR_DIR.mkdir(parents=True, exist_ok=True)
|
||||
fname = f"{account}{ext}"
|
||||
@@ -185,7 +185,7 @@ def admin_avatar_upload(file: UploadFile = File(...),
|
||||
except OSError:
|
||||
pass
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET avatar = ? WHERE account = ?", (fname, account))
|
||||
conn.execute("UPDATE accounts SET avatar = %s WHERE account = %s", (fname, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "avatar": fname}
|
||||
|
||||
@@ -194,7 +194,7 @@ def admin_avatar_upload(file: UploadFile = File(...),
|
||||
def admin_avatar_get(account: str) -> FileResponse:
|
||||
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
|
||||
with _db() as conn:
|
||||
row = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
row = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if not row or not row["avatar"]:
|
||||
raise HTTPException(404, "未设置头像")
|
||||
path = config.AVATAR_DIR / row["avatar"]
|
||||
@@ -208,7 +208,11 @@ def admin_avatar_get(account: str) -> FileResponse:
|
||||
def admin_grant(g: schemas.GrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤;同时维护插件级授权表。"""
|
||||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤。
|
||||
|
||||
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||||
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
@@ -216,21 +220,18 @@ def admin_grant(g: schemas.GrantIn,
|
||||
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在,请先上传发布")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
(account, plugin_id))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
|
||||
"can_download = excluded.can_download, can_run = excluded.can_run",
|
||||
"INSERT INTO account_plugins(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (%s, %s, %s, %s) "
|
||||
"ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), "
|
||||
"can_run = VALUES(can_run)",
|
||||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
@@ -250,13 +251,13 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||||
"INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (%s, %s)",
|
||||
(account, platform_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
@@ -301,11 +302,11 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
|
||||
"name = excluded.name, manifest = excluded.manifest"
|
||||
+ (", description = excluded.description" if manifest else "")
|
||||
+ (", category = excluded.category" if manifest else "")
|
||||
+ (", icon = excluded.icon" if manifest else ""),
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
|
||||
"name = VALUES(name), manifest = VALUES(manifest)"
|
||||
+ (", description = VALUES(description)" if manifest else "")
|
||||
+ (", category = VALUES(category)" if manifest else "")
|
||||
+ (", icon = VALUES(icon)" if manifest else ""),
|
||||
(plugin_id, name, version,
|
||||
(manifest or {}).get("description", ""),
|
||||
(manifest or {}).get("category", ""),
|
||||
@@ -313,12 +314,12 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
manifest_json))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
|
||||
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
|
||||
"VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
|
||||
"filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)",
|
||||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = %s", (plugin_id,))
|
||||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||||
conn.execute("UPDATE plugins SET latest_version = %s WHERE id = %s", (version, plugin_id))
|
||||
stale_files = _prune_versions(conn, plugin_id)
|
||||
conn.commit()
|
||||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||||
@@ -339,13 +340,14 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||||
files = [dict(r)["filename"] for r in conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))]
|
||||
# 外键 CASCADE 会连带清理 plugin_versions / account_plugins,显式删除仅作兜底保序
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = %s", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = %s", (plugin_id,))
|
||||
conn.commit()
|
||||
for fn in files:
|
||||
try:
|
||||
@@ -373,19 +375,19 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
fields = []
|
||||
vals = []
|
||||
if d.name is not None and d.name.strip():
|
||||
fields.append("name = ?"); vals.append(d.name.strip())
|
||||
fields.append("name = %s"); vals.append(d.name.strip())
|
||||
if d.description:
|
||||
fields.append("description = ?"); vals.append(d.description.strip())
|
||||
fields.append("description = %s"); vals.append(d.description.strip())
|
||||
if d.category:
|
||||
fields.append("category = ?"); vals.append(d.category.strip())
|
||||
fields.append("category = %s"); vals.append(d.category.strip())
|
||||
if d.icon:
|
||||
fields.append("icon = ?"); vals.append(d.icon.strip())
|
||||
fields.append("icon = %s"); vals.append(d.icon.strip())
|
||||
if d.status in ("published", "disabled", "revoked"):
|
||||
fields.append("status = ?"); vals.append(d.status)
|
||||
fields.append("status = %s"); vals.append(d.status)
|
||||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||||
if d.force_min_version and d.force_deadline:
|
||||
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
|
||||
fields.append("force_min_version = %s"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = %s"); vals.append(d.force_deadline.strip())
|
||||
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
|
||||
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
|
||||
elif d.clear_force:
|
||||
@@ -395,9 +397,9 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
return {"ok": True} # 无更新项
|
||||
vals.append(pid)
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (pid,)).fetchone():
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (pid,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = %s", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
@@ -424,27 +426,27 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
p["field_count"] = len(props)
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = ? ORDER BY version", (p["id"],))]
|
||||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = %s", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM plugin_grants "
|
||||
"WHERE plugin_id = ?", (p["id"],))}
|
||||
"SELECT account, can_download, can_run FROM account_plugins "
|
||||
"WHERE plugin_id = %s", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, is_admin, dept, nickname, avatar, status, created_at "
|
||||
"FROM accounts ORDER BY id")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants "
|
||||
"WHERE account = ?", (a["account"],))}
|
||||
"SELECT plugin_id, can_download, can_run FROM account_plugins "
|
||||
"WHERE account = %s", (a["account"],))}
|
||||
admins = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||||
@@ -475,11 +477,11 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
|
||||
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||||
trend_rows = conn.execute(
|
||||
"SELECT substr(at,1,10) AS day, "
|
||||
"SELECT LEFT(at,10) AS day, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||||
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
|
||||
"FROM runtime_reports WHERE at >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day"
|
||||
).fetchall()
|
||||
trend_map = {r["day"]: r for r in trend_rows}
|
||||
trend = []
|
||||
@@ -553,7 +555,7 @@ def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||||
"ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
"ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
@@ -570,12 +572,26 @@ def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
|
||||
|
||||
@router.get("/api/admin/devices")
|
||||
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""执行机设备列表(按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
|
||||
" chrome_ok, last_seen, status, created_at, updated_at "
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s", (limit,))]
|
||||
return {"devices": rows}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
async def admin_shell_release(upload: UploadFile = File(...),
|
||||
version: str = Query(...),
|
||||
|
||||
@@ -42,7 +42,7 @@ def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = ?",
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
|
||||
if not row or not row["status"]:
|
||||
@@ -74,7 +74,7 @@ def admin_auth(a: schemas.AuthIn,
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, is_admin, dept, nickname, must_change_pwd, status, avatar "
|
||||
"FROM accounts WHERE account = ?",
|
||||
"FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||
_auth_fail(account)
|
||||
@@ -105,7 +105,7 @@ def admin_password(p: schemas.PwdIn,
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = ?",
|
||||
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = %s",
|
||||
(login,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "账号不存在")
|
||||
@@ -115,8 +115,8 @@ def admin_password(p: schemas.PwdIn,
|
||||
raise HTTPException(401, "原密码错误")
|
||||
_hex, _salt = _hash_password(p.new_password)
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 "
|
||||
"WHERE account = ?", (_hex, _salt, login))
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s, must_change_pwd = 0 "
|
||||
"WHERE account = %s", (_hex, _salt, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": login}
|
||||
|
||||
|
||||
@@ -38,14 +38,14 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
ding_uid = (d.dingtalk_uid or "").strip()
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = ?",
|
||||
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
if nickname and nickname != (row["nickname"] or ""):
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account,
|
||||
@@ -60,7 +60,7 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
_hex, _salt = _hash_password(pwd)
|
||||
conn.execute(
|
||||
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||
"dingtalk_uid, must_change_pwd) VALUES (?, ?, ?, 0, '', ?, ?, 1)",
|
||||
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||
(account, _hex, _salt, nickname, ding_uid))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "nickname": nickname,
|
||||
|
||||
@@ -11,4 +11,4 @@ router = APIRouter()
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": config.DB_PATH.name}
|
||||
return {"ok": True, "db": "mysql", "host": config.MYSQL_HOST, "database": config.MYSQL_DB}
|
||||
@@ -22,7 +22,7 @@ router = APIRouter()
|
||||
def _account_disabled(acct: str) -> bool:
|
||||
"""账号是否已停用(停用后机器侧一律不给插件/授权)。"""
|
||||
with _db() as conn:
|
||||
row = conn.execute("SELECT status FROM accounts WHERE account = ?", (acct,)).fetchone()
|
||||
row = conn.execute("SELECT status FROM accounts WHERE account = %s", (acct,)).fetchone()
|
||||
return bool(row) and not bool(row["status"])
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ def plugins(account: str = Query(default="", description="账号(旧底座按此
|
||||
SELECT p.id, p.name, p.latest_version AS version
|
||||
FROM plugins p
|
||||
JOIN account_plugins ap ON ap.plugin_id = p.id
|
||||
WHERE ap.account = ?
|
||||
WHERE ap.account = %s
|
||||
ORDER BY p.id
|
||||
""",
|
||||
(acct,),
|
||||
@@ -72,7 +72,7 @@ def platforms_allowed(account: str = Query(default="", description="账号(旧
|
||||
return {"account": acct, "allowed": []}
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s ORDER BY platform_id",
|
||||
(acct,),
|
||||
).fetchall()
|
||||
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
|
||||
@@ -112,7 +112,7 @@ def pkg(plugin_id: str, version: str,
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, version),
|
||||
).fetchone()
|
||||
if not row:
|
||||
@@ -147,9 +147,9 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT g.plugin_id, g.can_download, g.can_run, p.name, p.status, p.latest_version
|
||||
FROM plugin_grants g
|
||||
FROM account_plugins g
|
||||
JOIN plugins p ON p.id = g.plugin_id
|
||||
WHERE g.account = ?
|
||||
WHERE g.account = %s
|
||||
""",
|
||||
(account.strip(),),
|
||||
).fetchall()
|
||||
@@ -199,10 +199,10 @@ def download_ticket(plugin_id: str, version: str,
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT can_download FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
"SELECT can_download FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||||
(account.strip(), plugin_id)).fetchone()
|
||||
ver = conn.execute(
|
||||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, version)).fetchone()
|
||||
if not ver:
|
||||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||
@@ -243,12 +243,42 @@ def runtime_report(b: schemas.RuntimeReportIn,
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO runtime_reports(account, device_id, plugin_id, version, status, msg, duration_sec, at) "
|
||||
"VALUES (?,?,?,?,?,?,?,?)",
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/device/report")
|
||||
def device_report(b: schemas.DeviceReportIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""执行机心跳/环境上报(含 Chrome 检测结果):按 device_id 幂等 upsert 设备记录。
|
||||
|
||||
供壳(执行机底座)启动/定时上报本机环境;last_seen 与 status 由中心机统一维护
|
||||
在线态(status 由调用方按心跳状态传,离线清理逻辑在管理端查询侧)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
device_id = (b.device_id or "").strip()
|
||||
if not device_id:
|
||||
raise HTTPException(400, "device_id 不能为空")
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO devices(device_id, account, hostname, os, ip, "
|
||||
"chrome_installed, chrome_version, chrome_ok, last_seen, status) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
|
||||
"ON DUPLICATE KEY UPDATE "
|
||||
"account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), "
|
||||
"ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), "
|
||||
"chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), "
|
||||
"last_seen = VALUES(last_seen), status = VALUES(status)",
|
||||
(device_id, (b.account or "").strip(), (b.hostname or "").strip(),
|
||||
(b.os or "").strip(), (b.ip or "").strip(),
|
||||
int(bool(b.chrome_installed)), (b.chrome_version or "").strip(),
|
||||
int(bool(b.chrome_ok)), _now(), int(bool(b.status))))
|
||||
conn.commit()
|
||||
return {"ok": True, "device_id": device_id}
|
||||
|
||||
|
||||
# ==================== 壳子(执行机主程序)自动更新 ====================
|
||||
# shell/version.json 约定:{"version": "1.0.0", "filename": "setup-37du-host-1.0.0.exe",
|
||||
# "sha256": "<可选,安装包校验值>", "notes": "<可选,更新说明>"}
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
- dingtalk.py 钉钉官方接口 - pkgutil.py 插件包校验/解析/版本
|
||||
- schemas.py 请求体模型 - apis/ 路由子包(meta/plugins/auth/dingtalk/admin)
|
||||
|
||||
DB:controlplane.db(同目录)。包文件:packages/。可选:CONTROLPLANE_TOKEN 非空时客户端须带
|
||||
DB:MySQL(连接参数在 controlplane/.env 的 MYSQL_*,库 37du_center;首次启动自动建库建表+种子)。
|
||||
包文件:packages/。可选:CONTROLPLANE_TOKEN 非空时客户端须带
|
||||
X-API-Token 请求头。
|
||||
|
||||
运行(本地 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
@@ -23,7 +24,6 @@ from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from controlplane import config
|
||||
from controlplane.core.db import _init_db, _seed
|
||||
@@ -41,7 +41,7 @@ async def lifespan(app: FastAPI):
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du 内网插件控制面", lifespan=lifespan)
|
||||
app = FastAPI(title="37du 插件管理平台", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
@@ -52,12 +52,6 @@ app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_admin.router)
|
||||
|
||||
|
||||
# ==================== 挂载控制面前端产物 ====================
|
||||
# 源码模式 => config.DIST(controlplane/frontend/dist);exe 模式 => _MEIPASS/frontend/dist(打进 exe)
|
||||
if config.DIST.is_dir():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
@@ -86,6 +80,6 @@ if __name__ == "__main__":
|
||||
if sys.stderr is None:
|
||||
sys.stderr = open(os.devnull, "w")
|
||||
|
||||
print(f"[controlplane] http://0.0.0.0:{config.CONTROLPLANE_PORT} sqlite={config.DB_PATH.name}")
|
||||
print(f"[controlplane] http://0.0.0.0:{config.CONTROLPLANE_PORT} mysql={config.MYSQL_DB}@{config.MYSQL_HOST}")
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.CONTROLPLANE_PORT,
|
||||
log_config=LOG_CONFIG, log_level="info")
|
||||
|
Before Width: | Height: | Size: 70 B After Width: | Height: | Size: 70 B |
@@ -68,7 +68,7 @@ def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
raise HTTPException(401, "缺少有效登录态")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM accounts WHERE account = ? AND is_admin = 1", (account,)).fetchone()
|
||||
"SELECT 1 FROM accounts WHERE account = %s AND is_admin = 1", (account,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||
return account
|
||||
@@ -131,7 +131,7 @@ def _auth_account_lookup(account: str) -> dict:
|
||||
return {"exists": False, "nickname": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT nickname FROM accounts WHERE account = ?", (account.strip(),)).fetchone()
|
||||
"SELECT nickname FROM accounts WHERE account = %s", (account.strip(),)).fetchone()
|
||||
return {"exists": bool(row), "nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
|
||||
@@ -18,11 +18,12 @@ from pathlib import Path
|
||||
def _app_base() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent
|
||||
# 源码模式:core/config.py → controlplane/(.env、packages、keys、.admin_secret、shell 均位于包根)
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_base()
|
||||
DB_PATH = APP_DIR / "controlplane.db"
|
||||
DB_PATH = APP_DIR / "controlplane.db" # 历史 SQLite 路径,仅作迁移数据源/备份,不再读写
|
||||
PKG_DIR = APP_DIR / "packages"
|
||||
AVATAR_DIR = APP_DIR / "avatars"
|
||||
# 壳子(执行机主程序)更新源:version.json + setup 安装包,供执行端自动下载升级
|
||||
@@ -52,6 +53,12 @@ _load_dotenv()
|
||||
# 内部凭证(底座→统一后端的调用凭证)。为空则不强制(内网可信场景)。
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
CONTROLPLANE_PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||
# MySQL 数据层(控制面唯一存储,无 SQLite 回退)。连接参数在 controlplane/.env 配置。
|
||||
MYSQL_HOST = os.getenv("MYSQL_HOST", "")
|
||||
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
|
||||
MYSQL_USER = os.getenv("MYSQL_USER", "root")
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "")
|
||||
MYSQL_DB = os.getenv("MYSQL_DB") or os.getenv("MYSQL_DATABASE") or "37du_center"
|
||||
# 钉钉扫码自动建号的初始密码;新号无插件权限、仅空壳,首次登录须改密。
|
||||
DINGTALK_DEFAULT_PASSWORD = os.getenv("DINGTALK_DEFAULT_PASSWORD", "123456")
|
||||
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||
@@ -85,5 +92,3 @@ def _admin_secret() -> str:
|
||||
return _ADMIN_SECRET_FALLBACK
|
||||
|
||||
|
||||
# 前端产物目录:源码 controlplane/frontend/dist;打包 _MEIPASS/frontend/dist(打进 exe)
|
||||
DIST = Path(getattr(sys, "_MEIPASS", APP_DIR)) / "frontend" / "dist"
|
||||
+240
-146
@@ -1,29 +1,235 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机数据层:SQLite 访问 + 建表 + 种子 + 审计 + 常用时间戳。
|
||||
"""中心机数据层:MySQL 访问 + 幂等建表(DDL 内嵌) + 迁移版本 + 种子 + 审计 + 常用时间戳。
|
||||
|
||||
数据访问统一收敛到 `_db()` 连接(commit+close 收口),路由只在本层之上组合读写。
|
||||
- 数据访问统一收敛到 `_db()`(PyMySQL DictCursor,commit+close 收口),路由只在本层之上组合读写。
|
||||
- 建表 DDL 与 `desktop/controlplane/tools/schema_mysql.sql` 保持同步(该文件为人工建库权威源,
|
||||
本文件为运行时幂等副本;新增表/字段需两处同步维护)。
|
||||
- 数据库连接由 `controlplane/.env` 的 MYSQL_* 决定;控制面不再提供 SQLite 回退。
|
||||
- 参数占位符统一 `%s`(PyMySQL),禁止 `?`(SQLite 语法)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
from pymysql.cursors import DictCursor
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260916_001"
|
||||
|
||||
# 全量 DDL(11 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def _connect(server: bool = False) -> pymysql.connections.Connection:
|
||||
"""建立 PyMySQL 连接;server=True 时不指定 database(用于建库)。"""
|
||||
return pymysql.connect(
|
||||
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
|
||||
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
|
||||
database=None if server else config.MYSQL_DB,
|
||||
charset="utf8mb4", cursorclass=DictCursor, autocommit=False)
|
||||
|
||||
|
||||
class _DbConn:
|
||||
"""薄适配层:让路由层沿用旧 sqlite3 风格 `conn.execute(...)` 调用 PyMySQL。
|
||||
|
||||
PyMySQL 1.x 的 Connection 没有 execute() 快捷方法,故在此代理到 cursor,
|
||||
并透传 commit/rollback/close。execute() 每次新建游标(DictCursor 默认缓冲读取,
|
||||
返回后仍可 fetchone/fetchall/迭代),随连接关闭一并回收。
|
||||
"""
|
||||
|
||||
def __init__(self, conn: pymysql.connections.Connection) -> None:
|
||||
self._conn = conn
|
||||
|
||||
def execute(self, sql: str, args=None):
|
||||
# PyMySQL 的 Cursor.execute() 返回 rowcount(int),需返回游标以支持 .fetchone()/.fetchall()/迭代
|
||||
cur = self._conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
return cur
|
||||
|
||||
def commit(self) -> None:
|
||||
self._conn.commit()
|
||||
|
||||
def rollback(self) -> None:
|
||||
self._conn.rollback()
|
||||
|
||||
def close(self) -> None:
|
||||
self._conn.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(统一收口,避免长运行服务累积连接)。
|
||||
|
||||
sqlite3 原生 with 语义只 commit 不 close,这里补 close;异常时不 commit 等价于回滚。
|
||||
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚。
|
||||
"""
|
||||
conn = sqlite3.connect(config.DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
if not config.MYSQL_HOST:
|
||||
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||
conn = _connect()
|
||||
try:
|
||||
yield conn
|
||||
yield _DbConn(conn)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -33,142 +239,30 @@ def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _ensure_col(conn: sqlite3.Connection, table: str, col: str, ddl: str) -> None:
|
||||
"""幂等给表补列:列已存在则忽略(sqlite 无 ADD COLUMN IF NOT EXISTS)。"""
|
||||
cols = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
if col not in cols:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
|
||||
|
||||
|
||||
def _migrate_accounts(conn: sqlite3.Connection) -> None:
|
||||
"""老库 accounts 迁移:account 主键 → 自增 id 主键(account 改唯一键),并补新列。
|
||||
|
||||
仅当表缺 id 列时执行;新库/已迁移库直接跳过。old 表在此前已 _ensure_col 补齐
|
||||
must_change_pwd,故 SELECT 可直接引用。
|
||||
"""
|
||||
cols = {r["name"] for r in conn.execute("PRAGMA table_info(accounts)").fetchall()}
|
||||
if "id" in cols:
|
||||
return
|
||||
conn.executescript("""
|
||||
CREATE TABLE accounts_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
dept TEXT DEFAULT '',
|
||||
nickname TEXT DEFAULT '',
|
||||
dingtalk_uid TEXT DEFAULT '',
|
||||
must_change_pwd INTEGER DEFAULT 0,
|
||||
avatar TEXT DEFAULT '',
|
||||
status INTEGER DEFAULT 1,
|
||||
created_at TEXT DEFAULT ''
|
||||
);
|
||||
INSERT INTO accounts_new(account, password_hash, salt, is_admin, dept,
|
||||
nickname, dingtalk_uid, must_change_pwd)
|
||||
SELECT account, password_hash, salt, is_admin, dept,
|
||||
nickname, dingtalk_uid, COALESCE(must_change_pwd, 0)
|
||||
FROM accounts;
|
||||
DROP TABLE accounts;
|
||||
ALTER TABLE accounts_new RENAME TO accounts;
|
||||
""")
|
||||
def _ensure_database() -> None:
|
||||
"""幂等建库(utf8mb4)。"""
|
||||
conn = _connect(server=True)
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 "
|
||||
"COLLATE utf8mb4_unicode_ci" % config.MYSQL_DB)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _init_db() -> None:
|
||||
"""建表(幂等)。基础表 + 产品化扩展表(插件授权/审计/运行上报),并兼容旧库补列。"""
|
||||
"""建表(幂等 DDL)+ 登记迁移版本,替代旧的 _ensure_col 渐进补列。"""
|
||||
if not config.MYSQL_HOST:
|
||||
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||
_ensure_database()
|
||||
with _db() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
latest_version TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
plugin_id TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
uploaded_at TEXT NOT NULL,
|
||||
PRIMARY KEY (plugin_id, version)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, platform_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
dept TEXT DEFAULT '',
|
||||
nickname TEXT DEFAULT '',
|
||||
dingtalk_uid TEXT DEFAULT '',
|
||||
must_change_pwd INTEGER DEFAULT 0,
|
||||
avatar TEXT DEFAULT '',
|
||||
status INTEGER DEFAULT 1,
|
||||
created_at TEXT DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_grants (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
can_download INTEGER DEFAULT 1,
|
||||
can_run INTEGER DEFAULT 1,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
target TEXT DEFAULT '',
|
||||
detail TEXT DEFAULT '',
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
device_id TEXT DEFAULT '',
|
||||
plugin_id TEXT DEFAULT '',
|
||||
version TEXT DEFAULT '',
|
||||
status TEXT DEFAULT '',
|
||||
msg TEXT DEFAULT '',
|
||||
duration_sec INTEGER DEFAULT 0,
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
# 幂等补齐旧表可能缺失的可选列(sqlite ALTER 不支持 ADD COLUMN IF NOT EXISTS)
|
||||
_ensure_col(conn, "plugins", "description", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "category", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "icon", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "status", "TEXT DEFAULT 'published'")
|
||||
_ensure_col(conn, "plugins", "force_min_version", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "force_deadline", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "manifest", "TEXT DEFAULT '{}'")
|
||||
_ensure_col(conn, "plugin_versions", "sha256", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "runtime_reports", "duration_sec", "INTEGER DEFAULT 0")
|
||||
_ensure_col(conn, "accounts", "nickname", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "dingtalk_uid", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "must_change_pwd", "INTEGER DEFAULT 0")
|
||||
# 老库迁移:account 主键 → 自增 id 主键 + 补 avatar/status/created_at(幂等)
|
||||
_migrate_accounts(conn)
|
||||
_ensure_col(conn, "accounts", "avatar", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "status", "INTEGER DEFAULT 1")
|
||||
_ensure_col(conn, "accounts", "created_at", "TEXT DEFAULT ''")
|
||||
# 回填:老库 account_plugins 已有授权但 plugin_grants 为空,则按"全权限"补录,
|
||||
# 保证离线票据 license 不会漏掉存量授权(can_download=1, can_run=1)。
|
||||
for ddl in _DDL_TABLES:
|
||||
conn.execute(ddl)
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"SELECT ap.account, ap.plugin_id, 1, 1 FROM account_plugins ap "
|
||||
"LEFT JOIN plugin_grants g ON g.account = ap.account AND g.plugin_id = ap.plugin_id "
|
||||
"WHERE g.account IS NULL"
|
||||
)
|
||||
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
|
||||
(_SCHEMA_VERSION,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
@@ -180,20 +274,20 @@ def _seed() -> None:
|
||||
config.PKG_DIR.mkdir(exist_ok=True)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugins(id, name, latest_version) VALUES (?, ?, ?)",
|
||||
"INSERT IGNORE INTO plugins(id, name, latest_version) VALUES (%s, %s, %s)",
|
||||
("seal_check", "考勤月报封存检查", "1.0.0"),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
"INSERT IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (%s, %s, %s, %s)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||||
for _acc, _dept in (("puddy", "IT"),):
|
||||
_hex, _salt = _hash_password("123456")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (?, ?, ?, ?, ?)", (_acc, _hex, _salt, 1, _dept))
|
||||
"INSERT IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (%s, %s, %s, %s, %s)", (_acc, _hex, _salt, 1, _dept))
|
||||
conn.commit()
|
||||
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
@@ -205,8 +299,8 @@ def _audit(account: str, action: str, target: str = "", detail: str = "") -> Non
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO audit_logs(account, action, target, detail, at) VALUES (?,?,?,?,?)",
|
||||
"INSERT INTO audit_logs(account, action, target, detail, at) VALUES (%s,%s,%s,%s,%s)",
|
||||
(account or "", action, target or "", detail or "", _now()))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
pass
|
||||
|
||||
@@ -75,10 +75,10 @@ def _extract_manifest(content: bytes) -> dict | None:
|
||||
def _prune_versions(conn, plugin_id: str) -> list:
|
||||
"""仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。"""
|
||||
rows = conn.execute(
|
||||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,)).fetchall()
|
||||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = %s", (plugin_id,)).fetchall()
|
||||
stale = sorted(rows, key=lambda r: _version_key(r["version"]), reverse=True)[_KEEP_VERSIONS:]
|
||||
for r in stale:
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s AND version = %s",
|
||||
(plugin_id, r["version"]))
|
||||
return [r["filename"] for r in stale]
|
||||
|
||||
|
||||
@@ -21,6 +21,19 @@ class RuntimeReportIn(BaseModel):
|
||||
duration_sec: int = 0
|
||||
|
||||
|
||||
class DeviceReportIn(BaseModel):
|
||||
"""执行机心跳/环境上报(含 Chrome 检测结果),与 devices 表一一对应。"""
|
||||
device_id: str
|
||||
account: str = ""
|
||||
hostname: str = ""
|
||||
os: str = ""
|
||||
ip: str = ""
|
||||
chrome_installed: int = 0 # 是否已安装 Chrome:1=是 0=否
|
||||
chrome_version: str = "" # Chrome 版本号(检测到才填)
|
||||
chrome_ok: int = 0 # Chrome 是否就绪:1=是 0=否
|
||||
status: int = 1 # 设备状态:1=在线 0=离线
|
||||
|
||||
|
||||
class AuthIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 内网插件控制面</title>
|
||||
<title>37du 插件管理平台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
-167
@@ -10,7 +10,6 @@
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"naive-ui": "^2.45.3",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -64,24 +63,6 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@css-render/plugin-bem": {
|
||||
"version": "0.15.14",
|
||||
"resolved": "https://registry.npmjs.org/@css-render/plugin-bem/-/plugin-bem-0.15.14.tgz",
|
||||
"integrity": "sha512-QK513CJ7yEQxm/P3EwsI+d+ha8kSOcjGvD6SevM41neEMxdULE+18iuQK6tEChAWMOQNQPLG/Rw3Khb69r5neg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"css-render": "~0.15.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@css-render/vue3-ssr": {
|
||||
"version": "0.15.14",
|
||||
"resolved": "https://registry.npmjs.org/@css-render/vue3-ssr/-/vue3-ssr-0.15.14.tgz",
|
||||
"integrity": "sha512-//8027GSbxE9n3QlD73xFY6z4ZbHbvrOVB7AO6hsmrEzGbg+h2A09HboUyDgu+xsmj7JnvJD39Irt+2D0+iV8g==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
},
|
||||
"node_modules/@ctrl/tinycolor": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.1.tgz",
|
||||
@@ -100,12 +81,6 @@
|
||||
"vue": "^3.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emotion/hash": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz",
|
||||
"integrity": "sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
@@ -579,12 +554,6 @@
|
||||
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@juggle/resize-observer": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@juggle/resize-observer/-/resize-observer-3.4.0.tgz",
|
||||
"integrity": "sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@napi-rs/lzma-linux-x64-gnu": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
|
||||
@@ -1189,47 +1158,12 @@
|
||||
"integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/css-render": {
|
||||
"version": "0.15.14",
|
||||
"resolved": "https://registry.npmjs.org/css-render/-/css-render-0.15.14.tgz",
|
||||
"integrity": "sha512-9nF4PdUle+5ta4W5SyZdLCCmFd37uVimSjg1evcTqKJCyvCEEj12WKzOSBNak6r4im4J4iYXKH1OWpUV5LBYFg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@emotion/hash": "~0.8.0",
|
||||
"csstype": "~3.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/css-render/node_modules/csstype": {
|
||||
"version": "3.0.11",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.11.tgz",
|
||||
"integrity": "sha512-sa6P2wJ+CAbgyy4KFssIb/JNMLxFvKF1pCYCSXS8ZMuqZnMsrxqI2E5sPyoTpxoPU/gVZMzr2zjOfg8GIZOMsw==",
|
||||
"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/date-fns": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz",
|
||||
"integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/kossnocorp"
|
||||
}
|
||||
},
|
||||
"node_modules/date-fns-tz": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-3.2.0.tgz",
|
||||
"integrity": "sha512-sg8HqoTEulcbbbVXeg84u5UnlsQa8GS5QXMqjjYIhS4abEVVKIUwe0/l/UhrZdKaL/W5eWZNlbTeEIiOXTcsBQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"date-fns": "^3.0.0 || ^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dayjs": {
|
||||
"version": "1.11.23",
|
||||
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
|
||||
@@ -1322,12 +1256,6 @@
|
||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/evtd": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "https://registry.npmjs.org/evtd/-/evtd-0.2.4.tgz",
|
||||
"integrity": "sha512-qaeGN5bx63s/AXgQo8gj6fBkxge+OoLddLniox5qtLAEY5HSnuSlISXVPxnSae1dWblvTh4/HoMIB+mbMsvZzw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
@@ -1361,15 +1289,6 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/highlight.js": {
|
||||
"version": "11.12.0",
|
||||
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz",
|
||||
"integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.18.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||
@@ -1408,38 +1327,6 @@
|
||||
"integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/naive-ui": {
|
||||
"version": "2.45.3",
|
||||
"resolved": "https://registry.npmjs.org/naive-ui/-/naive-ui-2.45.3.tgz",
|
||||
"integrity": "sha512-D83gJ+6zUdkQ5DuUbmlfyaM1t8pV5WMPa6KmL9mByqQuiL12qBdA0n/iEIth4dQw1x/duNGpOS2anpt5FKO1kw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@css-render/plugin-bem": "^0.15.14",
|
||||
"@css-render/vue3-ssr": "^0.15.14",
|
||||
"@types/lodash": "^4.17.20",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"async-validator": "^4.2.5",
|
||||
"css-render": "^0.15.14",
|
||||
"csstype": "^3.1.3",
|
||||
"date-fns": "^4.1.0",
|
||||
"date-fns-tz": "^3.2.0",
|
||||
"evtd": "^0.2.4",
|
||||
"highlight.js": "^11.8.0",
|
||||
"lodash": "^4.17.21",
|
||||
"lodash-es": "^4.17.21",
|
||||
"seemly": "^0.3.10",
|
||||
"treemate": "^0.3.11",
|
||||
"vdirs": "^0.1.8",
|
||||
"vooks": "^0.2.12",
|
||||
"vueuc": "^0.4.66"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
@@ -1557,12 +1444,6 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/seemly": {
|
||||
"version": "0.3.10",
|
||||
"resolved": "https://registry.npmjs.org/seemly/-/seemly-0.3.10.tgz",
|
||||
"integrity": "sha512-2+SMxtG1PcsL0uyhkumlOU6Qo9TAQ/WyH7tthnPIOQB05/12jz9naq6GZ6iZ6ApVsO3rr2gsnTf3++OV63kE1Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
@@ -1589,24 +1470,6 @@
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/treemate": {
|
||||
"version": "0.3.11",
|
||||
"resolved": "https://registry.npmjs.org/treemate/-/treemate-0.3.11.tgz",
|
||||
"integrity": "sha512-M8RGFoKtZ8dF+iwJfAJTOH/SM4KluKOKRJpjCMhI8bG3qB74zrFoArKZ62ll0Fr3mqkMJiQOmWYkdYgDeITYQg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vdirs": {
|
||||
"version": "0.1.8",
|
||||
"resolved": "https://registry.npmjs.org/vdirs/-/vdirs-0.1.8.tgz",
|
||||
"integrity": "sha512-H9V1zGRLQZg9b+GdMk8MXDN2Lva0zx72MPahDKc30v+DtwKjfyOSXWRIX4t2mhDubM1H09gPhWeth/BJWPHGUw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"evtd": "^0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
@@ -1682,18 +1545,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vooks": {
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/vooks/-/vooks-0.2.12.tgz",
|
||||
"integrity": "sha512-iox0I3RZzxtKlcgYaStQYKEzWWGAduMmq+jS7OrNdQo1FgGfPMubGL3uGHOU9n97NIvfFDBGnpSvkWyb/NSn/Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"evtd": "^0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue": {
|
||||
"version": "3.5.42",
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.42.tgz",
|
||||
@@ -1720,24 +1571,6 @@
|
||||
"resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz",
|
||||
"integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vueuc": {
|
||||
"version": "0.4.66",
|
||||
"resolved": "https://registry.npmjs.org/vueuc/-/vueuc-0.4.66.tgz",
|
||||
"integrity": "sha512-hHrZl+0AsrUvqYPBXSXQ2QaSrO3razjeUseLAhJWlOS/Hdfw/Y2MU05fOTP1qn1A3121gMxsHLaEz2V6CkWdTg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@css-render/vue3-ssr": "^0.15.10",
|
||||
"@juggle/resize-observer": "^3.3.1",
|
||||
"css-render": "^0.15.10",
|
||||
"evtd": "^0.2.4",
|
||||
"seemly": "^0.3.6",
|
||||
"vdirs": "^0.1.4",
|
||||
"vooks": "^0.2.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"naive-ui": "^2.45.3",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,49 +1,56 @@
|
||||
<template>
|
||||
<n-config-provider :theme-overrides="themeOverrides" :locale="zhCN" :date-locale="dateZhCN">
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="console" v-else>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>中心机 · 控制面</span>
|
||||
</div>
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="console" v-else>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>中心机 · 控制面</span>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<n-dropdown trigger="click" :options="acctOptions" @select="onCommand">
|
||||
<div class="acct">
|
||||
<span class="avatar">{{ initial }}</span>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<n-tag v-if="store.isAdmin" size="small" round :bordered="false" type="primary" class="admin-tag">管理员</n-tag>
|
||||
<n-icon class="caret" :size="13"><ArrowDown /></n-icon>
|
||||
</div>
|
||||
</n-dropdown>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<aside class="aside">
|
||||
<div class="aside-inner">
|
||||
<n-menu class="menu" :value="activeKey" :options="menuOptions" :root-indent="0" @update:value="onMenu" />
|
||||
</div>
|
||||
<div class="aside-foot">
|
||||
<span>37du 自动化</span>
|
||||
<span class="ver">v0.1.0</span>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="main">
|
||||
<component :is="viewComp" :key="route" />
|
||||
</main>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<el-dropdown trigger="click" @command="onCommand">
|
||||
<div class="acct">
|
||||
<span class="avatar">{{ initial }}</span>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<el-tag v-if="store.isAdmin" size="small" type="primary" round effect="light" class="admin-tag">管理员</el-tag>
|
||||
<el-icon class="caret"><ArrowDown /></el-icon>
|
||||
</div>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="pwd"><el-icon><Lock /></el-icon>修改密码</el-dropdown-item>
|
||||
<el-dropdown-item divided command="logout"><el-icon><SwitchButton /></el-icon>退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<aside class="aside">
|
||||
<div class="aside-inner">
|
||||
<el-menu :default-active="activeKey" @select="onMenu">
|
||||
<el-menu-item v-for="m in menuOptions" :key="m.key" :index="m.key">
|
||||
<el-icon><component :is="m.icon" /></el-icon>
|
||||
<span>{{ m.label }}</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="main">
|
||||
<transition name="view-fade" mode="out-in">
|
||||
<component :is="viewComp" :key="route" />
|
||||
</transition>
|
||||
</main>
|
||||
</div>
|
||||
<PasswordDialog v-model="pwdOpen" />
|
||||
</n-config-provider>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ArrowDown } from '@element-plus/icons-vue'
|
||||
import { themeOverrides, zhCN, dateZhCN, message } from './naive'
|
||||
import { ArrowDown, Lock, SwitchButton, Odometer, TrendCharts, Box, User, Key, Document } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import PasswordDialog from './components/PasswordDialog.vue'
|
||||
import OverviewView from './views/OverviewView.vue'
|
||||
@@ -56,20 +63,15 @@ import { store, clearSession } from './store'
|
||||
import { adminMe } from './api'
|
||||
|
||||
const menuOptions = [
|
||||
{ label: '概览', key: 'overview' },
|
||||
{ label: '数据看板', key: 'stats' },
|
||||
{ label: '插件管理', key: 'plugins' },
|
||||
{ label: '账号管理', key: 'accounts' },
|
||||
{ label: '权限授权', key: 'grants' },
|
||||
{ label: '审计报表', key: 'audit' },
|
||||
]
|
||||
const acctOptions = [
|
||||
{ label: '修改密码', key: 'pwd' },
|
||||
{ type: 'divider', key: 'd1' },
|
||||
{ label: '退出登录', key: 'logout' },
|
||||
{ label: '概览', key: 'overview', icon: Odometer },
|
||||
{ label: '数据看板', key: 'stats', icon: TrendCharts },
|
||||
{ label: '插件管理', key: 'plugins', icon: Box },
|
||||
{ label: '账号管理', key: 'accounts', icon: User },
|
||||
{ label: '权限授权', key: 'grants', icon: Key },
|
||||
{ label: '审计报表', key: 'audit', icon: Document },
|
||||
]
|
||||
|
||||
// 轻量 hash 路由:StaticFiles(html=True) 下刷新安全,零后端改动
|
||||
// 轻量 hash 路由:静态站刷新安全,零后端改动
|
||||
const KEY = {
|
||||
'#/overview': 'overview',
|
||||
'#/stats': 'stats',
|
||||
@@ -129,71 +131,67 @@ onMounted(async () => {
|
||||
<style scoped>
|
||||
.console { height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* ---------- 顶栏:磨砂玻璃 ---------- */
|
||||
/* ---------- 顶栏:纸白面板 ---------- */
|
||||
.topbar {
|
||||
height: 64px; flex-shrink: 0;
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 0 24px;
|
||||
background: rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border-bottom: 1px solid var(--cp-border);
|
||||
padding: 0 26px;
|
||||
background: rgba(255, 253, 248, .86);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
border-bottom: 1px solid var(--cp-line);
|
||||
box-shadow: 0 6px 20px -18px rgba(35, 42, 58, .3);
|
||||
position: relative; z-index: 20;
|
||||
}
|
||||
.topbar::after {
|
||||
content: ''; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px;
|
||||
background: linear-gradient(90deg, transparent, rgba(59, 108, 255, .35), rgba(34, 199, 232, .35), transparent);
|
||||
background: linear-gradient(90deg, transparent, rgba(47, 92, 240, .4), rgba(15, 159, 155, .4), transparent);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 12px; }
|
||||
.logo {
|
||||
width: 38px; height: 38px; border-radius: 12px;
|
||||
display: grid; place-items: center; position: relative;
|
||||
background: linear-gradient(135deg, #3b6cff 0%, #22c7e8 130%);
|
||||
background: linear-gradient(135deg, var(--cp-blue) 0%, var(--cp-teal) 140%);
|
||||
color: #fff; font-size: 14px; font-weight: 800; letter-spacing: .5px;
|
||||
box-shadow: 0 6px 16px -6px rgba(59, 108, 255, .6);
|
||||
box-shadow: 0 8px 18px -8px rgba(47, 92, 240, .55);
|
||||
}
|
||||
.logo::after { content: ''; position: absolute; inset: 2px; border-radius: 10px; border: 1px solid rgba(255, 255, 255, .28); }
|
||||
.logo::after { content: ''; position: absolute; inset: 2px; border-radius: 10px; border: 1px solid rgba(255, 255, 255, .3); }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 15px; color: var(--cp-ink); letter-spacing: .2px; }
|
||||
.brand-meta strong { font-size: 15px; color: var(--cp-ink-1); letter-spacing: .2px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.spacer { flex: 1; }
|
||||
|
||||
.acct {
|
||||
display: flex; align-items: center; gap: 9px; cursor: pointer;
|
||||
padding: 6px 10px; border-radius: 12px; transition: background .18s;
|
||||
padding: 6px 12px; border-radius: 12px; border: 1px solid transparent;
|
||||
transition: background .18s, border-color .18s;
|
||||
}
|
||||
.acct:hover { background: rgba(59, 108, 255, .07); }
|
||||
.acct:hover { background: rgba(47, 92, 240, .06); border-color: rgba(47, 92, 240, .16); }
|
||||
.avatar {
|
||||
width: 30px; height: 30px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff, #22c7e8);
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff; font-size: 13px; font-weight: 700;
|
||||
}
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--cp-ink); }
|
||||
.acct-name { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.admin-tag { margin-left: 2px; }
|
||||
.caret { color: var(--cp-ink-3); }
|
||||
|
||||
/* ---------- 主体:悬浮侧栏 + 内容区 ---------- */
|
||||
.body { flex: 1; display: flex; gap: 18px; padding: 18px 24px 24px; min-height: 0; }
|
||||
/* ---------- 主体:侧栏 + 内容区(紧凑间距,避免挤压表格) ---------- */
|
||||
.body { flex: 1; display: flex; gap: 12px; padding: 14px 18px 22px; min-height: 0; }
|
||||
.aside {
|
||||
width: 208px; flex-shrink: 0;
|
||||
width: 192px; flex-shrink: 0;
|
||||
display: flex; flex-direction: column;
|
||||
background: rgba(255, 255, 255, .78);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
padding: 14px 10px;
|
||||
background: rgba(255, 253, 248, .8);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--cp-shadow);
|
||||
padding: 12px 8px;
|
||||
}
|
||||
.aside-inner { flex: 1; }
|
||||
.aside-foot {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 12px 12px 4px; margin-top: 8px;
|
||||
border-top: 1px dashed var(--cp-border);
|
||||
font-size: 11px; color: var(--cp-ink-3);
|
||||
}
|
||||
.main { flex: 1; min-width: 0; overflow: auto; padding: 4px 4px 8px; }
|
||||
.main { flex: 1; min-width: 0; overflow: auto; padding: 0 2px 8px; }
|
||||
|
||||
/* 页面切换过渡:轻微上浮淡入 */
|
||||
.view-fade-enter-active { transition: opacity .22s ease, transform .22s ease; }
|
||||
@@ -201,15 +199,18 @@ onMounted(async () => {
|
||||
.view-fade-enter-from { opacity: 0; transform: translateY(8px); }
|
||||
.view-fade-leave-to { opacity: 0; }
|
||||
|
||||
/* ---------- 侧栏菜单:干净的标准导航,配色由 naive 主题统一控制 ---------- */
|
||||
.menu { padding: 2px; }
|
||||
.menu :deep(.n-menu-item) { margin-bottom: 4px; }
|
||||
.menu :deep(.n-menu-item-content) {
|
||||
/* 无图标时 naive 给 `padding-left:0` 的内联样式,需 !important 压过,
|
||||
否则文字贴左边界、跑出圆角底色区域 */
|
||||
padding-left: 16px !important;
|
||||
padding-right: 16px !important;
|
||||
border-radius: 10px;
|
||||
box-sizing: border-box;
|
||||
/* ---------- 侧栏菜单:纸面导航 ---------- */
|
||||
.aside :deep(.el-menu-item) {
|
||||
height: 44px; margin-bottom: 4px;
|
||||
border-radius: 11px;
|
||||
font-weight: 600; color: var(--cp-ink-2);
|
||||
}
|
||||
.aside :deep(.el-menu-item:hover) { background: rgba(47, 92, 240, .06); color: var(--cp-blue); }
|
||||
.aside :deep(.el-menu-item.is-active) {
|
||||
background: linear-gradient(90deg, rgba(47, 92, 240, .12), rgba(47, 92, 240, .04));
|
||||
color: var(--cp-blue);
|
||||
font-weight: 700;
|
||||
box-shadow: inset 3px 0 0 var(--cp-blue);
|
||||
}
|
||||
.aside :deep(.el-menu-item .el-icon) { font-size: 17px; }
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<div class="card">
|
||||
<div class="card cp-rise">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
@@ -9,35 +9,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-form class="form" label-placement="top" @keydown.enter.prevent="doLogin">
|
||||
<n-form-item label="账号">
|
||||
<n-input
|
||||
v-model:value="account"
|
||||
placeholder="请输入账号"
|
||||
autocomplete="username"
|
||||
size="large"
|
||||
@keyup.enter="doLogin"
|
||||
>
|
||||
<template #prefix><n-icon><User /></n-icon></template>
|
||||
</n-input>
|
||||
</n-form-item>
|
||||
<n-form-item label="密码">
|
||||
<n-input
|
||||
v-model:value="password"
|
||||
type="password"
|
||||
placeholder="请输入密码"
|
||||
autocomplete="current-password"
|
||||
size="large"
|
||||
show-password-on="click"
|
||||
@keyup.enter="doLogin"
|
||||
>
|
||||
<template #prefix><n-icon><Lock /></n-icon></template>
|
||||
</n-input>
|
||||
</n-form-item>
|
||||
<n-button type="primary" size="large" block class="primary" :loading="busy" @click="doLogin">
|
||||
<el-form class="form" label-position="top" @keyup.enter="doLogin">
|
||||
<el-form-item label="账号">
|
||||
<el-input v-model="account" placeholder="请输入账号" autocomplete="username" size="large"
|
||||
:prefix-icon="User" @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 ? '登录中…' : '登 录' }}
|
||||
</n-button>
|
||||
</n-form>
|
||||
</el-button>
|
||||
</el-form>
|
||||
|
||||
<div class="foot">内网管理面 · 请使用管理员账号登录</div>
|
||||
</div>
|
||||
@@ -47,9 +31,9 @@
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { User, Lock } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminLogin } from '../api'
|
||||
import { store } from '../store.js'
|
||||
import { message } from '../naive'
|
||||
|
||||
const props = defineProps({ appName: { type: String, default: '37du 自动化工作台' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
@@ -71,7 +55,7 @@ async function doLogin() {
|
||||
store.token = r.token || ''
|
||||
store.isAdmin = true
|
||||
store.nickname = r.nickname || ''
|
||||
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) {}
|
||||
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) { }
|
||||
message.success(`欢迎,${store.nickname || acct}`)
|
||||
emit('ok', r)
|
||||
} catch (e) {
|
||||
@@ -90,37 +74,111 @@ async function doLogin() {
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
background: linear-gradient(180deg, #f7f8fa 0%, #eef0f4 100%);
|
||||
font-family: var(--font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif);
|
||||
}
|
||||
|
||||
.card {
|
||||
width: 380px;
|
||||
width: 404px;
|
||||
box-sizing: border-box;
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--cp-border, #e5e7ec);
|
||||
border-radius: 16px;
|
||||
padding: 34px 32px 28px;
|
||||
box-shadow: 0 16px 40px -24px rgba(30, 42, 76, .25);
|
||||
position: relative;
|
||||
background: var(--cp-panel);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 22px;
|
||||
padding: 40px 36px 28px;
|
||||
box-shadow: 0 26px 64px -30px rgba(35, 42, 58, .45);
|
||||
}
|
||||
|
||||
/* 顶部渐变描边 */
|
||||
.card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 30px;
|
||||
right: 30px;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, var(--cp-blue), var(--cp-teal), transparent);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* 纸面噪点质感 */
|
||||
.card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 22px;
|
||||
pointer-events: none;
|
||||
opacity: .5;
|
||||
background-image: radial-gradient(rgba(35, 42, 58, .08) 0.5px, transparent 0.5px);
|
||||
background-size: 5px 5px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-bottom: 30px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.brand { display: flex; align-items: center; gap: 14px; margin-bottom: 28px; }
|
||||
.logo {
|
||||
width: 42px; height: 42px; border-radius: 12px; flex: none;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff 0%, #22c7e8 130%);
|
||||
color: #fff; font-size: 15px; font-weight: 800; letter-spacing: .4px;
|
||||
box-shadow: 0 8px 18px -8px rgba(59, 108, 255, .55);
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
border-radius: 14px;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
position: relative;
|
||||
background: linear-gradient(135deg, var(--cp-blue) 0%, var(--cp-teal) 140%);
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .4px;
|
||||
box-shadow: 0 10px 22px -10px rgba(47, 92, 240, .6);
|
||||
}
|
||||
.brand-meta h1 { margin: 0; font-size: 17px; font-weight: 700; color: var(--cp-ink, #1c2433); letter-spacing: .2px; }
|
||||
.brand-meta p { margin: 3px 0 0; font-size: 12px; color: var(--cp-ink-3, #8a93a6); }
|
||||
|
||||
.form :deep(.n-form-item) { margin-bottom: 20px; }
|
||||
.form :deep(.n-form-item-label) { font-size: 12.5px; font-weight: 600; color: var(--cp-ink-2, #4a5270); padding-bottom: 6px; }
|
||||
.form :deep(.n-input) { border-radius: 8px; }
|
||||
.form :deep(.n-input__inner) { font-size: 14px; }
|
||||
.logo::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 2px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, .3);
|
||||
}
|
||||
|
||||
.primary.n-button--primary-type { height: 44px; border-radius: 8px; font-size: 14px; letter-spacing: .1em; }
|
||||
.brand-meta h1 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 800;
|
||||
color: var(--cp-ink-1);
|
||||
letter-spacing: .2px;
|
||||
}
|
||||
|
||||
.foot { margin-top: 20px; text-align: center; font-size: 11.5px; color: var(--cp-ink-3, #8a93a6); }
|
||||
</style>
|
||||
.brand-meta p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--cp-ink-3);
|
||||
letter-spacing: .4px;
|
||||
}
|
||||
|
||||
.form { position: relative; }
|
||||
.form .el-form-item { margin-bottom: 20px; }
|
||||
.form .el-form-item__label { font-size: 12.5px; font-weight: 700; padding-bottom: 6px; }
|
||||
.form .el-input__wrapper { border-radius: 10px; }
|
||||
|
||||
.primary {
|
||||
width: 100%;
|
||||
height: 46px;
|
||||
border-radius: 12px;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .12em;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.foot {
|
||||
margin-top: 24px;
|
||||
text-align: center;
|
||||
font-size: 11.5px;
|
||||
color: var(--cp-ink-3);
|
||||
letter-spacing: .4px;
|
||||
position: relative;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
<template>
|
||||
<n-modal v-model:show="visible" preset="card" title="修改密码" :style="{ width: '420px' }" :bordered="false" @after-leave="reset">
|
||||
<n-alert v-if="store.current" type="info" :bordered="false" class="acct-tip">当前账号:{{ store.current }}</n-alert>
|
||||
<n-form ref="formRef" :model="form" :rules="rules" label-placement="top">
|
||||
<n-form-item label="原密码" path="oldPwd">
|
||||
<n-input v-model:value="form.oldPwd" type="password" show-password-on="click" placeholder="请输入原密码" />
|
||||
</n-form-item>
|
||||
<n-form-item label="新密码" path="newPwd">
|
||||
<n-input v-model:value="form.newPwd" type="password" show-password-on="click" placeholder="至少 6 位,不与原密码相同" />
|
||||
</n-form-item>
|
||||
<n-form-item label="确认新密码" path="newPwd2">
|
||||
<n-input v-model:value="form.newPwd2" type="password" show-password-on="click" placeholder="再次输入新密码" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close @closed="reset">
|
||||
<el-alert v-if="store.current" type="info" :closable="false" class="acct-tip" show-icon>
|
||||
当前账号:<b class="mono">{{ store.current }}</b>
|
||||
</el-alert>
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top">
|
||||
<el-form-item label="原密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" placeholder="请输入原密码" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" placeholder="至少 6 位,不与原密码相同" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" placeholder="再次输入新密码" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="visible = false">取消</n-button>
|
||||
<n-button type="primary" :loading="busy" @click="submit">保存</n-button>
|
||||
</n-space>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="submit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { reactive, ref } from 'vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const visible = defineModel({ type: Boolean, default: false })
|
||||
const formRef = ref()
|
||||
@@ -37,17 +39,17 @@ const rules = {
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码' },
|
||||
{ min: 6, message: '新密码至少 6 位' },
|
||||
{ validator: (_r, v) => (v && v === form.oldPwd ? new Error('新密码不能与原密码相同') : true), message: '新密码不能与原密码相同' },
|
||||
{ validator: (_r, v, cb) => (v && v === form.oldPwd ? cb(new Error('新密码不能与原密码相同')) : cb()), message: '新密码不能与原密码相同' },
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码' },
|
||||
{ validator: (_r, v) => (v !== form.newPwd ? new Error('两次输入的密码不一致') : true), message: '两次输入的密码不一致' },
|
||||
{ validator: (_r, v, cb) => (v !== form.newPwd ? cb(new Error('两次输入的密码不一致')) : cb()), message: '两次输入的密码不一致' },
|
||||
],
|
||||
}
|
||||
|
||||
function reset() {
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
formRef.value?.restoreValidation()
|
||||
formRef.value?.resetFields()
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
@@ -66,5 +68,6 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.acct-tip { margin-bottom: 14px; }
|
||||
.acct-tip { margin-bottom: 16px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// 时间展示格式化:统一去掉 ISO 的 T,隐藏秒,避免出现 "2026-09-16T12:34:40" 这类原始格式
|
||||
export function fmtTime(iso) {
|
||||
if (!iso) return '—'
|
||||
if (!iso.includes('T')) return iso // 后端已是空格分隔格式,原样返回
|
||||
return iso.replace('T', ' ').slice(0, 16) // ISO → YYYY-MM-DD HH:mm
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import naive from 'naive-ui'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件,与 UI 框架解耦)
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件)
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
@@ -10,4 +11,4 @@ const app = createApp(App)
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(naive).mount('#app')
|
||||
app.use(ElementPlus).mount('#app')
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
// Naive UI 主题与离散式反馈(message/dialog 无需 Provider 包裹即可调用)
|
||||
import { createDiscreteApi, zhCN, dateZhCN } from 'naive-ui'
|
||||
|
||||
export const themeOverrides = {
|
||||
common: {
|
||||
primaryColor: '#3b6cff',
|
||||
primaryColorHover: '#5e84ff',
|
||||
primaryColorPressed: '#2f56d6',
|
||||
primaryColorSuppl: '#4c79ff',
|
||||
infoColor: '#3b6cff',
|
||||
successColor: '#22b07a',
|
||||
warningColor: '#eab308',
|
||||
errorColor: '#e5484d',
|
||||
borderRadius: '10px',
|
||||
borderRadiusSmall: '8px',
|
||||
fontFamily:
|
||||
'"HarmonyOS Sans SC","Microsoft YaHei UI","PingFang SC",-apple-system,"Segoe UI",sans-serif',
|
||||
},
|
||||
Card: {
|
||||
borderRadius: '16px',
|
||||
},
|
||||
Button: {
|
||||
borderRadiusMedium: '10px',
|
||||
borderRadiusLarge: '12px',
|
||||
},
|
||||
Menu: {
|
||||
itemHeight: '46px',
|
||||
itemBorderRadius: '10px',
|
||||
itemTextColor: '#3a4660',
|
||||
itemTextColorHover: '#3b6cff',
|
||||
itemTextColorActive: '#3b6cff',
|
||||
itemTextColorActiveHover: '#2f56d6',
|
||||
itemColorHover: 'rgba(31, 45, 80, .05)',
|
||||
itemColorActive: 'rgba(59, 108, 255, .10)',
|
||||
itemColorActiveHover: 'rgba(59, 108, 255, .15)',
|
||||
iconColor: '#7b8aa8',
|
||||
iconColorHover: '#3b6cff',
|
||||
iconColorActive: '#3b6cff',
|
||||
iconColorActiveHover: '#2f56d6',
|
||||
},
|
||||
DataTable: {
|
||||
thColor: '#f5f8fe',
|
||||
thTextColor: '#5b6b8c',
|
||||
thFontWeight: '600',
|
||||
tdColor: 'transparent',
|
||||
tdColorHover: 'rgba(59,108,255,.06)',
|
||||
borderColor: 'rgba(88,113,183,.10)',
|
||||
borderRadius: '12px',
|
||||
},
|
||||
Dialog: {
|
||||
borderRadius: '16px',
|
||||
},
|
||||
}
|
||||
|
||||
export const { message, dialog, notification } = createDiscreteApi(
|
||||
['message', 'dialog', 'notification'],
|
||||
{
|
||||
configProviderProps: { themeOverrides, locale: zhCN, dateLocale: dateZhCN },
|
||||
}
|
||||
)
|
||||
|
||||
export { zhCN, dateZhCN }
|
||||
@@ -2,7 +2,7 @@ import { reactive, ref } from 'vue'
|
||||
import { adminOverview } from './api'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '37du 内网插件控制面',
|
||||
appName: '37du 插件管理平台',
|
||||
isAdmin: false,
|
||||
current: _get('cp_account'),
|
||||
token: _get('cp_token'),
|
||||
|
||||
@@ -1,16 +1,65 @@
|
||||
/* ============ 37du 内网插件控制面 全局基础样式(组件由 Naive UI 提供) ============ */
|
||||
/* ============================================================
|
||||
37du 插件管理平台 · 全局样式(Element Plus)
|
||||
设计语言:纸张 + 墨色 · 编辑部数据台
|
||||
- 暖白纸感画布 + 细网格底纹
|
||||
- 深墨色文字 + 钴蓝/琥珀强调色
|
||||
- 数字/ID/时间用等宽字体,营造精密仪表感
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* 设计令牌:文字 / 边框 / 表面 / 品牌色 / 投影 */
|
||||
--cp-ink: #141c33;
|
||||
--cp-ink-2: #5b6b8c;
|
||||
--cp-ink-3: #94a3c4;
|
||||
--cp-border: rgba(88, 113, 183, .14);
|
||||
--cp-surface: rgba(255, 255, 255, .82);
|
||||
--cp-blue: #3b6cff;
|
||||
--cp-cyan: #22c7e8;
|
||||
--cp-violet: #8b5cf6;
|
||||
--cp-card-shadow: 0 10px 30px -14px rgba(43, 64, 132, .20);
|
||||
--cp-card-shadow-hover: 0 18px 44px -18px rgba(59, 108, 255, .30);
|
||||
/* ---------- Element Plus 主题变量 ---------- */
|
||||
--el-color-primary: #2f5cf0;
|
||||
--el-color-primary-light-3: #7a96f5;
|
||||
--el-color-primary-light-5: #a5b9f9;
|
||||
--el-color-primary-light-7: #cfdbfc;
|
||||
--el-color-primary-light-8: #e3eafd;
|
||||
--el-color-primary-light-9: #f1f5fe;
|
||||
--el-color-primary-dark-2: #2246c0;
|
||||
--el-color-success: #1d9d5c;
|
||||
--el-color-warning: #d97706;
|
||||
--el-color-danger: #d6453d;
|
||||
--el-color-error: #d6453d;
|
||||
--el-color-info: #7a8398;
|
||||
--el-bg-color: #fffdf8;
|
||||
--el-bg-color-overlay: #fffdf8;
|
||||
--el-bg-color-page: #f3f0e8;
|
||||
--el-fill-color-blank: #fffdf8;
|
||||
--el-fill-color: rgba(35, 42, 58, .08);
|
||||
--el-fill-color-light: rgba(35, 42, 58, .06);
|
||||
--el-fill-color-lighter: rgba(35, 42, 58, .04);
|
||||
--el-fill-color-extra-light: rgba(35, 42, 58, .03);
|
||||
--el-text-color-primary: #232a3a;
|
||||
--el-text-color-regular: #3b4358;
|
||||
--el-text-color-secondary: #6b7488;
|
||||
--el-text-color-placeholder: #9aa2b4;
|
||||
--el-text-color-disabled: #b9bfcc;
|
||||
--el-border-color: rgba(35, 42, 58, .16);
|
||||
--el-border-color-light: rgba(35, 42, 58, .12);
|
||||
--el-border-color-lighter: rgba(35, 42, 58, .10);
|
||||
--el-border-color-extra-light: rgba(35, 42, 58, .07);
|
||||
--el-border-radius-base: 10px;
|
||||
--el-border-radius-small: 8px;
|
||||
--el-box-shadow-light: 0 14px 34px -20px rgba(35, 42, 58, .28);
|
||||
--el-mask-color: rgba(20, 26, 40, .45);
|
||||
|
||||
/* ---------- 设计令牌 ---------- */
|
||||
--cp-bg: #f3f0e8; /* 纸感画布 */
|
||||
--cp-ink-1: #232a3a; /* 主墨色(标题) */
|
||||
--cp-ink: #3b4358; /* 正文 */
|
||||
--cp-ink-2: #6b7488; /* 次要文字 */
|
||||
--cp-ink-3: #9aa2b4; /* 弱化文字 */
|
||||
--cp-line: rgba(35, 42, 58, .12);
|
||||
--cp-line-strong: rgba(35, 42, 58, .22);
|
||||
--cp-panel: #fffdf8; /* 纸白面板 */
|
||||
--cp-panel-2: #faf7ee; /* 次级面板(轨道/底色) */
|
||||
--cp-blue: #2f5cf0;
|
||||
--cp-teal: #0f9f9b;
|
||||
--cp-amber: #d97706;
|
||||
--cp-success: #1d9d5c;
|
||||
--cp-danger: #d6453d;
|
||||
--cp-mono: ui-monospace, "Cascadia Code", "JetBrains Mono", Consolas, "Courier New", monospace;
|
||||
--cp-shadow: 0 14px 34px -22px rgba(35, 42, 58, .28);
|
||||
--cp-shadow-hover: 0 20px 44px -22px rgba(47, 92, 240, .30);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -21,57 +70,219 @@ body {
|
||||
font-size: 13px;
|
||||
color: var(--cp-ink);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
background-color: #eaf0fb;
|
||||
/* 浅色极光画布:三层低透明光晕 + 渐变底 */
|
||||
background-color: var(--cp-bg);
|
||||
/* 纸感画布:暖白底 + 低透明细网格 + 两侧轻微墨晕 */
|
||||
background-image:
|
||||
radial-gradient(1100px 520px at 88% -10%, rgba(59, 108, 255, .14), transparent 60%),
|
||||
radial-gradient(900px 480px at -8% 108%, rgba(34, 199, 232, .12), transparent 55%),
|
||||
radial-gradient(760px 420px at 55% 118%, rgba(139, 92, 246, .10), transparent 60%),
|
||||
linear-gradient(180deg, #f4f7fd 0%, #e9eefb 100%);
|
||||
radial-gradient(900px 420px at 90% -8%, rgba(47, 92, 240, .07), transparent 62%),
|
||||
radial-gradient(760px 400px at -6% 104%, rgba(15, 159, 155, .06), transparent 58%),
|
||||
linear-gradient(rgba(35, 42, 58, .035) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(35, 42, 58, .035) 1px, transparent 1px);
|
||||
background-size: auto, auto, 44px 44px, 44px 44px;
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
::selection { background: rgba(59, 108, 255, .18); }
|
||||
::selection { background: rgba(47, 92, 240, .16); }
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #c8d2e8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #b3c0de; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-thumb { background: rgba(35, 42, 58, .22); border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: rgba(35, 42, 58, .34); background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* ---------- Naive 组件统一质感 ---------- */
|
||||
.n-card {
|
||||
--n-border-color: var(--cp-border);
|
||||
--n-color: rgba(255, 255, 255, .82);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
/* ============================================================
|
||||
Element Plus 组件质感覆盖
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 按钮 ---------- */
|
||||
.el-button {
|
||||
--el-button-bg-color: #fffdf8;
|
||||
--el-button-border-color: rgba(35, 42, 58, .20);
|
||||
--el-button-text-color: var(--cp-ink);
|
||||
--el-button-hover-bg-color: #fff;
|
||||
--el-button-hover-border-color: var(--cp-blue);
|
||||
--el-button-hover-text-color: var(--cp-blue);
|
||||
--el-button-active-bg-color: #eef2fe;
|
||||
--el-button-active-border-color: var(--cp-blue);
|
||||
--el-button-active-text-color: var(--cp-blue);
|
||||
font-weight: 600;
|
||||
}
|
||||
.n-data-table {
|
||||
--n-border-color: rgba(88, 113, 183, .10);
|
||||
.el-button--primary {
|
||||
--el-button-bg-color: var(--cp-blue);
|
||||
--el-button-border-color: var(--cp-blue);
|
||||
--el-button-text-color: #fff;
|
||||
--el-button-hover-bg-color: #5579f3;
|
||||
--el-button-hover-border-color: #5579f3;
|
||||
--el-button-hover-text-color: #fff;
|
||||
--el-button-active-bg-color: #2246c0;
|
||||
--el-button-active-border-color: #2246c0;
|
||||
--el-button-active-text-color: #fff;
|
||||
box-shadow: 0 8px 18px -10px rgba(47, 92, 240, .55);
|
||||
}
|
||||
.el-button--danger {
|
||||
--el-button-bg-color: var(--cp-danger);
|
||||
--el-button-border-color: var(--cp-danger);
|
||||
--el-button-text-color: #fff;
|
||||
--el-button-hover-bg-color: #e26860;
|
||||
--el-button-hover-border-color: #e26860;
|
||||
--el-button-hover-text-color: #fff;
|
||||
--el-button-active-bg-color: #b33831;
|
||||
--el-button-active-border-color: #b33831;
|
||||
--el-button-active-text-color: #fff;
|
||||
}
|
||||
|
||||
/* ---------- 共享页面工具类 ---------- */
|
||||
.page { max-width: 1280px; margin: 0 auto; }
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 18px; }
|
||||
.page-head h3 { margin: 0 0 6px; font-size: 20px; font-weight: 700; letter-spacing: .2px; color: var(--cp-ink); display: flex; align-items: center; gap: 10px; }
|
||||
/* ---------- 输入类 ---------- */
|
||||
.el-input__wrapper,
|
||||
.el-select__wrapper {
|
||||
--el-input-border-color: rgba(35, 42, 58, .20);
|
||||
--el-input-hover-border-color: var(--cp-blue);
|
||||
--el-input-focus-border-color: var(--cp-blue);
|
||||
box-shadow: 0 0 0 1px rgba(35, 42, 58, .18) inset;
|
||||
background: #fffdf8;
|
||||
}
|
||||
.el-input__wrapper.is-focus,
|
||||
.el-select__wrapper.is-focused { box-shadow: 0 0 0 1px var(--cp-blue) inset, 0 0 0 3px rgba(47, 92, 240, .12); }
|
||||
.el-textarea__inner { background: #fffdf8; box-shadow: 0 0 0 1px rgba(35, 42, 58, .18) inset; }
|
||||
.el-textarea__inner:focus { box-shadow: 0 0 0 1px var(--cp-blue) inset, 0 0 0 3px rgba(47, 92, 240, .12); }
|
||||
|
||||
/* ---------- 卡片 ---------- */
|
||||
.el-card {
|
||||
--el-card-bg-color: var(--cp-panel);
|
||||
--el-card-border-color: var(--cp-line);
|
||||
--el-card-border-radius: 16px;
|
||||
border: 1px solid var(--cp-line);
|
||||
box-shadow: var(--cp-shadow);
|
||||
transition: box-shadow .22s ease, transform .22s ease;
|
||||
}
|
||||
.el-card:hover { box-shadow: var(--cp-shadow-hover); }
|
||||
|
||||
/* ---------- 表格 ---------- */
|
||||
.el-table {
|
||||
--el-table-border-color: rgba(35, 42, 58, .08);
|
||||
--el-table-header-bg-color: #f6f2e7;
|
||||
--el-table-header-text-color: var(--cp-ink-2);
|
||||
--el-table-row-hover-bg-color: rgba(47, 92, 240, .05);
|
||||
--el-table-bg-color: transparent;
|
||||
--el-table-tr-bg-color: transparent;
|
||||
--el-table-expanded-cell-bg-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
.el-table th.el-table__cell {
|
||||
font-weight: 700;
|
||||
font-size: 12px;
|
||||
letter-spacing: .4px;
|
||||
}
|
||||
.el-table .el-table__cell { padding: 9px 0; }
|
||||
.el-table__inner-wrapper::before { display: none; }
|
||||
.el-table--border .el-table__inner-wrapper::after { display: none; }
|
||||
|
||||
/* ---------- 标签 ---------- */
|
||||
.el-tag { font-weight: 600; }
|
||||
.el-tag--primary { --el-tag-bg-color: rgba(47,92,240,.10); --el-tag-border-color: rgba(47,92,240,.22); --el-tag-text-color: var(--cp-blue); }
|
||||
.el-tag--success { --el-tag-bg-color: rgba(29,157,92,.10); --el-tag-border-color: rgba(29,157,92,.24); --el-tag-text-color: #15803d; }
|
||||
.el-tag--warning { --el-tag-bg-color: rgba(217,119,6,.10); --el-tag-border-color: rgba(217,119,6,.24); --el-tag-text-color: var(--cp-amber); }
|
||||
.el-tag--danger { --el-tag-bg-color: rgba(214,69,61,.10); --el-tag-border-color: rgba(214,69,61,.24); --el-tag-text-color: var(--cp-danger); }
|
||||
.el-tag--info { --el-tag-bg-color: rgba(35,42,58,.06); --el-tag-border-color: rgba(35,42,58,.14); --el-tag-text-color: var(--cp-ink-2); }
|
||||
|
||||
/* ---------- 弹窗 / 浮层 ---------- */
|
||||
.el-dialog {
|
||||
--el-dialog-bg-color: var(--cp-panel);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 24px 60px -24px rgba(35, 42, 58, .4);
|
||||
}
|
||||
.el-dialog__header { padding-bottom: 14px; border-bottom: 1px solid var(--cp-line); }
|
||||
.el-dialog__title { font-weight: 800; color: var(--cp-ink-1); }
|
||||
.el-popper.is-light { background: var(--cp-panel); border-color: var(--cp-line); }
|
||||
.el-select-dropdown, .el-dropdown__popper { background: var(--cp-panel); }
|
||||
.el-select-dropdown__item.is-hovering { background: rgba(47, 92, 240, .08); }
|
||||
.el-select-dropdown__item.is-selected { color: var(--cp-blue); font-weight: 700; }
|
||||
|
||||
/* ---------- 开关 / 复选 / 单选 ---------- */
|
||||
.el-switch { --el-switch-on-color: var(--cp-blue); }
|
||||
.el-checkbox { --el-checkbox-checked-bg-color: var(--cp-blue); --el-checkbox-checked-input-border-color: var(--cp-blue); --el-checkbox-input-border-color: rgba(35,42,58,.3); --el-checkbox-text-color: var(--cp-ink); }
|
||||
.el-checkbox__label { font-weight: 500; }
|
||||
|
||||
/* ---------- 表单 ---------- */
|
||||
.el-form-item__label { font-weight: 600; color: var(--cp-ink-2); }
|
||||
|
||||
/* ---------- 标签页 ---------- */
|
||||
.el-tabs__item { font-weight: 600; color: var(--cp-ink-2); }
|
||||
.el-tabs__item.is-active { color: var(--cp-blue); }
|
||||
.el-tabs__active-bar { background-color: var(--cp-blue); height: 3px; border-radius: 2px; }
|
||||
|
||||
/* ---------- 消息 / 提示 ---------- */
|
||||
.el-message { background: var(--cp-panel); border-color: var(--cp-line); box-shadow: var(--cp-shadow); }
|
||||
.el-message-box { background: var(--cp-panel); border: 1px solid var(--cp-line); border-radius: 16px; }
|
||||
|
||||
/* ---------- 空态 / 骨架 ---------- */
|
||||
.el-empty__description p { color: var(--cp-ink-3); }
|
||||
.el-skeleton { --el-skeleton-color: rgba(35,42,58,.06); --el-skeleton-to-color: rgba(35,42,58,.10); }
|
||||
|
||||
/* ---------- 菜单 ---------- */
|
||||
.el-menu { border-right: none !important; background: transparent; }
|
||||
|
||||
/* ============================================================
|
||||
共享页面工具类
|
||||
============================================================ */
|
||||
.page { max-width: 1400px; margin: 0 auto; }
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 20px; }
|
||||
.page-head h3 {
|
||||
margin: 0 0 6px; font-size: 22px; font-weight: 800; letter-spacing: .3px;
|
||||
color: var(--cp-ink-1); display: flex; align-items: center; gap: 12px;
|
||||
}
|
||||
.page-head h3 .badge {
|
||||
font-size: 11px; font-weight: 600; color: var(--cp-blue); letter-spacing: .6px;
|
||||
background: rgba(59, 108, 255, .10); border: 1px solid rgba(59, 108, 255, .18);
|
||||
padding: 2px 9px; border-radius: 20px;
|
||||
font-size: 10.5px; font-weight: 700; color: var(--cp-blue); letter-spacing: 1px;
|
||||
font-family: var(--cp-mono); text-transform: uppercase;
|
||||
background: rgba(47, 92, 240, .08); border: 1px solid rgba(47, 92, 240, .2);
|
||||
padding: 3px 10px; border-radius: 20px;
|
||||
}
|
||||
.page-head p { margin: 0; font-size: 12.5px; color: var(--cp-ink-3); }
|
||||
.block { margin-bottom: 16px; }
|
||||
.page-head p { margin: 0; font-size: 12.5px; color: var(--cp-ink-3); letter-spacing: .2px; }
|
||||
.block { margin-bottom: 18px; }
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.who { color: var(--cp-blue); font-weight: 600; }
|
||||
.who { color: var(--cp-blue); font-weight: 700; }
|
||||
|
||||
/* 卡片标题前的小渐变竖条 */
|
||||
.card-title { font-size: 15px; font-weight: 700; color: var(--cp-ink); display: flex; align-items: center; gap: 8px; }
|
||||
.card-title::before { content: ''; width: 4px; height: 14px; border-radius: 3px; background: linear-gradient(180deg, #3b6cff, #22c7e8); }
|
||||
/* 面板卡片 */
|
||||
.cp-card {
|
||||
position: relative;
|
||||
background: var(--cp-panel);
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--cp-shadow);
|
||||
transition: box-shadow .22s ease, transform .22s ease;
|
||||
}
|
||||
.cp-card:hover { box-shadow: var(--cp-shadow-hover); }
|
||||
/* 卡片顶部渐变发丝线 */
|
||||
.cp-card::before {
|
||||
content: ''; position: absolute; top: 0; left: 22px; right: 22px; height: 1px;
|
||||
background: linear-gradient(90deg, transparent, rgba(47, 92, 240, .45), rgba(15, 159, 155, .45), transparent);
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
/* 表格单元格通用 */
|
||||
.cell-strong { font-weight: 700; color: var(--cp-ink); }
|
||||
/* 小标题(带竖线标记) */
|
||||
.card-title {
|
||||
font-size: 14px; font-weight: 800; color: var(--cp-ink-1);
|
||||
display: flex; align-items: center; gap: 9px;
|
||||
}
|
||||
.card-title::before {
|
||||
content: ''; width: 4px; height: 14px; border-radius: 2px;
|
||||
background: linear-gradient(180deg, var(--cp-blue), var(--cp-teal));
|
||||
}
|
||||
|
||||
/* 等宽数字(ID / 时间 / 统计值) */
|
||||
.mono { font-family: var(--cp-mono); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* 表格列通用 */
|
||||
.cell-strong { font-weight: 700; color: var(--cp-ink-1); }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
|
||||
/* 表格列内 render 的动态节点(不继承 scoped,全局生效) */
|
||||
.acct { line-height: 1.3; }
|
||||
.acct .ann { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); }
|
||||
.acct .anick { font-size: 11px; color: var(--cp-ink-3); }
|
||||
|
||||
/* 状态圆点 */
|
||||
.status-dot { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.status-dot i { width: 7px; height: 7px; border-radius: 50%; display: inline-block; }
|
||||
|
||||
/* ---------- 动效 ---------- */
|
||||
@keyframes cp-rise { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
|
||||
.cp-rise { animation: cp-rise .5s cubic-bezier(.22, .61, .36, 1) both; }
|
||||
|
||||
@@ -5,123 +5,149 @@
|
||||
<h3>账号管理 <span class="badge">Accounts</span></h3>
|
||||
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||
</div>
|
||||
<n-space :size="10">
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<n-button type="primary" @click="openCreate">
|
||||
<template #icon><n-icon><Plus /></n-icon></template>新建账号
|
||||
</n-button>
|
||||
</n-space>
|
||||
<div class="head-acts">
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建账号</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-card class="cp-rise" :bordered="false">
|
||||
<n-data-table
|
||||
:columns="columns"
|
||||
:data="accounts"
|
||||
:loading="overviewBusy"
|
||||
:row-key="r => r.account"
|
||||
:single-line="false"
|
||||
/>
|
||||
</n-card>
|
||||
<!-- 账号卡片 -->
|
||||
<div class="acct-grid" v-if="accounts.length">
|
||||
<div class="acct-card cp-card cp-rise" v-for="(a, i) in accounts" :key="a.account" :style="{ animationDelay: i * 40 + 'ms' }">
|
||||
<div class="acct-top">
|
||||
<div class="avatar-wrap">
|
||||
<img v-if="a.avatar" :src="`/api/avatar/${a.account}?v=${encodeURIComponent(a.avatar)}`" class="avatar"
|
||||
@error="e => e.target.style.display = 'none'" />
|
||||
<span v-else class="avatar avatar-fallback">{{ (a.nickname || a.account || '?')[0].toUpperCase() }}</span>
|
||||
<el-tooltip content="上传头像" placement="top">
|
||||
<span class="avatar-edit" @click="pickAvatar(a)"><el-icon><Camera /></el-icon></span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
<div class="acct-id">
|
||||
<div class="id-row">
|
||||
<span class="acct-account mono">{{ a.account }}</span>
|
||||
<el-tag v-if="a.is_admin" size="small" type="primary" round effect="light">管理员</el-tag>
|
||||
</div>
|
||||
<div class="acct-nick">{{ a.nickname || '未设置昵称' }}</div>
|
||||
</div>
|
||||
<div class="acct-actions">
|
||||
<el-tooltip content="重置密码"><el-button link type="primary" :icon="EditPen" @click="resetPwd(a)" /></el-tooltip>
|
||||
<el-tooltip content="编辑资料"><el-button link type="info" :icon="Edit" @click="openEdit(a)" /></el-tooltip>
|
||||
<el-tooltip content="删除账号"><el-button link type="danger" :icon="Delete" :disabled="a.account === current" @click="delAccount(a)" /></el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="acct-tags">
|
||||
<span class="tag-label">状态</span>
|
||||
<el-switch size="small" :model-value="!!a.status" :disabled="a.account === current"
|
||||
:loading="busySwitch === a.account" @change="v => toggleStatus(a, v)" />
|
||||
<el-tag v-if="a.dept" size="small" type="info" effect="plain" round>{{ a.dept }}</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="acct-tags" v-if="a.plugins?.length">
|
||||
<span class="tag-label">插件</span>
|
||||
<el-tag v-for="p in a.plugins.slice(0, 3)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||
<span v-if="a.plugins.length > 3" class="more mono">+{{ a.plugins.length - 3 }}</span>
|
||||
</div>
|
||||
<div class="acct-tags" v-else>
|
||||
<span class="tag-label">插件</span>
|
||||
<span class="dim">未授权</span>
|
||||
</div>
|
||||
|
||||
<div class="acct-tags" v-if="a.platforms?.length">
|
||||
<span class="tag-label">平台</span>
|
||||
<el-tag v-for="pf in a.platforms" :key="pf" size="small" type="success" effect="light" round>{{ pf }}</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="acct-foot">
|
||||
<span class="mono created dim-sm">创建于 {{ fmtTime(a.created_at) }}</span>
|
||||
<span class="mono uid dim-sm">ID {{ a.id ?? '—' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else-if="!overviewBusy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||
|
||||
<!-- 新建账号 -->
|
||||
<n-modal v-model:show="createOpen" preset="card" title="新建账号" :style="{ width: '420px' }" :bordered="false" @after-leave="resetCreate">
|
||||
<n-form ref="formRef" :model="form" :rules="rules" label-placement="top">
|
||||
<n-form-item label="账号" path="account">
|
||||
<n-input v-model:value="form.account" placeholder="登录账号" />
|
||||
</n-form-item>
|
||||
<n-form-item label="昵称">
|
||||
<n-input v-model:value="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</n-form-item>
|
||||
<n-form-item label="初始密码" path="password">
|
||||
<n-input v-model:value="form.password" type="password" show-password-on="click" placeholder="至少 6 位" />
|
||||
</n-form-item>
|
||||
<n-form-item label="部门">
|
||||
<n-input v-model:value="form.dept" placeholder="如 财务部 / IT" />
|
||||
</n-form-item>
|
||||
<n-form-item label="管理员">
|
||||
<n-switch v-model:value="form.is_admin" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<el-dialog v-model="createOpen" title="新建账号" width="440px" align-center destroy-on-close @closed="resetCreate">
|
||||
<el-form ref="createFormRef" :model="form" :rules="rules" label-position="top">
|
||||
<el-form-item label="账号" prop="account">
|
||||
<el-input v-model="form.account" placeholder="登录账号" />
|
||||
</el-form-item>
|
||||
<el-form-item label="昵称">
|
||||
<el-input v-model="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="初始密码" prop="password">
|
||||
<el-input v-model="form.password" type="password" placeholder="至少 6 位" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-input v-model="form.dept" placeholder="如 财务部 / IT" />
|
||||
</el-form-item>
|
||||
<el-form-item label="管理员">
|
||||
<el-switch v-model="form.is_admin" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="createOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="creating" @click="createAccount">建号</n-button>
|
||||
</n-space>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="createOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="creating" @click="createAccount">建号</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 编辑资料 -->
|
||||
<el-dialog v-model="editOpen" title="编辑账号资料" width="420px" align-center destroy-on-close>
|
||||
<el-form :model="editForm" label-position="top">
|
||||
<el-form-item label="账号">
|
||||
<el-input :model-value="editTarget" disabled class="mono" />
|
||||
</el-form-item>
|
||||
<el-form-item label="昵称">
|
||||
<el-input v-model="editForm.nickname" placeholder="真实姓名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-input v-model="editForm.dept" placeholder="如 财务部 / IT" />
|
||||
</el-form-item>
|
||||
<el-form-item label="管理员">
|
||||
<el-switch v-model="editForm.is_admin" :disabled="editTarget === current" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="editOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="savingEdit" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 重置密码 -->
|
||||
<n-modal v-model:show="resetOpen" preset="card" title="重置密码" :style="{ width: '400px' }" :bordered="false">
|
||||
<n-alert v-if="resetTarget" type="info" :bordered="false" style="margin-bottom: 14px">
|
||||
为账号 <b>{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
</n-alert>
|
||||
<n-input v-model:value="resetPwdVal" type="password" show-password-on="click" placeholder="新密码(至少 6 位)" @keydown.enter="confirmReset" />
|
||||
<el-dialog v-model="resetOpen" title="重置密码" width="420px" align-center destroy-on-close>
|
||||
<el-alert type="info" :closable="false" class="reset-tip" show-icon>
|
||||
为账号 <b class="mono">{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
</el-alert>
|
||||
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 6 位)" show-password @keyup.enter="confirmReset" />
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="resetOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="resetting" @click="confirmReset">确认重置</n-button>
|
||||
</n-space>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="resetOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="resetting" @click="confirmReset">确认重置</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { NButton, NInput, NSwitch, NTag } from 'naive-ui'
|
||||
import { Refresh, Plus } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, Plus, Camera, EditPen, Edit, Delete } from '@element-plus/icons-vue'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||
import { message, dialog } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
const busySwitch = ref('')
|
||||
|
||||
// ---------- 部门 / 昵称 行内编辑 ----------
|
||||
const editing = ref('') // 正在编辑的账号
|
||||
const editField = ref('') // 'dept' | 'nickname'
|
||||
const editDraft = ref('')
|
||||
function startEdit(row, field) {
|
||||
if (row.account === current.value) return
|
||||
editing.value = row.account
|
||||
editField.value = field
|
||||
editDraft.value = row[field] || ''
|
||||
}
|
||||
async function saveEdit(row) {
|
||||
if (editing.value !== row.account) return
|
||||
const field = editField.value
|
||||
editing.value = ''
|
||||
const val = (editDraft.value || '').trim()
|
||||
if (val === (row[field] || '')) return
|
||||
try {
|
||||
await adminAccountUpdate({ account: row.account, [field]: val })
|
||||
message.success(`已更新 ${row.account} 的${field === 'nickname' ? '昵称' : '部门'}`)
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
function inlineInput(row, field) {
|
||||
if (row.account === editing.value && editField.value === field) {
|
||||
return h(NInput, {
|
||||
value: editDraft.value,
|
||||
size: 'small',
|
||||
style: 'width: 140px',
|
||||
onUpdateValue: v => (editDraft.value = v),
|
||||
onKeyup: (e) => { if (e.key === 'Enter') saveEdit(row) },
|
||||
onBlur: () => saveEdit(row),
|
||||
})
|
||||
}
|
||||
return h('span', { class: 'dept', onClick: () => startEdit(row, field) },
|
||||
row[field] || '—')
|
||||
}
|
||||
async function toggleAdmin(row) {
|
||||
try { await adminAccountUpdate({ account: row.account, is_admin: !row.is_admin }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
async function toggleStatus(row, v) {
|
||||
if (row.account === current.value && !v) { message.warning('不能停用当前登录的账号'); return }
|
||||
try { await adminAccountUpdate({ account: row.account, status: v }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
// ---------- 头像(显示 + 上传) ----------
|
||||
@@ -131,83 +157,32 @@ const _fileInput = (() => {
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar(row) {
|
||||
function pickAvatar(a) {
|
||||
_fileInput.onchange = async () => {
|
||||
const f = _fileInput.files && _fileInput.files[0]
|
||||
_fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
await adminAvatarUpload(row.account, f)
|
||||
message.success(`已更新 ${row.account} 的头像`)
|
||||
await adminAvatarUpload(a.account, f)
|
||||
message.success(`已更新 ${a.account} 的头像`)
|
||||
await refresh()
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
_fileInput.click()
|
||||
}
|
||||
function avatarCell(row) {
|
||||
const img = row.avatar
|
||||
? h('img', {
|
||||
src: `/api/avatar/${row.account}?v=${encodeURIComponent(row.avatar)}`,
|
||||
class: 'cell-avatar',
|
||||
onError: (e) => { e.target.style.display = 'none' },
|
||||
})
|
||||
: h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'cell-avatar-wrap' }, [
|
||||
img,
|
||||
h(NButton, { text: true, size: 'tiny', type: 'primary', onClick: () => pickAvatar(row) }, { default: () => '上传' }),
|
||||
])
|
||||
}
|
||||
|
||||
function renderTags(list, kind) {
|
||||
if (!list || !list.length) return h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'tags' }, list.map(t => h(NTag, {
|
||||
size: 'small', round: true, bordered: false,
|
||||
type: kind === 'platform' ? 'success' : 'primary',
|
||||
}, { default: () => t })))
|
||||
async function toggleStatus(a, v) {
|
||||
if (a.account === current.value && !v) { message.warning('不能停用当前登录的账号'); return }
|
||||
busySwitch.value = a.account
|
||||
try { await adminAccountUpdate({ account: a.account, status: v }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
finally { busySwitch.value = '' }
|
||||
}
|
||||
|
||||
const columns = computed(() => [
|
||||
{ title: 'ID', key: 'id', width: 64, render: r => h('span', { class: 'dim' }, r.id ?? '—') },
|
||||
{ title: '用户名(工号)', key: 'account', width: 130, render: r => h('b', { class: 'cell-strong' }, r.account) },
|
||||
{ title: '昵称(姓名)', key: 'nickname', width: 130, render: r => inlineInput(r, 'nickname') },
|
||||
{ title: '部门', key: 'dept', width: 130, render: (row) => inlineInput(row, 'dept') },
|
||||
{ title: '头像', key: 'avatar', width: 120, render: r => avatarCell(r) },
|
||||
{
|
||||
title: '状态', key: 'status', width: 90,
|
||||
render: (row) => h(NSwitch, {
|
||||
value: !!row.status,
|
||||
disabled: row.account === current.value,
|
||||
onUpdateValue: (v) => toggleStatus(row, v),
|
||||
}),
|
||||
},
|
||||
{ title: '创建时间', key: 'created_at', width: 150, render: r => h('span', { class: 'dim' }, r.created_at || '—') },
|
||||
{
|
||||
title: '管理员', key: 'is_admin', width: 90,
|
||||
render: (row) => h(NSwitch, {
|
||||
value: !!row.is_admin,
|
||||
disabled: row.account === current.value,
|
||||
onUpdateValue: () => toggleAdmin(row),
|
||||
}),
|
||||
},
|
||||
{ title: '已授权插件', key: 'plugins', minWidth: 160, render: r => renderTags(r.plugins, 'plugin') },
|
||||
{ title: '已授权平台', key: 'platforms', minWidth: 130, render: r => renderTags(r.platforms, 'platform') },
|
||||
{
|
||||
title: '操作', key: 'actions', width: 170,
|
||||
render: (row) => h('div', { class: 'ops' }, [
|
||||
h(NButton, { text: true, type: 'primary', onClick: () => resetPwd(row) }, { default: () => '重置密码' }),
|
||||
h(NButton, {
|
||||
text: true, type: 'error',
|
||||
disabled: row.account === current.value,
|
||||
onClick: () => delAccount(row),
|
||||
}, { default: () => '删除' }),
|
||||
]),
|
||||
},
|
||||
])
|
||||
|
||||
// ---------- 新建账号 ----------
|
||||
const createOpen = ref(false)
|
||||
const creating = ref(false)
|
||||
const formRef = ref()
|
||||
const createFormRef = ref()
|
||||
const form = reactive({ account: '', password: '', dept: '', nickname: '', is_admin: false })
|
||||
const rules = {
|
||||
account: { required: true, message: '请输入账号' },
|
||||
@@ -220,10 +195,10 @@ function openCreate() { createOpen.value = true }
|
||||
function resetCreate() {
|
||||
form.account = form.password = form.dept = form.nickname = ''
|
||||
form.is_admin = false
|
||||
formRef.value?.restoreValidation()
|
||||
createFormRef.value?.resetFields()
|
||||
}
|
||||
async function createAccount() {
|
||||
try { await formRef.value.validate() } catch (_) { return }
|
||||
try { await createFormRef.value.validate() } catch (_) { return }
|
||||
creating.value = true
|
||||
try {
|
||||
await adminAccountCreate({ ...form, account: form.account.trim() })
|
||||
@@ -234,13 +209,36 @@ async function createAccount() {
|
||||
finally { creating.value = false }
|
||||
}
|
||||
|
||||
// ---------- 编辑资料 ----------
|
||||
const editOpen = ref(false)
|
||||
const savingEdit = ref(false)
|
||||
const editTarget = ref('')
|
||||
const editForm = reactive({ nickname: '', dept: '', is_admin: false })
|
||||
function openEdit(a) {
|
||||
editTarget.value = a.account
|
||||
editForm.nickname = a.nickname || ''
|
||||
editForm.dept = a.dept || ''
|
||||
editForm.is_admin = !!a.is_admin
|
||||
editOpen.value = true
|
||||
}
|
||||
async function saveEdit() {
|
||||
savingEdit.value = true
|
||||
try {
|
||||
await adminAccountUpdate({ account: editTarget.value, nickname: editForm.nickname, dept: editForm.dept, is_admin: editForm.is_admin })
|
||||
message.success(`已更新 ${editTarget.value}`)
|
||||
editOpen.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
finally { savingEdit.value = false }
|
||||
}
|
||||
|
||||
// ---------- 重置密码 ----------
|
||||
const resetOpen = ref(false)
|
||||
const resetTarget = ref('')
|
||||
const resetPwdVal = ref('')
|
||||
const resetting = ref(false)
|
||||
function resetPwd(row) {
|
||||
resetTarget.value = row.account
|
||||
function resetPwd(a) {
|
||||
resetTarget.value = a.account
|
||||
resetPwdVal.value = ''
|
||||
resetOpen.value = true
|
||||
}
|
||||
@@ -256,34 +254,75 @@ async function confirmReset() {
|
||||
finally { resetting.value = false }
|
||||
}
|
||||
|
||||
function delAccount(row) {
|
||||
dialog.warning({
|
||||
title: '删除账号',
|
||||
content: `确认删除账号 ${row.account}?其插件授权将一并清除`,
|
||||
positiveText: '删除',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
try { await adminAccountDelete({ account: row.account }); message.success(`已删除 ${row.account}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
},
|
||||
})
|
||||
function delAccount(a) {
|
||||
dialog.confirm(`确认删除账号 ${a.account}?其插件授权将一并清除`, '删除账号', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
}).then(async () => {
|
||||
try { await adminAccountDelete({ account: a.account }); message.success(`已删除 ${a.account}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dept { cursor: pointer; border-bottom: 1px dashed transparent; transition: border-color .15s; }
|
||||
.dept:hover { color: var(--cp-blue); border-bottom-color: rgba(59, 108, 255, .4); }
|
||||
</style>
|
||||
.head-acts { display: flex; gap: 10px; }
|
||||
|
||||
<!-- 列 render 中由 naive-ui 动态渲染的节点不继承 scoped scopeId,须用全局样式 -->
|
||||
<style>
|
||||
.ops { display: flex; align-items: center; gap: 16px; }
|
||||
.ops .n-button { padding: 0 4px; }
|
||||
.cell-avatar-wrap { display: flex; align-items: center; gap: 8px; }
|
||||
.cell-avatar { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; background: #f2f3f7; flex: none; }
|
||||
.acct-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.acct-card {
|
||||
padding: 20px;
|
||||
display: flex; flex-direction: column; gap: 12px;
|
||||
}
|
||||
.acct-top { display: flex; align-items: center; gap: 14px; }
|
||||
|
||||
.avatar-wrap { position: relative; flex-shrink: 0; }
|
||||
.avatar {
|
||||
width: 52px; height: 52px; border-radius: 16px; object-fit: cover;
|
||||
display: block; box-shadow: 0 6px 14px -8px rgba(35, 42, 58, .4);
|
||||
}
|
||||
.avatar-fallback {
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff; font-size: 20px; font-weight: 800;
|
||||
}
|
||||
.avatar-edit {
|
||||
position: absolute; right: -6px; bottom: -6px;
|
||||
width: 22px; height: 22px; border-radius: 8px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--cp-panel); border: 1px solid var(--cp-line-strong);
|
||||
color: var(--cp-ink-2); cursor: pointer;
|
||||
transition: all .18s;
|
||||
}
|
||||
.avatar-edit:hover { color: var(--cp-blue); border-color: var(--cp-blue); background: rgba(47, 92, 240, .06); }
|
||||
|
||||
.acct-id { flex: 1; min-width: 0; }
|
||||
.id-row { display: flex; align-items: center; gap: 8px; }
|
||||
.acct-account { font-size: 16px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.acct-nick { font-size: 12.5px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
.acct-actions { display: flex; align-items: center; gap: 2px; flex-shrink: 0; }
|
||||
.acct-actions .el-button { font-size: 16px; }
|
||||
|
||||
.acct-tags { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; }
|
||||
.tag-label {
|
||||
font-size: 11px; font-weight: 700; color: var(--cp-ink-3);
|
||||
letter-spacing: .5px; margin-right: 2px; flex-shrink: 0;
|
||||
}
|
||||
.more { font-size: 12px; color: var(--cp-ink-3); font-weight: 700; }
|
||||
|
||||
.acct-foot {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
margin-top: auto; padding-top: 12px;
|
||||
border-top: 1px dashed var(--cp-line-strong);
|
||||
}
|
||||
.dim-sm { color: var(--cp-ink-3); font-size: 11px; }
|
||||
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
.reset-tip { margin-bottom: 16px; }
|
||||
</style>
|
||||
|
||||
@@ -5,34 +5,115 @@
|
||||
<h3>审计与运行报表 <span class="badge">Audit</span></h3>
|
||||
<p>操作审计 · 部署端运行上报记录(最新在前)</p>
|
||||
</div>
|
||||
<n-button :loading="busy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<n-tabs type="line" class="block cp-rise" :value="tab" @update:value="v => tab = v" justify-content="space-evenly">
|
||||
<n-tab-pane name="audit" tab="操作审计">
|
||||
<n-data-table :columns="auditCols" :data="audits" size="small" :loading="busy" :row-key="r => r.id" :single-line="false" />
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="report" tab="运行上报">
|
||||
<n-data-table :columns="reportCols" :data="reports" size="small" :loading="busy" :row-key="r => r.id" :single-line="false" />
|
||||
</n-tab-pane>
|
||||
</n-tabs>
|
||||
<!-- 顶部摘要 -->
|
||||
<div class="kpis cp-rise" v-if="loaded">
|
||||
<div class="kpi cp-card" v-for="(k, i) in kpis" :key="k.label" :style="{ animationDelay: i * 50 + 'ms' }">
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }"><el-icon :size="17"><component :is="k.icon" /></el-icon></div>
|
||||
<div class="kpi-meta">
|
||||
<div class="kpi-num mono" :style="{ color: k.color }">{{ k.value }}</div>
|
||||
<div class="kpi-lab">{{ k.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-tabs v-model="tab">
|
||||
<el-tab-pane label="操作审计" name="audit">
|
||||
<div class="toolbar">
|
||||
<el-select v-model="actionFilter" clearable placeholder="操作类型" style="width: 150px">
|
||||
<el-option v-for="(lb, key) in DETAIL_LABEL" :key="key" :label="lb" :value="key" />
|
||||
</el-select>
|
||||
<el-input v-model="search" placeholder="搜索账号 / 对象 / 详情" clearable :prefix-icon="Search" style="width: 240px" />
|
||||
</div>
|
||||
<el-table :data="filteredAudits" size="small" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" round effect="light" :type="actType(row.action)">{{ DETAIL_LABEL[row.action] || row.action }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann mono">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else class="mono">{{ row.account || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="对象" width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.target || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="详情" min-width="220" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.detail }">{{ row.detail || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane label="运行上报" name="report">
|
||||
<el-table :data="reports" size="small" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="110">
|
||||
<template #default="{ row }">
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ row.status || '—' }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann mono">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else class="mono">{{ row.account || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="设备" width="130" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ row.device_id || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="150" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.plugin_id || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="版本" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时长" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ typeof row.duration_sec === 'number' ? fmtDur(row.duration_sec) : '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="消息" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { h } from 'vue'
|
||||
import { NTag } from 'naive-ui'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, Search, Document, DataLine, CircleCloseFilled, WarningFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminAudit, adminReports } from '../api'
|
||||
import { message } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const tab = ref('audit')
|
||||
const busy = ref(false)
|
||||
const loaded = ref(false)
|
||||
const audits = ref([])
|
||||
const reports = ref([])
|
||||
const actionFilter = ref('')
|
||||
const search = ref('')
|
||||
|
||||
const DETAIL_LABEL = {
|
||||
grant: '授权', 'revoke-grant': '撤销授权', 'plugin-patch': '更新插件',
|
||||
@@ -40,44 +121,13 @@ const DETAIL_LABEL = {
|
||||
'account-update': '改号', 'account-reset': '重置密码', 'account-delete': '删除',
|
||||
'platform-grant': '平台授权', login: '登录',
|
||||
}
|
||||
function actTag(a) {
|
||||
const map = { grant: 'info', 'revoke-grant': 'error', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'info', }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[a] || 'default', round: true },
|
||||
{ default: () => DETAIL_LABEL[a] || a })
|
||||
function actType(a) {
|
||||
return { grant: 'primary', 'revoke-grant': 'danger', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary' }[a] || 'info'
|
||||
}
|
||||
function acctCell(r) {
|
||||
const nn = r.nickname
|
||||
if (!r.account && !nn) return h('span', { class: 'dim' }, '—')
|
||||
if (!nn) return h('span', null, r.account || '—')
|
||||
return h('div', { class: 'acct' }, [
|
||||
h('div', { class: 'ann' }, r.account || '—'),
|
||||
h('div', { class: 'anick' }, nn || ''),
|
||||
])
|
||||
function statusColor(s) {
|
||||
return { start: '#2f5cf0', running: '#2f5cf0', done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d' }[s] || '#9aa2b4'
|
||||
}
|
||||
function statusTag(s) {
|
||||
const map = { start: 'info', running: 'info', done: 'success', error: 'error' }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[s] || 'default', round: true },
|
||||
{ default: () => s || '—' })
|
||||
}
|
||||
|
||||
const auditCols = [
|
||||
{ title: '时间', key: 'at', width: 170 },
|
||||
{ title: '操作', key: 'action', width: 130, render: r => actTag(r.action) },
|
||||
{ title: '账号', key: 'account', width: 130, render: r => acctCell(r) },
|
||||
{ title: '对象', key: 'target', width: 140, ellipsis: { tooltip: true } },
|
||||
{ title: '详情', key: 'detail', minWidth: 220, ellipsis: { tooltip: true } },
|
||||
]
|
||||
const reportCols = [
|
||||
{ title: '时间', key: 'at', width: 170 },
|
||||
{ title: '状态', key: 'status', width: 100, render: r => statusTag(r.status) },
|
||||
{ title: '账号', key: 'account', width: 130, render: r => acctCell(r) },
|
||||
{ title: '设备', key: 'device_id', width: 110, render: r => r.device_id || h('span', { class: 'dim' }, '—') },
|
||||
{ title: '插件', key: 'plugin_id', width: 140, ellipsis: { tooltip: true } },
|
||||
{ title: '版本', key: 'version', width: 90 },
|
||||
{ title: '时长', key: 'duration_sec', width: 90, render: r => typeof r.duration_sec === 'number' ? fmtDur(r.duration_sec) : '—' },
|
||||
{ title: '消息', key: 'msg', minWidth: 200, ellipsis: { tooltip: true } },
|
||||
]
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
if (sec < 60) return sec + 's'
|
||||
@@ -86,12 +136,35 @@ function fmtDur(sec) {
|
||||
return `${Math.floor(m / 60)}h${m % 60}m`
|
||||
}
|
||||
|
||||
const kpis = computed(() => {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const tActs = audits.value.filter(a => (a.at || '').slice(0, 10) === today).length
|
||||
const tReports = reports.value.filter(r => (r.at || '').slice(0, 10) === today).length
|
||||
const fails = reports.value.filter(r => r.status === 'error' || r.status === 'failed').length
|
||||
return [
|
||||
{ label: '审计记录', value: audits.value.length, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '今日操作', value: tActs, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '运行上报', value: reports.value.length, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '今日上报', value: tReports, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
{ label: '上报失败', value: fails, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
]
|
||||
})
|
||||
|
||||
const filteredAudits = computed(() => {
|
||||
let list = audits.value
|
||||
if (actionFilter.value) list = list.filter(a => a.action === actionFilter.value)
|
||||
const kw = search.value.trim().toLowerCase()
|
||||
if (kw) list = list.filter(a => [a.account, a.nickname, a.target, a.detail].join(' ').toLowerCase().includes(kw))
|
||||
return list
|
||||
})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const [a, r] = await Promise.all([adminAudit(), adminReports()])
|
||||
audits.value = a.auditlogs || []
|
||||
reports.value = r.reports || []
|
||||
loaded.value = true
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
@@ -99,10 +172,15 @@ onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.kpis { display: grid; grid-template-columns: repeat(5, 1fr); gap: 16px; margin-bottom: 18px; }
|
||||
@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(3, 1fr); } }
|
||||
.kpi { display: flex; align-items: center; gap: 13px; padding: 16px; }
|
||||
.kpi-ic { width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0; display: grid; place-items: center; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7); }
|
||||
.kpi-meta { min-width: 0; }
|
||||
.kpi-num { font-size: 22px; font-weight: 800; line-height: 1.1; }
|
||||
.kpi-lab { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
|
||||
.panel { padding: 8px 18px 18px; }
|
||||
.toolbar { display: flex; gap: 10px; margin: 4px 0 14px; }
|
||||
.dim-sm { color: var(--cp-ink-2); }
|
||||
</style>
|
||||
<style>
|
||||
.acct { line-height: 1.25; }
|
||||
.acct .ann { font-size: 13px; color: var(--cp-ink-1); }
|
||||
.acct .anick { font-size: 11px; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
@@ -5,88 +5,87 @@
|
||||
<h3>权限授权 <span class="badge">Grants</span></h3>
|
||||
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<n-form inline>
|
||||
<n-form-item label="选择账号">
|
||||
<n-select
|
||||
v-model:value="account"
|
||||
:options="accountOptions"
|
||||
placeholder="选择账号…"
|
||||
style="width: 240px"
|
||||
filterable
|
||||
clearable
|
||||
/>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="account">
|
||||
<span class="sel-hint">{{ account }} · 已授权 {{ grantedIds.length }} 个插件 / {{ platChecked.length }} 个平台</span>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</n-card>
|
||||
<div class="cp-card panel cp-rise">
|
||||
<!-- 账号选择 -->
|
||||
<div class="pick-row">
|
||||
<div class="pick-label">选择账号</div>
|
||||
<el-select v-model="account" filterable clearable placeholder="选择账号…" style="width: 260px" :prefix-icon="User">
|
||||
<el-option v-for="a in accountOptions" :key="a.value" :label="a.label" :value="a.value" />
|
||||
</el-select>
|
||||
<div class="pick-hint" v-if="account">
|
||||
已授权 <b class="mono">{{ grantedIds.length }}</b> 个插件 / <b class="mono">{{ platChecked.length }}</b> 个平台
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="account">
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<b>插件授权</b>
|
||||
<n-button type="primary" size="small" :loading="saving" @click="saveGrant">保存插件授权</n-button>
|
||||
<template v-if="account">
|
||||
<!-- 插件授权 -->
|
||||
<div class="section">
|
||||
<div class="section-head">
|
||||
<div class="card-title">插件授权</div>
|
||||
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||
</div>
|
||||
</template>
|
||||
<n-checkbox-group v-model:value="grantedIds" v-if="plugins.length">
|
||||
<div class="ck-grid">
|
||||
<n-checkbox v-for="p in plugins" :key="p.id" :value="p.id" class="ck">
|
||||
<span class="ck-main">
|
||||
<span>{{ p.id }}<span class="dim">({{ p.name }})</span></span>
|
||||
<span class="ck-sub" v-if="grantState[p.id]?.granted">
|
||||
<n-switch size="small" :value="grantState[p.id].canRun"
|
||||
@update:value="v => setGrant(p.id, { canRun: v })">
|
||||
<template #checked>可运行</template>
|
||||
<template #unchecked>禁运行</template>
|
||||
</n-switch>
|
||||
<n-switch size="small" :value="grantState[p.id].canDownload"
|
||||
@update:value="v => setGrant(p.id, { canDownload: v })">
|
||||
<template #checked>可下载</template>
|
||||
<template #unchecked>禁下载</template>
|
||||
</n-switch>
|
||||
</span>
|
||||
</span>
|
||||
</n-checkbox>
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
<n-empty v-else description="暂无插件,请先在「插件管理」上传" size="small" />
|
||||
</n-card>
|
||||
<el-checkbox-group v-model="grantedIds" class="plist">
|
||||
<div class="prow" v-for="p in plugins" :key="p.id" :class="{ on: grantedIds.includes(p.id) }">
|
||||
<el-checkbox :value="p.id" class="pck">
|
||||
<span class="pname mono">{{ p.id }}</span>
|
||||
<span class="psub dim">{{ p.name }}</span>
|
||||
</el-checkbox>
|
||||
<div class="pswitches">
|
||||
<div class="psw">
|
||||
<span class="psw-label" :class="{ on: canRun(p.id) }">可运行</span>
|
||||
<el-switch size="small" :model-value="canRun(p.id)" :disabled="!grantedIds.includes(p.id)" @change="v => setGrant(p.id, { canRun: v })" />
|
||||
</div>
|
||||
<div class="psw">
|
||||
<span class="psw-label" :class="{ on: canDownload(p.id) }">可下载</span>
|
||||
<el-switch size="small" :model-value="canDownload(p.id)" :disabled="!grantedIds.includes(p.id)" @change="v => setGrant(p.id, { canDownload: v })" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-checkbox-group>
|
||||
<el-empty v-if="!plugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<b>平台授权</b>
|
||||
<n-button type="primary" size="small" :loading="savingPlat" @click="savePlat">保存平台授权</n-button>
|
||||
<!-- 平台授权 -->
|
||||
<div class="section">
|
||||
<div class="section-head">
|
||||
<div class="card-title">平台授权</div>
|
||||
</div>
|
||||
</template>
|
||||
<n-checkbox-group v-model:value="platChecked">
|
||||
<div class="ck-grid">
|
||||
<n-checkbox v-for="pf in PLATFORM_OPTS" :key="pf.id" :value="pf.id" class="ck">
|
||||
{{ pf.label }}<span class="dim">({{ pf.id }})</span>
|
||||
</n-checkbox>
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
</n-card>
|
||||
</template>
|
||||
<el-checkbox-group v-model="platChecked" class="pf-list">
|
||||
<el-checkbox v-for="pf in PLATFORM_OPTS" :key="pf.id" :value="pf.id" class="pf-chip">
|
||||
<span>{{ pf.label }}</span>
|
||||
<span class="dim mono">({{ pf.id }})</span>
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<n-empty v-else description="先在上方选择一个账号" class="no-acc cp-rise" />
|
||||
<el-empty v-else description="先在上方选择一个账号" :image-size="80" class="no-acc" />
|
||||
</div>
|
||||
|
||||
<!-- 底部保存栏 -->
|
||||
<transition name="savebar">
|
||||
<div class="savebar cp-card cp-rise" v-if="account">
|
||||
<div class="save-hint">
|
||||
<span class="dot" :class="{ dirty: dirtyCount > 0 }"></span>
|
||||
{{ dirtyCount > 0 ? `有 ${dirtyCount} 项授权变更待保存` : '授权已是最新' }}
|
||||
</div>
|
||||
<el-button type="primary" :loading="saving" :disabled="dirtyCount === 0" :icon="Check" @click="saveAll">
|
||||
保存授权
|
||||
</el-button>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { Refresh, User, Check } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const PLATFORM_OPTS = ref([])
|
||||
|
||||
@@ -102,7 +101,6 @@ const grantedIds = ref([])
|
||||
const grantState = ref({}) // plugin_id -> { granted, canRun, canDownload }
|
||||
const platChecked = ref([])
|
||||
const saving = ref(false)
|
||||
const savingPlat = ref(false)
|
||||
let heldGrantState = {} // 已保存快照,用于差异比对
|
||||
let heldPlatforms = new Set()
|
||||
|
||||
@@ -110,6 +108,15 @@ function setGrant(pid, patch) {
|
||||
grantState.value[pid] = { ...grantState.value[pid], ...patch }
|
||||
grantState.value = { ...grantState.value }
|
||||
}
|
||||
function canRun(pid) { return grantState.value[pid]?.canRun !== false }
|
||||
function canDownload(pid) { return grantState.value[pid]?.canDownload !== false }
|
||||
|
||||
// 全选 / 半选
|
||||
const allChecked = computed(() => plugins.value.length > 0 && grantedIds.value.length === plugins.value.length)
|
||||
const someChecked = computed(() => grantedIds.value.length > 0 && !allChecked.value)
|
||||
function toggleAll(v) {
|
||||
grantedIds.value = v ? plugins.value.map(p => p.id) : []
|
||||
}
|
||||
|
||||
// 选中账号即自动载入其现有授权
|
||||
watch(account, (acc) => {
|
||||
@@ -139,10 +146,27 @@ watch(grantedIds, (ids) => {
|
||||
grantState.value = state
|
||||
})
|
||||
|
||||
// 差异计算
|
||||
const pluginDirty = computed(() => {
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => { if (s.granted) want[pid] = s })
|
||||
const allPids = [...new Set([...Object.keys(want), ...Object.keys(heldGrantState)])]
|
||||
return allPids.filter(pid => {
|
||||
const w = want[pid]; const h = heldGrantState[pid]
|
||||
if (!!w !== !!h) return true
|
||||
if (w && h) return w.canRun !== h.canRun || w.canDownload !== h.canDownload
|
||||
return false
|
||||
})
|
||||
})
|
||||
const platDirty = computed(() => {
|
||||
const want = new Set(platChecked.value)
|
||||
return [...new Set([...want, ...heldPlatforms])].filter(pf => want.has(pf) !== heldPlatforms.has(pf))
|
||||
})
|
||||
const dirtyCount = computed(() => pluginDirty.value.length + platDirty.value.length)
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
// 拉取可授权平台列表(后端只读接口,替代写死 hr/oa)
|
||||
async function loadPlatforms() {
|
||||
try {
|
||||
const r = await adminPlatforms()
|
||||
@@ -150,78 +174,121 @@ async function loadPlatforms() {
|
||||
} catch (e) { message.error('平台列表读取失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
async function saveGrant() {
|
||||
async function savePluginDiff() {
|
||||
const acc = account.value
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => { if (s.granted) want[pid] = s })
|
||||
const diff = pluginDirty.value
|
||||
const results = await Promise.allSettled(diff.map(pid => adminGrant({
|
||||
account: acc, plugin_id: pid, granted: !!want[pid],
|
||||
can_run: want[pid]?.canRun !== false, can_download: want[pid]?.canDownload !== false,
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`插件授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return 0 }
|
||||
heldGrantState = JSON.parse(JSON.stringify(grantState.value))
|
||||
return diff.length
|
||||
}
|
||||
async function savePlatDiff() {
|
||||
const acc = account.value
|
||||
const want = new Set(platChecked.value)
|
||||
const diff = platDirty.value
|
||||
const results = await Promise.allSettled(diff.map(pf => adminPlatformGrant({
|
||||
account: acc, platform_id: pf, granted: want.has(pf),
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`平台授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return 0 }
|
||||
heldPlatforms = new Set(platChecked.value)
|
||||
return diff.length
|
||||
}
|
||||
|
||||
async function saveAll() {
|
||||
const acc = account.value; if (!acc) return
|
||||
saving.value = true
|
||||
try {
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => {
|
||||
if (s.granted) want[pid] = s
|
||||
})
|
||||
const allPids = [...new Set([...Object.keys(want), ...Object.keys(heldGrantState)])]
|
||||
const diff = allPids.filter(pid => {
|
||||
const w = want[pid]; const h = heldGrantState[pid]
|
||||
if (!!w !== !!h) return true
|
||||
if (w && h) return w.canRun !== h.canRun || w.canDownload !== h.canDownload
|
||||
return false
|
||||
})
|
||||
if (!diff.length) { message.info('插件授权无需变更'); return }
|
||||
const results = await Promise.allSettled(diff.map(pid => adminGrant({
|
||||
account: acc, plugin_id: pid, granted: !!want[pid],
|
||||
can_run: want[pid]?.canRun !== false, can_download: want[pid]?.canDownload !== false,
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`插件授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return }
|
||||
message.success(`已更新 ${diff.length} 项插件授权`)
|
||||
heldGrantState = JSON.parse(JSON.stringify(grantState.value))
|
||||
let okP = 0, okPl = 0
|
||||
if (pluginDirty.value.length) okP = await savePluginDiff()
|
||||
if (platDirty.value.length) okPl = await savePlatDiff()
|
||||
if (!pluginDirty.value.length && !platDirty.value.length) { message.info('授权无需变更'); return }
|
||||
message.success(`已保存:插件 ${okP} 项,平台 ${okPl} 项`)
|
||||
await refresh()
|
||||
} finally { saving.value = false }
|
||||
}
|
||||
async function savePlat() {
|
||||
const acc = account.value; if (!acc) return
|
||||
savingPlat.value = true
|
||||
try {
|
||||
const want = new Set(platChecked.value)
|
||||
const diff = [...new Set([...want, ...heldPlatforms])].filter(pf => want.has(pf) !== heldPlatforms.has(pf))
|
||||
if (!diff.length) { message.info('平台授权无需变更'); return }
|
||||
const results = await Promise.allSettled(diff.map(pf => adminPlatformGrant({
|
||||
account: acc, platform_id: pf, granted: want.has(pf),
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`平台授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return }
|
||||
message.success(`已更新 ${diff.length} 项平台授权`)
|
||||
heldPlatforms = new Set(platChecked.value)
|
||||
await refresh()
|
||||
} finally { savingPlat.value = false }
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
onMounted(() => { refresh(); loadPlatforms() })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.sel-hint { font-size: 12px; color: var(--cp-ink-2); }
|
||||
.no-acc { margin-top: 60px; }
|
||||
.panel { padding: 22px 24px 26px; }
|
||||
|
||||
/* 授权项:卡片式勾选 */
|
||||
.ck-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 10px; }
|
||||
.ck-main { display: flex; flex-direction: column; gap: 8px; min-width: 0; line-height: 1.2; }
|
||||
.ck-sub { display: flex; align-items: center; gap: 10px; }
|
||||
:deep(.n-checkbox) {
|
||||
display: flex; align-items: center; margin: 0;
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--cp-border);
|
||||
.pick-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; padding-bottom: 20px; border-bottom: 1px dashed var(--cp-line-strong); }
|
||||
.pick-label { font-size: 13px; font-weight: 700; color: var(--cp-ink-1); }
|
||||
.pick-hint { font-size: 12.5px; color: var(--cp-ink-3); }
|
||||
.pick-hint b { color: var(--cp-blue); font-size: 13px; }
|
||||
|
||||
.section { margin-top: 24px; }
|
||||
.section-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||
.section-head .card-title { margin-bottom: 0; }
|
||||
|
||||
/* 插件授权行 */
|
||||
.plist { display: flex; flex-direction: column; gap: 8px; }
|
||||
.prow {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, .65);
|
||||
background: var(--cp-panel);
|
||||
transition: border-color .18s, background .18s, box-shadow .18s;
|
||||
}
|
||||
:deep(.n-checkbox:hover) { border-color: rgba(59, 108, 255, .4); }
|
||||
:deep(.n-checkbox.n-checkbox--checked) {
|
||||
border-color: rgba(59, 108, 255, .45);
|
||||
background: linear-gradient(135deg, rgba(59, 108, 255, .08), rgba(34, 199, 232, .06));
|
||||
box-shadow: 0 8px 18px -10px rgba(59, 108, 255, .35);
|
||||
.prow:hover { border-color: rgba(47, 92, 240, .35); }
|
||||
.prow.on {
|
||||
border-color: rgba(47, 92, 240, .4);
|
||||
background: linear-gradient(90deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .03));
|
||||
box-shadow: 0 8px 18px -12px rgba(47, 92, 240, .4);
|
||||
}
|
||||
:deep(.n-checkbox .n-checkbox__label) { padding-left: 4px; flex: 1; min-width: 0; }
|
||||
.prow .pck { flex: 1; min-width: 0; }
|
||||
.pname { font-weight: 700; color: var(--cp-ink-1); font-size: 13px; }
|
||||
.psub { font-size: 12px; margin-left: 8px; }
|
||||
|
||||
.pswitches { display: flex; gap: 22px; flex-shrink: 0; }
|
||||
.psw { display: flex; align-items: center; gap: 8px; }
|
||||
.psw-label { font-size: 12px; color: var(--cp-ink-3); transition: color .18s; }
|
||||
.psw-label.on { color: var(--cp-blue); font-weight: 600; }
|
||||
|
||||
/* 平台授权 chips */
|
||||
.pf-list { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.pf-chip { margin: 0 !important; }
|
||||
.pf-chip :deep(.el-checkbox__input) { display: none; }
|
||||
.pf-chip :deep(.el-checkbox__label) {
|
||||
display: inline-flex; align-items: center; gap: 6px;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid var(--cp-line);
|
||||
border-radius: 12px;
|
||||
background: var(--cp-panel);
|
||||
font-weight: 600;
|
||||
transition: border-color .18s, background .18s, box-shadow .18s, color .18s;
|
||||
}
|
||||
.pf-chip:hover :deep(.el-checkbox__label) { border-color: rgba(47, 92, 240, .4); }
|
||||
.pf-chip.is-checked :deep(.el-checkbox__label) {
|
||||
border-color: rgba(47, 92, 240, .55);
|
||||
background: linear-gradient(135deg, rgba(47, 92, 240, .10), rgba(15, 159, 155, .06));
|
||||
color: var(--cp-blue);
|
||||
box-shadow: 0 6px 14px -10px rgba(47, 92, 240, .5);
|
||||
}
|
||||
.no-acc { padding: 30px 0; }
|
||||
|
||||
/* 底部保存栏 */
|
||||
.savebar {
|
||||
position: sticky; bottom: 18px; z-index: 10;
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
margin-top: 20px; padding: 14px 20px;
|
||||
background: rgba(255, 253, 248, .92);
|
||||
backdrop-filter: blur(12px);
|
||||
}
|
||||
.save-hint { display: flex; align-items: center; gap: 9px; font-size: 13px; color: var(--cp-ink-2); font-weight: 600; }
|
||||
.save-hint .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--cp-success); }
|
||||
.save-hint .dot.dirty { background: var(--cp-amber); box-shadow: 0 0 0 4px rgba(217, 119, 6, .18); }
|
||||
.savebar-enter-active, .savebar-leave-active { transition: opacity .25s ease, transform .25s ease; }
|
||||
.savebar-enter-from, .savebar-leave-to { opacity: 0; transform: translateY(10px); }
|
||||
</style>
|
||||
|
||||
@@ -5,27 +5,25 @@
|
||||
<h3>概览 <span class="badge">Dashboard</span></h3>
|
||||
<p>中心机 · 插件分发与账号权限 · 当前账号 <b class="who">{{ store.nickname || store.current }}</b></p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="stat-grid" v-if="ov">
|
||||
<div class="stat-card" v-for="(s, i) in stats" :key="s.label" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :class="{ wide: s.wide }" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<n-icon :size="20"><component :is="s.icon" /></n-icon>
|
||||
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-num mono" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
</div>
|
||||
<n-skeleton v-else-if="overviewBusy" text :repeat="3" style="margin-top: 20px" />
|
||||
<el-skeleton v-else-if="overviewBusy" animated :rows="3" style="margin-top: 20px" />
|
||||
|
||||
<div class="tip-card cp-rise">
|
||||
<div class="tip-ic"><n-icon :size="18"><InfoFilled /></n-icon></div>
|
||||
<div class="tip-card cp-card cp-rise">
|
||||
<div class="tip-ic"><el-icon :size="18"><InfoFilled /></el-icon></div>
|
||||
<div class="tip-body">
|
||||
<b>使用说明</b>
|
||||
<p>「插件管理」上传与发布插件包(每插件保留最近 3 个版本);「账号管理」建号与账号维护;「权限授权」按账号勾选可用的插件与平台。部署机(webhost)仅在启动与手动刷新时拉取插件,授权变更后需在部署机刷新生效。</p>
|
||||
@@ -36,26 +34,26 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Refresh, InfoFilled } from '@element-plus/icons-vue'
|
||||
import { Refresh, InfoFilled, Box, Collection, User, UserFilled, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { message } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const ov = computed(() => overview.value)
|
||||
const stats = computed(() => {
|
||||
const plugins = ov.value?.plugins || []
|
||||
return [
|
||||
{ label: '插件', value: plugins.length, icon: 'Box', color: '#3b6cff', bg: 'linear-gradient(135deg,#eef2ff,#dbe6ff)' },
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: 'Collection', color: '#7c5cff', bg: 'linear-gradient(135deg,#f2edff,#e6dcff)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: 'User', color: '#12a4d8', bg: 'linear-gradient(135deg,#e7f6fb,#d3effa)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: 'UserFilled', color: '#22b07a', bg: 'linear-gradient(135deg,#e6f7f0,#d2f1e4)' },
|
||||
{ label: '最近上传', value: latest(), icon: 'UploadFilled', color: '#d99a1b', bg: 'linear-gradient(135deg,#fbf3e2,#f6e8c8)', small: true },
|
||||
{ label: '插件', value: plugins.length, icon: Box, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: Collection, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: User, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: UserFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '最近上传', value: latest(), icon: UploadFilled, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)', small: true, wide: true },
|
||||
]
|
||||
})
|
||||
function latest() {
|
||||
const all = (ov.value?.plugins || []).flatMap(p => p.versions || []).map(v => v.uploaded_at).filter(Boolean)
|
||||
if (!all.length) return '—'
|
||||
// ISO 时间转友好格式:2026-09-10T12:51:33 → 2026-09-10 12:51
|
||||
return all.sort().at(-1).replace('T', ' ').slice(0, 16)
|
||||
return fmtTime(all.sort().at(-1))
|
||||
}
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
@@ -66,47 +64,39 @@ onMounted(refresh)
|
||||
<style scoped>
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fill, minmax(236px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.stat-card {
|
||||
position: relative; overflow: hidden;
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
background: var(--cp-surface);
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 18px;
|
||||
padding: 18px;
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
transition: transform .22s ease, box-shadow .22s ease;
|
||||
animation: cp-rise .5s cubic-bezier(.22, .61, .36, 1) both;
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stat-card:hover { transform: translateY(-4px); box-shadow: var(--cp-card-shadow-hover); }
|
||||
.stat-card.wide { grid-column: span 2; }
|
||||
.stat-ic {
|
||||
width: 46px; height: 46px; border-radius: 14px; flex-shrink: 0;
|
||||
width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .6);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.stat-meta { min-width: 0; }
|
||||
.stat-num { font-size: 26px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink); font-variant-numeric: tabular-nums; }
|
||||
.stat-num.sm { font-size: 13px; font-weight: 600; word-break: break-all; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 3px; }
|
||||
.stat-num { font-size: 27px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink-1); }
|
||||
.stat-num.sm { font-size: 18px; font-weight: 700; white-space: nowrap; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
.stat-glow { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; border-radius: 0 6px 6px 0; opacity: .9; }
|
||||
|
||||
.tip-card {
|
||||
margin-top: 18px;
|
||||
margin-top: 20px;
|
||||
display: flex; gap: 14px;
|
||||
background: linear-gradient(135deg, rgba(59, 108, 255, .06), rgba(34, 199, 232, .05)), rgba(255, 255, 255, .7);
|
||||
border: 1px solid rgba(59, 108, 255, .16);
|
||||
border-radius: 16px;
|
||||
padding: 18px 20px;
|
||||
padding: 20px 22px;
|
||||
background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel);
|
||||
}
|
||||
.tip-ic {
|
||||
width: 38px; height: 38px; border-radius: 12px; flex-shrink: 0;
|
||||
width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff, #22c7e8);
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff;
|
||||
box-shadow: 0 6px 14px -6px rgba(59, 108, 255, .55);
|
||||
box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6);
|
||||
}
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink); margin-bottom: 4px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.7; color: var(--cp-ink-2); }
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink-1); margin-bottom: 5px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.8; color: var(--cp-ink-2); }
|
||||
</style>
|
||||
|
||||
@@ -5,125 +5,199 @@
|
||||
<h3>插件管理 <span class="badge">Plugins</span></h3>
|
||||
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header><span class="card-title">上传插件包</span></template>
|
||||
<n-form inline>
|
||||
<n-form-item label="插件 ID">
|
||||
<n-input v-model:value="pid" placeholder="如 seal_check" style="width: 150px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="名称">
|
||||
<n-input v-model:value="pname" placeholder="插件显示名" style="width: 150px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="版本">
|
||||
<n-input v-model:value="pver" placeholder="如 1.1.0" style="width: 110px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="包文件">
|
||||
<n-space align="center" :size="8">
|
||||
<n-upload :default-upload="false" :show-file-list="false" accept=".zip" @change="onFileChange">
|
||||
<n-button :type="pfile ? 'info' : 'default'">
|
||||
<template #icon><n-icon><UploadFilled /></n-icon></template>
|
||||
<div class="cp-card block cp-rise up-card">
|
||||
<div class="card-title">上传插件包</div>
|
||||
<el-form inline class="up-form" @submit.prevent>
|
||||
<el-form-item label="插件 ID">
|
||||
<el-input v-model="pid" placeholder="如 seal_check" style="width: 160px" class="mono" />
|
||||
</el-form-item>
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="pname" placeholder="插件显示名" style="width: 160px" />
|
||||
</el-form-item>
|
||||
<el-form-item label="版本">
|
||||
<el-input v-model="pver" placeholder="如 1.1.0" style="width: 120px" class="mono" />
|
||||
</el-form-item>
|
||||
<el-form-item label="包文件">
|
||||
<div class="file-row">
|
||||
<el-upload :auto-upload="false" :show-file-list="false" accept=".zip" :on-change="onFileChange" ref="upRef">
|
||||
<el-button :type="pfile ? 'primary' : 'default'" plain :icon="FolderOpened">
|
||||
{{ pfile ? '重新选择' : '选择 ZIP 包' }}
|
||||
</n-button>
|
||||
</n-upload>
|
||||
<n-tag v-if="pfile" size="small" round type="info" :bordered="false">{{ pfile.name }}</n-tag>
|
||||
</n-space>
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
<n-button type="primary" :loading="uploading" @click="upload">
|
||||
<template #icon v-if="!uploading"><n-icon><UploadFilled /></n-icon></template>上传发布
|
||||
</n-button>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</el-button>
|
||||
</el-upload>
|
||||
<el-tag v-if="pfile" size="small" round effect="plain" type="primary" class="mono">{{ pfile.name }}</el-tag>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="uploading" :icon="UploadFilled" @click="upload">上传发布</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="hint">包根目录需含 plugin.json / main.py / requirements.txt,ZIP 完整性校验通过才会发布。</div>
|
||||
</n-card>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header><span class="card-title">插件列表</span></template>
|
||||
<n-data-table
|
||||
:columns="columns"
|
||||
:data="plugins"
|
||||
:loading="overviewBusy"
|
||||
:row-key="r => r.id"
|
||||
:single-line="false"
|
||||
:row-props="rowProps"
|
||||
/>
|
||||
</n-card>
|
||||
<div class="cp-card block cp-rise list-card">
|
||||
<div class="card-title">插件列表</div>
|
||||
<el-table :data="plugins" size="small" :loading="overviewBusy" :row-key="r => r.id">
|
||||
<el-table-column label="插件 ID" min-width="160">
|
||||
<template #default="{ row }"><b class="cell-strong mono">{{ row.id }}</b></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="名称" min-width="180" show-overflow-tooltip prop="name" />
|
||||
<el-table-column label="分类" min-width="110">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="row.category" size="small" effect="plain" type="info" round>{{ row.category }}</el-tag>
|
||||
<span v-else class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[row.status]?.type || 'info'">
|
||||
{{ statusMeta[row.status]?.label || row.status || '—' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最新版" min-width="110">
|
||||
<template #default="{ row }"><span class="mono">{{ row.latest_version || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="210" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-ops">
|
||||
<el-button link type="info" :icon="View" @click="openDetail(row)">详情</el-button>
|
||||
<el-button link type="primary" :icon="Edit" @click="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" :icon="Delete" @click="delPlugin(row)">删除</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<n-modal v-model:show="editShow" preset="card" :bordered="false" style="width: 560px" :title="`编辑插件 · ${edit.pid}`">
|
||||
<n-form label-placement="top">
|
||||
<n-form-item label="名称">
|
||||
<n-input v-model:value="edit.name" placeholder="插件显示名" />
|
||||
</n-form-item>
|
||||
<n-form-item label="分类">
|
||||
<n-input v-model:value="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</n-form-item>
|
||||
<n-form-item label="描述">
|
||||
<n-input v-model:value="edit.description" type="textarea" :rows="2" placeholder="插件用途说明" />
|
||||
</n-form-item>
|
||||
<n-form-item label="状态">
|
||||
<n-radio-group v-model:value="edit.status">
|
||||
<n-radio-button value="published">正常发布</n-radio-button>
|
||||
<n-radio-button value="disabled">禁用(停止分发)</n-radio-button>
|
||||
<n-radio-button value="revoked">下架(禁止运行)</n-radio-button>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
<n-form-item label="强制更新(留空表示不强制)" :show-feedback="false">
|
||||
<!-- 编辑插件 -->
|
||||
<el-dialog v-model="editShow" :title="`编辑插件 · ${edit.pid}`" width="560px" align-center destroy-on-close>
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="edit.name" placeholder="插件显示名" />
|
||||
</el-form-item>
|
||||
<el-form-item label="分类">
|
||||
<el-input v-model="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</el-form-item>
|
||||
<el-form-item label="描述">
|
||||
<el-input v-model="edit.description" type="textarea" :rows="2" placeholder="插件用途说明" />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-radio-group v-model="edit.status">
|
||||
<el-radio-button value="published">正常发布</el-radio-button>
|
||||
<el-radio-button value="disabled">禁用(停止分发)</el-radio-button>
|
||||
<el-radio-button value="revoked">下架(禁止运行)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="强制更新(留空表示不强制)">
|
||||
<div class="force-row">
|
||||
<n-input v-model:value="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 180px" />
|
||||
<n-input v-model:value="edit.force_dl" type="datetime-local" placeholder="截止时间" style="width: 200px" />
|
||||
<div class="force-line">
|
||||
<el-input v-model="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 180px" class="mono" />
|
||||
<el-input v-model="edit.force_dl" type="datetime-local" placeholder="截止时间" style="width: 200px" class="mono" />
|
||||
</div>
|
||||
<span class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<n-button @click="editShow = false">取消</n-button>
|
||||
<n-button type="primary" :loading="saving" @click="saveEdit">保存</n-button>
|
||||
<el-button @click="editShow = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 插件详情 -->
|
||||
<el-dialog v-model="detailShow" :title="`插件详情 · ${detail?.id || ''}`" width="640px" align-center destroy-on-close>
|
||||
<div v-if="detail" class="plg-detail">
|
||||
<div class="d-head">
|
||||
<span class="d-id mono">{{ detail.id }}</span>
|
||||
<span class="d-name">{{ detail.name }}</span>
|
||||
<el-tag size="small" round effect="light" :type="statusMeta[detail.status]?.type || 'info'">
|
||||
{{ statusMeta[detail.status]?.label || detail.status || '—' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="d-grid">
|
||||
<div class="d-item"><label>分类</label><span>{{ detail.category || '—' }}</span></div>
|
||||
<div class="d-item"><label>最新版本</label><span class="mono">{{ detail.latest_version || '—' }}</span></div>
|
||||
<div class="d-item"><label>表单字段</label><span class="mono">{{ detail.field_count || 0 }}</span></div>
|
||||
<div class="d-item"><label>强制更新</label><span>{{ forceText(detail) }}</span></div>
|
||||
</div>
|
||||
|
||||
<div class="d-sec"><label>描述</label><p class="d-desc">{{ detail.description || '—' }}</p></div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>能力</label>
|
||||
<div class="tags" v-if="detail.capabilities?.length">
|
||||
<el-tag v-for="c in detail.capabilities" :key="c" size="small" effect="plain" round>{{ c }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">—</span>
|
||||
</div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>版本历史</label>
|
||||
<div class="vlist" v-if="detail.versions?.length">
|
||||
<div class="vrow" v-for="v in detail.versions" :key="v.version">
|
||||
<el-tag size="small" round effect="light" class="mono"
|
||||
:type="v.version === detail.latest_version ? 'primary' : 'info'">{{ v.version }}</el-tag>
|
||||
<span class="vtime mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span v-else class="dim">暂无版本</span>
|
||||
</div>
|
||||
|
||||
<div class="d-sec">
|
||||
<label>授权账号</label>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">未授权</span>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="detailShow = false">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { NButton, NTag } from 'naive-ui'
|
||||
import { Refresh, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { message, dialog } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
const uploading = ref(false)
|
||||
const upRef = ref()
|
||||
|
||||
// 状态徽标文案与配色
|
||||
const STATUS_META = {
|
||||
const statusMeta = {
|
||||
published: { label: '正常', type: 'success' },
|
||||
disabled: { label: '禁用', type: 'warning' },
|
||||
revoked: { label: '已下架', type: 'error' },
|
||||
}
|
||||
function renderStatus(row) {
|
||||
const s = STATUS_META[row.status] || { label: row.status || '—', type: 'default' }
|
||||
return h(NTag, { size: 'small', round: true, bordered: false, type: s.type }, { default: () => s.label })
|
||||
revoked: { label: '已下架', type: 'danger' },
|
||||
}
|
||||
|
||||
function onFileChange(e) {
|
||||
pfile.value = e?.file?.file || null
|
||||
function onFileChange(uploadFile) {
|
||||
pfile.value = uploadFile.raw || null
|
||||
}
|
||||
|
||||
function renderVersions(row) {
|
||||
const list = row.versions || []
|
||||
if (!list.length) return h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'tags' }, list.map(v => h(NTag, {
|
||||
size: 'small', round: true, bordered: false,
|
||||
type: v.version === row.latest_version ? 'primary' : 'default',
|
||||
}, { default: () => v.version })))
|
||||
// —— 详情弹窗 ——
|
||||
const detailShow = ref(false)
|
||||
const detail = ref(null)
|
||||
function openDetail(row) {
|
||||
detail.value = row
|
||||
detailShow.value = true
|
||||
}
|
||||
function forceText(p) {
|
||||
if (p.force_min_version && p.force_deadline) return `${p.force_min_version} 起 · 截止 ${fmtTime(p.force_deadline)}`
|
||||
return '无'
|
||||
}
|
||||
|
||||
// —— 编辑弹窗状态 ——
|
||||
@@ -163,37 +237,6 @@ async function saveEdit() {
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
const columns = computed(() => [
|
||||
{ title: '插件 ID', key: 'id', width: 150, render: r => h('b', { class: 'cell-strong' }, r.id) },
|
||||
{ title: '名称', key: 'name', width: 130, ellipsis: { tooltip: true } },
|
||||
{ title: '分类', key: 'category', width: 90, render: r => r.category ? h(NTag, { size: 'small', bordered: false, type: 'info' }, { default: () => r.category }) : h('span', { class: 'dim' }, '—') },
|
||||
{
|
||||
title: '能力 / 表单', key: 'caps', minWidth: 130,
|
||||
render: r => h('div', { class: 'tags' }, [
|
||||
...(r.capabilities?.length ? r.capabilities.map(c => h(NTag, { size: 'small', bordered: false, type: 'default' }, { default: () => c })) : [h('span', { class: 'dim' }, '—')]),
|
||||
h(NTag, { size: 'small', bordered: false, type: 'info', style: 'margin-left:2px' }, { default: () => `${r.field_count || 0} 字段` }),
|
||||
]),
|
||||
},
|
||||
{ title: '状态', key: 'status', width: 80, render: renderStatus },
|
||||
{ title: '最新版', key: 'latest_version', width: 90 },
|
||||
{ title: '版本历史', key: 'versions', minWidth: 200, render: renderVersions },
|
||||
{
|
||||
title: '授权账号', key: 'accounts', minWidth: 130,
|
||||
render: r => (r.accounts?.length ? r.accounts.join('、') : h('span', { class: 'dim' }, '—')),
|
||||
ellipsis: { tooltip: true },
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'actions', width: 120,
|
||||
render: r => h('div', { class: 'row-acts' }, [
|
||||
h(NButton, { size: 'small', text: true, type: 'primary', onClick: () => openEdit(r) }, { default: () => '编辑' }),
|
||||
h(NButton, { size: 'small', text: true, type: 'error', onClick: () => delPlugin(r) }, { default: () => '删除' }),
|
||||
]),
|
||||
},
|
||||
])
|
||||
function rowProps() {
|
||||
return { style: 'cursor:default' }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
@@ -204,38 +247,51 @@ async function upload() {
|
||||
await adminUpload(pid.value, pname.value || pid.value, pver.value, pfile.value)
|
||||
message.success(`已发布 ${pid.value}@${pver.value}`)
|
||||
pid.value = ''; pname.value = ''; pver.value = ''; pfile.value = null
|
||||
upRef.value?.clearFiles()
|
||||
await refresh()
|
||||
} catch (e) { message.error('上传失败:' + (e.message || e)) }
|
||||
finally { uploading.value = false }
|
||||
}
|
||||
function delPlugin(p) {
|
||||
dialog.warning({
|
||||
title: '删除插件',
|
||||
content: `确认删除插件 ${p.id}?其全部版本与授权将一并清除`,
|
||||
positiveText: '删除',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
try { await adminPluginDelete({ plugin_id: p.id }); message.success(`已删除插件 ${p.id}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
},
|
||||
})
|
||||
dialog.confirm(`确认删除插件 ${p.id}?其全部版本与授权将一并清除`, '删除插件', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '删除',
|
||||
cancelButtonText: '取消',
|
||||
}).then(async () => {
|
||||
try { await adminPluginDelete({ plugin_id: p.id }); message.success(`已删除插件 ${p.id}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}).catch(() => {})
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
.up-card, .list-card { padding: 20px 22px; }
|
||||
.up-card .card-title { margin-bottom: 16px; }
|
||||
.up-form :deep(.el-form-item) { margin-bottom: 16px; }
|
||||
.file-row { display: flex; align-items: center; gap: 10px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 2px; line-height: 1.7; }
|
||||
.force-row { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
||||
.force-line { display: flex; gap: 10px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
</style>
|
||||
.cell-ops { display: flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.cell-ops .el-button { padding: 0 4px; }
|
||||
.cell-ops .el-button + .el-button { margin-left: 0; }
|
||||
|
||||
<!-- 以下类用于 n-data-table 列 render 中由 naive-ui 作用域动态渲染的节点,
|
||||
它们不继承本组件 scoped scopeId,必须用全局(非 scoped)样式才生效。 -->
|
||||
<style>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.cell-strong { font-weight: 600; color: var(--cp-ink-1); }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.row-acts { display: flex; align-items: center; gap: 14px; white-space: nowrap; }
|
||||
.row-acts .n-button { --n-padding: 0; }
|
||||
.row-acts .n-button + .n-button { margin-left: 0; }
|
||||
/* 插件详情 */
|
||||
.plg-detail { display: flex; flex-direction: column; gap: 18px; }
|
||||
.d-head { display: flex; align-items: center; gap: 10px; }
|
||||
.d-id { font-size: 16px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.d-name { font-size: 15px; color: var(--cp-ink-2); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.d-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
|
||||
.d-item { display: flex; flex-direction: column; gap: 5px; padding: 12px 14px; background: var(--cp-panel-2); border-radius: 12px; }
|
||||
.d-item label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.d-item span { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); }
|
||||
.d-sec { display: flex; flex-direction: column; gap: 8px; }
|
||||
.d-sec > label { font-size: 11px; font-weight: 700; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.d-desc { margin: 0; font-size: 13px; line-height: 1.7; color: var(--cp-ink); background: var(--cp-panel-2); padding: 10px 14px; border-radius: 10px; }
|
||||
.vlist { display: flex; flex-direction: column; gap: 6px; }
|
||||
.vrow { display: flex; align-items: center; gap: 12px; }
|
||||
.vtime { font-size: 12px; }
|
||||
.dim-sm { color: var(--cp-ink-3); }
|
||||
</style>
|
||||
|
||||
@@ -5,25 +5,26 @@
|
||||
<h3>运行统计 <span class="badge">Stats</span></h3>
|
||||
<p>账号 · 插件规模 · 执行次数/时长/成败 · 近 14 天趋势</p>
|
||||
</div>
|
||||
<n-button :loading="busy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<template v-if="st">
|
||||
<!-- 指标卡 -->
|
||||
<div class="kpis cp-rise">
|
||||
<div class="kpi"><span class="num" style="color:var(--cp-blue)">{{ st.users.total }}</span><span class="lab">用户总数</span></div>
|
||||
<div class="kpi"><span class="num">{{ st.plugins.total }}</span><span class="lab">插件总数</span></div>
|
||||
<div class="kpi"><span class="num">{{ st.runs.total }}</span><span class="lab">累计执行</span></div>
|
||||
<div class="kpi"><span class="num" style="color:#34a853">{{ st.runs.success }}</span><span class="lab">成功</span></div>
|
||||
<div class="kpi"><span class="num" style="color:#e5484d">{{ st.runs.failed }}</span><span class="lab">失败</span></div>
|
||||
<div class="kpi"><span class="num">{{ fmtDur(st.runs.durationSec) }}</span><span class="lab">总运行时长</span></div>
|
||||
<div class="kpi cp-card" v-for="(k, i) in kpis" :key="k.label" :style="{ animationDelay: i * 50 + 'ms' }">
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }">
|
||||
<el-icon :size="18"><component :is="k.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="kpi-meta">
|
||||
<div class="kpi-num mono" :style="{ color: k.color }">{{ k.value }}</div>
|
||||
<div class="kpi-lab">{{ k.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cp-rise">
|
||||
<div class="grid">
|
||||
<!-- 近 14 天趋势 -->
|
||||
<div class="card">
|
||||
<div class="cp-card trend-card cp-rise">
|
||||
<div class="card-title">近 14 天运行趋势</div>
|
||||
<div class="trend">
|
||||
<div class="tcol" v-for="d in st.trend" :key="d.day" :title="`${d.day} · ${d.runs} 次(成功 ${d.success} / 失败 ${d.failed})`">
|
||||
@@ -31,33 +32,44 @@
|
||||
<div class="tbar failed" :style="{ height: pct(d.failed, maxRuns) + '%' }"></div>
|
||||
<div class="tbar success" :style="{ height: pct(d.success, maxRuns) + '%' }"></div>
|
||||
</div>
|
||||
<span class="tday">{{ d.day }}</span>
|
||||
<span class="tday mono">{{ d.day }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="trend-legend">
|
||||
<span><i class="dot ok"></i>成功</span>
|
||||
<span><i class="dot fail"></i>失败</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 插件 / 用户排行 -->
|
||||
<div class="rank-wrap">
|
||||
<div class="card">
|
||||
<div class="card-title">插件排行(按运行次数)</div>
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">插件排行 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk">{{ i + 1 }}</span>
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead"><span class="rname">{{ p.name || p.pluginId }}</span><em>{{ p.runs }} 次</em></div>
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ p.name || p.pluginId }}</span>
|
||||
<em class="mono">{{ p.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(p.runs, rankMax(st.topPlugins)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topPlugins.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-title">活跃用户</div>
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">活跃用户 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk">{{ i + 1 }}</span>
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead"><span class="rname">{{ u.account }}</span><em>{{ u.runs }} 次</em></div>
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ u.account }}</span>
|
||||
<em class="mono">{{ u.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(u.runs, rankMax(st.topUsers)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topUsers.length" class="empty">暂无运行记录</li>
|
||||
@@ -70,39 +82,76 @@
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近运行</h4></div>
|
||||
</div>
|
||||
<n-card class="cp-rise" :bordered="false" size="small">
|
||||
<n-data-table :columns="recentCols" :data="st.recent" size="small" :row-key="r => r.at + r.pluginId" :single-line="false" />
|
||||
</n-card>
|
||||
<div class="cp-card cp-rise recent-card">
|
||||
<el-table :data="st.recent" size="small" :row-key="r => r.at + r.pluginId">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="110">
|
||||
<template #default="{ row }">
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ statusLabel(row.status) }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else>{{ row.account || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.pluginId }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="版本" width="100">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时长" width="100">
|
||||
<template #default="{ row }"><span class="mono">{{ fmtDur(row.durationSec) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="信息" min-width="220" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<n-skeleton v-else-if="busy" text :repeat="4" style="margin-top: 20px" />
|
||||
<div v-else class="empty-tip cp-rise">加载失败或暂无数据</div>
|
||||
<el-skeleton v-else-if="busy" animated :rows="5" style="margin-top: 20px" />
|
||||
<div v-else class="empty-tip cp-card cp-rise">加载失败或暂无数据</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { h } from 'vue'
|
||||
import { NTag } from 'naive-ui'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, User, Box, VideoPlay, CircleCheckFilled, CircleCloseFilled, Timer } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminStats } from '../api'
|
||||
import { message } from '../naive'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
const busy = ref(false)
|
||||
const st = ref(null)
|
||||
|
||||
function statusTag(s) {
|
||||
const map = { done: 'success', success: 'success', error: 'error', failed: 'error', running: 'info', start: 'info' }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[s] || 'default', round: true },
|
||||
{ default: () => (s === 'done' || s === 'success' ? '成功' : s === 'error' || s === 'failed' ? '失败' : s) })
|
||||
const kpis = computed(() => {
|
||||
if (!st.value) return []
|
||||
const r = st.value
|
||||
return [
|
||||
{ label: '用户总数', value: r.users.total, icon: User, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '插件总数', value: r.plugins.total, icon: Box, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '累计执行', value: r.runs.total, icon: VideoPlay, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '成功', value: r.runs.success, icon: CircleCheckFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '失败', value: r.runs.failed, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
{ label: '总运行时长', value: fmtDur(r.runs.durationSec), icon: Timer, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
]
|
||||
})
|
||||
|
||||
function statusColor(s) {
|
||||
return { done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d', running: '#2f5cf0', start: '#2f5cf0' }[s] || '#9aa2b4'
|
||||
}
|
||||
function acctCell(r) {
|
||||
const nn = r.nickname
|
||||
if (!nn) return h('span', null, r.account || '—')
|
||||
return h('div', { class: 'acct' }, [
|
||||
h('div', { class: 'ann' }, r.account || '—'),
|
||||
h('div', { class: 'anick' }, nn || ''),
|
||||
])
|
||||
function statusLabel(s) {
|
||||
return (s === 'done' || s === 'success') ? '成功' : (s === 'error' || s === 'failed') ? '失败' : s
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
@@ -112,17 +161,8 @@ function fmtDur(sec) {
|
||||
const hh = Math.floor(m / 60)
|
||||
return `${hh}h${m % 60}m`
|
||||
}
|
||||
const recentCols = [
|
||||
{ title: '时间', key: 'at', width: 165 },
|
||||
{ title: '状态', key: 'status', width: 90, render: r => statusTag(r.status) },
|
||||
{ title: '账号', key: 'account', width: 110, render: r => acctCell(r) },
|
||||
{ title: '插件', key: 'pluginId', width: 150, ellipsis: { tooltip: true } },
|
||||
{ title: '版本', key: 'version', width: 90 },
|
||||
{ title: '时长', key: 'durationSec', width: 90, render: r => fmtDur(r.durationSec) },
|
||||
{ title: '信息', key: 'msg', minWidth: 220, ellipsis: { tooltip: true }, render: r => r.msg || h('span', { class: 'dim' }, '—') },
|
||||
]
|
||||
const maxRuns = () => Math.max(1, ...(st.value?.trend || []).map(t => t.runs || 0))
|
||||
const pct = (n, max) => Math.max(1, Math.round((n || 0) / (max || 1) * 100))
|
||||
const pct = (n, max) => Math.max(2, Math.round((n || 0) / (max || 1) * 100))
|
||||
const rankMax = list => Math.max(1, ...(list || []).map(x => x.runs || 1))
|
||||
|
||||
async function refresh() {
|
||||
@@ -141,36 +181,59 @@ onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 14px; margin-bottom: 16px; }
|
||||
.kpi { padding: 16px 18px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.kpi .num { font-size: 26px; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; }
|
||||
.kpi .lab { font-size: 12px; color: var(--cp-ink-3); }
|
||||
.grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 16px; margin-bottom: 16px; }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 16px; }
|
||||
.card { padding: 18px 20px; }
|
||||
.card-title { font-size: 14px; font-weight: 600; color: var(--cp-ink-1); margin-bottom: 14px; }
|
||||
.trend { display: flex; gap: 4px; height: 160px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 4px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 1px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 1px 1px 0 0; }
|
||||
.tbar.success { background: #34a853; }
|
||||
.tbar.failed { background: #e5484d; }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 10px; padding: 7px 0; }
|
||||
.rank .rk { width: 20px; height: 20px; flex: none; border-radius: 6px; background: var(--cp-bg-2); color: var(--cp-ink-3); font-size: 12px; display: flex; align-items: center; justify-content: center; }
|
||||
.rank li:nth-child(1) .rk { background: rgba(59,108,255,.12); color: var(--cp-blue); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; }
|
||||
.rname { font-size: 13px; color: var(--cp-ink-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rhead em { font-style: normal; font-size: 12px; color: var(--cp-ink-3); }
|
||||
.rbar { height: 5px; border-radius: 3px; background: var(--cp-bg-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: var(--cp-blue); border-radius: 3px; }
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 16px 0 !important; }
|
||||
.empty-tip { padding: 30px; text-align: center; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 18px; }
|
||||
@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(3, 1fr); } }
|
||||
.kpi {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 18px;
|
||||
}
|
||||
.kpi-ic {
|
||||
width: 42px; height: 42px; border-radius: 13px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.kpi-meta { min-width: 0; }
|
||||
.kpi-num { font-size: 24px; font-weight: 800; line-height: 1.1; }
|
||||
.kpi-lab { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
|
||||
<style>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
</style>
|
||||
.grid { display: grid; grid-template-columns: 1.45fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||
@media (max-width: 1100px) { .grid { grid-template-columns: 1fr; } }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 18px; }
|
||||
.trend-card, .rank-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 16px; }
|
||||
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||
|
||||
.trend { display: flex; gap: 5px; height: 176px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 6px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 2px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 3px 3px 0 0; transition: filter .18s, transform .18s; }
|
||||
.tbar.success { background: linear-gradient(180deg, #34b877, #1d9d5c); }
|
||||
.tbar.failed { background: linear-gradient(180deg, #f07a72, #d6453d); }
|
||||
.tcol:hover .tbar { filter: brightness(1.05); }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.trend-legend { display: flex; gap: 18px; margin-top: 14px; font-size: 12px; color: var(--cp-ink-2); }
|
||||
.trend-legend .dot { width: 9px; height: 9px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||
.trend-legend .ok { background: #1d9d5c; }
|
||||
.trend-legend .fail { background: #d6453d; }
|
||||
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 11px; padding: 8px 0; }
|
||||
.rank .rk {
|
||||
width: 24px; height: 24px; flex: none; border-radius: 8px;
|
||||
background: var(--cp-panel-2); color: var(--cp-ink-3);
|
||||
font-size: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.rank .rk.top { background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 4px 10px -4px rgba(47, 92, 240, .5); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; gap: 10px; }
|
||||
.rname { font-size: 13px; font-weight: 600; color: var(--cp-ink-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rhead em { font-style: normal; font-size: 11.5px; color: var(--cp-ink-3); flex: none; }
|
||||
.rbar { height: 6px; border-radius: 4px; background: var(--cp-panel-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--cp-blue), var(--cp-teal)); border-radius: 4px; transition: width .6s cubic-bezier(.22, .61, .36, 1); }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 18px 0 !important; }
|
||||
.empty-tip { padding: 40px; text-align: center; color: var(--cp-ink-3); }
|
||||
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.recent-card { padding: 12px 16px; }
|
||||
.dim-sm { color: var(--cp-ink-2); }
|
||||
</style>
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 运维/构建工具集(CLI、PyInstaller spec、Windows 运维脚本)。"""
|
||||
"""controlplane 运维/构建工具集(CLI、数据库迁移、Windows 防火墙脚本)。"""
|
||||
@@ -0,0 +1,166 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SQLite → MySQL 一次性迁移脚本(37du 控制面)。
|
||||
|
||||
将历史 controlplane.db(SQLite)中的业务数据迁入 MySQL(MYSQL_DB 库)。
|
||||
- 幂等:有唯一键的表用 ON DUPLICATE KEY UPDATE,可重复执行;
|
||||
audit_logs / runtime_reports 无唯一键(纯追加日志),请勿重复执行,否则会追加副本。
|
||||
- plugin_grants 已并入 account_plugins(MySQL 版无独立 plugin_grants 表),
|
||||
迁移时以 plugin_grants 的 can_download/can_run 覆盖同名 account_plugins 行。
|
||||
|
||||
用法(在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.migrate_sqlite_to_mysql
|
||||
|
||||
前提:
|
||||
- controlplane/.env 已配置 MYSQL_*(迁移目标);
|
||||
- 脚本会自动建库建表(幂等 DDL),无需手工先建。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 兼容两种执行方式:python -m controlplane.tools.xxx(desktop/ 为搜索根)或直接跑脚本
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
import pymysql # noqa: E402
|
||||
from pymysql.cursors import DictCursor # noqa: E402
|
||||
|
||||
from controlplane.core import config # noqa: E402
|
||||
from controlplane.core.db import _ensure_database, _init_db # noqa: E402
|
||||
|
||||
|
||||
def _mysql() -> pymysql.connections.Connection:
|
||||
return pymysql.connect(
|
||||
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
|
||||
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
|
||||
database=config.MYSQL_DB, charset="utf8mb4",
|
||||
cursorclass=DictCursor, autocommit=False)
|
||||
|
||||
|
||||
def _sqlite_cols(conn: sqlite3.Connection, table: str) -> set:
|
||||
try:
|
||||
return {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
except sqlite3.OperationalError:
|
||||
return set()
|
||||
|
||||
|
||||
def _common_cols(conn: sqlite3.Connection, table: str, wanted: list) -> list:
|
||||
have = _sqlite_cols(conn, table)
|
||||
return [c for c in wanted if c in have]
|
||||
|
||||
|
||||
def _upsert(mysql, table: str, columns: list, rows: list) -> int:
|
||||
"""按唯一键幂等写入;columns 含目标列名(与 SQLite 同名)。"""
|
||||
if not columns or not rows:
|
||||
return 0
|
||||
ph = ", ".join(["%s"] * len(columns))
|
||||
sets = ", ".join(f"{c} = VALUES({c})" for c in columns)
|
||||
sql = (f"INSERT INTO {table}({', '.join(columns)}) VALUES ({ph}) "
|
||||
f"ON DUPLICATE KEY UPDATE {sets}")
|
||||
with mysql.cursor() as cur:
|
||||
for r in rows:
|
||||
cur.execute(sql, tuple(r))
|
||||
mysql.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _insert_append(mysql, table: str, columns: list, rows: list) -> int:
|
||||
"""日志类纯追加写入(无唯一键,重复执行会追加副本)。"""
|
||||
if not columns or not rows:
|
||||
return 0
|
||||
ph = ", ".join(["%s"] * len(columns))
|
||||
sql = f"INSERT INTO {table}({', '.join(columns)}) VALUES ({ph})"
|
||||
with mysql.cursor() as cur:
|
||||
for r in rows:
|
||||
cur.execute(sql, tuple(r))
|
||||
mysql.commit()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _main() -> int:
|
||||
if not config.MYSQL_HOST:
|
||||
print("[migrate] 未配置 MySQL(MYSQL_HOST),请先配置 controlplane/.env")
|
||||
return 1
|
||||
src = config.DB_PATH
|
||||
if not src.is_file():
|
||||
print(f"[migrate] 未找到 SQLite 源库:{src},无需迁移")
|
||||
return 0
|
||||
|
||||
print(f"[migrate] 源库(SQLite):{src}")
|
||||
print(f"[migrate] 目标(MySQL):{config.MYSQL_DB}@{config.MYSQL_HOST}:{config.MYSQL_PORT}")
|
||||
|
||||
_ensure_database()
|
||||
_init_db() # 幂等建表 + 登记迁移版本,保证目标结构就绪
|
||||
mysql = _mysql()
|
||||
try:
|
||||
with sqlite3.connect(str(src)) as sconn:
|
||||
sconn.row_factory = sqlite3.Row
|
||||
|
||||
# ---- 1) accounts(id 自增不迁移,账号唯一键幂等) ----
|
||||
cols = _common_cols(sconn, "accounts", [
|
||||
"account", "password_hash", "salt", "is_admin", "dept", "nickname",
|
||||
"dingtalk_uid", "must_change_pwd", "avatar", "status", "created_at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM accounts")] if cols else []
|
||||
print(f"[migrate] accounts: {_upsert(mysql, 'accounts', cols, rows)}")
|
||||
|
||||
# ---- 2) plugins ----
|
||||
cols = _common_cols(sconn, "plugins", [
|
||||
"id", "name", "latest_version", "description", "category", "icon",
|
||||
"status", "force_min_version", "force_deadline", "manifest", "created_at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM plugins")] if cols else []
|
||||
print(f"[migrate] plugins: {_upsert(mysql, 'plugins', cols, rows)}")
|
||||
|
||||
# ---- 3) plugin_versions(id 不迁移) ----
|
||||
cols = _common_cols(sconn, "plugin_versions", [
|
||||
"plugin_id", "version", "filename", "uploaded_at", "sha256", "size_bytes"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM plugin_versions")] if cols else []
|
||||
print(f"[migrate] plugin_versions: {_upsert(mysql, 'plugin_versions', cols, rows)}")
|
||||
|
||||
# ---- 4) account_plugins + plugin_grants 合并(后者权限位覆盖前者) ----
|
||||
a_cols = _common_cols(sconn, "account_plugins", ["account", "plugin_id"])
|
||||
a_rows = [tuple(r[c] for c in a_cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(a_cols)} FROM account_plugins")] if a_cols else []
|
||||
g_cols = _common_cols(sconn, "plugin_grants",
|
||||
["account", "plugin_id", "can_download", "can_run"])
|
||||
g_rows = [tuple(r[c] for c in g_cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(g_cols)} FROM plugin_grants")] if g_cols else []
|
||||
acc_rows = []
|
||||
for _a, _p in a_rows:
|
||||
acc_rows.append((_a, _p, 1, 1))
|
||||
for _a, _p, _d, _rn in g_rows:
|
||||
acc_rows.append((_a, _p, int(_d), int(_rn)))
|
||||
print(f"[migrate] account_plugins(合并 plugin_grants): "
|
||||
f"{_upsert(mysql, 'account_plugins', ['account', 'plugin_id', 'can_download', 'can_run'], acc_rows)}")
|
||||
|
||||
# ---- 5) account_platforms ----
|
||||
cols = _common_cols(sconn, "account_platforms", ["account", "platform_id"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM account_platforms")] if cols else []
|
||||
print(f"[migrate] account_platforms: {_upsert(mysql, 'account_platforms', cols, rows)}")
|
||||
|
||||
# ---- 6) audit_logs / 7) runtime_reports(纯追加,id 不迁移) ----
|
||||
cols = _common_cols(sconn, "audit_logs", ["account", "action", "target", "detail", "at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM audit_logs")] if cols else []
|
||||
print(f"[migrate] audit_logs(追加): {_insert_append(mysql, 'audit_logs', cols, rows)}")
|
||||
|
||||
cols = _common_cols(sconn, "runtime_reports", [
|
||||
"account", "device_id", "plugin_id", "version", "status", "msg",
|
||||
"duration_sec", "at"])
|
||||
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
|
||||
f"SELECT {', '.join(cols)} FROM runtime_reports")] if cols else []
|
||||
print(f"[migrate] runtime_reports(追加): {_insert_append(mysql, 'runtime_reports', cols, rows)}")
|
||||
|
||||
finally:
|
||||
mysql.close()
|
||||
|
||||
print("[migrate] 完成:devices/chrome_releases/system_settings 为 MySQL 新增表,无历史数据,跳过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(_main())
|
||||
@@ -1,39 +0,0 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane deployment script
|
||||
rem 1) copy 37du-center.exe to D:\code\controlplane
|
||||
rem 2) register auto-start (Startup folder vbs)
|
||||
rem 3) launch 37du-center.exe
|
||||
rem Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
set "TARGET=D:\code\controlplane"
|
||||
|
||||
rem locate exe: parent folder (controlplane/), or its dist-exe\ subfolder
|
||||
if exist "%~dp0..\37du-center.exe" (
|
||||
set "SRC=%~dp0..\37du-center.exe"
|
||||
) else if exist "%~dp0..\dist-exe\37du-center.exe" (
|
||||
set "SRC=%~dp0..\dist-exe\37du-center.exe"
|
||||
) else (
|
||||
set "SRC=%~dp0..\dist\37du-center.exe"
|
||||
)
|
||||
if not exist "%SRC%" (echo [ERROR] Not found: 37du-center.exe & pause & exit /b 1)
|
||||
|
||||
rem 1) copy to deployment folder
|
||||
if not exist "%TARGET%" mkdir "%TARGET%"
|
||||
copy /y "%SRC%" "%TARGET%\37du-center.exe" >nul
|
||||
echo [OK] Copied to %TARGET%
|
||||
|
||||
rem 2) register auto-start
|
||||
set "STARTUP=%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup"
|
||||
set "VBS=%STARTUP%\37du-center.vbs"
|
||||
echo Set WshShell = CreateObject("WScript.Shell") > "%VBS%"
|
||||
echo WshShell.Run """%TARGET%\37du-center.exe""", 0, False >> "%VBS%"
|
||||
echo [OK] Auto-start registered.
|
||||
|
||||
rem 3) launch service
|
||||
taskkill /f /im 37du-center.exe >nul 2>&1
|
||||
start "" "%TARGET%\37du-center.exe"
|
||||
echo [OK] 37du-center started. Visit http://this-host-ip:8800
|
||||
pause
|
||||
@@ -0,0 +1,189 @@
|
||||
-- ============================================================
|
||||
-- 37du 自动化平台 · 中心机控制面 表结构(MySQL 5.7+)
|
||||
-- 引擎:InnoDB / 字符集:utf8mb4 / 排序:utf8mb4_unicode_ci
|
||||
-- 执行:mysql -h<host> -u<user> -p < schema_mysql.sql
|
||||
-- 幂等:全部 CREATE TABLE IF NOT EXISTS,可重复执行
|
||||
-- ============================================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS 37du_center
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE 37du_center;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 迁移版本记录:db.py 启动幂等建表时登记,替代旧 _ensure_col 渐进补列
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 统一账号
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件元数据
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件版本:每插件仅保留最近 N 版,旧版由应用层裁剪
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-插件授权:含下载/运行权限位(合并原 plugin_grants)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-平台白名单:账号可登录的平台
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 审计日志:下载/授权/管控/发布等关键操作留痕
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 运行上报:执行机运行记录(启动/完成/失败/离线补报)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机设备:环境/心跳上报(配合执行机 Chrome 检测)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Chrome 安装包下载源配置:外链 URL,中心机不存包
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 系统级键值配置:全局配置沉淀(如环境依赖项)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
@@ -1,16 +0,0 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane stop script
|
||||
rem stops 37du-center.exe (auto-start registration is kept)
|
||||
rem MUST run as Administrator because the service was started
|
||||
rem from an elevated register_autostart.bat.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
taskkill /f /im 37du-center.exe >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [OK] 37du-center.exe is not running.
|
||||
) else (
|
||||
echo [OK] 37du-center.exe stopped.
|
||||
)
|
||||
pause
|
||||
@@ -9,7 +9,7 @@ from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins, _cloud_plugin_manifest
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
@@ -53,6 +53,11 @@ def plugins_sync(request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
# 以「登录账号的授权插件集」作为加载白名单(替代启动时 CONTROLPLANE_ACCOUNT 的固定白名单),
|
||||
# 保证给员工账号授权插件后登录即可见/可运行;控制面不可达(manifest=None)时保持原白名单。
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is not None:
|
||||
_st.set_allowed({p.get("id") for p in manifest})
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
|
||||
@@ -12,14 +12,14 @@ from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/config.py,parents[1]=webhost)
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/core/config.py,parents[2]=webhost)
|
||||
# 打包运行(frozen)时:底座根 = exe 所在目录(.env、plugins/ 与 exe 同级部署);
|
||||
# 前端静态资源打包进 exe 内部,运行时从解压目录(_MEIPASS)读取
|
||||
if getattr(sys, "frozen", False):
|
||||
_HOST_ROOT = Path(sys.executable).resolve().parent
|
||||
DIST = Path(getattr(sys, "_MEIPASS", _HOST_ROOT)) / "frontend" / "dist"
|
||||
else:
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[1]
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[2]
|
||||
DIST = _HOST_ROOT / "frontend" / "dist"
|
||||
|
||||
PORT = 8799
|
||||
|
||||
@@ -104,7 +104,7 @@
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员在控制面授权</span></div>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员进行授权</span></div>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
</aside>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user