diff --git a/app/(main)/dashboard/page.tsx b/app/(main)/dashboard/page.tsx index f5750db5..205fc902 100644 --- a/app/(main)/dashboard/page.tsx +++ b/app/(main)/dashboard/page.tsx @@ -1,349 +1,439 @@ "use client" -import { useState } from "react" -import { Button } from "@/components/ui/button" +import { useEffect, useMemo, useState } from "react" import Link from "next/link" import { - ActivityIcon, - BellIcon, CableIcon, - FilterIcon, - GitMergeIcon, - HardDriveIcon, + ChartColumnIcon, + CircleAlertIcon, HeartPulseIcon, - MapIcon, + LayoutDashboardIcon, ServerIcon, - ShieldIcon, + SlidersHorizontalIcon, + TableIcon, } from "lucide-react" +import { Button, buttonVariants } from "@/components/ui/button" +import { + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuLabel, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/reui/alert" +import { Badge } from "@/components/reui/badge" import { PageHeader } from "@/components/page-header" -import { OpsPanel } from "@/components/ops-panel" -import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" -import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid" -import { AttentionQueue } from "@/components/reui-kit/attention-queue" +import { PageTitle } from "@/components/page-title" +import { DataFreshness } from "@/components/data-freshness" +import { EmptyState } from "@/components/empty-state" +import { CapacityGrid, SectionFrame, SparkKpiGrid, ToneBadge, seriesDelta, type Tone } from "@/components/reui-kit/ops-blocks" import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart" import { LatencyChart } from "@/components/dashboard/latency-chart" -import { DashboardEventsTimeline } from "@/components/dashboard/dashboard-events-timeline" import { InternetPathPanel } from "@/components/dashboard/internet-path-panel" +import { DashboardSourcesSummary, dashboardSourceRows, sourceErrorText } from "@/components/dashboard/dashboard-sources-summary" +import { + DashboardAttentionGrid, + DashboardHealth, + DashboardIncidents, + DashboardQuickLinks, + type AttentionGridRow, +} from "@/components/dashboard/dashboard-overview-blocks" import { DashboardActiveProbesDataGrid } from "@/components/data-grids/dashboard-active-probes-data-grid" -import { EmptyState } from "@/components/empty-state" -import { DashboardDataStatus } from "@/components/dashboard/dashboard-data-status" -import { Badge } from "@/components/reui/badge" -import { buttonVariants } from "@/components/ui/button" -import { cn } from "@/lib/utils" import { fmtRate } from "@/lib/fmt-rate" +import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state" import { useDashboardLive, type AttentionRow } from "@/hooks/use-dashboard-live" +const WIDGETS = { + cap: "Ёмкость", + spark: "Показатели", + sources: "Сводка источников", + health: "Здоровье сети", + timeline: "Лента инцидентов", + path: "Internet path", + attention: "Требует внимания", + latency: "Задержка до серверов", + traffic: "Пропускная способность", + probes: "Активные пробы", + links: "Быстрые переходы", +} as const +type Widget = keyof typeof WIDGETS +const HIDDEN_WIDGETS_LS = "mm:dashboard-hidden-widgets" + +function useHiddenWidgets() { + const [hidden, setHidden] = useState>(new Set()) + useEffect(() => { + try { + const raw = JSON.parse(localStorage.getItem(HIDDEN_WIDGETS_LS) ?? "[]") + if (Array.isArray(raw)) queueMicrotask(() => setHidden(new Set(raw.filter((key): key is Widget => key in WIDGETS)))) + } catch { + /* повреждённое значение — показываем все виджеты */ + } + }, []) + function toggle(key: Widget, visible: boolean) { + setHidden((previous) => { + const next = new Set(previous) + if (visible) next.delete(key) + else next.add(key) + try { + localStorage.setItem(HIDDEN_WIDGETS_LS, JSON.stringify([...next])) + } catch { + /* хранилище недоступно — настройка действует до перезагрузки */ + } + return next + }) + } + return { hidden, toggle } +} + function fmtIntRu(n: number): string { return n.toLocaleString("ru-RU") } -function AttentionRows({ rows }: { rows: AttentionRow[] }) { - const [expanded,setExpanded]=useState(false) - const [visible,setVisible]=useState(55) - function renderRow(row: AttentionRow) { - return ( - - {row.title} - - {row.hint} - - - ) +function averageSeries(series: Record): number[] { + const rows = Object.values(series) + const length = Math.max(0, ...rows.map((values) => values.length)) + const out: number[] = [] + for (let i = 0; i < length; i++) { + const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v)) + if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length) } + return out +} - return ( -
- {rows.slice(0, 5).map(renderRow)} - {rows.length > 5 && ( -
{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}> - Ещё {rows.length - 5} - {expanded && rows.slice(5,visible).map(renderRow)} - {expanded && rows.length>visible && } -
- )} -
- ) +function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] { + return rows.map((row) => ({ + id: row.id, + title: row.title, + kind, + hint: row.hint, + href: row.href, + tone: row.tone === "destructive" ? "er" : "wn", + confirmed: row.hint !== "Статус неизвестен", + })) } export default function DashboardPage() { const dash = useDashboardLive() + const { hidden, toggle } = useHiddenWidgets() + const [tab, setTab] = useState("over") + const [mockAt] = useState(() => Date.now()) + const show = (key: Widget) => !hidden.has(key) + + // Демо-режим не опрашивает API: показываем источники полученными в момент открытия страницы. + const sources: DashboardSources = useMemo( + () => dash.isLive ? dash.sources : Object.fromEntries((Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => [key, { receivedAt: mockAt, error: null }])), + [dash.isLive, dash.sources, mockAt], + ) + const sourceRows = dashboardSourceRows(sources) + const failedSources = sourceRows.filter((row) => row.error) + const received = sourceRows.map((row) => row.receivedAt).filter((at): at is number => at != null) + const freshAt = received.length ? Math.max(...received) : null + const offline = dash.offlineCount - const health = dash.probeDown + dash.probeWarn + const problems = dash.probeDown + dash.probeWarn + const serverTrouble = offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 + const serverCaption = !dash.availability.servers ? "нет данных" : !dash.isLive + ? "демо" + : serverTrouble + ? [offline > 0 ? `${offline} не в сети` : null, dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null, dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ") + : dash.totalServers > 0 ? "все в сети" : "нет серверов" + + const latencySeries = dash.latency.kind === "mock" || dash.latency.kind === "live" ? averageSeries(dash.latency.series) : [] + const rttNow = latencySeries.length ? Math.round(latencySeries[latencySeries.length - 1]) : null + + const probesMeasured = useMemo(() => dash.enabledProbes.filter((p) => p.status !== "unknown"), [dash.enabledProbes]) + const avgLoss = probesMeasured.length ? probesMeasured.reduce((sum, p) => sum + (p.loss ?? 0), 0) / probesMeasured.length : null + const rtts = probesMeasured.map((p) => p.rtt).filter((v): v is number => typeof v === "number" && Number.isFinite(v)) + const avgRtt = rtts.length ? Math.round(rtts.reduce((sum, v) => sum + v, 0) / rtts.length) : null + const okSources = sourceRows.filter((row) => row.tone === "ok").length + + const attentionRows = [ + ...toGridRows(dash.attentionServers, "Сервер"), + ...toGridRows(dash.attentionOverlay, "Туннель"), + ...toGridRows(dash.attentionProbes, "Проверка"), + ] + const emptyNotes = [ + dash.attentionServers.length ? null : dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Серверы: состояние не подтверждено", + dash.attentionOverlay.length ? null : dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Туннели: состояние не подтверждено", + dash.attentionProbes.length ? null : dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Проверки: состояние не подтверждено", + ].filter((note): note is string => note != null) + + const latencyBody = dash.latency.kind === "loading" ? ( +
+ ) : dash.latency.kind === "empty" ? ( +

{dash.latency.message}

+ ) : ( + + ) + const latencyDescription = dash.latency.kind === "mock" || dash.latency.kind === "live" ? dash.latency.subtitle : dash.latency.kind === "loading" ? "Загрузка…" : "Нет серии RTT" return (
- + } />
-
- {dash.isLive && } - - 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 - ? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ") - : dash.totalServers > 0 - ? "все в сети" - : "нет серверов", - href: "/servers", - icon: , - iconClassName: "text-muted-foreground", - variant: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 ? "warning" : "default", - }, - { - id: "overlay", - label: "Туннели работают", - value: dash.availability.overlay ? String(dash.overlay.up) : "—", - hint: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `Не работают: ${dash.overlay.down}` : "нет туннелей", - href: "/gre", - icon: , - iconClassName: "text-info", - variant: dash.overlay.down > 0 ? "warning" : "default", - }, - { - id: "bgp", - label: "Префиксы BGP", - value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—", - hint: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных", - href: "/bgp", - icon: , - iconClassName: "text-primary", - }, - { - id: "health", - label: "Проверки с проблемами", - value: dash.availability.probes && dash.unknownProbeCount===0 ? String(health) : "—", - hint: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount>0?` · неизвестны: ${dash.unknownProbeCount}`:""}` : "нет данных", - href: "/uptime", - icon: , - iconClassName: health > 0 ? "text-destructive" : "text-muted-foreground", - variant: health > 0 ? "destructive" : "default", - }, - ]} +
+ } + title="Дашборд" + description="Здоровье сети: индекс, события за период, Internet path, пробы и источники" + actions={ + <> + + Настроить виджеты} /> + + + Виджеты дашборда + {(Object.keys(WIDGETS) as Widget[]).map((key) => ( + toggle(key, !!value)}> + {WIDGETS[key]} + + ))} + + + + + + } /> -
-

Требует внимания

- 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено", - emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.", - children: , - }, - { - id: "overlay", - title: "Туннели", - icon: CableIcon, - iconClassName: "text-info", - count: dash.attentionOverlay.length, - countVariant: "destructive-light", - emptyTitle: dash.reliable.overlay ? (dash.overlay.total > 0 ? "Туннели работают" : "Нет туннелей") : "Состояние не подтверждено", - emptyDescription: dash.reliable.overlay ? "В GRE, WireGuard и VXLAN проблем не обнаружено." : "Проверьте состояние источников выше.", - children: , - }, - { - id: "probes", - title: "Проверки", - icon: HeartPulseIcon, - iconClassName: "text-destructive", - count: dash.attentionProbes.length, - countVariant: "destructive-light", - emptyTitle: dash.reliable.probes ? (dash.probeCount > 0 ? "Проверки без ошибок" : "Нет активных проверок") : "Состояние не подтверждено", - emptyDescription: dash.reliable.probes ? "Нет ошибок и предупреждений активных проверок." : "Проверьте состояние источников выше.", - children: , - }, - ]} - /> -
+
+ {failedSources.length > 0 ? ( + + + Не все источники доступны. + + Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже. + + + + + + ) : null} -
- - {dash.latency.kind === "loading" && ( -
- )} - {dash.latency.kind === "empty" && ( -

{dash.latency.message}

- )} - {(dash.latency.kind === "mock" || dash.latency.kind === "live") && ( - - )} - - - - Все → - - } - > - , + href: "/servers", + }, + { + id: "overlay", + title: "Туннели работают", + caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей", + value: dash.availability.overlay ? dash.overlay.up : null, + total: dash.availability.overlay ? dash.overlay.total : null, + tone: dash.overlay.down > 0 ? "wn" : "ok", + icon: , + href: "/gre", + }, + { + id: "health", + title: "Проверки с проблемами", + caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных", + value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null, + total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null, + tone: problems > 0 ? "er" : "ok", + icon: , + href: "/uptime", + }, + ]} /> - -
+ ) : null} -
- Трафик →} - contentClassName="px-3 pb-3" - > - {dash.loading && !dash.traffic ? ( -
- ) : !dash.traffic ? ( -

- Нет данных трафика за последний час.{" "} - - Открыть трафик - -

- ) : ( - <> -
- {dash.traffic.demo ? демо : !dash.traffic.observationsKnown ? Измерения не подтверждены API : null} - RX {dash.traffic.rxNow===null?"—":fmtRate(dash.traffic.rxNow)} - TX {dash.traffic.txNow===null?"—":fmtRate(dash.traffic.txNow)} + {show("spark") ? ( + typeof v === "number"), + delta: seriesDelta(dash.traffic?.rx.filter((v): v is number => typeof v === "number")), + footnote: "суммарно · 1 ч", + href: "/traffic", + }, + { + id: "tx", + title: "TX", + value: dash.traffic?.txNow != null ? fmtRate(dash.traffic.txNow) : "—", + series: dash.traffic?.tx.filter((v): v is number => typeof v === "number"), + delta: seriesDelta(dash.traffic?.tx.filter((v): v is number => typeof v === "number")), + footnote: "суммарно · 1 ч", + href: "/traffic", + }, + ]} + /> + ) : null} + + {show("sources") ? : null} + + setTab(String(value))} className="gap-5"> + + Обзор + + Источники и время получения + {sourceRows.length} + + История RTT + + + + {show("health") ? ( + (p.loss ?? 0) === 0).length / probesMeasured.length : null }, + { label: "Задержка (RTT)", value: avgRtt == null ? "—" : `${avgRtt} мс`, ratio: probesMeasured.length ? probesMeasured.filter((p) => p.status === "up").length / probesMeasured.length : null }, + { label: "Свежесть данных", value: `${okSources} из ${sourceRows.length}`, ratio: sourceRows.length ? okSources / sourceRows.length : null }, + { label: "Серверы в сети", value: dash.availability.servers ? `${dash.onlineCount} из ${dash.totalServers}` : "—", ratio: dash.availability.servers && dash.totalServers > 0 ? dash.onlineCount / dash.totalServers : null }, + { label: "Туннели", value: dash.availability.overlay ? `${dash.overlay.up} из ${dash.overlay.total}` : "—", ratio: dash.availability.overlay && dash.overlay.total > 0 ? dash.overlay.up / dash.overlay.total : null }, + ]} + /> + ) : null} + + {show("timeline") ? : null} + + {show("path") ? : null} + + {show("attention") ? : null} + + {show("latency") ? ( + + {latencyBody} + + ) : null} + + {show("traffic") ? ( + Трафик →} + panelClassName="px-3.5 pt-3.5 pb-2" + > + {dash.loading && !dash.traffic ? ( +
+ ) : !dash.traffic ? ( +

+ Нет данных трафика за последний час.{" "} + Открыть трафик +

+ ) : ( + <> +
+ {dash.traffic.demo ? демо : !dash.traffic.observationsKnown ? Измерения не подтверждены API : null} + RX {dash.traffic.rxNow === null ? "—" : fmtRate(dash.traffic.rxNow)} + TX {dash.traffic.txNow === null ? "—" : fmtRate(dash.traffic.txNow)} +
+ + + )} + + ) : null} + + {show("probes") ? ( + {dash.probesSubtitle}} + icon={} + actions={Мониторинг →} + > + {dash.activeProbes.length === 0 && !dash.probesLoading ? ( + Открыть мониторинг} + /> + ) : ( + + )} + + ) : null} + + {show("links") ? ( + + ) : null} + + + + {failedSources.length > 0 ? ( + + + Не обновлены источники: {failedSources.length} + Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны. + + ) : null} + }> +
+ + + + + + + + + + + + {sourceRows.map((row) => ( + + + + + + + + ))} + +
ИсточникСтатусПолученоЗамерОшибка
{row.name}{row.label}{row.receivedAt != null ? new Date(row.receivedAt).toLocaleString("ru-RU") : "—"}{row.sampledAt ? new Date(row.sampledAt).toLocaleString("ru-RU") : "—"}{sourceErrorText(row) ?? "—"}
- - - )} - - +
+
+ + + {latencyBody} + + +
- - - - {dash.probesSubtitle} - } - headerRight={ - - Мониторинг → - - } - contentClassName="px-0 pb-0" - > - {dash.activeProbes.length === 0 && !dash.probesLoading ? ( - - Открыть мониторинг - - } - /> - ) : ( - - )} - - - , - iconClassName: "text-info", - }, - { - id: "map", - title: "Карта сети", - description: "Топология GRE и WAN", - href: "/network-map", - icon: , - iconClassName: "text-primary", - }, - { - id: "filters", - title: "Фильтры", - description: "Правила обхода и списки", - href: "/filters", - icon: , - iconClassName: "text-info", - }, - { - id: "firewall", - title: "Firewall", - description: "Цепочки filter / nat", - href: "/firewall", - icon: , - iconClassName: "text-warning", - }, - { - id: "backups", - title: "Бэкапы", - description: "Снапшоты и расписание", - href: "/backups", - icon: , - iconClassName: "text-muted-foreground", - }, - { - id: "bgp", - title: "BGP", - description: "Сессии и префиксы", - href: "/bgp", - icon: , - iconClassName: "text-primary", - }, - ]} - /> -
diff --git a/app/(main)/layout.tsx b/app/(main)/layout.tsx index 6c2b525e..a9e177cd 100644 --- a/app/(main)/layout.tsx +++ b/app/(main)/layout.tsx @@ -22,7 +22,7 @@ export default function MainLayout({ children }: { children: ReactNode }) { К содержимому - + {children} diff --git a/app/(main)/network-map/page.tsx b/app/(main)/network-map/page.tsx index 1e51cc95..4c1d32cb 100644 --- a/app/(main)/network-map/page.tsx +++ b/app/(main)/network-map/page.tsx @@ -11,6 +11,7 @@ import {Dialog,DialogContent,DialogHeader,DialogTitle,DialogDescription} from "@ import {usePrefersReducedMotion} from "@/hooks/use-prefers-reduced-motion" import {toast} from "sonner" import { PageHeader } from "@/components/page-header" +import { PageTitle } from "@/components/page-title" import { NetworkMapLegend } from "@/components/network-map-legend" import { servers as mockServers, @@ -2044,22 +2045,28 @@ function NetworkMapContent() { return (
- - {useLiveData && ( - + )} + - )} - - - } - /> + + } + /> +
{urlState.server&&((hasSnapshot||!useLiveData)&&!selected||selected&&selWanIdx!==null&&!selected.wanUplinks?.[selWanIdx])&&Объект карты недоступен{!selected?"Устройство "+urlState.server+" отсутствует в текущем снимке.":"Запрошенный WAN отсутствует у выбранного устройства."}} diff --git a/app/(main)/statistics/page.tsx b/app/(main)/statistics/page.tsx index 8b4f1519..7dfdfbca 100644 --- a/app/(main)/statistics/page.tsx +++ b/app/(main)/statistics/page.tsx @@ -1,17 +1,22 @@ "use client" -import { Suspense, useCallback, useEffect, useMemo, useState } from "react" +import { Suspense, useCallback, useEffect, useMemo, useState, type ReactNode } from "react" import { useSearchParams } from "next/navigation" import { ActivityIcon, + ChartColumnIcon, DatabaseIcon, GaugeIcon, + GlobeIcon, ServerIcon, UsersIcon, } from "lucide-react" import { Button } from "@/components/ui/button" import { PageHeader } from "@/components/page-header" +import { PageTitle } from "@/components/page-title" import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" +import { CapacityGrid, type CapacityItem } from "@/components/reui-kit/ops-blocks" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { DataPageCard } from "@/components/data-page-card" import { DataPageToolbar } from "@/components/data-page-toolbar" import { SegmentedControl } from "@/components/form-kit" @@ -102,8 +107,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind { return t && isStatisticsSliceKind(t) ? t : "users" } -function readView(sp: URLSearchParams): "explore" | "pivot" { - return sp.get("view") === "pivot" ? "pivot" : "explore" +type StatisticsView = "overview" | "explore" | "pivot" + +/** Вкладка макета v3: Обзор, Срезы (explore) или Сводная (pivot); старые ссылки с разрезом открывают Срезы. */ +function readView(sp: URLSearchParams): StatisticsView { + const v = sp.get("view") + if (v === "pivot" || v === "explore" || v === "overview") return v + return sp.has("dim") || sp.has("tab") || SLICE_KEYS.some((key) => sp.has(key)) ? "explore" : "overview" } function readPlanes(sp: URLSearchParams): "unique" | "all" { @@ -241,7 +251,9 @@ function StatisticsPageInner() { const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams]) const [retry, setRetry] = useState(0) - const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, view, pivotRow, pivotCol, planes, retry, rangeError, paramsError }) + // Обзор и Срезы читают один и тот же куб — смена этих вкладок не перезапрашивает данные. + const pivotView = view === "pivot" + const requestKey = JSON.stringify({ backendUrl, isLive, range, slices, pivotView, pivotRow, pivotCol, planes, retry, rangeError, paramsError }) const [result, setResult] = useState<{ key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null } | null>(null) @@ -295,7 +307,7 @@ function StatisticsPageInner() { const dto = await getStatistics(backendUrl, query) if (cancelled) return let matrix = EMPTY_PIVOT - if (view === "pivot" && pivotRow !== pivotCol) { + if (pivotView && pivotRow !== pivotCol) { matrix = await getStatisticsPivot(backendUrl, { ...query, row: pivotRow, @@ -313,7 +325,7 @@ function StatisticsPageInner() { return () => { cancelled = true } - }, [backendUrl, isLive, prefsHydrated, range, slices, view, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError]) + }, [backendUrl, isLive, prefsHydrated, range, slices, pivotView, pivotRow, pivotCol, planes, requestKey, rangeError, paramsError]) const viewData = dataReady ? current.data : EMPTY const sliced = hasAnySlice(slices) @@ -348,175 +360,194 @@ function StatisticsPageInner() { : sliced ? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов` : `${rowsForKind(viewData, dim).length} строк` + const hasContext = STATISTICS_CONTEXT_KEYS.some((key) => searchParams.has(key)) + const resetContext = () => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map((key) => [key, undefined]))) + const scope = planes === "all" ? "Все плоскости" : "GRE/WG клиентов, без hops" + const bytesOf = (rows: StatisticsBreakdownRow[]) => rows.reduce((total, row) => total + row.bytes, 0) + const shareOf = (bytes: number) => (kpis.bytes > 0 ? Math.min(1, bytes / kpis.bytes) : 0) + const bytesItem = (id: string, title: string, caption: string, bytes: number, icon: ReactNode): CapacityItem => { + const [valueText, ...unit] = formatBytes(bytes).split(" ") + return { id, title, caption, value: bytes, total: kpis.bytes, ratio: shareOf(bytes), tone: shareOf(bytes) >= 0.999 ? "wn" : "ok", icon, valueText, unit: unit.join(" ") } + } + const planesControl = ( + updateParams({ planes: next === "all" ? "all" : undefined })} + options={[ + { value: "all", label: "Все плоскости" }, + { value: "unique", label: "GRE/WG клиентов" }, + ]} + /> + ) + const cubeState = isLive && !dataReady ? ( +
{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}
+ ) : emptyCube ? ( + + ) : null + const sliceChips = ( + { + const next = { ...slices } + delete next[key as keyof CubeSlices] + setSlices(next) + }} + /> + ) + const filters = + const tabTrigger = "h-auto flex-none px-3 py-2.5 after:bottom-[-1px]" return (
- setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней : } - /> + -
- {!isLive ? ( - - Живые данные выключены - - Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт. - - - ) : null} +
+ } + title="Статистика" + description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей" + actions={ + <> + {rangeError ? : } + + + } + /> - {error ? ( - - {rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"} - {error}{!rangeError && !paramsError && }{paramsError && } - - ) : null} +
+ {!isLive ? ( + + Живые данные выключены + + Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт. + + + ) : null} - {!slices.serverId && dataReady && !emptyCube ? ( - - Уникальный объём - - Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN. - - - ) : null} + {error ? ( + + {rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"} + {error}{!rangeError && !paramsError && } + + ) : null} - {(dataReady || loading) && , - iconClassName: "text-muted-foreground", - }, - { - id: "packets", - label: "Пакеты", - value: kpis.packets.toLocaleString("ru-RU"), - hint: kpis.topService ? `топ: ${kpis.topService}` : undefined, - icon: , - iconClassName: "text-muted-foreground", - }, - { - id: "bps", - label: "Средний bitrate", - value: fmtBps(kpis.avgBps), - icon: , - iconClassName: "text-muted-foreground", - }, - { - id: "users", - label: "Пользователи", - value: String(kpis.users), - icon: , - iconClassName: "text-muted-foreground", - }, - { - id: "servers", - label: "Серверы", - value: String(kpis.servers), - hint: slices.serverId - ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) - : planes === "all" - ? "WAN и дубли в списке" - : "без WAN и overlay", - icon: , - iconClassName: "text-muted-foreground", - }, - ]} - />} + {(dataReady || loading) && , + iconClassName: planes === "all" ? "text-muted-foreground" : "text-success", + }, + { + id: "packets", + label: "Пакеты", + value: kpis.packets.toLocaleString("ru-RU"), + hint: kpis.topService ? `топ: ${kpis.topService}` : undefined, + icon: , + iconClassName: "text-muted-foreground", + }, + { + id: "bps", + label: "Средний bitrate", + value: fmtBps(kpis.avgBps), + icon: , + iconClassName: "text-muted-foreground", + }, + { + id: "users", + label: "Пользователи", + value: String(kpis.users), + hint: `Серверы: ${kpis.servers}`, + icon: , + iconClassName: "text-muted-foreground", + }, + ]} + />} - {dataReady && } + updateParams({ view: String(next) })} className="gap-5"> + + Обзор + Сводная (куб) + Срезы + - - - updateParams({ view: next === "pivot" ? "pivot" : "explore" })} - options={[ - { value: "explore", label: "Разрез" }, - { value: "pivot", label: "Сводка" }, - ]} - /> - updateParams({ planes: next === "all" ? "all" : undefined })} - options={[ - { value: "unique", label: "Уникальный" }, - { value: "all", label: "Все плоскости" }, - ]} - /> - {view === "explore" && !sliced ? ( - updateParams({ dim: next, tab: undefined })} + + {cubeState ?? ( + <> + + ), + bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), ), + bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), ), + ]} /> - ) : null} - {view === "pivot" ? ( - <> - updateParams({ pivotRow: next })} - /> - updateParams({ pivotCol: next })} - /> - - ) : null} -
- } - filterControl={} - countLabel={dataReady ? countLabel : undefined} - /> - { - const next = { ...slices } - delete next[key as keyof CubeSlices] - setSlices(next) - }} - /> - {isLive && !dataReady ? ( -
{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}
- ) : emptyCube ? ( - - ) : view === "pivot" ? ( - - ) : sliced ? ( -
+ } + filterControl={filters} + countLabel={dataReady ? countLabel : undefined} + /> + {sliceChips} + {cubeState ?? } + + + + + + + {planesControl} + {!sliced ? updateParams({ dim: next, tab: undefined })} /> : null} +
+ } + filterControl={filters} + countLabel={dataReady ? countLabel : undefined} + /> + {sliceChips} + {cubeState ?? (sliced ? ( +
) diff --git a/app/(main)/traffic/page.tsx b/app/(main)/traffic/page.tsx index ee9a71bc..716e54a2 100644 --- a/app/(main)/traffic/page.tsx +++ b/app/(main)/traffic/page.tsx @@ -7,7 +7,9 @@ import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status" import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status" import { TrafficDataTime } from "@/components/traffic/traffic-data-time" import { PageHeader } from "@/components/page-header" -import { Frame, FramePanel } from "@/components/reui/frame" +import { PageTitle } from "@/components/page-title" +import { FramePanel } from "@/components/reui/frame" +import { SectionFrame } from "@/components/reui-kit/ops-blocks" import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart" import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart" @@ -1229,46 +1231,57 @@ export default function TrafficPage() { }, ] + const modeCount: Record = { + servers: activeServerTraffic.length, + users: (isLive ? liveUsers : userTraffic).length, + ifaces: (isLive ? liveBoundIfaces : boundIfaces).length, + flows: null, + } + const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading) + const listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы" + const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length + return (
- - - - } - /> + - {/* ── mode tab bar ── */} -
-
- {GROUP_MODES.map(({ mode, icon, label }) => ( - - ))} -
-
- -
+
+
+ } + title="Трафик" + description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам" + actions={ + <> + + + + } + />
+
+ {GROUP_MODES.map(({ mode, label }) => ( + + ))} +
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && )} -
-
+
+
-
- + + {analyticsLoading &&

Загрузка аналитики…

} {currentAnalytics?.error && Аналитика недоступна{currentAnalytics.error}} @@ -1399,7 +1412,7 @@ export default function TrafficPage() { emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)} />
- +
) : ( -
+
{/* ── left panel ── */} -
+ {/* search */}
@@ -1461,10 +1474,10 @@ export default function TrafficPage() { setSelectedId(c.id)} /> ))}
-
+ {/* ── detail panel ── */} - + {isLive && effectiveMode === "servers" && (
@@ -1550,11 +1563,12 @@ export default function TrafficPage() { {effectiveMode === "users" && selUser && } {effectiveMode === "ifaces" && selIface && } - +
)}
+
) diff --git a/components/app-sidebar.tsx b/components/app-sidebar.tsx index 2680da78..6f90f951 100644 --- a/components/app-sidebar.tsx +++ b/components/app-sidebar.tsx @@ -107,7 +107,7 @@ export function AppSidebar({ ...props }: React.ComponentProps) { }, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot]) return ( - + diff --git a/components/dashboard/dashboard-data-status.tsx b/components/dashboard/dashboard-data-status.tsx deleted file mode 100644 index d67e7fa3..00000000 --- a/components/dashboard/dashboard-data-status.tsx +++ /dev/null @@ -1,39 +0,0 @@ -"use client" - -import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert" -import { Button } from "@/components/ui/button" -import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state" - -export function DashboardDataStatus({ sources, refreshing, onRefresh }: { - sources: DashboardSources - refreshing: boolean - onRefresh: () => void -}) { - const failed = Object.values(sources).filter(source => source.error) - const summary = failed.length ? `Не обновлены источники: ${failed.length}` : "Состояние источников" - return
- {failed.length > 0 && - {summary} - Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны. - } -
-
0 || undefined}> - Источники и время получения -
    - {(Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map(key => { - const source = sources[key] - return
  • - {DASHBOARD_SOURCES[key]}: {source?.error ? `ошибка обновления — ${source.error}. ` : ""} - {source?.receivedAt != null ? <>Получено {source.error ? " · данные могут быть устаревшими" : ""} : "Успешных загрузок ещё нет"} - {source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) && <> · замер } -
  • - })} -
-
-
- {refreshing ? "Обновление данных…" : "Обновление завершено"} - -
-
-
-} diff --git a/components/dashboard/dashboard-events-timeline.tsx b/components/dashboard/dashboard-events-timeline.tsx deleted file mode 100644 index 42b8d1f4..00000000 --- a/components/dashboard/dashboard-events-timeline.tsx +++ /dev/null @@ -1,90 +0,0 @@ -"use client" - -import Link from "next/link" -import { - Timeline, - TimelineContent, - TimelineDate, - TimelineHeader, - TimelineIndicator, - TimelineItem, - TimelineSeparator, - TimelineTitle, -} from "@/components/reui/timeline" -import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert" -import { cn } from "@/lib/utils" -import type { EventItem } from "@mmapp/contracts/events" - -function formatEventAge(iso: string): string { - const ts = Date.parse(iso) - if (!Number.isFinite(ts)) return "—" - const diffMs = Math.max(0, Date.now() - ts) - const minutes = Math.floor(diffMs / 60_000) - if (minutes < 1) return "сейчас" - if (minutes < 60) return `${minutes}м` - const hours = Math.floor(minutes / 60) - if (hours < 24) return `${hours}ч` - const days = Math.floor(hours / 24) - return `${days}д` -} - -const LEVEL_DOT: Record = { - critical: "border-destructive bg-destructive/20 group-data-completed/timeline-item:border-destructive", - warning: "border-warning bg-warning/20 group-data-completed/timeline-item:border-warning", - info: "border-info bg-info/20 group-data-completed/timeline-item:border-info", -} - -/** - * Compact activity timeline. - * Preview: https://reui.io/preview/base/timeline-3 - * Docs: https://reui.io/docs/components/base/timeline - */ -export function DashboardEventsTimeline({ - events, - loading, - error, -}: { - events: EventItem[] - loading?: boolean - error?: string | null -}) { - if (loading && events.length === 0) { - return

Загрузка событий…

- } - if (error && events.length === 0) { - return ( -
- - События недоступны - {error} - -
- ) - } - if (events.length === 0) { - return ( -

- Событий пока нет.{" "} - - Оповещения - -

- ) - } - - return ( - - {events.map((event, index) => ( - - - - {formatEventAge(event.createdAt)} - {event.title} - - - {event.message} - - ))} - - ) -} diff --git a/components/dashboard/dashboard-overview-blocks.tsx b/components/dashboard/dashboard-overview-blocks.tsx new file mode 100644 index 00000000..f6919e7f --- /dev/null +++ b/components/dashboard/dashboard-overview-blocks.tsx @@ -0,0 +1,245 @@ +"use client" + +import { useState, type ReactNode } from "react" +import Link from "next/link" +import { SearchIcon, TableIcon } from "lucide-react" +import { Button, buttonVariants } from "@/components/ui/button" +import { FramePanel } from "@/components/reui/frame" +import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert" +import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks" +import { cn } from "@/lib/utils" +import type { EventItem } from "@mmapp/contracts/events" + +export type HealthFactor = { label: string; value: string; ratio: number | null } + +function factorTone(ratio: number): Tone { + return ratio >= 0.85 ? "ok" : ratio >= 0.6 ? "wn" : "er" +} + +/** + * Здоровье сети (блок health макета v3): кольцо сводного индекса и факторы. + * Индекс — среднее долей исправных по факторам с известными данными. + */ +export function DashboardHealth({ factors }: { factors: HealthFactor[] }) { + const known = factors.filter((f): f is HealthFactor & { ratio: number } => f.ratio != null) + const score = known.length ? Math.round((known.reduce((sum, f) => sum + f.ratio, 0) / known.length) * 100) : null + const tone: Tone = score == null ? "mu" : factorTone(score / 100) + const badge = score == null ? "Нет данных" : tone === "ok" ? "В норме" : tone === "wn" ? "С замечаниями" : "Требует внимания" + const circumference = 2 * Math.PI * 52 + return ( + {badge}} + panelClassName="grid grid-cols-1 items-center gap-6 p-5 md:grid-cols-[200px_minmax(0,1fr)]" + > +
+
+ + + {score != null ? ( + + ) : null} + +
+ {score ?? "—"} + из 100 +
+
+ {known.length} из {factors.length} факторов с данными +
+
+ {factors.map((factor) => ( +
+ {factor.label} + + {factor.value} +
+ ))} +
+
+ ) +} + +const LEVEL: Record = { + critical: { tone: "er", label: "Сбой" }, + warning: { tone: "wn", label: "Внимание" }, + info: { tone: "in", label: "Инфо" }, +} + +function hhmm(iso: string) { + const ts = Date.parse(iso) + return Number.isFinite(ts) ? new Date(ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : "—" +} + +/** Лента инцидентов (блок timeline макета v3) из последних событий системы. */ +export function DashboardIncidents({ events, loading, error }: { events: EventItem[]; loading?: boolean; error?: string | null }) { + let body: ReactNode + if (loading && events.length === 0) body =

Загрузка событий…

+ else if (error && events.length === 0) { + body = ( +
+ + События недоступны + {error} + +
+ ) + } else if (events.length === 0) body =

Событий пока нет.

+ else { + body = ( +
    + {events.map((event, index) => { + const level = LEVEL[event.level] ?? LEVEL.info + return ( +
  1. + + + + {level.label} + {event.title} + {event.message ? {event.message} : null} + +
  2. + ) + })} +
+ ) + } + return ( + Все события} + > + {body} + + ) +} + +export type AttentionGridRow = { + id: string + title: string + kind: "Сервер" | "Туннель" | "Проверка" + hint: string + href: string + tone: Tone + /** Подтверждённая проблема; false — состояние неизвестно. */ + confirmed: boolean +} + +const PAGE = 50 + +/** + * Требует внимания (блок grid макета v3): вкладки, поиск и строки-ссылки на объект. + * Пустые категории перечислены в подвале, чтобы «нет проблем» не путалось с «нет данных». + */ +export function DashboardAttentionGrid({ rows, emptyNotes }: { rows: AttentionGridRow[]; emptyNotes: string[] }) { + const [view, setView] = useState<"all" | "confirmed">("all") + const [query, setQuery] = useState("") + const [visible, setVisible] = useState(PAGE) + const confirmed = rows.filter((row) => row.confirmed) + const q = query.trim().toLowerCase() + const shown = (view === "all" ? rows : confirmed).filter((row) => !q || `${row.title} ${row.kind} ${row.hint}`.toLowerCase().includes(q)) + const tabs = [ + { id: "all" as const, label: "Все", count: rows.length }, + { id: "confirmed" as const, label: "С проблемами", count: confirmed.length }, + ] + return ( + } bare> +
+ {tabs.map((tab) => ( + + ))} +
+
+ + {q ? {shown.length} из {rows.length} : null} +
+ +
+ + {shown.length === 0 ? ( +

{rows.length === 0 ? "Проблем не обнаружено" : "Ничего не найдено"}

+ ) : ( + shown.slice(0, visible).map((row) => ( + + + + + {row.title} + {row.kind} + + + {row.tone === "er" ? "Сбой" : row.confirmed ? "Внимание" : "Неизвестно"} + {row.kind} + {row.hint} + + )) + )} +
+ {shown.length > visible ? ( +
+ +
+ ) : null} +
+ {emptyNotes.length ? ( +
+ {emptyNotes.map((note) => {note})} +
+ ) : null} +
+ ) +} + +export type QuickLink = { id: string; title: string; description: string; href: string } + +/** Быстрые переходы (блок cards макета v3). */ +export function DashboardQuickLinks({ links }: { links: QuickLink[] }) { + return ( + + {links.map((link) => ( + +
+ {link.title} + Открыть +
+
{link.description}
+ + ))} +
+ ) +} diff --git a/components/dashboard/dashboard-sources-summary.tsx b/components/dashboard/dashboard-sources-summary.tsx new file mode 100644 index 00000000..b4e85694 --- /dev/null +++ b/components/dashboard/dashboard-sources-summary.tsx @@ -0,0 +1,149 @@ +"use client" + +import type { ReactNode } from "react" +import { ActivityIcon, BellIcon, BoxIcon, ChartColumnIcon, DatabaseIcon, GlobeIcon, LinkIcon, LockIcon, RouteIcon, ServerIcon } from "lucide-react" +import { Button } from "@/components/ui/button" +import { FramePanel } from "@/components/reui/frame" +import { IconTile } from "@/components/reui/icon-tile" +import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks" +import { DASHBOARD_SOURCES, type DashboardSource, type DashboardSources } from "@/lib/dashboard-source-state" +import { cn } from "@/lib/utils" + +const SOURCE_ICON: Record = { + servers: , probes: , bgp: , gre: , wg: , + vxlan: , traffic: , internetPath: , events: , +} + +export type SourceRow = { + key: DashboardSource + name: string + tone: Tone + label: string + receivedAt: number | null + sampledAt: string | null + error: string | null +} + +/** Состояние каждого источника дашборда: обновлён, устарел (ошибка после успеха), нет загрузок или ожидание. */ +export function dashboardSourceRows(sources: DashboardSources): SourceRow[] { + return (Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map((key) => { + const source = sources[key] + const receivedAt = source?.receivedAt ?? null + const error = source?.error ?? null + const sampledAt = source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) ? source.sampledAt : null + const tone: Tone = error ? (receivedAt != null ? "wn" : "er") : receivedAt != null ? "ok" : "mu" + const label = error ? (receivedAt != null ? "Устарел" : "Нет загрузок") : receivedAt != null ? "Обновлён" : "Ожидание" + return { key, name: DASHBOARD_SOURCES[key], tone, label, receivedAt, sampledAt, error } + }) +} + +function Clock({ at }: { at: number | string | null }) { + if (at == null) return — + const date = new Date(at) + return ( + + ) +} + +export function sourceErrorText(row: SourceRow) { + if (!row.error) return null + return row.receivedAt != null + ? `Ошибка обновления — ${row.error} · данные могут быть устаревшими` + : `Ошибка обновления — ${row.error} · успешных загрузок ещё нет` +} + +/** + * Сводка источников дашборда (блок sources макета v3): итог слева, плитки источников справа. + * @see https://reui.io/docs/components/base/frame + */ +export function DashboardSourcesSummary({ rows, refreshing, onRefresh }: { + rows: SourceRow[] + refreshing: boolean + onRefresh: () => void +}) { + const count = (tone: Tone) => rows.filter((row) => row.tone === tone).length + const ok = count("ok") + const segments = ([ + ["ok", "Обновлены", count("ok")], + ["wn", "С ошибкой", count("wn")], + ["er", "Нет загрузок", count("er")], + ["mu", "Ожидание", count("mu")], + ] as const).filter(([, , n]) => n > 0) + const sub = [ + count("wn") ? `${count("wn")} с ошибкой — показаны прошлые данные` : null, + count("er") ? `${count("er")} без успешных загрузок` : null, + count("mu") ? `${count("mu")} ожидают первой загрузки` : null, + ].filter(Boolean).join(" · ") || "Все источники получены" + + return ( + } + bare + actions={ + <> + {refreshing ? "Обновление данных…" : "Обновление завершено"} + + + } + > + +
+
Источники обновлены
+
+ {ok} + / {rows.length} +
+
{sub}
+
`${label}: ${n}`).join(", ")} className="mt-1.5 flex h-2 gap-[3px]"> + {segments.map(([tone, label, n]) => ( + + ))} +
+
+ {segments.map(([tone, label, n]) => ( + +