Files
planet/frontend/src/admin/pages/Dashboard.tsx
T
rayd1o 30b44ec00d
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.84.2
2026-12-05 01:56:03 +08:00

2375 lines
90 KiB
TypeScript

import axios from 'axios'
import type { ColumnDef } from '@tanstack/react-table'
import {
AlertTriangle,
BarChart3,
Check,
CheckCheck,
Database,
ExternalLink,
Globe2,
KeyRound,
Layers,
PlugZap,
Power,
RefreshCw,
RotateCw,
Signal,
SignalZero,
X,
} from 'lucide-react'
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type ReactNode,
} from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useNavigate } from 'react-router-dom'
import { useWebSocket } from '../../hooks/useWebSocket'
import { describeApiError, describeApiValue } from '../../i18n/api-errors'
import { translateLegacyAdminText } from '../../i18n/LegacyI18nBridge'
import { normalizeLocale } from '../../i18n/locale'
import { useAuthStore } from '../../stores/auth'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN, parseBackendDate } from '../../utils/datetime'
import { DataTable } from '../components/data-table/DataTable'
import { AdminLayout } from '../components/layout/AdminLayout'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { Dialog } from '../components/ui/dialog'
import { Input } from '../components/ui/input'
import { Select } from '../components/ui/select'
import { TableActionButton } from '../components/ui/table-action-button'
import { useToast } from '../components/ui/toast'
import { StatusText } from '../patterns/patterns'
import { formatNumber } from '../utils'
import {
DashboardHorizontalBarChart,
DashboardLayerDonutChart,
DashboardTaskTrendChart,
} from './dashboardCharts'
import {
buildLayerShareItems,
buildTaskTrendBuckets,
computeDatasourceHealth,
extractArrayPayload,
formatDataTypeLabel,
formatDurationShort,
formatRelativeAge,
normalizeCollectorRows,
type AssetDistributionItem,
type CollectedSummaryResponse,
type CollectorHealth,
type ComputeCountsSummary,
type DashboardAlertRow,
type DashboardCollectorRow,
type DashboardDatasourceRow,
type DashboardTaskRow,
type DatasourceHealth,
type LayerSummaryItem,
} from './dashboardHelpers'
type CardId = 'data_assets' | 'runtime_insights' | 'datasources' | 'system_alerts'
type AssetDim = 'source' | 'type' | 'layer'
type RuntimeTab = 'tasks' | 'layers'
type TaskWindow = '24h' | '7d'
type OpsTab = 'datasources' | 'collectors'
type BadgeTone = 'default' | 'blue' | 'green' | 'amber' | 'red' | 'purple' | 'cyan' | 'slate'
type BarSegmentTone = 'green' | 'blue' | 'amber' | 'red' | 'slate'
type DotTone = 'green' | 'blue' | 'amber' | 'red' | 'muted'
interface Stats {
total_datasources: number
active_datasources: number
tasks_today: number
success_rate: number
last_updated: string
alerts: {
critical: number
warning: number
info: number
}
}
interface RealtimeSourceItem {
id: string
name: string
connected?: boolean
last_1h?: number
}
interface AIProviderStatus {
provider?: string
status?: string
model?: string
}
interface RestartTask {
task_id: string
action: string
status: string
stage: string
message: string
}
interface RestartTaskLogs {
task_id: string
lines: string[]
}
interface CardDescriptor {
id: CardId
title: string
icon: ReactNode
dockKpi: string
dockSub: string
}
type RestartAction =
| 'restart-backend'
| 'restart-frontend'
| 'restart-ai-provider'
| 'restart-database'
| 'restart-system'
type RestartStage = 'confirming' | 'waiting_for_shutdown' | 'waiting_for_recovery' | 'recovered' | 'failed' | 'timeout'
const RESTART_ACTION_OPTIONS: Array<{ value: RestartAction; label: string; description: string; command: string }> = [
{ value: 'restart-backend', label: '重启后端', description: '重启后端服务,页面会短暂断开后自动恢复。', command: './planet.sh restart -b' },
{ value: 'restart-frontend', label: '重启前端', description: '重启前端服务,恢复后将自动刷新页面。', command: './planet.sh restart -f' },
{ value: 'restart-ai-provider', label: '重启 AI 服务', description: '重启 AI 适配服务。', command: './planet.sh restart -a' },
{ value: 'restart-database', label: '重启数据库', description: '重启 PostgreSQL 和 Redis 容器。', command: './planet.sh restart -d' },
{ value: 'restart-system', label: '完全重启', description: '重启前后端及相关服务,恢复后将自动刷新页面。', command: './planet.sh restart' },
]
const FLIP_DURATION_MS = 680
const FLIP_EASING = 'cubic-bezier(0.22, 1, 0.36, 1)'
let cachedDashboardStats: Stats | null = null
function getRestartConfirmMessage(action: RestartAction): string {
return RESTART_ACTION_OPTIONS.find((item) => item.value === action)?.description || '将重启服务。'
}
function datasourceHealthTone(health: DatasourceHealth): 'success' | 'running' | 'warning' | 'danger' | 'neutral' {
if (health === 'healthy') return 'success'
if (health === 'running') return 'running'
if (health === 'stale') return 'warning'
if (health === 'error') return 'danger'
return 'neutral'
}
function datasourceDotTone(health: DatasourceHealth): DotTone {
if (health === 'healthy') return 'green'
if (health === 'running') return 'blue'
if (health === 'stale') return 'amber'
if (health === 'error') return 'red'
return 'muted'
}
function datasourceHealthLabel(health: DatasourceHealth): string {
if (health === 'healthy') return '健康'
if (health === 'running') return '采集中'
if (health === 'stale') return '偏旧'
if (health === 'error') return '失败'
return '已停用'
}
function collectorHealthTone(health: CollectorHealth): 'success' | 'warning' | 'danger' | 'neutral' {
if (health === 'connected') return 'success'
if (health === 'missing_credentials') return 'danger'
if (health === 'unverified') return 'warning'
return 'neutral'
}
function collectorDotTone(health: CollectorHealth): DotTone {
if (health === 'connected') return 'green'
if (health === 'missing_credentials') return 'red'
if (health === 'unverified') return 'amber'
return 'muted'
}
function collectorHealthLabel(health: CollectorHealth): string {
if (health === 'connected') return '已连通'
if (health === 'missing_credentials') return '缺凭证'
if (health === 'unverified') return '未验证'
return '已停用'
}
function taskStatusTone(status: string): 'success' | 'running' | 'danger' | 'warning' | 'neutral' {
const s = status.toLowerCase()
if (s === 'success' || s === 'completed') return 'success'
if (s === 'running' || s === 'queued' || s === 'pending') return 'running'
if (s === 'failed' || s === 'error') return 'danger'
if (s === 'cancelled') return 'warning'
return 'neutral'
}
function taskStatusLabel(status: string): string {
const s = status.toLowerCase()
if (s === 'success' || s === 'completed') return '成功'
if (s === 'running' || s === 'queued' || s === 'pending') return '运行中'
if (s === 'failed' || s === 'error') return '失败'
if (s === 'cancelled') return '已取消'
return status || '-'
}
function alertSeverityBadge(severity: string): { tone: BadgeTone; dotTone: DotTone; label: string } {
const s = severity.toLowerCase()
if (s === 'critical') return { tone: 'red', dotTone: 'red', label: '严重' }
if (s === 'warning') return { tone: 'amber', dotTone: 'amber', label: '警告' }
return { tone: 'blue', dotTone: 'blue', label: '提示' }
}
function DashboardContent() {
const { token, clearAuth, user } = useAuthStore()
const { toast } = useToast()
const navigate = useNavigate()
const { i18n } = useTranslation()
const locale = normalizeLocale(i18n.language)
const isEnglish = locale === 'en-US'
const [stats, setStats] = useState<Stats | null>(cachedDashboardStats)
const [loading, setLoading] = useState(cachedDashboardStats === null)
const [refreshing, setRefreshing] = useState(false)
const [error, setError] = useState<string | null>(null)
const [datasources, setDatasources] = useState<DashboardDatasourceRow[]>([])
const [collectors, setCollectors] = useState<DashboardCollectorRow[]>([])
const [tasks, setTasks] = useState<DashboardTaskRow[]>([])
const [alerts, setAlerts] = useState<DashboardAlertRow[]>([])
const [realtimeSources, setRealtimeSources] = useState<RealtimeSourceItem[]>([])
const [aiStatus, setAiStatus] = useState<AIProviderStatus | null>(null)
const [collectedSummary, setCollectedSummary] = useState<CollectedSummaryResponse | null>(null)
const [layers, setLayers] = useState<LayerSummaryItem[]>([])
const [computeCounts, setComputeCounts] = useState<ComputeCountsSummary>({ total: 0, byStatus: {} })
const [focusedCard, setFocusedCard] = useState<CardId | null>(null)
const [assetDim, setAssetDim] = useState<AssetDim>('source')
const [runtimeTab, setRuntimeTab] = useState<RuntimeTab>('tasks')
const [taskWindow, setTaskWindow] = useState<TaskWindow>('24h')
const [opsTab, setOpsTab] = useState<OpsTab>('datasources')
const [dsFilter, setDsFilter] = useState<'all' | 'issue' | 'running' | 'disabled'>('all')
const [dsSearch, setDsSearch] = useState('')
const [colFilter, setColFilter] = useState<'all' | 'missing_credentials' | 'configured' | 'no_credentials'>('all')
const [colSearch, setColSearch] = useState('')
const [alertFilter, setAlertFilter] = useState<'all' | 'critical' | 'warning' | 'info'>('all')
const [rowBusy, setRowBusy] = useState<Record<string, boolean>>({})
const [batchTesting, setBatchTesting] = useState(false)
const [restartModalOpen, setRestartModalOpen] = useState(false)
const [restartAction, setRestartAction] = useState<RestartAction>('restart-backend')
const [restartSubmitting, setRestartSubmitting] = useState(false)
const [restartTaskId, setRestartTaskId] = useState<string | null>(null)
const [restartLogs, setRestartLogs] = useState<string[]>([])
const [restartMessage, setRestartMessage] = useState<string>(() => getRestartConfirmMessage('restart-backend'))
const [restartStage, setRestartStage] = useState<RestartStage>('confirming')
const [restartStartedAt, setRestartStartedAt] = useState<number | null>(null)
const stageRef = useRef<HTMLDivElement | null>(null)
const beforeRectsRef = useRef<Map<string, DOMRect>>(new Map())
const morphAnimatingRef = useRef(false)
const cleanupTimerRef = useRef<number | null>(null)
const isSuperAdmin = user?.role === 'superadmin'
const selectedRestartAction =
RESTART_ACTION_OPTIONS.find((item) => item.value === restartAction) || RESTART_ACTION_OPTIONS[0]
const fetchAll = useCallback(async (isInitial = false) => {
try {
if (isInitial && cachedDashboardStats === null) setLoading(true)
else setRefreshing(true)
const authHeaders = token ? { Authorization: `Bearer ${token}` } : undefined
const results = await Promise.allSettled([
axios.get('/api/v1/dashboard/stats'),
axios.get('/api/v1/datasources'),
axios.get('/api/v1/datasources/configs/all', { headers: authHeaders }),
axios.get('/api/v1/datasources/configs', { headers: authHeaders }),
axios.get('/api/v1/tasks?page=1&page_size=100'),
axios.get('/api/v1/alerts?status=active'),
axios.get('/api/v1/realtime-sources'),
axios.get('/api/v1/ai/provider/status'),
axios.get('/api/v1/collected/summary'),
axios.get('/api/v1/data-ledger/layers'),
axios.get('/api/v1/data-ledger/compute-centers?page=1&page_size=1'),
])
const unauthorized = results.some(
(res) => res.status === 'rejected' && axios.isAxiosError(res.reason) && res.reason.response?.status === 401,
)
if (unauthorized) {
clearAuth()
return
}
const [
statsRes,
dsRes,
builtinRes,
customRes,
tasksRes,
alertsRes,
rtRes,
aiRes,
summaryRes,
layersRes,
computeRes,
] = results
if (statsRes.status === 'fulfilled' && statsRes.value.data) {
cachedDashboardStats = statsRes.value.data
setStats(statsRes.value.data)
setError(null)
} else if (statsRes.status === 'rejected') {
setError('获取数据失败')
}
if (dsRes.status === 'fulfilled') {
const rawList = extractArrayPayload<Record<string, unknown>>(dsRes.value.data)
setDatasources(
rawList.map((row) => ({
id: Number(row.id || 0),
source: String(row.source || row.source_id || ''),
name: String(row.name || row.source || '-'),
module: String(row.module || '-'),
product: typeof row.product === 'string' ? row.product : undefined,
frequency: typeof row.frequency === 'string' ? row.frequency : undefined,
frequency_minutes: typeof row.frequency_minutes === 'number' ? row.frequency_minutes : undefined,
is_active: row.is_active !== false,
is_running: Boolean(row.is_running || row.is_task_active),
last_status: typeof row.last_status === 'string' ? row.last_status : null,
last_run_at: typeof row.last_run_at === 'string' ? row.last_run_at : null,
collected_records: typeof row.collected_records === 'number' ? row.collected_records : undefined,
records_processed: typeof row.records_processed === 'number' ? row.records_processed : null,
error_message: typeof row.error_message === 'string' ? row.error_message : null,
health: computeDatasourceHealth({
is_active: row.is_active !== false,
is_running: Boolean(row.is_running || row.is_task_active),
last_status: typeof row.last_status === 'string' ? row.last_status : null,
last_run_at: typeof row.last_run_at === 'string' ? row.last_run_at : null,
frequency_minutes: typeof row.frequency_minutes === 'number' ? row.frequency_minutes : undefined,
}),
})),
)
}
const builtinPayload = builtinRes.status === 'fulfilled' ? builtinRes.value.data : []
const customPayload = customRes.status === 'fulfilled' ? customRes.value.data : []
setCollectors(normalizeCollectorRows(builtinPayload, customPayload))
if (tasksRes.status === 'fulfilled') {
setTasks(extractArrayPayload<DashboardTaskRow>(tasksRes.value.data))
}
if (alertsRes.status === 'fulfilled') {
setAlerts(extractArrayPayload<DashboardAlertRow>(alertsRes.value.data))
}
if (rtRes.status === 'fulfilled') {
setRealtimeSources(extractArrayPayload<RealtimeSourceItem>(rtRes.value.data))
}
if (aiRes.status === 'fulfilled' && aiRes.value.data) {
setAiStatus(aiRes.value.data)
}
if (summaryRes.status === 'fulfilled' && summaryRes.value.data) {
setCollectedSummary(summaryRes.value.data as CollectedSummaryResponse)
}
if (layersRes.status === 'fulfilled' && layersRes.value.data) {
const rawLayers = Array.isArray(layersRes.value.data?.layers)
? (layersRes.value.data.layers as LayerSummaryItem[])
: []
setLayers(rawLayers)
}
if (computeRes.status === 'fulfilled' && computeRes.value.data) {
const payload = computeRes.value.data as {
total?: number
counts?: { by_status?: Record<string, number> }
}
setComputeCounts({
total: Number(payload.total || 0),
byStatus: payload.counts?.by_status || {},
})
}
} catch (err) {
setError('获取数据失败')
console.error(err)
} finally {
setLoading(false)
setRefreshing(false)
}
}, [clearAuth, token])
useEffect(() => {
void fetchAll(true)
}, [fetchAll])
const handleWsMessage = useCallback(
(message: { type?: string; channel?: string; payload?: Record<string, unknown> }) => {
if (message.type === 'data_frame' && message.channel === 'dashboard' && message.payload?.stats) {
const nextStats = message.payload.stats as Stats
cachedDashboardStats = nextStats
setStats(nextStats)
}
},
[],
)
const { connected, connecting } = useWebSocket({
autoConnect: true,
autoSubscribe: ['dashboard'],
onMessage: handleWsMessage,
})
const switchFocus = useCallback((nextFocus: CardId | null) => {
if (stageRef.current) {
const rects = new Map<string, DOMRect>()
stageRef.current.querySelectorAll<HTMLElement>('.an-dash-card[data-card-id]').forEach((el) => {
const id = el.dataset.cardId
if (id) rects.set(id, el.getBoundingClientRect())
})
beforeRectsRef.current = rects
morphAnimatingRef.current = true
}
setFocusedCard(nextFocus)
}, [])
useLayoutEffect(() => {
if (!morphAnimatingRef.current || !stageRef.current) return
morphAnimatingRef.current = false
const beforeRects = beforeRectsRef.current
beforeRectsRef.current = new Map()
if (!beforeRects.size) return
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return
const cardEls = Array.from(stageRef.current.querySelectorAll<HTMLElement>('.an-dash-card[data-card-id]'))
cardEls.forEach((el) => {
const id = el.dataset.cardId || ''
const first = beforeRects.get(id)
if (!first) return
const last = el.getBoundingClientRect()
if (!last.width || !last.height) return
const dx = first.left - last.left
const dy = first.top - last.top
const sx = first.width / last.width
const sy = first.height / last.height
if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5 && Math.abs(sx - 1) < 0.01 && Math.abs(sy - 1) < 0.01) {
return
}
el.style.zIndex = el.classList.contains('is-hero') ? '8' : '3'
el.style.transformOrigin = 'top left'
el.style.transition = 'none'
el.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`
})
void stageRef.current.offsetHeight
const raf = window.requestAnimationFrame(() => {
cardEls.forEach((el) => {
el.style.transition = `transform ${FLIP_DURATION_MS}ms ${FLIP_EASING}`
el.style.transform = 'translate3d(0, 0, 0) scale(1, 1)'
})
if (cleanupTimerRef.current !== null) window.clearTimeout(cleanupTimerRef.current)
cleanupTimerRef.current = window.setTimeout(() => {
cardEls.forEach((el) => {
el.style.transition = ''
el.style.transform = ''
el.style.transformOrigin = ''
el.style.zIndex = ''
})
}, FLIP_DURATION_MS + 60)
})
return () => window.cancelAnimationFrame(raf)
}, [focusedCard])
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key === 'Escape' && focusedCard !== null && !restartModalOpen) {
switchFocus(null)
}
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [focusedCard, restartModalOpen, switchFocus])
const openRestartModal = () => {
setRestartAction('restart-backend')
setRestartTaskId(null)
setRestartLogs([])
setRestartSubmitting(false)
setRestartStartedAt(null)
setRestartStage('confirming')
setRestartMessage(getRestartConfirmMessage('restart-backend'))
setRestartModalOpen(true)
}
const handleRestartAction = async () => {
setRestartSubmitting(true)
setRestartLogs(['正在准备重启任务...'])
try {
const res = await axios.post<RestartTask>('/api/v1/system/restart-tasks', { action: restartAction })
setRestartTaskId(res.data.task_id)
setRestartStartedAt(Date.now())
setRestartStage('waiting_for_shutdown')
setRestartMessage(describeApiValue(res.data.message, '已发送重启指令,正在等待服务进入重启流程。'))
setRestartLogs((current) => [...current, `任务已创建: ${res.data.task_id}`])
} catch (restartError: unknown) {
const restartFailureMessage = describeApiError(restartError, '提交重启任务失败')
setRestartStage('failed')
setRestartMessage(restartFailureMessage)
setRestartLogs((current) => [...current, '提交重启任务失败'])
toast({ tone: 'error', title: '提交失败', description: restartFailureMessage })
} finally {
setRestartSubmitting(false)
}
}
useEffect(() => {
if (!restartModalOpen || restartStage !== 'confirming') return
setRestartMessage(getRestartConfirmMessage(restartAction))
}, [restartAction, restartModalOpen, restartStage])
useEffect(() => {
if (!restartModalOpen || !restartTaskId || restartStartedAt === null) return
let cancelled = false
let sawUnhealthy = false
let healthyStreak = 0
let frontendHealthyStreak = 0
let pollTimer: number | null = null
const appendLog = (line: string) => {
setRestartLogs((current) => (current[current.length - 1] === line ? current : [...current, line].slice(-8)))
}
const poll = async () => {
if (cancelled) return
const elapsed = Date.now() - restartStartedAt
if (elapsed > 90_000) {
setRestartStage('timeout')
setRestartMessage('恢复超时,请手动检查服务状态。')
appendLog('恢复超时,请手动检查服务状态')
return
}
try {
const taskRes = await axios.get<RestartTask>(`/api/v1/system/restart-tasks/${restartTaskId}`, { timeout: 1500 })
const task = taskRes.data
if (!cancelled && task?.message) setRestartMessage(describeApiValue(task.message, '重启任务正在执行'))
if (!cancelled && restartAction !== 'restart-system') {
const logsRes = await axios.get<RestartTaskLogs>(`/api/v1/system/restart-tasks/${restartTaskId}/logs`, { timeout: 1500 })
if (logsRes.data.lines.length > 0) setRestartLogs(logsRes.data.lines.slice(-8))
}
if (!cancelled && task?.stage === 'healthy') {
setRestartStage('recovered')
setRestartMessage('服务已恢复,正在刷新页面。')
window.setTimeout(() => window.location.reload(), 600)
return
}
if (!cancelled && (task.status === 'failed' || task.status === 'timeout')) {
setRestartStage(task.status === 'timeout' ? 'timeout' : 'failed')
setRestartMessage(describeApiValue(task.message, '重启任务失败'))
return
}
} catch {
// 服务重启过程中短暂失败是预期行为,继续健康检查。
}
if (restartAction === 'restart-system' || restartAction === 'restart-frontend') {
try {
const rootRes = await fetch(`/?restart_probe=${Date.now()}`, { cache: 'no-store' })
if (rootRes.ok) {
frontendHealthyStreak += 1
if (sawUnhealthy && frontendHealthyStreak >= 2) {
setRestartStage('recovered')
setRestartMessage('前端已恢复,正在刷新页面。')
window.setTimeout(() => window.location.reload(), 600)
return
}
} else {
sawUnhealthy = true
frontendHealthyStreak = 0
setRestartStage('waiting_for_recovery')
setRestartMessage('前端正在重启,正在等待页面入口恢复访问。')
}
} catch {
sawUnhealthy = true
frontendHealthyStreak = 0
setRestartStage('waiting_for_recovery')
setRestartMessage('前端正在重启,正在等待页面入口恢复访问。')
}
pollTimer = window.setTimeout(poll, 1500)
return
}
try {
const healthRes = await fetch('/health', { cache: 'no-store' })
if (healthRes.ok) {
healthyStreak += 1
if (sawUnhealthy && healthyStreak >= 2) {
setRestartStage('recovered')
setRestartMessage('服务已恢复,正在刷新页面。')
window.setTimeout(() => window.location.reload(), 600)
return
}
} else {
sawUnhealthy = true
healthyStreak = 0
setRestartStage('waiting_for_recovery')
setRestartMessage('后端已停止响应,正在等待服务恢复。')
}
} catch {
sawUnhealthy = true
healthyStreak = 0
setRestartStage('waiting_for_recovery')
setRestartMessage('后端已停止响应,正在等待服务恢复。')
}
pollTimer = window.setTimeout(poll, 1500)
}
pollTimer = window.setTimeout(poll, 1200)
return () => {
cancelled = true
if (pollTimer !== null) window.clearTimeout(pollTimer)
}
}, [restartAction, restartModalOpen, restartStartedAt, restartTaskId])
const triggerDatasource = useCallback(
async (datasourceId: number, label: string) => {
const busyKey = `ds:${datasourceId}`
setRowBusy((prev) => ({ ...prev, [busyKey]: true }))
try {
await axios.post(`/api/v1/datasources/${datasourceId}/trigger`)
toast({ tone: 'success', title: '已提交采集任务', description: label })
void fetchAll()
} catch (err) {
toast({ tone: 'error', title: '操作失败', description: describeApiError(err, label) })
} finally {
setRowBusy((prev) => ({ ...prev, [busyKey]: false }))
}
},
[fetchAll, toast],
)
const testCollector = useCallback(
async (row: DashboardCollectorRow, silent = false) => {
const busyKey = row.key
setRowBusy((prev) => ({ ...prev, [busyKey]: true }))
try {
let ok = false
let msg = ''
if (row.kind === 'builtin') {
const res = await axios.post('/api/v1/datasources/configs/builtin/connect', {
name: row.name,
endpoint: row.endpoint,
auth_type: row.authType || 'none',
headers: row.headers || {},
config: row.config || {},
})
ok = Boolean(res.data?.connected || res.data?.success)
msg = String(res.data?.message || res.data?.error || '')
} else if (row.configId) {
const res = await axios.post(`/api/v1/datasources/configs/${row.configId}/test`)
ok = Boolean(res.data?.success ?? res.data?.connected)
msg = String(res.data?.message || res.data?.error || '')
}
setCollectors((prev) =>
prev.map((item) =>
item.key === row.key
? {
...item,
health: ok
? 'connected'
: row.requiresCredentials && !row.hasCredentials
? 'missing_credentials'
: 'unverified',
}
: item,
),
)
if (!silent) {
toast({ tone: ok ? 'success' : 'error', title: '连通测试完成', description: msg || row.displayName })
}
} catch (err) {
if (!silent) {
toast({ tone: 'error', title: '连接失败', description: describeApiError(err, row.displayName) })
}
} finally {
setRowBusy((prev) => ({ ...prev, [busyKey]: false }))
}
},
[toast],
)
const testAllCollectors = useCallback(async () => {
const targets = collectors.filter((item) => item.isActive && (!item.requiresCredentials || item.hasCredentials))
if (!targets.length) return
setBatchTesting(true)
try {
await Promise.allSettled(targets.map((item) => testCollector(item, true)))
toast({ tone: 'success', title: '连通测试完成', description: `${targets.length}` })
void fetchAll()
} finally {
setBatchTesting(false)
}
}, [collectors, fetchAll, testCollector, toast])
const ackAlert = useCallback(
async (alertId: number) => {
const busyKey = `alert:${alertId}`
setRowBusy((prev) => ({ ...prev, [busyKey]: true }))
try {
await axios.post(`/api/v1/alerts/${alertId}/acknowledge`)
toast({ tone: 'success', title: '已确认' })
void fetchAll()
} catch (err) {
toast({ tone: 'error', title: '操作失败', description: describeApiError(err, '操作失败') })
} finally {
setRowBusy((prev) => ({ ...prev, [busyKey]: false }))
}
},
[fetchAll, toast],
)
const resolveAlert = useCallback(
async (alertId: number) => {
const busyKey = `alert:${alertId}`
setRowBusy((prev) => ({ ...prev, [busyKey]: true }))
try {
await axios.post(`/api/v1/alerts/${alertId}/resolve`, { resolution: 'Resolved from dashboard' })
toast({ tone: 'success', title: '已解决' })
void fetchAll()
} catch (err) {
toast({ tone: 'error', title: '操作失败', description: describeApiError(err, '操作失败') })
} finally {
setRowBusy((prev) => ({ ...prev, [busyKey]: false }))
}
},
[fetchAll, toast],
)
const dsCounts = useMemo(() => {
const issue = datasources.filter((item) => item.health === 'error' || item.health === 'stale').length
const running = datasources.filter((item) => item.health === 'running').length
const disabled = datasources.filter((item) => item.health === 'disabled').length
const healthy = datasources.filter((item) => item.health === 'healthy').length
const enabled = datasources.length - disabled
return { all: datasources.length, enabled, healthy, running, issue, disabled }
}, [datasources])
const colCounts = useMemo(() => {
const missing = collectors.filter((item) => item.requiresCredentials && !item.hasCredentials).length
const configured = collectors.filter((item) => item.requiresCredentials && item.hasCredentials).length
const noCred = collectors.filter((item) => !item.requiresCredentials).length
const connectedCount = collectors.filter((item) => item.health === 'connected').length
return { all: collectors.length, missing, configured, noCred, connectedCount }
}, [collectors])
const alertCounts = useMemo(() => {
const active = alerts.filter((item) => String(item.status || '').toLowerCase() !== 'resolved')
const critical = active.filter((item) => item.severity === 'critical').length
const warning = active.filter((item) => item.severity === 'warning').length
const info = active.filter((item) => item.severity === 'info').length
return { all: active.length, critical, warning, info, rows: active }
}, [alerts])
const assetItemsBySource = useMemo<AssetDistributionItem[]>(() => {
const raw = collectedSummary?.source_totals || []
return [...raw]
.filter((item) => Number(item.count) > 0)
.sort((a, b) => b.count - a.count)
.map((item) => ({
key: item.source,
name: translateLegacyAdminText(item.source_name || item.source, locale),
count: Number(item.count || 0),
filterQuery: `layer=raw&source=${encodeURIComponent(item.source)}`,
}))
}, [collectedSummary, locale])
const assetItemsByType = useMemo<AssetDistributionItem[]>(() => {
const raw = collectedSummary?.type_totals || []
return [...raw]
.filter((item) => Number(item.count) > 0)
.sort((a, b) => b.count - a.count)
.map((item) => ({
key: item.data_type,
name: formatDataTypeLabel(item.data_type, isEnglish),
count: Number(item.count || 0),
filterQuery: `layer=raw&type=${encodeURIComponent(item.data_type)}`,
}))
}, [collectedSummary, isEnglish])
const assetItemsByLayer = useMemo<AssetDistributionItem[]>(() => {
return [...layers]
.filter((item) => Number(item.count) > 0)
.sort((a, b) => b.count - a.count)
.map((item) => ({
key: item.id,
name: translateLegacyAdminText(item.name || item.id, locale),
count: Number(item.count || 0),
filterQuery: `layer=${encodeURIComponent(item.id)}`,
}))
}, [layers, locale])
const activeAssetItems = useMemo(() => {
if (assetDim === 'source') return assetItemsBySource
if (assetDim === 'type') return assetItemsByType
return assetItemsByLayer
}, [assetDim, assetItemsByLayer, assetItemsBySource, assetItemsByType])
const overallCollectedRecords = useMemo(() => {
if (collectedSummary && typeof collectedSummary.overall_total_records === 'number') {
return collectedSummary.overall_total_records
}
return assetItemsBySource.reduce((sum, item) => sum + item.count, 0)
}, [assetItemsBySource, collectedSummary])
const layerShares = useMemo(
() =>
buildLayerShareItems(
layers.map((item) => ({
...item,
name: translateLegacyAdminText(item.name || item.id, locale),
})),
6,
isEnglish ? 'Other Layers' : '其他图层',
),
[isEnglish, layers, locale],
)
const totalLayerRecords = useMemo(
() => layers.reduce((sum, item) => sum + Number(item.count || 0), 0),
[layers],
)
const taskTrendBuckets = useMemo(
() => buildTaskTrendBuckets(tasks, taskWindow),
[taskWindow, tasks],
)
const windowTaskSummary = useMemo(() => {
const okSum = taskTrendBuckets.reduce((sum, item) => sum + item.ok, 0)
const failSum = taskTrendBuckets.reduce((sum, item) => sum + item.fail, 0)
const total = okSum + failSum
const rate = total > 0 ? ((okSum / total) * 100).toFixed(1) : '0.0'
return { total, okSum, failSum, rate }
}, [taskTrendBuckets])
const orderedDatasources = useMemo(() => {
const priority: Record<DatasourceHealth, number> = {
error: 0,
stale: 1,
running: 2,
healthy: 3,
disabled: 4,
}
return [...datasources].sort((a, b) => priority[a.health] - priority[b.health])
}, [datasources])
const orderedCollectors = useMemo(() => {
const priority: Record<CollectorHealth, number> = {
missing_credentials: 0,
unverified: 1,
connected: 2,
disabled: 3,
}
return [...collectors].sort((a, b) => priority[a.health] - priority[b.health])
}, [collectors])
const systemChannels = useMemo(() => {
return [
{
key: 'ws',
name: 'WebSocket',
detail: isEnglish ? 'Dashboard channel' : '仪表盘频道',
status: connected ? (isEnglish ? 'Connected' : '实时连接') : connecting ? (isEnglish ? 'Connecting' : '正在连接') : isEnglish ? 'Offline' : '离线',
tone: (connected ? 'green' : connecting ? 'blue' : 'muted') as DotTone,
},
{
key: 'ai',
name: aiStatus?.model || aiStatus?.provider || 'AI',
detail: aiStatus?.provider ? `${aiStatus.provider}` : isEnglish ? 'AI Provider' : '模型通道',
status: aiStatus?.status === 'ok' ? (isEnglish ? 'Healthy' : '正常') : isEnglish ? 'Unconfigured' : '未配置',
tone: (aiStatus?.status === 'ok' ? 'green' : 'amber') as DotTone,
},
...realtimeSources.map((src, idx) => ({
key: `rt-${src.id || src.name}-${idx}`,
name: translateLegacyAdminText(src.name, locale),
detail:
typeof src.last_1h === 'number'
? isEnglish
? `${formatNumber(src.last_1h)} in 1h`
: `近1小时 ${formatNumber(src.last_1h)} 条`
: isEnglish
? 'Realtime stream'
: '实时流',
status: src.connected ? (isEnglish ? 'Online' : '在线') : isEnglish ? 'Offline' : '离线',
tone: (src.connected ? 'green' : 'muted') as DotTone,
})),
]
}, [aiStatus, connected, connecting, isEnglish, locale, realtimeSources])
const cardDescriptors = useMemo<CardDescriptor[]>(() => {
const activeDsCount = datasources.length ? dsCounts.enabled : (stats?.active_datasources ?? 0)
const totalDsCount = datasources.length || (stats?.total_datasources ?? 0)
const tasksToday = stats?.tasks_today ?? tasks.length
const successRate = stats?.success_rate ?? Number(windowTaskSummary.rate)
const criticalTotal = stats?.alerts?.critical ?? alertCounts.critical
const warningTotal = stats?.alerts?.warning ?? alertCounts.warning
const infoTotal = stats?.alerts?.info ?? alertCounts.info
const totalAlertCount = Math.max(alertCounts.all, criticalTotal + warningTotal + infoTotal)
return [
{
id: 'data_assets',
title: '数据资产',
icon: <Layers size={15} />,
dockKpi: formatNumber(overallCollectedRecords),
dockSub: isEnglish
? `${assetItemsBySource.length} sources · ${layers.length} layers`
: `${assetItemsBySource.length} 源 · ${layers.length} 图层`,
},
{
id: 'runtime_insights',
title: '运行态势',
icon: <BarChart3 size={15} />,
dockKpi: `${successRate}%`,
dockSub: isEnglish ? `${formatNumber(tasksToday)} today` : `今日 ${formatNumber(tasksToday)} 任务`,
},
{
id: 'datasources',
title: '数据源与采集器',
icon: <Database size={15} />,
dockKpi: `${formatNumber(activeDsCount)} / ${formatNumber(totalDsCount)}`,
dockSub: isEnglish
? `${dsCounts.issue} issues · ${colCounts.missing} missing`
: `${dsCounts.issue} 需关注 · ${colCounts.missing} 缺凭证`,
},
{
id: 'system_alerts',
title: '告警与系统通道',
icon: <AlertTriangle size={15} />,
dockKpi: isEnglish ? `${formatNumber(totalAlertCount)} alerts` : `${formatNumber(totalAlertCount)} 告警`,
dockSub: `${isEnglish ? (connected ? 'WS Live' : 'WS Offline') : connected ? 'WS 在线' : 'WS 离线'} · ${aiStatus?.provider || 'AI'}`,
},
]
}, [
aiStatus?.provider,
alertCounts.all,
alertCounts.critical,
alertCounts.info,
alertCounts.warning,
assetItemsBySource.length,
colCounts.missing,
connected,
datasources.length,
dsCounts.enabled,
dsCounts.issue,
isEnglish,
layers.length,
overallCollectedRecords,
stats?.active_datasources,
stats?.alerts?.critical,
stats?.alerts?.info,
stats?.alerts?.warning,
stats?.success_rate,
stats?.tasks_today,
stats?.total_datasources,
tasks.length,
windowTaskSummary.rate,
])
const filteredDatasources = useMemo(() => {
const query = dsSearch.trim().toLowerCase()
return datasources.filter((item) => {
if (dsFilter === 'issue' && item.health !== 'error' && item.health !== 'stale') return false
if (dsFilter === 'running' && item.health !== 'running') return false
if (dsFilter === 'disabled' && item.health !== 'disabled') return false
if (
query &&
!item.name.toLowerCase().includes(query) &&
!item.module.toLowerCase().includes(query) &&
!item.source.toLowerCase().includes(query)
) {
return false
}
return true
})
}, [datasources, dsFilter, dsSearch])
const filteredCollectors = useMemo(() => {
const query = colSearch.trim().toLowerCase()
return collectors.filter((item) => {
if (colFilter === 'missing_credentials' && !(item.requiresCredentials && !item.hasCredentials)) return false
if (colFilter === 'configured' && !(item.requiresCredentials && item.hasCredentials)) return false
if (colFilter === 'no_credentials' && item.requiresCredentials) return false
if (
query &&
!item.displayName.toLowerCase().includes(query) &&
!item.name.toLowerCase().includes(query) &&
!item.endpoint.toLowerCase().includes(query)
) {
return false
}
return true
})
}, [colFilter, colSearch, collectors])
const filteredAlerts = useMemo(() => {
if (alertFilter === 'all') return alertCounts.rows
return alertCounts.rows.filter((item) => item.severity === alertFilter)
}, [alertCounts.rows, alertFilter])
const handleAssetNavigate = useCallback(
(item: AssetDistributionItem) => {
navigate(item.filterQuery ? `/data?${item.filterQuery}` : '/data?layer=raw')
},
[navigate],
)
const assetColumns = useMemo<Array<ColumnDef<AssetDistributionItem>>>(() => {
const total = activeAssetItems.reduce((sum, item) => sum + item.count, 0) || 1
return [
{
id: 'name',
accessorFn: (row) => row.name,
header: '名称',
size: 210,
cell: ({ row }) => (
<button type="button" className="an-table-link" onClick={() => handleAssetNavigate(row.original)}>
{row.original.name}
</button>
),
},
{
id: 'count',
accessorFn: (row) => row.count,
header: '记录数',
size: 100,
cell: ({ row }) => <span className="an-tabular">{formatNumber(row.original.count)}</span>,
},
{
id: 'share',
accessorFn: (row) => row.count,
header: '占比',
size: 84,
cell: ({ row }) => (
<span className="an-muted-text an-tabular">{`${((row.original.count / total) * 100).toFixed(1)}%`}</span>
),
},
{
id: 'actions',
header: '台账',
size: 72,
enableSorting: false,
cell: ({ row }) => (
<span className="an-table-actions">
<TableActionButton
title="查看采集数据"
aria-label="查看采集数据"
onClick={() => handleAssetNavigate(row.original)}
>
<ExternalLink size={14} aria-hidden="true" />
</TableActionButton>
</span>
),
},
]
}, [activeAssetItems, handleAssetNavigate])
const datasourceColumns = useMemo<Array<ColumnDef<DashboardDatasourceRow>>>(
() => [
{
id: 'name',
accessorFn: (row) => translateLegacyAdminText(row.name, locale),
header: '名称',
size: 220,
cell: ({ row }) => (
<button type="button" className="an-table-link" onClick={() => navigate('/datasources')}>
{translateLegacyAdminText(row.original.name, locale)}
</button>
),
},
{
id: 'module',
accessorFn: (row) => String(row.module || ''),
header: '模块',
size: 88,
cell: ({ row }) => translateLegacyAdminText(row.original.module, locale),
},
{
id: 'health',
accessorFn: (row) => row.health,
header: '健康',
size: 108,
cell: ({ row }) => (
<StatusText tone={datasourceHealthTone(row.original.health)}>
{datasourceHealthLabel(row.original.health)}
</StatusText>
),
},
{
id: 'updated',
accessorFn: (row) => {
const parsed = row.last_run_at ? parseBackendDate(row.last_run_at) : null
return parsed && !Number.isNaN(parsed.getTime()) ? parsed.getTime() : 0
},
header: '更新时间',
size: 112,
cell: ({ row }) => formatRelativeAge(row.original.last_run_at, isEnglish),
},
{
id: 'metric',
accessorFn: (row) => (typeof row.collected_records === 'number' ? row.collected_records : -1),
header: '指标',
size: 88,
cell: ({ row }) => (
<span className="an-muted-text an-tabular">
{typeof row.original.collected_records === 'number'
? formatNumber(row.original.collected_records)
: '-'}
</span>
),
},
{
id: 'actions',
header: '操作',
size: 84,
enableSorting: false,
cell: ({ row }) => (
<span className="an-table-actions" onClick={(event) => event.stopPropagation()}>
<TableActionButton
icon="trigger"
loading={Boolean(rowBusy[`ds:${row.original.id}`])}
disabled={!row.original.is_active}
title="立即采集"
aria-label="立即采集"
onClick={() => void triggerDatasource(row.original.id, row.original.name)}
/>
<TableActionButton
title="查看数据源"
aria-label="查看数据源"
onClick={() => navigate('/datasources')}
>
<ExternalLink size={14} aria-hidden="true" />
</TableActionButton>
</span>
),
},
],
[isEnglish, locale, navigate, rowBusy, triggerDatasource],
)
const collectorColumns = useMemo<Array<ColumnDef<DashboardCollectorRow>>>(
() => [
{
id: 'name',
accessorFn: (row) => translateLegacyAdminText(row.displayName, locale),
header: '名称',
size: 220,
cell: ({ row }) => (
<button type="button" className="an-table-link" onClick={() => navigate('/collection-management')}>
{translateLegacyAdminText(row.original.displayName, locale)}
</button>
),
},
{
id: 'kind',
accessorFn: (row) => row.kind,
header: '类型',
size: 94,
cell: ({ row }) => (
<Badge tone={row.original.kind === 'builtin' ? 'slate' : 'blue'}>
{row.original.kind === 'builtin' ? '内置' : '自定义'}
</Badge>
),
},
{
id: 'health',
accessorFn: (row) => row.health,
header: '健康',
size: 108,
cell: ({ row }) => (
<StatusText tone={collectorHealthTone(row.original.health)}>
{collectorHealthLabel(row.original.health)}
</StatusText>
),
},
{
id: 'auth',
accessorFn: (row) => (row.requiresCredentials ? row.authType || 'API Key' : ''),
header: '认证',
size: 98,
cell: ({ row }) => (
<span className="an-muted-text">
{row.original.requiresCredentials ? row.original.authType || 'API Key' : '免凭证'}
</span>
),
},
{
id: 'credential',
accessorFn: (row) => (row.requiresCredentials ? (row.hasCredentials ? 1 : 0) : -1),
header: '凭证',
size: 164,
cell: ({ row }) => {
if (!row.original.requiresCredentials) return <span className="an-muted-text">-</span>
if (!row.original.hasCredentials) return <StatusText tone="danger">未配置</StatusText>
return (
<code className="an-dash-cred-mask" title={row.original.credentialPreview || '已配置'}>
{row.original.credentialPreview || '••••••'}
</code>
)
},
},
{
id: 'actions',
header: '操作',
size: 84,
enableSorting: false,
cell: ({ row }) => (
<span className="an-table-actions" onClick={(event) => event.stopPropagation()}>
<TableActionButton
loading={Boolean(rowBusy[row.original.key])}
disabled={!row.original.isActive}
title="测试连接"
aria-label="测试连接"
onClick={() => void testCollector(row.original)}
>
<PlugZap size={14} aria-hidden="true" />
</TableActionButton>
<TableActionButton
title="前往凭证配置"
aria-label="前往凭证配置"
onClick={() => navigate('/collection-management')}
>
<KeyRound size={14} aria-hidden="true" />
</TableActionButton>
</span>
),
},
],
[locale, navigate, rowBusy, testCollector],
)
const taskColumns = useMemo<Array<ColumnDef<DashboardTaskRow>>>(
() => [
{
id: 'time',
accessorFn: (row) => {
const parsed = row.started_at ? parseBackendDate(row.started_at) : null
return parsed && !Number.isNaN(parsed.getTime()) ? parsed.getTime() : 0
},
header: '时间',
size: 92,
cell: ({ row }) => formatRelativeAge(row.original.started_at, isEnglish),
},
{
id: 'name',
accessorFn: (row) => translateLegacyAdminText(row.datasource_name, locale),
header: '名称',
size: 180,
cell: ({ row }) => translateLegacyAdminText(row.original.datasource_name, locale),
},
{
id: 'status',
accessorFn: (row) => String(row.status || ''),
header: '状态',
size: 94,
cell: ({ row }) => (
<StatusText tone={taskStatusTone(row.original.status)}>
{taskStatusLabel(row.original.status)}
</StatusText>
),
},
{
id: 'duration',
accessorFn: (row) => {
const start = row.started_at ? parseBackendDate(row.started_at)?.getTime() : undefined
const end = row.completed_at ? parseBackendDate(row.completed_at)?.getTime() : undefined
return typeof start === 'number' && typeof end === 'number' ? end - start : -1
},
header: '耗时',
size: 74,
cell: ({ row }) => formatDurationShort(row.original.started_at, row.original.completed_at),
},
{
id: 'records',
accessorFn: (row) => row.records_processed ?? row.total_records ?? -1,
header: '记录',
size: 80,
cell: ({ row }) => {
const val = row.original.records_processed ?? row.original.total_records
return <span className="an-muted-text an-tabular">{typeof val === 'number' ? formatNumber(val) : '-'}</span>
},
},
{
id: 'actions',
header: '操作',
size: 64,
enableSorting: false,
cell: ({ row }) => {
const canRetry =
['failed', 'error'].includes(String(row.original.status || '').toLowerCase()) &&
Boolean(row.original.datasource_id)
if (!canRetry) return <span className="an-muted-text">-</span>
return (
<span className="an-table-actions">
<TableActionButton
loading={Boolean(rowBusy[`ds:${row.original.datasource_id}`])}
title="重试采集"
aria-label="重试采集"
onClick={() => void triggerDatasource(row.original.datasource_id, row.original.datasource_name)}
>
<RotateCw size={14} aria-hidden="true" />
</TableActionButton>
</span>
)
},
},
],
[isEnglish, locale, rowBusy, triggerDatasource],
)
const alertColumns = useMemo<Array<ColumnDef<DashboardAlertRow>>>(
() => [
{
id: 'severity',
accessorFn: (row) => {
const sev = String(row.severity || '').toLowerCase()
if (sev === 'critical') return 3
if (sev === 'warning') return 2
return 1
},
header: '级别',
size: 88,
cell: ({ row }) => {
const sev = alertSeverityBadge(row.original.severity)
return <Badge tone={sev.tone}>{sev.label}</Badge>
},
},
{
id: 'title',
accessorFn: (row) => translateLegacyAdminText(row.title, locale),
header: '标题',
size: 240,
cell: ({ row }) => translateLegacyAdminText(row.original.title, locale),
},
{
id: 'time',
accessorFn: (row) => {
const parsed = row.created_at ? parseBackendDate(row.created_at) : null
return parsed && !Number.isNaN(parsed.getTime()) ? parsed.getTime() : 0
},
header: '时间',
size: 98,
cell: ({ row }) => formatRelativeAge(row.original.created_at, isEnglish),
},
{
id: 'actions',
header: '操作',
size: 84,
enableSorting: false,
cell: ({ row }) => (
<span className="an-table-actions">
<TableActionButton
disabled={String(row.original.status || '').toLowerCase() === 'acknowledged' || Boolean(rowBusy[`alert:${row.original.id}`])}
title="确认"
aria-label="确认"
onClick={() => void ackAlert(row.original.id)}
>
<Check size={14} aria-hidden="true" />
</TableActionButton>
<TableActionButton
disabled={Boolean(rowBusy[`alert:${row.original.id}`])}
title="解决"
aria-label="解决"
onClick={() => void resolveAlert(row.original.id)}
>
<CheckCheck size={14} aria-hidden="true" />
</TableActionButton>
</span>
),
},
],
[ackAlert, isEnglish, locale, rowBusy, resolveAlert],
)
const handleCardKeyDown = (event: KeyboardEvent<HTMLElement>, cardId: CardId) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
switchFocus(cardId)
}
}
const assetUnitLabel = isEnglish ? 'records' : '条'
const assetShareLabel = isEnglish ? 'Share' : '占比'
const chartEmptyText = isEnglish ? 'No data available' : '暂无统计数据'
const renderAssetDimTabs = () => (
<div
className="an-dash-seg"
role="tablist"
aria-label={isEnglish ? 'Asset distribution dimension' : '数据资产维度'}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<button
type="button"
className={assetDim === 'source' ? 'is-active' : undefined}
onClick={() => setAssetDim('source')}
>
按数据源
</button>
<button
type="button"
className={assetDim === 'type' ? 'is-active' : undefined}
onClick={() => setAssetDim('type')}
>
按类型
</button>
<button
type="button"
className={assetDim === 'layer' ? 'is-active' : undefined}
onClick={() => setAssetDim('layer')}
>
按图层
</button>
</div>
)
const renderRuntimeTabs = () => (
<div
className="an-dash-seg"
role="tablist"
aria-label={isEnglish ? 'Runtime view' : '运行态势视图'}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<button
type="button"
className={runtimeTab === 'tasks' ? 'is-active' : undefined}
onClick={() => setRuntimeTab('tasks')}
>
任务态势
</button>
<button
type="button"
className={runtimeTab === 'layers' ? 'is-active' : undefined}
onClick={() => setRuntimeTab('layers')}
>
图层占比
</button>
</div>
)
const renderTaskWindowTabs = (compact = false) => (
<div
className={compact ? 'an-dash-seg an-dash-seg--compact' : 'an-dash-seg'}
role="tablist"
aria-label={isEnglish ? 'Task window' : '时间窗口'}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<button
type="button"
className={taskWindow === '24h' ? 'is-active' : undefined}
onClick={() => setTaskWindow('24h')}
>
24h
</button>
<button
type="button"
className={taskWindow === '7d' ? 'is-active' : undefined}
onClick={() => setTaskWindow('7d')}
>
7天
</button>
</div>
)
const renderOpsTabs = () => (
<div
className="an-dash-seg"
role="tablist"
aria-label={isEnglish ? 'Sources and collectors' : '数据源与采集器'}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<button
type="button"
className={opsTab === 'datasources' ? 'is-active' : undefined}
onClick={() => setOpsTab('datasources')}
>
<span>数据源</span>
<span className="an-dash-seg__num">{dsCounts.all}</span>
</button>
<button
type="button"
className={opsTab === 'collectors' ? 'is-active' : undefined}
onClick={() => setOpsTab('collectors')}
>
<span>采集器</span>
<span className="an-dash-seg__num">{colCounts.all}</span>
</button>
</div>
)
const computeLocatedCount = Number(computeCounts.byStatus?.located || 0)
const computeNeedsConfirmCount = Number(computeCounts.byStatus?.needs_confirmation || 0)
const renderBentoCardBody = (card: CardDescriptor) => {
if (card.id === 'data_assets') {
const dimMeta =
assetDim === 'source'
? isEnglish
? `${formatNumber(overallCollectedRecords)} records · ${assetItemsBySource.length} sources`
: `${formatNumber(overallCollectedRecords)} 条 · ${assetItemsBySource.length} 数据源`
: assetDim === 'type'
? isEnglish
? `${formatNumber(overallCollectedRecords)} records · ${assetItemsByType.length} entity types`
: `${formatNumber(overallCollectedRecords)} 条 · ${assetItemsByType.length} 实体类型`
: isEnglish
? `${layers.length} core globe layers`
: `${layers.length} 个地球核心图层`
return (
<div className="an-dash-card__bento an-dash-card__bento--two">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
<span className="an-dash-card__subkpi">{dimMeta}</span>
</div>
<div className="an-dash-card__head-right">
{renderAssetDimTabs()}
</div>
</div>
<DashboardHorizontalBarChart
items={activeAssetItems}
compact
emptyText={chartEmptyText}
unitLabel={assetUnitLabel}
shareLabel={assetShareLabel}
/>
</div>
)
}
if (card.id === 'runtime_insights') {
return (
<div className="an-dash-card__bento">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
<div className="an-dash-card__head-right">
{renderRuntimeTabs()}
</div>
</div>
{runtimeTab === 'tasks' ? (
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">
<span>{formatNumber(windowTaskSummary.total)}</span>
<span className="an-dash-kpi-line__rate">{` · ${windowTaskSummary.rate}%`}</span>
</span>
{renderTaskWindowTabs(true)}
</div>
) : (
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">
{isEnglish ? `${layers.length} layers` : `${layers.length} 图层`}
</span>
<span className="an-dash-kpi-line__meta">
{isEnglish ? `${formatNumber(totalLayerRecords)} indexed` : `${formatNumber(totalLayerRecords)} 核心索引`}
</span>
</div>
)}
{runtimeTab === 'tasks' ? (
<DashboardTaskTrendChart
buckets={taskTrendBuckets}
compact
okLabel={isEnglish ? 'Success' : '成功'}
failLabel={isEnglish ? 'Failed' : '失败'}
rateLabel={isEnglish ? 'Rate' : '成功率'}
/>
) : (
<DashboardLayerDonutChart
items={layerShares}
centerLabel={isEnglish ? 'Core Layer Records' : '核心图层记录'}
unitLabel={assetUnitLabel}
shareLabel={assetShareLabel}
emptyText={chartEmptyText}
computeLocated={computeLocatedCount}
computeTotal={computeCounts.total}
computeNeedsConfirm={computeNeedsConfirmCount}
geocodeTitle={isEnglish ? 'Compute Center Geocoding Progress' : '算力中心地理定位进度'}
/>
)}
</div>
)
}
if (card.id === 'datasources') {
const dsBarSegments: Array<{ tone: BarSegmentTone; weight: number }> = datasources.length
? [
{ tone: 'green' as const, weight: dsCounts.healthy },
{ tone: 'blue' as const, weight: dsCounts.running },
{ tone: 'amber' as const, weight: dsCounts.issue },
{ tone: 'slate' as const, weight: dsCounts.disabled },
].filter((seg) => seg.weight > 0)
: [{ tone: 'slate', weight: 1 }]
const colBarSegments: Array<{ tone: BarSegmentTone; weight: number }> = collectors.length
? [
{ tone: 'green' as const, weight: colCounts.configured + colCounts.noCred },
{ tone: 'red' as const, weight: colCounts.missing },
].filter((seg) => seg.weight > 0)
: [{ tone: 'slate', weight: 1 }]
const segments = opsTab === 'datasources' ? dsBarSegments : colBarSegments
const previewList =
opsTab === 'datasources' ? orderedDatasources.slice(0, 6) : orderedCollectors.slice(0, 6)
return (
<div className="an-dash-card__bento">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
<div className="an-dash-card__head-right">
{renderOpsTabs()}
</div>
</div>
<div className="an-dash-meter-block">
{opsTab === 'datasources' ? (
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">
{`${formatNumber(dsCounts.enabled)} / ${formatNumber(dsCounts.all)} `}
<span className="an-dash-kpi-line__unit">已启用</span>
</span>
<span className={`an-dash-status-inline ${dsCounts.issue > 0 ? 'is-amber' : 'is-green'}`}>
<span className={`an-dash-dot ${dsCounts.issue > 0 ? 'is-amber' : 'is-green'}`} />
<span>
{dsCounts.issue > 0
? isEnglish
? `${dsCounts.issue} issues`
: `${dsCounts.issue} 条需关注`
: isEnglish
? 'Healthy'
: '全部健康'}
</span>
</span>
</div>
) : (
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">
{`${formatNumber(colCounts.all - colCounts.missing)} / ${formatNumber(colCounts.all)} `}
<span className="an-dash-kpi-line__unit">已连通</span>
</span>
<span className={`an-dash-status-inline ${colCounts.missing > 0 ? 'is-red' : 'is-green'}`}>
<span className={`an-dash-dot ${colCounts.missing > 0 ? 'is-red' : 'is-green'}`} />
<span>
{colCounts.missing > 0
? isEnglish
? `${colCounts.missing} missing`
: `${colCounts.missing} 缺凭证`
: isEnglish
? 'Configured'
: '凭证齐全'}
</span>
</span>
</div>
)}
<div className="an-dash-bar">
{segments.map((seg, idx) => (
<span
key={`${opsTab}-seg-${idx}`}
className={`an-dash-bar__seg an-dash-bar__seg--${seg.tone}`}
style={{ '--an-bar-weight': seg.weight } as CSSProperties}
/>
))}
</div>
</div>
<Scrollbar className="an-dash-hairline-list" axis="y">
{opsTab === 'datasources' ? (
previewList.length > 0 ? (
(previewList as DashboardDatasourceRow[]).map((item) => {
const tone = datasourceDotTone(item.health)
return (
<div key={`ds-row-${item.id}`} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
<span className={`an-dash-dot is-${tone}`} />
<span className="an-dash-hairline-row__name">
{translateLegacyAdminText(item.name, locale)}
</span>
<span className="an-dash-hairline-row__tag">
{`${translateLegacyAdminText(item.module, locale)} · ${formatRelativeAge(item.last_run_at, isEnglish)}`}
</span>
</div>
<div
className="an-dash-hairline-row__right"
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<span className={`an-dash-status-inline is-${tone}`}>
{datasourceHealthLabel(item.health)}
</span>
<TableActionButton
icon="trigger"
loading={Boolean(rowBusy[`ds:${item.id}`])}
disabled={!item.is_active}
title="立即采集"
aria-label="立即采集"
onClick={() => void triggerDatasource(item.id, item.name)}
/>
</div>
</div>
)
})
) : (
<div className="an-dash-chart-empty">暂无数据源</div>
)
) : previewList.length > 0 ? (
(previewList as DashboardCollectorRow[]).map((item) => {
const tone = collectorDotTone(item.health)
return (
<div key={item.key} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
<span className={`an-dash-dot is-${tone}`} />
<span className="an-dash-hairline-row__name">
{translateLegacyAdminText(item.displayName, locale)}
</span>
<span className="an-dash-hairline-row__tag">
{item.requiresCredentials ? item.authType || 'API Key' : '免凭证'}
</span>
</div>
<div
className="an-dash-hairline-row__right"
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<span className={`an-dash-status-inline is-${tone}`}>
{collectorHealthLabel(item.health)}
</span>
<TableActionButton
loading={Boolean(rowBusy[item.key])}
disabled={!item.isActive}
title="测试连接"
aria-label="测试连接"
onClick={() => void testCollector(item)}
>
<PlugZap size={14} aria-hidden="true" />
</TableActionButton>
</div>
</div>
)
})
) : (
<div className="an-dash-chart-empty">暂无采集器</div>
)}
</Scrollbar>
</div>
)
}
const activeAlerts = alertCounts.rows
return (
<div className="an-dash-card__bento an-dash-card__bento--two">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
<div className="an-dash-card__head-right">
<span className={`an-dash-status-inline ${activeAlerts.length > 0 ? 'is-red' : 'is-green'}`}>
<span className={`an-dash-dot ${activeAlerts.length > 0 ? 'is-red' : 'is-green'}`} />
<span>
{activeAlerts.length > 0
? isEnglish
? `${activeAlerts.length} active alerts`
: `${activeAlerts.length} 条活跃告警`
: isEnglish
? '0 active alerts'
: '0 活跃告警'}
</span>
</span>
</div>
</div>
<Scrollbar className="an-dash-hairline-list" axis="y">
{activeAlerts.slice(0, 3).map((item) => {
const sev = alertSeverityBadge(item.severity)
return (
<div key={`alert-row-${item.id}`} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
<span className={`an-dash-dot is-${sev.dotTone}`} />
<span className="an-dash-hairline-row__name">
{translateLegacyAdminText(item.title, locale)}
</span>
<span className="an-dash-hairline-row__tag">
{formatRelativeAge(item.created_at, isEnglish)}
</span>
</div>
<div
className="an-dash-hairline-row__right"
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => event.stopPropagation()}
>
<TableActionButton
disabled={Boolean(rowBusy[`alert:${item.id}`])}
title="解决"
aria-label="解决"
onClick={() => void resolveAlert(item.id)}
>
<CheckCheck size={14} aria-hidden="true" />
</TableActionButton>
</div>
</div>
)
})}
{systemChannels.map((ch) => (
<div key={ch.key} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
<span className={`an-dash-dot is-${ch.tone}`} />
<span className="an-dash-hairline-row__name">{ch.name}</span>
<span className="an-dash-hairline-row__tag">{ch.detail}</span>
</div>
<div className="an-dash-hairline-row__right">
<span className={`an-dash-status-inline is-${ch.tone}`}>{ch.status}</span>
</div>
</div>
))}
</Scrollbar>
</div>
)
}
const renderHeroBody = (heroCard: CardDescriptor) => {
return (
<div className="an-dash-hero is-revealing">
<div className="an-dash-hero__heading">
<div className="an-dash-hero__heading-left">
<span className="an-dash-card__icon">{heroCard.icon}</span>
<h2>{heroCard.title}</h2>
</div>
<div className="an-toolbar">
{heroCard.id === 'data_assets' ? (
<>
{renderAssetDimTabs()}
<Button asChild size="icon" variant="subtle" title="采集数据" aria-label="采集数据">
<Link to="/data?layer=raw">
<ExternalLink size={15} />
</Link>
</Button>
</>
) : null}
{heroCard.id === 'runtime_insights' ? (
<>
{renderRuntimeTabs()}
{runtimeTab === 'tasks' ? renderTaskWindowTabs(false) : null}
<Button asChild size="icon" variant="subtle" title="采集数据" aria-label="采集数据">
<Link to="/data">
<ExternalLink size={15} />
</Link>
</Button>
</>
) : null}
{heroCard.id === 'datasources' ? (
<>
{renderOpsTabs()}
{opsTab === 'collectors' ? (
<Button
size="icon"
variant="subtle"
loading={batchTesting}
title="批量测连"
aria-label="批量测连"
onClick={() => void testAllCollectors()}
>
<PlugZap size={15} />
</Button>
) : null}
<Button
asChild
size="icon"
variant="subtle"
title={opsTab === 'datasources' ? '数据源' : '前往凭证配置'}
aria-label={opsTab === 'datasources' ? '数据源' : '前往凭证配置'}
>
<Link to={opsTab === 'datasources' ? '/datasources' : '/collection-management'}>
<ExternalLink size={15} />
</Link>
</Button>
</>
) : null}
{heroCard.id === 'system_alerts' ? (
<Button asChild size="icon" variant="subtle" title="AI" aria-label="AI">
<Link to="/ai">
<ExternalLink size={15} />
</Link>
</Button>
) : null}
<Button
size="icon"
variant="subtle"
title="关闭"
aria-label="关闭"
onClick={() => switchFocus(null)}
>
<X size={15} />
</Button>
</div>
</div>
{heroCard.id === 'data_assets' ? (
<div className="an-dash-hero__body an-dash-hero__body--assets">
<div className="an-dash-kpi-strip">
<div className="an-dash-kpi-cell">
<span>总采集记录</span>
<strong>{formatNumber(overallCollectedRecords)}</strong>
</div>
<div className="an-dash-kpi-cell">
<span>覆盖数据源</span>
<strong>{formatNumber(assetItemsBySource.length)}</strong>
</div>
<div className="an-dash-kpi-cell">
<span>地球核心图层</span>
<strong>{formatNumber(layers.length)}</strong>
</div>
<div className="an-dash-kpi-cell">
<span>算力已定位</span>
<strong>{`${formatNumber(computeLocatedCount)} / ${formatNumber(computeCounts.total)}`}</strong>
</div>
</div>
<div className="an-dash-hero-split">
<div className="an-dash-subbox">
<div className="an-dash-subbox__title">
<span>
{assetDim === 'source'
? '按数据源记录分布'
: assetDim === 'type'
? '按实体类型记录分布'
: '按地球图层记录分布'}
</span>
<span className="an-dash-subbox__hint">悬停查看占比</span>
</div>
<DashboardHorizontalBarChart
items={activeAssetItems}
compact={false}
emptyText={chartEmptyText}
unitLabel={assetUnitLabel}
shareLabel={assetShareLabel}
onItemClick={handleAssetNavigate}
/>
</div>
<div className="an-dash-hero__table">
<DataTable
columns={assetColumns}
data={activeAssetItems}
getRowId={(row) => `${assetDim}:${row.key}`}
columnWidthStorageKey="planet.table.widths.dashboard.assets"
/>
</div>
</div>
</div>
) : null}
{heroCard.id === 'runtime_insights' ? (
<div className="an-dash-hero__body">
<div className="an-dash-hero-split">
<div className="an-dash-subbox">
<div className="an-dash-subbox__title">
<span>
{runtimeTab === 'tasks' ? '采集任务执行趋势' : '地球图层资产占比与算力定位'}
</span>
</div>
{runtimeTab === 'tasks' ? (
<DashboardTaskTrendChart
buckets={taskTrendBuckets}
compact={false}
okLabel={isEnglish ? 'Success' : '成功'}
failLabel={isEnglish ? 'Failed' : '失败'}
rateLabel={isEnglish ? 'Rate' : '成功率'}
/>
) : (
<DashboardLayerDonutChart
items={layerShares}
centerLabel={isEnglish ? 'Core Layer Records' : '核心图层记录'}
unitLabel={assetUnitLabel}
shareLabel={assetShareLabel}
emptyText={chartEmptyText}
computeLocated={computeLocatedCount}
computeTotal={computeCounts.total}
computeNeedsConfirm={computeNeedsConfirmCount}
geocodeTitle={isEnglish ? 'Compute Center Geocoding Progress' : '算力中心地理定位进度'}
/>
)}
</div>
<div className="an-dash-hero__table">
<DataTable
columns={taskColumns}
data={tasks}
getRowId={(row) => String(row.id)}
columnWidthStorageKey="planet.table.widths.dashboard.tasks"
/>
</div>
</div>
</div>
) : null}
{heroCard.id === 'datasources' ? (
<div className="an-dash-hero__body an-dash-hero__body--ops">
{opsTab === 'datasources' ? (
<div className="an-dash-hero__filters">
<div className="an-segmented an-segmented--counted" role="group" aria-label="状态">
{[
{ key: 'all' as const, label: '全部', count: dsCounts.all },
{ key: 'issue' as const, label: '需关注', count: dsCounts.issue },
{ key: 'running' as const, label: '采集中', count: dsCounts.running },
{ key: 'disabled' as const, label: '已停用', count: dsCounts.disabled },
].map((opt) => (
<button
key={opt.key}
type="button"
className={dsFilter === opt.key ? 'is-active' : undefined}
onClick={() => setDsFilter(opt.key)}
>
<span>{opt.label}</span>
<span className="an-segmented__count">{opt.count}</span>
</button>
))}
</div>
<Input
className="an-dash-hero__search"
placeholder="搜索名称或模块"
value={dsSearch}
onChange={(event) => setDsSearch(event.target.value)}
/>
</div>
) : (
<div className="an-dash-hero__filters">
<div className="an-segmented an-segmented--counted" role="group" aria-label="认证">
{[
{ key: 'all' as const, label: '全部', count: colCounts.all },
{ key: 'missing_credentials' as const, label: '缺凭证', count: colCounts.missing },
{ key: 'configured' as const, label: '已配置', count: colCounts.configured },
{ key: 'no_credentials' as const, label: '免凭证', count: colCounts.noCred },
].map((opt) => (
<button
key={opt.key}
type="button"
className={colFilter === opt.key ? 'is-active' : undefined}
onClick={() => setColFilter(opt.key)}
>
<span>{opt.label}</span>
<span className="an-segmented__count">{opt.count}</span>
</button>
))}
</div>
<Input
className="an-dash-hero__search"
placeholder="搜索采集器或端点"
value={colSearch}
onChange={(event) => setColSearch(event.target.value)}
/>
</div>
)}
<div className="an-dash-hero__table">
{opsTab === 'datasources' ? (
<DataTable
columns={datasourceColumns}
data={filteredDatasources}
getRowId={(row) => String(row.id || row.source)}
columnWidthStorageKey="planet.table.widths.dashboard.datasources"
/>
) : (
<DataTable
columns={collectorColumns}
data={filteredCollectors}
getRowId={(row) => row.key}
columnWidthStorageKey="planet.table.widths.dashboard.collectors"
/>
)}
</div>
{opsTab === 'datasources' && realtimeSources.length > 0 ? (
<div className="an-dash-streams">
{realtimeSources.map((src, idx) => (
<span key={`stream-${src.id || src.name}-${idx}`} className="an-dash-streams__item">
<strong>{translateLegacyAdminText(src.name, locale)}</strong>
<StatusText tone={src.connected ? 'success' : 'neutral'}>
{src.connected ? '在线' : '离线'}
</StatusText>
</span>
))}
</div>
) : null}
</div>
) : null}
{heroCard.id === 'system_alerts' ? (
<div className="an-dash-hero__body an-dash-hero__body--alerts">
<div className="an-dash-hero__filters">
<div className="an-segmented an-segmented--counted" role="group" aria-label="级别">
{[
{ key: 'all' as const, label: '全部', count: alertCounts.all },
{ key: 'critical' as const, label: '严重告警', count: alertCounts.critical },
{ key: 'warning' as const, label: '警告', count: alertCounts.warning },
{ key: 'info' as const, label: '提示', count: alertCounts.info },
].map((opt) => (
<button
key={opt.key}
type="button"
className={alertFilter === opt.key ? 'is-active' : undefined}
onClick={() => setAlertFilter(opt.key)}
>
<span>{opt.label}</span>
<span className="an-segmented__count">{opt.count}</span>
</button>
))}
</div>
</div>
<div className="an-dash-hero-split">
<div className="an-dash-subbox">
<div className="an-dash-subbox__title">
<span>系统与实时通道</span>
<span className="an-dash-subbox__hint">
{isEnglish ? `${systemChannels.length} channels` : `${systemChannels.length} 条通道`}
</span>
</div>
<Scrollbar className="an-dash-hairline-list" axis="y">
{systemChannels.map((ch) => (
<div key={`hero-${ch.key}`} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
<span className={`an-dash-dot is-${ch.tone}`} />
<span className="an-dash-hairline-row__name">{ch.name}</span>
<span className="an-dash-hairline-row__tag">{ch.detail}</span>
</div>
<span className={`an-dash-status-inline is-${ch.tone}`}>{ch.status}</span>
</div>
))}
</Scrollbar>
</div>
<div className="an-dash-hero__table">
<DataTable
columns={alertColumns}
data={filteredAlerts}
getRowId={(row) => String(row.id)}
emptyText="无活跃告警"
columnWidthStorageKey="planet.table.widths.dashboard.alerts"
/>
</div>
</div>
</div>
) : null}
</div>
)
}
if (loading && !stats) {
return (
<AdminLayout>
<div className="an-loading">
<span className="an-spinner" />
加载中
</div>
</AdminLayout>
)
}
const activeHero = focusedCard ? cardDescriptors.find((item) => item.id === focusedCard) || cardDescriptors[0] : null
const dockedCards = activeHero ? cardDescriptors.filter((item) => item.id !== activeHero.id) : []
return (
<AdminLayout>
<div className="an-page an-dashboard-page">
<div className="an-page__header">
<div>
<h1>仪表盘</h1>
<p>系统总览与实时态势</p>
</div>
<div className="an-toolbar">
{connected ? (
<Badge tone="green">
<Signal size={14} />
实时连接
</Badge>
) : connecting ? (
<Badge tone="blue">
<span className="an-spinner an-spinner--inline" />
正在连接
</Badge>
) : (
<Badge tone="slate">
<SignalZero size={14} />
离线
</Badge>
)}
<Button asChild size="icon" variant="primary" aria-label="访问智能星球" title="访问智能星球">
<Link to="/earth">
<Globe2 size={16} />
</Link>
</Button>
{isSuperAdmin ? (
<Button size="icon" variant="danger" onClick={openRestartModal} aria-label="重启" title="重启">
<Power size={16} />
</Button>
) : null}
<Button
size="icon"
variant="subtle"
onClick={() => void fetchAll()}
loading={refreshing}
aria-label="刷新"
title="刷新"
>
<RefreshCw size={16} />
</Button>
</div>
</div>
{error ? <div className="an-alert an-alert--error">{error}</div> : null}
<Scrollbar className="an-dash-stage-scroll" axis="y">
<div ref={stageRef} className="an-dash-stage" data-layout={activeHero ? 'focused' : 'bento'}>
<div className="an-dash-dock">
{dockedCards.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-docked"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
<div className="an-dash-card__dock">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
</div>
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">{card.dockKpi}</span>
<span className="an-dash-kpi-line__meta">{card.dockSub}</span>
</div>
</div>
</section>
))}
</div>
<div className="an-dash-hero-slot">
{activeHero ? (
<section key={activeHero.id} data-card-id={activeHero.id} className="an-dash-card is-hero">
{renderHeroBody(activeHero)}
</section>
) : (
cardDescriptors.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-bento"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
{renderBentoCardBody(card)}
</section>
))
)}
</div>
</div>
</Scrollbar>
{stats?.last_updated ? (
<div className="an-page__footer-note">
最后更新: {formatDateTimeZhCN(stats.last_updated)}
{connected ? <Badge tone="green">实时同步中</Badge> : null}
</div>
) : null}
</div>
<Dialog
title="重启服务"
open={restartModalOpen}
onOpenChange={(open) => {
if (restartSubmitting || restartStage === 'waiting_for_shutdown' || restartStage === 'waiting_for_recovery') {
return
}
setRestartModalOpen(open)
}}
footer={
<>
<Button
variant="subtle"
disabled={restartSubmitting || restartStage === 'waiting_for_shutdown' || restartStage === 'waiting_for_recovery'}
onClick={() => setRestartModalOpen(false)}
>
{restartStage === 'confirming' ? '取消' : '关闭'}
</Button>
<Button
variant="danger"
loading={restartSubmitting}
disabled={restartSubmitting || restartStage !== 'confirming'}
onClick={handleRestartAction}
>
重启
</Button>
</>
}
>
<div className="an-restart">
<label className="an-field">
<span>重启动作</span>
<Select
value={restartAction}
onValueChange={(value) => setRestartAction(value as RestartAction)}
disabled={restartSubmitting || restartStage !== 'confirming'}
options={RESTART_ACTION_OPTIONS.map((item) => ({ value: item.value, label: item.label }))}
/>
</label>
<div className="an-restart__meta">
<span>
执行命令 <code>{selectedRestartAction.command}</code>
</span>
<span>
任务 ID <strong>{restartTaskId || '等待创建'}</strong>
</span>
</div>
<p className="an-muted">{restartMessage}</p>
{restartLogs.length > 0 ? <pre className="an-log-tail">{restartLogs.join('\n')}</pre> : null}
</div>
</Dialog>
</AdminLayout>
)
}
export default function Dashboard() {
return <DashboardContent />
}