Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
607689b9e6 | ||
|
|
ef2a921765 | ||
|
|
193d5618be | ||
|
|
cd7d4fd118 | ||
|
|
ccdaa67787 | ||
|
|
1aaa159363 | ||
|
|
62426ef7bb | ||
|
|
4fb216cde0 | ||
|
|
bb56461c79 | ||
|
|
1fe0fae37f | ||
|
|
9b44723b35 | ||
|
|
36d8f7db2f | ||
|
|
1b7c2b0177 | ||
|
|
787234146b | ||
|
|
cda279fa66 | ||
|
|
f7759b7cee | ||
|
|
81222ad990 | ||
|
|
df6776caba | ||
|
|
febdd5b917 | ||
|
|
7279c9f71f | ||
|
|
ddd59345ed | ||
|
|
91b16ec6c3 | ||
|
|
88d84757ac | ||
|
|
9728fa40fe | ||
|
|
4a7b5e4f21 | ||
|
|
209427f685 | ||
|
|
4ea81cea91 | ||
|
|
067ba0abe1 | ||
|
|
5b673fcdc7 | ||
|
|
70c680a612 | ||
|
|
8b68d015c2 | ||
|
|
cfa976cac3 | ||
|
|
65d3b0952f | ||
|
|
870dbb9ce5 | ||
|
|
e9787ecb22 | ||
|
|
c0af291502 | ||
|
|
0b3dc0b9ae | ||
|
|
2f6b329745 | ||
|
|
3a1cccc0c6 | ||
|
|
7a2e45e7c4 | ||
|
|
b53e71c85d | ||
|
|
ca6637b69e | ||
|
|
253ebe7b0b | ||
|
|
3a6ef57592 | ||
|
|
04b5b33bb7 | ||
|
|
21d3654616 | ||
|
|
d181b4bfc8 | ||
|
|
6b36336ca6 | ||
|
|
458220ecbc | ||
|
|
a2c089499e | ||
|
|
c5355e16c2 | ||
|
|
0d144715a0 | ||
|
|
7cf783e7c6 | ||
|
|
982ef65530 | ||
|
|
73056ed32e | ||
|
|
351f791f1a | ||
|
|
79afd967a7 | ||
|
|
e6d94c95ba | ||
|
|
16d5865fef | ||
|
|
eba2bc3948 | ||
|
|
51ff6dbcc6 | ||
|
|
f6f41913dc | ||
|
|
a1acc6e63b | ||
|
|
b5b29d28d7 | ||
|
|
b2fa36bd35 | ||
|
|
6d57c7ed65 | ||
|
|
db855241c5 | ||
|
|
faddf24d11 | ||
|
|
19c832b244 | ||
|
|
92634cbf73 | ||
|
|
78078822d7 |
@@ -2,3 +2,4 @@
|
||||
# Python 字节码缓存
|
||||
__pycache__/
|
||||
*.pyc
|
||||
web/server.log
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""iAOP 本地账号认证与会话管理(issue #150 / PRD 8.2)。
|
||||
|
||||
子模块:
|
||||
- users:用户模型 + PBKDF2 密码哈希 + UserStore
|
||||
- session:HMAC 签名会话 token
|
||||
- postgres_users_schema:PG users 表 DDL(#30)
|
||||
- auth_api:认证 HTTP 端点 + 写操作守卫
|
||||
"""
|
||||
from .users import User, UserStore, hash_password, verify_password, VALID_ROLES
|
||||
from .session import issue_token, parse_token, SESSION_COOKIE
|
||||
from .auth_api import require_auth, can_write, AuthError, make_server
|
||||
|
||||
__all__ = [
|
||||
"User", "UserStore", "hash_password", "verify_password", "VALID_ROLES",
|
||||
"issue_token", "parse_token", "SESSION_COOKIE",
|
||||
"require_auth", "can_write", "AuthError", "make_server",
|
||||
]
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""④-1 认证 HTTP 端点 + 写操作守卫 —— issue #150 / PRD 8.2。
|
||||
|
||||
最小认证服务(标准库 http.server,零依赖),对外提供:
|
||||
|
||||
- POST /auth/login {username,password} → 200 {token,user}(Set-Cookie)/ 401
|
||||
- POST /auth/logout → 204(清 cookie)
|
||||
- GET /auth/me → 200 {user} / 401(凭 token 校验当前用户)
|
||||
|
||||
并导出 `require_auth` 装饰器与 `can_write` 守卫:未登录或非写角色
|
||||
(readonly)对写操作返回 403,落实 PRD 8.2「未登录不可访问写操作」。
|
||||
|
||||
可独立运行 `python -m core.auth.auth_api` 冒烟(默认 :8088,绑定 127.0.0.1)。
|
||||
生产由统一网关接入,本模块只负责认证语义。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Callable, Optional, Tuple
|
||||
|
||||
from .session import SESSION_COOKIE, issue_token, parse_token
|
||||
from .users import VALID_ROLES, UserStore
|
||||
|
||||
WRITE_ROLES = ("engineer", "admin") # 写操作允许的角色(rbac.py 语义)
|
||||
|
||||
|
||||
class AuthError(Exception):
|
||||
def __init__(self, status: int, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 守卫(供其它路由复用)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def require_auth(headers, store: UserStore) -> Tuple["object", None]:
|
||||
"""从请求头/cookie 取 token 校验,返回 (user, None) 或抛 AuthError(401)。"""
|
||||
token = _extract_token(headers)
|
||||
if not token:
|
||||
raise AuthError(HTTPStatus.UNAUTHORIZED, "未登录")
|
||||
sess = parse_token(token)
|
||||
if sess is None:
|
||||
raise AuthError(HTTPStatus.UNAUTHORIZED, "会话无效或已过期")
|
||||
user = store.get(sess.user_id)
|
||||
if user is None or not user.active:
|
||||
raise AuthError(HTTPStatus.UNAUTHORIZED, "账号不可用")
|
||||
return user, None
|
||||
|
||||
|
||||
def can_write(user) -> None:
|
||||
"""写操作角色守卫:非 engineer/admin 抛 AuthError(403)。"""
|
||||
if not hasattr(user, "role") or user.role not in WRITE_ROLES:
|
||||
raise AuthError(HTTPStatus.FORBIDDEN, "权限不足:当前角色不可执行写操作")
|
||||
|
||||
|
||||
def _extract_token(headers) -> Optional[str]:
|
||||
# 1) Authorization: Bearer <token>
|
||||
auth = headers.get("Authorization", "") if headers else ""
|
||||
if auth.startswith("Bearer "):
|
||||
return auth[7:].strip()
|
||||
# 2) Cookie: iaop_session=<token>
|
||||
cookie = headers.get("Cookie", "") if headers else ""
|
||||
for part in cookie.split(";"):
|
||||
if "=" in part:
|
||||
k, v = part.strip().split("=", 1)
|
||||
if k == SESSION_COOKIE:
|
||||
return v.strip()
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP 端点
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class AuthAPIHandler(BaseHTTPRequestHandler):
|
||||
"""认证端点。store 与 server 共享(见 make_server)。"""
|
||||
|
||||
server_version = "iAOP-AuthAPI/1.0"
|
||||
|
||||
def log_message(self, fmt, *args): # 安静日志
|
||||
pass
|
||||
|
||||
@property
|
||||
def store(self) -> UserStore:
|
||||
return self.server.user_store # type: ignore[attr-defined]
|
||||
|
||||
def _json(self, status: int, body: dict, *, set_cookie: Optional[str] = None,
|
||||
clear_cookie: bool = False) -> None:
|
||||
payload = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
if set_cookie:
|
||||
self.send_header("Set-Cookie", set_cookie)
|
||||
if clear_cookie:
|
||||
self.send_header("Set-Cookie",
|
||||
"%s=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax" % SESSION_COOKIE)
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def _read_json(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length", 0) or 0)
|
||||
if length <= 0 or length > 4096:
|
||||
return {}
|
||||
raw = self.rfile.read(length)
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return {}
|
||||
|
||||
def do_POST(self) -> None:
|
||||
try:
|
||||
if self.path == "/auth/login":
|
||||
self._handle_login()
|
||||
elif self.path == "/auth/logout":
|
||||
self._json(HTTPStatus.NO_CONTENT, {}, clear_cookie=True) if False else self._send_no_content()
|
||||
else:
|
||||
self._json(HTTPStatus.NOT_FOUND, {"error": "not found"})
|
||||
except AuthError as e:
|
||||
self._json(e.status, {"error": e.message})
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._json(HTTPStatus.INTERNAL_SERVER_ERROR, {"error": "server error: %s" % e})
|
||||
|
||||
def do_GET(self) -> None:
|
||||
try:
|
||||
if self.path == "/auth/me":
|
||||
user, _ = require_auth(self.headers, self.store)
|
||||
self._json(HTTPStatus.OK, {"user": user.to_public()})
|
||||
elif self.path == "/auth/health":
|
||||
self._json(HTTPStatus.OK, {"status": "ok"})
|
||||
else:
|
||||
self._json(HTTPStatus.NOT_FOUND, {"error": "not found"})
|
||||
except AuthError as e:
|
||||
self._json(e.status, {"error": e.message})
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._json(HTTPStatus.INTERNAL_SERVER_ERROR, {"error": "server error: %s" % e})
|
||||
|
||||
def _send_no_content(self) -> None:
|
||||
self.send_response(HTTPStatus.NO_CONTENT)
|
||||
self.send_header("Set-Cookie",
|
||||
"%s=; Max-Age=0; Path=/; HttpOnly; SameSite=Lax" % SESSION_COOKIE)
|
||||
self.end_headers()
|
||||
|
||||
def _handle_login(self) -> None:
|
||||
body = self._read_json()
|
||||
username = str(body.get("username", "")).strip()
|
||||
password = str(body.get("password", ""))
|
||||
if not username or not password:
|
||||
raise AuthError(HTTPStatus.BAD_REQUEST, "用户名和密码不能为空")
|
||||
user = self.store.authenticate(username, password)
|
||||
# 不区分"用户不存在/密码错",统一 401 防枚举
|
||||
if user is None:
|
||||
raise AuthError(HTTPStatus.UNAUTHORIZED, "用户名或密码错误")
|
||||
token = issue_token(user.id)
|
||||
cookie = "%s=%s; Path=/; Max-Age=%d; HttpOnly; SameSite=Lax" % (
|
||||
SESSION_COOKIE, token, 8 * 3600)
|
||||
self._json(HTTPStatus.OK, {"token": token, "user": user.to_public()},
|
||||
set_cookie=cookie)
|
||||
|
||||
|
||||
def make_server(store: UserStore, host: str = "127.0.0.1", port: int = 8088) -> ThreadingHTTPServer:
|
||||
srv = ThreadingHTTPServer((host, port), AuthAPIHandler)
|
||||
srv.user_store = store # type: ignore[attr-defined]
|
||||
return srv
|
||||
|
||||
|
||||
def _main() -> None:
|
||||
store = UserStore()
|
||||
store.ensure_bootstrap_admin("admin", "change-me-now") # 生产必须改密
|
||||
srv = make_server(store)
|
||||
print("iAOP AuthAPI on http://%s:%d (bootstrap admin: admin / change-me-now)"
|
||||
% srv.server_address)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_main()
|
||||
@@ -0,0 +1,170 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""FBA JWT 校验(Epic #159 · Phase 4)—— iAOP 业务接口接入 FBA 统一认证。
|
||||
|
||||
背景:认证/RBAC 基座已迁移到 FBA(fastapi-best-architecture)。
|
||||
FBA access token 为 HS256 JWT,claims:{sub: 用户ID, session_uuid, exp}。
|
||||
iAOP 后端为零依赖标准库实现,本模块用 hmac/hashlib 手写 HS256 校验,
|
||||
不引入 PyJWT。
|
||||
|
||||
用法(任意 iAOP HTTP 服务内):
|
||||
|
||||
from core.auth.fba_jwt import FbaAuth, FbaAuthError
|
||||
|
||||
fba = FbaAuth.from_env() # 读 FBA_TOKEN_SECRET_KEY / FBA_API_BASE
|
||||
if fba is not None: # 未配置 → 调用方走旧 core/auth 会话
|
||||
claims = fba.verify(authorization_header) # 无效抛 FbaAuthError(401)
|
||||
fba.require_perm(authorization_header, "iaop:admin") # 无权抛 403
|
||||
|
||||
权限码(按钮级):
|
||||
前端菜单播种时已写入 perms=iaop:<module>(deploy/fba/seed_iaop_menus.py)。
|
||||
require_perm() 携用户 token 回源 FBA GET /auth/codes 校验(带 TTL 缓存,
|
||||
避免每请求打满 FBA)。超管在 FBA 侧自动拥有全部权限码。
|
||||
|
||||
双轨过渡:FBA_TOKEN_SECRET_KEY 未配置时 from_env() 返回 None,
|
||||
业务接口应继续接受旧 core/auth HMAC 会话(见 auth_api.require_auth),
|
||||
待 Phase 5 收尾时再移除旧轨。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from http import HTTPStatus
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class FbaAuthError(Exception):
|
||||
"""FBA 认证/授权失败。status: 401 未认证,403 无权限,503 FBA 不可达。"""
|
||||
|
||||
def __init__(self, status: int, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
def _b64url_decode(seg: str) -> bytes:
|
||||
pad = "=" * (-len(seg) % 4)
|
||||
return base64.urlsafe_b64decode(seg + pad)
|
||||
|
||||
|
||||
def _b64url_encode(raw: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||
|
||||
|
||||
class FbaAuth:
|
||||
"""FBA JWT 校验器(HS256,与 FBA backend/common/security/jwt.py 对齐)。"""
|
||||
|
||||
def __init__(self, secret_key: str, api_base: str = "http://127.0.0.1:8001/api/v1",
|
||||
perm_cache_ttl: int = 300) -> None:
|
||||
if not secret_key:
|
||||
raise ValueError("secret_key 不能为空")
|
||||
self._secret = secret_key.encode()
|
||||
self.api_base = api_base.rstrip("/")
|
||||
self.perm_cache_ttl = perm_cache_ttl
|
||||
# token → (expires_at, codes set);简单内存缓存,进程级
|
||||
self._perm_cache: dict[str, tuple[float, set]] = {}
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> Optional["FbaAuth"]:
|
||||
"""读环境变量构造;未配置 FBA_TOKEN_SECRET_KEY 时返回 None(降级旧轨)。"""
|
||||
secret = os.environ.get("FBA_TOKEN_SECRET_KEY", "").strip()
|
||||
if not secret:
|
||||
return None
|
||||
return cls(secret, os.environ.get(
|
||||
"FBA_API_BASE", "http://127.0.0.1:8001/api/v1"))
|
||||
|
||||
# ------------------------------------------------------------------ JWT
|
||||
def verify(self, authorization: str) -> dict:
|
||||
"""校验 'Bearer <token>',返回 claims;失败抛 FbaAuthError(401)。"""
|
||||
token = self._extract_bearer(authorization)
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3:
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 格式无效")
|
||||
signing_input = (parts[0] + "." + parts[1]).encode()
|
||||
expect = _b64url_encode(hmac.new(self._secret, signing_input,
|
||||
hashlib.sha256).digest())
|
||||
if not hmac.compare_digest(expect, parts[2]):
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 签名无效")
|
||||
try:
|
||||
header = json.loads(_b64url_decode(parts[0]))
|
||||
payload = json.loads(_b64url_decode(parts[1]))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 解析失败")
|
||||
if header.get("alg") != "HS256":
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 算法不受支持")
|
||||
if not payload.get("sub") or not payload.get("session_uuid"):
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 缺少必要字段")
|
||||
exp = payload.get("exp")
|
||||
if not isinstance(exp, (int, float)) or exp < time.time():
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 已过期")
|
||||
return payload
|
||||
|
||||
@staticmethod
|
||||
def _extract_bearer(authorization: str) -> str:
|
||||
if not authorization:
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "未携带认证信息")
|
||||
parts = authorization.split(None, 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "认证头格式应为 Bearer <token>")
|
||||
return parts[1].strip()
|
||||
|
||||
# ------------------------------------------------------------- 权限码
|
||||
def get_codes(self, authorization: str) -> set:
|
||||
"""携 token 回源 FBA /auth/codes 取权限码集合(带 TTL 缓存)。"""
|
||||
token = self._extract_bearer(authorization)
|
||||
now = time.time()
|
||||
hit = self._perm_cache.get(token)
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
req = urllib.request.Request(
|
||||
self.api_base + "/auth/codes",
|
||||
headers={"Authorization": f"Bearer {token}"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=5) as r:
|
||||
d = json.loads(r.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code in (401, 403):
|
||||
raise FbaAuthError(HTTPStatus.UNAUTHORIZED, "Token 已失效")
|
||||
raise FbaAuthError(HTTPStatus.SERVICE_UNAVAILABLE,
|
||||
f"FBA 权限码查询失败:HTTP {e.code}")
|
||||
except OSError:
|
||||
raise FbaAuthError(HTTPStatus.SERVICE_UNAVAILABLE, "FBA 服务不可达")
|
||||
if d.get("code") != 200 or not isinstance(d.get("data"), list):
|
||||
raise FbaAuthError(HTTPStatus.SERVICE_UNAVAILABLE, "FBA 权限码响应异常")
|
||||
codes = set(d["data"])
|
||||
self._perm_cache[token] = (now + self.perm_cache_ttl, codes)
|
||||
# 简单清理过期缓存项
|
||||
for k in [k for k, v in self._perm_cache.items() if v[0] <= now]:
|
||||
self._perm_cache.pop(k, None)
|
||||
return codes
|
||||
|
||||
def require_perm(self, authorization: str, perm: str) -> dict:
|
||||
"""校验 token + 权限码;返回 claims。401/403 抛 FbaAuthError。"""
|
||||
claims = self.verify(authorization)
|
||||
codes = self.get_codes(authorization)
|
||||
if perm not in codes:
|
||||
raise FbaAuthError(HTTPStatus.FORBIDDEN, f"缺少权限:{perm}")
|
||||
return claims
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 自测试用:生成与 FBA 同构的 HS256 token(tests 使用)
|
||||
# ---------------------------------------------------------------------------
|
||||
def make_test_token(secret: str, user_id: int = 1,
|
||||
session_uuid: str = "test-session",
|
||||
exp_offset: int = 3600) -> str:
|
||||
header = _b64url_encode(json.dumps(
|
||||
{"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
|
||||
payload = _b64url_encode(json.dumps({
|
||||
"sub": str(user_id), "session_uuid": session_uuid,
|
||||
"exp": time.time() + exp_offset,
|
||||
}, separators=(",", ":")).encode())
|
||||
sig = _b64url_encode(hmac.new(secret.encode(),
|
||||
f"{header}.{payload}".encode(),
|
||||
hashlib.sha256).digest())
|
||||
return f"{header}.{payload}.{sig}"
|
||||
@@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""④-1 PostgreSQL users 表 DDL + 映射 —— issue #150 / #30 / PRD 8.2。
|
||||
|
||||
定义本地账号在 PostgreSQL 中的存储结构(#30 users 表 schema),并提供
|
||||
`UserStore` 与 PG 之间的映射。DDL 仅用标准库拼装(无 psycopg2 依赖),
|
||||
实际接库时上层注入连接即可。
|
||||
|
||||
表结构(对齐 core/data-bus/postgres_schema.py 的命名风格):
|
||||
|
||||
users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username VARCHAR(64) UNIQUE NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL, -- pbkdf2_sha256$<iter>$<salt>$<hash>
|
||||
role VARCHAR(16) NOT NULL DEFAULT 'readonly', -- readonly/engineer/admin
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_login_at TIMESTAMPTZ
|
||||
)
|
||||
|
||||
索引:username 唯一索引(登录走 username);role 普通索引(用户管理筛选)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from .users import User, VALID_ROLES
|
||||
|
||||
USERS_TABLE_DDL = """CREATE TABLE IF NOT EXISTS users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username VARCHAR(64) UNIQUE NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
role VARCHAR(16) NOT NULL DEFAULT 'readonly',
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_login_at TIMESTAMPTZ,
|
||||
CONSTRAINT users_role_chk CHECK (role IN ('readonly','engineer','admin'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);
|
||||
"""
|
||||
|
||||
|
||||
def row_to_user(row: Any) -> User:
|
||||
"""PG 行(dict/tuple-like)→ User。row 需含 keys: id/username/password_hash/role/active/created_at/last_login_at。"""
|
||||
def g(k, default=None):
|
||||
if isinstance(row, dict):
|
||||
return row.get(k, default)
|
||||
return getattr(row, k, default)
|
||||
created = g("created_at")
|
||||
last = g("last_login_at")
|
||||
# PG TIMESTAMPTZ → epoch(若为 datetime 有 timestamp())
|
||||
def to_epoch(v):
|
||||
if v is None:
|
||||
return None
|
||||
if hasattr(v, "timestamp"):
|
||||
return v.timestamp()
|
||||
return v
|
||||
return User(
|
||||
id=int(g("id")),
|
||||
username=str(g("username")),
|
||||
password_hash=str(g("password_hash")),
|
||||
role=str(g("role", "readonly")) or "readonly",
|
||||
active=bool(g("active", True)),
|
||||
created_at=to_epoch(created) or 0.0,
|
||||
last_login_at=to_epoch(last),
|
||||
)
|
||||
|
||||
|
||||
def user_to_row(user: User) -> Dict[str, Any]:
|
||||
"""User → PG 列字典(不含 id,用于 INSERT;UPDATE 时按 id 定位)。"""
|
||||
return {
|
||||
"username": user.username,
|
||||
"password_hash": user.password_hash,
|
||||
"role": user.role,
|
||||
"active": user.active,
|
||||
}
|
||||
|
||||
|
||||
def validate_role(role: str) -> str:
|
||||
if role not in VALID_ROLES:
|
||||
raise ValueError("role must be one of %r" % (VALID_ROLES,))
|
||||
return role
|
||||
|
||||
|
||||
__all__ = ["USERS_TABLE_DDL", "row_to_user", "user_to_row", "validate_role"]
|
||||
@@ -0,0 +1,97 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""④-1 会话管理:登录 token 签发/校验 —— issue #150 / PRD 8.2。
|
||||
|
||||
无状态会话令牌(self-contained token),服务端无需存 session 表即可校验,
|
||||
适合配置台这种轻量场景:
|
||||
|
||||
- 令牌格式:`<user_id>.<expire_epoch>.<hmac_sha256_sig>`(base64url 友好);
|
||||
- 签名密钥来自部署环境(`IAOP_AUTH_SECRET`),未配置时随机生成(进程内有效,
|
||||
重启失效——生产必须配置固定密钥以支持多副本);
|
||||
- 校验恒定时间(`hmac.compare_digest`),过期/签名不符一律判无效;
|
||||
- `SESSION_COOKIE` 为会话 cookie 名(`iaop_session`,HttpOnly + SameSite=Lax)。
|
||||
|
||||
PRD 8.2 验收口径:未携带有效 token 的请求,写操作一律拒绝(见 auth_api.py)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hmac
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Tuple
|
||||
|
||||
SESSION_COOKIE = "iaop_session"
|
||||
DEFAULT_TTL = 8 * 3600 # 8 小时
|
||||
HASH_BYTES = 32
|
||||
|
||||
|
||||
def _b64url(b: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def _b64url_decode(s: str) -> bytes:
|
||||
pad = "=" * (-len(s) % 4)
|
||||
return base64.urlsafe_b64decode(s + pad)
|
||||
|
||||
|
||||
def _secret() -> bytes:
|
||||
"""会话签名密钥。优先环境变量,否则进程内随机(重启失效)。"""
|
||||
env = os.environ.get("IAOP_AUTH_SECRET")
|
||||
if env:
|
||||
return env.encode("utf-8")
|
||||
if not hasattr(_secret, "_fallback"):
|
||||
_secret._fallback = os.urandom(32) # type: ignore[attr-defined]
|
||||
return _secret._fallback # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def _sign(payload: bytes) -> str:
|
||||
sig = hmac.new(_secret(), payload, hashlib.sha256).digest()
|
||||
return _b64url(sig)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Session:
|
||||
user_id: int
|
||||
expire_at: int
|
||||
|
||||
@property
|
||||
def expired(self) -> bool:
|
||||
return time.time() >= self.expire_at
|
||||
|
||||
|
||||
def issue_token(user_id: int, *, ttl: int = DEFAULT_TTL) -> str:
|
||||
"""为 user_id 签发会话 token。"""
|
||||
if not isinstance(user_id, int) or user_id <= 0:
|
||||
raise ValueError("user_id must be a positive int")
|
||||
expire_at = int(time.time()) + ttl
|
||||
payload = "%d.%d" % (user_id, expire_at)
|
||||
sig = _sign(payload.encode("ascii"))
|
||||
return payload + "." + sig
|
||||
|
||||
|
||||
def parse_token(token: str) -> Optional[Session]:
|
||||
"""校验 token,成功返回 Session,失败(格式/签名/过期)返回 None。"""
|
||||
if not isinstance(token, str):
|
||||
return None
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3:
|
||||
return None
|
||||
uid_s, exp_s, sig = parts
|
||||
payload = (uid_s + "." + exp_s).encode("ascii")
|
||||
expected = _sign(payload)
|
||||
# 恒定时间比较签名
|
||||
if not hmac.compare_digest(expected, sig):
|
||||
return None
|
||||
try:
|
||||
uid = int(uid_s)
|
||||
expire_at = int(exp_s)
|
||||
except ValueError:
|
||||
return None
|
||||
if uid <= 0:
|
||||
return None
|
||||
sess = Session(user_id=uid, expire_at=expire_at)
|
||||
if sess.expired:
|
||||
return None
|
||||
return sess
|
||||
@@ -0,0 +1 @@
|
||||
# core/auth tests package
|
||||
@@ -0,0 +1,132 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""issue #150 本地账号认证单元测试(pytest / 纯标准库亦可 unittest 跑)。
|
||||
|
||||
覆盖:
|
||||
- 密码哈希:hash/verify、恒定时间、盐随机(同密码两次哈希不同)
|
||||
- UserStore:create/authenticate/角色校验/重复用户名/禁用账号/改密
|
||||
- session:签发/校验/过期/篡改签名/伪造
|
||||
- 守卫:require_auth 未登录 401、can_write readonly 403
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
|
||||
# 让 tests 能 import core.auth(仓库根在 ../../.. )
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from core.auth import (UserStore, hash_password, verify_password,
|
||||
issue_token, parse_token, require_auth, can_write, AuthError)
|
||||
from core.auth.users import User
|
||||
|
||||
|
||||
class TestPasswordHash(unittest.TestCase):
|
||||
def test_hash_then_verify(self):
|
||||
h = hash_password("S3cretPwd!")
|
||||
self.assertTrue(h.startswith("pbkdf2_sha256$"))
|
||||
self.assertTrue(verify_password("S3cretPwd!", h))
|
||||
self.assertFalse(verify_password("wrong", h))
|
||||
|
||||
def test_salt_random(self):
|
||||
# 同一密码两次哈希应不同(盐随机)
|
||||
self.assertNotEqual(hash_password("S3cretPwd!"), hash_password("S3cretPwd!"))
|
||||
|
||||
def test_tampered_store_rejected(self):
|
||||
h = hash_password("S3cretPwd!")
|
||||
# 篡改 hash 段
|
||||
scheme, it, salt, _ = h.split("$")
|
||||
self.assertFalse(verify_password("S3cretPwd!", "%s$%s$%s$AAAA" % (scheme, it, salt)))
|
||||
|
||||
def test_empty_password(self):
|
||||
with self.assertRaises(ValueError):
|
||||
hash_password("")
|
||||
|
||||
|
||||
class TestUserStore(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.store = UserStore()
|
||||
self.user = self.store.create("alice", "password1", role="engineer")
|
||||
|
||||
def test_authenticate_success(self):
|
||||
u = self.store.authenticate("alice", "password1")
|
||||
self.assertIsNotNone(u)
|
||||
self.assertEqual(u.id, self.user.id)
|
||||
self.assertIsNotNone(u.last_login_at)
|
||||
|
||||
def test_authenticate_wrong_password(self):
|
||||
self.assertIsNone(self.store.authenticate("alice", "nope"))
|
||||
|
||||
def test_authenticate_unknown_user(self):
|
||||
self.assertIsNone(self.store.authenticate("bob", "password1"))
|
||||
|
||||
def test_duplicate_username(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.store.create("alice", "password2")
|
||||
|
||||
def test_short_password(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.store.create("carol", "123")
|
||||
|
||||
def test_invalid_role(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.store.create("dave", "password1", role="superuser")
|
||||
|
||||
def test_deactivate_blocks_login(self):
|
||||
self.store.set_active(self.user.id, False)
|
||||
self.assertIsNone(self.store.authenticate("alice", "password1"))
|
||||
|
||||
def test_set_password(self):
|
||||
self.store.set_password(self.user.id, "brand-new-pwd")
|
||||
self.assertIsNone(self.store.authenticate("alice", "password1"))
|
||||
self.assertIsNotNone(self.store.authenticate("alice", "brand-new-pwd"))
|
||||
|
||||
def test_set_role(self):
|
||||
self.store.set_role(self.user.id, "admin")
|
||||
self.assertEqual(self.store.get(self.user.id).role, "admin")
|
||||
|
||||
|
||||
class TestSession(unittest.TestCase):
|
||||
def test_issue_and_parse(self):
|
||||
tok = issue_token(42)
|
||||
sess = parse_token(tok)
|
||||
self.assertIsNotNone(sess)
|
||||
self.assertEqual(sess.user_id, 42)
|
||||
|
||||
def test_expired(self):
|
||||
tok = issue_token(1, ttl=-1) # 已过期
|
||||
self.assertIsNone(parse_token(tok))
|
||||
|
||||
def test_tampered_sig(self):
|
||||
tok = issue_token(1)
|
||||
uid, exp, sig = tok.split(".")
|
||||
bad = ".".join([uid, exp, "A" * len(sig)])
|
||||
self.assertIsNone(parse_token(bad))
|
||||
|
||||
def test_garbage(self):
|
||||
self.assertIsNone(parse_token("not.a.token"))
|
||||
self.assertIsNone(parse_token(""))
|
||||
|
||||
|
||||
class TestGuards(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.store = UserStore()
|
||||
self.admin = self.store.create("admin", "password1", role="admin")
|
||||
self.viewer = self.store.create("viewer", "password1", role="readonly")
|
||||
|
||||
def test_require_auth_no_token(self):
|
||||
with self.assertRaises(AuthError):
|
||||
require_auth({}, self.store)
|
||||
|
||||
def test_can_write_viewer_forbidden(self):
|
||||
with self.assertRaises(AuthError):
|
||||
can_write(self.viewer)
|
||||
|
||||
def test_can_write_admin_ok(self):
|
||||
can_write(self.admin) # 不抛即通过
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,77 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""FBA JWT 校验模块单元测试(Epic #159 · Phase 4)。
|
||||
|
||||
运行:python -m unittest core.auth.tests.test_fba_jwt -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from core.auth.fba_jwt import FbaAuth, FbaAuthError, make_test_token
|
||||
|
||||
SECRET = "unit-test-secret-key"
|
||||
|
||||
|
||||
class FbaJwtTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.auth = FbaAuth(SECRET)
|
||||
|
||||
def test_verify_ok(self):
|
||||
token = make_test_token(SECRET, user_id=42, session_uuid="s-1")
|
||||
claims = self.auth.verify(f"Bearer {token}")
|
||||
self.assertEqual(claims["sub"], "42")
|
||||
self.assertEqual(claims["session_uuid"], "s-1")
|
||||
|
||||
def test_verify_expired(self):
|
||||
token = make_test_token(SECRET, exp_offset=-10)
|
||||
with self.assertRaises(FbaAuthError) as ctx:
|
||||
self.auth.verify(f"Bearer {token}")
|
||||
self.assertEqual(ctx.exception.status, 401)
|
||||
self.assertIn("过期", ctx.exception.message)
|
||||
|
||||
def test_verify_bad_signature(self):
|
||||
token = make_test_token("other-secret")
|
||||
with self.assertRaises(FbaAuthError) as ctx:
|
||||
self.auth.verify(f"Bearer {token}")
|
||||
self.assertEqual(ctx.exception.status, 401)
|
||||
|
||||
def test_verify_missing_bearer(self):
|
||||
for bad in ("", "token-abc", "Basic abc"):
|
||||
with self.assertRaises(FbaAuthError) as ctx:
|
||||
self.auth.verify(bad)
|
||||
self.assertEqual(ctx.exception.status, 401)
|
||||
|
||||
def test_verify_malformed(self):
|
||||
with self.assertRaises(FbaAuthError):
|
||||
self.auth.verify("Bearer not-a-jwt")
|
||||
|
||||
def test_missing_fields(self):
|
||||
# 无 session_uuid 的 token(签名正确但字段缺失)
|
||||
import base64, hashlib, hmac, json, time
|
||||
enc = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=").decode()
|
||||
header = enc(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
|
||||
payload = enc(json.dumps({"sub": "1", "exp": time.time() + 60}).encode())
|
||||
sig = enc(hmac.new(SECRET.encode(), f"{header}.{payload}".encode(),
|
||||
hashlib.sha256).digest())
|
||||
with self.assertRaises(FbaAuthError) as ctx:
|
||||
self.auth.verify(f"Bearer {header}.{payload}.{sig}")
|
||||
self.assertIn("字段", ctx.exception.message)
|
||||
|
||||
def test_from_env_absent(self):
|
||||
os.environ.pop("FBA_TOKEN_SECRET_KEY", None)
|
||||
self.assertIsNone(FbaAuth.from_env())
|
||||
|
||||
def test_from_env_present(self):
|
||||
os.environ["FBA_TOKEN_SECRET_KEY"] = SECRET
|
||||
try:
|
||||
auth = FbaAuth.from_env()
|
||||
self.assertIsNotNone(auth)
|
||||
token = make_test_token(SECRET)
|
||||
self.assertEqual(auth.verify(f"Bearer {token}")["sub"], "1")
|
||||
finally:
|
||||
os.environ.pop("FBA_TOKEN_SECRET_KEY", None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,201 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""④-1 本地账号认证:用户模型 + 密码哈希 —— issue #150 / PRD 8.2。
|
||||
|
||||
登录认证是写操作的入口闸门(PRD 8.2「未登录不可访问写操作」)。本模块提供:
|
||||
|
||||
- 密码哈希:`PBKDF2-HMAC-SHA256`(hashlib 标准库,盐 16B、迭代 200000,
|
||||
与 Django/OWASP 2023 推荐量级一致),存储形如 `pbkdf2_sha256$<iter>$<salt>$<hash>`;
|
||||
- 用户模型:`User`(id/username/password_hash/role/active),角色对齐
|
||||
`core/template-console/rbac.py` 的三级(readonly/engineer/admin);
|
||||
- `UserStore`:内存/可持久化用户仓,提供 create / authenticate / get / list。
|
||||
|
||||
数据可落 PostgreSQL users 表(#30 schema,见 `postgres_users_schema.py`);
|
||||
本模块零运行时依赖(仅标准库),`UserStore` 默认内存,接入 PG 时实现
|
||||
`PgUserBackend` 即可,上层 API 不变。
|
||||
|
||||
安全要点:
|
||||
- 永不存储明文密码;`authenticate` 用恒定时间比较防时序侧信道(`hmac.compare_digest`);
|
||||
- 内置初始管理员账号仅在首次初始化时创建,生产部署必须改密。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 常量(与 #30 users 表 schema 对齐)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
PBKDF2_ALGO = "sha256"
|
||||
PBKDF2_ITER = 200_000 # OWASP 2023 推荐(SHA256)
|
||||
SALT_BYTES = 16
|
||||
HASH_BYTES = 32
|
||||
HASH_SCHEME = "pbkdf2_sha256" # 存储前缀,便于将来升级算法
|
||||
|
||||
# 角色与 rbac.py 一致(readonly/engineer/admin)
|
||||
VALID_ROLES = ("readonly", "engineer", "admin")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 密码哈希
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def hash_password(password: str, *, iterations: int = PBKDF2_ITER,
|
||||
salt: Optional[bytes] = None) -> str:
|
||||
"""返回 `scheme$iter$<salt-b64>$<hash-b64>` 形式的密码哈希。"""
|
||||
if not isinstance(password, str) or not password:
|
||||
raise ValueError("password must be a non-empty string")
|
||||
if iterations < 100_000:
|
||||
raise ValueError("iterations must be >= 100000")
|
||||
raw_salt = salt if salt is not None else os.urandom(SALT_BYTES)
|
||||
if len(raw_salt) != SALT_BYTES:
|
||||
raise ValueError("salt must be %d bytes" % SALT_BYTES)
|
||||
dk = hashlib.pbkdf2_hmac(PBKDF2_ALGO, password.encode("utf-8"),
|
||||
raw_salt, iterations, HASH_BYTES)
|
||||
return "%s$%d$%s$%s" % (HASH_SCHEME, iterations,
|
||||
base64.b64encode(raw_salt).decode("ascii"),
|
||||
base64.b64encode(dk).decode("ascii"))
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
"""恒定时间校验密码。`stored` 为 `hash_password` 的输出。"""
|
||||
try:
|
||||
scheme, iter_s, salt_b64, hash_b64 = stored.split("$")
|
||||
if scheme != HASH_SCHEME:
|
||||
return False
|
||||
iterations = int(iter_s)
|
||||
raw_salt = base64.b64decode(salt_b64)
|
||||
expected = base64.b64decode(hash_b64)
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
dk = hashlib.pbkdf2_hmac(PBKDF2_ALGO, password.encode("utf-8"),
|
||||
raw_salt, iterations, len(expected))
|
||||
return hmac.compare_digest(dk, expected) # 恒定时间比较,防时序侧信道
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 用户模型
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass
|
||||
class User:
|
||||
id: int
|
||||
username: str
|
||||
password_hash: str
|
||||
role: str = "readonly" # readonly/engineer/admin
|
||||
active: bool = True
|
||||
created_at: float = field(default_factory=time.time)
|
||||
last_login_at: Optional[float] = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.role not in VALID_ROLES:
|
||||
raise ValueError("role must be one of %r" % (VALID_ROLES,))
|
||||
|
||||
@property
|
||||
def is_admin(self) -> bool:
|
||||
return self.role == "admin"
|
||||
|
||||
def to_public(self) -> Dict:
|
||||
"""对外暴露(不含 password_hash)。"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"role": self.role,
|
||||
"active": self.active,
|
||||
"created_at": self.created_at,
|
||||
"last_login_at": self.last_login_at,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 用户仓
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class UserStore:
|
||||
"""内存用户仓(默认)。接 PostgreSQL 时换 PgUserBackend,API 不变。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._users: Dict[int, User] = {}
|
||||
self._by_name: Dict[str, int] = {}
|
||||
self._next_id = 1
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def create(self, username: str, password: str, *, role: str = "readonly",
|
||||
active: bool = True) -> User:
|
||||
username = (username or "").strip()
|
||||
if not username or len(username) > 64:
|
||||
raise ValueError("username must be 1..64 chars")
|
||||
if len(password) < 8:
|
||||
raise ValueError("password must be >= 8 chars")
|
||||
with self._lock:
|
||||
if username in self._by_name:
|
||||
raise ValueError("username already exists: %s" % username)
|
||||
uid = self._next_id
|
||||
user = User(id=uid, username=username,
|
||||
password_hash=hash_password(password), role=role, active=active)
|
||||
self._users[uid] = user
|
||||
self._by_name[username] = uid
|
||||
self._next_id += 1
|
||||
return user
|
||||
|
||||
def set_password(self, user_id: int, new_password: str) -> None:
|
||||
if len(new_password) < 8:
|
||||
raise ValueError("password must be >= 8 chars")
|
||||
with self._lock:
|
||||
user = self._users.get(user_id)
|
||||
if user is None:
|
||||
raise KeyError("user not found: %r" % (user_id,))
|
||||
user.password_hash = hash_password(new_password)
|
||||
|
||||
def set_role(self, user_id: int, role: str) -> None:
|
||||
if role not in VALID_ROLES:
|
||||
raise ValueError("role must be one of %r" % (VALID_ROLES,))
|
||||
with self._lock:
|
||||
user = self._users.get(user_id)
|
||||
if user is None:
|
||||
raise KeyError("user not found: %r" % (user_id,))
|
||||
user.role = role
|
||||
|
||||
def set_active(self, user_id: int, active: bool) -> None:
|
||||
with self._lock:
|
||||
user = self._users.get(user_id)
|
||||
if user is None:
|
||||
raise KeyError("user not found: %r" % (user_id,))
|
||||
user.active = active
|
||||
|
||||
def get(self, user_id: int) -> Optional[User]:
|
||||
return self._users.get(user_id)
|
||||
|
||||
def get_by_name(self, username: str) -> Optional[User]:
|
||||
uid = self._by_name.get((username or "").strip())
|
||||
return self._users.get(uid) if uid is not None else None
|
||||
|
||||
def list(self) -> List[User]:
|
||||
return [self._users[i] for i in sorted(self._users)]
|
||||
|
||||
def authenticate(self, username: str, password: str) -> Optional[User]:
|
||||
"""成功返回 User(并刷新 last_login_at),失败返回 None。
|
||||
|
||||
失败原因不区分"用户不存在"与"密码错",避免用户名枚举。
|
||||
"""
|
||||
user = self.get_by_name(username)
|
||||
if user is None or not user.active:
|
||||
return None
|
||||
if not verify_password(password, user.password_hash):
|
||||
return None
|
||||
with self._lock:
|
||||
user.last_login_at = time.time()
|
||||
return user
|
||||
|
||||
def ensure_bootstrap_admin(self, username: str, password: str) -> User:
|
||||
"""首次初始化管理员账号(已存在则返回,不改密)。"""
|
||||
existing = self.get_by_name(username)
|
||||
if existing is not None:
|
||||
return existing
|
||||
return self.create(username, password, role="admin")
|
||||
@@ -37,8 +37,9 @@ from .layout import ( # 复用 #50 已定义的布局模型与常量
|
||||
# 主题 token(PRD 5.5「配置点:主题」dark / light 两套调色)
|
||||
# ---------------------------------------------------------------------------
|
||||
# 工业驾驶舱约定配色:dark 偏深蓝底 + 青绿强调(车间大屏常用);
|
||||
# light 偏白底 + 蓝色强调(白天值班室)。前端按这些 CSS 变量渲染,
|
||||
# 切换主题 = 切一套变量,组件代码不动。
|
||||
# light 采用 Ant Design 5 官方色板(2026-08 全站 Ant Design Pro 风格重构:
|
||||
# 白底卡片 + #1677ff 主色 + 灰底 #f0f2f5,与门户/配置台/管理台统一)。
|
||||
# 前端按这些 CSS 变量渲染,切换主题 = 切一套变量,组件代码不动。
|
||||
THEME_TOKENS: Dict[str, Dict[str, str]] = {
|
||||
"dark": {
|
||||
"--cockpit-bg": "#0b1220",
|
||||
@@ -50,13 +51,13 @@ THEME_TOKENS: Dict[str, Dict[str, str]] = {
|
||||
"--cockpit-grid-line": "rgba(255,255,255,0.06)",
|
||||
},
|
||||
"light": {
|
||||
"--cockpit-bg": "#f5f7fb",
|
||||
"--cockpit-surface": "#ffffff",
|
||||
"--cockpit-fg": "#1f2d3d",
|
||||
"--cockpit-fg-muted": "#6b7c93",
|
||||
"--cockpit-accent": "#2f7af2", # 蓝
|
||||
"--cockpit-warn": "#e08600",
|
||||
"--cockpit-grid-line": "rgba(0,0,0,0.06)",
|
||||
"--cockpit-bg": "#f0f2f5", # AntD colorBgLayout
|
||||
"--cockpit-surface": "#ffffff", # AntD colorBgContainer
|
||||
"--cockpit-fg": "rgba(0,0,0,0.88)", # AntD colorText
|
||||
"--cockpit-fg-muted": "rgba(0,0,0,0.45)", # AntD colorTextTertiary
|
||||
"--cockpit-accent": "#1677ff", # AntD 5 主色蓝(KPI / 趋势主线)
|
||||
"--cockpit-warn": "#faad14", # AntD warning(告警强调)
|
||||
"--cockpit-grid-line": "rgba(5,5,5,0.06)", # AntD colorSplit
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# iAOP · FBA 基础设施部署(Epic #159 · Phase 0)
|
||||
|
||||
将 [fastapi-best-architecture](https://github.com/fastapi-practices/fastapi-best-architecture)
|
||||
(下称 FBA)作为 iAOP 的统一认证 / 用户角色权限基座,以 Docker 方式与现有 iAOP
|
||||
服务并行部署,由宿主机现有 nginx 以 `/fba/` 前缀统一反代。
|
||||
|
||||
## 架构位置
|
||||
|
||||
```
|
||||
浏览器
|
||||
│ http://39.101.182.167:8090
|
||||
▼
|
||||
宿主机 nginx(现有 iAOP 站点)
|
||||
├── / → iAOP 前端(web/ 静态)
|
||||
├── /api/v1/ → iAOP 后端(现有 FastAPI,业务接口)
|
||||
└── /fba/ → 127.0.0.1:8001 → fba_server(FBA 后端,认证/RBAC)
|
||||
├── fba_postgres(PG16)
|
||||
└── fba_redis
|
||||
```
|
||||
|
||||
> iAOP 自身也使用 `/api/v1` 前缀,因此 FBA 必须通过 `/fba/` 前缀隔离,
|
||||
> 两者不能共用路径。
|
||||
|
||||
## 前置条件
|
||||
|
||||
1. 服务器已安装 Docker 与 Docker Compose 插件(`docker compose version` 可查)。
|
||||
2. 获取 FBA 源码,放到本仓库同级目录:
|
||||
|
||||
```bash
|
||||
cd /opt/apps # 假设 iAOP 在 /opt/apps/iAOP
|
||||
git clone https://github.com/fastapi-practices/fastapi-best-architecture fba-backend
|
||||
```
|
||||
|
||||
若放在其他位置,修改 `compose.env` 中的 `FBA_SRC`。
|
||||
|
||||
## 部署步骤
|
||||
|
||||
```bash
|
||||
cd /opt/apps/iAOP/deploy/fba
|
||||
|
||||
# 1. 修改密钥与密码(生产必做)
|
||||
# - compose.env: FBA_PG_PASSWORD
|
||||
# - fba.env: DATABASE_PASSWORD(与上一致)、TOKEN_SECRET_KEY
|
||||
python3 -c "import secrets; print(secrets.token_urlsafe(32))" # 生成 TOKEN_SECRET_KEY
|
||||
|
||||
# 2. 构建并启动
|
||||
docker compose --env-file compose.env up -d --build
|
||||
|
||||
# 3. 初始化数据库表结构 + 内置数据(菜单/角色/管理员)
|
||||
docker exec -it fba_server fba init
|
||||
# 若 fba 命令不可用,改用:docker exec -it fba_server python backend/cli.py init
|
||||
|
||||
# 4. 验证服务
|
||||
curl -s http://127.0.0.1:8001/api/v1/auth/captcha | head -c 200
|
||||
|
||||
# 5. 合并 nginx 片段(见 nginx-fba.conf 头部说明),然后 reload
|
||||
nginx -t && nginx -s reload
|
||||
|
||||
# 6. 通过外部入口验证
|
||||
curl -s http://39.101.182.167:8090/fba/api/v1/auth/captcha | head -c 200
|
||||
```
|
||||
|
||||
FBA 默认管理员账号:`admin / 123456`(登录后请立即修改)。
|
||||
|
||||
## 常用运维命令
|
||||
|
||||
```bash
|
||||
docker compose --env-file compose.env logs -f fba_server # 看日志
|
||||
docker compose --env-file compose.env restart fba_server # 重启
|
||||
docker compose --env-file compose.env down # 停止(数据保留在卷中)
|
||||
docker exec -it fba_postgres psql -U postgres -d fba # 进数据库
|
||||
```
|
||||
|
||||
## 与 iAOP 代码侧的关系(后续 Phase)
|
||||
|
||||
- **Phase 1**:iAOP 前端 `web/shared/session.js` 改为调用
|
||||
`/fba/api/v1/auth/login`(JSON 登录)与 `/fba/api/v1/auth/codes`
|
||||
(授权码)做登录与鉴权,现有 `core/auth` 退役。
|
||||
- **Phase 2**:Sider 菜单由 FBA `sys_menu` 接口驱动(`GET /fba/api/v1/sys/menus/sidebar`,
|
||||
服务端按角色授权过滤),替代前端硬编码角色过滤。**需先执行菜单播种**:
|
||||
```bash
|
||||
python3 deploy/fba/seed_iaop_menus.py \
|
||||
--base http://127.0.0.1:8001/api/v1 \
|
||||
--username admin --password '<FBA管理员密码>'
|
||||
```
|
||||
脚本幂等:注册 iAOP 6 模块菜单(含子菜单)、创建 `engineer`/`viewer`
|
||||
角色并按 PRD 8.2 分配菜单。之后在 FBA 后台给用户分配角色即可。
|
||||
未播种时前端自动降级为本地角色过滤,菜单不会空白。
|
||||
- **Phase 3**:FBA UI(Vue3 + AntDV)管理界面已预构建,产物在
|
||||
`deploy/fba/artifacts/fba-ui-dist.tar.gz`(构建参数 `VITE_BASE=/fba-admin/`、
|
||||
`VITE_GLOB_API_URL=http://39.101.182.167:8090/fba`)。部署:
|
||||
```bash
|
||||
cd /opt/apps/iAOP
|
||||
mkdir -p deploy/fba/fba-ui
|
||||
tar -xzf deploy/fba/artifacts/fba-ui-dist.tar.gz -C deploy/fba/fba-ui/
|
||||
# 确认 nginx 已 include 最新 nginx-fba.conf(含 /fba-admin/ 段)后 reload
|
||||
nginx -t && nginx -s reload
|
||||
```
|
||||
入口 `http://39.101.182.167:8090/fba-admin/`,用 FBA 账号登录即可管理
|
||||
用户/角色/菜单/日志。iAOP 顶栏对 admin 角色提供「系统管理」直达链接。
|
||||
若需重新构建(如换域名):改 `fba-ui/apps/web-antdv-next/.env.production`
|
||||
后 `pnpm --filter @vben/web-antdv-next build`(Vben5 monorepo,需 pnpm)。
|
||||
- **Phase 4**:业务接口按钮级权限。
|
||||
- 前端:`IAOP_SESSION.perms()` / `hasPerm(code)` 读取 FBA `/auth/codes`
|
||||
权限码(超管自动拥有全部;菜单播种时已写入 `iaop:<module>`)。
|
||||
- 后端:`core/auth/fba_jwt.py` 提供零依赖 HS256 校验器 `FbaAuth`
|
||||
(与 FBA 的 JWT 同构:claims = sub/session_uuid/exp,密钥取环境变量
|
||||
`FBA_TOKEN_SECRET_KEY`,**必须与 fba.env 的 TOKEN_SECRET_KEY 一致**)。
|
||||
业务服务内 `FbaAuth.from_env()` 返回 None 时走旧 core/auth 会话(双轨过渡)。
|
||||
按钮级校验用 `fba.require_perm(authorization, "iaop:xxx")`(回源
|
||||
`/auth/codes`,带 5 分钟内存缓存)。
|
||||
- 单元测试:`python -m unittest core.auth.tests.test_fba_jwt -v`(8 例全过)。
|
||||
- **Phase 5**:收尾。待全部 Phase 部署验收后:旧 core/auth 登录轨与
|
||||
UserStore 本地账号降级保留为演示模式;生产环境以 FBA 为唯一认证源。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `fba_postgres` / `fba_redis` 不映射宿主端口,仅容器网络内可达;
|
||||
`fba_server` 仅绑定 `127.0.0.1:8001`。
|
||||
- iAOP 现有数据(SQLite 业务库)与 FBA 的 PG 库完全独立,Phase 0 不迁移任何数据。
|
||||
- FBA 源码目录(`fba-backend`)不属于本仓库,升级 FBA 时在
|
||||
`fba-backend` 目录内 `git pull` 后重新 `--build` 即可。
|
||||
|
||||
---
|
||||
|
||||
## Epic #163 · FBA UI 原生重构(2026-08,issue #164-#177)
|
||||
|
||||
### 新架构
|
||||
|
||||
```
|
||||
浏览器
|
||||
│ http://39.101.182.167:8090
|
||||
▼
|
||||
宿主机 nginx(deploy/fba/nginx-fba.conf)
|
||||
├── / → iAOP 静态外壳(web/,C1 后自动收口到 /fba-admin/)
|
||||
├── /fba-admin/ → FBA UI 原生版(Vben5 web-antdv-next,构建产物 dist/)
|
||||
│ · 菜单由 FBA 后端下发(seed_iaop_menus.py v2,type=1 原生菜单)
|
||||
│ · 6 模块 → views/iaop/*(cockpit/chat/studio/admin)
|
||||
│ · 推理通道 /v1/ → 127.0.0.1:30800(推理服务,独立于 /fba)
|
||||
├── /fba/ → 127.0.0.1:8001 fba_server(认证/RBAC/系统管理)
|
||||
└── /v1/ → 127.0.0.1:30800 推理服务(iAOP LLM 网关)
|
||||
```
|
||||
|
||||
### 组件落点
|
||||
- 受控源码:`fba-ui-src/`(fastapi-best-architecture-ui 工程,apps/web-antdv-next)
|
||||
- 构建流水线:`build-ui.sh`(pnpm install → build → artifacts/fba-ui-dist.tar.gz)
|
||||
- 菜单播种 v2:`seed_iaop_menus.py`(幂等 upsert + admin 角色 + 退役菜单隐藏)
|
||||
- 部署:解包 dist → 替换 fba_ui 容器站点目录 → nginx reload(见 C2 验证记录)
|
||||
|
||||
### 旧架构存档
|
||||
- `web/` 静态演示外壳保留(FBA 停掉时兜底;/index.html、/auth/login.html 已加 C1 自动收口跳转)
|
||||
- 旧登录页三轨会话已精简为 FBA 单轨(session.js,FBA 接入版)
|
||||
Binary file not shown.
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# iAOP FBA UI 构建流水线(Epic #163 / issue #164 [A1])
|
||||
#
|
||||
# 用法:
|
||||
# ./deploy/fba/build-ui.sh [--src DIR] [--out DIR]
|
||||
# --src FBA UI 工程目录(默认 deploy/fba/fba-ui-src)
|
||||
# --out 产物输出目录(默认 deploy/fba/artifacts)
|
||||
#
|
||||
# 流程:pnpm install → 生产构建 → 打 tar 到 artifacts/
|
||||
# 产物:artifacts/fba-ui-dist.tar.gz(解压后 dist/ 即 nginx 站点目录)
|
||||
#
|
||||
# 环境要求:Node.js >= 18.18、pnpm >= 9(Vben5 monorepo)
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
SRC="${SRC_DIR:-$ROOT/deploy/fba/fba-ui-src}"
|
||||
OUT="${OUT_DIR:-$ROOT/deploy/fba/artifacts}"
|
||||
APP_DIR="$SRC/apps/web-antdv-next"
|
||||
|
||||
# 1) 参数校验
|
||||
[ -d "$APP_DIR" ] || { echo "[fail] 未找到 UI 工程: $APP_DIR"; exit 1; }
|
||||
mkdir -p "$OUT"
|
||||
|
||||
# 2) 环境检查
|
||||
command -v node >/dev/null || { echo "[fail] 缺少 node(>=18.18)"; exit 1; }
|
||||
command -v pnpm >/dev/null || { echo "[fail] 缺少 pnpm(>=9),请先安装: npm i -g pnpm"; exit 1; }
|
||||
|
||||
echo "[1/4] 依赖安装(pnpm install)..."
|
||||
cd "$SRC"
|
||||
pnpm install --frozen-lockfile=false
|
||||
|
||||
echo "[2/4] 生产构建(web-antdv-next)..."
|
||||
cd "$APP_DIR"
|
||||
pnpm run build
|
||||
|
||||
echo "[3/4] 打包 dist/ -> $OUT/fba-ui-dist.tar.gz"
|
||||
cd "$APP_DIR"
|
||||
tar -czf "$OUT/fba-ui-dist.tar.gz" dist/
|
||||
|
||||
echo "[4/4] 完成:$OUT/fba-ui-dist.tar.gz"
|
||||
ls -lh "$OUT/fba-ui-dist.tar.gz"
|
||||
@@ -0,0 +1,16 @@
|
||||
# =============================================================================
|
||||
# docker compose --env-file 使用的变量文件
|
||||
# 作用域:仅 deploy/fba/docker-compose.yml 的变量插值
|
||||
# =============================================================================
|
||||
|
||||
# FBA 源码所在目录(需包含其官方 Dockerfile)。
|
||||
# 默认期望克隆到 iAOP 仓库同级目录,例如:
|
||||
# /opt/apps/iAOP ← 本仓库
|
||||
# /opt/apps/fba-backend ← git clone https://github.com/fastapi-practices/fastapi-best-architecture
|
||||
FBA_SRC=../../../fba-backend
|
||||
|
||||
# fba_server 对外(回环)端口,nginx 反代目标
|
||||
DOCKER_MAP_SERVER_PORT=8001
|
||||
|
||||
# FBA PostgreSQL 超级用户密码,必须与 fba.env 中 DATABASE_PASSWORD 一致
|
||||
FBA_PG_PASSWORD=123456
|
||||
@@ -0,0 +1,102 @@
|
||||
# =============================================================================
|
||||
# iAOP · FBA(fastapi-best-architecture)最小化部署编排
|
||||
# Epic issue #159 · Phase 0 基础设施
|
||||
#
|
||||
# 只包含 iAOP 需要的 3 个服务:fba_server / fba_postgres / fba_redis。
|
||||
# 已移除 FBA 官方 compose 中的 celery / rabbitmq / nginx / 监控组件
|
||||
# (iAOP 无定时任务需求,对外由宿主机现有 nginx 统一反代)。
|
||||
#
|
||||
# 前置条件:
|
||||
# 1. 宿主机安装 Docker + Docker Compose 插件
|
||||
# 2. 将 FBA 源码克隆到本仓库的同级目录:
|
||||
# git clone https://github.com/fastapi-practices/fastapi-best-architecture ../fba-backend
|
||||
# 或通过环境变量 FBA_SRC 指定其他路径(见下)
|
||||
# 3. 按 fba.env 模板填写配置(务必更换 TOKEN_SECRET_KEY 与数据库密码)
|
||||
#
|
||||
# 启动:
|
||||
# cd deploy/fba
|
||||
# docker compose --env-file compose.env up -d --build
|
||||
#
|
||||
# 停止:
|
||||
# docker compose --env-file compose.env down
|
||||
# =============================================================================
|
||||
|
||||
networks:
|
||||
fba_network:
|
||||
name: fba_network
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
fba_postgres:
|
||||
name: fba_postgres
|
||||
fba_redis:
|
||||
name: fba_redis
|
||||
fba_static:
|
||||
name: fba_static
|
||||
fba_static_upload:
|
||||
name: fba_static_upload
|
||||
|
||||
services:
|
||||
# FBA 后端 API 服务(FastAPI + Casbin RBAC)
|
||||
fba_server:
|
||||
build:
|
||||
# FBA 源码根目录(含其官方 Dockerfile)。默认取 iAOP 仓库同级目录 fba-backend,
|
||||
# 可通过 compose.env 中的 FBA_SRC 覆盖。
|
||||
context: ${FBA_SRC:-../../../fba-backend}
|
||||
dockerfile: Dockerfile
|
||||
image: fba_server:latest
|
||||
container_name: fba_server
|
||||
restart: always
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
ports:
|
||||
# 仅绑定回环地址:不直接对外,由宿主机 nginx 以 /fba/ 前缀反代
|
||||
- "127.0.0.1:${DOCKER_MAP_SERVER_PORT:-8001}:8001"
|
||||
depends_on:
|
||||
- fba_postgres
|
||||
- fba_redis
|
||||
volumes:
|
||||
# 用本目录下的 fba.env 作为 FBA 后端配置,避免改动 FBA 源码树
|
||||
- ./fba.env:/fba/backend/.env:ro
|
||||
- fba_static:/fba/backend/app/static
|
||||
- fba_static_upload:/fba/backend/static/upload
|
||||
- ./logs/fba:/var/log/fba
|
||||
networks:
|
||||
- fba_network
|
||||
# 等待数据库与缓存就绪后再启动 supervisord(复用官方启动方式)
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- |
|
||||
wait-for-it -s fba_postgres:5432 -s fba_redis:6379 -t 300
|
||||
supervisord -c /etc/supervisor/supervisord.conf
|
||||
supervisorctl restart
|
||||
|
||||
# PostgreSQL 16:FBA 的数据库(用户/角色/菜单/Casbin 规则等)
|
||||
fba_postgres:
|
||||
image: postgres:16
|
||||
container_name: fba_postgres
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_DB: fba
|
||||
# 必须与 fba.env 中 DATABASE_PASSWORD 一致
|
||||
POSTGRES_PASSWORD: ${FBA_PG_PASSWORD:-123456}
|
||||
TZ: Asia/Shanghai
|
||||
# 不映射宿主端口,仅 fba_network 内可达
|
||||
volumes:
|
||||
- fba_postgres:/var/lib/postgresql/data
|
||||
networks:
|
||||
- fba_network
|
||||
|
||||
# Redis:Token 黑名单、验证码、限流
|
||||
fba_redis:
|
||||
image: redis:latest
|
||||
container_name: fba_redis
|
||||
restart: always
|
||||
environment:
|
||||
- TZ=Asia/Shanghai
|
||||
# 不映射宿主端口,仅 fba_network 内可达
|
||||
volumes:
|
||||
- fba_redis:/data
|
||||
networks:
|
||||
- fba_network
|
||||
@@ -0,0 +1,4 @@
|
||||
> 1%
|
||||
last 2 versions
|
||||
not dead
|
||||
not ie 11
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from '@vben/commitlint-config';
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
dist
|
||||
.turbo
|
||||
dist.zip
|
||||
@@ -0,0 +1,18 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset=utf-8
|
||||
end_of_line=lf
|
||||
insert_final_newline=true
|
||||
indent_style=space
|
||||
indent_size=2
|
||||
max_line_length = 100
|
||||
trim_trailing_whitespace = true
|
||||
quote_type = single
|
||||
|
||||
[*.{yml,yaml,json}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,11 @@
|
||||
# https://docs.github.com/cn/get-started/getting-started-with-git/configuring-git-to-handle-line-endings
|
||||
|
||||
# Automatically normalize line endings (to LF) for all text-based files.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Declare files that will always have CRLF line endings on checkout.
|
||||
*.{cmd,[cC][mM][dD]} text eol=crlf
|
||||
*.{bat,[bB][aA][tT]} text eol=crlf
|
||||
|
||||
# Denote all files that are truly binary and should not be modified.
|
||||
*.{ico,png,jpg,jpeg,gif,webp,svg,woff,woff2} binary
|
||||
@@ -0,0 +1,2 @@
|
||||
[core]
|
||||
ignorecase = false
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.local
|
||||
@@ -0,0 +1,20 @@
|
||||
export default {
|
||||
'*.md': ['prettier --cache --ignore-unknown --write'],
|
||||
'*.vue': [
|
||||
'prettier --write',
|
||||
'eslint --cache --fix',
|
||||
'stylelint --fix --allow-empty-input',
|
||||
],
|
||||
'*.{js,jsx,ts,tsx}': [
|
||||
'prettier --cache --ignore-unknown --write',
|
||||
'eslint --cache --fix',
|
||||
],
|
||||
'*.{scss,less,styl,html,vue,css}': [
|
||||
'prettier --cache --ignore-unknown --write',
|
||||
'stylelint --fix --allow-empty-input',
|
||||
],
|
||||
'package.json': ['prettier --cache --write'],
|
||||
'{!(package)*.json,*.code-snippets,.!(browserslist)*rc}': [
|
||||
'prettier --cache --write--parser json',
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
24.16.0
|
||||
@@ -0,0 +1 @@
|
||||
registry=https://registry.npmmirror.com
|
||||
@@ -0,0 +1,8 @@
|
||||
dist
|
||||
public
|
||||
__tests__
|
||||
coverage
|
||||
.codex
|
||||
.claude
|
||||
.agent
|
||||
.agents
|
||||
@@ -0,0 +1,18 @@
|
||||
FROM guergeiro/pnpm:lts-latest-slim AS build
|
||||
|
||||
WORKDIR /fba_ui
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN pnpm install \
|
||||
&& pnpm build
|
||||
|
||||
FROM nginx
|
||||
|
||||
COPY scripts/deploy/nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
COPY --from=build /fba_ui/apps/web-antdv-next/dist /var/www/fba_ui
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 FastAPI Practices
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,23 @@
|
||||
# FastAPI Best Architecture UI
|
||||
|
||||
Front-end Implementation of the [FastAPI Best Architecture](https://github.com/fastapi-practices/fastapi_best_architecture)
|
||||
|
||||
## Help
|
||||
|
||||
For more details, please check the [official documentation](https://fastapi-practices.github.io/fastapi_best_architecture_docs/frontend/summary/quick-start.html)
|
||||
|
||||
## Contributors
|
||||
|
||||
<a href="https://github.com/fastapi-practices/fba_ui/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=fastapi-practices/fba_ui"/>
|
||||
</a>
|
||||
|
||||
## Special thanks
|
||||
|
||||
- [Vue.js](https://cn.vuejs.org/guide/introduction.html)
|
||||
- [Vben Admin](https://www.vben.pro/)
|
||||
- ...
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the terms of the [MIT](https://github.com/fastapi-practices/fba_ui/blob/master/LICENSE) license
|
||||
@@ -0,0 +1,8 @@
|
||||
# 应用标题
|
||||
VITE_APP_TITLE=FBA UI
|
||||
|
||||
# 应用命名空间,用于缓存、store等功能的前缀,确保隔离
|
||||
VITE_APP_NAMESPACE=fba-ui
|
||||
|
||||
# 对store进行加密的密钥,在将store持久化到localStorage时会使用该密钥进行加密
|
||||
VITE_APP_STORE_SECURE_KEY=please-replace-me-with-your-own-key
|
||||
@@ -0,0 +1,7 @@
|
||||
# public path
|
||||
VITE_BASE=/
|
||||
|
||||
# Basic interface address SPA
|
||||
VITE_GLOB_API_URL=http://localhost:8000
|
||||
|
||||
VITE_VISUALIZER=true
|
||||
@@ -0,0 +1,16 @@
|
||||
# 端口号
|
||||
VITE_PORT=5173
|
||||
|
||||
VITE_BASE=/
|
||||
|
||||
# 接口地址
|
||||
VITE_GLOB_API_URL=http://localhost:8000
|
||||
|
||||
# 是否开启 Nitro Mock服务,true 为开启,false 为关闭
|
||||
VITE_NITRO_MOCK=false
|
||||
|
||||
# 是否打开 devtools,true 为打开,false 为关闭
|
||||
VITE_DEVTOOLS=false
|
||||
|
||||
# 是否注入全局loading
|
||||
VITE_INJECT_APP_LOADING=true
|
||||
@@ -0,0 +1,25 @@
|
||||
# ===== Epic #163 / #164:构建参数模板化 =====
|
||||
# 构建/部署时按环境替换(部署见 deploy/fba/build-ui.sh)
|
||||
# 1) VITE_BASE:FBA UI 挂载前缀(nginx /fba-admin/ 反代)
|
||||
VITE_BASE=/fba-admin/
|
||||
|
||||
# 2) VITE_GLOB_API_URL:后端 API 基础地址(nginx 反代 /fba/ → fba_server:8001)
|
||||
VITE_GLOB_API_URL=http://39.101.182.167:8090/fba
|
||||
|
||||
# 3) VITE_APP_TITLE:浏览器标题(iAOP 品牌,preferences.ts 已固定,可覆盖)
|
||||
VITE_APP_TITLE=iAOP 云美工业AI优化平台
|
||||
|
||||
# 是否开启压缩,可以设置为 none, brotli, gzip
|
||||
VITE_COMPRESS=none
|
||||
|
||||
# 是否开启 PWA
|
||||
VITE_PWA=false
|
||||
|
||||
# vue-router 的模式
|
||||
VITE_ROUTER_HISTORY=hash
|
||||
|
||||
# 是否注入全局loading
|
||||
VITE_INJECT_APP_LOADING=true
|
||||
|
||||
# 打包后是否生成dist.zip
|
||||
VITE_ARCHIVER=false
|
||||
@@ -0,0 +1,24 @@
|
||||
<!doctype html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
|
||||
<meta name="renderer" content="webkit" />
|
||||
<meta name="description" content="A Modern Back-end Management System" />
|
||||
<meta name="keywords" content="Vben Admin Vue3 Vite" />
|
||||
<meta name="author" content="Vben" />
|
||||
<meta name="google-site-verification" content="......." />
|
||||
<meta name="fba" content="Enterprise-level backend architecture solution" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0"
|
||||
/>
|
||||
<!-- 由 vite 注入 VITE_APP_TITLE 变量,在 .env 文件内配置 -->
|
||||
<title>%VITE_APP_TITLE%</title>
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"name": "@vben/web-antdv-next",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://vben.pro",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vbenjs/vue-vben-admin.git",
|
||||
"directory": "apps/web-antdv-next"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
"name": "vben",
|
||||
"email": "ann.vben@gmail.com",
|
||||
"url": "https://github.com/anncwb"
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm vite build --mode production",
|
||||
"build:analyze": "pnpm vite build --mode analyze",
|
||||
"dev": "pnpm vite --mode development",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "vue-tsc --noEmit --skipLibCheck"
|
||||
},
|
||||
"imports": {
|
||||
"#/*": "./src/*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vben/access": "workspace:*",
|
||||
"@vben/common-ui": "workspace:*",
|
||||
"@vben/constants": "workspace:*",
|
||||
"@vben/hooks": "workspace:*",
|
||||
"@vben/icons": "workspace:*",
|
||||
"@vben/layouts": "workspace:*",
|
||||
"@vben/locales": "workspace:*",
|
||||
"@vben/plugins": "workspace:*",
|
||||
"@vben/preferences": "workspace:*",
|
||||
"@vben/request": "workspace:*",
|
||||
"@vben/stores": "workspace:*",
|
||||
"@vben/styles": "workspace:*",
|
||||
"@vben/types": "workspace:*",
|
||||
"@vben/utils": "workspace:*",
|
||||
"@vueuse/core": "catalog:",
|
||||
"antdv-next": "catalog:",
|
||||
"croner": "catalog:",
|
||||
"dayjs": "catalog:",
|
||||
"mitt": "catalog:",
|
||||
"pinia": "catalog:",
|
||||
"socket.io-client": "catalog:",
|
||||
"vue": "catalog:",
|
||||
"vue-router": "catalog:"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"schema": "iAOP-chat-citations-v1",
|
||||
"documents": [
|
||||
{
|
||||
"title": "GB/T 5475 离子交换树脂取样方法",
|
||||
"source": "templates/resin/rag-kb/documents/GB-T-5475-离子交换树脂取样方法.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# GB/T 5475 离子交换树脂取样方法 - 规定离子交换树脂产品取样方法:从批中按规定数量抽取样品。 - 取样要求代表性:不同包装单元均匀取样,混合后缩分。 - 样品量:每批取样量按标准规定,样品密封保存并标识批次。 - 取样记录:批次号、取样时间、取样人、样品编号(对齐 sample_id)。"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "GB/T 8144 阳离子交换树脂交换容量测定方法",
|
||||
"source": "templates/resin/rag-kb/documents/GB-T-8144-阳离子交换树脂交换容量测定方法.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# GB/T 8144 阳离子交换树脂交换容量测定方法 - 规定阳离子交换树脂交换容量(mmol/g)测定方法。 - 原理:树脂经酸/碱转型后,用标准溶液滴定测定交换容量。 - 结果用于质量分级:交换容量 ≥ 规定值(如 ≥ 4.2 mmol/g)为合格品。 - 测定结果按批次录入 LIMS(tag_id: LIMS."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "GB/T 8330 离子交换树脂湿真密度测定方法",
|
||||
"source": "templates/resin/rag-kb/documents/GB-T-8330-离子交换树脂湿真密度测定方法.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# GB/T 8330 离子交换树脂湿真密度测定方法 - 规定离子交换树脂湿真密度测定方法(比重瓶法)。 - 湿真密度反映树脂交联度与孔结构,与交换容量、强度相关。 - 测定条件:恒温(25℃)、湿态样品、排除气泡后称量。 - 结果记录:按批次录入,作为工艺优化与质量追溯的辅助指标。"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "交接班报告生成规范",
|
||||
"source": "templates/resin/rag-kb/documents/交接班报告生成规范.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# 交接班报告生成规范 - 交接班报告须包含:生产概况、设备运行状态、异常与处置、安全注意事项、待办事项。 - 异常事项必须标注发生时间、处理人与处置结果。 - 待办事项需明确责任人与期望完成时间。 - 每班次结束前 30 分钟生成,当班班长审核后交下一班。"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "交联度超标处置流程",
|
||||
"source": "templates/resin/rag-kb/documents/交联度超标处置流程.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# 交联度超标处置流程 1. 化验确认交联度超标(相对配方设计值偏差 > 5%)后,立即隔离该批树脂。 2. 通知当班班长与质检科,暂停同一配方后续批次投料。 3. 原因排查:DVB 计量偏差、搅拌不均、温度曲线漂移。 4. 处置选项:回用(与低交联度批次调配)或降级(非标用途),由 QE 评审放行。 5. 处置结果录"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "吸附树脂合成工艺规范",
|
||||
"source": "templates/resin/rag-kb/documents/吸附树脂合成工艺规范.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# 吸附树脂合成工艺规范 - 吸附树脂系列:ASC / ASD / HPR / ACD,采用悬浮聚合法,间歇/配方驱动生产。 - 主要单体:苯乙烯(ST)+ 交联剂二乙烯苯(DVB),按配方比例投料。 - 关键工艺参数:聚合温度 70–90℃,引发剂滴加速率按配方设定,搅拌转速 100–300 rpm。 - 交联度(D"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "树脂合成异常处置SOP",
|
||||
"source": "templates/resin/rag-kb/documents/树脂合成异常处置SOP.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# 树脂合成异常处置SOP - SOP-R-001:釜温超上限(>95℃)→ 立即停引发剂滴加、加大冷却水,10 分钟未回落按紧急排料流程。 - SOP-R-002:釜压异常升高 → 停止加热、检查放空阀,联系仪表检修。 - SOP-R-003:搅拌故障 → 降速至停止,启用备用搅拌(如有),未恢复则终止本批。 - S"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "离子交换树脂生产操作手册",
|
||||
"source": "templates/resin/rag-kb/documents/离子交换树脂生产操作手册.md",
|
||||
"sections": [
|
||||
{
|
||||
"heading": "全文",
|
||||
"snippet": "# 离子交换树脂生产操作手册 - 开机前确认:原料计量罐、反应釜密封、加热/冷却系统、尾气处理正常。 - 投料顺序:先加去离子水与分散剂,再按配方加入苯乙烯/二乙烯苯与引发剂。 - 反应期间每 30 分钟记录一次釜温、釜压、搅拌转速。 - 聚合完成判断:釜温回落且无明显放热,取样测交联度。 - 洗涤:去离子水洗至 pH"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"subscribe": "alarm_stream",
|
||||
"severityStyles": {
|
||||
"P0": {
|
||||
"fg": "#ff4d4f",
|
||||
"bg": "rgba(255,77,79,0.10)",
|
||||
"icon": "alert-octagon",
|
||||
"border": "#ff4d4f"
|
||||
},
|
||||
"P1": {
|
||||
"fg": "#faad14",
|
||||
"bg": "rgba(250,173,20,0.10)",
|
||||
"icon": "alert-triangle",
|
||||
"border": "#faad14"
|
||||
},
|
||||
"P2": {
|
||||
"fg": "#1677ff",
|
||||
"bg": "rgba(22,119,255,0.08)",
|
||||
"icon": "info"
|
||||
}
|
||||
},
|
||||
"rulesSource": {
|
||||
"kind": "asset",
|
||||
"ref": "ti-cl4/impurity-forecast/config/alert_rules.template.yaml"
|
||||
},
|
||||
"showSop": true,
|
||||
"requireAck": true,
|
||||
"muteLower": "P2",
|
||||
"groupBy": "severity",
|
||||
"sortBy": "severity",
|
||||
"maxItems": 50,
|
||||
"thresholdsSource": {
|
||||
"kind": "asset",
|
||||
"ref": "ti-cl4/impurity-forecast/config/alert_rules.template.yaml"
|
||||
},
|
||||
"ackTimeoutS": 300
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
{
|
||||
"$schema": "iAOP-cockpit-layout-v1",
|
||||
"title": "吸附树脂车间驾驶舱",
|
||||
"theme": "light",
|
||||
"themeTokens": {
|
||||
"--cockpit-bg": "#f0f2f5",
|
||||
"--cockpit-surface": "#ffffff",
|
||||
"--cockpit-fg": "rgba(0,0,0,0.88)",
|
||||
"--cockpit-fg-muted": "rgba(0,0,0,0.45)",
|
||||
"--cockpit-accent": "#1677ff",
|
||||
"--cockpit-warn": "#faad14",
|
||||
"--cockpit-grid-line": "rgba(5,5,5,0.06)"
|
||||
},
|
||||
"grid": {
|
||||
"columns": 12
|
||||
},
|
||||
"widgets": [
|
||||
{
|
||||
"id": "process_view-0",
|
||||
"component": "ProcessView",
|
||||
"type": "process_view",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 12,
|
||||
"rowStart": 1,
|
||||
"rowSpan": 4,
|
||||
"widthPct": 100.0,
|
||||
"style": "grid-column: 1 / span 12; grid-row: 1 / span 4;"
|
||||
},
|
||||
"description": "四状态工艺流程(合成 → 交联 → 洗涤 → 干燥)",
|
||||
"props": {
|
||||
"src": "resin_four_state.svg",
|
||||
"states": [
|
||||
"running",
|
||||
"warning",
|
||||
"alarm",
|
||||
"offline"
|
||||
]
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "trend-1",
|
||||
"component": "TrendChart",
|
||||
"type": "trend",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 6,
|
||||
"rowStart": 5,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 50.0,
|
||||
"style": "grid-column: 1 / span 6; grid-row: 5 / span 2;"
|
||||
},
|
||||
"description": "反应釜温度实时趋势",
|
||||
"props": {
|
||||
"series": "R-801.TEMP",
|
||||
"window": "PT30M"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "trend-2",
|
||||
"component": "TrendChart",
|
||||
"type": "trend",
|
||||
"grid": {
|
||||
"columnStart": 7,
|
||||
"columnSpan": 6,
|
||||
"rowStart": 5,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 50.0,
|
||||
"style": "grid-column: 7 / span 6; grid-row: 5 / span 2;"
|
||||
},
|
||||
"description": "搅拌转速实时趋势",
|
||||
"props": {
|
||||
"series": "R-801.AGIT",
|
||||
"window": "PT30M"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-3",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 1 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "当批平均交换容量(mmol/g)",
|
||||
"props": {
|
||||
"metric": "resin_exchange_capacity",
|
||||
"label": "交换容量"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-4",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 4,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 4 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "当批平均交联度(%)",
|
||||
"props": {
|
||||
"metric": "resin_crosslink_degree",
|
||||
"label": "交联度"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-5",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 7,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 7 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "当批产率(%)",
|
||||
"props": {
|
||||
"metric": "batch_yield",
|
||||
"label": "批产率"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-6",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 10,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 10 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "单吨树脂综合能耗(kWh/t)",
|
||||
"props": {
|
||||
"metric": "energy_per_ton",
|
||||
"label": "单吨能耗"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "alarm_panel-7",
|
||||
"component": "AlarmPanel",
|
||||
"type": "alarm_panel",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 9,
|
||||
"rowStart": 9,
|
||||
"rowSpan": 3,
|
||||
"widthPct": 75.0,
|
||||
"style": "grid-column: 1 / span 9; grid-row: 9 / span 3;"
|
||||
},
|
||||
"description": "告警面板(温度/交联度/质量预测异常)",
|
||||
"props": {
|
||||
"subscribe": "alarm_stream"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "nl_query-8",
|
||||
"component": "NlQuery",
|
||||
"type": "nl_query",
|
||||
"grid": {
|
||||
"columnStart": 10,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 9,
|
||||
"rowSpan": 3,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 10 / span 3; grid-row: 9 / span 3;"
|
||||
},
|
||||
"description": "自然语言查询入口(配方/质量/能耗问答)",
|
||||
"props": {
|
||||
"placeholder": "输入自然语言查询(配方 / 质量 / 能耗)"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"widgetCount": 9,
|
||||
"perfFlags": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
},
|
||||
"perfHint": null
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
{
|
||||
"$schema": "iAOP-cockpit-layout-v1",
|
||||
"title": "海绵钛车间驾驶舱",
|
||||
"theme": "light",
|
||||
"themeTokens": {
|
||||
"--cockpit-bg": "#f0f2f5",
|
||||
"--cockpit-surface": "#ffffff",
|
||||
"--cockpit-fg": "rgba(0,0,0,0.88)",
|
||||
"--cockpit-fg-muted": "rgba(0,0,0,0.45)",
|
||||
"--cockpit-accent": "#1677ff",
|
||||
"--cockpit-warn": "#faad14",
|
||||
"--cockpit-grid-line": "rgba(5,5,5,0.06)"
|
||||
},
|
||||
"grid": {
|
||||
"columns": 12
|
||||
},
|
||||
"widgets": [
|
||||
{
|
||||
"id": "process_view-0",
|
||||
"component": "ProcessView",
|
||||
"type": "process_view",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 12,
|
||||
"rowStart": 1,
|
||||
"rowSpan": 4,
|
||||
"widthPct": 100.0,
|
||||
"style": "grid-column: 1 / span 12; grid-row: 1 / span 4;"
|
||||
},
|
||||
"description": "四状态工艺流程(氯化 → 精制 → 还原 → 蒸馏)",
|
||||
"props": {
|
||||
"src": "ti_four_state.svg",
|
||||
"states": [
|
||||
"running",
|
||||
"warning",
|
||||
"alarm",
|
||||
"offline"
|
||||
],
|
||||
"stages": [
|
||||
{
|
||||
"id": "chlorination",
|
||||
"name": "氯化",
|
||||
"device": "CLF-01",
|
||||
"order": 1
|
||||
},
|
||||
{
|
||||
"id": "purification",
|
||||
"name": "精制",
|
||||
"order": 2
|
||||
},
|
||||
{
|
||||
"id": "reduction",
|
||||
"name": "还原",
|
||||
"device": "RF-01",
|
||||
"order": 3
|
||||
},
|
||||
{
|
||||
"id": "distillation",
|
||||
"name": "蒸馏",
|
||||
"order": 4
|
||||
}
|
||||
]
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "trend-1",
|
||||
"component": "TrendChart",
|
||||
"type": "trend",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 6,
|
||||
"rowStart": 5,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 50.0,
|
||||
"style": "grid-column: 1 / span 6; grid-row: 5 / span 2;"
|
||||
},
|
||||
"description": "氯化炉温度实时趋势(沸腾氯化炉温 850±50℃)",
|
||||
"props": {
|
||||
"series": "CLF-01.TEMP",
|
||||
"window": "PT30M"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "trend-2",
|
||||
"component": "TrendChart",
|
||||
"type": "trend",
|
||||
"grid": {
|
||||
"columnStart": 7,
|
||||
"columnSpan": 6,
|
||||
"rowStart": 5,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 50.0,
|
||||
"style": "grid-column: 7 / span 6; grid-row: 5 / span 2;"
|
||||
},
|
||||
"description": "氯气流量实时趋势(流态化监控)",
|
||||
"props": {
|
||||
"series": "CLF-01.CL2",
|
||||
"window": "PT30M"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-3",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 1 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "还原 TiCl₄ 纯度(%,工艺 ≥ 99.9%)",
|
||||
"props": {
|
||||
"metric": "ticl4_purity",
|
||||
"label": "TiCl₄纯度"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-4",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 4,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 4 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "还原杂质含量(%,越低越好)",
|
||||
"props": {
|
||||
"metric": "ticl4_impurity",
|
||||
"label": "杂质含量"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-5",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 7,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 7 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "车间累计电耗(kWh,单吨海绵钛综合能耗输入)",
|
||||
"props": {
|
||||
"metric": "energy_per_ton",
|
||||
"label": "累计电耗"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kpi_card-6",
|
||||
"component": "KpiCard",
|
||||
"type": "kpi_card",
|
||||
"grid": {
|
||||
"columnStart": 10,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 7,
|
||||
"rowSpan": 2,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 10 / span 3; grid-row: 7 / span 2;"
|
||||
},
|
||||
"description": "蒸汽流量(t/h,公用工程监控)",
|
||||
"props": {
|
||||
"metric": "steam_flow",
|
||||
"label": "蒸汽流量"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "alarm_panel-7",
|
||||
"component": "AlarmPanel",
|
||||
"type": "alarm_panel",
|
||||
"grid": {
|
||||
"columnStart": 1,
|
||||
"columnSpan": 9,
|
||||
"rowStart": 9,
|
||||
"rowSpan": 3,
|
||||
"widthPct": 75.0,
|
||||
"style": "grid-column: 1 / span 9; grid-row: 9 / span 3;"
|
||||
},
|
||||
"description": "告警面板(氯化炉温/还原真空度/纯度/杂质异常)",
|
||||
"props": {
|
||||
"subscribe": "alarm_stream"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "nl_query-8",
|
||||
"component": "NlQuery",
|
||||
"type": "nl_query",
|
||||
"grid": {
|
||||
"columnStart": 10,
|
||||
"columnSpan": 3,
|
||||
"rowStart": 9,
|
||||
"rowSpan": 3,
|
||||
"widthPct": 25.0,
|
||||
"style": "grid-column: 10 / span 3; grid-row: 9 / span 3;"
|
||||
},
|
||||
"description": "自然语言查询入口(工艺/质量/能耗问答)",
|
||||
"props": {
|
||||
"placeholder": "输入自然语言查询(配方 / 质量 / 能耗)"
|
||||
},
|
||||
"perf": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"widgetCount": 9,
|
||||
"perfFlags": {
|
||||
"virtualScroll": false,
|
||||
"downsample": false,
|
||||
"worker": false
|
||||
},
|
||||
"perfHint": null
|
||||
}
|
||||
@@ -0,0 +1,788 @@
|
||||
/**
|
||||
* 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用
|
||||
* 可用于 vben-form、vben-modal、vben-drawer 等组件使用,
|
||||
*/
|
||||
|
||||
/* eslint-disable vue/one-component-per-file */
|
||||
|
||||
import type {
|
||||
AutoCompleteProps,
|
||||
ButtonProps,
|
||||
CascaderProps,
|
||||
CheckboxGroupProps,
|
||||
CheckboxProps,
|
||||
DatePickerProps,
|
||||
DividerProps,
|
||||
InputNumberProps,
|
||||
InputProps,
|
||||
MentionsProps,
|
||||
RadioGroupProps,
|
||||
RadioProps,
|
||||
RangePickerProps,
|
||||
RateProps,
|
||||
SelectProps,
|
||||
SpaceProps,
|
||||
SwitchProps,
|
||||
TextAreaProps,
|
||||
TimePickerProps,
|
||||
TreeSelectProps,
|
||||
UploadChangeParam,
|
||||
UploadFile,
|
||||
UploadProps,
|
||||
} from 'antdv-next';
|
||||
|
||||
import type { Component, Ref } from 'vue';
|
||||
|
||||
import type {
|
||||
ApiComponentSharedProps,
|
||||
BaseFormComponentType,
|
||||
CollapsibleParamsProps,
|
||||
IconPickerProps,
|
||||
} from '@vben/common-ui';
|
||||
import type { Sortable } from '@vben/hooks';
|
||||
import type { TipTapProps } from '@vben/plugins/tiptap';
|
||||
import type { Recordable } from '@vben/types';
|
||||
|
||||
import {
|
||||
computed,
|
||||
defineAsyncComponent,
|
||||
defineComponent,
|
||||
h,
|
||||
nextTick,
|
||||
onMounted,
|
||||
onUnmounted,
|
||||
ref,
|
||||
render,
|
||||
unref,
|
||||
watch,
|
||||
} from 'vue';
|
||||
|
||||
import {
|
||||
ApiComponent,
|
||||
globalShareState,
|
||||
IconPicker,
|
||||
VbenCollapsibleParams,
|
||||
VCropper,
|
||||
} from '@vben/common-ui';
|
||||
import { useSortable } from '@vben/hooks';
|
||||
import { IconifyIcon } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
import { VbenTiptap } from '@vben/plugins/tiptap';
|
||||
import { isEmpty } from '@vben/utils';
|
||||
|
||||
import { message, Modal, notification } from 'antdv-next';
|
||||
|
||||
import { upload_file } from '#/api';
|
||||
type AdapterUploadProps = UploadProps & {
|
||||
aspectRatio?: string;
|
||||
crop?: boolean;
|
||||
draggable?: boolean;
|
||||
handleChange?: (event: UploadChangeParam) => void;
|
||||
maxSize?: number;
|
||||
onDragSort?: (oldIndex: number, newIndex: number) => void;
|
||||
onHandleChange?: (event: UploadChangeParam) => void;
|
||||
};
|
||||
|
||||
const AutoComplete = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/auto-complete/index'),
|
||||
);
|
||||
const Button = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/button/index'),
|
||||
);
|
||||
const Checkbox = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/checkbox/index'),
|
||||
);
|
||||
const CheckboxGroup = defineAsyncComponent(() =>
|
||||
import('antdv-next/dist/checkbox/index').then((res) => res.CheckboxGroup),
|
||||
);
|
||||
const DatePicker = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/date-picker/index'),
|
||||
);
|
||||
const Divider = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/divider/index'),
|
||||
);
|
||||
const Input = defineAsyncComponent(() => import('antdv-next/dist/input/index'));
|
||||
const InputNumber = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/input-number/index'),
|
||||
);
|
||||
const InputPassword = defineAsyncComponent(() =>
|
||||
import('antdv-next/dist/input/index').then((res) => res.InputPassword),
|
||||
);
|
||||
const Mentions = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/mentions/index'),
|
||||
);
|
||||
const Radio = defineAsyncComponent(() => import('antdv-next/dist/radio/index'));
|
||||
const RadioGroup = defineAsyncComponent(() =>
|
||||
import('antdv-next/dist/radio/index').then((res) => res.RadioGroup),
|
||||
);
|
||||
const RangePicker = defineAsyncComponent(() =>
|
||||
import('antdv-next/dist/date-picker/index').then(
|
||||
(res) => res.DateRangePicker,
|
||||
),
|
||||
);
|
||||
const Rate = defineAsyncComponent(() => import('antdv-next/dist/rate/index'));
|
||||
const Select = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/select/index'),
|
||||
);
|
||||
const Space = defineAsyncComponent(() => import('antdv-next/dist/space/index'));
|
||||
const Switch = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/switch/index'),
|
||||
);
|
||||
const Textarea = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/input/TextArea'),
|
||||
);
|
||||
const TimePicker = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/time-picker/index'),
|
||||
);
|
||||
const TreeSelect = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/tree-select/index'),
|
||||
);
|
||||
const Cascader = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/cascader/index'),
|
||||
);
|
||||
const Upload = defineAsyncComponent(
|
||||
() => import('antdv-next/dist/upload/index'),
|
||||
);
|
||||
const Image = defineAsyncComponent(() => import('antdv-next/dist/image/index'));
|
||||
const PreviewGroup = defineAsyncComponent(() =>
|
||||
import('antdv-next/dist/image/index').then((res) => res.ImagePreviewGroup),
|
||||
);
|
||||
|
||||
const withDefaultPlaceholder = (
|
||||
component: Component,
|
||||
type: 'input' | 'select',
|
||||
componentProps: Recordable<any> = {},
|
||||
) => {
|
||||
return defineComponent({
|
||||
name: component.name,
|
||||
inheritAttrs: false,
|
||||
setup: (props: any, { attrs, expose, slots }) => {
|
||||
const placeholder =
|
||||
props?.placeholder ||
|
||||
attrs?.placeholder ||
|
||||
$t(`ui.placeholder.${type}`);
|
||||
// 透传组件暴露的方法
|
||||
const innerRef = ref();
|
||||
expose(
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get: (_target, key) => innerRef.value?.[key],
|
||||
has: (_target, key) => key in (innerRef.value || {}),
|
||||
},
|
||||
),
|
||||
);
|
||||
return () =>
|
||||
h(
|
||||
component,
|
||||
{ ...componentProps, placeholder, ...props, ...attrs, ref: innerRef },
|
||||
slots,
|
||||
);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const IMAGE_EXTENSIONS = new Set([
|
||||
'bmp',
|
||||
'gif',
|
||||
'jpeg',
|
||||
'jpg',
|
||||
'png',
|
||||
'svg',
|
||||
'webp',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 检查是否为图片文件
|
||||
*/
|
||||
function isImageFile(file: UploadFile): boolean {
|
||||
if (file.url) {
|
||||
try {
|
||||
const pathname = new URL(file.url, 'http://localhost').pathname;
|
||||
const ext = pathname.split('.').pop()?.toLowerCase();
|
||||
return ext ? IMAGE_EXTENSIONS.has(ext) : false;
|
||||
} catch {
|
||||
const ext = file.url?.split('.').pop()?.toLowerCase();
|
||||
return ext ? IMAGE_EXTENSIONS.has(ext) : false;
|
||||
}
|
||||
}
|
||||
if (!file.type) {
|
||||
const ext = file.name?.split('.').pop()?.toLowerCase();
|
||||
return ext ? IMAGE_EXTENSIONS.has(ext) : false;
|
||||
}
|
||||
return file.type.startsWith('image/');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建默认的上传按钮插槽
|
||||
*/
|
||||
function createDefaultUploadSlots(listType: string, placeholder: string) {
|
||||
if (listType === 'picture-card') {
|
||||
return { default: () => placeholder };
|
||||
}
|
||||
return {
|
||||
default: () =>
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
icon: h(IconifyIcon, {
|
||||
icon: 'ant-design:upload-outlined',
|
||||
class: 'mb-1 size-4',
|
||||
}),
|
||||
},
|
||||
() => placeholder,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件的 Base64
|
||||
*/
|
||||
function getBase64(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(file);
|
||||
reader.addEventListener('load', () => resolve(reader.result as string));
|
||||
reader.addEventListener('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览图片
|
||||
*/
|
||||
async function previewImage(
|
||||
file: UploadFile,
|
||||
open: Ref<boolean>,
|
||||
fileList: Ref<UploadProps['fileList']>,
|
||||
) {
|
||||
// 非图片文件直接打开链接
|
||||
if (!isImageFile(file)) {
|
||||
const url = file.url || file.preview;
|
||||
if (url) {
|
||||
window.open(url, '_blank');
|
||||
} else if (file.preview) {
|
||||
window.open(file.preview, '_blank');
|
||||
} else {
|
||||
message.error($t('ui.formRules.previewWarning'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const [ImageComponent, PreviewGroupComponent] = await Promise.all([
|
||||
Image,
|
||||
PreviewGroup,
|
||||
]);
|
||||
|
||||
// 过滤图片文件并生成预览
|
||||
const imageFiles = (unref(fileList) || []).filter((f) => isImageFile(f));
|
||||
|
||||
for (const imgFile of imageFiles) {
|
||||
if (!imgFile.url && !imgFile.preview && imgFile.originFileObj) {
|
||||
imgFile.preview = await getBase64(imgFile.originFileObj);
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
let isUnmounted = false;
|
||||
|
||||
const currentIndex = imageFiles.findIndex((f) => f.uid === file.uid);
|
||||
|
||||
const PreviewWrapper = {
|
||||
setup() {
|
||||
return () => {
|
||||
if (isUnmounted) return null;
|
||||
return h(
|
||||
PreviewGroupComponent,
|
||||
{
|
||||
class: 'hidden',
|
||||
preview: {
|
||||
open: open.value,
|
||||
current: currentIndex,
|
||||
onOpenChange: (value: boolean) => {
|
||||
open.value = value;
|
||||
if (!value) {
|
||||
setTimeout(() => {
|
||||
if (!isUnmounted && container) {
|
||||
isUnmounted = true;
|
||||
render(null, container);
|
||||
container.remove();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
() =>
|
||||
imageFiles.map((imgFile) =>
|
||||
h(ImageComponent, {
|
||||
key: imgFile.uid,
|
||||
src: imgFile.url || imgFile.preview,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
render(h(PreviewWrapper), container);
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片裁剪操作
|
||||
*/
|
||||
function cropImage(file: File, aspectRatio: string | undefined) {
|
||||
return new Promise<Blob | string | undefined>((resolve, reject) => {
|
||||
const container = document.createElement('div');
|
||||
document.body.append(container);
|
||||
|
||||
let isUnmounted = false;
|
||||
let objectUrl: null | string = null;
|
||||
|
||||
const open = ref<boolean>(true);
|
||||
const cropperRef = ref<InstanceType<typeof VCropper> | null>(null);
|
||||
|
||||
function closeModal() {
|
||||
open.value = false;
|
||||
setTimeout(() => {
|
||||
if (!isUnmounted && container) {
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
isUnmounted = true;
|
||||
render(null, container);
|
||||
container.remove();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
|
||||
const CropperWrapper = {
|
||||
setup() {
|
||||
return () => {
|
||||
if (isUnmounted) return null;
|
||||
if (!objectUrl) {
|
||||
objectUrl = URL.createObjectURL(file);
|
||||
}
|
||||
return h(
|
||||
Modal,
|
||||
{
|
||||
open: open.value,
|
||||
title: h('div', {}, [
|
||||
$t('ui.crop.title'),
|
||||
h(
|
||||
'span',
|
||||
{
|
||||
class: `${aspectRatio ? '' : 'hidden'} ml-2 text-sm text-gray-400 font-normal`,
|
||||
},
|
||||
$t('ui.crop.titleTip', [aspectRatio]),
|
||||
),
|
||||
]),
|
||||
centered: true,
|
||||
width: 548,
|
||||
keyboard: false,
|
||||
maskClosable: false,
|
||||
closable: false,
|
||||
cancelText: $t('common.cancel'),
|
||||
okText: $t('ui.crop.confirm'),
|
||||
destroyOnHidden: true,
|
||||
onOk: async () => {
|
||||
const cropper = cropperRef.value;
|
||||
if (!cropper) {
|
||||
reject(new Error('Cropper not found'));
|
||||
closeModal();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const dataUrl = await cropper.getCropImage();
|
||||
if (dataUrl) {
|
||||
resolve(dataUrl);
|
||||
} else {
|
||||
reject(new Error($t('ui.crop.errorTip')));
|
||||
}
|
||||
} catch {
|
||||
reject(new Error($t('ui.crop.errorTip')));
|
||||
} finally {
|
||||
closeModal();
|
||||
}
|
||||
},
|
||||
onCancel() {
|
||||
resolve('');
|
||||
closeModal();
|
||||
},
|
||||
},
|
||||
() =>
|
||||
h(VCropper, {
|
||||
ref: (ref: any) => (cropperRef.value = ref),
|
||||
img: objectUrl as string,
|
||||
aspectRatio,
|
||||
}),
|
||||
);
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
render(h(CropperWrapper), container);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 带预览功能的上传组件
|
||||
*/
|
||||
function withPreviewUpload() {
|
||||
return defineComponent({
|
||||
name: Upload.name,
|
||||
emits: ['update:modelValue'],
|
||||
setup(
|
||||
props: any,
|
||||
{ attrs, slots, emit }: { attrs: any; emit: any; slots: any },
|
||||
) {
|
||||
const previewVisible = ref<boolean>(false);
|
||||
const placeholder = attrs?.placeholder || $t('ui.placeholder.upload');
|
||||
const listType = attrs?.listType || attrs?.['list-type'] || 'text';
|
||||
const fileList = ref<UploadProps['fileList']>(
|
||||
attrs?.fileList || attrs?.['file-list'] || [],
|
||||
);
|
||||
|
||||
const maxSize = computed(() => attrs?.maxSize ?? attrs?.['max-size']);
|
||||
const aspectRatio = computed(
|
||||
() => attrs?.aspectRatio ?? attrs?.['aspect-ratio'],
|
||||
);
|
||||
|
||||
async function handleBeforeUpload(
|
||||
file: UploadFile,
|
||||
originFileList: Array<File>,
|
||||
) {
|
||||
// 文件大小限制
|
||||
if (maxSize.value && (file.size || 0) / 1024 / 1024 > maxSize.value) {
|
||||
message.error($t('ui.formRules.sizeLimit', [maxSize.value]));
|
||||
file.status = 'removed';
|
||||
return false;
|
||||
}
|
||||
|
||||
// 图片裁剪处理
|
||||
if (
|
||||
attrs.crop &&
|
||||
!attrs.multiple &&
|
||||
originFileList[0] &&
|
||||
isImageFile(file)
|
||||
) {
|
||||
file.status = 'removed';
|
||||
const blob = await cropImage(originFileList[0], aspectRatio.value);
|
||||
if (!blob) {
|
||||
throw new Error($t('ui.crop.errorTip'));
|
||||
}
|
||||
return blob;
|
||||
}
|
||||
|
||||
return attrs.beforeUpload?.(file) ?? true;
|
||||
}
|
||||
|
||||
function handleChange(event: UploadChangeParam) {
|
||||
try {
|
||||
attrs.handleChange?.(event);
|
||||
attrs.onHandleChange?.(event);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
fileList.value = event.fileList.filter(
|
||||
(file) => file.status !== 'removed',
|
||||
);
|
||||
emit(
|
||||
'update:modelValue',
|
||||
event.fileList?.length ? fileList.value : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
function handlePreview(file: UploadFile) {
|
||||
previewVisible.value = true;
|
||||
return previewImage(file, previewVisible, fileList);
|
||||
}
|
||||
|
||||
function renderUploadButton() {
|
||||
if (attrs.disabled) return null;
|
||||
return isEmpty(slots)
|
||||
? createDefaultUploadSlots(listType, placeholder)
|
||||
: slots;
|
||||
}
|
||||
|
||||
// 拖拽排序
|
||||
const draggable = computed(
|
||||
() => (attrs.draggable ?? false) && !attrs.disabled,
|
||||
);
|
||||
const uploadId = `upload-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||
const sortableInstance = ref<null | Sortable>(null);
|
||||
|
||||
const styleId = `upload-drag-style-${uploadId}`;
|
||||
|
||||
function injectDragStyle() {
|
||||
if (!document.querySelector(`[id="${styleId}"]`)) {
|
||||
const style = document.createElement('style');
|
||||
style.id = styleId;
|
||||
style.textContent = `
|
||||
[data-upload-id="${uploadId}"] .ant-upload-list-item { cursor: move; }
|
||||
[data-upload-id="${uploadId}"] .ant-upload-list-item:hover { box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
}
|
||||
|
||||
function removeDragStyle() {
|
||||
document.querySelector(`[id="${styleId}"]`)?.remove();
|
||||
}
|
||||
|
||||
async function initSortable(retryCount = 0) {
|
||||
if (!draggable.value) return;
|
||||
|
||||
injectDragStyle();
|
||||
await nextTick();
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
const container = document.querySelector(
|
||||
`[data-upload-id="${uploadId}"] .ant-upload-list`,
|
||||
) as HTMLElement;
|
||||
|
||||
if (!container) {
|
||||
if (retryCount < 5) {
|
||||
setTimeout(() => initSortable(retryCount + 1), 200);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { initializeSortable } = useSortable(container, {
|
||||
animation: 300,
|
||||
delay: 400,
|
||||
delayOnTouchOnly: true,
|
||||
filter:
|
||||
'.ant-upload-select, .ant-upload-list-item-error, .ant-upload-list-item-uploading',
|
||||
onEnd: (evt) => {
|
||||
const { oldIndex, newIndex } = evt;
|
||||
if (
|
||||
oldIndex === undefined ||
|
||||
newIndex === undefined ||
|
||||
oldIndex === newIndex
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const list = [...(fileList.value || [])];
|
||||
const [movedItem] = list.splice(oldIndex, 1);
|
||||
if (movedItem) {
|
||||
list.splice(newIndex, 0, movedItem);
|
||||
fileList.value = list;
|
||||
}
|
||||
|
||||
attrs.onDragSort?.(oldIndex, newIndex);
|
||||
emit('update:modelValue', fileList.value);
|
||||
},
|
||||
});
|
||||
|
||||
sortableInstance.value = await initializeSortable();
|
||||
}
|
||||
|
||||
// 监听表单值变化
|
||||
watch(
|
||||
() => attrs.modelValue,
|
||||
(res) => {
|
||||
fileList.value = res;
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(initSortable);
|
||||
onUnmounted(() => {
|
||||
sortableInstance.value?.destroy();
|
||||
removeDragStyle();
|
||||
});
|
||||
|
||||
return () =>
|
||||
h(
|
||||
'div',
|
||||
{ 'data-upload-id': uploadId, class: 'w-full' },
|
||||
h(
|
||||
Upload,
|
||||
{
|
||||
...props,
|
||||
...attrs,
|
||||
fileList: fileList.value,
|
||||
beforeUpload: handleBeforeUpload,
|
||||
onChange: handleChange,
|
||||
onPreview: handlePreview,
|
||||
},
|
||||
renderUploadButton() as any,
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明
|
||||
export type ComponentType =
|
||||
| 'ApiCascader'
|
||||
| 'ApiSelect'
|
||||
| 'ApiTreeSelect'
|
||||
| 'AutoComplete'
|
||||
| 'Cascader'
|
||||
| 'Checkbox'
|
||||
| 'CheckboxGroup'
|
||||
| 'CollapsibleParams'
|
||||
| 'DatePicker'
|
||||
| 'DefaultButton'
|
||||
| 'Divider'
|
||||
| 'IconPicker'
|
||||
| 'Input'
|
||||
| 'InputNumber'
|
||||
| 'InputPassword'
|
||||
| 'Mentions'
|
||||
| 'PrimaryButton'
|
||||
| 'Radio'
|
||||
| 'RadioGroup'
|
||||
| 'RangePicker'
|
||||
| 'Rate'
|
||||
| 'RichEditor'
|
||||
| 'Select'
|
||||
| 'Space'
|
||||
| 'Switch'
|
||||
| 'Textarea'
|
||||
| 'TimePicker'
|
||||
| 'TreeSelect'
|
||||
| 'Upload'
|
||||
| BaseFormComponentType;
|
||||
|
||||
/**
|
||||
* 与 {@link ComponentType} 中注册的组件名一一对应,便于 Schema 上 `component` + `componentProps` 联动提示
|
||||
*/
|
||||
export interface ComponentPropsMap {
|
||||
ApiCascader: ApiComponentSharedProps & CascaderProps;
|
||||
ApiSelect: ApiComponentSharedProps & SelectProps;
|
||||
ApiTreeSelect: ApiComponentSharedProps & TreeSelectProps;
|
||||
AutoComplete: AutoCompleteProps;
|
||||
Cascader: CascaderProps;
|
||||
Checkbox: CheckboxProps;
|
||||
CheckboxGroup: CheckboxGroupProps;
|
||||
CollapsibleParams: CollapsibleParamsProps;
|
||||
DatePicker: DatePickerProps;
|
||||
DefaultButton: ButtonProps;
|
||||
Divider: DividerProps;
|
||||
IconPicker: IconPickerProps;
|
||||
Input: InputProps;
|
||||
InputNumber: InputNumberProps;
|
||||
InputPassword: InputProps;
|
||||
Mentions: MentionsProps;
|
||||
PrimaryButton: ButtonProps;
|
||||
Radio: RadioProps;
|
||||
RadioGroup: RadioGroupProps;
|
||||
RangePicker: RangePickerProps;
|
||||
Rate: RateProps;
|
||||
RichEditor: TipTapProps;
|
||||
Select: SelectProps;
|
||||
Space: SpaceProps;
|
||||
Switch: SwitchProps;
|
||||
Textarea: TextAreaProps;
|
||||
TimePicker: TimePickerProps;
|
||||
TreeSelect: TreeSelectProps;
|
||||
Upload: AdapterUploadProps;
|
||||
}
|
||||
|
||||
async function initComponentAdapter() {
|
||||
const components: Partial<Record<ComponentType, Component>> = {
|
||||
// 如果你的组件体积比较大,可以使用异步加载
|
||||
// Button: () =>
|
||||
// import('xxx').then((res) => res.Button),
|
||||
|
||||
ApiCascader: withDefaultPlaceholder(ApiComponent, 'select', {
|
||||
component: Cascader,
|
||||
fieldNames: { label: 'label', value: 'value', children: 'children' },
|
||||
loadingSlot: 'suffixIcon',
|
||||
modelPropName: 'value',
|
||||
visibleEvent: 'onOpenChange',
|
||||
}),
|
||||
ApiSelect: withDefaultPlaceholder(ApiComponent, 'select', {
|
||||
component: Select,
|
||||
loadingSlot: 'suffixIcon',
|
||||
modelPropName: 'value',
|
||||
visibleEvent: 'onOpenChange',
|
||||
}),
|
||||
ApiTreeSelect: withDefaultPlaceholder(ApiComponent, 'select', {
|
||||
component: TreeSelect,
|
||||
fieldNames: { label: 'label', value: 'value', children: 'children' },
|
||||
loadingSlot: 'suffixIcon',
|
||||
modelPropName: 'value',
|
||||
optionsPropName: 'treeData',
|
||||
visibleEvent: 'onOpenChange',
|
||||
}),
|
||||
AutoComplete,
|
||||
Cascader,
|
||||
Checkbox,
|
||||
CheckboxGroup,
|
||||
DatePicker,
|
||||
// 自定义默认按钮
|
||||
DefaultButton: (props, { attrs, slots }) => {
|
||||
return h(Button, { ...props, attrs, type: 'default' }, slots);
|
||||
},
|
||||
Divider,
|
||||
IconPicker: withDefaultPlaceholder(IconPicker, 'select', {
|
||||
iconSlot: 'addonAfter',
|
||||
inputComponent: Input,
|
||||
modelValueProp: 'value',
|
||||
}),
|
||||
Input: withDefaultPlaceholder(Input, 'input'),
|
||||
InputNumber: withDefaultPlaceholder(InputNumber, 'input', {
|
||||
style: { width: '100%' },
|
||||
}),
|
||||
InputPassword: withDefaultPlaceholder(InputPassword, 'input'),
|
||||
Mentions: withDefaultPlaceholder(Mentions, 'input'),
|
||||
// 自定义主要按钮
|
||||
PrimaryButton: (props, { attrs, slots }) => {
|
||||
return h(Button, { ...props, attrs, type: 'primary' }, slots);
|
||||
},
|
||||
Radio,
|
||||
RadioGroup,
|
||||
RangePicker,
|
||||
Rate,
|
||||
RichEditor: withDefaultPlaceholder(VbenTiptap, 'input', {
|
||||
imageUpload: {
|
||||
upload: (file: any, onProgress: any) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
upload_file({
|
||||
file,
|
||||
onProgress({ percent }) {
|
||||
onProgress?.(percent);
|
||||
},
|
||||
onSuccess(response) {
|
||||
// 从响应中提取图片URL
|
||||
resolve(response?.data?.url ?? response?.url ?? '');
|
||||
},
|
||||
onError() {
|
||||
reject(new Error($t('ui.tiptap.upload.uploadFailed')));
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
}),
|
||||
Select: withDefaultPlaceholder(Select, 'select'),
|
||||
Space,
|
||||
Switch,
|
||||
Textarea: withDefaultPlaceholder(Textarea, 'input'),
|
||||
TimePicker,
|
||||
TreeSelect: withDefaultPlaceholder(TreeSelect, 'select'),
|
||||
Upload: withPreviewUpload(),
|
||||
CollapsibleParams: VbenCollapsibleParams,
|
||||
};
|
||||
|
||||
// 将组件注册到全局共享状态中
|
||||
globalShareState.setComponents(components);
|
||||
|
||||
// 定义全局共享状态中的消息提示
|
||||
globalShareState.defineMessage({
|
||||
// 复制成功消息提示
|
||||
copyPreferencesSuccess: (title, content) => {
|
||||
notification.success({
|
||||
description: content,
|
||||
title,
|
||||
placement: 'bottomRight',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export { initComponentAdapter };
|
||||
@@ -0,0 +1,48 @@
|
||||
import type {
|
||||
VbenFormProps as FormProps,
|
||||
VbenFormSchema as FormSchema,
|
||||
} from '@vben/common-ui';
|
||||
|
||||
import type { ComponentPropsMap, ComponentType } from './component';
|
||||
|
||||
import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
async function initSetupVbenForm() {
|
||||
setupVbenForm<ComponentType>({
|
||||
config: {
|
||||
// ant design vue组件库默认都是 v-model:value
|
||||
baseModelPropName: 'value',
|
||||
|
||||
// 一些组件是 v-model:checked 或者 v-model:fileList
|
||||
modelPropNameMap: {
|
||||
Checkbox: 'checked',
|
||||
Radio: 'checked',
|
||||
Switch: 'checked',
|
||||
Upload: 'fileList',
|
||||
},
|
||||
},
|
||||
defineRules: {
|
||||
// 输入项目必填国际化适配
|
||||
required: (value, _params, ctx) => {
|
||||
if (value === undefined || value === null || value.length === 0) {
|
||||
return $t('ui.formRules.required', [ctx.label]);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
// 选择项目必填国际化适配
|
||||
selectRequired: (value, _params, ctx) => {
|
||||
if (value === undefined || value === null) {
|
||||
return $t('ui.formRules.selectRequired', [ctx.label]);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const useVbenForm = useForm<ComponentType, ComponentPropsMap>;
|
||||
|
||||
export { initSetupVbenForm, useVbenForm, z };
|
||||
|
||||
export type VbenFormSchema = FormSchema<ComponentType, ComponentPropsMap>;
|
||||
export type VbenFormProps = FormProps<ComponentType, ComponentPropsMap>;
|
||||
@@ -0,0 +1,318 @@
|
||||
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
|
||||
import type { Recordable } from '@vben/types';
|
||||
|
||||
import type { ComponentPropsMap, ComponentType } from './component';
|
||||
|
||||
import { h } from 'vue';
|
||||
|
||||
import { IconifyIcon } from '@vben/icons';
|
||||
import { $te } from '@vben/locales';
|
||||
import {
|
||||
setupVbenVxeTable,
|
||||
useVbenVxeGrid as useGrid,
|
||||
} from '@vben/plugins/vxe-table';
|
||||
import { get, isFunction, isString } from '@vben/utils';
|
||||
|
||||
import { objectOmit } from '@vueuse/core';
|
||||
import { Button, Dropdown, Image, Popconfirm, Switch, Tag } from 'antdv-next';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
import { DictEnum, getDictOptions } from '#/utils/dict';
|
||||
|
||||
import { useVbenForm } from './form';
|
||||
|
||||
setupVbenVxeTable({
|
||||
configVxeTable: (vxeUI) => {
|
||||
vxeUI.setConfig({
|
||||
grid: {
|
||||
align: 'center',
|
||||
border: false,
|
||||
columnConfig: {
|
||||
resizable: true,
|
||||
},
|
||||
minHeight: 180,
|
||||
formConfig: {
|
||||
// 全局禁用vxe-table的表单配置,使用formOptions
|
||||
enabled: false,
|
||||
},
|
||||
proxyConfig: {
|
||||
autoLoad: true,
|
||||
response: {
|
||||
result: 'items',
|
||||
total: 'total',
|
||||
list: '',
|
||||
},
|
||||
showActiveMsg: true,
|
||||
showResponseMsg: false,
|
||||
},
|
||||
round: true,
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
} as VxeTableGridOptions,
|
||||
});
|
||||
|
||||
// 表格配置项可以用 cellRender: { name: 'CellImage' },
|
||||
vxeUI.renderer.add('CellImage', {
|
||||
renderTableDefault(renderOpts, params) {
|
||||
const { props } = renderOpts;
|
||||
const { column, row } = params;
|
||||
return h(Image, { src: row[column.field], ...props });
|
||||
},
|
||||
});
|
||||
|
||||
// 表格配置项可以用 cellRender: { name: 'CellLink' },
|
||||
vxeUI.renderer.add('CellLink', {
|
||||
renderTableDefault(renderOpts) {
|
||||
const { props } = renderOpts;
|
||||
return h(
|
||||
Button,
|
||||
{ size: 'small', type: 'link' },
|
||||
{ default: () => props?.text },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// 单元格渲染:Tag
|
||||
vxeUI.renderer.add('CellTag', {
|
||||
renderTableDefault({ options, props }, { column, row }) {
|
||||
const value = get(row, column.field);
|
||||
// const tagOptions = options ?? [
|
||||
// { color: 'success', label: $t('common.enabled'), value: 1 },
|
||||
// { color: 'error', label: $t('common.disabled'), value: 0 },
|
||||
// ];
|
||||
const tagOptions = options ?? getDictOptions(DictEnum.SYS_STATUS);
|
||||
const tagItem = tagOptions.find((item) => item.value === value);
|
||||
return h(
|
||||
Tag,
|
||||
{
|
||||
...props,
|
||||
...objectOmit(tagItem ?? {}, ['label']),
|
||||
},
|
||||
{ default: () => tagItem?.label ?? value },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// 单元格渲染器:Switch
|
||||
vxeUI.renderer.add('CellSwitch', {
|
||||
renderTableDefault({ attrs, props }, { column, row }) {
|
||||
const loadingKey = `__loading_${column.field}`;
|
||||
const finallyProps = {
|
||||
checkedChildren: $t('common.enabled'),
|
||||
checkedValue: props?.checkedValue || 1,
|
||||
unCheckedChildren: $t('common.disabled'),
|
||||
unCheckedValue: props?.unCheckedValue || 0,
|
||||
...props,
|
||||
checked: row[column.field],
|
||||
loading: row[loadingKey] ?? false,
|
||||
'onUpdate:checked': onChange,
|
||||
};
|
||||
async function onChange(newVal: any) {
|
||||
row[loadingKey] = true;
|
||||
try {
|
||||
const result = await attrs?.beforeChange?.(newVal, row);
|
||||
if (result !== false) {
|
||||
row[column.field] = newVal;
|
||||
attrs?.onChange?.({ row });
|
||||
}
|
||||
} finally {
|
||||
row[loadingKey] = false;
|
||||
}
|
||||
}
|
||||
return h(Switch, finallyProps);
|
||||
},
|
||||
});
|
||||
|
||||
// 注册表格的操作按钮渲染器
|
||||
vxeUI.renderer.add('CellOperation', {
|
||||
renderTableDefault({ attrs, options, props }, { column, row }) {
|
||||
const defaultProps = { size: 'small', type: 'link', ...props };
|
||||
let align = 'end';
|
||||
if (column.align === 'center') {
|
||||
align = 'center';
|
||||
} else if (column.align === 'left') {
|
||||
align = 'start';
|
||||
}
|
||||
const presets: Recordable<Recordable<any>> = {
|
||||
delete: {
|
||||
danger: true,
|
||||
text: $t('common.delete'),
|
||||
},
|
||||
edit: {
|
||||
text: $t('common.edit'),
|
||||
},
|
||||
};
|
||||
const operations: Array<Recordable<any>> = (
|
||||
options || ['edit', 'delete']
|
||||
)
|
||||
.map((opt) => {
|
||||
if (isString(opt)) {
|
||||
return presets[opt]
|
||||
? { code: opt, ...presets[opt], ...defaultProps }
|
||||
: {
|
||||
code: opt,
|
||||
text: $te(`common.${opt}`) ? $t(`common.${opt}`) : opt,
|
||||
...defaultProps,
|
||||
};
|
||||
} else {
|
||||
return { ...defaultProps, ...presets[opt.code], ...opt };
|
||||
}
|
||||
})
|
||||
.map((opt) => {
|
||||
const optBtn: Recordable<any> = {};
|
||||
Object.keys(opt).forEach((key) => {
|
||||
optBtn[key] = isFunction(opt[key]) ? opt[key](row) : opt[key];
|
||||
});
|
||||
return optBtn;
|
||||
})
|
||||
.filter((opt) => opt.show !== false);
|
||||
|
||||
function renderBtn(opt: Recordable<any>, listen = true) {
|
||||
return h(
|
||||
Button,
|
||||
{
|
||||
...props,
|
||||
...opt,
|
||||
icon: undefined,
|
||||
onClick: listen
|
||||
? () =>
|
||||
attrs?.onClick?.({
|
||||
code: opt.code,
|
||||
row,
|
||||
})
|
||||
: undefined,
|
||||
},
|
||||
{
|
||||
default: () => {
|
||||
const content = [];
|
||||
if (opt.icon) {
|
||||
content.push(
|
||||
h(IconifyIcon, { class: 'size-5', icon: opt.icon }),
|
||||
);
|
||||
}
|
||||
content.push(opt.text);
|
||||
return content;
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function renderConfirm(opt: Recordable<any>) {
|
||||
return h(
|
||||
Popconfirm,
|
||||
{
|
||||
getPopupContainer(el) {
|
||||
if (el.closest('.fixed-right--wrapper')) {
|
||||
return document.body;
|
||||
}
|
||||
return (
|
||||
el
|
||||
.closest('.vxe-table--viewport-wrapper')
|
||||
?.querySelector('.vxe-table--main-wrapper')
|
||||
?.querySelector('tbody') || document.body
|
||||
);
|
||||
},
|
||||
placement: 'topLeft',
|
||||
title: $t('ui.actionTitle.delete', [attrs?.nameTitle || '']),
|
||||
...props,
|
||||
...opt,
|
||||
icon: undefined,
|
||||
onConfirm: () => {
|
||||
attrs?.onClick?.({
|
||||
code: opt.code,
|
||||
row,
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => renderBtn({ ...opt }, false),
|
||||
description: () =>
|
||||
h(
|
||||
'div',
|
||||
{ class: 'truncate' },
|
||||
$t('ui.actionMessage.deleteConfirm', [
|
||||
row[attrs?.nameField || 'name'],
|
||||
]),
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function renderDropdown(opt: Recordable<any>) {
|
||||
const menuItems =
|
||||
opt.items?.map((item: Recordable<any>) => ({
|
||||
key: item.code || item.text,
|
||||
label: item.text,
|
||||
icon: item.icon ?? undefined,
|
||||
disabled: item.disabled ?? undefined,
|
||||
})) || [];
|
||||
|
||||
return h(
|
||||
Dropdown,
|
||||
{
|
||||
getPopupContainer(el) {
|
||||
if (el.closest('.fixed-right--wrapper')) {
|
||||
return document.body;
|
||||
}
|
||||
return (
|
||||
el
|
||||
.closest('.vxe-table--viewport-wrapper')
|
||||
?.querySelector('.vxe-table--main-wrapper')
|
||||
?.querySelector('tbody') || document.body
|
||||
);
|
||||
},
|
||||
placement: 'bottomLeft',
|
||||
...props,
|
||||
...opt,
|
||||
menu: {
|
||||
items: menuItems,
|
||||
onClick: ({ key }: { key: string }) =>
|
||||
attrs?.onClick?.({ code: key, row }),
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => renderBtn({ ...opt, icon: 'tabler:dots' }, false),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const btns = operations.map((opt) => {
|
||||
if (opt.code === 'delete') {
|
||||
return renderConfirm(opt);
|
||||
} else if (opt.code === 'more') {
|
||||
return renderDropdown(opt);
|
||||
} else {
|
||||
return renderBtn(opt);
|
||||
}
|
||||
});
|
||||
return h(
|
||||
'div',
|
||||
{
|
||||
class: 'flex table-operations',
|
||||
style: { justifyContent: align },
|
||||
},
|
||||
btns,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化
|
||||
// vxeUI.formats.add
|
||||
},
|
||||
useVbenForm,
|
||||
});
|
||||
|
||||
export const useVbenVxeGrid = <T extends Record<string, any>>(
|
||||
...rest: Parameters<typeof useGrid<T, ComponentType, ComponentPropsMap>>
|
||||
) => useGrid<T, ComponentType, ComponentPropsMap>(...rest);
|
||||
|
||||
export type OnActionClickParams<T = Recordable<any>> = {
|
||||
code: string;
|
||||
row: T;
|
||||
};
|
||||
|
||||
export type OnActionClickFn<T = Recordable<any>> = (
|
||||
params: OnActionClickParams<T>,
|
||||
) => void;
|
||||
|
||||
export type * from '@vben/plugins/vxe-table';
|
||||
@@ -0,0 +1,63 @@
|
||||
import { miniRequestClient, requestClient } from '#/api/request';
|
||||
|
||||
export interface CaptchaResult {
|
||||
is_enabled: boolean;
|
||||
expire_seconds: number;
|
||||
uuid: string;
|
||||
image: string;
|
||||
}
|
||||
|
||||
export interface LoginParams {
|
||||
username: string;
|
||||
password: string;
|
||||
uuid: string;
|
||||
captcha: string;
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
access_token: string;
|
||||
session_uuid: string;
|
||||
}
|
||||
|
||||
export type RefreshTokenResult = LoginResult;
|
||||
|
||||
/**
|
||||
* 登录验证码
|
||||
*/
|
||||
export async function getCaptchaApi() {
|
||||
return requestClient.get<CaptchaResult>('/api/v1/auth/captcha');
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录
|
||||
*/
|
||||
export async function loginApi(data: LoginParams) {
|
||||
return requestClient.post<LoginResult>('/api/v1/auth/login', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新accessToken
|
||||
*/
|
||||
export async function refreshTokenApi() {
|
||||
return miniRequestClient.post<RefreshTokenResult>(
|
||||
'/api/v1/auth/refresh',
|
||||
undefined,
|
||||
{
|
||||
withCredentials: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
export async function logoutApi() {
|
||||
return requestClient.post('/api/v1/auth/logout');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户权限码
|
||||
*/
|
||||
export async function getAccessCodesApi() {
|
||||
return requestClient.get<string[]>('/api/v1/auth/codes');
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from './auth';
|
||||
export * from './menu';
|
||||
export * from './upload';
|
||||
export * from './user';
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { RouteRecordStringComponent } from '@vben/types';
|
||||
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface SysMenuResult {
|
||||
id: number;
|
||||
title: string;
|
||||
name: string;
|
||||
path: string;
|
||||
sort: number;
|
||||
icon?: string;
|
||||
type: number;
|
||||
component?: string;
|
||||
perms?: string;
|
||||
status: number;
|
||||
display: number;
|
||||
cache: number;
|
||||
remark?: string;
|
||||
parent_id?: number;
|
||||
created_time: string;
|
||||
}
|
||||
|
||||
export interface SysMenuTreeResult extends SysMenuResult {
|
||||
children?: SysMenuTreeResult[];
|
||||
}
|
||||
|
||||
export interface SysMenuParams {
|
||||
title: string;
|
||||
name: string;
|
||||
path?: string;
|
||||
parent_id?: number;
|
||||
sort?: number;
|
||||
icon?: string;
|
||||
type?: number;
|
||||
component?: string;
|
||||
perms?: string;
|
||||
status?: number;
|
||||
display?: number;
|
||||
cache?: number;
|
||||
link?: string;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface SysMenuTreeParams {
|
||||
title?: string;
|
||||
status: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户所有菜单
|
||||
*/
|
||||
export async function getAllMenusApi() {
|
||||
return requestClient.get<RouteRecordStringComponent[]>(
|
||||
'/api/v1/sys/menus/sidebar',
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSysMenuTreeApi(params: SysMenuTreeParams) {
|
||||
const transformMenuTitles = (menuData: SysMenuTreeResult[]) => {
|
||||
return menuData.map((item) => {
|
||||
const transformedItem = {
|
||||
...item,
|
||||
title: $t(item.title),
|
||||
};
|
||||
|
||||
if (item.children && item.children.length > 0) {
|
||||
transformedItem.children = transformMenuTitles(item.children);
|
||||
}
|
||||
|
||||
return transformedItem;
|
||||
});
|
||||
};
|
||||
|
||||
const filterMenuTree = (
|
||||
menuData: SysMenuTreeResult[],
|
||||
keyword: string,
|
||||
): SysMenuTreeResult[] => {
|
||||
const lowerKeyword = keyword.toLowerCase();
|
||||
const result: SysMenuTreeResult[] = [];
|
||||
for (const item of menuData) {
|
||||
const filteredChildren = item.children?.length
|
||||
? filterMenuTree(item.children, keyword)
|
||||
: [];
|
||||
const isMatch = item.title.toLowerCase().includes(lowerKeyword);
|
||||
if (isMatch || filteredChildren.length > 0) {
|
||||
result.push({
|
||||
...item,
|
||||
children: isMatch ? item.children : filteredChildren,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const { title, ...restParams } = params;
|
||||
|
||||
const data = await requestClient.get<SysMenuTreeResult[]>(
|
||||
'/api/v1/sys/menus',
|
||||
{
|
||||
params: restParams,
|
||||
},
|
||||
);
|
||||
|
||||
const translatedData = transformMenuTitles(data);
|
||||
|
||||
if (title) {
|
||||
return filterMenuTree(translatedData, title);
|
||||
}
|
||||
|
||||
return translatedData;
|
||||
}
|
||||
|
||||
export async function createSysMenuApi(data: SysMenuParams) {
|
||||
return requestClient.post('/api/v1/sys/menus', data);
|
||||
}
|
||||
|
||||
export async function updateSysMenuApi(pk: number, data: SysMenuParams) {
|
||||
return requestClient.put(`/api/v1/sys/menus/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function deleteSysMenuApi(pk: number) {
|
||||
return requestClient.delete(`/api/v1/sys/menus/${pk}`);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
interface UploadFileParams {
|
||||
file: File;
|
||||
onError?: (error: Error) => void;
|
||||
onProgress?: (progress: { percent: number }) => void;
|
||||
onSuccess?: (data: any, file: File) => void;
|
||||
}
|
||||
export async function upload_file({
|
||||
file,
|
||||
onError,
|
||||
onProgress,
|
||||
onSuccess,
|
||||
}: UploadFileParams) {
|
||||
try {
|
||||
onProgress?.({ percent: 0 });
|
||||
|
||||
const data = await requestClient.upload('/api/v1/sys/files/upload', {
|
||||
file,
|
||||
});
|
||||
|
||||
onProgress?.({ percent: 100 });
|
||||
onSuccess?.(data, file);
|
||||
} catch (error) {
|
||||
onError?.(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { UserInfo } from '@vben/types';
|
||||
|
||||
import type { SysDeptResult, SysRoleResult } from '#/api';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface MyUserInfo extends UserInfo {
|
||||
id: number;
|
||||
nickname: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
dept?: string;
|
||||
last_login_time: string;
|
||||
}
|
||||
|
||||
export interface SysUserResult {
|
||||
id: number;
|
||||
uuid: string;
|
||||
dept_id?: number;
|
||||
username: string;
|
||||
nickname: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
avatar?: string;
|
||||
status: number;
|
||||
is_superuser: boolean;
|
||||
is_staff: boolean;
|
||||
is_multi_login: boolean;
|
||||
join_time: string;
|
||||
last_login_time: string;
|
||||
dept?: SysDeptResult;
|
||||
roles: SysRoleResult[];
|
||||
}
|
||||
|
||||
export interface SysUserParams {
|
||||
dept?: number;
|
||||
username?: string;
|
||||
phone?: string;
|
||||
status?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface SysUpdateUserParams {
|
||||
dept_id?: number;
|
||||
username: string;
|
||||
nickname: string;
|
||||
avatar?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
roles: number[];
|
||||
}
|
||||
|
||||
export interface SysAddUserParams extends SysUpdateUserParams {
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface SysUpdatePasswordParams {
|
||||
old_password: string;
|
||||
new_password: string;
|
||||
confirm_password: string;
|
||||
}
|
||||
|
||||
export interface SysUpdateUserPhoneParams {
|
||||
phone: string;
|
||||
captcha: string;
|
||||
}
|
||||
|
||||
export interface SysUpdateUserEmailParams {
|
||||
email: string;
|
||||
captcha: string;
|
||||
}
|
||||
|
||||
export interface SysUpdateUserNicknameParams {
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface SysUpdateUserAvatarParams {
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
export interface SysResetPasswordParams {
|
||||
password: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户信息
|
||||
*/
|
||||
export async function getUserInfoApi() {
|
||||
return requestClient.get<MyUserInfo>('/api/v1/sys/users/me');
|
||||
}
|
||||
|
||||
export async function getSysUserListApi(params: SysUserParams) {
|
||||
return requestClient.get<SysUserResult>('/api/v1/sys/users', { params });
|
||||
}
|
||||
|
||||
export async function createSysUserApi(data: SysAddUserParams) {
|
||||
return requestClient.post('/api/v1/sys/users', data);
|
||||
}
|
||||
|
||||
export async function updateSysUserApi(pk: number, data: SysUpdateUserParams) {
|
||||
return requestClient.put(`/api/v1/sys/users/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function updateSysUserPermissionApi(pk: number, type: string) {
|
||||
return requestClient.put(`/api/v1/sys/users/${pk}/permissions`, undefined, {
|
||||
params: { type },
|
||||
paramsSerializer: 'repeat',
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateSysUserAvatarApi(data: SysUpdateUserAvatarParams) {
|
||||
return requestClient.put(`/api/v1/sys/users/me/avatar`, data);
|
||||
}
|
||||
|
||||
export async function updateSysUserNicknameApi(
|
||||
data: SysUpdateUserNicknameParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/sys/users/me/nickname`, data);
|
||||
}
|
||||
export async function updateSysUserPhoneApi(data: SysUpdateUserPhoneParams) {
|
||||
return requestClient.put(`/api/v1/sys/users/me/phone`, data);
|
||||
}
|
||||
|
||||
export async function updateSysUserEmailApi(data: SysUpdateUserEmailParams) {
|
||||
return requestClient.put(`/api/v1/sys/users/me/email`, data);
|
||||
}
|
||||
|
||||
export async function updateSysUserPasswordApi(data: SysUpdatePasswordParams) {
|
||||
return requestClient.put(`/api/v1/sys/users/me/password`, data);
|
||||
}
|
||||
|
||||
export async function resetSysUserPasswordApi(
|
||||
pk: number,
|
||||
data: SysResetPasswordParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/sys/users/${pk}/password`, data);
|
||||
}
|
||||
|
||||
export async function deleteSysUserApi(pk: number) {
|
||||
return requestClient.delete(`/api/v1/sys/users/${pk}`);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface SysDataScopeResult {
|
||||
id: number;
|
||||
name: string;
|
||||
status: number;
|
||||
created_time: string;
|
||||
updated_time: string;
|
||||
}
|
||||
|
||||
export interface SysDataRuleResult {
|
||||
id: number;
|
||||
name: string;
|
||||
model: string;
|
||||
column: string;
|
||||
operator: string;
|
||||
expression: string;
|
||||
value: string;
|
||||
created_time: string;
|
||||
updated_time: string;
|
||||
}
|
||||
|
||||
export interface SysDataScopeParams {
|
||||
name?: string;
|
||||
status?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface CreateSysDataScopeParams {
|
||||
name: string;
|
||||
status: number;
|
||||
}
|
||||
|
||||
export interface SysDataScopeRulesResult extends SysDataScopeResult {
|
||||
rules: SysDataRuleResult[];
|
||||
}
|
||||
|
||||
export interface SysDataRuleParams {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface SysDataRuleModelColumnsResult {
|
||||
key: string;
|
||||
comment: string;
|
||||
}
|
||||
|
||||
export interface SysDataRuleTemplateVariableResult {
|
||||
key: string;
|
||||
comment: string;
|
||||
}
|
||||
|
||||
export interface CreateSysDataRuleParams {
|
||||
name: string;
|
||||
model: string;
|
||||
column: string;
|
||||
operator: string;
|
||||
expression: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export async function getSysDataScopeListApi(params: SysDataScopeParams) {
|
||||
return requestClient.get<SysDataScopeResult[]>('/api/v1/sys/data-scopes', {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSysDataScopesApi() {
|
||||
return requestClient.get<SysDataScopeResult[]>('/api/v1/sys/data-scopes/all');
|
||||
}
|
||||
|
||||
export async function getSysDataScopeRulesApi(pk: number) {
|
||||
return requestClient.get<SysDataScopeRulesResult>(
|
||||
`/api/v1/sys/data-scopes/${pk}/rules`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createSysDataScope(data: CreateSysDataScopeParams) {
|
||||
return requestClient.post('/api/v1/sys/data-scopes', data);
|
||||
}
|
||||
|
||||
export async function updateSysDataScope(
|
||||
pk: number,
|
||||
data: CreateSysDataScopeParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/sys/data-scopes/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function updateSysDataScopeRulesApi(pk: number, rules: number[]) {
|
||||
return requestClient.put(`/api/v1/sys/data-scopes/${pk}/rules`, { rules });
|
||||
}
|
||||
|
||||
export async function deleteSysDataScopeApi(pks: number[]) {
|
||||
return requestClient.delete(`/api/v1/sys/data-scopes`, { data: { pks } });
|
||||
}
|
||||
|
||||
export async function getSysDataRuleListApi(params: SysDataRuleParams) {
|
||||
return requestClient.get<SysDataRuleResult[]>('/api/v1/sys/data-rules', {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSysDataRulesApi() {
|
||||
return requestClient.get<SysDataRuleResult[]>('/api/v1/sys/data-rules/all');
|
||||
}
|
||||
|
||||
export async function getSysDataRuleModelsApi() {
|
||||
return requestClient.get<string[]>('/api/v1/sys/data-rules/models');
|
||||
}
|
||||
|
||||
export async function getSysDataRuleModelColumnsApi(model: string) {
|
||||
return requestClient.get<SysDataRuleModelColumnsResult[]>(
|
||||
`/api/v1/sys/data-rules/models/${model}/columns`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSysDataRuleTemplateVariablesApi() {
|
||||
return requestClient.get<SysDataRuleTemplateVariableResult[]>(
|
||||
'/api/v1/sys/data-rules/value-template-variables',
|
||||
);
|
||||
}
|
||||
|
||||
export async function createSysDataRuleApi(data: CreateSysDataRuleParams) {
|
||||
return requestClient.post('/api/v1/sys/data-rules', data);
|
||||
}
|
||||
|
||||
export async function updateSysDataRuleApi(
|
||||
pk: number,
|
||||
data: CreateSysDataRuleParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/sys/data-rules/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function deleteSysDataRuleApi(pks: number[]) {
|
||||
return requestClient.delete(`/api/v1/sys/data-rules`, { data: { pks } });
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { requestClient } from './request';
|
||||
|
||||
export interface SysDeptResult {
|
||||
id: number;
|
||||
name: string;
|
||||
parent_id: number;
|
||||
sort: number;
|
||||
leader?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
status: number;
|
||||
created_time: string;
|
||||
}
|
||||
|
||||
export interface SysDeptTreeResult extends SysDeptResult {
|
||||
children?: SysDeptTreeResult[];
|
||||
}
|
||||
|
||||
export interface SysDeptParams {
|
||||
name: string;
|
||||
parent_id?: number;
|
||||
sort?: number;
|
||||
leader?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
status: number;
|
||||
}
|
||||
|
||||
export interface SysDeptTreeParams {
|
||||
name?: string;
|
||||
leader?: string;
|
||||
phone?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取部门树
|
||||
*/
|
||||
export async function getSysDeptTreeApi(params: SysDeptTreeParams) {
|
||||
return requestClient.get<SysDeptTreeResult[]>('/api/v1/sys/depts', {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取部门详情
|
||||
*/
|
||||
export async function getSysDeptDetailApi(pk: number) {
|
||||
return requestClient.get<SysDeptTreeResult>(`/api/v1/sys/depts/${pk}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建部门
|
||||
*/
|
||||
export async function createSysDeptApi(data: SysDeptParams) {
|
||||
return requestClient.post('/api/v1/sys/depts', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新部门
|
||||
*/
|
||||
export async function updateSysDeptApi(pk: number, data: SysDeptParams) {
|
||||
return requestClient.put(`/api/v1/sys/depts/${pk}`, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除部门
|
||||
*/
|
||||
export async function deleteSysDeptApi(pk: number) {
|
||||
return requestClient.delete(`/api/v1/sys/depts/${pk}`);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* iAOP API 客户端出口(Epic #163 / issue #166 [A3])
|
||||
*
|
||||
* - infer.ts —— LLM 网关(/v1/*:health / models / chat/completions)
|
||||
* - templates.ts —— 驾驶舱布局与告警面板模板 JSON(public/iaop/plans)
|
||||
* - registry.ts —— 模型注册表 HTTP API(E1 #182 / E2 #183:list/register/promote/rollback)
|
||||
*/
|
||||
export * from './infer';
|
||||
export * from './registry';
|
||||
export * from './templates';
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* iAOP LLM 网关客户端(Epic #163 / issue #166 [A3])
|
||||
*
|
||||
* 对齐旧 `web/` 各模块的 INFER_BASE(nginx 反代 /v1/ → 推理服务 :30800):
|
||||
* GET /v1/health —— 健康巡检
|
||||
* GET /v1/models —— 模型列表
|
||||
* POST /v1/chat/completions —— OpenAI 兼容对话(dry-run 占位 / 真实推理)
|
||||
*
|
||||
* 推理服务为 iAOP 独立通道(不要求 FBA JWT),故用原生 fetch 封装,
|
||||
* 统一超时 / 错误信息 / 结果结构;FBA requestClient 仅用于 /fba/* 接口。
|
||||
*/
|
||||
const BASE_URL = '/v1';
|
||||
const TIMEOUT_MS = 15000;
|
||||
|
||||
export interface InferResult {
|
||||
text: string;
|
||||
meta: Record<string, unknown>;
|
||||
backend: string;
|
||||
latencyMs: number;
|
||||
}
|
||||
|
||||
export interface ChatCompletionChoice {
|
||||
index: number;
|
||||
message: { role: string; content: string };
|
||||
finish_reason: string;
|
||||
}
|
||||
|
||||
export interface ChatCompletionResponse {
|
||||
id: string;
|
||||
object: string;
|
||||
choices: ChatCompletionChoice[];
|
||||
model: string;
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 带超时的 fetch */
|
||||
async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const resp = await fetch(`${BASE_URL}${path}`, {
|
||||
...init,
|
||||
signal: controller.signal,
|
||||
headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) },
|
||||
});
|
||||
if (!resp.ok) {
|
||||
throw new Error(`推理服务 HTTP ${resp.status}`);
|
||||
}
|
||||
const text = await resp.text();
|
||||
return (text ? JSON.parse(text) : {}) as T;
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === 'AbortError') {
|
||||
throw new Error(`推理服务请求超时(>${TIMEOUT_MS / 1000}s)`);
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** 健康巡检(前端徽标展示;失败不抛出,由调用方降级) */
|
||||
export async function fetchHealth(): Promise<Record<string, unknown> | null> {
|
||||
try {
|
||||
return await fetchJson<Record<string, unknown>>('/health');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 模型列表 */
|
||||
export async function fetchModels(): Promise<string[]> {
|
||||
const data = await fetchJson<{ models?: string[] }>('/v1/models');
|
||||
return data.models || [];
|
||||
}
|
||||
|
||||
/** OpenAI 兼容对话(含 dry-run 占位响应) */
|
||||
export async function chatCompletion(
|
||||
prompt: string,
|
||||
opts?: { model?: string; maxTokens?: number; temperature?: number },
|
||||
): Promise<ChatCompletionResponse> {
|
||||
const body = {
|
||||
model: opts?.model || '',
|
||||
prompt,
|
||||
max_tokens: opts?.maxTokens || 1024,
|
||||
temperature: opts?.temperature ?? 0.1,
|
||||
};
|
||||
return fetchJson<ChatCompletionResponse>('/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
/** 便捷:返回纯文本(B 系列页面统一使用) */
|
||||
export async function ask(prompt: string, opts?: Parameters<typeof chatCompletion>[1]): Promise<InferResult> {
|
||||
const resp = await chatCompletion(prompt, opts);
|
||||
const msg = resp.choices?.[0]?.message?.content || '';
|
||||
return {
|
||||
text: msg,
|
||||
meta: (resp.meta as Record<string, unknown>) || {},
|
||||
backend: String((resp.meta as Record<string, unknown>)?.backend || 'gpu'),
|
||||
latencyMs: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* iAOP 模型注册表 API 客户端(issue #183 [E2] / PRD 5.3 ③)
|
||||
*
|
||||
* 对接 E1 后端 ``core/model-framework/registry_api.py``(nginx 反代
|
||||
* ``/api/v1/registry/`` → :8090),四接口:
|
||||
*
|
||||
* GET /api/v1/registry/models 列表(可按 stage 过滤)
|
||||
* POST /api/v1/registry/models 注册新版本(服务端校验)
|
||||
* POST /api/v1/registry/models/{name}/{ver}/promote dev→staging→prod
|
||||
* POST /api/v1/registry/models/{name}/rollback?version=&stage= 回滚
|
||||
*
|
||||
* 鉴权:读接口接 FBA JWT,写接口要求权限码 iaop:admin/iaop:studio。
|
||||
* 复用 FBA requestClient 的 token 注入(``useAccessStore().accessToken``),
|
||||
* 但注册表走 iAOP 后端独立路径 ``/api/v1/registry/``(非 /fba),故用原生
|
||||
* fetch 封装,与 infer.ts 同款风格(超时 / 错误信息 / 结果结构统一)。
|
||||
*
|
||||
* 调用方应在 catch 中降级到 localStorage 演示模式(见 views/iaop/admin/models.vue)。
|
||||
*/
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
const BASE_URL = '/api/v1/registry';
|
||||
const TIMEOUT_MS = 10000;
|
||||
|
||||
/** 注册表模型视图(对齐后端 registry_api._tpl_view) */
|
||||
export interface RegistryModel {
|
||||
name: string;
|
||||
version: string;
|
||||
backbone: string;
|
||||
stage: 'dev' | 'staging' | 'prod';
|
||||
hyperparams?: Record<string, unknown>;
|
||||
feature_columns?: string[];
|
||||
target_column?: string;
|
||||
metrics?: Record<string, number>;
|
||||
registered_at: number;
|
||||
description?: string;
|
||||
extra?: Record<string, unknown>;
|
||||
/** 种子/迁移字段(extra.author 提到顶层,便于前端展示) */
|
||||
author?: string;
|
||||
}
|
||||
|
||||
/** 列表响应 */
|
||||
interface ListResponse {
|
||||
models: RegistryModel[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** 是否处于「服务不可达」错误(调用方据此降级 localStorage) */
|
||||
export function isRegistryUnavailable(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
return /Failed to fetch|NetworkError|超时|HTTP 5\d\d|HTTP 0/i.test(err.message);
|
||||
}
|
||||
|
||||
/** 注册新版本的请求体 */
|
||||
export interface RegisterModelParams {
|
||||
name: string;
|
||||
version: string;
|
||||
backbone?: string;
|
||||
stage?: 'dev' | 'staging' | 'prod';
|
||||
hyperparams?: Record<string, unknown>;
|
||||
feature_columns?: string[];
|
||||
target_column?: string;
|
||||
metrics?: Record<string, number>;
|
||||
description?: string;
|
||||
extra?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 取当前 FBA access token(与 requestClient 同源注入) */
|
||||
function authHeader(): Record<string, string> {
|
||||
try {
|
||||
const token = useAccessStore().accessToken;
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
} catch {
|
||||
// store 未就绪(如独立运行 / 单测)时降级无鉴权
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** 带超时的 fetch + FBA token 注入 */
|
||||
async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const resp = await fetch(`${BASE_URL}${path}`, {
|
||||
...init,
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeader(),
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
});
|
||||
if (!resp.ok) {
|
||||
// 401/403/404 等业务错误:尝试读后端 {error} 字段,否则给 HTTP 码
|
||||
let detail = `HTTP ${resp.status}`;
|
||||
try {
|
||||
const body = await resp.json();
|
||||
if (body?.error) detail = body.error;
|
||||
} catch { /* 非 JSON 错误体忽略 */ }
|
||||
throw new Error(detail);
|
||||
}
|
||||
const text = await resp.text();
|
||||
return (text ? JSON.parse(text) : {}) as T;
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === 'AbortError') {
|
||||
throw new Error(`注册表服务请求超时(>${TIMEOUT_MS / 1000}s)`);
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** 列表(可按 stage 过滤)。失败抛错,调用方降级。 */
|
||||
export async function listModels(stage?: 'dev' | 'staging' | 'prod'): Promise<RegistryModel[]> {
|
||||
const qs = stage ? `?stage=${encodeURIComponent(stage)}` : '';
|
||||
const data = await fetchJson<ListResponse>(`/models${qs}`);
|
||||
return data.models || [];
|
||||
}
|
||||
|
||||
/** 注册新版本。冲突(同 name+version 已存在)抛 409 错误。 */
|
||||
export async function registerModel(params: RegisterModelParams): Promise<RegistryModel> {
|
||||
return fetchJson<RegistryModel>('/models', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(params),
|
||||
});
|
||||
}
|
||||
|
||||
/** 提升 dev→staging→prod(逐级)。已在 prod 抛错。 */
|
||||
export async function promoteModel(name: string, version: string): Promise<RegistryModel> {
|
||||
return fetchJson<RegistryModel>(
|
||||
`/models/${encodeURIComponent(name)}/${encodeURIComponent(version)}/promote`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
}
|
||||
|
||||
/** 回滚某 stage 指针到指定版本。 */
|
||||
export async function rollbackModel(
|
||||
name: string,
|
||||
version: string,
|
||||
stage: 'dev' | 'staging' | 'prod' = 'prod',
|
||||
): Promise<RegistryModel> {
|
||||
const qs = `?version=${encodeURIComponent(version)}&stage=${encodeURIComponent(stage)}`;
|
||||
return fetchJson<RegistryModel>(
|
||||
`/models/${encodeURIComponent(name)}/rollback${qs}`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* iAOP 模板 JSON 加载器(Epic #163 / issue #166 [A3])
|
||||
*
|
||||
* 从 `public/iaop/plans/` 加载驾驶舱布局与告警面板模板资产(自 web/cockpit/plans 迁入):
|
||||
* ti-cl4.json —— 海绵钛驾驶舱布局(RenderPlan,iAOP-cockpit-layout-v1)
|
||||
* resin.json —— 树脂驾驶舱布局
|
||||
* alarm_panel.ti.json —— 告警面板配置(severity 配色 / SOP / 确认)
|
||||
*
|
||||
* 统一:带缓存(会话内重复加载不重发请求)+ 结构校验 + 错误提示。
|
||||
*/
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
export interface CockpitPlan {
|
||||
$schema?: string;
|
||||
title?: string;
|
||||
theme?: string;
|
||||
themeTokens?: Record<string, string>;
|
||||
grid?: { rows?: number; cols?: number; gap?: number };
|
||||
widgets?: Array<Record<string, unknown>>;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
export interface AlarmPanelConfig {
|
||||
subscribe?: string;
|
||||
severityStyles?: Record<string, Record<string, string>>;
|
||||
rulesSource?: string;
|
||||
showSop?: boolean;
|
||||
requireAck?: boolean;
|
||||
muteLower?: number;
|
||||
[k: string]: unknown;
|
||||
}
|
||||
|
||||
const CACHE = new Map<string, unknown>();
|
||||
|
||||
// 静态模板资产在 public/iaop/plans/,随 VITE_BASE 挂载(生产 /fba-admin/),
|
||||
// 必须用 BASE_URL 前缀,不能用根绝对路径(否则 nginx 子路径下 404)。
|
||||
const PLANS_BASE = `${import.meta.env.BASE_URL}iaop/plans`;
|
||||
|
||||
async function loadJson<T>(name: string, base: string): Promise<T> {
|
||||
const key = `${base}/${name}`;
|
||||
if (CACHE.has(key)) {
|
||||
return CACHE.get(key) as T;
|
||||
}
|
||||
try {
|
||||
const resp = await fetch(`${base}/${name}`);
|
||||
if (!resp.ok) {
|
||||
throw new Error(`模板 ${name} 加载失败(HTTP ${resp.status})`);
|
||||
}
|
||||
const data = (await resp.json()) as T;
|
||||
CACHE.set(key, data);
|
||||
return data;
|
||||
} catch (err) {
|
||||
message.error(`模板 ${name} 加载失败`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** 驾驶舱布局(按行业模板切换:ti-cl4 / resin) */
|
||||
export function loadCockpitPlan(template: 'ti-cl4' | 'resin'): Promise<CockpitPlan> {
|
||||
return loadJson<CockpitPlan>(`${template}.json`, PLANS_BASE);
|
||||
}
|
||||
|
||||
/** 告警面板配置 */
|
||||
export function loadAlarmPanel(): Promise<AlarmPanelConfig> {
|
||||
return loadJson<AlarmPanelConfig>('alarm_panel.ti.json', PLANS_BASE);
|
||||
}
|
||||
|
||||
/** 清理模板缓存(发布新版本后调用) */
|
||||
export function clearTemplateCache(): void {
|
||||
CACHE.clear();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export * from './core';
|
||||
export * from './data-permission';
|
||||
export * from './dept';
|
||||
export * from './log';
|
||||
export * from './monitor';
|
||||
export * from './plugin';
|
||||
export * from './role';
|
||||
export * from './scheduler';
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { PaginationResult } from '#/types';
|
||||
|
||||
import { requestClient } from './request';
|
||||
|
||||
export interface LoginLogParams {
|
||||
username?: string;
|
||||
status?: number;
|
||||
ip?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface LoginLogResult {
|
||||
id: number;
|
||||
username: string;
|
||||
status: number;
|
||||
ip: string;
|
||||
country?: string;
|
||||
region?: string;
|
||||
os?: string;
|
||||
browser?: string;
|
||||
device?: string;
|
||||
msg: string;
|
||||
login_time: string;
|
||||
}
|
||||
|
||||
export type OperaLogParams = LoginLogParams;
|
||||
|
||||
export interface OperaLogResult {
|
||||
id: number;
|
||||
trace_id: string;
|
||||
username?: string;
|
||||
method: string;
|
||||
title: string;
|
||||
path: string;
|
||||
ip: string;
|
||||
country?: string;
|
||||
region?: string;
|
||||
city?: string;
|
||||
user_agent: string;
|
||||
os?: string;
|
||||
browser?: string;
|
||||
device?: string;
|
||||
args?: JSON;
|
||||
status: number;
|
||||
code: string;
|
||||
msg: string;
|
||||
cost_time: number;
|
||||
opera_time: string;
|
||||
}
|
||||
|
||||
export async function getLoginLogListApi(params: LoginLogParams) {
|
||||
return requestClient.get<PaginationResult<LoginLogResult>>(
|
||||
'/api/v1/logs/login',
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteLoginLogApi(pks: number[]) {
|
||||
return requestClient.delete('/api/v1/logs/login', { data: { pks } });
|
||||
}
|
||||
|
||||
export async function getOperaLogListApi(params: OperaLogParams) {
|
||||
return requestClient.get<PaginationResult<OperaLogResult>>(
|
||||
'/api/v1/logs/opera',
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteOperaLogApi(pks: number[]) {
|
||||
return requestClient.delete('/api/v1/logs/opera', { data: { pks } });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { requestClient } from './request';
|
||||
|
||||
export interface ServerMonitorResult {
|
||||
cpu: Record<string, any>;
|
||||
mem: Record<string, any>;
|
||||
sys: Record<string, any>;
|
||||
disk: Record<string, any>[];
|
||||
service: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface RedisMonitorResult {
|
||||
info: Record<string, any>;
|
||||
stats: Record<string, any>[];
|
||||
}
|
||||
|
||||
export interface OnlineMonitorResult {
|
||||
id: number;
|
||||
session_uuid: string;
|
||||
username: string;
|
||||
nickname: string;
|
||||
ip: string;
|
||||
os: string;
|
||||
browser: string;
|
||||
device: string;
|
||||
status: number;
|
||||
last_login_time: string;
|
||||
expires_time: number;
|
||||
}
|
||||
|
||||
export interface MonitorOnlineParams {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface KickOutOnlineParams {
|
||||
session_uuid: string;
|
||||
}
|
||||
|
||||
export async function getServerMonitorApi() {
|
||||
return requestClient.get<ServerMonitorResult>('/api/v1/monitors/server');
|
||||
}
|
||||
|
||||
export async function getRedisMonitorApi() {
|
||||
return requestClient.get<RedisMonitorResult>('/api/v1/monitors/redis');
|
||||
}
|
||||
|
||||
export async function getOnlineMonitorApi(params: MonitorOnlineParams) {
|
||||
return requestClient.get<OnlineMonitorResult[]>('/api/v1/monitors/sessions', {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
export async function kickOutOnlineApi(
|
||||
pk: number,
|
||||
params: KickOutOnlineParams,
|
||||
) {
|
||||
return requestClient.delete(`/api/v1/monitors/sessions/${pk}`, { params });
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface PluginResult {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export async function getPluginListApi() {
|
||||
return requestClient.get<PluginResult[]>('/api/v1/sys/plugins');
|
||||
}
|
||||
|
||||
export async function getPluginChangedApi() {
|
||||
return requestClient.get<boolean>('/api/v1/sys/plugins/changed');
|
||||
}
|
||||
|
||||
export async function installZipPluginApi(file: File) {
|
||||
return await requestClient.upload(
|
||||
'/api/v1/sys/plugins',
|
||||
{ file },
|
||||
{ params: { type: 'zip' }, timeout: 60_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function installGitPluginApi(repo_url: string) {
|
||||
return await requestClient.post('/api/v1/sys/plugins', undefined, {
|
||||
params: { type: 'git', repo_url },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updatePluginStatus(plugin: string) {
|
||||
return await requestClient.put(`/api/v1/sys/plugins/${plugin}/status`);
|
||||
}
|
||||
|
||||
export async function downloadPluginApi(plugin: string) {
|
||||
return await requestClient.download<Blob>(`/api/v1/sys/plugins/${plugin}`);
|
||||
}
|
||||
|
||||
export async function uninstallPluginApi(plugin: string) {
|
||||
return await requestClient.delete(`/api/v1/sys/plugins/${plugin}`);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* 该文件可自行根据业务逻辑进行调整
|
||||
*/
|
||||
import type { RequestClientOptions } from '@vben/request';
|
||||
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import {
|
||||
authenticateResponseInterceptor,
|
||||
defaultResponseInterceptor,
|
||||
errorMessageResponseInterceptor,
|
||||
RequestClient,
|
||||
} from '@vben/request';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
import { useAuthStore } from '#/store';
|
||||
|
||||
import { refreshTokenApi } from './core';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
function createRequestClient(baseURL: string, options?: RequestClientOptions) {
|
||||
const client = new RequestClient({
|
||||
...options,
|
||||
baseURL,
|
||||
});
|
||||
|
||||
/**
|
||||
* 重新认证逻辑
|
||||
*/
|
||||
async function doReAuthenticate() {
|
||||
console.warn('Access token or refresh token is invalid or expired. ');
|
||||
const accessStore = useAccessStore();
|
||||
const authStore = useAuthStore();
|
||||
accessStore.setAccessToken(null);
|
||||
accessStore.setAccessSessionUuid(null);
|
||||
if (
|
||||
preferences.app.loginExpiredMode === 'modal' &&
|
||||
accessStore.isAccessChecked
|
||||
) {
|
||||
accessStore.setLoginExpired(true);
|
||||
} else {
|
||||
await authStore.logout();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新token逻辑
|
||||
*/
|
||||
async function doRefreshToken() {
|
||||
const accessStore = useAccessStore();
|
||||
const resp = await refreshTokenApi();
|
||||
const newToken = resp.access_token;
|
||||
accessStore.setAccessToken(newToken);
|
||||
accessStore.setAccessSessionUuid(resp.session_uuid);
|
||||
return newToken;
|
||||
}
|
||||
|
||||
function formatToken(token: null | string) {
|
||||
return token ? `Bearer ${token}` : null;
|
||||
}
|
||||
|
||||
// 请求头处理
|
||||
client.addRequestInterceptor({
|
||||
fulfilled: async (config) => {
|
||||
const accessStore = useAccessStore();
|
||||
|
||||
config.headers.Authorization = formatToken(accessStore.accessToken);
|
||||
config.headers['Accept-Language'] = preferences.app.locale;
|
||||
return config;
|
||||
},
|
||||
});
|
||||
|
||||
// 处理返回的响应数据格式
|
||||
client.addResponseInterceptor(
|
||||
defaultResponseInterceptor({
|
||||
codeField: 'code',
|
||||
dataField: 'data',
|
||||
successCode: 200,
|
||||
}),
|
||||
);
|
||||
|
||||
// token过期的处理
|
||||
client.addResponseInterceptor(
|
||||
authenticateResponseInterceptor({
|
||||
client,
|
||||
doReAuthenticate,
|
||||
doRefreshToken,
|
||||
enableRefreshToken: preferences.app.enableRefreshToken,
|
||||
formatToken,
|
||||
}),
|
||||
);
|
||||
|
||||
// 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里
|
||||
client.addResponseInterceptor(
|
||||
errorMessageResponseInterceptor((msg: string, error) => {
|
||||
// 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg
|
||||
// 当前mock接口返回的错误字段是 error 或者 message
|
||||
const responseData = error?.response?.data ?? {};
|
||||
const errorMessage =
|
||||
responseData?.error ?? responseData?.msg ?? error?.msg ?? '';
|
||||
// 如果没有错误信息,则会根据状态码进行提示
|
||||
message.error(errorMessage || msg);
|
||||
}),
|
||||
);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
function createMiniRequestClient(
|
||||
baseURL: string,
|
||||
options?: RequestClientOptions,
|
||||
) {
|
||||
const client = new RequestClient({
|
||||
...options,
|
||||
baseURL,
|
||||
});
|
||||
|
||||
// 处理返回的响应数据格式
|
||||
client.addResponseInterceptor(
|
||||
defaultResponseInterceptor({
|
||||
codeField: 'code',
|
||||
dataField: 'data',
|
||||
successCode: 200,
|
||||
}),
|
||||
);
|
||||
|
||||
// 通用的错误处理
|
||||
client.addResponseInterceptor(
|
||||
errorMessageResponseInterceptor((msg: string, error) => {
|
||||
const responseData = error?.response?.data ?? {};
|
||||
const errorMessage =
|
||||
responseData?.error ?? responseData?.msg ?? error?.msg ?? '';
|
||||
message.error(errorMessage || msg);
|
||||
}),
|
||||
);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
export const requestClient = createRequestClient(apiURL, {
|
||||
responseReturn: 'data',
|
||||
});
|
||||
|
||||
export const miniRequestClient = createMiniRequestClient(apiURL, {
|
||||
responseReturn: 'data',
|
||||
});
|
||||
|
||||
export const baseRequestClient = new RequestClient({ baseURL: apiURL });
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { RouteRecordStringComponent } from '@vben/types';
|
||||
|
||||
import { requestClient } from './request';
|
||||
|
||||
export interface SysRoleParams {
|
||||
name?: string;
|
||||
status?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface SysRoleResult {
|
||||
id: number;
|
||||
name: string;
|
||||
status: number;
|
||||
is_filter_scopes: boolean;
|
||||
remark?: string;
|
||||
created_time: string;
|
||||
updated_time: string;
|
||||
}
|
||||
|
||||
export interface CreateSysRoleParams {
|
||||
name: string;
|
||||
status: number;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取系统角色列表
|
||||
*/
|
||||
export async function getSysRoleListApi(params: SysRoleParams) {
|
||||
return requestClient.get<SysRoleResult[]>('/api/v1/sys/roles', { params });
|
||||
}
|
||||
|
||||
export async function getAllSysRoleApi() {
|
||||
return requestClient.get<SysRoleResult[]>('/api/v1/sys/roles/all');
|
||||
}
|
||||
|
||||
export async function getSysRoleMenuApi(pk: number) {
|
||||
return requestClient.get<RouteRecordStringComponent[]>(
|
||||
`/api/v1/sys/roles/${pk}/menus`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSysRoleDataScopesApi(pk: number) {
|
||||
return requestClient.get<number[]>(`/api/v1/sys/roles/${pk}/scopes`);
|
||||
}
|
||||
|
||||
export async function createSysRoleApi(data: CreateSysRoleParams) {
|
||||
return requestClient.post('/api/v1/sys/roles', data);
|
||||
}
|
||||
|
||||
export async function updateSysRoleApi(pk: number, data: CreateSysRoleParams) {
|
||||
return requestClient.put(`/api/v1/sys/roles/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function updateSysRoleMenuApi(pk: number, menus: number[]) {
|
||||
return requestClient.put(`/api/v1/sys/roles/${pk}/menus`, { menus });
|
||||
}
|
||||
|
||||
export async function updateSysRoleDataScopesApi(pk: number, scopes: number[]) {
|
||||
return requestClient.put(`/api/v1/sys/roles/${pk}/scopes`, { scopes });
|
||||
}
|
||||
|
||||
export async function deleteSysRoleApi(pks: number[]) {
|
||||
return requestClient.delete(`/api/v1/sys/roles`, { data: { pks } });
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { Dayjs } from 'dayjs';
|
||||
|
||||
import type { PaginationResult } from '#/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface TaskResultParams {
|
||||
name?: string;
|
||||
task_id?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface TaskSchedulerParams {
|
||||
name?: string;
|
||||
type?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface TaskResult {
|
||||
id: number;
|
||||
task_id: string;
|
||||
status: string;
|
||||
result?: string;
|
||||
date_done?: string;
|
||||
traceback?: string;
|
||||
name?: string;
|
||||
args?: string;
|
||||
kwargs?: string;
|
||||
worker?: string;
|
||||
retries?: number;
|
||||
queue?: string;
|
||||
}
|
||||
|
||||
export interface CreateTaskSchedulerParams {
|
||||
name: string;
|
||||
task: string;
|
||||
args?: string;
|
||||
kwargs?: string;
|
||||
queue?: string;
|
||||
exchange?: string;
|
||||
routing_key?: string;
|
||||
start_time?: Dayjs;
|
||||
expire_time?: Dayjs;
|
||||
expire_seconds?: number;
|
||||
type: number;
|
||||
interval_every?: number;
|
||||
interval_period?: string;
|
||||
crontab: string;
|
||||
one_off: boolean;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface TaskSchedulerResult extends CreateTaskSchedulerParams {
|
||||
id: number;
|
||||
enabled: boolean;
|
||||
total_run_count: number;
|
||||
last_run_time: string;
|
||||
created_time: string;
|
||||
updated_time?: string;
|
||||
}
|
||||
|
||||
export async function getTaskResultApi(pk: number) {
|
||||
return requestClient.get<TaskResult>(`/api/v1/task-results/${pk}`);
|
||||
}
|
||||
|
||||
export async function getTaskResultListApi(params?: TaskResultParams) {
|
||||
return requestClient.get<PaginationResult<TaskSchedulerResult>>(
|
||||
'/api/v1/task-results',
|
||||
{
|
||||
params,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteTaskResultApi(pks: number[]) {
|
||||
return requestClient.delete('/api/v1/task-results', { data: { pks } });
|
||||
}
|
||||
|
||||
export async function getAllTaskSchedulerApi() {
|
||||
return requestClient.get<TaskSchedulerResult[]>('/api/v1/schedulers/all');
|
||||
}
|
||||
|
||||
export async function getTaskSchedulerListApi(params?: TaskSchedulerParams) {
|
||||
return requestClient.get<PaginationResult<TaskSchedulerResult>>(
|
||||
'/api/v1/schedulers',
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
export async function getTaskSchedulerApi(pk: number) {
|
||||
return requestClient.get<TaskSchedulerResult>(`/api/v1/schedulers/${pk}`);
|
||||
}
|
||||
|
||||
export async function createTaskSchedulerApi(data: CreateTaskSchedulerParams) {
|
||||
return requestClient.post('/api/v1/schedulers', data);
|
||||
}
|
||||
|
||||
export async function updateTaskSchedulerApi(
|
||||
pk: number,
|
||||
data: CreateTaskSchedulerParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/schedulers/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function updateTaskSchedulerStatusApi(pk: number) {
|
||||
return requestClient.put(`/api/v1/schedulers/${pk}/status`);
|
||||
}
|
||||
|
||||
export async function deleteTaskSchedulerApi(pk: number) {
|
||||
return requestClient.delete(`/api/v1/schedulers/${pk}`);
|
||||
}
|
||||
|
||||
export async function executeTaskSchedulerApi(pk: number) {
|
||||
return requestClient.post(`/api/v1/schedulers/${pk}/execute`);
|
||||
}
|
||||
|
||||
export async function getTaskRegisteredApi() {
|
||||
return requestClient.get<any[]>('/api/v1/tasks/registered');
|
||||
}
|
||||
|
||||
export async function revokeTaskSchedulerApi(task_id: string) {
|
||||
return requestClient.delete(`/api/v1/tasks/${task_id}/cancel`);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, watch } from 'vue';
|
||||
|
||||
import { useAntdDesignTokens } from '@vben/hooks';
|
||||
import { preferences, usePreferences } from '@vben/preferences';
|
||||
|
||||
import { App, ConfigProvider, theme } from 'antdv-next';
|
||||
|
||||
import { antdLocale } from '#/locales';
|
||||
|
||||
defineOptions({ name: 'App' });
|
||||
|
||||
const { isDark } = usePreferences();
|
||||
const { tokens } = useAntdDesignTokens();
|
||||
|
||||
const tokenTheme = computed(() => {
|
||||
const algorithm = isDark.value
|
||||
? [theme.darkAlgorithm]
|
||||
: [theme.defaultAlgorithm];
|
||||
|
||||
// antd 紧凑模式算法
|
||||
if (preferences.app.compact) {
|
||||
algorithm.push(theme.compactAlgorithm);
|
||||
}
|
||||
|
||||
return {
|
||||
algorithm,
|
||||
token: tokens,
|
||||
};
|
||||
});
|
||||
|
||||
watch(
|
||||
tokenTheme,
|
||||
(themeConfig) => {
|
||||
ConfigProvider.config({ theme: themeConfig });
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ConfigProvider :locale="antdLocale" :theme="tokenTheme">
|
||||
<App>
|
||||
<RouterView />
|
||||
</App>
|
||||
</ConfigProvider>
|
||||
</template>
|
||||
@@ -0,0 +1,80 @@
|
||||
import { createApp, watchEffect } from 'vue';
|
||||
|
||||
import { registerAccessDirective } from '@vben/access';
|
||||
import { registerLoadingDirective } from '@vben/common-ui/es/loading';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { initStores } from '@vben/stores';
|
||||
import '@vben/styles';
|
||||
import '@vben/styles/antdv-next';
|
||||
|
||||
import { useTitle } from '@vueuse/core';
|
||||
import Antd from 'antdv-next';
|
||||
|
||||
import { $t, setupI18n } from '#/locales';
|
||||
|
||||
import { initComponentAdapter } from './adapter/component';
|
||||
import { initSetupVbenForm } from './adapter/form';
|
||||
import App from './app.vue';
|
||||
import { router } from './router';
|
||||
|
||||
async function bootstrap(namespace: string) {
|
||||
// 初始化组件适配器
|
||||
await initComponentAdapter();
|
||||
|
||||
// 初始化表单组件
|
||||
await initSetupVbenForm();
|
||||
|
||||
// // 设置弹窗的默认配置
|
||||
// setDefaultModalProps({
|
||||
// fullscreenButton: false,
|
||||
// });
|
||||
// // 设置抽屉的默认配置
|
||||
// setDefaultDrawerProps({
|
||||
// zIndex: 1020,
|
||||
// });
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
// 注册v-loading指令
|
||||
registerLoadingDirective(app, {
|
||||
loading: 'loading', // 在这里可以自定义指令名称,也可以明确提供false表示不注册这个指令
|
||||
spinning: 'spinning',
|
||||
});
|
||||
|
||||
// 国际化 i18n 配置
|
||||
await setupI18n(app);
|
||||
|
||||
// 配置 pinia-tore
|
||||
await initStores(app, { namespace });
|
||||
|
||||
// 安装权限指令
|
||||
registerAccessDirective(app);
|
||||
|
||||
// 初始化 tippy
|
||||
const { initTippy } = await import('@vben/common-ui/es/tippy');
|
||||
initTippy(app);
|
||||
|
||||
// 全局加载 antdv
|
||||
app.use(Antd);
|
||||
|
||||
// 配置路由及路由守卫
|
||||
app.use(router);
|
||||
|
||||
// 配置Motion插件
|
||||
const { MotionPlugin } = await import('@vben/plugins/motion');
|
||||
app.use(MotionPlugin);
|
||||
|
||||
// 动态更新标题
|
||||
watchEffect(() => {
|
||||
if (preferences.app.dynamicTitle) {
|
||||
const routeTitle = router.currentRoute.value.meta?.title;
|
||||
const pageTitle =
|
||||
(routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name;
|
||||
useTitle(pageTitle);
|
||||
}
|
||||
});
|
||||
|
||||
app.mount('#app');
|
||||
}
|
||||
|
||||
export { bootstrap };
|
||||
@@ -0,0 +1,25 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue';
|
||||
|
||||
import { AuthPageLayout } from '@vben/layouts';
|
||||
import { preferences } from '@vben/preferences';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
|
||||
const appName = computed(() => preferences.app.name);
|
||||
const logo = computed(() => preferences.logo.source);
|
||||
const logoDark = computed(() => preferences.logo.sourceDark);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AuthPageLayout
|
||||
:app-name="appName"
|
||||
:logo="logo"
|
||||
:logo-dark="logoDark"
|
||||
:page-description="$t('authentication.pageDesc')"
|
||||
:page-title="$t('authentication.pageTitle')"
|
||||
>
|
||||
<!-- 自定义工具栏 -->
|
||||
<!-- <template #toolbar></template> -->
|
||||
</AuthPageLayout>
|
||||
</template>
|
||||
@@ -0,0 +1,256 @@
|
||||
<script lang="ts" setup>
|
||||
import type { NotificationItem } from '@vben/layouts';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { AuthenticationLoginExpiredModal } from '@vben/common-ui';
|
||||
import { VBEN_DOC_URL, VBEN_GITHUB_URL } from '@vben/constants';
|
||||
import { useWatermark } from '@vben/hooks';
|
||||
import { BookOpenText, CircleHelp, SvgGithubIcon } from '@vben/icons';
|
||||
import {
|
||||
BasicLayout,
|
||||
LockScreen,
|
||||
Notification,
|
||||
UserDropdown,
|
||||
} from '@vben/layouts';
|
||||
import { preferences, usePreferences } from '@vben/preferences';
|
||||
import { useAccessStore, useUserStore } from '@vben/stores';
|
||||
import { openWindow } from '@vben/utils';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
import { useAuthStore } from '#/store';
|
||||
import LoginForm from '#/views/_core/authentication/login.vue';
|
||||
|
||||
const notifications = ref<NotificationItem[]>([
|
||||
{
|
||||
id: 1,
|
||||
avatar: 'https://avatar.vercel.sh/vercel.svg?text=VB',
|
||||
date: '3小时前',
|
||||
isRead: true,
|
||||
message: '描述信息描述信息描述信息',
|
||||
title: '收到了 14 份新周报',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
avatar: 'https://avatar.vercel.sh/1',
|
||||
date: '刚刚',
|
||||
isRead: false,
|
||||
message: '描述信息描述信息描述信息',
|
||||
title: '朱偏右 回复了你',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
avatar: 'https://avatar.vercel.sh/1',
|
||||
date: '2024-01-01',
|
||||
isRead: false,
|
||||
message: '描述信息描述信息描述信息',
|
||||
title: '曲丽丽 评论了你',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
avatar: 'https://avatar.vercel.sh/satori',
|
||||
date: '1天前',
|
||||
isRead: false,
|
||||
message: '描述信息描述信息描述信息',
|
||||
title: '代办提醒',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
avatar: 'https://avatar.vercel.sh/satori',
|
||||
date: '1天前',
|
||||
isRead: false,
|
||||
message: '描述信息描述信息描述信息',
|
||||
title: '跳转Workspace示例',
|
||||
link: '/workspace',
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
avatar: 'https://avatar.vercel.sh/satori',
|
||||
date: '1天前',
|
||||
isRead: false,
|
||||
message: '描述信息描述信息描述信息',
|
||||
title: '跳转外部链接示例',
|
||||
link: 'https://doc.vben.pro',
|
||||
},
|
||||
]);
|
||||
|
||||
const router = useRouter();
|
||||
const userStore = useUserStore();
|
||||
const authStore = useAuthStore();
|
||||
const accessStore = useAccessStore();
|
||||
const { destroyWatermark, updateWatermark } = useWatermark();
|
||||
const { isDark } = usePreferences();
|
||||
const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
const menus = computed(() => [
|
||||
{
|
||||
handler: () => {
|
||||
router.push({ name: 'Profile' });
|
||||
},
|
||||
icon: 'lucide:user',
|
||||
text: $t('page.auth.profile'),
|
||||
},
|
||||
{
|
||||
handler: () => {
|
||||
openWindow(VBEN_DOC_URL, {
|
||||
target: '_blank',
|
||||
});
|
||||
},
|
||||
icon: BookOpenText,
|
||||
text: $t('ui.widgets.document'),
|
||||
},
|
||||
{
|
||||
handler: () => {
|
||||
openWindow(VBEN_GITHUB_URL, {
|
||||
target: '_blank',
|
||||
});
|
||||
},
|
||||
icon: SvgGithubIcon,
|
||||
text: 'GitHub',
|
||||
},
|
||||
{
|
||||
handler: () => {
|
||||
openWindow(`${VBEN_GITHUB_URL}/issues`, {
|
||||
target: '_blank',
|
||||
});
|
||||
},
|
||||
icon: CircleHelp,
|
||||
text: $t('ui.widgets.qa'),
|
||||
},
|
||||
]);
|
||||
|
||||
const avatar = computed(() => {
|
||||
return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
|
||||
});
|
||||
|
||||
async function handleLogout() {
|
||||
await authStore.logout(false);
|
||||
}
|
||||
|
||||
function handleNoticeClear() {
|
||||
notifications.value = [];
|
||||
}
|
||||
|
||||
function markRead(id: number | string) {
|
||||
const item = notifications.value.find((item) => item.id === id);
|
||||
if (item) {
|
||||
item.isRead = true;
|
||||
}
|
||||
}
|
||||
|
||||
function remove(id: number | string) {
|
||||
notifications.value = notifications.value.filter((item) => item.id !== id);
|
||||
}
|
||||
|
||||
function handleMakeAll() {
|
||||
notifications.value.forEach((item) => (item.isRead = true));
|
||||
}
|
||||
|
||||
const viewAll = () => {};
|
||||
|
||||
const handleClick = (item: NotificationItem) => {
|
||||
// 如果通知项有链接,点击时跳转
|
||||
if (item.link) {
|
||||
navigateTo(item.link, item.query, item.state);
|
||||
}
|
||||
};
|
||||
|
||||
function navigateTo(
|
||||
link: string,
|
||||
query?: Record<string, any>,
|
||||
state?: Record<string, any>,
|
||||
) {
|
||||
if (link.startsWith('http://') || link.startsWith('https://')) {
|
||||
// 外部链接,在新标签页打开
|
||||
window.open(link, '_blank');
|
||||
} else {
|
||||
// 内部路由链接,支持 query 参数和 state
|
||||
router.push({
|
||||
path: link,
|
||||
query: query || {},
|
||||
state,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => ({
|
||||
enable: preferences.app.watermark,
|
||||
content: preferences.app.watermarkContent,
|
||||
isDark: isDark.value,
|
||||
}),
|
||||
async ({ enable, content, isDark: isDarkValue }) => {
|
||||
if (enable) {
|
||||
const watermarkColor = isDarkValue
|
||||
? 'rgba(255, 255, 255, 0.12)'
|
||||
: 'rgba(0, 0, 0, 0.12)';
|
||||
|
||||
await updateWatermark({
|
||||
advancedStyle: {
|
||||
colorStops: [
|
||||
{
|
||||
color: watermarkColor,
|
||||
offset: 0,
|
||||
},
|
||||
{
|
||||
color: watermarkColor,
|
||||
offset: 1,
|
||||
},
|
||||
],
|
||||
type: 'linear',
|
||||
},
|
||||
content:
|
||||
content ||
|
||||
`${userStore.userInfo?.username} - ${userStore.userInfo?.realName}`,
|
||||
});
|
||||
} else {
|
||||
destroyWatermark();
|
||||
}
|
||||
},
|
||||
{
|
||||
immediate: true,
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BasicLayout @clear-preferences-and-logout="handleLogout">
|
||||
<template #user-dropdown>
|
||||
<UserDropdown
|
||||
:avatar
|
||||
:menus
|
||||
:text="userStore.userInfo?.realName"
|
||||
description="ann.vben@gmail.com"
|
||||
tag-text="Pro"
|
||||
@logout="handleLogout"
|
||||
@clear-preferences-and-logout="handleLogout"
|
||||
/>
|
||||
</template>
|
||||
<template #notification>
|
||||
<Notification
|
||||
:dot="showDot"
|
||||
:notifications="notifications"
|
||||
@clear="handleNoticeClear"
|
||||
@read="(item) => item.id && markRead(item.id)"
|
||||
@remove="(item) => item.id && remove(item.id)"
|
||||
@make-all="handleMakeAll"
|
||||
@on-click="handleClick"
|
||||
@view-all="viewAll"
|
||||
/>
|
||||
</template>
|
||||
<template #extra>
|
||||
<AuthenticationLoginExpiredModal
|
||||
v-model:open="accessStore.loginExpired"
|
||||
:avatar
|
||||
>
|
||||
<LoginForm />
|
||||
</AuthenticationLoginExpiredModal>
|
||||
</template>
|
||||
<template #lock-screen>
|
||||
<LockScreen :avatar @to-login="handleLogout" />
|
||||
</template>
|
||||
</BasicLayout>
|
||||
</template>
|
||||
@@ -0,0 +1,6 @@
|
||||
const BasicLayout = () => import('./basic.vue');
|
||||
const AuthPageLayout = () => import('./auth.vue');
|
||||
|
||||
const IFrameView = () => import('@vben/layouts').then((m) => m.IFrameView);
|
||||
|
||||
export { AuthPageLayout, BasicLayout, IFrameView };
|
||||
@@ -0,0 +1,3 @@
|
||||
# locale
|
||||
|
||||
每个app使用的国际化可能不同,这里用于扩展国际化的功能,例如扩展 dayjs、antd组件库的多语言切换,以及app本身的国际化文件。
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { Locale } from 'antdv-next/dist/locale/index';
|
||||
|
||||
import type { App } from 'vue';
|
||||
|
||||
import type { LocaleSetupOptions, SupportedLanguagesType } from '@vben/locales';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import {
|
||||
$t,
|
||||
setupI18n as coreSetup,
|
||||
loadLocalesMapFromDir,
|
||||
} from '@vben/locales';
|
||||
import { preferences } from '@vben/preferences';
|
||||
|
||||
import antdEnLocale from 'antdv-next/dist/locale/en_US';
|
||||
import antdDefaultLocale from 'antdv-next/dist/locale/zh_CN';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
const antdLocale = ref<Locale>(antdDefaultLocale);
|
||||
|
||||
const modules = import.meta.glob('./langs/**/*.json');
|
||||
|
||||
const pluginModules = import.meta.glob('../plugins/**/langs/**/*.json');
|
||||
|
||||
const localesMap = loadLocalesMapFromDir(
|
||||
/\.\/langs\/([^/]+)\/(.*)\.json$/,
|
||||
modules,
|
||||
);
|
||||
|
||||
const pluginLocalesMap = loadLocalesMapFromDir(
|
||||
/\/plugins\/[^/]+\/langs\/([^/]+)\/([^/]+)\.json$/,
|
||||
pluginModules,
|
||||
);
|
||||
/**
|
||||
* 加载应用特有的语言包
|
||||
* 这里也可以改造为从服务端获取翻译数据
|
||||
* @param lang
|
||||
*/
|
||||
async function loadMessages(lang: SupportedLanguagesType) {
|
||||
const [appLocaleMessages, pluginLocalMessages] = await Promise.all([
|
||||
localesMap[lang]?.(),
|
||||
pluginLocalesMap[lang]?.(),
|
||||
loadThirdPartyMessage(lang),
|
||||
]);
|
||||
return { ...appLocaleMessages?.default, ...pluginLocalMessages?.default };
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载第三方组件库的语言包
|
||||
* @param lang
|
||||
*/
|
||||
async function loadThirdPartyMessage(lang: SupportedLanguagesType) {
|
||||
await Promise.all([loadAntdLocale(lang), loadDayjsLocale(lang)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载dayjs的语言包
|
||||
* @param lang
|
||||
*/
|
||||
async function loadDayjsLocale(lang: SupportedLanguagesType) {
|
||||
let locale;
|
||||
switch (lang) {
|
||||
case 'en-US': {
|
||||
locale = await import('dayjs/locale/en');
|
||||
break;
|
||||
}
|
||||
case 'zh-CN': {
|
||||
locale = await import('dayjs/locale/zh-cn');
|
||||
break;
|
||||
}
|
||||
// 默认使用英语
|
||||
default: {
|
||||
locale = await import('dayjs/locale/en');
|
||||
}
|
||||
}
|
||||
if (locale) {
|
||||
dayjs.locale(locale);
|
||||
} else {
|
||||
console.error(`Failed to load dayjs locale for ${lang}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载antd的语言包
|
||||
* @param lang
|
||||
*/
|
||||
async function loadAntdLocale(lang: SupportedLanguagesType) {
|
||||
switch (lang) {
|
||||
case 'en-US': {
|
||||
antdLocale.value = antdEnLocale;
|
||||
break;
|
||||
}
|
||||
case 'zh-CN': {
|
||||
antdLocale.value = antdDefaultLocale;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function setupI18n(app: App, options: LocaleSetupOptions = {}) {
|
||||
await coreSetup(app, {
|
||||
defaultLocale: preferences.app.locale,
|
||||
loadMessages,
|
||||
missingWarn: !import.meta.env.PROD,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
export { $t, antdLocale, setupI18n };
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"form": {
|
||||
"query": "Query",
|
||||
"select": "Please select",
|
||||
"status": "Status"
|
||||
},
|
||||
"table": {
|
||||
"created_time": "Created Time",
|
||||
"id": "ID",
|
||||
"mark": "Mark",
|
||||
"operation": "Operation",
|
||||
"updated_time": "Updated time"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"title": "Demos",
|
||||
"antd": "Antdv Next",
|
||||
"vben": {
|
||||
"title": "Project",
|
||||
"about": "About",
|
||||
"document": "Document",
|
||||
"antdv": "Ant Design Vue Version",
|
||||
"antdv-next": "Antdv Next Version",
|
||||
"naive-ui": "Naive UI Version",
|
||||
"element-plus": "Element Plus Version",
|
||||
"tdesign": "TDesign Vue Version"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"auth": {
|
||||
"login": "Login",
|
||||
"register": "Register",
|
||||
"codeLogin": "Code Login",
|
||||
"qrcodeLogin": "Qr Code Login",
|
||||
"forgetPassword": "Forget Password",
|
||||
"captchaPlaceholder": "Please enter the captcha",
|
||||
"captchaRequired": "The captcha is required",
|
||||
"profile": "Profile"
|
||||
},
|
||||
"dashboard": {
|
||||
"title": "Dashboard",
|
||||
"analytics": "Analytics",
|
||||
"workspace": "Workspace"
|
||||
},
|
||||
"menu": {
|
||||
"system": "System",
|
||||
"scheduler": "Scheduler",
|
||||
"schedulerManage": "Manage",
|
||||
"schedulerRecord": "Record",
|
||||
"log": "System Log",
|
||||
"login": "Login",
|
||||
"monitor": "System Monitor",
|
||||
"opera": "Opera",
|
||||
"online": "Online",
|
||||
"redis": "Redis",
|
||||
"server": "Server",
|
||||
"sysDataPermission": "Data Permission",
|
||||
"sysDataScope": "Data Scope",
|
||||
"sysDataRule": "Data Rule",
|
||||
"sysPlugin": "Plugin",
|
||||
"sysDept": "Dept",
|
||||
"sysMenu": "User",
|
||||
"sysRole": "Role",
|
||||
"sysUser": "User",
|
||||
"profile": "Profile"
|
||||
},
|
||||
"monitor": {
|
||||
"redis": {
|
||||
"cards": {
|
||||
"commands": {
|
||||
"title": "Command Statistics"
|
||||
},
|
||||
"memory": {
|
||||
"title": "Memory Status"
|
||||
}
|
||||
},
|
||||
"info": {
|
||||
"title": "Server Info",
|
||||
"redis_version": "Version",
|
||||
"redis_mode": "Mode",
|
||||
"role": "Role",
|
||||
"tcp_port": "TCP Port",
|
||||
"uptime": "Uptime",
|
||||
"connected_clients": "Connected Clients",
|
||||
"blocked_clients": "Blocked Clients",
|
||||
"used_memory_human": "Used Memory",
|
||||
"used_memory_rss_human": "RSS Memory",
|
||||
"maxmemory_human": "Max Memory",
|
||||
"mem_fragmentation_ratio": "Fragmentation Ratio",
|
||||
"total_commands_processed": "Commands Processed",
|
||||
"instantaneous_ops_per_sec": "Ops/Sec",
|
||||
"rejected_connections": "Rejected Connections",
|
||||
"keys_num": "Keys"
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"cpu": {
|
||||
"title": "CPU",
|
||||
"current_freq": "Current Freq (MHz)",
|
||||
"logical_num": "Logical Cores",
|
||||
"physical_num": "Physical Cores",
|
||||
"usage": "CPU Usage"
|
||||
},
|
||||
"disk": {
|
||||
"title": "Disk",
|
||||
"device": "Device",
|
||||
"dir": "Mount Point",
|
||||
"free": "Free",
|
||||
"total": "Total",
|
||||
"type": "Type",
|
||||
"usage": "Usage",
|
||||
"used": "Used"
|
||||
},
|
||||
"memory": {
|
||||
"title": "Memory",
|
||||
"free": "Free",
|
||||
"total": "Total",
|
||||
"usage": "Usage",
|
||||
"used": "Used"
|
||||
},
|
||||
"service": {
|
||||
"title": "Service Info",
|
||||
"name": "Service Name",
|
||||
"version": "Version",
|
||||
"home": "Home Path",
|
||||
"cpu_usage": "CPU Usage",
|
||||
"mem_vms": "Virtual Memory",
|
||||
"mem_rss": "Physical Memory",
|
||||
"mem_free": "Free Memory",
|
||||
"startup": "Startup Time",
|
||||
"elapsed": "Elapsed Time"
|
||||
},
|
||||
"system": {
|
||||
"title": "System Info",
|
||||
"name": "Hostname",
|
||||
"ip": "IP Address",
|
||||
"os": "OS",
|
||||
"arch": "Architecture"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"form": {
|
||||
"query": "查询",
|
||||
"select": "请选择",
|
||||
"status": "状态"
|
||||
},
|
||||
"table": {
|
||||
"created_time": "创建时间",
|
||||
"id": "序号",
|
||||
"mark": "备注",
|
||||
"operation": "操作",
|
||||
"updated_time": "更新时间"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"title": "演示",
|
||||
"antd": "Antdv Next",
|
||||
"vben": {
|
||||
"title": "项目",
|
||||
"about": "关于",
|
||||
"document": "文档",
|
||||
"antdv": "Ant Design Vue 版本",
|
||||
"antdv-next": "Antdv Next 版本",
|
||||
"naive-ui": "Naive UI 版本",
|
||||
"element-plus": "Element Plus 版本",
|
||||
"tdesign": "TDesign Vue 版本"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"auth": {
|
||||
"login": "登录",
|
||||
"register": "注册",
|
||||
"codeLogin": "验证码登录",
|
||||
"qrcodeLogin": "二维码登录",
|
||||
"forgetPassword": "忘记密码",
|
||||
"captchaPlaceholder": "请输入验证码",
|
||||
"captchaRequired": "验证码是必须的",
|
||||
"profile": "个人中心"
|
||||
},
|
||||
"dashboard": {
|
||||
"title": "概览",
|
||||
"analytics": "分析页",
|
||||
"workspace": "工作台"
|
||||
},
|
||||
"menu": {
|
||||
"system": "系统管理",
|
||||
"scheduler": "任务调度",
|
||||
"schedulerManage": "任务管理",
|
||||
"schedulerRecord": "执行记录",
|
||||
"log": "日志管理",
|
||||
"login": "登录日志",
|
||||
"monitor": "系统监控",
|
||||
"opera": "操作日志",
|
||||
"online": "在线用户",
|
||||
"redis": "Redis",
|
||||
"server": "服务器",
|
||||
"sysDataPermission": "数据权限",
|
||||
"sysDataScope": "数据范围",
|
||||
"sysDataRule": "数据规则",
|
||||
"sysPlugin": "插件管理",
|
||||
"sysDept": "部门管理",
|
||||
"sysMenu": "菜单管理",
|
||||
"sysRole": "角色管理",
|
||||
"sysUser": "用户管理",
|
||||
"profile": "个人中心"
|
||||
},
|
||||
"monitor": {
|
||||
"redis": {
|
||||
"cards": {
|
||||
"commands": {
|
||||
"title": "命令统计"
|
||||
},
|
||||
"memory": {
|
||||
"title": "内存使用"
|
||||
}
|
||||
},
|
||||
"info": {
|
||||
"title": "服务器信息",
|
||||
"redis_version": "版本",
|
||||
"redis_mode": "运行模式",
|
||||
"role": "节点角色",
|
||||
"tcp_port": "监听端口",
|
||||
"uptime": "运行时长",
|
||||
"connected_clients": "已连接客户端数",
|
||||
"blocked_clients": "阻塞客户端数",
|
||||
"used_memory_human": "已使用内存",
|
||||
"used_memory_rss_human": "RSS 内存",
|
||||
"maxmemory_human": "最大内存限制",
|
||||
"mem_fragmentation_ratio": "内存碎片率",
|
||||
"total_commands_processed": "命令处理总数",
|
||||
"instantaneous_ops_per_sec": "每秒操作数",
|
||||
"rejected_connections": "拒绝连接数",
|
||||
"keys_num": "键总数"
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"cpu": {
|
||||
"title": "CPU 信息",
|
||||
"current_freq": "当前频率 (MHz)",
|
||||
"logical_num": "逻辑核心数",
|
||||
"physical_num": "物理核心数",
|
||||
"usage": "CPU 使用率"
|
||||
},
|
||||
"disk": {
|
||||
"title": "磁盘信息",
|
||||
"device": "设备名称",
|
||||
"dir": "挂载点",
|
||||
"free": "可用",
|
||||
"total": "总容量",
|
||||
"type": "文件系统类型",
|
||||
"usage": "使用率",
|
||||
"used": "已使用"
|
||||
},
|
||||
"memory": {
|
||||
"free": "可用",
|
||||
"title": "内存信息",
|
||||
"total": "总量",
|
||||
"usage": "使用率",
|
||||
"used": "已使用"
|
||||
},
|
||||
"service": {
|
||||
"title": "服务信息",
|
||||
"name": "服务名称",
|
||||
"version": "版本",
|
||||
"home": "安装路径",
|
||||
"cpu_usage": "CPU 使用率",
|
||||
"mem_vms": "虚拟内存",
|
||||
"mem_rss": "物理内存",
|
||||
"mem_free": "可用内存",
|
||||
"startup": "启动时间",
|
||||
"elapsed": "运行时长"
|
||||
},
|
||||
"system": {
|
||||
"title": "系统信息",
|
||||
"name": "主机名",
|
||||
"ip": "IP 地址",
|
||||
"os": "操作系统",
|
||||
"arch": "系统架构"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { initPreferences } from '@vben/preferences';
|
||||
import { unmountGlobalLoading } from '@vben/utils';
|
||||
|
||||
import { overridesPreferences } from './preferences';
|
||||
|
||||
/**
|
||||
* 应用初始化完成之后再进行页面加载渲染
|
||||
*/
|
||||
async function initApplication() {
|
||||
// name用于指定项目唯一标识
|
||||
// 用于区分不同项目的偏好设置以及存储数据的key前缀以及其他一些需要隔离的数据
|
||||
const env = import.meta.env.PROD ? 'prod' : 'dev';
|
||||
const appVersion = import.meta.env.VITE_APP_VERSION;
|
||||
const namespace = `${import.meta.env.VITE_APP_NAMESPACE}-${appVersion}-${env}`;
|
||||
|
||||
// app偏好设置初始化
|
||||
await initPreferences({
|
||||
namespace,
|
||||
overrides: overridesPreferences,
|
||||
});
|
||||
|
||||
// 启动应用并挂载
|
||||
// vue应用主要逻辑及视图
|
||||
const { bootstrap } = await import('./bootstrap');
|
||||
await bootstrap(namespace);
|
||||
|
||||
// 移除并销毁loading
|
||||
unmountGlobalLoading();
|
||||
}
|
||||
|
||||
initApplication();
|
||||
@@ -0,0 +1,12 @@
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
interface phoneCaptchaParams {
|
||||
phone: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送短信验证码
|
||||
*/
|
||||
export async function getPhoneCaptchaApi(data: phoneCaptchaParams) {
|
||||
return requestClient.post('/api/v1/phones/captcha', data);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "@fba-ui/aliyun-sms",
|
||||
"version": "5.7.0",
|
||||
"private": true,
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { Recordable } from '@vben/types';
|
||||
|
||||
import type { PaginationResult } from '#/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface QueryCodeGenBusinessParams {
|
||||
table_name?: string;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface CodeGenBusinessParams {
|
||||
app_name: string;
|
||||
table_name: string;
|
||||
doc_comment: string;
|
||||
table_comment?: string;
|
||||
class_name?: string;
|
||||
schema_name?: string;
|
||||
filename?: string;
|
||||
datetime_mixin?: boolean;
|
||||
api_version?: string;
|
||||
tag?: string;
|
||||
gen_path?: string;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface CodeGenBusinessResult extends CodeGenBusinessParams {
|
||||
id: number;
|
||||
created_time: string;
|
||||
updated_time: string;
|
||||
}
|
||||
|
||||
export interface CodeGenColumnParams {
|
||||
name: string;
|
||||
comment?: string;
|
||||
type: string;
|
||||
default?: string;
|
||||
sort: number;
|
||||
length: number;
|
||||
is_pk: boolean;
|
||||
is_nullable: boolean;
|
||||
gen_business_id: number;
|
||||
}
|
||||
|
||||
export interface CodeGenColumnResult extends CodeGenColumnParams {
|
||||
id: number;
|
||||
pd_type: string;
|
||||
}
|
||||
|
||||
export interface CodeGenBusinessImportParams {
|
||||
app: string;
|
||||
table_schema: string;
|
||||
table_name: string;
|
||||
}
|
||||
|
||||
export async function getCodeGenBusinessDetailApi(pk: number) {
|
||||
return requestClient.get<CodeGenBusinessResult>(
|
||||
`/api/v1/code-generation/businesses/${pk}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getAllCodeGenBusinessApi() {
|
||||
return requestClient.get<CodeGenBusinessResult[]>(
|
||||
'/api/v1/code-generation/businesses/all',
|
||||
);
|
||||
}
|
||||
|
||||
export async function createCodeGenBusinessApi(data: CodeGenBusinessParams) {
|
||||
return requestClient.post(`/api/v1/code-generation/businesses`, data);
|
||||
}
|
||||
|
||||
export async function updateCodeGenBusinessApi(
|
||||
pk: number,
|
||||
data: CodeGenBusinessParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/code-generation/businesses/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function deleteCodeGenBusinessApi(pk: number) {
|
||||
return requestClient.delete(`/api/v1/code-generation/businesses/${pk}`);
|
||||
}
|
||||
|
||||
export async function getCodeGenBusinessListApi(
|
||||
params: QueryCodeGenBusinessParams,
|
||||
) {
|
||||
return requestClient.get<PaginationResult<CodeGenBusinessResult>>(
|
||||
`/api/v1/code-generation/businesses`,
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
export async function getAllCodeGenBusinessColumnApi(pk: number) {
|
||||
return requestClient.get<PaginationResult<CodeGenColumnResult>>(
|
||||
`/api/v1/code-generation/businesses/${pk}/columns`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getAllCodeGenColumnTypeApi() {
|
||||
return requestClient.get<string[]>(`/api/v1/code-generation/columns/types`);
|
||||
}
|
||||
|
||||
export async function getCodeGenColumnDetailApi(pk: number) {
|
||||
return requestClient.get(`/api/v1/code-generation/columns/${pk}`);
|
||||
}
|
||||
|
||||
export async function createCodeGenColumnApi(data: CodeGenColumnParams) {
|
||||
return requestClient.post(`/api/v1/code-generation/columns`, data);
|
||||
}
|
||||
|
||||
export async function updateCodeGenColumnApi(
|
||||
pk: number,
|
||||
data: CodeGenColumnParams,
|
||||
) {
|
||||
return requestClient.put(`/api/v1/code-generation/columns/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function deleteCodeGenColumnApi(pk: number) {
|
||||
return requestClient.delete(`/api/v1/code-generation/columns/${pk}`);
|
||||
}
|
||||
|
||||
export async function getCodeGenDbTableApi(params: Recordable<any>) {
|
||||
return requestClient.get<string[]>(
|
||||
`/api/v1/code-generation/generations/tables`,
|
||||
{
|
||||
params,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function importCodeGenDbTableApi(
|
||||
data: CodeGenBusinessImportParams,
|
||||
) {
|
||||
return requestClient.post(
|
||||
`/api/v1/code-generation/generations/imports`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function previewCodeGenApi(pk: number) {
|
||||
return requestClient.get(`/api/v1/code-generation/generations/${pk}/preview`);
|
||||
}
|
||||
|
||||
export async function getCodeGenPathApi(pk: number) {
|
||||
return requestClient.get<string[]>(
|
||||
`/api/v1/code-generation/generations/${pk}/paths`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateCodeApi(pk: number) {
|
||||
return requestClient.post(`/api/v1/code-generation/generations/${pk}`);
|
||||
}
|
||||
|
||||
export async function downloadCodeApi(pk: number) {
|
||||
return requestClient.download<Blob>(
|
||||
`/api/v1/code-generation/generations/${pk}`,
|
||||
);
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"menu": "Code Generator"
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"menu": "代码生成"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "@fba-ui/code-generator",
|
||||
"version": "5.7.0",
|
||||
"private": true,
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
name: 'PluginCodeGenerator',
|
||||
path: '/plugins/code-generator',
|
||||
component: () => import('../views/index.vue'),
|
||||
meta: {
|
||||
title: $t('code_generator.menu'),
|
||||
icon: 'tabler:code',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export default routes;
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
<script lang="ts" setup>
|
||||
import type { CodeGenColumnParams, CodeGenColumnResult } from '../api';
|
||||
|
||||
import type {
|
||||
OnActionClickParams,
|
||||
VxeTableGridOptions,
|
||||
} from '#/adapter/vxe-table';
|
||||
|
||||
import { computed, h, ref } from 'vue';
|
||||
|
||||
import {
|
||||
confirm,
|
||||
useVbenDrawer,
|
||||
useVbenModal,
|
||||
VbenButton,
|
||||
} from '@vben/common-ui';
|
||||
import { MaterialSymbolsAdd } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
import { downloadFileFromBlob } from '@vben/utils';
|
||||
|
||||
import { Alert, message } from 'antdv-next';
|
||||
|
||||
import { useVbenForm } from '#/adapter/form';
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
|
||||
import {
|
||||
createCodeGenColumnApi,
|
||||
deleteCodeGenColumnApi,
|
||||
downloadCodeApi,
|
||||
generateCodeApi,
|
||||
getAllCodeGenBusinessColumnApi,
|
||||
getCodeGenPathApi,
|
||||
updateCodeGenColumnApi,
|
||||
} from '../api';
|
||||
import { columnSchema, useColumnColumns } from './data';
|
||||
import ExtraModal from './preview.vue';
|
||||
|
||||
const generateLoading = ref(false);
|
||||
|
||||
const gridOptions: VxeTableGridOptions<CodeGenColumnResult[]> = {
|
||||
rowConfig: {
|
||||
keyField: 'id',
|
||||
},
|
||||
height: 'auto',
|
||||
virtualYConfig: {
|
||||
enabled: true,
|
||||
},
|
||||
pagerConfig: {
|
||||
enabled: false,
|
||||
},
|
||||
columns: useColumnColumns(onActionClick),
|
||||
proxyConfig: {
|
||||
autoLoad: false,
|
||||
ajax: {
|
||||
query: async () => {
|
||||
return await getAllCodeGenBusinessColumnApi(drawerApi.getData().pk);
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
|
||||
|
||||
function onActionClick({
|
||||
code,
|
||||
row,
|
||||
}: OnActionClickParams<CodeGenColumnResult>) {
|
||||
switch (code) {
|
||||
case 'delete': {
|
||||
deleteCodeGenColumnApi(row.id).then(() => {
|
||||
message.success({
|
||||
content: $t('ui.actionMessage.deleteSuccess', [row.name]),
|
||||
key: 'action_process_msg',
|
||||
});
|
||||
onRefresh();
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'edit': {
|
||||
modalApi.setData(row).open();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onRefresh() {
|
||||
gridApi.query();
|
||||
}
|
||||
|
||||
const [Drawer, drawerApi] = useVbenDrawer({
|
||||
destroyOnClose: true,
|
||||
closable: false,
|
||||
cancelText: '预览',
|
||||
confirmText: '下载',
|
||||
class: 'w-2/3',
|
||||
onOpenChange(isOpen) {
|
||||
if (isOpen) {
|
||||
gridApi.setLoading(true);
|
||||
}
|
||||
},
|
||||
async onOpened() {
|
||||
try {
|
||||
await gridApi.query();
|
||||
} finally {
|
||||
gridApi.setLoading(false);
|
||||
}
|
||||
},
|
||||
onCancel: () => {
|
||||
previewModalApi.setData({ pk: drawerApi.getData().pk }).open();
|
||||
},
|
||||
onConfirm: async () => {
|
||||
drawerApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const res = await downloadCodeApi(drawerApi.getData().pk);
|
||||
downloadFileFromBlob({ fileName: 'fba_generator', source: res });
|
||||
message.success('代码包已开始下载');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
drawerApi.setState({ confirmLoading: false });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function showGenerate() {
|
||||
const paths = await getCodeGenPathApi(drawerApi.getData().pk);
|
||||
confirm({
|
||||
title: '警告',
|
||||
content: h('div', null, [
|
||||
h(Alert, {
|
||||
type: 'error',
|
||||
showIcon: false,
|
||||
message:
|
||||
'代码生成将进行磁盘文件(覆盖)写入,切勿在生产环境中使用!!!',
|
||||
}),
|
||||
h('br'),
|
||||
h('div', { class: 'rounded border border-solid border-gray-300' }, [
|
||||
h(
|
||||
'div',
|
||||
{
|
||||
class:
|
||||
'border-b border-solid border-gray-300 bg-gray-50 px-4 py-2 font-medium',
|
||||
},
|
||||
'即将写入以下文件:',
|
||||
),
|
||||
h(
|
||||
'ul',
|
||||
{ class: 'list-none p-0 m-0' },
|
||||
paths.map((item: string) =>
|
||||
h(
|
||||
'li',
|
||||
{
|
||||
class:
|
||||
'border-b border-solid border-gray-200 px-4 py-2 last:border-b-0',
|
||||
},
|
||||
h('p', { class: 'text-orange-500 m-0' }, item),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
icon: 'error',
|
||||
confirmText: '不怂!就是干',
|
||||
})
|
||||
.then(async () => {
|
||||
generateLoading.value = true;
|
||||
try {
|
||||
await generateCodeApi(drawerApi.getData().pk);
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
generateLoading.value = false;
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
interface formCodeGenColumnParams extends CodeGenColumnParams {
|
||||
id?: number;
|
||||
}
|
||||
|
||||
const formData = ref<formCodeGenColumnParams>();
|
||||
|
||||
const modalTile = computed(() => {
|
||||
return formData.value?.id
|
||||
? $t('ui.actionTitle.edit', ['模型列'])
|
||||
: $t('ui.actionTitle.create', ['模型列']);
|
||||
});
|
||||
|
||||
const [Form, formApi] = useVbenForm({
|
||||
showDefaultActions: false,
|
||||
schema: columnSchema,
|
||||
});
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
destroyOnClose: true,
|
||||
class: 'w-1/3',
|
||||
async onConfirm() {
|
||||
const { valid } = await formApi.validate();
|
||||
if (valid) {
|
||||
modalApi.lock();
|
||||
const data = await formApi.getValues<CodeGenColumnParams>();
|
||||
try {
|
||||
await (formData.value?.id
|
||||
? updateCodeGenColumnApi(formData.value.id, data)
|
||||
: createCodeGenColumnApi(data));
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
await modalApi.close();
|
||||
onRefresh();
|
||||
} finally {
|
||||
modalApi.unlock();
|
||||
}
|
||||
}
|
||||
},
|
||||
onOpenChange(isOpen) {
|
||||
if (isOpen) {
|
||||
const data = modalApi.getData<formCodeGenColumnParams>();
|
||||
formApi.resetForm();
|
||||
if (data) {
|
||||
formData.value = data;
|
||||
formApi.setValues(formData.value);
|
||||
if (!formData.value.id) {
|
||||
formApi.setFieldValue('gen_business_id', drawerApi.getData().pk);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const [PreviewModal, previewModalApi] = useVbenModal({
|
||||
connectedComponent: ExtraModal,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Drawer title="业务模型列">
|
||||
<Grid />
|
||||
<template #extra>
|
||||
<a-alert :show-icon="false">
|
||||
<template #title>
|
||||
主键 ID 列状态:<a-tag color="success">自动生成</a-tag>
|
||||
默认时间列状态:
|
||||
<a-tag
|
||||
:color="drawerApi.getData().datetime_mixin ? 'success' : 'warning'"
|
||||
>
|
||||
{{ drawerApi.getData().datetime_mixin ? '已配置' : '未配置' }}
|
||||
</a-tag>
|
||||
</template>
|
||||
</a-alert>
|
||||
<VbenButton @click="modalApi.setData(null).open()" class="ml-3">
|
||||
<MaterialSymbolsAdd class="size-5" />
|
||||
新增模型列
|
||||
</VbenButton>
|
||||
</template>
|
||||
<template #center-footer>
|
||||
<a-button :loading="generateLoading" type="primary" @click="showGenerate">
|
||||
生成
|
||||
</a-button>
|
||||
</template>
|
||||
</Drawer>
|
||||
<Modal :title="modalTile">
|
||||
<Form />
|
||||
</Modal>
|
||||
<PreviewModal />
|
||||
</template>
|
||||
@@ -0,0 +1,415 @@
|
||||
import type { CodeGenBusinessResult, CodeGenColumnResult } from '../api';
|
||||
|
||||
import type { VbenFormSchema } from '#/adapter/form';
|
||||
import type { OnActionClickFn, VxeGridProps } from '#/adapter/vxe-table';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { DictEnum, getDictOptions } from '#/utils/dict';
|
||||
|
||||
import {
|
||||
getAllCodeGenBusinessApi,
|
||||
getAllCodeGenColumnTypeApi,
|
||||
getCodeGenDbTableApi,
|
||||
} from '../api';
|
||||
|
||||
export const querySchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'table_name',
|
||||
label: '表名称',
|
||||
},
|
||||
];
|
||||
|
||||
export function useColumns(
|
||||
onActionClick?: OnActionClickFn<CodeGenBusinessResult>,
|
||||
): VxeGridProps['columns'] {
|
||||
return [
|
||||
{
|
||||
field: 'seq',
|
||||
title: $t('common.table.id'),
|
||||
type: 'seq',
|
||||
width: 50,
|
||||
},
|
||||
{ field: 'app_name', title: '应用名称' },
|
||||
{ field: 'table_name', title: '表名称' },
|
||||
{ field: 'table_comment', title: '表描述' },
|
||||
{
|
||||
field: 'doc_comment',
|
||||
title: '文档描述',
|
||||
titleSuffix: { content: '用于 python 代码类、函数、参数文档' },
|
||||
},
|
||||
{
|
||||
field: 'class_name',
|
||||
title: '实体类名',
|
||||
titleSuffix: {
|
||||
content: '用于 python 代码基础类名',
|
||||
},
|
||||
},
|
||||
{
|
||||
field: 'schema_name',
|
||||
title: 'Schema 类名',
|
||||
titleSuffix: {
|
||||
content: '用于 python Schema 代码基础类名',
|
||||
},
|
||||
},
|
||||
{
|
||||
field: 'filename',
|
||||
title: '文件名',
|
||||
titleSuffix: {
|
||||
content: '用于 python 代码基础文件名',
|
||||
},
|
||||
},
|
||||
{ field: 'api_version', title: '版本' },
|
||||
{
|
||||
field: 'tag',
|
||||
title: '标签',
|
||||
titleSuffix: {
|
||||
content: '用于 API 文档分组标签',
|
||||
},
|
||||
},
|
||||
{
|
||||
field: 'gen_path',
|
||||
title: '生成路径',
|
||||
titleSuffix: {
|
||||
content: '默认生成到 app 根路径,也可以自定义生成路径',
|
||||
},
|
||||
align: 'left',
|
||||
},
|
||||
{ field: 'remark', title: $t('common.table.mark'), align: 'left' },
|
||||
{
|
||||
field: 'operation',
|
||||
title: $t('common.table.operation'),
|
||||
align: 'center',
|
||||
fixed: 'right',
|
||||
width: 150,
|
||||
cellRender: {
|
||||
attrs: {
|
||||
onClick: onActionClick,
|
||||
},
|
||||
name: 'CellOperation',
|
||||
options: [
|
||||
{
|
||||
code: 'details',
|
||||
text: '详情',
|
||||
},
|
||||
'edit',
|
||||
'delete',
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const tableSchemaValue = ref<string>();
|
||||
export const importSchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'app',
|
||||
label: '应用名称',
|
||||
help: '将代码生成到指定应用下',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'table_schema',
|
||||
label: '数据库名',
|
||||
help: '当前服务所连接的数据库名',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'ApiSelect',
|
||||
componentProps: {
|
||||
allowClear: true,
|
||||
api: getCodeGenDbTableApi,
|
||||
params: { table_schema: tableSchemaValue },
|
||||
afterFetch: (data: { table_comment: string; table_name: string }[]) => {
|
||||
return data.map((item: any) => ({
|
||||
label: item.table_comment || item.table_name,
|
||||
value: item.table_name,
|
||||
}));
|
||||
},
|
||||
class: 'w-full',
|
||||
},
|
||||
dependencies: {
|
||||
disabled: (values) => {
|
||||
return !values.table_schema;
|
||||
},
|
||||
trigger(values) {
|
||||
tableSchemaValue.value = values.table_schema;
|
||||
},
|
||||
triggerFields: ['table_schema'],
|
||||
},
|
||||
fieldName: 'table_name',
|
||||
label: '数据库表名',
|
||||
rules: 'required',
|
||||
},
|
||||
];
|
||||
|
||||
export const editSchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'app_name',
|
||||
label: '应用名称',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'table_name',
|
||||
label: '表名称',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'table_comment',
|
||||
label: '表描述',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'doc_comment',
|
||||
label: '文档描述',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'class_name',
|
||||
label: '实体类名',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'schema_name',
|
||||
label: 'Schema 类名',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'filename',
|
||||
label: '文件名',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'api_version',
|
||||
label: 'API 版本',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'tag',
|
||||
label: '标签',
|
||||
},
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
buttonStyle: 'solid',
|
||||
// options: [
|
||||
// { label: $t('common.enabled'), value: true },
|
||||
// { label: $t('common.disabled'), value: false },
|
||||
// ],
|
||||
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE),
|
||||
optionType: 'button',
|
||||
},
|
||||
fieldName: 'datetime_mixin',
|
||||
label: '默认时间列',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Textarea',
|
||||
fieldName: 'gen_path',
|
||||
label: '生成路径',
|
||||
},
|
||||
{
|
||||
component: 'Textarea',
|
||||
fieldName: 'remark',
|
||||
label: $t('common.table.mark'),
|
||||
},
|
||||
];
|
||||
|
||||
export function useColumnColumns(
|
||||
onActionClick?: OnActionClickFn<CodeGenColumnResult>,
|
||||
): VxeGridProps['columns'] {
|
||||
return [
|
||||
{
|
||||
field: 'seq',
|
||||
title: $t('common.table.id'),
|
||||
type: 'seq',
|
||||
width: 50,
|
||||
},
|
||||
{
|
||||
field: 'name',
|
||||
title: '名称',
|
||||
},
|
||||
{
|
||||
field: 'is_pk',
|
||||
title: '是否主键',
|
||||
cellRender: {
|
||||
name: 'CellTag',
|
||||
// options: [
|
||||
// { color: 'success', label: $t('common.enabled'), value: true },
|
||||
// { color: 'error', label: $t('common.disabled'), value: false },
|
||||
// ],
|
||||
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE),
|
||||
},
|
||||
},
|
||||
{
|
||||
field: 'comment',
|
||||
title: '描述',
|
||||
},
|
||||
{
|
||||
field: 'type',
|
||||
title: 'SQLA 类型',
|
||||
},
|
||||
{
|
||||
field: 'pd_type',
|
||||
title: 'Pydantic 类型',
|
||||
},
|
||||
{
|
||||
field: 'default',
|
||||
title: '默认值',
|
||||
},
|
||||
{
|
||||
field: 'sort',
|
||||
title: '排序',
|
||||
},
|
||||
{
|
||||
field: 'length',
|
||||
title: '长度',
|
||||
},
|
||||
{
|
||||
field: 'is_nullable',
|
||||
title: '选填',
|
||||
cellRender: {
|
||||
name: 'CellTag',
|
||||
// options: [
|
||||
// { color: 'success', label: $t('common.enabled'), value: true },
|
||||
// { color: 'error', label: $t('common.disabled'), value: false },
|
||||
// ],
|
||||
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE),
|
||||
},
|
||||
},
|
||||
{
|
||||
field: 'operation',
|
||||
title: $t('common.table.operation'),
|
||||
align: 'center',
|
||||
fixed: 'right',
|
||||
width: 120,
|
||||
cellRender: {
|
||||
attrs: {
|
||||
onClick: onActionClick,
|
||||
},
|
||||
name: 'CellOperation',
|
||||
options: ['edit', 'delete'],
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export const columnSchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'ApiSelect',
|
||||
componentProps: {
|
||||
allowClear: true,
|
||||
api: getAllCodeGenBusinessApi,
|
||||
afterFetch: (data: CodeGenBusinessResult[]) => {
|
||||
return data.map((item: CodeGenBusinessResult) => ({
|
||||
label: item.app_name,
|
||||
value: item.id,
|
||||
}));
|
||||
},
|
||||
disabled: true,
|
||||
class: 'w-full',
|
||||
},
|
||||
fieldName: 'gen_business_id',
|
||||
label: '所属业务',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'name',
|
||||
label: '列名称',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'comment',
|
||||
label: '列描述',
|
||||
},
|
||||
{
|
||||
component: 'ApiSelect',
|
||||
componentProps: {
|
||||
allowClear: true,
|
||||
api: getAllCodeGenColumnTypeApi,
|
||||
afterFetch: (data: string[]) => {
|
||||
return data.map((item: string) => ({
|
||||
label: item,
|
||||
value: item,
|
||||
}));
|
||||
},
|
||||
class: 'w-full',
|
||||
},
|
||||
fieldName: 'type',
|
||||
label: 'SQLA 列类型',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'default',
|
||||
label: '列默认值',
|
||||
},
|
||||
{
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
class: 'w-full',
|
||||
min: 0,
|
||||
},
|
||||
fieldName: 'sort',
|
||||
label: '列排序',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
class: 'w-full',
|
||||
min: 0,
|
||||
},
|
||||
fieldName: 'length',
|
||||
label: '列长度',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
buttonStyle: 'solid',
|
||||
// options: [
|
||||
// { label: $t('common.enabled'), value: true },
|
||||
// { label: $t('common.disabled'), value: false },
|
||||
// ],
|
||||
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: false,
|
||||
fieldName: 'is_pk',
|
||||
label: '是否主键',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
buttonStyle: 'solid',
|
||||
// options: [
|
||||
// { label: $t('common.enabled'), value: true },
|
||||
// { label: $t('common.disabled'), value: false },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: false,
|
||||
fieldName: 'is_nullable',
|
||||
label: '是否选填',
|
||||
rules: 'required',
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,224 @@
|
||||
<script lang="ts" setup>
|
||||
import type { VbenFormProps } from '@vben/common-ui';
|
||||
|
||||
import type {
|
||||
CodeGenBusinessImportParams,
|
||||
CodeGenBusinessParams,
|
||||
CodeGenBusinessResult,
|
||||
} from '../api';
|
||||
|
||||
import type {
|
||||
OnActionClickParams,
|
||||
VxeTableGridOptions,
|
||||
} from '#/adapter/vxe-table';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Page, useVbenDrawer, useVbenModal, VbenButton } from '@vben/common-ui';
|
||||
import { MaterialSymbolsAdd } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
import { useVbenForm } from '#/adapter/form';
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
|
||||
import {
|
||||
createCodeGenBusinessApi,
|
||||
deleteCodeGenBusinessApi,
|
||||
getCodeGenBusinessListApi,
|
||||
importCodeGenDbTableApi,
|
||||
updateCodeGenBusinessApi,
|
||||
} from '../api';
|
||||
import ExtraDrawer from './column.vue';
|
||||
import { editSchema, importSchema, querySchema, useColumns } from './data';
|
||||
|
||||
const formOptions: VbenFormProps = {
|
||||
collapsed: true,
|
||||
showCollapseButton: true,
|
||||
submitButtonOptions: {
|
||||
content: $t('common.form.query'),
|
||||
},
|
||||
schema: querySchema,
|
||||
};
|
||||
|
||||
const gridOptions: VxeTableGridOptions<CodeGenBusinessResult> = {
|
||||
rowConfig: {
|
||||
keyField: 'id',
|
||||
},
|
||||
checkboxConfig: {
|
||||
highlight: true,
|
||||
},
|
||||
height: 'auto',
|
||||
exportConfig: {},
|
||||
printConfig: {},
|
||||
toolbarConfig: {
|
||||
export: true,
|
||||
print: true,
|
||||
refresh: true,
|
||||
refreshOptions: {
|
||||
code: 'query',
|
||||
},
|
||||
custom: true,
|
||||
zoom: true,
|
||||
},
|
||||
columns: useColumns(onActionClick),
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async ({ page }, formValues) => {
|
||||
return await getCodeGenBusinessListApi({
|
||||
page: page.currentPage,
|
||||
size: page.pageSize,
|
||||
...formValues,
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
|
||||
|
||||
function onActionClick({
|
||||
code,
|
||||
row,
|
||||
}: OnActionClickParams<CodeGenBusinessResult>) {
|
||||
switch (code) {
|
||||
case 'delete': {
|
||||
deleteCodeGenBusinessApi(row.id).then(() => {
|
||||
message.success({
|
||||
content: $t('ui.actionMessage.deleteSuccess', [row.table_name]),
|
||||
key: 'action_process_msg',
|
||||
});
|
||||
onRefresh();
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'details': {
|
||||
drawerApi
|
||||
.setData({
|
||||
pk: row.id,
|
||||
datetime_mixin: row.datetime_mixin,
|
||||
})
|
||||
.open();
|
||||
break;
|
||||
}
|
||||
case 'edit': {
|
||||
modalApi.setData(row).open();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onRefresh() {
|
||||
gridApi.query();
|
||||
}
|
||||
|
||||
const [ImportForm, importFormApi] = useVbenForm({
|
||||
layout: 'vertical',
|
||||
showDefaultActions: false,
|
||||
schema: importSchema,
|
||||
});
|
||||
|
||||
const [ImportModal, importModalApi] = useVbenModal({
|
||||
destroyOnClose: true,
|
||||
async onConfirm() {
|
||||
const { valid } = await importFormApi.validate();
|
||||
if (valid) {
|
||||
importModalApi.lock();
|
||||
const data = await importFormApi.getValues<CodeGenBusinessImportParams>();
|
||||
try {
|
||||
await importCodeGenDbTableApi(data);
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
await importModalApi.close();
|
||||
onRefresh();
|
||||
} finally {
|
||||
importModalApi.unlock();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const [Form, formApi] = useVbenForm({
|
||||
wrapperClass: 'grid-cols-1 md:grid-cols-2',
|
||||
showDefaultActions: false,
|
||||
schema: editSchema,
|
||||
});
|
||||
|
||||
interface formCodeGenBusinessParams extends CodeGenBusinessParams {
|
||||
id?: number;
|
||||
}
|
||||
|
||||
const formData = ref<formCodeGenBusinessParams>();
|
||||
|
||||
const modalTitle = computed(() => {
|
||||
return formData.value?.id
|
||||
? $t('ui.actionTitle.edit', ['代码生成业务'])
|
||||
: $t('ui.actionTitle.create', ['代码生成业务']);
|
||||
});
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
class: 'w-5/12',
|
||||
destroyOnClose: true,
|
||||
async onConfirm() {
|
||||
const { valid } = await formApi.validate();
|
||||
if (valid) {
|
||||
modalApi.lock();
|
||||
const data = await formApi.getValues<CodeGenBusinessParams>();
|
||||
try {
|
||||
await (formData.value?.id
|
||||
? updateCodeGenBusinessApi(formData.value.id, data)
|
||||
: createCodeGenBusinessApi(data));
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
await modalApi.close();
|
||||
onRefresh();
|
||||
} finally {
|
||||
modalApi.unlock();
|
||||
}
|
||||
}
|
||||
},
|
||||
onOpenChange(isOpen) {
|
||||
if (isOpen) {
|
||||
const data = modalApi.getData<formCodeGenBusinessParams>();
|
||||
formApi.resetForm();
|
||||
if (data) {
|
||||
formData.value = data;
|
||||
formApi.setValues(formData.value);
|
||||
} else {
|
||||
formData.value = undefined;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const [Drawer, drawerApi] = useVbenDrawer({
|
||||
connectedComponent: ExtraDrawer,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height>
|
||||
<Grid>
|
||||
<template #toolbar-actions>
|
||||
<VbenButton @click="() => modalApi.setData(null).open()">
|
||||
<MaterialSymbolsAdd class="size-5" />
|
||||
添加
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
class="ml-2"
|
||||
variant="outline"
|
||||
@click="importModalApi.setData(null).open()"
|
||||
>
|
||||
<MaterialSymbolsAdd class="size-5" />
|
||||
导入
|
||||
</VbenButton>
|
||||
</template>
|
||||
</Grid>
|
||||
<Modal :title="modalTitle">
|
||||
<Form />
|
||||
</Modal>
|
||||
<ImportModal title="导入表">
|
||||
<ImportForm />
|
||||
</ImportModal>
|
||||
<Drawer />
|
||||
</Page>
|
||||
</template>
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<script setup lang="ts">
|
||||
import type { Component } from 'vue';
|
||||
|
||||
import type { LanguageSupport } from '@vben/common-ui';
|
||||
import type { Recordable } from '@vben/types';
|
||||
|
||||
import { markRaw, ref } from 'vue';
|
||||
|
||||
import { CodeMirror, ColPage, useVbenModal } from '@vben/common-ui';
|
||||
import {
|
||||
BxsFile,
|
||||
FlatColorIconsFolder,
|
||||
MaterialIconThemePython,
|
||||
} from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { useClipboard } from '@vueuse/core';
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
import { previewCodeGenApi } from '../api';
|
||||
|
||||
interface TreeNode {
|
||||
children: TreeNode[];
|
||||
title: string;
|
||||
key: string;
|
||||
icon: Component;
|
||||
}
|
||||
|
||||
const treeData = ref<TreeNode[]>([]);
|
||||
const codes = ref<null | Recordable<any>>(null);
|
||||
const language = ref<LanguageSupport>('python');
|
||||
const modalTitle = ref<string>('代码预览');
|
||||
const codeContent = ref<string>('点击左侧树节点查看代码');
|
||||
const previewLoading = ref(false);
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
destroyOnClose: true,
|
||||
fullscreen: true,
|
||||
fullscreenButton: false,
|
||||
footer: false,
|
||||
contentClass: 'p-0',
|
||||
async onOpenChange(isOpen) {
|
||||
if (!isOpen) {
|
||||
treeData.value = [];
|
||||
codes.value = null;
|
||||
language.value = 'python';
|
||||
modalTitle.value = '代码预览';
|
||||
codeContent.value = '点击左侧树节点查看代码';
|
||||
previewLoading.value = false;
|
||||
return null;
|
||||
}
|
||||
|
||||
treeData.value = [];
|
||||
codes.value = null;
|
||||
previewLoading.value = true;
|
||||
try {
|
||||
const res = await previewCodeGenApi(modalApi.getData().pk);
|
||||
codes.value = res;
|
||||
treeData.value = convertToTree(Object.keys(res));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
previewLoading.value = false;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* 文件路径数组转树结构
|
||||
* @param paths 文件路径数组
|
||||
*/
|
||||
function convertToTree(paths: string[]): TreeNode[] {
|
||||
const root: TreeNode[] = [];
|
||||
const nodeMap = new Map<string, TreeNode>();
|
||||
|
||||
for (const path of paths) {
|
||||
const segments = path.split('/');
|
||||
let parentPath = '';
|
||||
let parentChildren = root;
|
||||
|
||||
for (const [i, segment] of segments.entries()) {
|
||||
parentPath = i === 0 ? segment : `${parentPath}/${segment}`;
|
||||
let node = nodeMap.get(parentPath);
|
||||
|
||||
if (!node) {
|
||||
node = {
|
||||
icon: findIcon(parentPath),
|
||||
key: parentPath,
|
||||
title: segment,
|
||||
children: [],
|
||||
};
|
||||
parentChildren.push(node);
|
||||
nodeMap.set(parentPath, node);
|
||||
}
|
||||
|
||||
parentChildren = node.children;
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
const defaultFileIcon = BxsFile;
|
||||
const defaultFolderIcon = FlatColorIconsFolder;
|
||||
const iconMap: Record<string, any> = {
|
||||
py: MaterialIconThemePython,
|
||||
};
|
||||
|
||||
function findIcon(path: string) {
|
||||
const dotIndex = path.lastIndexOf('.');
|
||||
if (dotIndex !== -1) {
|
||||
const ext = path.slice(dotIndex + 1);
|
||||
return markRaw(iconMap[ext] || defaultFileIcon);
|
||||
}
|
||||
return markRaw(defaultFolderIcon);
|
||||
}
|
||||
|
||||
function handleSelect(selectedKeys: Array<number | string>) {
|
||||
const [selectedKey] = selectedKeys;
|
||||
const currentFile =
|
||||
selectedKey === null || selectedKey === undefined
|
||||
? ''
|
||||
: String(selectedKey);
|
||||
const currentCode = codes.value?.[currentFile];
|
||||
if (!currentCode) return;
|
||||
|
||||
changeLanguageType(currentFile);
|
||||
modalTitle.value = `代码预览: ${currentFile}`;
|
||||
codeContent.value = currentCode;
|
||||
}
|
||||
|
||||
const typeMap: Record<string, LanguageSupport> = {
|
||||
'.py': 'python',
|
||||
'.sql': 'sql',
|
||||
};
|
||||
|
||||
function changeLanguageType(filename: string) {
|
||||
const entry = Object.entries(typeMap).find(([ext]) => filename.endsWith(ext));
|
||||
language.value = entry?.[1] ?? 'python';
|
||||
}
|
||||
|
||||
const { copy } = useClipboard({ legacy: true });
|
||||
|
||||
function copyCodeContent(code: string) {
|
||||
copy(code);
|
||||
message.success($t('preferences.copyPreferencesSuccessTitle'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :title="modalTitle">
|
||||
<a-skeleton v-if="previewLoading" active />
|
||||
<div v-else-if="codes">
|
||||
<ColPage
|
||||
auto-content-height
|
||||
:height-offset="-35"
|
||||
:resizable="false"
|
||||
:left-width="30"
|
||||
:right-width="70"
|
||||
>
|
||||
<template #left>
|
||||
<div class="mr-2 h-full overflow-y-auto">
|
||||
<a-tree
|
||||
v-if="treeData.length > 0"
|
||||
:show-line="{ showLeafIcon: false }"
|
||||
:tree-data="treeData"
|
||||
:virtual="false"
|
||||
default-expand-all
|
||||
@select="handleSelect"
|
||||
>
|
||||
<template #titleRender="{ title, icon }">
|
||||
<div class="flex items-center gap-[8px]">
|
||||
<component :is="icon" />
|
||||
<span>{{ title }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</a-tree>
|
||||
</div>
|
||||
</template>
|
||||
<CodeMirror
|
||||
class="h-full overflow-y-scroll text-[13px]"
|
||||
v-model="codeContent"
|
||||
:language="language"
|
||||
/>
|
||||
<div class="fixed right-12 top-20">
|
||||
<a-button @click="copyCodeContent(codeContent)">复制</a-button>
|
||||
</div>
|
||||
</ColPage>
|
||||
</div>
|
||||
<a-empty v-else description="暂无预览内容" />
|
||||
</Modal>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
/** codeMirror 占满容器高度 即 calc 计算的高度 */
|
||||
:deep(.cm-editor) {
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Recordable } from '@vben/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface ConfigParams {
|
||||
id: string;
|
||||
name: string;
|
||||
type?: string;
|
||||
key: string;
|
||||
value: string;
|
||||
is_frontend: boolean;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface ConfigResult extends ConfigParams {
|
||||
created_time: string;
|
||||
updated_time?: string;
|
||||
}
|
||||
|
||||
export async function getAllConfigApi(params: Recordable<any>) {
|
||||
return requestClient.get<ConfigResult[]>('/api/v1/sys/configs/all', {
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateConfigApi(params: ConfigParams[]) {
|
||||
return requestClient.put('/api/v1/sys/configs', params);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"menu": "Parameter config"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"menu": "参数配置"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "@fba-ui/config",
|
||||
"version": "5.7.0",
|
||||
"private": true,
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import { $t } from '#/locales';
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
name: 'PluginConfig',
|
||||
path: '/plugins/config',
|
||||
component: () => import('../views/index.vue'),
|
||||
meta: {
|
||||
title: $t('config.menu'),
|
||||
icon: 'codicon:symbol-parameter',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export default routes;
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { VbenFormSchema } from '#/adapter/form';
|
||||
|
||||
import { z } from '#/adapter/form';
|
||||
import { DictEnum, getDictOptions } from '#/utils/dict';
|
||||
|
||||
export const userSecuritySchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
// options: [
|
||||
// { label: $t('common.enabled'), value: '1' },
|
||||
// { label: $t('common.disabled'), value: '0' },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_STATUS, { asString: true }),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: '0',
|
||||
fieldName: 'USER_SECURITY_CONFIG_STATUS',
|
||||
label: '状态',
|
||||
help: '默认使用本地配置,当启用时,将使用此配置',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_LOCK_THRESHOLD',
|
||||
label: '密码错误锁定阈值',
|
||||
description: '用户连续登录失败达到此次数后将被锁定,0 表示禁用锁定',
|
||||
renderComponentContent: () => ({
|
||||
suffix: () => '次',
|
||||
}),
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_LOCK_SECONDS',
|
||||
label: '密码错误锁定时长(秒)',
|
||||
description: '用户被锁定后自动解锁的时间',
|
||||
renderComponentContent: () => ({
|
||||
suffix: () => '秒',
|
||||
}),
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_PASSWORD_EXPIRY_DAYS',
|
||||
label: '密码有效期(天)',
|
||||
description: '密码强制修改周期,0 表示永不过期',
|
||||
renderComponentContent: () => ({
|
||||
suffix: () => '天',
|
||||
}),
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_PASSWORD_REMINDER_DAYS',
|
||||
label: '密码到期提醒(天)',
|
||||
description: '密码到期前多少天提醒用户修改密码,0 表示不提醒',
|
||||
renderComponentContent: () => ({
|
||||
suffix: () => '天',
|
||||
}),
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_PASSWORD_HISTORY_CHECK_COUNT',
|
||||
label: '密码历史检查次数',
|
||||
description: '新密码不能与最近 N 次使用的密码相同',
|
||||
renderComponentContent: () => ({
|
||||
suffix: () => '次',
|
||||
}),
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_PASSWORD_MIN_LENGTH',
|
||||
label: '密码最小长度',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'USER_PASSWORD_MAX_LENGTH',
|
||||
label: '密码最大长度',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
// options: [
|
||||
// { color: 'success', label: $t('common.enabled'), value: 'true' },
|
||||
// { color: 'error', label: $t('common.disabled'), value: 'false' },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE, { asString: true }),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: 'false',
|
||||
fieldName: 'USER_PASSWORD_REQUIRE_SPECIAL_CHAR',
|
||||
label: '密码必须包含特殊字符',
|
||||
labelClass: 'float-left',
|
||||
rules: 'required',
|
||||
},
|
||||
];
|
||||
|
||||
export const loginSchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
// options: [
|
||||
// { label: $t('common.enabled'), value: '1' },
|
||||
// { label: $t('common.disabled'), value: '0' },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_STATUS, { asString: true }),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: '0',
|
||||
fieldName: 'LOGIN_CONFIG_STATUS',
|
||||
label: '状态',
|
||||
help: '默认使用本地配置,当启用时,将使用此配置',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
// options: [
|
||||
// { color: 'success', label: $t('common.enabled'), value: 'true' },
|
||||
// { color: 'error', label: $t('common.disabled'), value: 'false' },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE, { asString: true }),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: 'true',
|
||||
fieldName: 'LOGIN_CAPTCHA_ENABLED',
|
||||
label: '验证码开关',
|
||||
description: '是否启用登录验证码',
|
||||
labelClass: 'float-left',
|
||||
rules: 'required',
|
||||
},
|
||||
];
|
||||
|
||||
export const emailSchema: VbenFormSchema[] = [
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
// options: [
|
||||
// { label: $t('common.enabled'), value: '1' },
|
||||
// { label: $t('common.disabled'), value: '0' },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_STATUS, { asString: true }),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: '0',
|
||||
fieldName: 'EMAIL_STATUS',
|
||||
label: '状态',
|
||||
help: '默认使用本地配置,当启用时,将使用此配置',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Select',
|
||||
componentProps: {
|
||||
options: [
|
||||
{
|
||||
label: 'SMTP',
|
||||
value: '0',
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultValue: '0',
|
||||
fieldName: 'EMAIL_PROTOCOL',
|
||||
label: '邮件协议',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'RadioGroup',
|
||||
componentProps: {
|
||||
// options: [
|
||||
// { color: 'success', label: $t('common.enabled'), value: 'true' },
|
||||
// { color: 'error', label: $t('common.disabled'), value: 'false' },
|
||||
// ],
|
||||
options: getDictOptions(DictEnum.SYS_CHOOSE, { asString: true }),
|
||||
optionType: 'button',
|
||||
},
|
||||
defaultValue: '1',
|
||||
fieldName: 'EMAIL_SSL',
|
||||
label: 'SSL 加密',
|
||||
labelClass: 'float-left',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'EMAIL_HOST',
|
||||
label: '服务器地址',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'InputNumber',
|
||||
fieldName: 'EMAIL_PORT',
|
||||
label: '服务器端口',
|
||||
rules: 'required',
|
||||
},
|
||||
{
|
||||
component: 'Input',
|
||||
fieldName: 'EMAIL_USERNAME',
|
||||
label: '邮箱账号',
|
||||
rules: z.string().email({ message: '无效的邮箱地址' }),
|
||||
},
|
||||
{
|
||||
component: 'InputPassword',
|
||||
fieldName: 'EMAIL_PASSWORD',
|
||||
label: '邮箱密码',
|
||||
help: '账号授权密码',
|
||||
rules: 'required',
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,134 @@
|
||||
<script setup lang="ts">
|
||||
import type { ConfigResult } from '../api';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { VbenButton } from '@vben/common-ui';
|
||||
import { MaterialSymbolsEdit } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
import { useVbenForm } from '#/adapter/form';
|
||||
|
||||
import { getAllConfigApi, updateConfigApi } from '../api';
|
||||
import { emailSchema } from './data';
|
||||
|
||||
const [Form, formApi] = useVbenForm({
|
||||
showDefaultActions: false,
|
||||
schema: emailSchema,
|
||||
commonConfig: {
|
||||
controlClass: 'w-full max-w-80',
|
||||
disabled: true,
|
||||
labelClass: 'justify-start ml-2',
|
||||
labelWidth: 120,
|
||||
hideRequiredMark: true,
|
||||
},
|
||||
});
|
||||
|
||||
const editButtonShow = ref<boolean>(true);
|
||||
const loading = ref<boolean>(false);
|
||||
const saveLoading = ref<boolean>(false);
|
||||
|
||||
const emailData = ref<ConfigResult[]>([]);
|
||||
const fetchConfigList = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
emailData.value = await getAllConfigApi({ type: 'EMAIL' });
|
||||
emailData.value.forEach((config: any) => {
|
||||
formApi.setState((prev: any) => {
|
||||
return {
|
||||
schema: prev.schema?.map((item: any) => {
|
||||
if (item.fieldName === config.key) {
|
||||
return {
|
||||
...item,
|
||||
label: config.name,
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
};
|
||||
});
|
||||
formApi.setValues({ [config.key]: config.value });
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const saveEmailConfig = async () => {
|
||||
const { valid } = await formApi.validate();
|
||||
if (valid) {
|
||||
const data: Record<string, any> = await formApi.getValues();
|
||||
emailData.value.forEach((config: any) => {
|
||||
if (Object.prototype.hasOwnProperty.call(data, config.key)) {
|
||||
config.value = data[config.key];
|
||||
}
|
||||
});
|
||||
saveLoading.value = true;
|
||||
try {
|
||||
await updateConfigApi(emailData.value);
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
editButtonShow.value = true;
|
||||
formApi.setState({ commonConfig: { disabled: true } });
|
||||
await fetchConfigList();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
saveLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({
|
||||
fetchConfigList,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-spin :spinning="loading">
|
||||
<div>
|
||||
<Form />
|
||||
<VbenButton
|
||||
v-show="editButtonShow"
|
||||
class="ml-1.5 mt-3"
|
||||
@click="
|
||||
() => {
|
||||
editButtonShow = false;
|
||||
formApi.setState({ commonConfig: { disabled: false } });
|
||||
}
|
||||
"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
修改
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
v-show="!editButtonShow"
|
||||
class="ml-1.5 mt-3"
|
||||
:loading="saveLoading"
|
||||
@click="saveEmailConfig"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
保存
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
v-show="!editButtonShow"
|
||||
class="ml-3 mt-3"
|
||||
:disabled="saveLoading"
|
||||
variant="outline"
|
||||
@click="
|
||||
() => {
|
||||
editButtonShow = true;
|
||||
formApi.setState({ commonConfig: { disabled: true } });
|
||||
fetchConfigList();
|
||||
}
|
||||
"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
取消
|
||||
</VbenButton>
|
||||
</div>
|
||||
</a-spin>
|
||||
</template>
|
||||
@@ -0,0 +1,93 @@
|
||||
<script setup lang="ts">
|
||||
import { h, nextTick, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import Email from './email.vue';
|
||||
import Login from './login.vue';
|
||||
import UserSecurity from './user-security.vue';
|
||||
|
||||
const activeKey = ref('0');
|
||||
|
||||
const userSecurityRef = ref();
|
||||
const loginRef = ref();
|
||||
const emailRef = ref();
|
||||
|
||||
const tabItems = [
|
||||
{
|
||||
key: '0',
|
||||
label: '安全配置',
|
||||
icon: () => h('span', { class: 'icon-[carbon--security] -mb-1 size-5' }),
|
||||
},
|
||||
{
|
||||
key: '1',
|
||||
label: '登录配置',
|
||||
icon: () =>
|
||||
h('span', { class: 'icon-[majesticons--lock-line] -mb-1 size-5' }),
|
||||
},
|
||||
{
|
||||
key: '2',
|
||||
label: '邮件配置',
|
||||
icon: () => h('span', { class: 'icon-[ic--outline-email] -mb-1 size-5' }),
|
||||
},
|
||||
];
|
||||
|
||||
watch(activeKey, async (newValue) => {
|
||||
if (newValue === '0') {
|
||||
await nextTick();
|
||||
if (userSecurityRef.value) {
|
||||
await userSecurityRef.value.fetchConfigList();
|
||||
}
|
||||
}
|
||||
if (newValue === '1') {
|
||||
await nextTick();
|
||||
if (loginRef.value) {
|
||||
await loginRef.value.fetchConfigList();
|
||||
}
|
||||
}
|
||||
if (newValue === '2') {
|
||||
await nextTick();
|
||||
if (emailRef.value) {
|
||||
await emailRef.value.fetchConfigList();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick();
|
||||
if (userSecurityRef.value) {
|
||||
await userSecurityRef.value.fetchConfigList();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height>
|
||||
<a-card
|
||||
class="h-full overflow-y-auto rounded-[var(--radius)]"
|
||||
variant="borderless"
|
||||
>
|
||||
<a-tabs
|
||||
class="h-full"
|
||||
v-model:active-key="activeKey"
|
||||
tab-placement="start"
|
||||
animated
|
||||
:tab-bar-style="{ width: '16%' }"
|
||||
:items="tabItems"
|
||||
>
|
||||
<template #contentRender="{ item }">
|
||||
<UserSecurity v-if="item.key === '0'" ref="userSecurityRef" />
|
||||
<Login v-else-if="item.key === '1'" ref="loginRef" />
|
||||
<Email v-else-if="item.key === '2'" ref="emailRef" />
|
||||
</template>
|
||||
</a-tabs>
|
||||
</a-card>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
:deep(.ant-card-body) {
|
||||
height: 100%;
|
||||
min-height: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,135 @@
|
||||
<script setup lang="ts">
|
||||
import type { ConfigResult } from '../api';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { VbenButton } from '@vben/common-ui';
|
||||
import { MaterialSymbolsEdit } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
import { useVbenForm } from '#/adapter/form';
|
||||
|
||||
import { getAllConfigApi, updateConfigApi } from '../api';
|
||||
import { loginSchema } from './data';
|
||||
|
||||
const [Form, formApi] = useVbenForm({
|
||||
showDefaultActions: false,
|
||||
schema: loginSchema,
|
||||
commonConfig: {
|
||||
controlClass: 'w-full max-w-80',
|
||||
disabled: true,
|
||||
labelClass: 'justify-start ml-2 self-start',
|
||||
labelWidth: 120,
|
||||
wrapperClass: 'flex-col items-start',
|
||||
hideRequiredMark: true,
|
||||
},
|
||||
});
|
||||
|
||||
const editButtonShow = ref<boolean>(true);
|
||||
const loading = ref<boolean>(false);
|
||||
const saveLoading = ref<boolean>(false);
|
||||
|
||||
const loginData = ref<ConfigResult[]>([]);
|
||||
const fetchConfigList = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
loginData.value = await getAllConfigApi({ type: 'LOGIN' });
|
||||
loginData.value.forEach((config: any) => {
|
||||
formApi.setState((prev: any) => {
|
||||
return {
|
||||
schema: prev.schema?.map((item: any) => {
|
||||
if (item.fieldName === config.key) {
|
||||
return {
|
||||
...item,
|
||||
label: config.name,
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
};
|
||||
});
|
||||
formApi.setValues({ [config.key]: config.value });
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const saveLoginConfig = async () => {
|
||||
const { valid } = await formApi.validate();
|
||||
if (valid) {
|
||||
const data: Record<string, any> = await formApi.getValues();
|
||||
loginData.value.forEach((config: any) => {
|
||||
if (Object.prototype.hasOwnProperty.call(data, config.key)) {
|
||||
config.value = data[config.key];
|
||||
}
|
||||
});
|
||||
saveLoading.value = true;
|
||||
try {
|
||||
await updateConfigApi(loginData.value);
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
editButtonShow.value = true;
|
||||
formApi.setState({ commonConfig: { disabled: true } });
|
||||
await fetchConfigList();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
saveLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({
|
||||
fetchConfigList,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-spin :spinning="loading">
|
||||
<div>
|
||||
<Form />
|
||||
<VbenButton
|
||||
v-show="editButtonShow"
|
||||
class="ml-1.5 mt-3"
|
||||
@click="
|
||||
() => {
|
||||
editButtonShow = false;
|
||||
formApi.setState({ commonConfig: { disabled: false } });
|
||||
}
|
||||
"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
修改
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
v-show="!editButtonShow"
|
||||
class="ml-1.5 mt-3"
|
||||
:loading="saveLoading"
|
||||
@click="saveLoginConfig"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
保存
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
v-show="!editButtonShow"
|
||||
class="ml-3 mt-3"
|
||||
:disabled="saveLoading"
|
||||
variant="outline"
|
||||
@click="
|
||||
() => {
|
||||
editButtonShow = true;
|
||||
formApi.setState({ commonConfig: { disabled: true } });
|
||||
fetchConfigList();
|
||||
}
|
||||
"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
取消
|
||||
</VbenButton>
|
||||
</div>
|
||||
</a-spin>
|
||||
</template>
|
||||
@@ -0,0 +1,134 @@
|
||||
<script setup lang="ts">
|
||||
import type { ConfigResult } from '../api';
|
||||
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { VbenButton } from '@vben/common-ui';
|
||||
import { MaterialSymbolsEdit } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
|
||||
import { message } from 'antdv-next';
|
||||
|
||||
import { useVbenForm } from '#/adapter/form';
|
||||
|
||||
import { getAllConfigApi, updateConfigApi } from '../api';
|
||||
import { userSecuritySchema } from './data';
|
||||
|
||||
const [Form, formApi] = useVbenForm({
|
||||
showDefaultActions: false,
|
||||
schema: userSecuritySchema,
|
||||
commonConfig: {
|
||||
controlClass: 'w-full max-w-80',
|
||||
disabled: true,
|
||||
labelClass: 'justify-start ml-2 self-start',
|
||||
labelWidth: 180,
|
||||
hideRequiredMark: true,
|
||||
},
|
||||
});
|
||||
|
||||
const editButtonShow = ref<boolean>(true);
|
||||
const loading = ref<boolean>(false);
|
||||
const saveLoading = ref<boolean>(false);
|
||||
|
||||
const userSecurityData = ref<ConfigResult[]>([]);
|
||||
const fetchConfigList = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
userSecurityData.value = await getAllConfigApi({ type: 'USER_SECURITY' });
|
||||
userSecurityData.value.forEach((config: any) => {
|
||||
formApi.setState((prev: any) => {
|
||||
return {
|
||||
schema: prev.schema?.map((item: any) => {
|
||||
if (item.fieldName === config.key) {
|
||||
return {
|
||||
...item,
|
||||
label: config.name,
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
};
|
||||
});
|
||||
formApi.setValues({ [config.key]: config.value });
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const saveUserSecurityConfig = async () => {
|
||||
const { valid } = await formApi.validate();
|
||||
if (valid) {
|
||||
const data: Record<string, any> = await formApi.getValues();
|
||||
userSecurityData.value.forEach((config: any) => {
|
||||
if (Object.prototype.hasOwnProperty.call(data, config.key)) {
|
||||
config.value = data[config.key];
|
||||
}
|
||||
});
|
||||
saveLoading.value = true;
|
||||
try {
|
||||
await updateConfigApi(userSecurityData.value);
|
||||
message.success($t('ui.actionMessage.operationSuccess'));
|
||||
editButtonShow.value = true;
|
||||
formApi.setState({ commonConfig: { disabled: true } });
|
||||
await fetchConfigList();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
saveLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
defineExpose({
|
||||
fetchConfigList,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-spin :spinning="loading">
|
||||
<div>
|
||||
<Form />
|
||||
<VbenButton
|
||||
v-show="editButtonShow"
|
||||
class="ml-1.5 mt-3"
|
||||
@click="
|
||||
() => {
|
||||
editButtonShow = false;
|
||||
formApi.setState({ commonConfig: { disabled: false } });
|
||||
}
|
||||
"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
修改
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
v-show="!editButtonShow"
|
||||
class="ml-1.5 mt-3"
|
||||
:loading="saveLoading"
|
||||
@click="saveUserSecurityConfig"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
保存
|
||||
</VbenButton>
|
||||
<VbenButton
|
||||
v-show="!editButtonShow"
|
||||
class="ml-3 mt-3"
|
||||
:disabled="saveLoading"
|
||||
variant="outline"
|
||||
@click="
|
||||
() => {
|
||||
editButtonShow = true;
|
||||
formApi.setState({ commonConfig: { disabled: true } });
|
||||
fetchConfigList();
|
||||
}
|
||||
"
|
||||
>
|
||||
<MaterialSymbolsEdit class="mr-1" />
|
||||
取消
|
||||
</VbenButton>
|
||||
</div>
|
||||
</a-spin>
|
||||
</template>
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { PaginationResult } from '#/types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
export interface DictTypeParams {
|
||||
name?: string;
|
||||
code?: string;
|
||||
status?: number;
|
||||
page?: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface DictTypeResult {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
status: number;
|
||||
remark?: string;
|
||||
created_time: string;
|
||||
updated_time?: string;
|
||||
}
|
||||
|
||||
export interface CreateDictTypeParams {
|
||||
name: string;
|
||||
code: string;
|
||||
status: number;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface DictDataParams {
|
||||
type_id?: number;
|
||||
label?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
export interface DictDataResult {
|
||||
id: number;
|
||||
type_id: number;
|
||||
label: string;
|
||||
value: string;
|
||||
color?: string;
|
||||
sort: number;
|
||||
status: number;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export interface CreateDictDataParams {
|
||||
type_id: number;
|
||||
label: string;
|
||||
value: string;
|
||||
sort: number;
|
||||
status: number;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export async function getAllDictTypeApi() {
|
||||
return await requestClient.get<DictTypeResult[]>(
|
||||
'/api/v1/sys/dict-types/all',
|
||||
);
|
||||
}
|
||||
|
||||
export async function getDictTypeListApi(params: DictTypeParams) {
|
||||
return await requestClient.get<PaginationResult<DictTypeResult>>(
|
||||
'/api/v1/sys/dict-types',
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
export async function createDictTypeApi(data: CreateDictTypeParams) {
|
||||
return await requestClient.post('/api/v1/sys/dict-types', data);
|
||||
}
|
||||
|
||||
export async function updateDictTypeApi(
|
||||
pk: number,
|
||||
data: CreateDictTypeParams,
|
||||
) {
|
||||
return await requestClient.put(`/api/v1/sys/dict-types/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function deleteDictTypeApi(pks: number[]) {
|
||||
return await requestClient.delete('/api/v1/sys/dict-types', {
|
||||
data: { pks },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getDictDataDetailApi(code: string) {
|
||||
return await requestClient.get<DictDataResult[]>(
|
||||
`/api/v1/sys/dict-datas/type-codes/${code}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getDictDataListApi(params: DictDataParams) {
|
||||
return await requestClient.get<PaginationResult<DictDataResult>>(
|
||||
'/api/v1/sys/dict-datas',
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
export async function createDictDataApi(data: CreateDictDataParams) {
|
||||
return await requestClient.post('/api/v1/sys/dict-datas', data);
|
||||
}
|
||||
|
||||
export async function updateDictDataApi(
|
||||
pk: number,
|
||||
data: CreateDictDataParams,
|
||||
) {
|
||||
return await requestClient.put(`/api/v1/sys/dict-datas/${pk}`, data);
|
||||
}
|
||||
|
||||
export async function deleteDictDataApi(pks: number[]) {
|
||||
return await requestClient.delete('/api/v1/sys/dict-datas', {
|
||||
data: { pks },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"menu": "Dict"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"menu": "字典管理"
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user