更新前端看板

This commit is contained in:
wangjiming
2026-08-03 16:20:21 +08:00
parent 15c4223f2c
commit 0c601934a0
18 changed files with 356 additions and 187 deletions

View File

@@ -134,12 +134,45 @@ npm run dev
## 算力服务启动
算力服务是一个 FastAPI 应用,同时承载 Compute API模型训练/推理/GPU 管理)和 File Gateway文件上传下载路由。Docker 部署时对外暴露两个端口19100 和 19101均指向同一服务方便应用平台分别配置 `api_base_url``file_gateway_url`。本地开发只需启动一个进程。
### 方式一Docker 启动(推荐)
```bash
cd compute
uvicorn api.main:app --reload --port 19100
cd docker/compute
cp .env.example .env
docker compose up -d
```
默认 `COMPUTE_MODE=real`。真实 GPU 接入时,在每台算力服务器上部署 Compute API、Agent、File Gateway 和 LLaMA-Factory应用平台通过 `compute_nodes.api_base_url``compute_nodes.file_gateway_url` 主动轮询。仅在隔离联调环境可显式设置 `COMPUTE_MODE=simulator``COMPUTE_EXECUTION_MODE=simulator`
### 方式二:本地开发启动
**Windows (cmd)**
```cmd
cd /d E:\yg_ft\compute
set PYTHONPATH=E:\yg_ft
.\.venv\Scripts\python.exe -m uvicorn api.main:app --reload --port 19100
```
> `PYTHONPATH=E:\yg_ft` 是必需的,因为代码使用 `from compute.agent...` 绝对导入。
**Linux / macOS**
```bash
cd compute
PYTHONPATH=.. uvicorn api.main:app --reload --port 19100
```
### 环境变量说明
| 变量 | 默认值 | 说明 |
|---|---|---|
| `COMPUTE_MODE` | `real` | `real` / `simulator`,仅隔离联调用 simulator |
| `COMPUTE_EXECUTION_MODE` | `real` | 训练执行模式 |
| `COMPUTE_SERVICE_TOKEN` | `change_me` | 服务间认证 token |
| `MODELTF_ROUTE_PREFIX` | `/modelTF` | API 路由前缀 |
应用平台通过数据库 `compute_nodes` 表中的 `api_base_url``file_gateway_url` 主动轮询算力节点状态。
## 日志

View File

@@ -0,0 +1,10 @@
from app.db.platform_store import get_platform_store
store = get_platform_store()
with store.connect() as conn:
rows = conn.execute(
"SELECT id, user_id, login_at, logout_at, duration_seconds FROM sessions ORDER BY login_at DESC LIMIT 10"
).fetchall()
print(f"sessions count: {len(rows)}")
for r in rows:
print(f" user={r['user_id'][:25]}... login={r['login_at']} logout={r['logout_at']} dur={r['duration_seconds']}")

View File

@@ -255,10 +255,21 @@ async def _fine_tune_preflight_with_job_payload(
@router.post("/login")
async def login(payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
user = get_platform_store().login(payload.get("username", ""), payload.get("password", ""))
store = get_platform_store()
user = store.login(payload.get("username", ""), payload.get("password", ""))
if not user:
raise fail(401, "invalid username or password")
return ok({"token": f"platform-token-{user['id']}", "user": user})
sess = store.create_session(user["id"])
return ok({"token": f"platform-token-{user['id']}", "user": user, "session_id": sess["session_id"]})
@router.post("/logout")
async def logout(payload: dict[str, Any] = Body(...)) -> dict[str, Any]:
store = get_platform_store()
session_id = payload.get("session_id", "")
if session_id:
store.finish_session(session_id)
return ok(None)
@router.get("/me")
@@ -388,37 +399,23 @@ async def dashboard_stats() -> dict[str, Any]:
for t in tasks[:8]
]
# 用户操作分布:统计平台全部操作(含治理模块)
# 用户操作分布:统计 模型推理 / 模型训练 / 模型评测 / 数据处理 四类
MODULE_LABELS = [
("data-process", "数据处理"),
("data_process", "数据处理"),
("dataset", "数据集管"),
("dataset", "数据"),
("fine-tune", "模型训练"),
("fine_tune", "模型训练"),
("model-eval", "模型评测"),
("eval", "模型评测"),
("model-inference", "模型推理"),
("inference", "模型推理"),
("model-manage", "模型管理"),
("model", "模型管理"),
("trained", "模型管理"),
# 治理模块操作
("tenant", "租户与项目"),
("project", "租户与项目"),
("approval", "租户与项目"),
("acl", "租户与项目"),
("user", "用户管理"),
("role", "用户管理"),
]
OP_ORDER = [
"数据集管理",
"数据处理",
"模型训练",
"模型评测",
"模型推理",
"模型管理",
"租户与项目",
"用户管理",
]
def _op_module(action: str) -> str | None:
@@ -451,8 +448,8 @@ async def dashboard_stats() -> dict[str, Any]:
for u in recent
]
# 登录时长排行(本月)
login_duration_rank = store.login_duration_rank()
# 登录时长排行(本月),只取 top 5
login_duration_rank = store.login_duration_rank(limit=5)
return ok(
{

View File

@@ -297,9 +297,9 @@ class PlatformStore:
# TCP keepalive 让操作系统持续保活连接,抵抗远程库空闲静默断连。
pool_kwargs = {
"keepalives": 1,
"keepalives_idle": 30,
"keepalives_interval": 10,
"keepalives_count": 5,
"keepalives_idle": 10,
"keepalives_interval": 5,
"keepalives_count": 3,
}
self._pool = ConnectionPool(
conninfo=self.database_url,

View File

@@ -18,12 +18,12 @@ const auth = useAuthStore()
*/
let hiddenAt = 0
function handleVisibility() {
async function handleVisibility() {
if (document.hidden) {
hiddenAt = Date.now()
} else {
if (hiddenAt > 0 && Date.now() - hiddenAt >= SESSION_TIMEOUT) {
auth.logout()
await auth.logout()
ElMessage.warning('登录已过期,请重新登录')
router.push('/login')
}

View File

@@ -53,3 +53,6 @@ export const updateProjectMember = (id: string, userId: string, role: string) =>
/** 移除成员 */
export const removeProjectMember = (id: string, userId: string) =>
del(`/projects/${id}/members/${userId}`)
/** 删除项目 */
export const deleteProject = (id: string) => del(`/projects/${id}`)

View File

@@ -18,6 +18,10 @@ export const getHealth = () => get<HealthMetrics>('/health')
export const login = (username: string, password: string) =>
post<LoginResponse>('/login', { username, password })
/** 登出 */
export const logout = (sessionId?: string) =>
post('/logout', { session_id: sessionId || '' })
/** 用户列表 */
export const getUsers = () => get<SystemUser[]>('/users')

View File

@@ -1,4 +1,4 @@
import { get, post, put } from '../request'
import { del, get, post, put } from '../request'
export interface Tenant {
id: string
@@ -25,6 +25,9 @@ export const createTenant = (payload: Partial<Tenant>) =>
export const updateTenant = (id: string, payload: Partial<Tenant>) =>
put<Tenant>(`/tenants/${id}`, payload)
/** 删除租户 */
export const deleteTenant = (id: string) => del(`/tenants/${id}`)
/** 设置租户配额 */
export const setTenantQuota = (id: string, quota: Record<string, unknown>) =>
put<Tenant>(`/tenants/${id}/quota`, { quota })

View File

@@ -14,7 +14,7 @@ export interface ApiResult<T = any> {
const service: AxiosInstance = axios.create({
// Use a relative path; Vite proxies /modelTF to http://localhost:17861 in local development.
baseURL: '/modelTF',
timeout: 30000,
timeout: 120000,
})
/**

View File

@@ -2,6 +2,7 @@
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getAcl, setAcl, type AclEntry } from '@/api/modules/acl'
import { getUsers, type SystemUser } from '@/api/modules/system'
const props = defineProps<{
modelValue: boolean
@@ -15,13 +16,20 @@ const visible = computed({
set: (v) => emit('update:modelValue', v),
})
const entries = ref<AclEntry[]>([])
const users = ref<SystemUser[]>([])
const loading = ref(false)
const ALL_PERMS = ['read', 'write', 'execute', 'download', 'delete', 'share']
const PROJECT_ROLES = ['member', 'admin', 'viewer']
async function load() {
loading.value = true
try {
entries.value = await getAcl(props.resourceType, props.resourceId)
const [acl, us] = await Promise.all([
getAcl(props.resourceType, props.resourceId),
getUsers().catch(() => [] as SystemUser[]),
])
entries.value = acl
users.value = us
} finally {
loading.value = false
}
@@ -53,7 +61,12 @@ async function save() {
<el-option label="用户" value="user" />
<el-option label="项目角色" value="project_role" />
</el-select>
<el-input v-model="entry.subject_id" placeholder="subject ID" style="width: 200px" />
<el-select v-if="entry.subject_type === 'user'" v-model="entry.subject_id" placeholder="选择用户" style="width: 200px" filterable>
<el-option v-for="u in users" :key="u.id" :label="`${u.username} (${u.id})`" :value="u.id" />
</el-select>
<el-select v-else v-model="entry.subject_id" placeholder="选择角色" style="width: 200px">
<el-option v-for="r in PROJECT_ROLES" :key="r" :label="r" :value="r" />
</el-select>
<el-checkbox-group v-model="entry.permissions">
<el-checkbox v-for="p in ALL_PERMS" :key="p" :value="p">{{ p }}</el-checkbox>
</el-checkbox-group>

View File

@@ -132,8 +132,8 @@ async function handleSelect(key: string) {
}
}
function handleLogout() {
auth.logout()
async function handleLogout() {
await auth.logout()
router.push('/login')
}
</script>

View File

@@ -377,7 +377,7 @@ router.beforeEach((to, _from, next) => {
}
if (!auth.isLoggedIn) {
auth.logout()
auth.logout() // fire-and-forget无需阻塞跳转
next({ name: 'login' })
return
}

View File

@@ -1,9 +1,10 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi } from '@/api/modules/system'
import { login as loginApi, logout as logoutApi } from '@/api/modules/system'
import type { PermissionCode, SystemUser } from '@/types'
const USER_STORAGE_KEY = 'currentUser'
const SESSION_STORAGE_KEY = 'sessionId'
const allPermissions: PermissionCode[] = [
'dashboard',
@@ -29,20 +30,6 @@ function restoreUser(): SystemUser | null {
localStorage.removeItem(USER_STORAGE_KEY)
}
}
// 兼容改造前已经登录的 admin 会话。
if (localStorage.getItem('username') === 'admin') {
return {
id: 'USR-0001',
username: 'admin',
display_name: '系统管理员',
role: 'admin',
status: 'active',
permissions: allPermissions,
create_time: '2026-01-01T08:00:00+08:00',
protected: true,
}
}
return null
}
@@ -69,6 +56,9 @@ export const useAuthStore = defineStore('auth', () => {
currentUser.value = response.user
localStorage.setItem('username', response.user.username)
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(response.user))
if (response.session_id) {
localStorage.setItem(SESSION_STORAGE_KEY, response.session_id)
}
}
/** 检查当前账号是否拥有指定模块权限。 */
@@ -78,10 +68,15 @@ export const useAuthStore = defineStore('auth', () => {
}
/** 退出 */
function logout() {
async function logout() {
const sessionId = localStorage.getItem(SESSION_STORAGE_KEY)
if (sessionId) {
try { await logoutApi(sessionId) } catch { /* 静默 */ }
}
currentUser.value = null
localStorage.removeItem('username')
localStorage.removeItem(USER_STORAGE_KEY)
localStorage.removeItem(SESSION_STORAGE_KEY)
}
return {

View File

@@ -446,6 +446,7 @@ export interface SystemUser {
export interface LoginResponse {
token: string
user: SystemUser
session_id?: string
}
export interface CreateUserPayload {

View File

@@ -179,20 +179,30 @@ const chartOption = computed<EChartsOption>(() => ({
],
}))
// 模块固定配色,保证每个模块颜色不同
const OPERATION_COLORS = ['#4f46e5', '#10b981', '#f59e0b', '#3b82f6', '#ec4899', '#8b5cf6', '#ef4444', '#14b8a6']
// 模块固定配色,按顺序循环分配颜色(与后端 OP_ORDER 一致:数据处理/模型训练/模型评测/模型推理)
const OPERATION_COLORS = ['#4f46e5', '#10b981', '#f59e0b', '#3b82f6']
const operationChartOption = computed<EChartsOption>(() => {
const items = operationDistribution.value
const total = items.reduce((s, d) => s + (d.value || 0), 0)
// 完全没有操作数据时,用等分灰色占位扇区,保证 6 个模块都可见
const data =
total > 0
? items.map((d) => ({ value: d.value || 0, name: d.name }))
: items.map((d) => ({ value: 1, name: d.name, itemStyle: { color: '#e2e8f0' } }))
// 按数据项顺序显式分配颜色,避免依赖 name 匹配或全局 color 数组;
// value=0 的项给一个极小值0.001)让扇区可见,从而显示各自颜色,
// 但占比几乎为 0 不影响有数据项的百分比展示。
const data = items.map((d, idx) => {
const raw = d.value || 0
return {
value: total > 0 ? (raw > 0 ? raw : 0.001) : 1,
name: d.name,
itemStyle: {
color: OPERATION_COLORS[idx % OPERATION_COLORS.length] || '#94a3b8',
borderRadius: 6,
borderColor: '#fff',
borderWidth: 2,
},
}
})
return {
animationDuration: 500,
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
color: OPERATION_COLORS,
legend: {
type: 'scroll',
bottom: 0,
@@ -207,11 +217,6 @@ const operationChartOption = computed<EChartsOption>(() => {
radius: ['38%', '60%'],
center: ['50%', '42%'],
avoidLabelOverlap: true,
itemStyle: {
borderRadius: 6,
borderColor: '#fff',
borderWidth: 2,
},
label: {
show: true,
position: 'outside',
@@ -235,43 +240,54 @@ const operationChartOption = computed<EChartsOption>(() => {
}
})
const loginDurationChartOption = computed<EChartsOption>(() => ({
animationDuration: 500,
grid: { top: 8, right: 12, bottom: 6, left: 8, containLabel: true },
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
valueFormatter: (value) => `${value} 小时`,
},
xAxis: {
type: 'value',
max: Math.max(10, Math.ceil(Math.max(...loginDurationStats.value.map((user) => user.duration), 0) * 1.15 / 10) * 10),
splitNumber: 4,
axisLabel: { color: '#94a3b8', fontSize: 11, formatter: '{value}h' },
axisLine: { show: false },
axisTick: { show: false },
splitLine: { lineStyle: { color: '#eef2f7' } },
},
yAxis: {
type: 'category',
inverse: true,
data: loginDurationStats.value.map((user) => user.username),
axisLabel: { color: '#475569', fontSize: 12 },
axisLine: { show: false },
axisTick: { show: false },
},
series: [
{
name: '登录时长',
type: 'bar',
data: loginDurationStats.value.map((user) => user.duration),
barMaxWidth: 18,
barCategoryGap: '34%',
itemStyle: { color: '#4f46e5', borderRadius: [0, 4, 4, 0] },
label: { show: true, position: 'insideRight', distance: 6, color: '#ffffff', fontSize: 11, formatter: '{c} 小时' },
const loginDurationChartOption = computed<EChartsOption>(() => {
const stats = loginDurationStats.value
const data = stats.map((u) => ({ name: u.username, value: u.duration }))
const maxVal = data.length
? Math.max(10, Math.ceil(Math.max(...data.map((d) => d.value), 0) * 1.15 / 10) * 10)
: 10
return {
animationDuration: 500,
grid: { top: 8, right: 12, bottom: 6, left: 8, containLabel: true },
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
valueFormatter: (value: number) => `${value} 小时`,
},
],
}))
xAxis: {
type: 'value',
max: maxVal,
splitNumber: 4,
axisLabel: { color: '#94a3b8', fontSize: 11, formatter: '{value}h' },
axisLine: { show: false },
axisTick: { show: false },
splitLine: { lineStyle: { color: '#eef2f7' } },
},
yAxis: {
type: 'category',
inverse: true,
data: data.map((d) => d.name),
axisLabel: {
color: '#1f2937',
fontSize: 14,
fontFamily: '"PingFang SC", "Microsoft YaHei", system-ui, -apple-system, sans-serif',
margin: 12,
},
axisLine: { show: false },
axisTick: { show: false },
},
series: [
{
name: '登录时长',
type: 'bar',
data: data.map((d) => d.value),
barMaxWidth: 18,
barCategoryGap: '34%',
itemStyle: { color: '#4f46e5', borderRadius: [0, 4, 4, 0] },
},
],
}
})
const roleTagType: Record<string, 'danger' | 'primary' | 'info'> = {
'超级管理员': 'danger',
@@ -405,10 +421,9 @@ function viewTask(task: DashboardTask) {
<section class="stat-card" aria-labelledby="login-dur-title">
<h2 id="login-dur-title" class="section-title">登录时长排行 (本月)</h2>
<div v-if="loginDurationStats.length" class="chart-container">
<div class="chart-container">
<VChart class="duration-chart" :option="loginDurationChartOption" autoresize />
</div>
<div v-else class="empty-hint">暂无数据</div>
</section>
<section class="stat-card" aria-labelledby="recent-login-title">

View File

@@ -1,10 +1,10 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import DataTablePage from '@/components/DataTablePage.vue'
import { createProject, getProjects, type Project } from '@/api/modules/project'
import { createProject, deleteProject, getProjects, type Project } from '@/api/modules/project'
import { getTenants, type Tenant } from '@/api/modules/tenant'
const router = useRouter()
@@ -13,13 +13,24 @@ const projects = ref<Project[]>([])
const tenants = ref<Tenant[]>([])
const tenantId = ref('default')
const showCreate = ref(false)
const form = ref({ name: '', code: '', description: '', tenant_id: 'default' })
const form = ref({ name: '', code: '', description: '', tenant_id: '' })
const tenantOptions = computed(() => [
{ label: 'default', value: 'default' },
...tenants.value.map((t) => ({ label: t.name, value: t.id })),
])
const tenantCodeOptions = computed(() =>
tenants.value.map((t) => ({ label: t.code, value: t.code, tenantId: t.id }))
)
function onTenantCodeChange(code: string) {
const tenant = tenants.value.find((t) => t.code === code)
if (tenant) {
form.value.tenant_id = tenant.id
}
}
async function load() {
loading.value = true
try {
@@ -42,14 +53,29 @@ function openDetail(id: string) {
}
async function submitCreate() {
if (!form.value.name || !form.value.code) {
ElMessage.warning('请填写项目名与编码')
if (!form.value.name || !form.value.tenant_id) {
ElMessage.warning('请填写项目名与编码ID')
return
}
await createProject({ ...form.value })
ElMessage.success('项目创建成功')
showCreate.value = false
form.value = { name: '', code: '', description: '', tenant_id: 'default' }
form.value = { name: '', code: '', description: '', tenant_id: '' }
load()
}
async function handleDelete(row: Project) {
try {
await ElMessageBox.confirm(
`确定要删除项目「${row.name}」吗?删除后相关数据将无法恢复。`,
'删除确认',
{ confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning' },
)
} catch {
return
}
await deleteProject(row.id)
ElMessage.success('项目已删除')
load()
}
@@ -70,13 +96,14 @@ onMounted(() => {
</template>
<template #columns>
<el-table-column prop="name" label="项目名" min-width="140" />
<el-table-column prop="code" label="编码" min-width="100" />
<el-table-column prop="code" label="编码ID" min-width="100" />
<el-table-column prop="status" label="状态" min-width="100" />
<el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
<el-table-column prop="create_time" label="创建时间" min-width="180" />
</template>
<template #actions="{ row }">
<el-button link type="primary" @click="openDetail(row.id)">详情</el-button>
<el-button link type="danger" @click="handleDelete(row)">删除</el-button>
</template>
</DataTablePage>
<el-dialog v-model="showCreate" title="新建项目" width="520px">
@@ -84,12 +111,9 @@ onMounted(() => {
<el-form-item label="名称" required>
<el-input v-model="form.name" placeholder="项目名" />
</el-form-item>
<el-form-item label="编码" required>
<el-input v-model="form.code" placeholder="project code" />
</el-form-item>
<el-form-item label="租户">
<el-select v-model="form.tenant_id" style="width: 100%">
<el-option v-for="t in tenantOptions" :key="t.value" :label="t.label" :value="t.value" />
<el-form-item label="编码ID" required>
<el-select v-model="form.tenant_id" style="width: 100%" placeholder="选择租户编码">
<el-option v-for="t in tenantCodeOptions" :key="t.value" :label="t.label" :value="t.tenantId" />
</el-select>
</el-form-item>
<el-form-item label="描述">

View File

@@ -1,25 +1,42 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import DataTablePage from '@/components/DataTablePage.vue'
import { getTenant, setTenantQuota, type Tenant } from '@/api/modules/tenant'
import { getProjects, type Project } from '@/api/modules/project'
const route = useRoute()
const router = useRouter()
const tenant = ref<Tenant | null>(null)
const projects = ref<Project[]>([])
const loading = ref(false)
const quotaText = ref('')
const quotaForm = reactive({ gpu: 0, storage: 0, maxProjects: 0 })
function parseQuota(quota: Record<string, unknown> | undefined | null) {
const q = quota || {}
return {
gpu: Number(q.gpu || q.gpu_quota || 0),
storage: Number(q.storage || q.storage_quota || 0),
maxProjects: Number(q.max_projects || 0),
}
}
function formatQuota(quota: Record<string, unknown> | undefined | null) {
const q = parseQuota(quota)
const parts: string[] = []
if (q.gpu > 0) parts.push(`GPU ${q.gpu}`)
if (q.storage > 0) parts.push(`存储 ${q.storage}GB`)
if (q.maxProjects > 0) parts.push(`项目 ${q.maxProjects}`)
return parts.length ? parts.join(' | ') : '—'
}
async function load() {
const id = route.params.id as string
loading.value = true
try {
tenant.value = await getTenant(id)
projects.value = await getProjects(id)
quotaText.value = JSON.stringify(tenant.value?.quota || {})
const q = parseQuota(tenant.value?.quota)
quotaForm.gpu = q.gpu
quotaForm.storage = q.storage
quotaForm.maxProjects = q.maxProjects
} finally {
loading.value = false
}
@@ -27,18 +44,13 @@ async function load() {
async function saveQuota() {
if (!tenant.value) return
try {
const q = JSON.parse(quotaText.value || '{}')
await setTenantQuota(tenant.value.id, q)
ElMessage.success('配额已保存')
load()
} catch {
ElMessage.error('配额需为合法 JSON')
}
}
function openProject(id: string) {
router.push(`/projects/${id}`)
const quota: Record<string, unknown> = {}
if (quotaForm.gpu > 0) quota.gpu = quotaForm.gpu
if (quotaForm.storage > 0) quota.storage = quotaForm.storage
if (quotaForm.maxProjects > 0) quota.max_projects = quotaForm.maxProjects
await setTenantQuota(tenant.value.id, quota)
ElMessage.success('配额已保存')
load()
}
onMounted(load)
@@ -55,31 +67,30 @@ onMounted(load)
<template #header>基本信息</template>
<el-descriptions :column="2" border>
<el-descriptions-item label="名称">{{ tenant?.name }}</el-descriptions-item>
<el-descriptions-item label="编码">{{ tenant?.code }}</el-descriptions-item>
<el-descriptions-item label="用户ID">{{ tenant?.code }}</el-descriptions-item>
<el-descriptions-item label="状态">{{ tenant?.status }}</el-descriptions-item>
<el-descriptions-item label="创建时间">{{ tenant?.create_time }}</el-descriptions-item>
<el-descriptions-item label="配额">{{ formatQuota(tenant?.quota) }}</el-descriptions-item>
</el-descriptions>
<el-divider />
<div class="quota-edit">
<span class="label">配额 JSON</span>
<el-input v-model="quotaText" type="textarea" :rows="3" />
<el-button type="primary" @click="saveQuota">保存配额</el-button>
<span class="label">配额设置0 表示不限制</span>
<el-form label-width="100px">
<el-form-item label="GPU 数量">
<el-input-number v-model="quotaForm.gpu" :min="0" :step="1" />
</el-form-item>
<el-form-item label="存储配额(GB)">
<el-input-number v-model="quotaForm.storage" :min="0" :step="10" />
</el-form-item>
<el-form-item label="最大项目数">
<el-input-number v-model="quotaForm.maxProjects" :min="0" :step="1" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="saveQuota">保存配额</el-button>
</el-form-item>
</el-form>
</div>
</el-card>
<el-card class="section">
<template #header>项目空间</template>
<DataTablePage title="项目空间" :data="projects">
<template #columns>
<el-table-column prop="name" label="项目名" min-width="140" />
<el-table-column prop="code" label="编码" min-width="100" />
<el-table-column prop="status" label="状态" min-width="100" />
<el-table-column prop="create_time" label="创建时间" min-width="180" />
</template>
<template #actions="{ row }">
<el-button link type="primary" @click="openProject(row.id)">打开</el-button>
</template>
</DataTablePage>
</el-card>
</div>
</template>

View File

@@ -1,16 +1,37 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import DataTablePage from '@/components/DataTablePage.vue'
import { createTenant, getTenants, setTenantQuota, type Tenant } from '@/api/modules/tenant'
import { createTenant, deleteTenant, getTenants, setTenantQuota, type Tenant } from '@/api/modules/tenant'
const router = useRouter()
const loading = ref(false)
const tenants = ref<Tenant[]>([])
const showCreate = ref(false)
const form = ref({ name: '', code: '', quota: '' as string })
const showQuota = ref(false)
const currentTenant = ref<Tenant | null>(null)
const form = ref({ name: '', code: '', gpu: 0, storage: 0, maxProjects: 0 })
const quotaForm = reactive({ gpu: 0, storage: 0, maxProjects: 0 })
function parseQuota(quota: Record<string, unknown> | undefined | null) {
const q = quota || {}
return {
gpu: Number(q.gpu || q.gpu_quota || 0),
storage: Number(q.storage || q.storage_quota || 0),
maxProjects: Number(q.max_projects || 0),
}
}
function formatQuota(quota: Record<string, unknown> | undefined | null) {
const q = parseQuota(quota)
const parts: string[] = []
if (q.gpu > 0) parts.push(`GPU ${q.gpu}`)
if (q.storage > 0) parts.push(`存储 ${q.storage}GB`)
if (q.maxProjects > 0) parts.push(`项目 ${q.maxProjects}`)
return parts.length ? parts.join(' | ') : '—'
}
async function load() {
loading.value = true
@@ -30,35 +51,51 @@ async function submitCreate() {
ElMessage.warning('请填写租户名称')
return
}
let quota: Record<string, unknown> = {}
if (form.value.quota) {
try {
quota = JSON.parse(form.value.quota)
} catch {
ElMessage.error('配额需为合法 JSON')
return
}
}
const quota: Record<string, unknown> = {}
if (form.value.gpu > 0) quota.gpu = form.value.gpu
if (form.value.storage > 0) quota.storage = form.value.storage
if (form.value.maxProjects > 0) quota.max_projects = form.value.maxProjects
await createTenant({ name: form.value.name, code: form.value.code, quota })
ElMessage.success('租户创建成功')
showCreate.value = false
form.value = { name: '', code: '', quota: '' }
form.value = { name: '', code: '', gpu: 0, storage: 0, maxProjects: 0 }
load()
}
async function setQuota(row: Tenant) {
const input = await ElMessageBox.prompt('输入租户配额 JSON', '设置配额', {
inputValue: JSON.stringify(row.quota || {}),
}).catch(() => null)
if (!input) return
function openQuotaDialog(row: Tenant) {
currentTenant.value = row
const q = parseQuota(row.quota)
quotaForm.gpu = q.gpu
quotaForm.storage = q.storage
quotaForm.maxProjects = q.maxProjects
showQuota.value = true
}
async function submitQuota() {
if (!currentTenant.value) return
const quota: Record<string, unknown> = {}
if (quotaForm.gpu > 0) quota.gpu = quotaForm.gpu
if (quotaForm.storage > 0) quota.storage = quotaForm.storage
if (quotaForm.maxProjects > 0) quota.max_projects = quotaForm.maxProjects
await setTenantQuota(currentTenant.value.id, quota)
ElMessage.success('配额已更新')
showQuota.value = false
load()
}
async function handleDelete(row: Tenant) {
try {
const q = JSON.parse(input.value)
await setTenantQuota(row.id, q)
ElMessage.success('配额已更新')
load()
await ElMessageBox.confirm(
`确定要删除租户「${row.name}」吗?删除后相关数据将无法恢复。`,
'删除确认',
{ confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning' },
)
} catch {
ElMessage.error('无效的 JSON')
return
}
await deleteTenant(row.id)
ElMessage.success('租户已删除')
load()
}
onMounted(load)
@@ -72,30 +109,34 @@ onMounted(load)
</template>
<template #columns>
<el-table-column prop="name" label="租户名称" min-width="140" />
<el-table-column prop="code" label="编码" min-width="100" />
<el-table-column label="配额" min-width="160">
<template #default="{ row }">
{{ Object.keys(row.quota || {}).length ? JSON.stringify(row.quota) : '—' }}
</template>
</el-table-column>
<el-table-column prop="code" label="用户ID" min-width="100" />
<el-table-column prop="status" label="状态" min-width="100" />
<el-table-column prop="create_time" label="创建时间" min-width="180" />
</template>
<template #actions="{ row }">
<el-button link type="primary" @click="openDetail(row.id)">详情</el-button>
<el-button link type="primary" @click="setQuota(row)">配额</el-button>
<el-button link type="danger" @click="handleDelete(row)">删除</el-button>
</template>
</DataTablePage>
<!-- 新建租户弹窗 -->
<el-dialog v-model="showCreate" title="新建租户" width="520px">
<el-form label-width="90px">
<el-form label-width="100px">
<el-form-item label="名称" required>
<el-input v-model="form.name" placeholder="租户名称" />
</el-form-item>
<el-form-item label="编码">
<el-input v-model="form.code" placeholder="tenant code" />
<el-form-item label="用户ID">
<el-input v-model="form.code" placeholder="用户ID" />
</el-form-item>
<el-form-item label="配额 JSON">
<el-input v-model="form.quota" type="textarea" :rows="3" placeholder='{"gpu": 8}' />
<el-divider content-position="left">配额设置可选0 表示不限制</el-divider>
<el-form-item label="GPU 数量">
<el-input-number v-model="form.gpu" :min="0" :step="1" placeholder="GPU 卡数" />
</el-form-item>
<el-form-item label="存储配额(GB)">
<el-input-number v-model="form.storage" :min="0" :step="10" placeholder="存储大小" />
</el-form-item>
<el-form-item label="最大项目数">
<el-input-number v-model="form.maxProjects" :min="0" :step="1" placeholder="项目上限" />
</el-form-item>
</el-form>
<template #footer>
@@ -103,6 +144,25 @@ onMounted(load)
<el-button type="primary" @click="submitCreate">创建</el-button>
</template>
</el-dialog>
<!-- 设置配额弹窗 -->
<el-dialog v-model="showQuota" title="设置配额" width="480px">
<el-form label-width="100px">
<el-form-item label="GPU 数量">
<el-input-number v-model="quotaForm.gpu" :min="0" :step="1" placeholder="GPU 卡数" />
</el-form-item>
<el-form-item label="存储配额(GB)">
<el-input-number v-model="quotaForm.storage" :min="0" :step="10" placeholder="存储大小" />
</el-form-item>
<el-form-item label="最大项目数">
<el-input-number v-model="quotaForm.maxProjects" :min="0" :step="1" placeholder="项目上限" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="showQuota = false">取消</el-button>
<el-button type="primary" @click="submitQuota">保存</el-button>
</template>
</el-dialog>
</div>
</template>