Files
Nexus/frontend/src/pages/DashboardPage.vue
T
Nexus Agent fe8b24ca0b fix(notify): 资源恢复 Telegram 联动 CPU/内存/磁盘开关
关闭分项告警后不再推送对应恢复消息;仪表盘移除服务器列表并更新设置页说明。

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

318 lines
10 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" />
<!-- ── Bottom Row: Alerts + Summary ── -->
<v-row class="mt-5">
<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%;
}
</style>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import { useWebSocket } from '@/composables/useWebSocket'
import { usePageActivateRefresh } from '@/composables/usePageActivateRefresh'
import { CACHE_KEYS, cachedFetch } from '@/composables/useCachedQuery'
import { 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'
defineOptions({ name: 'DashboardPage' })
const snackbar = useSnackbar()
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' },
])
// ── 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)
categories.value = s.categories || {}
statsTotal.value = s.total
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 {
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
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}%`
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
}
}
async function refreshDashboard(silent = false) {
await Promise.all([
loadStats(silent),
loadAlerts(),
loadSummary(),
loadRecentAudit(),
])
if (!silent) {
http.post('/settings/bing-wallpapers/sync').catch(() => {})
}
}
const ws = useWebSocket()
watch(ws.alerts, () => {
void loadStats(true)
void loadAlerts()
})
usePageActivateRefresh((silent) => refreshDashboard(silent))
interface AlertItem {
title: string
subtitle: string
value: string
color: string
icon: string
}
</script>