feat(controlplane): 完成多页面管理台重构与平台权限控制
1. 重构控制面前端为多页面路由架构,拆分出概览/插件/账号/权限管理页面 2. 引入Element Plus组件库优化UI样式与交互 3. 新增平台登录权限校验,支持按账号授权HR/OA平台访问 4. 新增平台登出接口与个人中心功能 5. 完善账号管理、插件授权相关API与UI交互 6. 新增防火墙、启停、自启动脚本与部署文档
This commit is contained in:
@@ -33,6 +33,11 @@ ENV/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
# 控制面签名密钥 / 运行期产物(禁止入库)
|
||||
.admin_secret
|
||||
.webhost.pid
|
||||
*.pid
|
||||
controlplane/packages/
|
||||
# 各平台会话 cookies / 缓存目录(统一移入 %LOCALAPPDATA%\37duAutomation,禁止入库)
|
||||
**/.sessions/
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# 控制面管理台多页面化重构计划
|
||||
|
||||
## Context
|
||||
当前控制面管理台(controlplane/frontend)把「上传插件 / 插件列表 / 账号管理 / 插件授权 / 平台授权 / 修改密码」全部挤在单个 ManagementView.vue(~270 行)里,一屏堆叠、滚动查看困难,CRUD 操作没有独立入口。用户要求拆成多页面版本,每个 CRUD 独立成页,清晰可管理。
|
||||
|
||||
现状关键事实:
|
||||
- `package.json` 仅有 vue 依赖,**无 vue-router**;app 由 FastAPI `StaticFiles(html=True)` 挂载,history 路由刷新会 404 → 采用 **hash 路由**(`#/plugins`),刷新安全且零后端改动。
|
||||
- 数据面 `adminOverview()` 一次返回 plugins(含 versions/accounts) + accounts(含 plugins/platforms) + admins,各页面按需复用。
|
||||
- api.js 已有全部 CRUD 封装(adminUpload/adminGrant/adminPlatformGrant/adminAccount*/adminPluginDelete/adminPassword),**后端零改动**。
|
||||
|
||||
## 方案
|
||||
|
||||
### 1. 轻量 hash 路由(不新增依赖)
|
||||
`App.vue` 内实现 ~20 行路由:`route = ref(location.hash || '#/overview')`,监听 `hashchange`;顶栏下改为 **左侧扁平导航 + 右侧页面区** 布局(导航项:概览 / 插件管理 / 账号管理 / 权限授权,激活态用主色文字+左侧竖条,不用盒子边框)。
|
||||
|
||||
### 2. 页面拆分(components/views/,迁移 ManagementView.vue 现有逻辑,逐块对应)
|
||||
| 新页面 | 迁移自 ManagementView | 内容 |
|
||||
|---|---|---|
|
||||
| `OverviewView.vue` | 无(新增,轻量) | 统计数字(插件数/账号数/版本总数/最近上传)+ 使用说明一行 |
|
||||
| `PluginManageView.vue` | 上传插件包 + 插件列表 section | 上传表单一行 + 插件表格(版本历史/授权账号/删除) |
|
||||
| `AccountManageView.vue` | 账号管理 section | 建号行 + 账号表格(部门行内编辑/管理员切换/重置密码/删除) |
|
||||
| `GrantManageView.vue` | 授权账号 + 授权平台 section | **改为下拉选账号自动载入**(替代手输账号+点载入),插件勾选区与平台勾选区上下分节(扁平标题+分隔线) |
|
||||
| `PasswordDialog.vue` | 修改密码 section | 顶栏「改密码」按钮弹出的小弹层 |
|
||||
|
||||
`ManagementView.vue` 整体删除,不留死代码。
|
||||
|
||||
### 3. 共享状态与样式
|
||||
- `store.js` 增加 `overview = ref(null)` 与 `loadOverview(force)`:各页面 mounted 时调用(有缓存不重复拉),每页右上保留「刷新」按钮强刷。
|
||||
- ManagementView 中被多页面复用的 scoped 样式(table/th/td、.row、.ck、.link、.toast-note、input/button)提升到全局 `style.css`(沿用现有 CSS 变量 --border/--primary 等),页面内只留布局样式。
|
||||
- 沿用用户偏好:亮色、扁平、分区用「小标题 + 底部分隔线」,不用带边框的盒子。
|
||||
|
||||
### 4. 涉及文件
|
||||
- 改:`src/App.vue`(路由 + 侧导航 + 改密弹层入口)、`src/store.js`(overview 缓存)、`src/style.css`(公共表格/表单样式)
|
||||
- 增:`src/views/OverviewView.vue`、`PluginManageView.vue`、`AccountManageView.vue`、`GrantManageView.vue`、`src/components/PasswordDialog.vue`
|
||||
- 删:`src/components/ManagementView.vue`
|
||||
- 后端 `controlplane/app.py`:**不改**
|
||||
|
||||
### 5. 验证
|
||||
1. `cd controlplane/frontend && npm run build` 成功
|
||||
2. 源码起 controlplane(.venv\Scripts\python.exe controlplane\app.py),浏览器逐页验证:
|
||||
- 登录 → 默认落 `#/overview`;刷新页面保持当前 hash 页
|
||||
- 插件页上传/删除;账号页建号/改部门/切管理员/重置密码/删号;授权页下拉选账号后勾选保存(对比 overview 数据回显)
|
||||
- 顶栏「改密码」弹层改密后用新密码重登
|
||||
3. 通过后重打 `37du-center.exe`(pyinstaller 37du-center.spec → dist-exe)供中心机部署
|
||||
@@ -0,0 +1,57 @@
|
||||
# 个人中心设计(webhost 底座)
|
||||
|
||||
## Context
|
||||
|
||||
webhost 当前顶部栏只显示「账号名 + 管理员标签 + 登出」,平台登录态按钮横向排列在顶部,但没有集中查看账号信息、管理平台登录态、查看自身插件权限的入口。用户希望新增"个人中心":点击顶部账号名弹出面板,包含账号信息+修改密码、我的插件权限、平台登录态管理,并支持头像展示(第三方随机头像 API)。
|
||||
|
||||
现状:
|
||||
- 后端已有 `/api/admin/me`(转发中心机,仅返回 `account/is_admin`)、`/api/admin/password`(改密)、`/api/admin/logout`、`/api/platforms/{pid}/login`
|
||||
- 无平台登出接口;中心机 `me` 接口未返回 `dept` 字段(accounts 表有 dept)
|
||||
- 前端无路由,纯状态切换(`store.view`),顶部栏在 [App.vue](file:///d:/work/code/37duAutomation/webhost/frontend/src/App.vue)
|
||||
|
||||
## 方案
|
||||
|
||||
点击顶部账号名 → 右侧滑出扁平面板(覆盖层),含 3 个分节:账号信息、平台登录态、我的插件、修改密码。样式遵循用户偏好:亮色、无白色边框盒子、分节标题 + 分隔线、只留必要字段和单个执行按钮。
|
||||
|
||||
### 后端(webhost/backend/main.py + auth.py)
|
||||
|
||||
1. **新增平台登出接口** `POST /api/platforms/{pid}/logout`:
|
||||
- `_require_login(request)` 鉴权
|
||||
- 调用 `auth.py` 新增的 `logout(pid)`:删除对应共享 cookies 文件 `%LOCALAPPDATA%\37duAutomation\.sessions\{pid}_cookies.json`(hr_cookies.json / oa_cookies.json),返回 `{ok, online: False}`
|
||||
- auth.py 新增 `logout()` 方法,参照现有 `COOKIE_FILES` 映射([auth.py L25-L35](file:///d:/work/code/37duAutomation/webhost/backend/auth.py))
|
||||
|
||||
2. **`/api/admin/me` 增强**:转发中心机返回 `dept` 字段(登录后 `me.dept` 展示部门)。
|
||||
|
||||
### 中心机(controlplane/app.py)
|
||||
|
||||
3. **`/api/admin/me` 返回 dept**:SQL 改为 `SELECT is_admin, dept FROM accounts WHERE account=?`,返回 `{account, is_admin, dept}`([app.py L273-L284](file:///d:/work/code/37duAutomation/controlplane/app.py))。
|
||||
|
||||
### 前端(webhost/frontend/src)
|
||||
|
||||
4. **App.vue**:账号名区域改为可点击(`@click` 打开面板),新增 `profileOpen` 状态与面板渲染。
|
||||
|
||||
5. **新增 ProfilePanel.vue**(右侧滑出覆盖层):
|
||||
- 顶部:头像(`https://v2.xxapi.cn/api/head` 302 直出随机头像)+ 账号名 + 部门 + 管理员标签
|
||||
- 分节"平台登录态":复用 `store.platforms`,显示 HR/OA 在线状态点,操作:重新登录、登出平台(调新 logout 接口后更新 `p.online`)
|
||||
- 分节"我的插件":复用 `store.plugins`(已是当前账号权限白名单过滤后),展示名称 + 版本
|
||||
- 分节"修改密码":旧密码 / 新密码 / 确认新密码 + 单个按钮,成功后提示并关闭面板
|
||||
- 样式:扁平亮色、无卡片边框、分节标题 + 分隔线,与现有 `.panel` 体系一致
|
||||
|
||||
6. **api.js**:新增 `adminChangePassword(payload)`、`platformLogout(pid)`。
|
||||
|
||||
7. **store.js**:`me` 增加 `dept` 字段存储。
|
||||
|
||||
## 涉及文件
|
||||
|
||||
- `webhost/backend/main.py`:新增平台登出接口、me 转发透传 dept
|
||||
- `webhost/backend/auth.py`:新增 `logout(pid)`
|
||||
- `controlplane/app.py`:admin_me 返回 dept
|
||||
- `webhost/frontend/src/App.vue`:账号名入口 + 面板挂载
|
||||
- `webhost/frontend/src/components/ProfilePanel.vue`:新建
|
||||
- `webhost/frontend/src/api.js`、`store.js`:新增 API 调用与状态
|
||||
|
||||
## 验证
|
||||
|
||||
1. 后端:重启后 `puddy/123456` 登录 → `GET /api/admin/me` 返回含 `dept`;`POST /api/platforms/hr/logout` 返回 `{ok:true}` 且 `.sessions\hr_cookies.json` 被删除;`GET /api/meta` 中 hr `online` 变 false
|
||||
2. 中心机:`curl http://127.0.0.1:8800/api/admin/me` 带 X-Admin-User 返回 `dept`
|
||||
3. 前端:`npm run build` 通过;窗口内点账号名弹出面板,三个分节展示正常,平台登出后状态点变灰,修改密码(旧/新)提交成功
|
||||
@@ -0,0 +1,58 @@
|
||||
# 平台登录权限控制(HR/OA)
|
||||
|
||||
## Context
|
||||
|
||||
webhost 底座的 HR/OA 平台登录目前只要登录了统一账户即可调用 `/api/platforms/{pid}/login`,无账号级权限区分。用户要求:平台登录也需按账号授权,未授权账号不能登录——与现有插件权限(`account_plugins` 表 + 中心机白名单)采用同一套授权模型。同时用户已开通中心机 SMB 共享(`\\DESKTOP-06SS2IA\code\controlplane`,账号 `admin`),要求本轮一并部署新版中心机 exe(含上一轮 dept 改动)。
|
||||
|
||||
现状:
|
||||
- 中心机已有 `account_plugins` 授权表、`/api/admin/account_plugins` 授权接口(INSERT OR IGNORE / DELETE)、`/api/plugins?account=` 白名单查询、`/api/admin/accounts`(返回每账号已授权 `plugins`)——平台授权完全复用此模式
|
||||
- webhost 平台登录流程:[/api/meta](file:///d:/work/code/37duAutomation/webhost/backend/main.py#L236-L241) 返回 platforms、[login](file:///d:/work/code/37duAutomation/webhost/backend/main.py#L244-L251) 仅 `_require_login`
|
||||
- 控制面管理台插件授权 UI 在 [ManagementView.vue L76-L163](file:///d:/work/code/37duAutomation/controlplane/frontend/src/components/ManagementView.vue)
|
||||
|
||||
## 方案
|
||||
|
||||
平台权限按「当前登录统一账户」判定(非底座共享账号 CONTROLPLANE_ACCOUNT),中心机为真源,webhost 实时校验。
|
||||
|
||||
### 中心机(controlplane/app.py)
|
||||
|
||||
1. **建表**:`_init_db` 的 executescript 追加 `account_platforms(account TEXT, platform_id TEXT, PRIMARY KEY(account, platform_id))`(参照 account_plugins,L112-L116)。
|
||||
2. **授权接口** `POST /api/admin/account_platforms`:入参 `{account, platform_id, granted}`,逻辑照抄 `admin_grant`(L525-L553):`_require_admin`、账号存在性校验、INSERT OR IGNORE / DELETE。
|
||||
3. **白名单查询** `GET /api/platforms/allowed?account=xxx`(webhost 用,非 admin):返回 `{"account":..., "allowed":["hr","oa"]}`;带 `_check_token` 兜底。
|
||||
4. **accounts 接口**:`/api/admin/accounts` 每个账号联查 `account_platforms` 返回 `platforms`(与现有 `plugins` 并列),供管理 UI 载入已授权平台。
|
||||
|
||||
### 控制面管理 UI(controlplane/frontend/src)
|
||||
|
||||
5. **ManagementView.vue**:
|
||||
- 账号表格加一列「可登录平台」显示 `a.platforms.join('、')`
|
||||
- 新增「平台授权」区块(复刻插件授权区 L76-L87):平台常量 `[{id:'hr',label:'HR 系统'},{id:'oa',label:'OA 系统'}]`,输入账号 → 载入已授权(从 accounts.platforms)→ 勾选 → 保存(逐个调授权接口,增量差量更新,参照 saveGrant L150-L163)
|
||||
- **api.js** 新增 `adminPlatformGrant({account, platform_id, granted})`
|
||||
|
||||
### webhost 后端(webhost/backend/main.py)
|
||||
|
||||
6. **meta 返回平台权限**:`/api/meta` 加 `request` 参数,取 `_sess_account(request)`;已登录则调中心机 `/api/platforms/allowed?account=` 得到 allowed 集合,platforms 每项加 `allowed`(未登录/中心机不可达时默认 `true`)。
|
||||
7. **login 强校验**:`/api/platforms/{pid}/login` 在 `_require_login` 后校验当前账号 allowed 含 pid,否则 403「无该平台访问权限」;中心机不可达时拒绝(503「控制面不可达,无法校验平台权限」),不做降级放行。
|
||||
|
||||
### webhost 前端(App.vue)
|
||||
|
||||
8. `onLogin` 后重新 `fetchMeta()` 刷新 platforms 的 `allowed`(登录后 cookie 生效);chip 绑定 `:class="{ online, locked: p.allowed === false }"`,未授权时 disabled + title「无权限:需管理员在控制面授权」;`login()` 对 `allowed===false` 直接拦截。
|
||||
|
||||
### 打包与部署
|
||||
|
||||
9. 控制面前端 `npm run build` → 重新打包 [37du-center.spec](file:///d:/work/code/37duAutomation/controlplane/37du-center.spec) → 同步到 `controlplane\dist\37du-center.exe`
|
||||
10. webhost 前端 `npm run build`
|
||||
11. **中心机部署**(SMB):`net use \\DESKTOP-06SS2IA\code /user:admin jsyx123456` 挂载凭据 → 中心机先执行 `stop_center.bat` 停服务(否则 exe 被占用)→ 覆盖 `\\DESKTOP-06SS2IA\code\controlplane\37du-center.exe` → 中心机执行 `register_autostart.bat` 重启
|
||||
|
||||
## 涉及文件
|
||||
|
||||
- `controlplane/app.py`:建表 + 授权接口 + allowed 查询 + accounts 返回 platforms
|
||||
- `controlplane/frontend/src/components/ManagementView.vue`、`api.js`:平台授权 UI
|
||||
- `webhost/backend/main.py`:meta allowed + login 权限校验
|
||||
- `webhost/frontend/src/App.vue`:未授权置灰 + 登录后刷新
|
||||
|
||||
## 验证
|
||||
|
||||
1. 中心机:`puddy` 授权 hr/oa 后 `/api/platforms/allowed?account=puddy` 返回 `["hr","oa"]`;`alice` 未授权返回空;`/api/admin/accounts` 返回每账号 `platforms`
|
||||
2. webhost:`puddy` 登录 → `/api/meta` platforms 带 `allowed`;对已授权平台 login 成功、未授权平台 403
|
||||
3. 管理台:账号表格显示可登录平台;alice 授权 hr 后置灰恢复可点
|
||||
4. 前端:`npm run build` 通过(webhost + controlplane)
|
||||
5. 部署后:中心机 `http://172.30.28.131:8800` 正常,webhost `me.dept` 返回部门
|
||||
+322
-61
@@ -17,12 +17,19 @@ DB:controlplane.db(同目录),三张表随时可重建(self-contained
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
import time
|
||||
import zipfile
|
||||
from contextlib import asynccontextmanager, contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
@@ -68,6 +75,57 @@ _load_dotenv()
|
||||
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
|
||||
# ==================== 管理台会话(签名票据,杜绝凭用户名冒用) ====================
|
||||
# 管理接口不再信任 "X-Admin-User: 用户名"(可直接 curl 伪造),改为登录后签发的签名票据。
|
||||
# secret 取值优先级:CONTROLPLANE_ADMIN_SECRET(envenv) > CONTROLPLANE_TOKEN > 首次随机生成并持久化
|
||||
# 到 .admin_secret 文件(保证重启不回退)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
if _ADMIN_SECRET_CANDIDATE:
|
||||
return _ADMIN_SECRET_CANDIDATE
|
||||
global _ADMIN_SECRET_FALLBACK
|
||||
if _ADMIN_SECRET_FALLBACK:
|
||||
return _ADMIN_SECRET_FALLBACK
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
_ADMIN_SECRET_FALLBACK = _f.read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
_ADMIN_SECRET_FALLBACK = secrets.token_hex(32)
|
||||
_f.write_text(_ADMIN_SECRET_FALLBACK, encoding="utf-8")
|
||||
return _ADMIN_SECRET_FALLBACK
|
||||
|
||||
|
||||
_ADMIN_SECRET_FALLBACK = ""
|
||||
_ADMIN_TOKEN_TTL = 12 * 3600 # 票据有效期 12h
|
||||
|
||||
|
||||
def _sign_admin_token(account: str) -> str:
|
||||
"""签发带过期时间的签名票据:<base64url(json)>.<hmac_sig>,内含账号,防篡改/防伪造。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + _ADMIN_TOKEN_TTL},
|
||||
separators=(",", ":")).encode()).decode().rstrip("=")
|
||||
sig = hmac.new(_admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||||
hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
def _verify_admin_token(tok: str) -> str:
|
||||
"""还原票据中的账号;签名无效或过期抛 ValueError。"""
|
||||
if "." not in tok:
|
||||
raise ValueError("invalid token")
|
||||
payload, sig = tok.rsplit(".", 1)
|
||||
expect = hmac.new(_admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||||
hashlib.sha256).hexdigest()
|
||||
if not secrets.compare_digest(expect, sig):
|
||||
raise ValueError("bad signature")
|
||||
pad = "=" * (-len(payload) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(payload + pad))
|
||||
if int(data.get("e", 0)) < int(time.time()):
|
||||
raise ValueError("expired")
|
||||
return str(data.get("a", "") or "")
|
||||
|
||||
|
||||
# ==================== 密码哈希(标准库 pbkdf2,盐 + 多轮) ====================
|
||||
_ITER = 120_000
|
||||
@@ -86,10 +144,17 @@ def _verify_password(pwd: str, salt: str, hexdigest: str) -> bool:
|
||||
|
||||
|
||||
# ==================== DB 访问 ====================
|
||||
def _db() -> sqlite3.Connection:
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(sqlite3 原生 with 语义只 commit 不 close,
|
||||
长运行服务会累积连接,这里统一收口)。异常时放弃 commit 等价于回滚。"""
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _init_db() -> None:
|
||||
@@ -114,6 +179,11 @@ def _init_db() -> None:
|
||||
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 (
|
||||
account TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL,
|
||||
@@ -127,7 +197,11 @@ def _init_db() -> None:
|
||||
|
||||
|
||||
def _seed() -> None:
|
||||
"""首次启动写入示例数据 + 默认管理员(puddy),并生成示例包。"""
|
||||
"""首次启动写入插件种子 + 默认管理员(puddy),并生成示例包。
|
||||
|
||||
不再种子 demo 普通账号(alice/bob 曾带弱口令 123456 入生产库),
|
||||
普通账号一律由管理员在控制台建号。
|
||||
"""
|
||||
PKG_DIR.mkdir(exist_ok=True)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
@@ -139,15 +213,12 @@ def _seed() -> None:
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
conn.execute("INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
("alice", "seal_check"),
|
||||
)
|
||||
# 统一账户:所有账号均有密码 + 所属部门(明文永不入库,只存盐+哈希)
|
||||
for _acc, _dept, _admin in (("puddy", "IT", 1), ("alice", "财务部", 0), ("bob", "营销部", 0)):
|
||||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||||
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, _admin, _dept))
|
||||
"VALUES (?, ?, ?, ?, ?)", (_acc, _hex, _salt, 1, _dept))
|
||||
conn.commit()
|
||||
pkg = PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
@@ -165,12 +236,15 @@ def _check_token(x_api_token: str = "") -> None:
|
||||
raise HTTPException(401, "鉴权失败:无效或缺失 X-API-Token")
|
||||
|
||||
|
||||
def _require_admin(x_admin_user: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:校验内部凭证 + 操作者账号存在且 is_admin=1。返回账号。"""
|
||||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:校验内部凭证(X-API-Token) + 登录票据(X-Admin-Token)对应账号 is_admin=1。返回账号。"""
|
||||
_check_token(x_api_token)
|
||||
account = (x_admin_user or "").strip()
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not account:
|
||||
raise HTTPException(400, "缺少 x-admin-user(当前登录账号)")
|
||||
raise HTTPException(401, "缺少有效登录态")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM accounts WHERE account = ? AND is_admin = 1", (account,)).fetchone()
|
||||
@@ -179,6 +253,48 @@ def _require_admin(x_admin_user: str = "", x_api_token: str = "") -> str:
|
||||
return account
|
||||
|
||||
|
||||
def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
x_admin_user: str = "") -> str:
|
||||
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin):
|
||||
|
||||
1. 优先验签名票据 X-Admin-Token(控制台直连场景);
|
||||
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||||
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
if account:
|
||||
return account
|
||||
except Exception:
|
||||
pass
|
||||
if (x_admin_user.strip() and CONTROLPLANE_TOKEN
|
||||
and x_api_token == CONTROLPLANE_TOKEN):
|
||||
return x_admin_user.strip()
|
||||
raise ValueError("no identity")
|
||||
|
||||
|
||||
# ==================== 登录防爆破(进程内计数,失败锁定退避) ====================
|
||||
_AUTH_FAILS: dict = {} # account -> [连续失败次数, 锁定截止时间戳]
|
||||
_AUTH_FAIL_LIMIT = 5 # 连续失败 N 次后锁定
|
||||
_AUTH_LOCK_SECS = 300 # 锁定 5 分钟
|
||||
|
||||
|
||||
def _auth_gate(account: str) -> None:
|
||||
fails, locked_until = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
if locked_until > time.time():
|
||||
raise HTTPException(429, f"失败次数过多,账号已临时锁定,请 {int(locked_until - time.time())} 秒后重试")
|
||||
|
||||
|
||||
def _auth_fail(account: str) -> None:
|
||||
fails, _ = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
fails += 1
|
||||
if fails >= _AUTH_FAIL_LIMIT:
|
||||
_AUTH_FAILS[account] = (0, time.time() + _AUTH_LOCK_SECS)
|
||||
else:
|
||||
_AUTH_FAILS[account] = (fails, 0.0)
|
||||
|
||||
|
||||
# ==================== 请求体 ====================
|
||||
class PluginOut(BaseModel):
|
||||
id: str
|
||||
@@ -225,6 +341,21 @@ def plugins(account: str = Query(..., description="账号"),
|
||||
return {"account": account.strip(), "plugins": [PluginOut(**dict(r)).model_dump() for r in rows]}
|
||||
|
||||
|
||||
@app.get("/api/platforms/allowed", response_model=dict)
|
||||
def platforms_allowed(account: str = Query(..., description="账号"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""按账号返回可登录平台白名单(与插件权限同模式)。"""
|
||||
_check_token(x_api_token)
|
||||
if not account.strip():
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
|
||||
(account.strip(),),
|
||||
).fetchall()
|
||||
return {"account": account.strip(), "allowed": [dict(r)["platform_id"] for r in rows]}
|
||||
|
||||
|
||||
@app.get("/api/manifest")
|
||||
def manifest(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全量插件版本清单:客户端据此比对是否需要拉新包。"""
|
||||
@@ -259,29 +390,79 @@ def pkg(plugin_id: str, version: str,
|
||||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
# # # # # ==================== 管理侧(写操作,需正确 token) ==================== # # # # #
|
||||
# # # # # # # # # ==================== 管理侧(写操作,需正确 token) ==================== # # # # #
|
||||
|
||||
# 插件包约束:大小上限 / 必含文件 / 保留版本数 / 安全文件名
|
||||
_PKG_MAX_BYTES = 200 * 1024 * 1024
|
||||
_PKG_REQUIRED_FILES = ("plugin.json", "main.py", "requirements.txt")
|
||||
_KEEP_VERSIONS = 3
|
||||
_SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
||||
|
||||
|
||||
def _validate_pkg_zip(content: bytes) -> None:
|
||||
"""插件包完整性校验:体积上限 + ZIP 结构 + 必含文件 + plugin.json 可解析。"""
|
||||
if len(content) > _PKG_MAX_BYTES:
|
||||
raise HTTPException(400, f"插件包超过大小上限({_PKG_MAX_BYTES // 1024 // 1024}MB)")
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
raise HTTPException(400, "上传内容不是有效的 ZIP 包")
|
||||
with zf:
|
||||
if zf.testzip() is not None:
|
||||
raise HTTPException(400, "ZIP 包校验失败(存在损坏条目)")
|
||||
names = set(zf.namelist())
|
||||
missing = [f for f in _PKG_REQUIRED_FILES if f not in names]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
400, f"插件包缺少必需文件:{', '.join(missing)}(包根目录需含 plugin.json / main.py / requirements.txt)")
|
||||
try:
|
||||
json.loads(zf.read("plugin.json").decode("utf-8"))
|
||||
except Exception:
|
||||
raise HTTPException(400, "plugin.json 不是合法 JSON")
|
||||
|
||||
|
||||
def _prune_versions(conn: sqlite3.Connection, plugin_id: str) -> list:
|
||||
"""仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。"""
|
||||
rows = conn.execute(
|
||||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = ?", (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 = ?",
|
||||
(plugin_id, r["version"]))
|
||||
return [r["filename"] for r in stale]
|
||||
|
||||
|
||||
def _version_key(v: str):
|
||||
def to_int(s):
|
||||
"""版本比较键:数字段转 (1, int),非数字段转 (0, str),
|
||||
保证任意段间可比较(如 1.0.0-beta 不再触发 int/str TypeError)。"""
|
||||
def to_key(s):
|
||||
try:
|
||||
return int(s)
|
||||
return (1, int(s))
|
||||
except ValueError:
|
||||
return s
|
||||
return tuple(to_int(x) for x in str(v).split("."))
|
||||
return (0, str(s).lower())
|
||||
return tuple(to_key(x) for x in str(v).split("."))
|
||||
|
||||
|
||||
@app.get("/api/admin/me")
|
||||
def admin_me(x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""查询当前账号是否为管理员。"""
|
||||
_check_token(x_api_token)
|
||||
account = (x_admin_user or "").strip()
|
||||
def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""查询当前账号信息:管理员标识 + 部门。
|
||||
|
||||
身份来源:控制台直连走 X-Admin-Token 票据;底座代理走 X-Admin-User 注入(需内部凭证)。
|
||||
"""
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False}
|
||||
return {"account": "", "is_admin": False, "dept": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
return {"account": account, "is_admin": bool(row and row["is_admin"])}
|
||||
"SELECT is_admin, dept FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
return {"account": account,
|
||||
"is_admin": bool(row and row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or ""}
|
||||
|
||||
|
||||
class AuthIn(BaseModel):
|
||||
@@ -297,13 +478,17 @@ def admin_auth(a: AuthIn,
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
_auth_gate(account)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, is_admin, dept FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||
_auth_fail(account)
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"])}
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
|
||||
|
||||
class PwdIn(BaseModel):
|
||||
@@ -314,39 +499,48 @@ class PwdIn(BaseModel):
|
||||
|
||||
@app.post("/api/admin/password")
|
||||
def admin_password(p: PwdIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""修改管理员密码:需旧密码校验通过。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。
|
||||
|
||||
身份来源同 /api/admin/me:控制台票据或底座代理注入;管理写操作(改他人)仍走管理员重置接口。
|
||||
"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
if p.account != x_admin_user:
|
||||
if p.account != login:
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt FROM accounts WHERE account = ?", (x_admin_user,)).fetchone()
|
||||
"SELECT password_hash, salt FROM accounts WHERE account = ?", (login,)).fetchone()
|
||||
if not row or not _verify_password(p.old_password, row["salt"], row["password_hash"]):
|
||||
raise HTTPException(401, "原密码错误")
|
||||
_hex, _salt = _hash_password(p.new_password)
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||||
(_hex, _salt, x_admin_user))
|
||||
(_hex, _salt, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": x_admin_user}
|
||||
return {"ok": True, "account": login}
|
||||
|
||||
|
||||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||
@app.get("/api/admin/accounts")
|
||||
def admin_accounts(x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全部账号(含部门/管理员标记/已授权插件)。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT account, is_admin, dept FROM accounts ORDER BY account")]
|
||||
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"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@@ -359,10 +553,10 @@ class AccountCreateIn(BaseModel):
|
||||
|
||||
@app.post("/api/admin/account")
|
||||
def admin_account_create(a: AccountCreateIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""新建账号:密码必填,可指定部门与是否管理员。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
@@ -388,10 +582,10 @@ class AccountUpdateIn(BaseModel):
|
||||
|
||||
@app.post("/api/admin/account/update")
|
||||
def admin_account_update(a: AccountUpdateIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""更新账号:改部门 / 授予或撤销管理员。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
@@ -407,7 +601,7 @@ def admin_account_update(a: AccountUpdateIn,
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||||
else:
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||||
(account, x_admin_user))
|
||||
(account, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
@@ -419,10 +613,10 @@ class AccountResetIn(BaseModel):
|
||||
|
||||
@app.post("/api/admin/account/reset_pwd")
|
||||
def admin_account_reset(r: AccountResetIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理员重置任意账号密码(无需原密码)。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
@@ -442,14 +636,14 @@ class AccountDelIn(BaseModel):
|
||||
|
||||
@app.post("/api/admin/account/delete")
|
||||
def admin_account_delete(d: AccountDelIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除账号:不可删除自己;连带清除其插件授权。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = d.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
if account == x_admin_user:
|
||||
if account == login:
|
||||
raise HTTPException(400, "不能删除当前登录的账号")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
@@ -461,10 +655,10 @@ def admin_account_delete(d: AccountDelIn,
|
||||
|
||||
|
||||
@app.get("/api/admin/overview")
|
||||
def admin_overview(x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理台一次性拉取:全部插件(含版本历史、被授予账号)+ 全部账号 + 管理员名单。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, latest_version FROM plugins ORDER BY id")]
|
||||
@@ -479,6 +673,8 @@ def admin_overview(x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
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"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (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}
|
||||
@@ -488,20 +684,24 @@ def admin_overview(x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
plugin_id: str = Query(...), name: str = Query(...),
|
||||
version: str = Query(...),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传并发布插件包:保存到磁盘,登记版本,更新最新版;插件不存在则自动创建。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = plugin_id.strip()
|
||||
name = name.strip() or plugin_id
|
||||
version = version.strip()
|
||||
if not plugin_id or not version:
|
||||
raise HTTPException(400, "plugin_id 与 version 不能为空")
|
||||
# 只允许安全字符(防止拼进文件路径造成目录穿越)
|
||||
if not _SAFE_NAME_RE.match(plugin_id) or not _SAFE_NAME_RE.match(version):
|
||||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||
filename = f"{plugin_id}_v{version}.zip"
|
||||
target = PKG_DIR / filename
|
||||
content = await upload.read()
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
_validate_pkg_zip(content)
|
||||
target.write_bytes(content)
|
||||
|
||||
with _db() as conn:
|
||||
@@ -516,7 +716,13 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||||
stale_files = _prune_versions(conn, plugin_id)
|
||||
conn.commit()
|
||||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||||
try:
|
||||
(PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||
|
||||
|
||||
@@ -528,10 +734,10 @@ class GrantIn(BaseModel):
|
||||
|
||||
@app.post("/api/admin/account_plugins")
|
||||
def admin_grant(g: GrantIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予或撤销某账号对某插件的权限。granted=True 授,False 撤。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
if not account or not plugin_id:
|
||||
@@ -542,7 +748,7 @@ def admin_grant(g: GrantIn,
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUEs (?, ?)",
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
(account, plugin_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||||
@@ -551,16 +757,46 @@ def admin_grant(g: GrantIn,
|
||||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||
|
||||
|
||||
class PlatformGrantIn(BaseModel):
|
||||
account: str
|
||||
platform_id: str
|
||||
granted: bool
|
||||
|
||||
|
||||
@app.post("/api/admin/account_platforms")
|
||||
def admin_platform_grant(g: PlatformGrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
platform_id = g.platform_id.strip()
|
||||
if not account or not platform_id:
|
||||
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():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||||
(account, platform_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
|
||||
|
||||
class PluginDelIn(BaseModel):
|
||||
plugin_id: str
|
||||
|
||||
|
||||
@app.post("/api/admin/plugin/delete")
|
||||
def admin_plugin_delete(d: PluginDelIn,
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||||
_require_admin(x_admin_user, x_api_token)
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = d.plugin_id.strip()
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
@@ -595,6 +831,31 @@ if DIST.is_dir():
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
# PyInstaller --noconsole 下 sys.stdout/stderr 可能为 None,
|
||||
# uvicorn 默认 DefaultFormatter 会调用 isatty() 导致启动崩溃,故自定义日志配置绕开颜色检测。
|
||||
LOG_CONFIG = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"default": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||||
"access": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||||
},
|
||||
"handlers": {
|
||||
"default": {"class": "logging.StreamHandler", "formatter": "default"},
|
||||
"access": {"class": "logging.StreamHandler", "formatter": "access"},
|
||||
},
|
||||
"loggers": {
|
||||
"uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||||
"uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||||
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
|
||||
},
|
||||
}
|
||||
if getattr(sys, "frozen", False):
|
||||
if sys.stdout is None:
|
||||
sys.stdout = open(os.devnull, "w")
|
||||
if sys.stderr is None:
|
||||
sys.stderr = open(os.devnull, "w")
|
||||
|
||||
PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||
print(f"[controlplane] http://127.0.0.1:{PORT} localStorage={DB_PATH.name}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")
|
||||
print(f"[controlplane] http://0.0.0.0:{PORT} sqlite={DB_PATH.name}")
|
||||
uvicorn.run(app, host="0.0.0.0", port=PORT, log_config=LOG_CONFIG, log_level="info")
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -0,0 +1,107 @@
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named org - imported by pickle (optional)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
|
||||
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
|
||||
missing module named gunicorn - imported by uvicorn.workers (top-level)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
|
||||
missing module named trio - imported by anyio._backends._trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
|
||||
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
|
||||
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
|
||||
missing module named readline - imported by websockets.cli (delayed, optional)
|
||||
missing module named werkzeug - imported by websockets.asyncio.router (optional)
|
||||
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
|
||||
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional)
|
||||
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
|
||||
missing module named uvloop - imported by anyio._backends._asyncio (delayed, conditional), uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level)
|
||||
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
|
||||
missing module named IPython - imported by dotenv.ipython (top-level)
|
||||
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level), D:\work\code\37duAutomation\controlplane\app.py (top-level)
|
||||
missing module named cython - imported by pydantic.v1.version (optional)
|
||||
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), pydantic.v1._hypothesis_plugin (optional)
|
||||
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
|
||||
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
|
||||
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
|
||||
missing module named mypy - imported by pydantic.mypy (top-level)
|
||||
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
|
||||
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
|
||||
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
|
||||
missing module named rich - imported by pydantic._internal._core_utils (conditional)
|
||||
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
|
||||
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
|
||||
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
|
||||
missing module named sniffio - imported by anyio._core._eventloop (optional)
|
||||
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
|
||||
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
|
||||
missing module named outcome - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
|
||||
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
|
||||
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane firewall script
|
||||
rem opens TCP port 8800. Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
netsh advfirewall firewall delete rule name="37du-center-8800" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-8800" dir=in action=allow protocol=TCP localport=8800
|
||||
|
||||
echo [OK] Firewall rule created: TCP 8800 open.
|
||||
pause
|
||||
@@ -0,0 +1,23 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center SMB firewall script
|
||||
rem opens SMB/NetBIOS ports so the deploy machine can reach
|
||||
rem the \\...\code share. Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
netsh advfirewall firewall delete rule name="37du-center-smb445" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-smb445" dir=in action=allow protocol=TCP localport=445
|
||||
netsh advfirewall firewall add rule name="37du-center-smb445udp" dir=in action=allow protocol=UDP localport=445
|
||||
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb139" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb139" dir=in action=allow protocol=TCP localport=139
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb137" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb137" dir=in action=allow protocol=UDP localport=137
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb138" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb138" dir=in action=allow protocol=UDP localport=138
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb135" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb135" dir=in action=allow protocol=UDP localport=135
|
||||
|
||||
echo [OK] Firewall rules created: SMB/NetBIOS open.
|
||||
pause
|
||||
Generated
+194
@@ -8,6 +8,8 @@
|
||||
"name": "37du-controlplane-frontend",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -61,6 +63,24 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@ctrl/tinycolor": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@ctrl/tinycolor/-/tinycolor-4.2.1.tgz",
|
||||
"integrity": "sha512-Vh5uy9Y1JBMId6J1f68TMXnZrTCvNdo9Fu2k0d1YnJngR+sM5kWTKl441c/3TFs+cG0NWOjRWgQ/iaWhbYx+7A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@element-plus/icons-vue": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@element-plus/icons-vue/-/icons-vue-2.3.2.tgz",
|
||||
"integrity": "sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"vue": "^3.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
@@ -503,6 +523,31 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/core": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
|
||||
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/dom": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
|
||||
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/core": "^1.8.0",
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/utils": {
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
|
||||
@@ -529,6 +574,17 @@
|
||||
"node": "^22.20 || ^24.12 || >=25"
|
||||
}
|
||||
},
|
||||
"node_modules/@popperjs/core": {
|
||||
"name": "@sxzz/popperjs-es",
|
||||
"version": "2.11.8",
|
||||
"resolved": "https://registry.npmjs.org/@sxzz/popperjs-es/-/popperjs-es-2.11.8.tgz",
|
||||
"integrity": "sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/popperjs"
|
||||
}
|
||||
},
|
||||
"node_modules/@rollup/rollup-android-arm-eabi": {
|
||||
"version": "4.63.1",
|
||||
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz",
|
||||
@@ -925,6 +981,27 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/lodash": {
|
||||
"version": "4.17.25",
|
||||
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz",
|
||||
"integrity": "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/lodash-es": {
|
||||
"version": "4.17.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz",
|
||||
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/lodash": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/web-bluetooth": {
|
||||
"version": "0.0.21",
|
||||
"resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
|
||||
"integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@vitejs/plugin-vue": {
|
||||
"version": "5.2.4",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz",
|
||||
@@ -1037,12 +1114,88 @@
|
||||
"integrity": "sha512-2rPxex1jQf4jvl9MOHl6YaXCPcrNqz/FstMOEh3QWY+/OME9nQTvl9WYeCwhW7AFjaR0SnngZGlp/wkR6rkI6g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@vueuse/core": {
|
||||
"version": "14.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.4.0.tgz",
|
||||
"integrity": "sha512-X4WHz1HlCzCBoYXesUkifzzWBAcZgXG8Fi5iNPQg/epdzOB3gu8Fawj3hvuwYR1nGcXGnvxwYYcUC/71++svtQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/web-bluetooth": "^0.0.21",
|
||||
"@vueuse/metadata": "14.4.0",
|
||||
"@vueuse/shared": "14.4.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vueuse/metadata": {
|
||||
"version": "14.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.4.0.tgz",
|
||||
"integrity": "sha512-swx/255R6JyHZFJhx845iz5CRWDZdCfvkZOpACWc5+c5WHcG24mv8gUT1WIdFQaHt6dq79rvILd9QnCWiyVm9g==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/@vueuse/shared": {
|
||||
"version": "14.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.4.0.tgz",
|
||||
"integrity": "sha512-JRgY90Sz8DDtPMsaDflvPMp9xYk69JZAmbuDvAquUVXKr2gEjqtzGNTTthLfckH0BzBqvnu31gb4a8TGLRe79g==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/async-validator": {
|
||||
"version": "4.2.5",
|
||||
"resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz",
|
||||
"integrity": "sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dayjs": {
|
||||
"version": "1.11.23",
|
||||
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
|
||||
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/element-plus": {
|
||||
"version": "2.14.5",
|
||||
"resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.14.5.tgz",
|
||||
"integrity": "sha512-bghYy/S+qg87enHPXELirhEdDqsVAUGcGpbGIeG8dz0kwpIkGz7gYsifulBshXX74iRtHib85XWQj0uSH2A1Yg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@ctrl/tinycolor": "^4.2.0",
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"@floating-ui/dom": "^1.8.0",
|
||||
"@popperjs/core": "npm:@sxzz/popperjs-es@^2.11.8",
|
||||
"@types/lodash": "^4.17.24",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@vueuse/core": "14.4.0",
|
||||
"async-validator": "^4.2.5",
|
||||
"dayjs": "^1.11.20",
|
||||
"lodash": "^4.18.1",
|
||||
"lodash-es": "^4.18.1",
|
||||
"lodash-unified": "^1.0.3",
|
||||
"memoize-one": "^6.0.0",
|
||||
"normalize-wheel-es": "^1.2.0",
|
||||
"vue-component-type-helpers": "^3.3.9"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.3.7"
|
||||
}
|
||||
},
|
||||
"node_modules/entities": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
|
||||
@@ -1136,6 +1289,29 @@
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.18.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash-es": {
|
||||
"version": "4.18.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",
|
||||
"integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash-unified": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash-unified/-/lodash-unified-1.0.3.tgz",
|
||||
"integrity": "sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/lodash-es": "*",
|
||||
"lodash": "*",
|
||||
"lodash-es": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.21",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||
@@ -1145,6 +1321,12 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/memoize-one": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz",
|
||||
"integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
@@ -1163,6 +1345,12 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/normalize-wheel-es": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/normalize-wheel-es/-/normalize-wheel-es-1.2.0.tgz",
|
||||
"integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -1377,6 +1565,12 @@
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vue-component-type-helpers": {
|
||||
"version": "3.3.11",
|
||||
"resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz",
|
||||
"integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -18,4 +20,4 @@
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="__app" v-else>
|
||||
<header class="topbar panel">
|
||||
<el-container class="console" v-else>
|
||||
<el-header class="topbar" height="56px">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
@@ -10,60 +10,122 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="acct">
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
|
||||
<button class="btn" @click="logout">登出</button>
|
||||
</div>
|
||||
</header>
|
||||
<el-dropdown trigger="click" @command="onCommand">
|
||||
<span class="acct">
|
||||
<el-icon><UserFilled /></el-icon>
|
||||
{{ store.current }}
|
||||
<el-tag v-if="store.isAdmin" size="small" type="primary" effect="light" round>管理员</el-tag>
|
||||
<el-icon class="caret"><ArrowDown /></el-icon>
|
||||
</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="pwd">修改密码</el-dropdown-item>
|
||||
<el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</el-header>
|
||||
|
||||
<main class="page panel">
|
||||
<ManagementView />
|
||||
</main>
|
||||
</div>
|
||||
<el-container class="body">
|
||||
<el-aside width="180px" class="aside">
|
||||
<el-menu :default-active="route" router class="menu" @select="onMenu">
|
||||
<el-menu-item index="#/overview">
|
||||
<el-icon><Odometer /></el-icon><span>概览</span>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="#/plugins">
|
||||
<el-icon><Box /></el-icon><span>插件管理</span>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="#/accounts">
|
||||
<el-icon><User /></el-icon><span>账号管理</span>
|
||||
</el-menu-item>
|
||||
<el-menu-item index="#/grants">
|
||||
<el-icon><Key /></el-icon><span>权限授权</span>
|
||||
</el-menu-item>
|
||||
</el-menu>
|
||||
</el-aside>
|
||||
<el-main class="main">
|
||||
<component :is="viewComp" :key="route" />
|
||||
</el-main>
|
||||
</el-container>
|
||||
</el-container>
|
||||
|
||||
<PasswordDialog v-model="pwdOpen" />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted } from 'vue'
|
||||
import ManagementView from './components/ManagementView.vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { UserFilled, ArrowDown, Odometer, Box, User, Key } from '@element-plus/icons-vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import { store } from './store'
|
||||
import PasswordDialog from './components/PasswordDialog.vue'
|
||||
import OverviewView from './views/OverviewView.vue'
|
||||
import PluginManageView from './views/PluginManageView.vue'
|
||||
import AccountManageView from './views/AccountManageView.vue'
|
||||
import GrantManageView from './views/GrantManageView.vue'
|
||||
import { store, clearSession } from './store'
|
||||
import { adminMe } from './api'
|
||||
|
||||
function onLogin() {
|
||||
// store 已在 LoginPage 写入
|
||||
// 轻量 hash 路由:StaticFiles(html=True) 下刷新安全,零后端改动
|
||||
const route = ref(location.hash && VIEWS[location.hash] ? location.hash : '#/overview')
|
||||
const VIEWS = {
|
||||
'#/overview': OverviewView,
|
||||
'#/plugins': PluginManageView,
|
||||
'#/accounts': AccountManageView,
|
||||
'#/grants': GrantManageView,
|
||||
}
|
||||
function logout() {
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
window.addEventListener('hashchange', () => {
|
||||
if (VIEWS[location.hash]) route.value = location.hash
|
||||
})
|
||||
const viewComp = computed(() => VIEWS[route.value] || OverviewView)
|
||||
|
||||
function onMenu(index) {
|
||||
location.hash = index
|
||||
route.value = index
|
||||
}
|
||||
|
||||
const pwdOpen = ref(false)
|
||||
function onCommand(cmd) {
|
||||
if (cmd === 'pwd') pwdOpen.value = true
|
||||
else if (cmd === 'logout') {
|
||||
clearSession()
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
}
|
||||
|
||||
function onLogin() {
|
||||
route.value = '#/overview'
|
||||
location.hash = '#/overview'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 已本地标记登录时,校验仍为管理员(控制面重启/权限变更后回登录页)
|
||||
// 已本地标记登录时,校验登录票据仍有效且为管理员(票据过期/权限变更后回登录页)
|
||||
if (!store.current) return
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account || !me.is_admin) { store.current = ''; store.isAdmin = false }
|
||||
if (!me.account || !me.is_admin) clearSession()
|
||||
else store.isAdmin = true
|
||||
} catch (_) { /* 后端 down:保持本地态 */ }
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.topbar { display: flex; align-items: center; gap: 16px; padding: 12px 18px; flex-shrink: 0; }
|
||||
.console { height: 100vh; background: #f5f7fa; }
|
||||
.topbar { display: flex; align-items: center; gap: 16px; background: #fff;
|
||||
border-bottom: 1px solid var(--el-border-color-light); }
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo { width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff; font-size: 14px; font-weight: 800;
|
||||
box-shadow: 0 4px 12px -3px rgba(59,108,255,.6); }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.brand-meta strong { font-size: 14px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
.logo { width: 34px; height: 34px; border-radius: 9px; display: grid; place-items: center;
|
||||
background: var(--el-color-primary); color: #fff; font-size: 13px; font-weight: 800; }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 14px; color: var(--el-text-color-primary); }
|
||||
.brand-meta span { font-size: 11px; color: var(--el-text-color-secondary); }
|
||||
.spacer { flex: 1; }
|
||||
.acct { display: flex; align-items: center; gap: 8px; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
.acct-tag { font-style: normal; font-size: 10px; color: var(--primary);
|
||||
border: 1px solid var(--primary-weak); background: var(--primary-weak); border-radius: 999px; padding: 1px 7px; }
|
||||
.btn { padding: 6px 14px; font-size: 12.5px; }
|
||||
.page { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; margin-top: 14px; }
|
||||
</style>
|
||||
.acct { display: inline-flex; align-items: center; gap: 6px; font-size: 13px;
|
||||
color: var(--el-text-color-primary); cursor: pointer; outline: none; }
|
||||
.acct .caret { font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
|
||||
.body { min-height: 0; }
|
||||
.aside { background: #fff; border-right: 1px solid var(--el-border-color-light); padding-top: 10px; }
|
||||
.menu { border-right: none; }
|
||||
.menu .el-menu-item { height: 44px; }
|
||||
.main { padding: 18px 20px; overflow: auto; }
|
||||
</style>
|
||||
|
||||
@@ -1,91 +1,88 @@
|
||||
// 与 FastAPI 后端交互,控制面前端直连 /api/*
|
||||
import { store } from './store.js'
|
||||
|
||||
async function j(url, opts) {
|
||||
async function req(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
try { msg = (await res.json()).detail || msg } catch (_) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
async function jj(url, opts) {
|
||||
const r = await fetch(url, opts)
|
||||
if (!r.ok) {
|
||||
let m = `HTTP ${r.status}`
|
||||
try { m = (await r.json()).detail || m } catch (_) {}
|
||||
throw new Error(m)
|
||||
}
|
||||
return r.json()
|
||||
}
|
||||
|
||||
// 管理接口为无状态鉴权:控制面直接读取 X-Admin-User 头注入当前登录账号
|
||||
// 管理接口无状态鉴权:携带登录后签发的签名票据(X-Admin-Token),后端验票解得当前账号
|
||||
function adminHeaders(extra = {}) {
|
||||
return { 'X-Admin-User': store.current || '', ...extra }
|
||||
return { 'X-Admin-Token': store.token || '', ...extra }
|
||||
}
|
||||
|
||||
export async function adminLogin(account, password) {
|
||||
return jj('/api/admin/auth', {
|
||||
return req('/api/admin/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ account, password })
|
||||
})
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return jj('/api/admin/password', {
|
||||
return req('/api/admin/password', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me', { headers: adminHeaders() })
|
||||
return req('/api/admin/me', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminOverview() {
|
||||
return j('/api/admin/overview', { headers: adminHeaders() })
|
||||
return req('/api/admin/overview', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminGrant(body) {
|
||||
return jj('/api/admin/account_plugins', {
|
||||
return req('/api/admin/account_plugins', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminPlatformGrant(body) {
|
||||
return req('/api/admin/account_platforms', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccounts() {
|
||||
return j('/api/admin/accounts', { headers: adminHeaders() })
|
||||
return req('/api/admin/accounts', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminAccountCreate(body) {
|
||||
return jj('/api/admin/account', {
|
||||
return req('/api/admin/account', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccountUpdate(body) {
|
||||
return jj('/api/admin/account/update', {
|
||||
return req('/api/admin/account/update', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccountReset(body) {
|
||||
return jj('/api/admin/account/reset_pwd', {
|
||||
return req('/api/admin/account/reset_pwd', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccountDelete(body) {
|
||||
return jj('/api/admin/account/delete', {
|
||||
return req('/api/admin/account/delete', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminPluginDelete(body) {
|
||||
return jj('/api/admin/plugin/delete', {
|
||||
return req('/api/admin/plugin/delete', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
@@ -95,5 +92,5 @@ export async function adminUpload(pluginId, name, version, file) {
|
||||
const fd = new FormData()
|
||||
fd.append('upload', file)
|
||||
const qs = new URLSearchParams({ plugin_id: pluginId, name, version })
|
||||
return jj('/api/admin/pkg?' + qs.toString(), { method: 'POST', headers: adminHeaders(), body: fd })
|
||||
return req('/api/admin/pkg?' + qs.toString(), { method: 'POST', headers: adminHeaders(), body: fd })
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="login-wrap">
|
||||
<div class="card panel">
|
||||
<el-card class="card" shadow="always">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
@@ -8,20 +8,26 @@
|
||||
<span>中心机统一账户登录</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="fields">
|
||||
<input v-model="account" class="input" placeholder="账号" @keyup.enter="doLogin">
|
||||
<input v-model="password" class="input" type="password" placeholder="密码" @keyup.enter="doLogin">
|
||||
</div>
|
||||
<p v-if="err" class="err">{{ err }}</p>
|
||||
<button class="btn primary" :disabled="busy" @click="doLogin">
|
||||
{{ busy ? '校验中…' : '登录' }}
|
||||
</button>
|
||||
</div>
|
||||
<el-form label-position="top" @keyup.enter="doLogin">
|
||||
<el-form-item label="账号">
|
||||
<el-input v-model="account" placeholder="请输入账号" size="large" :prefix-icon="User" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码">
|
||||
<el-input v-model="password" type="password" placeholder="请输入密码" size="large"
|
||||
:prefix-icon="Lock" show-password />
|
||||
</el-form-item>
|
||||
<el-button type="primary" size="large" class="login-btn" :loading="busy" @click="doLogin">
|
||||
{{ busy ? '校验中…' : '登 录' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { User, Lock } from '@element-plus/icons-vue'
|
||||
import { adminLogin } from '../api'
|
||||
import { store } from '../store.js'
|
||||
|
||||
@@ -31,24 +37,24 @@ const emit = defineEmits(['ok'])
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const err = ref('')
|
||||
|
||||
async function doLogin() {
|
||||
if (busy.value) return
|
||||
const acct = account.value.trim()
|
||||
if (!acct || !password.value) { err.value = '请输入账号与密码'; return }
|
||||
if (!acct || !password.value) { ElMessage.warning('请输入账号与密码'); return }
|
||||
busy.value = true
|
||||
err.value = ''
|
||||
try {
|
||||
const r = await adminLogin(acct, password.value)
|
||||
if (!r.ok) throw new Error('登录失败')
|
||||
if (!r.is_admin) { throw new Error('该账号无管理权限') }
|
||||
store.current = acct
|
||||
store.token = r.token || ''
|
||||
store.isAdmin = true
|
||||
try { localStorage.setItem('cp_account', acct) } catch (_) {}
|
||||
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) {}
|
||||
ElMessage.success(`欢迎,${acct}`)
|
||||
emit('ok', r)
|
||||
} catch (e) {
|
||||
err.value = e.message || String(e)
|
||||
ElMessage.error(e.message || String(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
@@ -56,17 +62,14 @@ async function doLogin() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login-wrap { flex: 1; display: grid; place-items: center; }
|
||||
.card { width: 340px; padding: 28px 26px; display: flex; flex-direction: column;
|
||||
gap: 16px; box-shadow: var(--shadow-md); }
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo { width: 40px; height: 40px; border-radius: 11px; display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff; font-size: 15px; font-weight: 800;
|
||||
box-shadow: 0 4px 14px -3px rgba(59,108,255,.6); }
|
||||
.login-wrap { height: 100vh; display: grid; place-items: center;
|
||||
background: linear-gradient(160deg, #eef2fb 0%, #f7f9fd 60%, #eaf1f8 100%); }
|
||||
.card { width: 360px; }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-bottom: 22px; }
|
||||
.logo { width: 42px; height: 42px; border-radius: 11px; display: grid; place-items: center;
|
||||
background: var(--el-color-primary); color: #fff; font-size: 15px; font-weight: 800; }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.3; }
|
||||
.brand-meta strong { font-size: 14px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
.fields { display: flex; flex-direction: column; gap: 10px; }
|
||||
.input { width: 100%; }
|
||||
.err { color: var(--err); font-size: 12px; margin: 0; }
|
||||
</style>
|
||||
.brand-meta strong { font-size: 15px; color: var(--el-text-color-primary); }
|
||||
.brand-meta span { font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.login-btn { width: 100%; margin-top: 4px; }
|
||||
</style>
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
<template>
|
||||
<div class="mgmt">
|
||||
<div class="m-head">
|
||||
<div>
|
||||
<h3>控制面管理</h3>
|
||||
<p class="m-sub">中心机 · 插件分发与账号权限 · 当前账号 {{ store.current }}</p>
|
||||
</div>
|
||||
<button class="btn primary" @click="load" :disabled="busy">{{ busy ? '读取中…' : '刷新' }}</button>
|
||||
</div>
|
||||
|
||||
<div class="toast-note" v-if="msg">{{ msg }}</div>
|
||||
|
||||
<section>
|
||||
<h4>上传插件包</h4>
|
||||
<div class="row">
|
||||
<input v-model="pid" placeholder="插件 ID,如 seal_check">
|
||||
<input v-model="pname" placeholder="插件名称">
|
||||
<input v-model="pver" placeholder="版本,如 1.1.0" style="width:110px">
|
||||
<input type="file" @change="e => pfile = e.target.files[0]">
|
||||
<button class="btn primary" @click="upload">上传发布</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>插件列表</h4>
|
||||
<table>
|
||||
<thead><tr><th>插件</th><th>名称</th><th>最新版</th><th>版本</th><th>授权账号</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-if="!data.plugins.length"><td colspan="6" class="muted">暂无插件,请先上传</td></tr>
|
||||
<tr v-for="p in data.plugins" :key="p.id">
|
||||
<td><b>{{ p.id }}</b></td>
|
||||
<td>{{ p.name }}</td>
|
||||
<td>{{ p.latest_version }}</td>
|
||||
<td class="muted">{{ (p.versions||[]).map(v=>v.version).join(' · ') || '—' }}</td>
|
||||
<td>{{ (p.accounts||[]).join('、') || '—' }}</td>
|
||||
<td><button class="link danger" @click="delPlugin(p.id)">删除</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>账号管理</h4>
|
||||
<div class="row" style="margin-bottom:14px">
|
||||
<input v-model="naAcct" placeholder="账号">
|
||||
<input v-model="naPwd" type="password" placeholder="初始密码">
|
||||
<input v-model="naDept" placeholder="部门" style="width:120px">
|
||||
<label class="ck"><input type="checkbox" v-model="naAdmin">管理员</label>
|
||||
<button class="btn primary" @click="createAccount">建号</button>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr><th>账号</th><th>部门</th><th>管理员</th><th>已授权插件</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="a in data.accounts" :key="a.account">
|
||||
<td><b>{{ a.account }}</b></td>
|
||||
<td>
|
||||
<input class="ipt-sm" :value="a.dept"
|
||||
@change="e => setDept(a.account, e.target.value)"
|
||||
:disabled="a.account===current">
|
||||
</td>
|
||||
<td>
|
||||
<button class="link" :class="{ 'on': a.is_admin, 'danger': !a.is_admin && a.account!==current }"
|
||||
@click="a.account!==current ? toggleAdmin(a) : null">
|
||||
{{ a.is_admin ? '是' : '否' }}
|
||||
</button>
|
||||
</td>
|
||||
<td class="muted">{{ (a.plugins||[]).join('、') || '—' }}</td>
|
||||
<td>
|
||||
<button class="link" @click="resetPwd(a.account)">重置密码</button>
|
||||
<button class="link danger" v-if="a.account!==current" @click="delAccount(a.account)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="row" style="margin-top:16px">
|
||||
<input v-model="grantAcc" placeholder="授权账号,如 alice">
|
||||
<button class="btn" @click="loadGrant">载入</button>
|
||||
<span v-if="grantAcc" class="muted">{{ grantAcc }} · 已授权 {{ checked.size }} 个</span>
|
||||
</div>
|
||||
<div class="checks" v-if="grantAcc && data.plugins.length">
|
||||
<label v-for="p in data.plugins" :key="p.id" class="ck">
|
||||
<input type="checkbox" :value="p.id" v-model="checked">
|
||||
{{ p.id }} · {{ p.name }}
|
||||
</label>
|
||||
</div>
|
||||
<button v-if="grantAcc" class="btn primary" style="margin-top:12px" @click="saveGrant">保存授权</button>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>修改密码</h4>
|
||||
<div class="row">
|
||||
<input v-model="oldPwd" type="password" placeholder="原密码">
|
||||
<input v-model="newPwd" type="password" placeholder="新密码">
|
||||
<button class="btn primary" @click="changePwd">保存新密码</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { store } from '../store.js'
|
||||
import { adminOverview, adminUpload, adminGrant, adminPassword,
|
||||
adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminPluginDelete } from '../api.js'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const data = ref({ plugins: [], accounts: [], admins: [] })
|
||||
const busy = ref(false)
|
||||
const msgRef = ref('')
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
const grantAcc = ref(''); const checked = ref(new Set())
|
||||
const naAcct = ref(''); const naPwd = ref(''); const naDept = ref(''); const naAdmin = ref(false)
|
||||
const oldPwd = ref(''); const newPwd = ref('')
|
||||
let grantHeld = new Set()
|
||||
|
||||
const msg = computed(() => msgRef.value)
|
||||
function toast(msg) {
|
||||
msgRef.value = msg
|
||||
clearTimeout(msgRef._h)
|
||||
msgRef._h = setTimeout(() => (msgRef.value = ''), 2600)
|
||||
}
|
||||
async function changePwd() {
|
||||
if (!oldPwd.value || !newPwd.value) return toast('请输入原密码与新密码')
|
||||
try {
|
||||
await adminPassword({ account: store.current, old_password: oldPwd.value, new_password: newPwd.value })
|
||||
oldPwd.value = ''; newPwd.value = ''
|
||||
toast('密码已修改')
|
||||
} catch (e) { toast('修改失败:' + (e.message || e)) }
|
||||
}
|
||||
async function load() {
|
||||
busy.value = true
|
||||
try { data.value = await adminOverview() } catch (e) { toast('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
async function upload() {
|
||||
if (!pid.value || !pver.value || !pfile.value) return toast('请填写 ID / 版本并选择包文件')
|
||||
try {
|
||||
await adminUpload(pid.value, pname.value || pid.value, pver.value, pfile.value)
|
||||
toast(`已发布 ${pid.value}@${pver.value}`)
|
||||
await load()
|
||||
} catch (e) { toast('上传失败:' + (e.message || e)) }
|
||||
}
|
||||
function loadGrant() {
|
||||
const acc = grantAcc.value.trim(); if (!acc) return toast('请输入账号')
|
||||
const a = data.value.accounts.find(x => x.account === acc)
|
||||
grantHeld = new Set(a ? a.plugins : [])
|
||||
checked.value = new Set(grantHeld)
|
||||
}
|
||||
async function saveGrant() {
|
||||
const acc = grantAcc.value.trim(); if (!acc) return
|
||||
const want = new Set(checked.value)
|
||||
let n = 0
|
||||
for (const pids of new Set([...want, ...grantHeld])) {
|
||||
const g = want.has(pids)
|
||||
if (g !== grantHeld.has(pids)) {
|
||||
try { await adminGrant({ account: acc, plugin_id: pids, granted: g }); n++ } catch (e) { toast((e.message||e)); }
|
||||
}
|
||||
}
|
||||
grantHeld = want
|
||||
await load()
|
||||
toast(n ? `已更新 ${n} 项` : '无需变更')
|
||||
}
|
||||
async function createAccount() {
|
||||
const acct = naAcct.value.trim(); const pwd = naPwd.value
|
||||
if (!acct || !pwd) return toast('账号与初始密码必填')
|
||||
try {
|
||||
await adminAccountCreate({ account: acct, password: pwd, dept: naDept.value.trim(), is_admin: naAdmin.value })
|
||||
toast(`已建号 ${acct}`); naAcct.value=''; naPwd.value=''; naDept.value=''; naAdmin.value=false
|
||||
await load()
|
||||
} catch (e) { toast('建号失败:' + (e.message || e)) }
|
||||
}
|
||||
async function setDept(acct, dept) {
|
||||
try { await adminAccountUpdate({ account: acct, dept }); toast(`已更新 ${acct} 部门`) }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function toggleAdmin(a) {
|
||||
try { await adminAccountUpdate({ account: a.account, is_admin: !a.is_admin }); await load() }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function resetPwd(acct) {
|
||||
if (acct === current.value) return toast('请用「修改密码」改自己的密码')
|
||||
const newp = prompt(`重置 ${acct} 的新密码:`)
|
||||
if (!newp) return
|
||||
try { await adminAccountReset({ account: acct, new_password: newp }); toast(`已重置 ${acct} 密码`) }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function delAccount(acct) {
|
||||
if (!confirm(`确认删除账号 ${acct}?其插件授权将一并清除`)) return
|
||||
try { await adminAccountDelete({ account: acct }); toast(`已删除 ${acct}`); await load() }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function delPlugin(pid) {
|
||||
if (!confirm(`确认删除插件 ${pid}?版本与授权将一并清除`)) return
|
||||
try { await adminPluginDelete({ plugin_id: pid }); toast(`已删除插件 ${pid}`); await load() }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
load()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mgmt { display: flex; flex-direction: column; gap: 26px; }
|
||||
.m-head { display: flex; justify-content: space-between; align-items: flex-start; }
|
||||
h3 { font-size: 16px; margin: 0; }
|
||||
p { margin: 0; }
|
||||
h4 { font-size: 13px; font-weight: 600; border-bottom: 1px solid var(--border); padding-bottom: 8px; margin-bottom: 14px; }
|
||||
.m-sub, .muted { color: var(--text-faint); font-size: 12px; }
|
||||
.toast-note { color: #fff; background: #3a3f4a; font-size: 12px; padding: 7px 12px; border-radius: 6px; margin-top: 10px; width: fit-content; }
|
||||
.row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
input, button { font: inherit; }
|
||||
input { border: 1px solid var(--border-strong); border-radius: var(--radius-sm); padding: 6px 10px; background: var(--surface); color: var(--text); }
|
||||
input:focus { outline: none; border-color: var(--primary); }
|
||||
button { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 6px 14px; cursor: pointer; color: var(--text-sub); }
|
||||
button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); font-size: 13px; }
|
||||
th { color: var(--text-faint); font-weight: 600; font-size: 12px; }
|
||||
.checks { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-top: 10px; }
|
||||
.ck { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; }
|
||||
.ck input[type=checkbox] { accent-color: var(--primary); }
|
||||
.link { border: none; background: none; color: var(--primary); padding: 0; margin-left: 4px; font-size: 12px; cursor: pointer; }
|
||||
.link.danger { color: #e5484d; }
|
||||
.link.on { color: var(--primary); font-weight: 600; }
|
||||
.ipt-sm { width: 90px; padding: 4px 6px; font-size: 12px; }
|
||||
</style>
|
||||
@@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<el-dialog v-model="visible" title="修改密码" width="380px" :close-on-click-modal="false" @closed="reset">
|
||||
<el-alert v-if="store.current" :title="`当前账号:${store.current}`" type="info" :closable="false" class="acct-tip" />
|
||||
<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" show-password placeholder="请输入原密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="submit">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
|
||||
const visible = defineModel({ type: Boolean, default: false })
|
||||
const formRef = ref()
|
||||
const busy = ref(false)
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
|
||||
const rules = {
|
||||
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码', trigger: 'blur' },
|
||||
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
|
||||
{ validator: (_, v, cb) => (v && v === form.oldPwd ? cb(new Error('新密码不能与原密码相同')) : cb()), trigger: 'blur' },
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
|
||||
{ validator: (_, v, cb) => (v !== form.newPwd ? cb(new Error('两次输入的密码不一致')) : cb()), trigger: 'blur' },
|
||||
],
|
||||
}
|
||||
|
||||
function reset() {
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
busy.value = true
|
||||
try {
|
||||
await adminPassword({ account: store.current, old_password: form.oldPwd, new_password: form.newPwd })
|
||||
ElMessage.success('密码已修改,下次登录请使用新密码')
|
||||
visible.value = false
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.acct-tip { margin-bottom: 14px; }
|
||||
</style>
|
||||
@@ -1,5 +1,8 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import 'element-plus/dist/index.css'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
|
||||
createApp(App).mount('#app')
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
|
||||
@@ -1,9 +1,40 @@
|
||||
import { reactive } from 'vue'
|
||||
import { reactive, ref } from 'vue'
|
||||
import { adminOverview } from './api'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '37du 内网插件控制面',
|
||||
isAdmin: false,
|
||||
current: (() => {
|
||||
try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' }
|
||||
})(),
|
||||
})
|
||||
current: _get('cp_account'),
|
||||
token: _get('cp_token'),
|
||||
})
|
||||
|
||||
// 概览数据缓存:各管理页共用一份 adminOverview 结果,避免切页重复拉取
|
||||
export const overview = ref(null)
|
||||
export const overviewBusy = ref(false)
|
||||
|
||||
export async function loadOverview(force = false) {
|
||||
if (overview.value && !force) return overview.value
|
||||
overviewBusy.value = true
|
||||
try {
|
||||
overview.value = await adminOverview()
|
||||
return overview.value
|
||||
} finally {
|
||||
overviewBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
export function resetOverview() {
|
||||
overview.value = null
|
||||
}
|
||||
|
||||
function _get(key) {
|
||||
try { return localStorage.getItem(key) || '' } catch (_) { return '' }
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
store.current = ''
|
||||
store.token = ''
|
||||
store.isAdmin = false
|
||||
resetOverview()
|
||||
try { localStorage.removeItem('cp_account'); localStorage.removeItem('cp_token') } catch (_) {}
|
||||
}
|
||||
@@ -1,111 +1,16 @@
|
||||
/* ============ 37du 内网插件控制面 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
}
|
||||
|
||||
/* ============ 37du 内网插件控制面 全局基础样式(组件样式由 Element Plus 提供) ============ */
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
color: #1f2633;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #f5f7fa;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
.fade-leave-to { opacity: 0; }
|
||||
@@ -0,0 +1,164 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h3>账号管理</h3>
|
||||
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||
</div>
|
||||
<div>
|
||||
<el-button :icon="Refresh" :loading="overviewBusy" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建账号</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-card shadow="never">
|
||||
<el-table :data="accounts" v-loading="overviewBusy" empty-text="暂无账号">
|
||||
<el-table-column prop="account" label="账号" min-width="120">
|
||||
<template #default="{ row }"><b>{{ row.account }}</b></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="部门" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<el-input v-if="row.account === editing" v-model="deptDraft" size="small" style="width: 120px"
|
||||
@keyup.enter="saveDept(row)" @blur="saveDept(row)" />
|
||||
<span v-else class="dept" @click="startEditDept(row)" title="点击编辑">
|
||||
{{ row.dept || '—' }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="管理员" width="100">
|
||||
<template #default="{ row }">
|
||||
<el-switch :model-value="!!row.is_admin" :disabled="row.account === current"
|
||||
@change="toggleAdmin(row)" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="已授权插件" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-for="p in row.plugins" :key="p" size="small" effect="plain" class="tag">{{ p }}</el-tag>
|
||||
<span v-if="!row.plugins?.length" class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="已授权平台" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-for="pf in row.platforms" :key="pf" size="small" type="success" effect="plain" class="tag">{{ pf }}</el-tag>
|
||||
<span v-if="!row.platforms?.length" class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" @click="resetPwd(row)">重置密码</el-button>
|
||||
<el-button link type="danger" :disabled="row.account === current" @click="delAccount(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
<el-dialog v-model="createOpen" title="新建账号" width="400px" @closed="resetCreate">
|
||||
<el-form ref="formRef" :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="初始密码" prop="password">
|
||||
<el-input v-model="form.password" type="password" show-password placeholder="至少 6 位" />
|
||||
</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>
|
||||
<el-button @click="createOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="creating" @click="createAccount">建号</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { Refresh, Plus } from '@element-plus/icons-vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete } from '../api'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
|
||||
const createOpen = ref(false)
|
||||
const creating = ref(false)
|
||||
const formRef = ref()
|
||||
const form = reactive({ account: '', password: '', dept: '', is_admin: false })
|
||||
const rules = {
|
||||
account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
|
||||
password: [
|
||||
{ required: true, message: '请输入初始密码', trigger: 'blur' },
|
||||
{ min: 6, message: '密码至少 6 位', trigger: 'blur' },
|
||||
],
|
||||
}
|
||||
function openCreate() { createOpen.value = true }
|
||||
function resetCreate() { form.account = form.password = form.dept = ''; form.is_admin = false; formRef.value?.clearValidate() }
|
||||
|
||||
// 部门行内编辑
|
||||
const editing = ref('')
|
||||
const deptDraft = ref('')
|
||||
function startEditDept(row) {
|
||||
if (row.account === current.value) return
|
||||
editing.value = row.account
|
||||
deptDraft.value = row.dept || ''
|
||||
}
|
||||
async function saveDept(row) {
|
||||
if (editing.value !== row.account) return
|
||||
editing.value = ''
|
||||
const dept = deptDraft.value.trim()
|
||||
if (dept === (row.dept || '')) return
|
||||
try { await adminAccountUpdate({ account: row.account, dept }); ElMessage.success(`已更新 ${row.account} 部门`) }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
async function toggleAdmin(row) {
|
||||
try { await adminAccountUpdate({ account: row.account, is_admin: !row.is_admin }); await refresh() }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
async function resetPwd(row) {
|
||||
let newp
|
||||
try {
|
||||
({ value: newp } = await ElMessageBox.prompt(`为账号 ${row.account} 设置新密码(至少 6 位)`, '重置密码', {
|
||||
inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
}))
|
||||
} catch (_) { return }
|
||||
try { await adminAccountReset({ account: row.account, new_password: newp }); ElMessage.success(`已重置 ${row.account} 密码`) }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
async function delAccount(row) {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除账号 ${row.account}?其插件授权将一并清除`, '删除账号', { type: 'warning' })
|
||||
} catch (_) { return }
|
||||
try { await adminAccountDelete({ account: row.account }); ElMessage.success(`已删除 ${row.account}`); await refresh() }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { ElMessage.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function createAccount() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
creating.value = true
|
||||
try {
|
||||
await adminAccountCreate({ ...form, account: form.account.trim() })
|
||||
ElMessage.success(`已建号 ${form.account.trim()}`)
|
||||
createOpen.value = false
|
||||
await refresh()
|
||||
} catch (e) { ElMessage.error('建号失败:' + (e.message || e)) }
|
||||
finally { creating.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 14px; }
|
||||
.page-head h3 { margin: 0 0 4px; font-size: 17px; }
|
||||
.page-head p { margin: 0; font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.dept { cursor: pointer; }
|
||||
.dept:hover { color: var(--el-color-primary); }
|
||||
.tag { margin-right: 5px; }
|
||||
.dim { color: var(--el-text-color-placeholder); }
|
||||
</style>
|
||||
@@ -0,0 +1,137 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h3>权限授权</h3>
|
||||
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||
</div>
|
||||
<el-button :icon="Refresh" :loading="overviewBusy" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<el-card shadow="never" class="block">
|
||||
<el-form inline>
|
||||
<el-form-item label="选择账号">
|
||||
<el-select v-model="account" placeholder="选择账号…" style="width: 240px" filterable>
|
||||
<el-option v-for="a in accounts" :key="a.account" :value="a.account"
|
||||
:label="a.dept ? `${a.account} · ${a.dept}` : a.account" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="account">
|
||||
<el-text type="info" size="small">
|
||||
{{ account }} · 已授权 {{ checked.length }} 个插件 / {{ platChecked.length }} 个平台
|
||||
</el-text>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<template v-if="account">
|
||||
<el-card shadow="never" class="block">
|
||||
<template #header>
|
||||
<div class="card-head"><b>插件授权</b>
|
||||
<el-button type="primary" size="small" :loading="saving" @click="saveGrant">保存插件授权</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<el-checkbox-group v-model="checked" v-if="plugins.length">
|
||||
<el-checkbox v-for="p in plugins" :key="p.id" :value="p.id" class="ck">
|
||||
{{ p.id }}<span class="dim">({{ p.name }})</span>
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
<el-empty description="暂无插件,请先在「插件管理」上传" :image-size="60" v-else />
|
||||
</el-card>
|
||||
|
||||
<el-card shadow="never" class="block">
|
||||
<template #header>
|
||||
<div class="card-head"><b>平台授权</b>
|
||||
<el-button type="primary" size="small" :loading="savingPlat" @click="savePlat">保存平台授权</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<el-checkbox-group v-model="platChecked">
|
||||
<el-checkbox v-for="pf in PLATFORM_OPTS" :key="pf.id" :value="pf.id" class="ck">
|
||||
{{ pf.label }}<span class="dim">({{ pf.id }})</span>
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</el-card>
|
||||
</template>
|
||||
<el-empty v-else description="先在上方选择一个账号" :image-size="90" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminGrant, adminPlatformGrant } from '../api'
|
||||
|
||||
const PLATFORM_OPTS = [
|
||||
{ id: 'hr', label: 'HR 系统' },
|
||||
{ id: 'oa', label: 'OA 系统' },
|
||||
]
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
|
||||
const account = ref('')
|
||||
const checked = ref([])
|
||||
const platChecked = ref([])
|
||||
const saving = ref(false)
|
||||
const savingPlat = ref(false)
|
||||
let heldPlugins = new Set()
|
||||
let heldPlatforms = new Set()
|
||||
|
||||
// 选中账号即自动载入其现有授权
|
||||
watch(account, (acc) => {
|
||||
const a = accounts.value.find(x => x.account === acc)
|
||||
heldPlugins = new Set(a?.plugins || [])
|
||||
heldPlatforms = new Set(a?.platforms || [])
|
||||
checked.value = [...heldPlugins]
|
||||
platChecked.value = [...heldPlatforms]
|
||||
})
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { ElMessage.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function saveGrant() {
|
||||
const acc = account.value; if (!acc) return
|
||||
const want = new Set(checked.value)
|
||||
let n = 0
|
||||
saving.value = true
|
||||
for (const pid of new Set([...want, ...heldPlugins])) {
|
||||
const g = want.has(pid)
|
||||
if (g === heldPlugins.has(pid)) continue
|
||||
try { await adminGrant({ account: acc, plugin_id: pid, granted: g }); n++ }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
heldPlugins = want
|
||||
saving.value = false
|
||||
await refresh()
|
||||
ElMessage.success(n ? `已更新 ${n} 项插件授权` : '插件授权无需变更')
|
||||
}
|
||||
async function savePlat() {
|
||||
const acc = account.value; if (!acc) return
|
||||
const want = new Set(platChecked.value)
|
||||
let n = 0
|
||||
savingPlat.value = true
|
||||
for (const pf of new Set([...want, ...heldPlatforms])) {
|
||||
const g = want.has(pf)
|
||||
if (g === heldPlatforms.has(pf)) continue
|
||||
try { await adminPlatformGrant({ account: acc, platform_id: pf, granted: g }); n++ }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
heldPlatforms = want
|
||||
savingPlat.value = false
|
||||
await refresh()
|
||||
ElMessage.success(n ? `已更新 ${n} 项平台授权` : '平台授权无需变更')
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 14px; }
|
||||
.page-head h3 { margin: 0 0 4px; font-size: 17px; }
|
||||
.page-head p { margin: 0; font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.block { margin-bottom: 14px; }
|
||||
.card-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.ck { margin-right: 18px; }
|
||||
.dim { color: var(--el-text-color-secondary); font-size: 12px; margin-left: 2px; }
|
||||
</style>
|
||||
@@ -0,0 +1,67 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h3>概览</h3>
|
||||
<p>中心机 · 插件分发与账号权限 · 当前账号 {{ store.current }}</p>
|
||||
</div>
|
||||
<el-button :icon="Refresh" :loading="overviewBusy" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<el-row :gutter="14" v-if="ov">
|
||||
<el-col :span="5" v-for="s in stats" :key="s.label">
|
||||
<el-card shadow="never" class="stat-card">
|
||||
<div class="stat-num">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-skeleton :rows="2" animated v-else-if="overviewBusy" />
|
||||
|
||||
<el-card shadow="never" class="tip-card">
|
||||
<template #header><b>使用说明</b></template>
|
||||
<el-text type="info" size="small">
|
||||
「插件管理」上传与发布插件包(每插件保留最近 3 个版本);「账号管理」建号与账号维护;
|
||||
「权限授权」按账号勾选可用的插件与平台。部署机(webhost)仅在启动与手动刷新时拉取插件,
|
||||
授权变更后需在部署机刷新生效。
|
||||
</el-text>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
|
||||
const ov = computed(() => overview.value)
|
||||
const stats = computed(() => {
|
||||
const plugins = ov.value?.plugins || []
|
||||
return [
|
||||
{ label: '插件', value: plugins.length },
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0) },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length },
|
||||
{ label: '最近上传', value: latest() },
|
||||
]
|
||||
})
|
||||
function latest() {
|
||||
const all = (ov.value?.plugins || []).flatMap(p => p.versions || []).map(v => v.uploaded_at).filter(Boolean)
|
||||
return all.length ? all.sort().at(-1) : '—'
|
||||
}
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { ElMessage.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 14px; }
|
||||
.page-head h3 { margin: 0 0 4px; font-size: 17px; }
|
||||
.page-head p { margin: 0; font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.stat-card { text-align: left; }
|
||||
.stat-num { font-size: 24px; font-weight: 700; color: var(--el-text-color-primary); line-height: 1.2; }
|
||||
.stat-label { font-size: 12px; color: var(--el-text-color-secondary); margin-top: 4px; }
|
||||
.tip-card { margin-top: 14px; }
|
||||
</style>
|
||||
@@ -0,0 +1,112 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h3>插件管理</h3>
|
||||
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||
</div>
|
||||
<el-button :icon="Refresh" :loading="overviewBusy" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<el-card shadow="never" class="block">
|
||||
<template #header><b>上传插件包</b></template>
|
||||
<el-form inline>
|
||||
<el-form-item label="插件 ID">
|
||||
<el-input v-model="pid" placeholder="如 seal_check" style="width: 150px" />
|
||||
</el-form-item>
|
||||
<el-form-item label="名称">
|
||||
<el-input v-model="pname" placeholder="插件显示名" style="width: 150px" />
|
||||
</el-form-item>
|
||||
<el-form-item label="版本">
|
||||
<el-input v-model="pver" placeholder="如 1.1.0" style="width: 110px" />
|
||||
</el-form-item>
|
||||
<el-form-item label="包文件">
|
||||
<el-select v-if="pfile" :model-value="pfile.name" style="width: 240px" allow-create filterable>
|
||||
<el-option :label="pfile.name" :value="pfile.name" />
|
||||
</el-select>
|
||||
<el-upload :show-file-list="false" :auto-upload="false" accept=".zip"
|
||||
:on-change="f => (pfile = f.raw)">
|
||||
<el-button :icon="UploadFilled">{{ pfile ? '重新选择' : '选择 ZIP 包' }}</el-button>
|
||||
</el-upload>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="uploading" @click="upload">上传发布</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-text type="info" size="small">
|
||||
包根目录需含 plugin.json / main.py / requirements.txt,ZIP 完整性校验通过才会发布。
|
||||
</el-text>
|
||||
</el-card>
|
||||
|
||||
<el-card shadow="never" class="block">
|
||||
<template #header><b>插件列表</b></template>
|
||||
<el-table :data="plugins" v-loading="overviewBusy" empty-text="暂无插件,请先上传">
|
||||
<el-table-column prop="id" label="插件 ID" min-width="130">
|
||||
<template #default="{ row }"><b>{{ row.id }}</b></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="name" label="名称" min-width="140" />
|
||||
<el-table-column prop="latest_version" label="最新版" width="90" />
|
||||
<el-table-column label="版本历史" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<el-tag v-for="v in row.versions" :key="v.version" size="small"
|
||||
:type="v.version === row.latest_version ? 'primary' : 'info'"
|
||||
effect="plain" class="ver-tag">{{ v.version }}</el-tag>
|
||||
<span v-if="!row.versions?.length" class="dim">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="授权账号" min-width="140">
|
||||
<template #default="{ row }">{{ row.accounts?.join('、') || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="danger" @click="delPlugin(row)">删除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete } from '../api'
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
const uploading = ref(false)
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { ElMessage.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function upload() {
|
||||
if (!pid.value || !pver.value || !pfile.value) { ElMessage.warning('请填写插件 ID / 版本并选择 ZIP 包'); return }
|
||||
uploading.value = true
|
||||
try {
|
||||
await adminUpload(pid.value, pname.value || pid.value, pver.value, pfile.value)
|
||||
ElMessage.success(`已发布 ${pid.value}@${pver.value}`)
|
||||
pid.value = ''; pname.value = ''; pver.value = ''; pfile.value = null
|
||||
await refresh()
|
||||
} catch (e) { ElMessage.error('上传失败:' + (e.message || e)) }
|
||||
finally { uploading.value = false }
|
||||
}
|
||||
async function delPlugin(p) {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除插件 ${p.id}?其全部版本与授权将一并清除`, '删除插件', { type: 'warning' })
|
||||
} catch (_) { return }
|
||||
try { await adminPluginDelete({ plugin_id: p.id }); ElMessage.success(`已删除插件 ${p.id}`); await refresh() }
|
||||
catch (e) { ElMessage.error(e.message || e) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 14px; }
|
||||
.page-head h3 { margin: 0 0 4px; font-size: 17px; }
|
||||
.page-head p { margin: 0; font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.block { margin-bottom: 14px; }
|
||||
.ver-tag { margin-right: 5px; }
|
||||
.dim { color: var(--el-text-color-placeholder); }
|
||||
</style>
|
||||
@@ -0,0 +1,37 @@
|
||||
@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: same folder as this bat, or under dist\ subfolder
|
||||
if exist "%~dp037du-center.exe" (
|
||||
set "SRC=%~dp037du-center.exe"
|
||||
) else (
|
||||
set "SRC=%~dp0dist\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,16 @@
|
||||
@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
|
||||
@@ -0,0 +1,120 @@
|
||||
# ERP物料收发汇总表多时间区间导出与整合需求文档
|
||||
|
||||
**版本**:V1.0
|
||||
**日期**:2026-09-10
|
||||
**状态**:定稿版
|
||||
**需求名称**:ERP物料收发汇总表多时间区间导出与整合
|
||||
|
||||
---
|
||||
|
||||
## 一、功能需求内容
|
||||
|
||||
### 1. 系统登录
|
||||
访问 ERP 网页端新账套,账号、密码支持配置化读取,不硬编码在代码中。账号密码可更换。
|
||||
|
||||
### 2. 报表查询
|
||||
1. 进入报表模块,打开【物料收发汇总表】,选择默认查询方案。
|
||||
2. 库存组织固定选择:**重庆金七象供应链管理有限公司**。
|
||||
3. 支持仓库筛选,可单选或多选,指定仓库编码:
|
||||
- 0101010101
|
||||
- 0101010201
|
||||
- 0101020201
|
||||
- 0101030201
|
||||
- 0101040201
|
||||
4. 生成五组固定时间区间报表:
|
||||
- 结束日期为执行当日;
|
||||
- 时间跨度分别为 60 天、30 天、15 天、7 天、3 天;
|
||||
- 时间区间包含起止当日。
|
||||
**计算规则**:开始日期 = 结束日期 -(N - 1)天。
|
||||
例如 3D:开始日期 = 今日 - 2 天,结束日期 = 今日。
|
||||
5. 同时支持自定义起止日期查询导出。
|
||||
|
||||
### 3. 文件导出与存储
|
||||
1. 自动在桌面创建文件夹,文件夹命名规则:`采购计划报表_YYYYMMDD`。桌面路径支持配置。
|
||||
2. 将五组不同时间区间的报表导出为 **xlsx** 格式文件,保存至新建文件夹内。
|
||||
3. 单表命名分别为:
|
||||
- `物料收发汇总表_60D.xlsx`
|
||||
- `物料收发汇总表_30D.xlsx`
|
||||
- `物料收发汇总表_15D.xlsx`
|
||||
- `物料收发汇总表_7D.xlsx`
|
||||
- `物料收发汇总表_3D.xlsx`
|
||||
|
||||
### 4. 数据后处理
|
||||
1. 对每一份已导出的单独报表,在表格第一列新增【时间区间】字段,填入对应报表名称,即:
|
||||
- `60D`
|
||||
- `30D`
|
||||
- `15D`
|
||||
- `7D`
|
||||
- `3D`
|
||||
2. 将五份处理完成的单表数据合并,生成完整汇总报表。
|
||||
3. 汇总表命名规则:`物料收发汇总表_YYYYMMDD.xlsx`。
|
||||
4. 汇总表与单表统一保存至同一文件夹中。
|
||||
|
||||
---
|
||||
|
||||
## 二、核心规则
|
||||
|
||||
### 1. 汇总表字段排版
|
||||
- 第一列为新增的【时间区间】字段。
|
||||
- 后续完整保留原报表所有字段。
|
||||
- 字段顺序不调整、数据不缺失。
|
||||
|
||||
### 2. 日期与区间规则
|
||||
- 固定区间结束日期为执行当日,包含起止当日。
|
||||
- 自定义日期区间导出时,文件命名为:`物料收发汇总表_自定义_YYYYMMDD.xlsx`。
|
||||
- 自定义区间导出的报表同样在第一列新增【时间区间】,填入实际起止日期,例如:`2026-09-01至2026-09-10`。
|
||||
- 默认仅五组固定区间报表自动合并进汇总表;自定义区间报表单独保存,是否合并由用户后续按需处理。
|
||||
|
||||
### 3. 重复执行策略
|
||||
- 同一天重复执行时,默认覆盖同名文件夹及文件。
|
||||
- 如需保留历史版本,可通过配置项开启时间戳后缀,例如:`采购计划报表_YYYYMMDD_HHMMSS`。
|
||||
|
||||
### 4. 异常场景处理
|
||||
针对以下异常情况,系统需自动记录异常日志,便于问题排查:
|
||||
- 登录失败
|
||||
- 报表查询无数据
|
||||
- 文件导出失败
|
||||
- 文件被占用
|
||||
- 报表数据合并失败
|
||||
|
||||
**日志规则**:
|
||||
- 日志文件存放于同一文件夹下,命名:`异常日志_YYYYMMDD.log`。
|
||||
- 记录内容包含:时间、步骤、异常类型、异常描述、涉及文件路径。
|
||||
- 异常发生时不影响其他已成功步骤,尽量继续执行或给出明确提示。
|
||||
|
||||
### 5. 配置项要求
|
||||
- 账号、密码支持配置文件读取。
|
||||
- 桌面路径支持配置。
|
||||
- 仓库编码支持配置。
|
||||
- 是否覆盖同名文件支持配置。
|
||||
- 自定义日期区间支持手动输入或配置文件指定。
|
||||
|
||||
---
|
||||
|
||||
## 三、项目交付物
|
||||
|
||||
1. 整合完成的物料收发汇总总报表及对应分组单表全套文件。
|
||||
2. 异常日志文件(如有异常发生)。
|
||||
3. 可配置化执行的自动化脚本或工具(如采用自动化实现)。
|
||||
|
||||
---
|
||||
|
||||
## 四、验收标准
|
||||
|
||||
1. 能成功登录 ERP 新账套并打开【物料收发汇总表】。
|
||||
2. 能按指定库存组织、仓库编码筛选数据。
|
||||
3. 能正确生成 60D、30D、15D、7D、3D 五组时间区间报表。
|
||||
4. 导出的单表命名正确,格式为 xlsx。
|
||||
5. 文件夹命名正确,路径为桌面且可配置。
|
||||
6. 每个单表第一列均新增【时间区间】字段,取值正确。
|
||||
7. 五份单表能正确合并为汇总表,字段完整、顺序不变、数据不缺失。
|
||||
8. 汇总表命名正确,并与单表存放于同一文件夹。
|
||||
9. 异常场景能记录日志,日志内容完整可追溯。
|
||||
|
||||
---
|
||||
|
||||
## 五、说明
|
||||
|
||||
- 本需求仅针对【物料收发汇总表】。
|
||||
- 文件夹 `采购计划报表_YYYYMMDD` 可能与其他报表需求共用,但本需求只负责物料收发汇总表相关文件的生成与存放。
|
||||
- 账号密码不在文档中记录明文,统一通过配置化方式管理。
|
||||
@@ -68,6 +68,19 @@ def login(pid: str) -> dict:
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def logout(pid: str) -> dict:
|
||||
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
|
||||
|
||||
返回 {id, label, online}
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
return {"id": pid, "label": _LABELS[pid], "online": False}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
|
||||
+149
-55
@@ -16,6 +16,7 @@ import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
@@ -27,6 +28,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import winjob as _winjob
|
||||
from webhost.backend.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
|
||||
|
||||
@@ -63,17 +65,26 @@ CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> account;登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
_SESS: dict[str, str] = {}
|
||||
_SESS_TTL = 24 * 3600 # 会话空闲有效期 24h(惰性过期,防长期运行无限累积)
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _sess_account(request: Request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录返回空串。"""
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
return _SESS.get(token, "")
|
||||
item = _SESS.get(token)
|
||||
if not item:
|
||||
return ""
|
||||
account, ts = item
|
||||
if time.time() - ts > _SESS_TTL:
|
||||
_SESS.pop(token, None)
|
||||
return ""
|
||||
_SESS[token] = (account, time.time()) # 滑动续期
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
@@ -88,11 +99,34 @@ def _require_login(request: Request) -> str:
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, result, error}
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
|
||||
_NS_LOCKS: dict[str, threading.Lock] = {}
|
||||
_NS_GUARD = threading.Lock()
|
||||
|
||||
|
||||
def _ns_gate(platform: str) -> threading.Lock:
|
||||
key = (platform or "").strip() or "local"
|
||||
with _NS_GUARD:
|
||||
if key not in _NS_LOCKS:
|
||||
_NS_LOCKS[key] = threading.Lock()
|
||||
return _NS_LOCKS[key]
|
||||
|
||||
|
||||
def _set_run(run_id: str, **kw) -> None:
|
||||
"""更新运行记录字段(保留 account 等既有键)。"""
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run.update(kw)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
@@ -153,7 +187,9 @@ def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
load_plugins(_resolve_allowed())
|
||||
global ALLOWED
|
||||
ALLOWED = _resolve_allowed()
|
||||
load_plugins(ALLOWED)
|
||||
yield
|
||||
|
||||
|
||||
@@ -193,7 +229,7 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = b.account.strip()
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
@@ -233,22 +269,59 @@ def _plugin_schema(p) -> dict:
|
||||
"fields": p.fields}
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/platforms/allowed",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/meta")
|
||||
def meta() -> dict:
|
||||
plugins = [_plugin_schema(p) for p in PLUGINS]
|
||||
platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)}
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据)
|
||||
plugins = [_plugin_schema(p) for p in PLUGINS] if account else []
|
||||
allowed = _account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed) if allowed is not None else True}
|
||||
for pid, m in PLATFORMS.items()]
|
||||
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/login")
|
||||
def login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.login(pid)
|
||||
return platform_auth.logout(pid)
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
@@ -260,6 +333,28 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(ALLOWED))]
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
job.assign(proc)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
@@ -270,22 +365,6 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-u", str(runner), "--plugin", plugin.id,
|
||||
"--run", run_id],
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None,
|
||||
"error": f"拉起执行子进程失败: {e}"}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
@@ -327,35 +406,35 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
proc.kill()
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "done" if ok else "error",
|
||||
"result": ev.get("result"), "error": ev.get("error")}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_set_run(run_id, status="done" if ok else "error",
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
_set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
@app.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
_require_login(request)
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
@@ -364,26 +443,41 @@ def start_run(req: RunReq, request: Request) -> dict:
|
||||
with RUN_LOCK:
|
||||
if len(RUNS) >= MAX_RUNS:
|
||||
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
|
||||
RUNS[run_id] = {"status": "running", "result": None, "error": None}
|
||||
RUNS[run_id] = {"status": "running", "account": account,
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
threading.Thread(target=_run_target, args=(plugin, req.fields, run_id),
|
||||
daemon=True, name=f"run-{plugin.id}").start()
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
_run_target(plugin, req.fields, run_id)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
_require_login(request)
|
||||
account = _require_login(request)
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if not run:
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
|
||||
|
||||
|
||||
@@ -55,6 +55,10 @@ def _run() -> int:
|
||||
if not plugin_id:
|
||||
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
|
||||
return 2
|
||||
# 宿主透传的插件白名单:与宿主进程加载集保持一致(未传 = 全量)
|
||||
allowed_arg = (sys.argv[sys.argv.index("--allowed") + 1]
|
||||
if "--allowed" in sys.argv else "")
|
||||
allowed = {s for s in allowed_arg.split(",") if s} if allowed_arg else None
|
||||
|
||||
# fields 经 stdin 传入(单行 JSON)
|
||||
fields: dict = {}
|
||||
@@ -78,7 +82,7 @@ def _run() -> int:
|
||||
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
|
||||
|
||||
try:
|
||||
load_plugins()
|
||||
load_plugins(allowed)
|
||||
plugin = PLUGINS.find(plugin_id)
|
||||
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
|
||||
auth=platform_auth)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Windows Job Object 封装:插件执行子进程整树托管。
|
||||
|
||||
- KILL_ON_JOB_CLOSE:句柄关闭/宿主崩溃时,作业内全部进程(含 DrissionPage 拉起的
|
||||
浏览器等孙进程)一并终止,杜绝超时强杀后残留孤儿进程;
|
||||
- PROCESS_MEMORY_LIMIT:作业级内存上限兜底,防插件内存爬升拖垮底座。
|
||||
非 Windows 平台所有方法安全降级为 no-op。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import sys
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_AVAILABLE = sys.platform == "win32"
|
||||
if _AVAILABLE:
|
||||
try:
|
||||
_K32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
except AttributeError: # 非 Windows 误导入
|
||||
_AVAILABLE = False
|
||||
|
||||
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
|
||||
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x0000_2000
|
||||
_JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x0000_0100
|
||||
_PROCESS_SET_QUOTA = 0x0100
|
||||
_PROCESS_TERMINATE = 0x0001
|
||||
|
||||
|
||||
if _AVAILABLE:
|
||||
class _IO_COUNTERS(ctypes.Structure):
|
||||
_fields_ = [(n, ctypes.c_uint64) for n in (
|
||||
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||||
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
|
||||
|
||||
class _BASIC_LIMIT_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("PerProcessUserTimeLimit", ctypes.c_int64),
|
||||
("PerJobUserTimeLimit", ctypes.c_int64),
|
||||
("LimitFlags", ctypes.c_uint32),
|
||||
("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t),
|
||||
("ActiveProcessLimit", ctypes.c_uint32),
|
||||
("Affinity", ctypes.c_size_t),
|
||||
("PriorityClass", ctypes.c_uint32),
|
||||
("SchedulingClass", ctypes.c_uint32),
|
||||
]
|
||||
|
||||
class _EXT_LIMIT_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("BasicLimitInformation", _BASIC_LIMIT_INFO),
|
||||
("IoInfo", _IO_COUNTERS),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t),
|
||||
("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
||||
("PeakJobMemoryUsed", ctypes.c_size_t),
|
||||
]
|
||||
|
||||
|
||||
class Job:
|
||||
"""一次性的插件子进程作业。用法:job = Job(); job.assign(proc); …; job.terminate()/close()。"""
|
||||
|
||||
def __init__(self, max_mem_mb: int = 0):
|
||||
self._h = None
|
||||
if not _AVAILABLE:
|
||||
return
|
||||
h = _K32.CreateJobObjectW(None, None)
|
||||
if not h:
|
||||
_LOGGER.warning("创建 Job Object 失败(winerror=%s),退化为无作业托管", ctypes.get_last_error())
|
||||
return
|
||||
info = _EXT_LIMIT_INFO()
|
||||
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if max_mem_mb > 0:
|
||||
info.BasicLimitInformation.LimitFlags |= _JOB_OBJECT_LIMIT_PROCESS_MEMORY
|
||||
info.ProcessMemoryLimit = max_mem_mb * 1024 * 1024
|
||||
if not _K32.SetInformationJobObject(
|
||||
h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
ctypes.byref(info), ctypes.sizeof(info)):
|
||||
_LOGGER.warning("设置 Job Object 限制失败(winerror=%s)", ctypes.get_last_error())
|
||||
self._h = h
|
||||
|
||||
def assign(self, proc) -> None:
|
||||
"""把子进程(及其后代)纳入作业托管。"""
|
||||
if not self._h:
|
||||
return
|
||||
if not _K32.AssignProcessToJobObject(self._h, int(proc._handle)):
|
||||
_LOGGER.warning("子进程纳入 Job Object 失败(winerror=%s)", ctypes.get_last_error())
|
||||
|
||||
def terminate(self, exit_code: int = 1) -> None:
|
||||
"""终止作业内全部进程(整树强杀,含浏览器等孙进程)。"""
|
||||
if self._h:
|
||||
_K32.TerminateJobObject(self._h, exit_code)
|
||||
|
||||
def close(self) -> None:
|
||||
"""关闭作业句柄;KILL_ON_JOB_CLOSE 保证句柄消失后作业内进程全部退出。"""
|
||||
if self._h:
|
||||
_K32.CloseHandle(self._h)
|
||||
self._h = None
|
||||
+107
-27
@@ -19,10 +19,10 @@
|
||||
v-for="p in store.platforms"
|
||||
:key="p.id"
|
||||
class="chip"
|
||||
:class="{ online: p.online }"
|
||||
:disabled="busyLogin === p.id"
|
||||
:class="{ online: p.online, locked: p.allowed === false }"
|
||||
:disabled="busyLogin === p.id || p.allowed === false"
|
||||
@click="login(p.id)"
|
||||
:title="p.online ? '已登录,点击刷新' : '未登录,点击登录'"
|
||||
:title="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
|
||||
>
|
||||
<i class="dot"></i>
|
||||
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
|
||||
@@ -37,8 +37,14 @@
|
||||
</div>
|
||||
|
||||
<div class="acct">
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
|
||||
<button class="acct-btn" title="个人中心" @click="profileOpen = true">
|
||||
<span class="acct-avatar">
|
||||
<img v-if="store.avatarUrl" :src="store.avatarUrl" alt="" @error="clearAvatarCache">
|
||||
<span v-else class="acct-avatar-fb">{{ store.current.slice(0, 1).toUpperCase() }}</span>
|
||||
</span>
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
|
||||
</button>
|
||||
<button class="chip" @click="logout">登出</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -75,6 +81,8 @@
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
|
||||
<div v-if="toast" class="toast">{{ toast }}</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
@@ -82,8 +90,9 @@ import { computed, onMounted, ref } from 'vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import { store, handleEvent, clearLogs } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout } from './api'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe } from './api'
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
@@ -95,55 +104,103 @@ function openPlugin(id) {
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins
|
||||
store.selectedId = meta.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
function openWS() {
|
||||
if (window.__ws) window.__ws.close()
|
||||
const ws = connectWS(handleEvent)
|
||||
window.__ws = ws
|
||||
ws.onopen = () => (store.wsOn = true)
|
||||
ws.onclose = () => { store.wsOn = false; setTimeout(() => (location.reload()), 2500) }
|
||||
ws.onclose = () => {
|
||||
store.wsOn = false
|
||||
// 仅登录态下自动重连刷新;未登录被拒(1008)时静默,避免 reload 死循环
|
||||
if (store.current) setTimeout(() => (location.reload()), 2500)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
openWS()
|
||||
checkSession()
|
||||
loadAvatar()
|
||||
})
|
||||
|
||||
const profileOpen = ref(false)
|
||||
const busyLogin = ref('')
|
||||
|
||||
// 极简顶部 toast:平台登录等轻量操作反馈
|
||||
const toast = ref('')
|
||||
let toastTimer = null
|
||||
function showToast(msg) {
|
||||
toast.value = msg
|
||||
if (toastTimer) clearTimeout(toastTimer)
|
||||
toastTimer = setTimeout(() => (toast.value = ''), 2200)
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
// 已在本地标记登录:与后端会话 cookie 是否一致(后端重启会失效,此时回登录页)
|
||||
if (!store.current) return
|
||||
try {
|
||||
const me = await fetch('/api/admin/me').then((r) => r.json())
|
||||
if (!me.account) { store.current = ''; store.isAdmin = false }
|
||||
else store.isAdmin = !!me.is_admin
|
||||
} catch (_) { /* 后端 down:暂保持本地态 */
|
||||
}
|
||||
const me = await adminMe()
|
||||
if (!me.account) { store.current = ''; store.isAdmin = false; store.dept = '' }
|
||||
else {
|
||||
store.isAdmin = !!me.is_admin
|
||||
store.dept = me.dept || ''
|
||||
// 会话有效:补拉插件清单(未登录时 meta 不返回插件)
|
||||
await refreshMeta()
|
||||
}
|
||||
} catch (_) { /* 后端 down:暂保持本地态 */ }
|
||||
}
|
||||
|
||||
function onLogin(ok) {
|
||||
async function refreshMeta() {
|
||||
try {
|
||||
const meta = await fetchMeta()
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
if (!store.selectedId) store.selectedId = store.plugins[0]?.id || ''
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function onLogin(ok) {
|
||||
store.current = ok.account
|
||||
store.isAdmin = !!ok.is_admin
|
||||
store.dept = ok.dept || ''
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
// 登录后:刷新平台权限与插件清单,并用带会话的连接重建 WS
|
||||
await refreshMeta()
|
||||
openWS()
|
||||
loadAvatar()
|
||||
}
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
}
|
||||
|
||||
async function login(id) {
|
||||
if (busyLogin.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
const label = p?.label || id
|
||||
if (p?.online) {
|
||||
showToast(`${label} 已登录`)
|
||||
return
|
||||
}
|
||||
busyLogin.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) p.online = !!r.online
|
||||
const ok = !!(r && r.online)
|
||||
if (p) p.online = ok
|
||||
log(ok ? 'INFO' : 'ERROR',
|
||||
ok ? `平台 ${label} 登录成功` : `平台 ${label} 登录未生效:${(r && r.message) || ''}`)
|
||||
showToast(ok ? `${label} 登录成功` : `${label} 登录失败:${(r && r.message) || '登录态未生效'}`)
|
||||
} catch (e) {
|
||||
alert('登录失败:' + (e.message || e))
|
||||
log('ERROR', `平台 ${label} 登录失败:${e.message || e}`)
|
||||
showToast(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busyLogin.value = ''
|
||||
}
|
||||
@@ -184,12 +241,29 @@ async function login(id) {
|
||||
.chip:hover { border-color: var(--primary); color: var(--primary); }
|
||||
.chip:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.chip:disabled:hover { border-color: var(--border-strong); color: var(--text-sub); }
|
||||
.chip.locked { border-style: dashed; opacity: .5; }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-label { font-size: 12px; color: var(--primary); font-weight: 600; min-width: 38px; text-align: right; }
|
||||
|
||||
.acct { display: flex; align-items: center; gap: 8px; margin-left: 12px; }
|
||||
.acct-btn {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
border: none; background: transparent; cursor: pointer;
|
||||
padding: 4px 8px; margin: -4px -8px; border-radius: 8px;
|
||||
font: inherit; transition: background .13s;
|
||||
}
|
||||
.acct-btn:hover { background: var(--surface-2); }
|
||||
.acct-avatar {
|
||||
width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0;
|
||||
position: relative; overflow: hidden;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.acct-avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
||||
.acct-avatar-fb { line-height: 1; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
.acct-tag { font-style: normal; font-size: 10px; color: var(--primary);
|
||||
border: 1px solid var(--primary-weak); background: var(--primary-weak); border-radius: 999px; padding: 1px 7px; }
|
||||
@@ -213,12 +287,18 @@ async function login(id) {
|
||||
display: grid; place-items: center; color: #fff; font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.scene-list li.active .scene-name { color: var(--primary); }
|
||||
.scene-list li.admin-entry { border-top: 1px dashed var(--border); margin-top: 6px; border-radius: 0; }
|
||||
.scene-list li.admin-entry.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; }
|
||||
|
||||
.main { flex: 1; display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; }
|
||||
|
||||
.toast {
|
||||
position: fixed; top: 18px; left: 50%; transform: translateX(-50%);
|
||||
background: rgba(24, 39, 75, .92); color: #fff;
|
||||
padding: 8px 18px; border-radius: 999px; font-size: 12.5px;
|
||||
z-index: 60; animation: toast-in .15s ease;
|
||||
box-shadow: 0 8px 24px -8px rgba(24, 39, 75, .4);
|
||||
}
|
||||
@keyframes toast-in { from { opacity: 0; transform: translate(-50%, -6px); } to { opacity: 1; transform: translate(-50%, 0); } }
|
||||
</style>
|
||||
@@ -19,6 +19,10 @@ export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function logoutPlatform(id) {
|
||||
return j(`/api/platforms/${id}/logout`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
@@ -44,20 +48,11 @@ export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return jj('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return jj('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
async function jj(url, opts) {
|
||||
const r = await fetch(url, opts)
|
||||
if (!r.ok) {
|
||||
let m = `HTTP ${r.status}`
|
||||
try { m = (await r.json()).detail || m } catch (_) {}
|
||||
throw new Error(m)
|
||||
}
|
||||
return r.json()
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<i class="blob b1"></i>
|
||||
<i class="blob b2"></i>
|
||||
<i class="blob b3"></i>
|
||||
|
||||
<div class="card">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
@@ -8,13 +12,35 @@
|
||||
<span>统一账户登录</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<input v-model="account" placeholder="账号" @keyup.enter="doLogin">
|
||||
<input v-model="password" type="password" placeholder="密码" @keyup.enter="doLogin">
|
||||
<label class="field">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<circle cx="12" cy="8" r="3.6" />
|
||||
<path d="M4.5 20a7.5 7.5 0 0 1 15 0" />
|
||||
</svg>
|
||||
<input v-model="account" placeholder="账号" autocomplete="username" @keyup.enter="doLogin">
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="4.5" y="10.5" width="15" height="9.5" rx="2.5" />
|
||||
<path d="M8 10.5V7.8a4 4 0 0 1 8 0v2.7" />
|
||||
</svg>
|
||||
<input v-model="password" type="password" placeholder="密码" autocomplete="current-password" @keyup.enter="doLogin">
|
||||
</label>
|
||||
</div>
|
||||
<button class="primary" :disabled="busy" @click="doLogin">{{ busy ? '校验中…' : '登录' }}</button>
|
||||
<p class="tip">账号统一由控制面带部门建档,所有账号均需密码登录,密码不落前端明文。</p>
|
||||
<p class="msg" v-if="msg">{{ msg }}</p>
|
||||
|
||||
<button class="primary" :disabled="busy" @click="doLogin">
|
||||
<span v-if="busy" class="spinner"></span>
|
||||
{{ busy ? '校验中…' : '登录' }}
|
||||
</button>
|
||||
|
||||
<transition name="fade">
|
||||
<p class="msg" v-if="msg">{{ msg }}</p>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -33,9 +59,10 @@ const msg = ref('')
|
||||
async function doLogin() {
|
||||
if (!account.value || !password.value) return (msg.value = '请输入账号和密码')
|
||||
busy.value = true
|
||||
msg.value = ''
|
||||
try {
|
||||
const r = await adminLogin(account.value, password.value)
|
||||
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin })
|
||||
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin, dept: r.dept || '' })
|
||||
} catch (e) {
|
||||
msg.value = '登录失败:' + (e.message || e)
|
||||
} finally {
|
||||
@@ -45,21 +72,204 @@ async function doLogin() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login { display: grid; place-items: center; height: 100%; }
|
||||
.card { width: 340px; display: flex; flex-direction: column; gap: 14px;
|
||||
border: 1px solid var(--border); border-radius: 12px; padding: 28px; box-shadow: 0 10px 30px -14px rgba(0,0,0,.18); }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
|
||||
.logo { width: 40px; height: 40px; border-radius: 11px; display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff; font-size: 15px; font-weight: 800; }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 15px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
.login {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
height: 100%;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: radial-gradient(1100px 520px at 50% -12%, rgba(59, 108, 255, .07), transparent 62%);
|
||||
}
|
||||
|
||||
/* ---------- 背景光斑 ---------- */
|
||||
.blob {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
filter: blur(90px);
|
||||
opacity: .38;
|
||||
pointer-events: none;
|
||||
will-change: transform;
|
||||
animation: float 18s ease-in-out infinite;
|
||||
}
|
||||
.b1 { width: 460px; height: 460px; background: #a8c1ff; top: -150px; right: -110px; }
|
||||
.b2 { width: 400px; height: 400px; background: #9fe3c8; bottom: -140px; left: -90px; animation-delay: -6s; }
|
||||
.b3 { width: 280px; height: 280px; background: #ffd6a8; bottom: 18%; right: 10%; opacity: .22; animation-delay: -12s; }
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translate3d(0, 0, 0) scale(1); }
|
||||
50% { transform: translate3d(0, -22px, 0) scale(1.06); }
|
||||
}
|
||||
|
||||
/* ---------- 卡片 ---------- */
|
||||
.card {
|
||||
width: 380px;
|
||||
max-width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 32px 32px 26px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 20px;
|
||||
background: var(--surface);
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
box-shadow:
|
||||
0 24px 60px -26px rgba(24, 39, 75, .34),
|
||||
0 2px 10px -3px rgba(24, 39, 75, .08);
|
||||
animation: rise .5s cubic-bezier(.22, 1, .36, 1) both;
|
||||
}
|
||||
|
||||
@keyframes rise {
|
||||
from { opacity: 0; transform: translateY(14px) scale(.985); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
/* ---------- 品牌区 ---------- */
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-bottom: 2px; }
|
||||
|
||||
.logo {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
flex: none;
|
||||
border-radius: 12px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .02em;
|
||||
box-shadow: 0 6px 16px -5px rgba(59, 108, 255, .65);
|
||||
}
|
||||
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.3; min-width: 0; }
|
||||
.brand-meta strong {
|
||||
font-size: 15px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.brand-meta span { font-size: 11.5px; color: var(--text-faint); letter-spacing: .02em; }
|
||||
|
||||
/* ---------- 输入框 ---------- */
|
||||
.row { display: flex; flex-direction: column; gap: 10px; }
|
||||
.row input { border: 1px solid var(--border-strong); border-radius: var(--radius-sm); padding: 10px 12px; background: var(--surface); font: inherit; }
|
||||
.row input:focus { outline: none; border-color: var(--primary); }
|
||||
button.primary { border: none; border-radius: var(--radius-sm); padding: 10px; cursor: pointer;
|
||||
background: var(--primary); color: #fff; font: inherit; }
|
||||
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.tip { color: var(--text-faint); font-size: 11.5px; line-height: 1.6; }
|
||||
.msg { color: #e5484d; font-size: 12px; }
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 0 13px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
transition: border-color .18s, box-shadow .18s;
|
||||
}
|
||||
.field:hover { border-color: var(--primary); }
|
||||
|
||||
.field:focus-within {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 4px var(--primary-weak);
|
||||
}
|
||||
|
||||
.field svg {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
color: var(--text-faint);
|
||||
transition: color .18s;
|
||||
}
|
||||
.field:focus-within svg { color: var(--primary); }
|
||||
|
||||
.field input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 12px 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
.field input::placeholder { color: var(--text-faint); }
|
||||
|
||||
/* 干掉 Chrome 自动填充的黄色底色 */
|
||||
.field input:-webkit-autofill {
|
||||
-webkit-text-fill-color: currentColor;
|
||||
transition: background-color 9999s ease-in-out 0s;
|
||||
}
|
||||
|
||||
/* ---------- 主按钮 ---------- */
|
||||
button.primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
margin-top: 2px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: .06em;
|
||||
box-shadow: 0 8px 20px -7px rgba(59, 108, 255, .65);
|
||||
transition: box-shadow .18s, transform .12s, filter .18s;
|
||||
}
|
||||
button.primary:hover:not(:disabled) {
|
||||
filter: brightness(1.05);
|
||||
box-shadow: 0 12px 28px -9px rgba(59, 108, 255, .75);
|
||||
}
|
||||
button.primary:active:not(:disabled) {
|
||||
transform: translateY(1px);
|
||||
box-shadow: 0 5px 14px -7px rgba(59, 108, 255, .65);
|
||||
}
|
||||
button.primary:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 4px var(--primary-weak), 0 8px 20px -7px rgba(59, 108, 255, .65);
|
||||
}
|
||||
button.primary:disabled { opacity: .6; cursor: not-allowed; box-shadow: none; }
|
||||
|
||||
.spinner {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border: 2px solid rgba(255, 255, 255, .38);
|
||||
border-top-color: #fff;
|
||||
border-radius: 50%;
|
||||
animation: spin .7s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* ---------- 提示信息 ---------- */
|
||||
.msg {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid rgba(229, 72, 77, .18);
|
||||
border-radius: 10px;
|
||||
background: rgba(229, 72, 77, .08);
|
||||
color: #e5484d;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.fade-enter-active,
|
||||
.fade-leave-active { transition: opacity .2s, transform .2s; }
|
||||
.fade-enter-from,
|
||||
.fade-leave-to { opacity: 0; transform: translateY(-4px); }
|
||||
|
||||
/* ---------- 自适应 & 降级 ---------- */
|
||||
@media (max-width: 420px) {
|
||||
.login { padding: 16px; }
|
||||
.card { padding: 26px 22px 22px; border-radius: 16px; }
|
||||
.blob { filter: blur(70px); opacity: .3; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.blob, .card { animation: none; }
|
||||
* { transition-duration: .01ms !important; }
|
||||
}
|
||||
</style>
|
||||
@@ -69,7 +69,7 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { store } from '../store'
|
||||
import { store, log } from '../store'
|
||||
import { startRun, getRun } from '../api'
|
||||
|
||||
const months = computed(() => {
|
||||
@@ -109,8 +109,14 @@ async function run() {
|
||||
store.lastSummary = ''
|
||||
const payload = { ...form.value }
|
||||
if (plugin.value.uses_month) payload.ref_month = month.value // 仅月度插件注入月份
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
try {
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
} catch (e) {
|
||||
store.running = false
|
||||
store.lastResult = { ok: false, error: e.message || String(e) }
|
||||
log('ERROR', `启动执行失败:${e.message || e}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 完成时拉取后端摘要填充横幅
|
||||
@@ -160,13 +166,12 @@ function closeBanner() {
|
||||
|
||||
.form-card {
|
||||
display: flex; flex-direction: column; gap: 16px;
|
||||
background: var(--surface-2); border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm); padding: 16px;
|
||||
padding: 2px 0 0;
|
||||
}
|
||||
.fields { display: flex; gap: 24px; flex-wrap: wrap; }
|
||||
.fgroup { display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
|
||||
.fgroup .input { width: 150px; }
|
||||
.actions { display: flex; justify-content: flex-end; }
|
||||
.actions { display: flex; justify-content: flex-end; border-top: 1px dashed var(--border); padding-top: 14px; }
|
||||
.run-btn { min-width: 128px; height: 38px; font-size: 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.spin { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.7s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
<template>
|
||||
<div class="mask" @click.self="emit('close')">
|
||||
<aside class="profile">
|
||||
<header class="head">
|
||||
<div class="avatar" aria-hidden="true">
|
||||
<img v-if="store.avatarUrl && !avatarFailed" :src="store.avatarUrl" alt="" @error="onAvatarError">
|
||||
<span v-else>{{ store.current.slice(0, 1).toUpperCase() }}</span>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div class="name-line">
|
||||
<strong>{{ store.current }}</strong>
|
||||
<em v-if="store.isAdmin" class="tag">管理员</em>
|
||||
</div>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
<button class="close" title="关闭" @click="emit('close')">✕</button>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<!-- 分节:平台登录态 -->
|
||||
<div class="sec">
|
||||
<div class="sec-title">平台登录态</div>
|
||||
<div v-for="p in store.platforms" :key="p.id" class="prow">
|
||||
<i class="dot" :class="{ on: p.online }"></i>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<span class="pstat">{{ p.online ? '已登录' : '未登录' }}</span>
|
||||
<button class="btn mini" :disabled="busy === p.id" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : '重新登录' }}
|
||||
</button>
|
||||
<button class="btn mini" :disabled="busy === p.id || !p.online" @click="logout(p.id)">登出</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分节:我的插件 -->
|
||||
<div class="sec">
|
||||
<div class="sec-title">我的插件</div>
|
||||
<div v-if="store.plugins.length" class="plist">
|
||||
<div v-for="p in store.plugins" :key="p.id" class="prow flat">
|
||||
<span class="pname">{{ p.name }}</span>
|
||||
<span class="ver">v{{ p.version }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="empty">当前账号暂无可用插件</p>
|
||||
</div>
|
||||
|
||||
<!-- 分节:修改密码 -->
|
||||
<div class="sec">
|
||||
<div class="sec-title">修改密码</div>
|
||||
<input class="input" v-model="oldPwd" type="password" placeholder="旧密码">
|
||||
<input class="input" v-model="newPwd" type="password" placeholder="新密码">
|
||||
<input class="input" v-model="againPwd" type="password" placeholder="确认新密码">
|
||||
<button class="btn primary block" :disabled="pwdBusy" @click="changePwd">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</button>
|
||||
<p v-if="pwdMsg" class="msg" :class="{ ok: pwdOk }">{{ pwdMsg }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<transition name="fade">
|
||||
<div v-if="tipMsg" class="tip">{{ tipMsg }}</div>
|
||||
</transition>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { store, log, clearAvatarCache } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
const avatarFailed = ref(false)
|
||||
function onAvatarError() {
|
||||
avatarFailed.value = true
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const busy = ref('')
|
||||
// 面板内轻提示:已登录再点击等操作反馈
|
||||
const tipMsg = ref('')
|
||||
let tipTimer = null
|
||||
function tip(m) {
|
||||
tipMsg.value = m
|
||||
if (tipTimer) clearTimeout(tipTimer)
|
||||
tipTimer = setTimeout(() => (tipMsg.value = ''), 2000)
|
||||
}
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
tip(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
alert('登录失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function logout(id) {
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await logoutPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
tip('登出失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const oldPwd = ref('')
|
||||
const newPwd = ref('')
|
||||
const againPwd = ref('')
|
||||
const pwdBusy = ref(false)
|
||||
const pwdMsg = ref('')
|
||||
const pwdOk = ref(false)
|
||||
async function changePwd() {
|
||||
pwdMsg.value = ''
|
||||
if (!oldPwd.value || !newPwd.value) return (pwdMsg.value = '请填写完整密码')
|
||||
if (newPwd.value !== againPwd.value) return (pwdMsg.value = '两次新密码不一致')
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: oldPwd.value,
|
||||
new_password: newPwd.value,
|
||||
})
|
||||
pwdMsg.value = '密码已修改'
|
||||
pwdOk.value = true
|
||||
oldPwd.value = newPwd.value = againPwd.value = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
pwdOk.value = false
|
||||
pwdMsg.value = '修改失败:' + (e.message || e)
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mask {
|
||||
position: fixed; inset: 0; z-index: 50;
|
||||
background: rgba(31, 38, 51, 0.35);
|
||||
display: flex; justify-content: flex-end;
|
||||
animation: fade .18s ease;
|
||||
}
|
||||
.tip {
|
||||
position: absolute; top: 18px; left: 50%; transform: translateX(-50%);
|
||||
background: rgba(24, 39, 75, .92); color: #fff;
|
||||
padding: 8px 18px; border-radius: 999px; font-size: 12.5px;
|
||||
z-index: 5; box-shadow: 0 8px 24px -8px rgba(24, 39, 75, .4);
|
||||
animation: fade .15s ease;
|
||||
}
|
||||
.profile {
|
||||
width: 320px; height: 100%;
|
||||
background: var(--surface);
|
||||
display: flex; flex-direction: column;
|
||||
box-shadow: -12px 0 34px -12px rgba(24, 39, 75, 0.3);
|
||||
animation: slide .2s ease;
|
||||
}
|
||||
@keyframes slide { from { transform: translateX(100%); } to { transform: translateX(0); } }
|
||||
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
|
||||
|
||||
.head {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 18px 20px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.avatar {
|
||||
width: 46px; height: 46px; border-radius: 50%;
|
||||
position: relative; overflow: hidden; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
color: #fff; font-size: 18px; font-weight: 700;
|
||||
background: var(--primary-grad);
|
||||
}
|
||||
.avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
||||
.meta { flex: 1; min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong { font-size: 15px; }
|
||||
.tag { font-style: normal; font-size: 10px; color: var(--primary);
|
||||
background: var(--primary-weak); border-radius: 999px; padding: 1px 8px; }
|
||||
.dept { font-size: 11.5px; color: var(--text-faint); }
|
||||
.close {
|
||||
border: none; background: transparent; cursor: pointer;
|
||||
color: var(--text-faint); font-size: 14px; padding: 6px; border-radius: 8px;
|
||||
}
|
||||
.close:hover { color: var(--text); background: var(--surface-2); }
|
||||
|
||||
.body { flex: 1; overflow: auto; padding: 4px 20px 20px; }
|
||||
.sec { padding: 14px 0 4px; }
|
||||
.sec + .sec { border-top: 1px dashed var(--border); margin-top: 6px; }
|
||||
.sec-title {
|
||||
font-size: 11px; font-weight: 700; letter-spacing: 0.04em;
|
||||
color: var(--text-faint); margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.prow { display: flex; align-items: center; gap: 8px; padding: 7px 0; }
|
||||
.prow.flat { padding: 6px 0; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: #c6ccdc; flex-shrink: 0; }
|
||||
.dot.on { background: var(--ok); box-shadow: 0 0 0 3px rgba(34, 176, 122, 0.18); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13px;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.pstat { font-size: 11px; color: var(--text-faint); }
|
||||
.ver { font-size: 11px; color: var(--text-faint); }
|
||||
.plist { display: flex; flex-direction: column; }
|
||||
.empty { color: var(--text-faint); font-size: 12px; margin: 4px 0; }
|
||||
.btn.mini { padding: 3px 10px; font-size: 12px; }
|
||||
|
||||
.input { width: 100%; margin-bottom: 10px; }
|
||||
.btn.block { width: 100%; margin-top: 2px; }
|
||||
.msg { font-size: 12px; color: var(--err); margin: 8px 0 0; }
|
||||
.msg.ok { color: var(--ok); }
|
||||
</style>
|
||||
@@ -14,11 +14,45 @@ export const store = reactive({
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 控制面管理视图(统一后端数据库 API)
|
||||
isAdmin: false,
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
isAdmin: false,
|
||||
dept: '',
|
||||
avatarUrl: '', // 在线头像(localStorage 缓存,避免每次刷新都请求)
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
})
|
||||
|
||||
// ===== 在线头像:优先读缓存,无缓存时请求接口并落盘;图片加载失败时清除缓存重新拉取 =====
|
||||
// 缓存按账号隔离(cp_avatar_url_<账号>),切换账号不会串用上一个人的头像
|
||||
const AVATAR_API = 'https://v2.xxapi.cn/api/head'
|
||||
|
||||
function avatarCacheKey() {
|
||||
return `cp_avatar_url_${store.current || 'anon'}`
|
||||
}
|
||||
|
||||
export function loadAvatar() {
|
||||
const key = avatarCacheKey()
|
||||
try {
|
||||
const cached = localStorage.getItem(key)
|
||||
if (cached) { store.avatarUrl = cached; return }
|
||||
} catch (_) {}
|
||||
store.avatarUrl = ''
|
||||
fetch(AVATAR_API, { signal: AbortSignal.timeout(4000) })
|
||||
.then((r) => r.json())
|
||||
.then((j) => {
|
||||
if (j && j.code === 200 && j.data) {
|
||||
store.avatarUrl = j.data
|
||||
try { localStorage.setItem(avatarCacheKey(), j.data) } catch (_) {}
|
||||
}
|
||||
})
|
||||
.catch(() => { /* 网络不可达/超时:保持首字符色块兜底 */ })
|
||||
}
|
||||
|
||||
export function clearAvatarCache() {
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem(avatarCacheKey()) } catch (_) {}
|
||||
loadAvatar()
|
||||
}
|
||||
|
||||
export function clearLogs() {
|
||||
store.logs = []
|
||||
store.lastResult = null
|
||||
|
||||
@@ -169,6 +169,7 @@ COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
COL_REMARK = "备注"
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
@@ -524,7 +525,8 @@ def check_bank_card(card_raw):
|
||||
|
||||
|
||||
# ==================== 核对分类 ====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account):
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
bank_name="", remark=""):
|
||||
"""按核对规则对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, bank_info)
|
||||
@@ -532,25 +534,36 @@ def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
bank_info: 银行卡校验结果 dict(无卡时为 None)
|
||||
规则:
|
||||
1. 开户人信息或银行卡空白 -> 异常
|
||||
1. 开户人身份证/姓名、银行卡三项均空白 -> 统一记为「未提供银行卡」;仅单项空白保留原标签
|
||||
2. 员工姓名与开户人姓名、身份证均不一致 -> 代发(不算异常,除非银行卡 BIN 核对错误)
|
||||
3. 仅身份证不一致 或 仅姓名不一致 -> 异常
|
||||
4. 银行卡非空但格式/位数错误 -> 银行卡信息异常
|
||||
3. 仅身份证不一致 -> 异常;仅姓名不一致(身份证一致)-> 「姓名不一致身份证一致」
|
||||
4. 开卡银行/银行卡号/备注任一列含「现金」-> 标记「现金发放」,不做 BIN 校验
|
||||
5. 银行卡非空但格式/位数错误 -> 银行卡信息异常
|
||||
"""
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if _is_empty(bank_account):
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
# 开卡银行/银行卡号/备注任一列含「现金」-> 现金发放(现金发放优先,不再记银行卡空白)
|
||||
cash_hit = any("现金" in str(v) for v in (bank_name, bank_account, remark))
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白(三项全空合并为「未提供银行卡」,单个还是单个) ----
|
||||
blank_id = _is_empty(card_idcard)
|
||||
blank_name = _is_empty(card_name)
|
||||
blank_bank = _is_empty(bank_account)
|
||||
if blank_id and blank_name and blank_bank:
|
||||
issues.append("未提供银行卡")
|
||||
basis.append("未提供银行卡(开户人姓名/身份证/银行卡均空白)")
|
||||
else:
|
||||
if blank_id:
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if blank_name:
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if blank_bank and not cash_hit:
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 代发 / 身份证、姓名不一致(开户人信息非空才比对) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
@@ -564,11 +577,14 @@ def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
if name_inconsistent:
|
||||
issues.append("员工姓名与开户人姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
issues.append("姓名不一致身份证一致")
|
||||
basis.append(f"姓名不一致身份证一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 3. 银行卡信息异常(银行卡非空但格式/位数错误) ----
|
||||
if not _is_empty(bank_account):
|
||||
# ---- 3. 现金发放(三列任一含「现金」) / 银行卡信息异常(非空但格式/位数错误) ----
|
||||
if cash_hit:
|
||||
issues.append("现金发放")
|
||||
basis.append("开卡银行/银行卡号/备注含「现金」,标记为现金发放")
|
||||
elif not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
issues.append("银行卡信息异常")
|
||||
@@ -644,6 +660,7 @@ def check_wage_card(wage_data, output_path=None):
|
||||
|
||||
issues, basis, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
bank_name=row.get(COL_BANK_NAME, ""), remark=row.get(COL_REMARK, ""),
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
@@ -684,8 +701,11 @@ def check_wage_card(wage_data, output_path=None):
|
||||
return view
|
||||
|
||||
# 异常名单 = 除「通过」「代发」外的全部记录(纯代发不算异常;代发+BIN错误仍计入)
|
||||
# 按异常原因种类排序(核对结果标签),同类原因聚在一起便于查看
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (df[COL_CHECK_RESULT] != "代发")
|
||||
abnormal_view = _abnormal_view(df[mask])
|
||||
abnormal_view = _abnormal_view(
|
||||
df[mask].sort_values(COL_CHECK_RESULT, kind="stable")
|
||||
)
|
||||
|
||||
with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
|
||||
abnormal_view.to_excel(writer, sheet_name=SHEET_ABNORMAL, index=False)
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
@CreateTime: 2026-08-20
|
||||
@Description: 改签离职电子签流程审核(影刀单文件版)- 业务逻辑与 App 版
|
||||
app/service/hrbp/oa/resign_e_sign/ 完全一致,规则见 aa.md。
|
||||
@Version: 1.0.0
|
||||
@Version: 1.1.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv pymupdf
|
||||
@@ -26,7 +26,7 @@ import random
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode, urlparse, parse_qs
|
||||
|
||||
@@ -85,6 +85,11 @@ CONTRACT_SAVE_DIR = r"D:\资料\人资\离职电子签流程审核\附件"
|
||||
# 监听其响应以区分提交成功/失败:state="1" 成功,state="0" 失败(失败时页面不关闭)
|
||||
SEND_WE_TASK_URL = f"{HR_BASE_URL}/RedseaPlatform/WeTask.mc"
|
||||
SEND_WE_TASK_MARK = "WeTask.mc?method=sendWeTask"
|
||||
# 流程节点列表查询接口:按 processId 查流程全部节点(activityName/createTime/endTime 等)
|
||||
WE_PROCESS_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc"
|
||||
# 超期检查:「完善信息(操作人)」节点 endTime 非空且距今超过 3 天 -> 超期提醒
|
||||
OVERDUE_ACTIVITY_NAME = "完善信息(操作人)"
|
||||
OVERDUE_DAYS = 3
|
||||
|
||||
# ---------- 分页 ----------
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
|
||||
@@ -343,6 +348,66 @@ def get_business_data(session, business_key, form_id):
|
||||
return result
|
||||
|
||||
|
||||
def get_activity_list(session, process_id):
|
||||
"""调用 WeProcess.mc?method=getActivityList 按 processId 查询流程全部节点。
|
||||
|
||||
返回 jsonList(每项含 activityName/createTime/endTime/currentState 等)。
|
||||
"""
|
||||
url = f"{WE_PROCESS_URL}?method=getActivityList&processId={process_id}"
|
||||
logger.info("查询流程节点列表: processId=%s", process_id)
|
||||
|
||||
session.post(url)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("WeProcess 请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"WeProcess 接口状态码异常: {resp.status_code}")
|
||||
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"WeProcess 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
if json_data.get("state") != "1":
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: {json_data.get('meg')}")
|
||||
|
||||
json_list = json_data.get("jsonList") or []
|
||||
logger.info("WeProcess 返回成功,共 %d 个节点", len(json_list))
|
||||
logger.debug("WeProcess 返回: %s", json_data)
|
||||
return json_list
|
||||
|
||||
|
||||
def check_process_overdue(session, process_id, now=None):
|
||||
"""超期检查:取「完善信息(操作人)」节点 endTime 判断是否超期。
|
||||
|
||||
规则:endTime 为 null(节点未完成)-> 不算超期,返回 None;
|
||||
endTime 非空且距今超过 OVERDUE_DAYS 天 -> 返回 {"endTime", "days"}。
|
||||
"""
|
||||
activities = get_activity_list(session, process_id)
|
||||
target = next(
|
||||
(a for a in activities if a.get("activityName") == OVERDUE_ACTIVITY_NAME),
|
||||
None,
|
||||
)
|
||||
if target is None:
|
||||
logger.warning("流程 %s 未找到「%s」节点,跳过超期检查", process_id, OVERDUE_ACTIVITY_NAME)
|
||||
return None
|
||||
|
||||
end_time = target.get("endTime")
|
||||
if not end_time:
|
||||
# 节点未完成(endTime=null),按要求不管
|
||||
logger.info("流程 %s「%s」未完成(endTime=null),不检查超期", process_id, OVERDUE_ACTIVITY_NAME)
|
||||
return None
|
||||
|
||||
end_dt = datetime.strptime(str(end_time).strip(), "%Y-%m-%d %H:%M:%S")
|
||||
now = now or datetime.now()
|
||||
days = (now - end_dt).total_seconds() / 86400
|
||||
if days > OVERDUE_DAYS:
|
||||
logger.info("流程 %s 已超期:endTime=%s(%.1f 天)", process_id, end_time, days)
|
||||
return {"endTime": str(end_time), "days": int(days)}
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 电子签真实签署状态查询 ====================
|
||||
# getBusinessDate 返回的 ext_is_initiate_sign / ext_staff_sign_status / ext_org_sign_status
|
||||
# 恒为空串,拿不到真实签署状态;需再调该查询接口(按 main_id 即合同业务主键)取真实状态:
|
||||
@@ -503,6 +568,9 @@ def parse_resign_e_sign_form(result):
|
||||
"工号": result.get("base_code"),
|
||||
"身份证号": result.get("idcard"),
|
||||
"所属事业部": result.get("belong_unit_org_name"),
|
||||
"原归属品牌": "-".join(
|
||||
v for v in (result.get("belong_unit_org_name"), result.get("dept_org_four")) if v
|
||||
),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"离职日期": result.get("leaveoffice_time"),
|
||||
@@ -626,12 +694,15 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
params = parse_qs(urlparse(browser.url).query)
|
||||
task_id = params.get("taskId", [None])[0] or params.get("fkId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
# 重定向 URL 同时携带流程实例 processId(WeProcess.getActivityList 超期检查用);
|
||||
# WfActivity 接口返回不含 processId,processId 只能从这里拿,缺失不阻断主流程
|
||||
process_id = params.get("processId", [None])[0] or ""
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"无法从重定向 URL 提取 taskId 或 businessKey: {browser.url}")
|
||||
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
return {"taskId": task_id, "businessKey": business_key}
|
||||
logger.info("SSO 解析成功: taskId=%s, businessKey=%s, processId=%s", task_id, business_key, process_id or "无")
|
||||
return {"taskId": task_id, "businessKey": business_key, "processId": process_id}
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
@@ -649,7 +720,9 @@ def _fetch_doc_detail(browser, session, doc):
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
task_id = sso_params["taskId"]
|
||||
business_key = sso_params["businessKey"]
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s", task_id, business_key)
|
||||
process_id = sso_params.get("processId", "")
|
||||
logger.info("SSO 解析完成: taskId=%s, businessKey=%s, processId=%s",
|
||||
task_id, business_key, process_id or "无")
|
||||
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
@@ -661,7 +734,8 @@ def _fetch_doc_detail(browser, session, doc):
|
||||
# 需再调签署状态查询接口把真实状态写回,否则校验结果永远是"未完成"
|
||||
enrich_form_sign_status(form_data, session)
|
||||
|
||||
return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id, "formData": form_data}
|
||||
return {**doc, "taskId": task_id, "businessKey": business_key, "formId": form_id,
|
||||
"processId": process_id, "formData": form_data}
|
||||
|
||||
|
||||
def show_rpa_result_popup(page: ChromiumPage,
|
||||
@@ -1005,10 +1079,32 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
results = []
|
||||
overdue_list = [] # 超期名单:完善信息(操作人)完成超 3 天仍未走完的流程
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
|
||||
# 超期检查(独立于审批校验,失败不影响主流程):
|
||||
# 完善信息(操作人)endTime 非空且距今超 3 天 -> 记入超期名单
|
||||
process_id = doc_detail.get("processId") or ""
|
||||
if process_id:
|
||||
try:
|
||||
overdue = check_process_overdue(session, process_id)
|
||||
if overdue:
|
||||
# 名单字段:姓名/实际离职日期/原归属品牌(从表单解析取)
|
||||
info = parse_resign_e_sign_form(doc_detail.get("formData") or {})
|
||||
overdue_list.append({
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"staff_name": info.get("员工姓名") or "",
|
||||
"leaveoffice_time": info.get("离职日期") or "",
|
||||
"brand": info.get("原归属品牌") or "",
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
**overdue,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning("超期检查失败(不影响主流程): %s: %s", doc.get("title"), e)
|
||||
# 真实审批提交:仅当 APPROVE_ENABLED=True 时执行
|
||||
if APPROVE_ENABLED:
|
||||
# 未完成(电子签未全部完成)不自动处理("不管"),仅对"通过"提交真实审批
|
||||
@@ -1054,6 +1150,25 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
# 生成推送消息(本脚本不发送,交由流程/推送指令):
|
||||
# 仅"通过但提交失败"推送明细 + 汇总;通过/未完成/失败 只在汇总统计数量
|
||||
texts = build_push_summary(results, subject)
|
||||
# 超期名单:完善信息(操作人)完成超 3 天仍未走完的流程,单独分组推送
|
||||
# 名单字段:姓名 / 实际离职日期 / 原归属品牌
|
||||
if overdue_list:
|
||||
overdue_blocks = []
|
||||
for r in overdue_list:
|
||||
lines = [f"**🔹 {r['staff_name'] or r['title']}**({r['creator']})"]
|
||||
if r.get("brand"):
|
||||
lines.append(f"> 原归属品牌:{r['brand']}")
|
||||
if r.get("leaveoffice_time"):
|
||||
lines.append(f"> 实际离职日期:{r['leaveoffice_time']}")
|
||||
lines.append(f"> 完善信息完成时间:{r['endTime']}(已超期 {r['days']} 天)")
|
||||
if r.get("detail_url"):
|
||||
lines.append(f"> 详情页:[查看详情]({r['detail_url']})")
|
||||
overdue_blocks.append("\n\n".join(lines))
|
||||
texts.append({
|
||||
"title": f"【{subject}审批】超期名单(完善信息完成超 {OVERDUE_DAYS} 天)",
|
||||
"blocks": overdue_blocks,
|
||||
})
|
||||
logger.info("超期名单 %d 条,已加入推送", len(overdue_list))
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
|
||||
Reference in New Issue
Block a user