Files
Nexus/frontend/src/pages/DashboardPage.vue
T
Nexus Agent 86bc737f4c fix(dashboard): 修复服务器列表不显示
清除 keep-alive 下 loading 卡死;改用 v-card-text 与表格内置 loading,并加 30s 自动刷新。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 13:13:34 +08:00

446 lines
15 KiB
Vue

<template>
<v-container fluid class="pa-4 pa-md-6 dashboard-root">
<v-skeleton-loader v-if="statsBooting" type="heading, text" class="mb-4" />
<StatCardsRow v-else :items="statItems" />
<!-- ── Server Table ── -->
<v-card class="my-5" elevation="0" rounded="lg" border>
<v-card-title class="text-h6">服务器列表</v-card-title>
<v-card-text>
<v-text-field
v-model="search"
autocomplete="off"
placeholder="搜索..."
prepend-inner-icon="mdi-magnify"
variant="outlined"
hide-details
rounded
density="compact"
class="mb-4"
@update:model-value="onSearch"
/>
<v-data-table-server
:items="servers"
:headers="headers"
:items-length="total"
:loading="loading"
:page="page"
:items-per-page="itemsPerPage"
:items-per-page-options="dataTablePageOptions"
v-model:sort-by="sortBy"
hover
item-value="id"
@update:page="onPageChange"
@update:items-per-page="onItemsPerPageChange"
>
<template #item.status="{ item }">
<v-chip
:color="statusChipColor(item.status)"
:text="statusLabel(item.status)"
border="sm"
size="x-small"
label
/>
</template>
<template #item.name="{ item }">
<span class="font-weight-medium">{{ item.name }}</span>
</template>
<template #item.domain="{ item }">
<span class="text-medium-emphasis">{{ item.domain }}</span>
</template>
<template #item.category="{ item }">
<span class="text-medium-emphasis">{{ item.category || '—' }}</span>
</template>
<template #item.agent_version="{ item }">
<span class="text-medium-emphasis">{{ item.agent_version || '—' }}</span>
</template>
<template #item.last_heartbeat="{ item }">
<span class="text-caption text-medium-emphasis">{{ formatRelativeTime(item.last_heartbeat) }}</span>
</template>
<template #item.actions="{ item }">
<div class="d-flex ga-1">
<v-btn variant="text" size="x-small" color="primary" density="compact" @click="openTerminal(item)">终端</v-btn>
<v-btn variant="text" size="x-small" density="compact" @click="openFiles(item)">文件</v-btn>
</div>
</template>
<template #no-data>
<div class="text-center text-medium-emphasis py-6">暂无服务器数据</div>
</template>
</v-data-table-server>
</v-card-text>
</v-card>
<!-- ── Bottom Row: Alerts + Summary ── -->
<v-row>
<v-col cols="12" md="6">
<v-card elevation="0" rounded="lg" title="告警历史" border>
<template #append>
<div class="my-5" />
</template>
<template #text>
<div v-if="recentAlerts.length === 0" class="text-center text-medium-emphasis py-4">
暂无告警
</div>
<v-list-item
v-for="(item, i) in recentAlerts"
:key="i"
:class="i !== 0 && 'mt-4'"
:subtitle="item.subtitle"
:title="item.title"
class="px-0"
lines="one"
>
<template #prepend>
<v-avatar
:color="item.color"
:icon="item.icon"
variant="tonal"
rounded
/>
</template>
<template #append>
<span class="text-body-large font-weight-regular">
{{ item.value }}
</span>
</template>
</v-list-item>
</template>
</v-card>
</v-col>
<v-col cols="12" md="6">
<v-card elevation="0" rounded="lg" title="资源概览" border>
<template #append>
<div class="my-5" />
</template>
<template #text>
<v-list-item
v-for="(item, i) in summaryItems"
:key="i"
:class="i !== 0 && 'mt-4'"
class="px-0"
>
<template #prepend>
<v-avatar :text="item.text" color="primary" size="large" variant="tonal" />
</template>
<template #title>
<div class="d-flex justify-space-between align-center text-medium-emphasis">
<span>{{ item.title }}</span>
<span>{{ item.value }}</span>
</div>
</template>
<template #subtitle>
<div class="py-1">
<v-progress-linear
:model-value="item.progress"
bg-color="surface-light"
bg-opacity="1"
color="primary"
height="8"
rounded
/>
</div>
</template>
</v-list-item>
</template>
</v-card>
</v-col>
</v-row>
<!-- ── Second Row: Categories + Recent Audit ── -->
<v-row>
<v-col cols="12" md="6">
<v-card elevation="0" rounded="lg" title="分类分布" border>
<template #text>
<div v-if="Object.keys(categories).length === 0" class="text-center text-medium-emphasis py-4">
暂无分类数据
</div>
<v-list-item
v-for="(count, name) in categories"
:key="name"
class="px-0"
>
<template #prepend>
<v-avatar color="primary" variant="tonal" size="small">
<span class="text-caption">{{ (name as string)[0]?.toUpperCase() }}</span>
</v-avatar>
</template>
<template #title>
<div class="d-flex justify-space-between align-center">
<span class="text-medium-emphasis">{{ name === 'uncategorized' ? '未分类' : name }}</span>
<span class="text-body-2 font-weight-medium">{{ count }} </span>
</div>
</template>
<template #subtitle>
<v-progress-linear
:model-value="statsTotal > 0 ? (count / statsTotal) * 100 : 0"
bg-color="surface-light"
bg-opacity="1"
color="primary"
height="6"
rounded
/>
</template>
</v-list-item>
</template>
</v-card>
</v-col>
<v-col cols="12" md="6">
<v-card elevation="0" rounded="lg" title="最近操作" border>
<template #append>
<v-btn size="small" variant="text" to="/audit">查看全部</v-btn>
</template>
<template #text>
<div v-if="recentAudit.length === 0" class="text-center text-medium-emphasis py-4">
暂无操作记录
</div>
<v-list-item
v-for="item in recentAudit"
:key="item.id"
:title="auditSummary(item)"
:subtitle="`${item.admin_username} · ${formatRelativeTime(item.created_at)}`"
class="px-0"
lines="two"
>
<template #append>
<v-chip size="x-small" variant="tonal" label>{{ item.ip_address || '—' }}</v-chip>
</template>
</v-list-item>
</template>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<style scoped>
.dashboard-root {
min-width: 0;
max-width: 100%;
}
.dashboard-root :deep(.v-table) {
overflow-x: auto;
}
</style>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import { useWebSocket } from '@/composables/useWebSocket'
import { useServerPagination } from '@/composables/useServerPagination'
import { usePageActivateRefresh } from '@/composables/usePageActivateRefresh'
import { usePageAutoRefresh } from '@/composables/usePageAutoRefresh'
import { CACHE_KEYS, cachedFetch } from '@/composables/useCachedQuery'
import { statusChipColor, statusLabel, formatRelativeTime } from '@/utils/status'
import { auditSummary } from '@/utils/auditLabels'
import { normalizeAuditList } from '@/utils/auditNormalize'
import type { ServerApiItem, AuditItem, AlertLogItem } from '@/types/api'
import StatCardsRow from '@/components/StatCardsRow.vue'
import { DATA_TABLE_ITEMS_PER_PAGE_OPTIONS } from '@/constants/dataTable'
defineOptions({ name: 'DashboardPage' })
const dataTablePageOptions = [...DATA_TABLE_ITEMS_PER_PAGE_OPTIONS]
const snackbar = useSnackbar()
const router = useRouter()
const statsBooting = ref(true)
// ── Stats ──
const statItems = ref([
{ subtitle: '服务器总数', title: '0', icon: 'mdi-server-network', color: 'blue' },
{ subtitle: '在线', title: '0', icon: 'mdi-check-circle-outline', color: 'green' },
{ subtitle: '离线', title: '0', icon: 'mdi-alert-circle-outline', color: 'orange' },
{ subtitle: '告警中', title: '0', icon: 'mdi-bell-alert-outline', color: 'red' },
])
// ── Server Table (composable) ──
const {
servers, loading, page, itemsPerPage, total, search, sortBy,
loadServers: _loadServers, onSearch, onPageChange, onItemsPerPageChange,
} = useServerPagination()
async function loadServers(silent = false) {
try {
await _loadServers({ silent })
} catch {
if (!silent) snackbar('加载服务器列表失败', 'error')
}
}
const headers = [
{ title: '状态', key: 'status', width: 100 },
{ title: '名称', key: 'name' },
{ title: '地址', key: 'domain' },
{ title: '分类', key: 'category', width: 100 },
{ title: 'Agent', key: 'agent_version', width: 100 },
{ title: '心跳', key: 'last_heartbeat', width: 140 },
{ title: '操作', key: 'actions', width: 140, align: 'end' as const, sortable: false },
]
// ── Alerts ──
const recentAlerts = ref<AlertItem[]>([])
// ── Summary ──
const summaryItems = ref([
{ title: '在线率', progress: 0, text: '在', value: '0%' },
{ title: 'Agent 覆盖', progress: 0, text: 'A', value: '0%' },
{ title: 'CPU 平均', progress: 0, text: 'C', value: '0%' },
{ title: '内存平均', progress: 0, text: 'M', value: '0%' },
])
// ── Categories ──
const categories = ref<Record<string, number>>({})
const statsTotal = ref(0)
// ── Recent Audit ──
const recentAudit = ref<AuditItem[]>([])
// ── Data Loading ──
async function loadStats(silent = false) {
if (!silent) statsBooting.value = true
try {
const { data: s } = await cachedFetch(
CACHE_KEYS.serverStats,
() => http.get<{ total: number; online: number; offline: number; alerts: number; categories: Record<string, number> }>('/servers/stats'),
)
statItems.value[0].title = String(s.total)
statItems.value[1].title = String(s.online)
statItems.value[2].title = String(s.offline)
statItems.value[3].title = String(s.alerts ?? 0)
// Capture categories and total for distribution chart
categories.value = s.categories || {}
statsTotal.value = s.total
// Update summary
const onlineRate = s.total ? Math.round((s.online / s.total) * 100) : 0
summaryItems.value[0].progress = onlineRate
summaryItems.value[0].value = `${onlineRate}%`
} catch {
if (!silent) snackbar('加载统计数据失败', 'error')
} finally {
if (!silent) statsBooting.value = false
}
}
async function loadAlerts() {
try {
const res = await http.get<{ items: AlertLogItem[] }>('/alert-history/', { limit: 5 })
recentAlerts.value = (res.items || []).map(a => ({
title: a.server_name,
subtitle: `${a.alert_type} ${a.is_recovery ? '(已恢复)' : ''} · ${formatRelativeTime(a.created_at)}`,
value: a.value,
color: a.is_recovery ? 'green' : 'red',
icon: a.is_recovery ? 'mdi-check-circle' : 'mdi-alert-circle',
}))
} catch {
recentAlerts.value = []
snackbar('加载告警记录失败', 'error')
}
}
async function loadRecentAudit() {
try {
const res = await http.get<{ items: unknown[] }>('/audit/', { limit: 10 })
recentAudit.value = normalizeAuditList(res.items || []).slice(0, 10)
} catch {
recentAudit.value = []
snackbar('加载审计记录失败', 'error')
}
}
async function loadSummary() {
try {
// Load a larger set to compute fleet-wide stats
const res = await http.get<{ items: ServerApiItem[]; total: number }>('/servers/', { per_page: 200 })
const allServers = res.items || []
const fleetTotal = res.total || allServers.length
if (fleetTotal === 0) return
// Agent coverage
const withAgent = allServers.filter(s => s.agent_version).length
const agentRate = Math.round((withAgent / fleetTotal) * 100)
summaryItems.value[1].progress = agentRate
summaryItems.value[1].value = `${agentRate}%`
// CPU / Memory averages (from servers with system_info)
const withCpu = allServers.filter(s => s.system_info?.cpu_usage != null)
const withMem = allServers.filter(s => s.system_info?.mem_usage != null)
if (withCpu.length > 0) {
const cpuAvg = Math.round(withCpu.reduce((sum, s) => sum + (s.system_info!.cpu_usage || 0), 0) / withCpu.length)
summaryItems.value[2].progress = cpuAvg
summaryItems.value[2].value = `${cpuAvg}%`
}
if (withMem.length > 0) {
const memAvg = Math.round(withMem.reduce((sum, s) => sum + (s.system_info!.mem_usage || 0), 0) / withMem.length)
summaryItems.value[3].progress = memAvg
summaryItems.value[3].value = `${memAvg}%`
}
} catch {
// Summary stats are non-critical, leave at previous values
}
}
function openTerminal(item: ServerApiItem) {
router.push({ path: '/terminal', query: { server_id: String(item.id) } })
}
function openFiles(item: ServerApiItem) {
router.push({ path: '/files', query: { server_id: String(item.id) } })
}
async function refreshDashboard(silent = false) {
await Promise.all([
loadStats(silent),
loadServers(silent),
loadAlerts(),
loadSummary(),
loadRecentAudit(),
])
if (!silent) {
http.post('/settings/bing-wallpapers/sync').catch(() => {})
}
}
// ── Init ──
// NOTE: WebSocket is managed by App.vue (connected when auth.isLoggedIn=true),
// so we reuse that global singleton instead of creating a second connection.
const ws = useWebSocket()
watch(ws.alerts, () => {
void loadStats(true)
void loadAlerts()
void loadServers(true)
})
usePageActivateRefresh((silent) => refreshDashboard(silent))
usePageAutoRefresh(() => loadServers(true), 30_000)
interface AlertItem {
title: string
subtitle: string
value: string
color: string
icon: string
}
</script>