diff --git a/app/(main)/dashboard/page.tsx b/app/(main)/dashboard/page.tsx index f5750db5..104ff4ed 100644 --- a/app/(main)/dashboard/page.tsx +++ b/app/(main)/dashboard/page.tsx @@ -1,349 +1,437 @@ "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 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: "Пробы в норме", value: probesMeasured.length ? `${probesMeasured.filter((p) => p.status === "up").length} из ${probesMeasured.length}` : "—", 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..08299a1e 100644 --- a/app/(main)/network-map/page.tsx +++ b/app/(main)/network-map/page.tsx @@ -11,9 +11,12 @@ 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 { MapKpiStrip } from "@/components/network-map/map-kpi-strip" import { NetworkMapLegend } from "@/components/network-map-legend" import { servers as mockServers, + systemEvents as mockSystemEvents, greTunnels as mockGreTunnels, type GreTunnel, type Server, @@ -27,7 +30,12 @@ import { buildGreMapEdges, buildServerResourceMap, buildWanJhEdges, - clipSegmentCircleToRect, + mapLinkPath, + MAP_LANES, + MAP_CARD_W, + MAP_CARD_H, + MAP_WAN_W, + MAP_SERVICE_COMPACT_W, computeNetworkMapLayout, MAP_SERVICE_NODE_H, MAP_SERVICE_NODE_W, @@ -80,12 +88,17 @@ import { StatusDot } from "@/components/status-dot" import { DownloadIcon, XIcon, LockIcon, LockOpenIcon, WifiIcon, RefreshCwIcon, ZoomInIcon, ZoomOutIcon, Maximize2Icon, SearchIcon, - LayersIcon, MapIcon, HomeIcon, TerminalIcon, ShieldIcon, + LayersIcon, FilterIcon, MapIcon, HomeIcon, TerminalIcon, ShieldIcon, CableIcon, ActivityIcon, } from "lucide-react" import { cn } from "@/lib/utils" import { formatServicePathLabel, formatServicePathTitle } from "@/lib/format-service-path-label" import Link from "next/link" +import { MapBottomPanel, MapTimeline, type MapBottomTab, type MapEventRow } from "@/components/network-map/map-bottom-panel" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { Badge } from "@/components/reui/badge" +import { listEvents } from "@/shared/api/events" +import type { EventItem } from "@mmapp/contracts/events" import { Flag, countryName } from "@/components/flag" // ─── Resource metrics (для мини-блока справа; числа детерминированы по id узла) ─ @@ -582,7 +595,7 @@ function SvgTooltip({ n }: { n: Server & { x: number; y: number } }) { const ss = STATUS_STYLE[n.status] const ts = TYPE_STYLE[n.type] const lc = latencyColor(n.latency) - const ox = n.x + ts.r + 14 + const ox = n.x + MAP_CARD_W / 2 + 12 const oy = n.y - 32 const lines = [ n.name, @@ -610,11 +623,18 @@ function SvgTooltip({ n }: { n: Server & { x: number; y: number } }) { ) } -function ServerNode({ labelScale = 1, n, isSel, isVis, isDragged, hideCatalogLatency, onClick, onDblClick, onHoverChange, onContextMenu, onPointerDown }: { +const STATUS_DOT: Record = { + online: "var(--success)", + degraded: "var(--warning)", + offline: "var(--destructive)", + unknown: "var(--muted-foreground)", +} + +/** Карточка устройства макета v3: плитка роли, точка статуса, имя, задержка и площадка, флаг. */ +function ServerNode({ n, isSel, isVis, isDragged, hideCatalogLatency, onClick, onDblClick, onHoverChange, onContextMenu, onPointerDown }: { n: Server & { x: number; y: number } - labelScale?: number isSel: boolean; isVis: boolean; isDragged: boolean - /** Не дублировать «N мс» из каталога, если на карте уже показаны метрики GRE (оранжевые числа в круге). */ + /** Не дублировать «N мс» из каталога, если на карте уже показаны метрики GRE. */ hideCatalogLatency?: boolean onClick: () => void onDblClick: () => void @@ -622,9 +642,15 @@ function ServerNode({ labelScale = 1, n, isSel, isVis, isDragged, hideCatalogLat onContextMenu: (e: React.MouseEvent) => void onPointerDown: (e: React.PointerEvent) => void }) { - const ss = STATUS_STYLE[n.status] const ts = TYPE_STYLE[n.type] - + const hw = MAP_CARD_W / 2 + const hh = MAP_CARD_H / 2 + const border = n.status === "degraded" + ? "color-mix(in oklch, var(--warning) 45%, transparent)" + : n.status === "offline" ? "color-mix(in oklch, var(--destructive) 45%, transparent)" : "var(--border)" + const sub = [hideCatalogLatency ? null : n.latency == null ? "—" : `${n.latency} мс`, n.site || n.country?.toUpperCase() || null].filter(Boolean).join(" · ") + const iso = n.country?.trim() + const name = shortName(n.name, 22) return ( {if(e.key==="Enter"||e.key===" "){e.preventDefault();e.stopPropagation();onClick()}}} @@ -638,76 +664,15 @@ function ServerNode({ labelScale = 1, n, isSel, isVis, isDragged, hideCatalogLat onMouseEnter={() => onHoverChange(true)} onMouseLeave={() => onHoverChange(false)} > - - {n.status === "online" && isVis && ( - - - )} - {n.status === "degraded" && isVis && ( - - )} - {isSel && ( - - )} - - - - {ts.label} - - {n.country?.trim() ? ( - - {/* Внутри foreignObject Tailwind не всегда применяется к тексту — явные стили, без lineHeight:0 (иначе подпись пропадает). */} -
)} - > - - 32 ? 18 : 16} /> - - 32 ? 13 : 11, - color: "var(--foreground)", - lineHeight: 1.25, - }} - > - {n.site || n.country?.toUpperCase() || "—"} - -
-
- ) : ( - 32 ? "13" : "11"} fontWeight="700" - fill="var(--foreground)" fontFamily="ui-monospace,monospace">{n.site || n.country?.toUpperCase() || "—"} - )} - {!hideCatalogLatency && ( - - {n.latency == null ? "—" : `${n.latency} мс`} - - )} - {(n.name && ( - {shortName(n.name,labelScale>1?12:24)} - ))} + + {isSel && } + + + {ts.label} + + 11 ? hw * 2 - 66 : undefined} lengthAdjust="spacingAndGlyphs">{name} + {iso ? : null} + {sub || "—"}
) } @@ -724,11 +689,20 @@ function ServiceNode({ iso, dim, shareLabel, + category, + rate, + compact, onClick, onPointerDown, }: { label: string share: number + /** Категория сервиса под названием (у страны — «Страна»). */ + category?: string + /** Скорость за окно NetFlow справа сверху. */ + rate?: string + /** Узкая строка: раскрытая страна показывает две колонки назначений. */ + compact?: boolean x: number y: number isSel: boolean @@ -743,8 +717,10 @@ function ServiceNode({ onClick: () => void onPointerDown: (e: React.PointerEvent) => void }) { - const bw = MAP_SERVICE_NODE_W + const bw = compact ? MAP_SERVICE_COMPACT_W : MAP_SERVICE_NODE_W const bh = MAP_SERVICE_NODE_H + const hw = bw / 2 + const barW = bw - 72 const flagIso = destMode === "countries" && iso && iso !== "Прочее" ? iso : "" return ( { e.stopPropagation(); onClick() }} > {`${label} · ${serviceSharePct(share)} ${shareLabel ?? "payload окна"}`} - - {isSel && ( - - )} - - + + {isSel && } + + + {flagIso ? : - - {label} - - - {serviceSharePct(share)} - + {shortName(label, compact ? 8 : 18)} + {compact ? serviceSharePct(share) : category || (destMode === "countries" ? "Страна" : "Сервис")} + {!compact && rate ? {rate} : null} + {!compact ? {serviceSharePct(share)} : null} + + ) } @@ -864,7 +820,7 @@ function WanSatNode({ x, y, wan, color, active, isSel, isDragged, onSelect, onPo onSelect: () => void onPointerDown: (e: React.PointerEvent) => void }) { - const r = 18 + const hw = MAP_WAN_W / 2 return ( {if(e.key==="Enter"||e.key===" "){e.preventDefault();e.stopPropagation();onSelect()}}} @@ -872,29 +828,16 @@ function WanSatNode({ x, y, wan, color, active, isSel, isDragged, onSelect, onPo style={{ cursor: isDragged ? "grabbing" : "grab" }} onPointerDown={e => { e.stopPropagation(); onPointerDown(e) }} onClick={e => { e.stopPropagation(); onSelect() }}> - - {active && ( - - - )} - {isSel && ( - - )} - - - - - + + {isSel && } + + + + - {wan.name} - - {wan.isp.length > 10 ? wan.isp.slice(0, 9) + "…" : wan.isp} - - - ↓{wan.maxDl} ↑{wan.maxUl} - + + {shortName(wan.isp || wan.name, 12)} + {shortName(wan.name, 8)} · ↓{wan.maxDl} ) } @@ -1123,6 +1066,19 @@ function NetworkMapContent() { const [flowListener,setFlowListener]=useState(false) const [flowLoading,setFlowLoading]=useState(false) const [flowRefresh,setFlowRefresh]=useState(0) + const [bottomTab, setBottomTab] = useState("flows") + const [mapEvents, setMapEvents] = useState(null) + const [eventsError, setEventsError] = useState(null) + const [eventsAt, setEventsAt] = useState(() => Date.now()) + const [showFilter, setShowFilter] = useState(false) + useEffect(() => { + if (!useLiveData) return + let cancelled = false + listEvents(backendUrl, { limit: 50 }) + .then(rows => { if (!cancelled) { setMapEvents(rows); setEventsError(null); setEventsAt(Date.now()) } }) + .catch(error => { if (!cancelled) setEventsError(error instanceof Error ? error.message : "не удалось загрузить") }) + return () => { cancelled = true } + }, [useLiveData, backendUrl, flowRefresh]) const [dnsError,setDnsError]=useState(null) const [dataError, setDataError] = useState(null) const [dataLoading, setDataLoading] = useState(false) @@ -1250,7 +1206,6 @@ function NetworkMapContent() { const [zoom, setZoom] = useState(1) const [viewportHeight,setViewportHeight]=useState(H) const [canvasMeasured,setCanvasMeasured]=useState(false) - const [canvasWidth,setCanvasWidth]=useState(W) const [isDragging, setIsDragging] = useState(false) // ── Interaction ───────────────────────────────────────────────────────────── @@ -1660,7 +1615,7 @@ function NetworkMapContent() { const svgRef = useRef(null) const canvasRef=useRef(null) const initialFit=useRef(false) - useEffect(()=>{const element=canvasRef.current;if(!element)return;const observer=new ResizeObserver(entries=>{const {width,height}=entries[0].contentRect;if(width<=0||height<=0)return;setViewportHeight(W*height/width);setCanvasWidth(width);setCanvasMeasured(true)});observer.observe(element);return()=>observer.disconnect()},[]) + useEffect(()=>{const element=canvasRef.current;if(!element)return;const observer=new ResizeObserver(entries=>{const {width,height}=entries[0].contentRect;if(width<=0||height<=0)return;setViewportHeight(W*height/width);setCanvasMeasured(true)});observer.observe(element);return()=>observer.disconnect()},[]) // Canvas pan drag const dragRef = useRef<{ @@ -1751,7 +1706,7 @@ function NetworkMapContent() { setZoom(newZoom) },[zoom,viewportHeight]) - const {pan:{x:fitX,y:fitY},zoom:fitZoom}=fitNetworkMapCamera([...Object.values(nodePosById),...Object.values(effectiveSatPos).flat(),...Object.values(servicePosById),...Object.values(nestedPosById)],W,viewportHeight) + const {pan:{x:fitX,y:fitY},zoom:fitZoom}=fitNetworkMapCamera([...Object.values(nodePosById),...Object.values(effectiveSatPos).flat(),...Object.values(servicePosById).map(p=>({x:p.x+(expandedCountryGroup?MAP_SERVICE_COMPACT_W:MAP_SERVICE_NODE_W)/2-100,y:p.y})),...Object.values(nestedPosById).map(p=>({x:p.x+MAP_SERVICE_COMPACT_W/2-100,y:p.y}))],W,viewportHeight) function fitView(){setPan({x:fitX,y:fitY});setZoom(fitZoom)} useEffect(()=>{if(initialFit.current||!canvasMeasured||!mapServers.length)return;initialFit.current=true;queueMicrotask(()=>{setPan({x:fitX,y:fitY});setZoom(fitZoom)})},[canvasMeasured,mapServers.length,fitX,fitY,fitZoom]) @@ -2042,53 +1997,99 @@ function NetworkMapContent() { // ═════════════════════════════════════════════════════════════════════════ + // Подписи связей (RTT, NetFlow) рисуются после карточек, чтобы карточка не перекрывала метку. + const linkBadgeLayer: React.ReactNode[] = [] + + // ── Рабочая панель под картой: потоки, RTT каналов, назначения, события + const rateOf = (bytes: number, bps: number) => formatNetflowRate({ bytes, bps, bpsFwd: bps, bpsRev: 0 }) + const eventTone = (level: "critical" | "warning" | "info") => level === "critical" ? { tone: "er" as const, label: "Сбой" } : level === "warning" ? { tone: "wn" as const, label: "Внимание" } : { tone: "in" as const, label: "Инфо" } + const unitMs: Record = { м: 60_000, ч: 3_600_000, д: 86_400_000 } + const eventRows: MapEventRow[] = (useLiveData + ? (mapEvents ?? []).map(e => ({ id: e.id, ts: Date.parse(e.createdAt), ...eventTone(e.level), title: e.title, message: e.message })) + : mockSystemEvents.map(e => { + const m = /^(\d+)([мчд])$/.exec(e.when) + return { id: e.id, ts: eventsAt - (m ? Number(m[1]) * unitMs[m[2]] : 0), ...eventTone(e.sev === "destructive" ? "critical" : e.sev), title: e.title, message: e.message } + }) + ).filter(e => Number.isFinite(e.ts)).sort((a, b) => b.ts - a.ts) + const flowRows = [...destPaths].sort((a, b) => b.bps - a.bps).slice(0, 100).map(p => ({ + id: servicePathKey(p), + client: p.clientName || p.viaName || p.viaId, + exit: p.enName || p.enId, + dest: destDisplayLabel(destNodes.find(svc => svc.id === p.serviceId), destMode, p.serviceId), + rate: rateOf(p.bytes, p.bps), + volume: formatBytes(p.bytes), + hl: Boolean(selected && (p.viaId === selected.id || p.enId === selected.id)) || selectedService?.id === p.serviceId, + })) + const rttRows = greEdges.map(e => { + const key = greEdgeKey(e) + const merged = mergeGreMetricsWithSpeedProbe(speedProbeByTunnelId.get(key), greTunnelProbe(e.tunnel, !useLiveData)) + return { + id: key, + name: e.tunnel.name, + route: `${e.fromServer.name} → ${e.toServer.name}`, + rtt: merged.pingMs != null ? `${merged.pingMs} мс` : "—", + speed: merged.dlMbps != null && merged.ulMbps != null ? `${merged.dlMbps} / ${merged.ulMbps} Мбит/с` : "—", + tone: e.tunnel.status === "up" ? "ok" as const : e.tunnel.status === "degraded" ? "wn" as const : "er" as const, + status: e.tunnel.status === "up" ? "Работает" : e.tunnel.status === "degraded" ? "Деградация" : "Недоступен", + hl: selected ? e.fromServer.id === selected.id || e.toServer.id === selected.id : selectedGreEdge ? greEdgeKey(selectedGreEdge) === key : false, + } + }) + const destRows = destNodes.map(svc => ({ + id: svc.id, + label: destDisplayLabel(svc, destMode, svc.id), + category: destMode === "countries" ? "Страна" : svc.category, + rate: rateOf(svc.bytes, svc.bps), + share: svc.share, + hl: selectedService?.id === svc.id || Boolean(selected && destEdges.some(edge => edge.fromId === selected.id && edge.toId === svc.id)), + })) + const bottomStat = `Окно ${Math.round(mapWindowSec / 60)} мин${flowReadAt ? " · " + new Date(flowReadAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }) : ""}${selected || selectedService || selectedGreEdge ? " · строки выбранного объекта подсвечены" : ""}` + return (
- - {useLiveData && ( - + )} + - )} - - - } - /> + + } + /> + 0 ? mapTotalBytes : useLiveData && flowReadAt ? 0 : null} + windowSec={mapWindowSec} + filter={filter} + onFilter={(key) => setFilter(key)} + onSelect={(server) => { setSelectedGreEdge(null); setSelectedService(null); setSelected(server) }} + /> {urlState.server&&((hasSnapshot||!useLiveData)&&!selected||selected&&selWanIdx!==null&&!selected.wanUplinks?.[selWanIdx])&&Объект карты недоступен{!selected?"Устройство "+urlState.server+" отсутствует в текущем снимке.":"Запрошенный WAN отсутствует у выбранного устройства."}} - + - {/* Filter pills */} -
- {filterBtns.map(b => ( - - ))} -
- {/* Search */}
-
- + {/* Вид карты */} +
+ {([ + { value: "all" as const, label: "Вся сеть" }, + { value: "ix-node" as const, label: "IX и клиенты" }, + ]).map((b) => ( + + ))} +
+ {/* Dest overlay: services vs countries */}
{([ @@ -2122,6 +2142,40 @@ function NetworkMapContent() { ))}
+ {/* Фильтр статуса и роли */} + + + + + +