Compare commits

...
8 Commits
Author SHA1 Message Date
DenozordecandClaude Opus 5.5 c94d417f1b feat(ui): перенести пилотные разделы на макет v3
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m53s
Docker images / frontend-image (push) Successful in 2m15s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 1m54s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
Слияние ветки claude/sad-bassi-fe48a8: этап 0 и пилот интеграции макета v3.

- оболочка: inset-сайдбар, крошки «Главная / …», заголовок страницы
  и индикатор свежести данных; общие блоки reui-kit/ops-blocks;
- дашборд: ёмкость, показатели со спарклайнами, сводка источников,
  вкладки «Обзор / Источники и время получения / История RTT»;
- статистика: вкладки «Обзор / Сводная (куб) / Срезы», демо-куб;
- трафик: вкладки разделов, детали с периодом и скоростями,
  «Доля RX», «Интерфейсы сервера»;
- карта сети: колонки макета, карточки узлов, KPI-полоса, панель
  объекта с вкладками, «Момент времени» и рабочая панель снизу.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 21:30:25 +07:00
Denozordec 63c0fc6506 fix(ix): ограничивать размер сегмента TCP для туннелей VPS
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Successful in 10m38s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m2s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-11-25 19:29:56 +07:00
DenozordecandClaude Opus 5.5 dd6e6b0b77 feat(ui): разделы карты сети по макету v3
- панель инструментов: поиск первым, вид «Вся сеть / IX и клиенты»,
  «Сервисы / Страны», окно «Фильтр» со статусами и ролями, справа
  «Слои» и «Легенда»;
- панель объекта: шапка с плиткой роли, адресом и статусом, вкладки
  «Обзор» (RTT, сессии, входящий/исходящий трафик, устройство,
  назначения через узел, ресурсы, действия), «Интерфейсы» (WAN-аплинки
  и трафик интерфейсов за окно NetFlow) и «GRE»;
- «Момент времени» под картой: инциденты из ленты событий за 24 часа
  и метка Live; архив снимков карты бэкенд не хранит;
- рабочая панель под картой: вкладки «Потоки NetFlow», «RTT каналов»,
  «Назначения» и «События», строки выбранного объекта подсвечены;
- на телефоне окно легенды растягивается по ширине экрана.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-25 00:08:07 +07:00
DenozordecandClaude Opus 5.5 a4694b8481 feat(ui): перерисовать карту сети по колонкам макета v3
- полосы Home Router · WAN · JumpHost · Exit (и IX) · назначения
  с заголовками и счётчиками; WAN-аплинки в своей колонке и не
  наезжают друг на друга;
- узлы — карточки 160×56 с плиткой роли, точкой статуса, именем,
  задержкой, площадкой и флагом; длинное имя ужимается, а не обрезается;
- WAN — «таблетки», назначения — строки с иконкой, категорией,
  скоростью, долей и полосой; при раскрытой стране обе колонки компактные;
- связи — горизонтальные кривые между гранями карточек; подписи RTT
  и NetFlow рисуются поверх карточек и остаются кликабельными;
- легенда — выпадающее окно кнопки «Легенда» в панели инструментов,
  закрыта по умолчанию;
- масштаб, перетаскивание, миникарта, клавиатура и экспорт SVG сохранены;
  ревизия раскладки 8 сбрасывает старые ручные позиции.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 23:41:56 +07:00
DenozordecandClaude Opus 5.5 640726aa86 fix(ui): доводка трафика и карты сети по макету v3
- карта: счётчики онлайн/с проблемами/оффлайн остались только в KPI-полосе,
  подпись NetFlow описывает среднюю скорость всех потоков окна,
  у кнопок статусов читаемое имя «Оффлайн 1»;
- трафик: детали клиента и интерфейса показывают скорости двумя колонками,
  как у сервера; на странице и в панели потоков нет текста мельче text-xs;
- e2e: «Объяснить» открывает вкладку источников с баннером
  «Не обновлены источники», счётчик оффлайн проверяется в KPI-полосе.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 23:10:54 +07:00
DenozordecandClaude Opus 5.5 67b1d9cde2 feat(ui): перенести трафик и карту сети на макет v3
Трафик: шапка деталей с названием, статусом и сегментным периодом;
текущие и пиковые скорости двумя колонками; блоки «Доля RX» и
«Интерфейсы сервера»; сегментная сортировка и поле поиска как в макете;
в карточках списка нет текста мельче text-xs.

Карта сети: KPI-полоса над картой (узлы со статусами-фильтрами,
GRE-туннели, NetFlow за окно, узлы, требующие внимания), прокручиваемая
страница с картой фиксированной высоты, поиск в стиле макета.
На узких экранах KPI-полоса уходит под карту, чтобы карта помещалась
в экран и работал жест панорамирования.

Скриншоты docs/ux-ui обновлены прогоном e2e пилота.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:56:03 +07:00
DenozordecandClaude Opus 5.5 8781f68674 fix(ui): демо-куб статистики и честная подпись фактора здоровья
Без живого API статистика показывает демо-куб вместо пустого состояния,
как в макете v3. Фактор «Задержка (RTT)» переименован в «Пробы в норме»:
его полоса — доля проб в норме, а не задержка.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:31:02 +07:00
DenozordecandClaude Opus 5.5 5fd028800a feat(ui): перенести дашборд, статистику и трафик на макет v3
Этап 0 и пилот интеграции макета v3:
- оболочка: inset-сайдбар, крошки «Главная / … /», индикатор свежести,
  заголовок страницы PageTitle;
- общие блоки reui-kit/ops-blocks: SectionFrame, CapacityGrid, SparkKpiGrid,
  ToneBadge;
- дашборд: ёмкость, показатели со спарклайнами, сводка источников,
  вкладки «Обзор / Источники и время получения / История RTT»,
  здоровье сети, лента инцидентов, схема Internet path, сводка маршрута,
  таблица «Требует внимания», настройка видимости виджетов;
- статистика: вкладки «Обзор / Сводная (куб) / Срезы», доли объёма;
- трафик: вкладки разделов со счётчиками, рамки списка и деталей,
  кнопка «Месячный отчёт».

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 22:23:16 +07:00
53 changed files with 2884 additions and 2021 deletions

No files matched your search

+394 -306
View File
@@ -1,349 +1,437 @@
"use client" "use client"
import { useState } from "react" import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import Link from "next/link" import Link from "next/link"
import { import {
ActivityIcon,
BellIcon,
CableIcon, CableIcon,
FilterIcon, ChartColumnIcon,
GitMergeIcon, CircleAlertIcon,
HardDriveIcon,
HeartPulseIcon, HeartPulseIcon,
MapIcon, LayoutDashboardIcon,
ServerIcon, ServerIcon,
ShieldIcon, SlidersHorizontalIcon,
TableIcon,
} from "lucide-react" } 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 { PageHeader } from "@/components/page-header"
import { OpsPanel } from "@/components/ops-panel" import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { DataFreshness } from "@/components/data-freshness"
import { QuickActionGrid } from "@/components/reui-kit/quick-action-grid" import { EmptyState } from "@/components/empty-state"
import { AttentionQueue } from "@/components/reui-kit/attention-queue" 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 { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
import { LatencyChart } from "@/components/dashboard/latency-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 { 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 { 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 { 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" 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<Set<Widget>>(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 { function fmtIntRu(n: number): string {
return n.toLocaleString("ru-RU") return n.toLocaleString("ru-RU")
} }
function AttentionRows({ rows }: { rows: AttentionRow[] }) { function averageSeries(series: Record<string, (number | null)[]>): number[] {
const [expanded,setExpanded]=useState(false) const rows = Object.values(series)
const [visible,setVisible]=useState(55) const length = Math.max(0, ...rows.map((values) => values.length))
function renderRow(row: AttentionRow) { const out: number[] = []
return ( for (let i = 0; i < length; i++) {
<Link const values = rows.map((row) => row[i]).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
key={row.id} if (values.length) out.push(values.reduce((sum, v) => sum + v, 0) / values.length)
href={row.href}
className="hover:bg-muted/40 focus-visible:ring-ring flex min-w-0 items-start justify-between gap-2 rounded-md px-1 py-1.5 focus-visible:ring-2"
>
<span className="min-w-0 wrap-anywhere text-sm font-medium">{row.title}</span>
<Badge
size="sm"
variant={row.tone === "warning" ? "warning-light" : "destructive-light"}
className="shrink-0"
>
{row.hint}
</Badge>
</Link>
)
} }
return out
}
return ( function toGridRows(rows: AttentionRow[], kind: AttentionGridRow["kind"]): AttentionGridRow[] {
<div className="flex flex-col gap-0.5"> return rows.map((row) => ({
{rows.slice(0, 5).map(renderRow)} id: row.id,
{rows.length > 5 && ( title: row.title,
<details onToggle={event=>{setExpanded(event.currentTarget.open);if(!event.currentTarget.open)setVisible(55)}}> kind,
<summary className="cursor-pointer rounded-md px-1 py-2 text-xs text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring">Ещё {rows.length - 5}</summary> hint: row.hint,
{expanded && rows.slice(5,visible).map(renderRow)} href: row.href,
{expanded && rows.length>visible && <Button type="button" variant="ghost" size="sm" onClick={()=>setVisible(count=>Math.min(count+50,rows.length))}>Показать ещё {Math.min(50,rows.length-visible)}</Button>} tone: row.tone === "destructive" ? "er" : "wn",
</details> confirmed: row.hint !== "Статус неизвестен",
)} }))
</div>
)
} }
export default function DashboardPage() { export default function DashboardPage() {
const dash = useDashboardLive() 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 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" ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : dash.latency.kind === "empty" ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p>
) : (
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} />
)
const latencyDescription = dash.latency.kind === "mock" || dash.latency.kind === "live" ? dash.latency.subtitle : dash.latency.kind === "loading" ? "Загрузка…" : "Нет серии RTT"
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageHeader crumbs={[{ label: "Обзор" }, { label: "Дашборд" }]} /> <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Дашборд" }]} status={<DataFreshness at={freshAt} live={dash.isLive} />} />
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto">
<div className="flex flex-col gap-4 px-4 py-4 md:gap-6 md:px-6 md:py-5"> <div className="flex flex-col gap-6 px-4 pt-5 pb-10 md:px-7 md:pt-6">
{dash.isLive && <DashboardDataStatus sources={dash.sources} refreshing={dash.refreshing} onRefresh={dash.retry} />} <PageTitle
icon={<LayoutDashboardIcon />}
<KpiStatGrid title="Дашборд"
aria-label="Сводка дашборда" description="Здоровье сети: индекс, события за период, Internet path, пробы и источники"
isLoading={dash.loading} actions={
items={[ <>
{ <DropdownMenu>
id: "fleet", <DropdownMenuTrigger render={<Button type="button" variant="outline"><SlidersHorizontalIcon data-icon="inline-start" />Настроить виджеты</Button>} />
label: "Серверы онлайн", <DropdownMenuContent align="end" className="w-60">
value: dash.availability.servers ? `${dash.onlineCount} / ${dash.totalServers}` : "—", <DropdownMenuGroup>
hint: !dash.availability.servers ? "нет данных" : !dash.isLive <DropdownMenuLabel>Виджеты дашборда</DropdownMenuLabel>
? "демо" {(Object.keys(WIDGETS) as Widget[]).map((key) => (
: offline > 0 || dash.unknownServerCount > 0 || dash.degradedServerCount > 0 <DropdownMenuCheckboxItem key={key} checked={show(key)} onCheckedChange={(value) => toggle(key, !!value)}>
? [offline > 0 ? `${offline} не в сети` : null,dash.unknownServerCount > 0 ? `Статус неизвестен: ${dash.unknownServerCount}` : null,dash.degradedServerCount > 0 ? `Ухудшение: ${dash.degradedServerCount}` : null].filter(Boolean).join(" · ") {WIDGETS[key]}
: dash.totalServers > 0 </DropdownMenuCheckboxItem>
? "все в сети" ))}
: "нет серверов", </DropdownMenuGroup>
href: "/servers", </DropdownMenuContent>
icon: <ServerIcon />, </DropdownMenu>
iconClassName: "text-muted-foreground", <Button type="button" onClick={dash.retry} disabled={dash.refreshing}>Обновить данные</Button>
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: <CableIcon />,
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: <GitMergeIcon />,
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: <BellIcon />,
iconClassName: health > 0 ? "text-destructive" : "text-muted-foreground",
variant: health > 0 ? "destructive" : "default",
},
]}
/> />
<section aria-labelledby="dashboard-attention-title" className="flex min-w-0 flex-col gap-2"> <div className="flex flex-col gap-5">
<h2 id="dashboard-attention-title" className="text-sm font-semibold">Требует внимания</h2> {failedSources.length > 0 ? (
<AttentionQueue <Alert variant="warning">
className="lg:grid-cols-3" <CircleAlertIcon />
columns={[ <AlertTitle>Не все источники доступны.</AlertTitle>
{ <AlertDescription>
id: "nodes", Последний успешный снимок; не все источники обновлены. Не обновлены: {failedSources.map((row) => row.name).join(", ")}. Проверьте состояние источников ниже.
title: "Серверы", </AlertDescription>
icon: ServerIcon, <AlertAction>
count: dash.attentionServers.length, <Button type="button" size="sm" variant="outline" onClick={() => setTab("src")}>Объяснить</Button>
countVariant: "warning-light", </AlertAction>
emptyTitle: dash.reliable.servers ? (dash.totalServers > 0 ? "Серверы без проблем" : "Нет серверов") : "Состояние не подтверждено", </Alert>
emptyDescription: dash.reliable.servers ? "Нет включённых серверов с ошибками доступности." : "Проверьте состояние источников выше.", ) : null}
children: <AttentionRows rows={dash.attentionServers} />,
},
{
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: <AttentionRows rows={dash.attentionOverlay} />,
},
{
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: <AttentionRows rows={dash.attentionProbes} />,
},
]}
/>
</section>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[2fr_1fr]"> {show("cap") ? (
<OpsPanel <CapacityGrid
title="Задержка до серверов" label="Ёмкость сети"
description={ items={[
dash.latency.kind === "mock" || dash.latency.kind === "live" {
? dash.latency.subtitle id: "fleet",
: dash.latency.kind === "loading" title: "Серверы онлайн",
? "Загрузка…" caption: serverCaption,
: "Нет серии RTT" value: dash.availability.servers ? dash.onlineCount : null,
} total: dash.availability.servers ? dash.totalServers : null,
contentClassName="px-3 pb-3" tone: serverTrouble ? "wn" : "ok",
> icon: <ServerIcon />,
{dash.latency.kind === "loading" && ( href: "/servers",
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" /> },
)} {
{dash.latency.kind === "empty" && ( id: "overlay",
<p className="text-muted-foreground px-4 py-10 text-center text-sm">{dash.latency.message}</p> title: "Туннели работают",
)} caption: !dash.availability.overlay ? "не все источники доступны" : !dash.reliable.overlay ? "Последний успешный снимок; не все источники обновлены" : dash.overlay.total > 0 ? `GRE · WireGuard · VXLAN · не работают: ${dash.overlay.down}` : "нет туннелей",
{(dash.latency.kind === "mock" || dash.latency.kind === "live") && ( value: dash.availability.overlay ? dash.overlay.up : null,
<LatencyChart series={dash.latency.series} labels={dash.latency.labels} /> total: dash.availability.overlay ? dash.overlay.total : null,
)} tone: dash.overlay.down > 0 ? "wn" : "ok",
</OpsPanel> icon: <CableIcon />,
href: "/gre",
<OpsPanel },
title="Последние события" {
description="Система и BGP" id: "health",
headerRight={ title: "Проверки с проблемами",
<Link href="/alerts" className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 text-xs")}> caption: dash.availability.probes ? `${dash.probeDown} ошибок · ${dash.probeWarn} предупреждений${dash.unknownProbeCount > 0 ? ` · неизвестны: ${dash.unknownProbeCount}` : ""}` : "нет данных",
Все → value: dash.availability.probes && dash.unknownProbeCount === 0 ? problems : null,
</Link> total: dash.availability.probes && dash.unknownProbeCount === 0 ? dash.probeCount : null,
} tone: problems > 0 ? "er" : "ok",
> icon: <HeartPulseIcon />,
<DashboardEventsTimeline href: "/uptime",
events={dash.recentEvents} },
loading={dash.eventsLoading} ]}
error={dash.eventsError}
/> />
</OpsPanel> ) : null}
</div>
<div> {show("spark") ? (
<OpsPanel <SparkKpiGrid
title="Пропускная способность" label="Показатели сети"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"} items={[
headerRight={<Link href="/traffic" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>Трафик →</Link>} {
contentClassName="px-3 pb-3" id: "bgp",
> title: "Префиксы BGP",
{dash.loading && !dash.traffic ? ( value: dash.bgp?.prefixSum != null ? fmtIntRu(dash.bgp.prefixSum) : "—",
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" /> footnote: dash.bgp ? `Сессий установлено: ${dash.bgp.establishedCount ?? "неизвестно"}${dash.bgp.prefixSum === null ? " · префиксы неизвестны" : ""}` : "нет данных",
) : !dash.traffic ? ( href: "/bgp",
<p className="text-muted-foreground px-4 py-10 text-center text-sm"> },
Нет данных трафика за последний час.{" "} {
<Link href="/traffic" className="underline underline-offset-2"> id: "rtt",
Открыть трафик title: "Средний RTT",
</Link> value: rttNow ?? "—",
</p> unit: rttNow != null ? " мс" : undefined,
) : ( series: latencySeries,
<> delta: seriesDelta(latencySeries, "wn", "ok"),
<div className="flex flex-wrap items-center gap-3 px-2 py-3 text-xs"> footnote: "за 1 ч",
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null} href: "/uptime",
<span className="tabular-nums">RX {dash.traffic.rxNow===null?"—":fmtRate(dash.traffic.rxNow)}</span> },
<span className="tabular-nums">TX {dash.traffic.txNow===null?"—":fmtRate(dash.traffic.txNow)}</span> {
id: "rx",
title: "RX",
value: dash.traffic?.rxNow != null ? fmtRate(dash.traffic.rxNow) : "—",
series: dash.traffic?.rx.filter((v): v is number => 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") ? <DashboardSourcesSummary rows={sourceRows} refreshing={dash.refreshing} onRefresh={dash.retry} /> : null}
<Tabs value={tab} onValueChange={(value) => setTab(String(value))} className="gap-5">
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
<TabsTrigger value="over" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">Обзор</TabsTrigger>
<TabsTrigger value="src" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">
Источники и время получения
<Badge variant="secondary" className="font-mono">{sourceRows.length}</Badge>
</TabsTrigger>
<TabsTrigger value="rtt" className="h-auto flex-none px-3 py-2.5 after:bottom-[-1px]">История RTT</TabsTrigger>
</TabsList>
<TabsContent value="over" className="flex flex-col gap-5">
{show("health") ? (
<DashboardHealth
factors={[
{ label: "Потери пакетов", value: avgLoss == null ? "—" : `${avgLoss.toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`, ratio: probesMeasured.length ? probesMeasured.filter((p) => (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") ? <DashboardIncidents events={dash.recentEvents} loading={dash.eventsLoading} error={dash.eventsError} /> : null}
{show("path") ? <InternetPathPanel model={dash.internetPath} loading={dash.internetPathLoading} error={dash.isLive ? dash.internetPathError : null} /> : null}
{show("attention") ? <DashboardAttentionGrid rows={attentionRows} emptyNotes={emptyNotes} /> : null}
{show("latency") ? (
<SectionFrame title="Задержка до серверов" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
{latencyBody}
</SectionFrame>
) : null}
{show("traffic") ? (
<SectionFrame
title="Пропускная способность"
description={dash.traffic?.demo ? "Суммарный RX / TX · демо" : "Суммарная история RX / TX · 1 ч; значения — последний измеренный снимок"}
actions={<Link href="/traffic" className={buttonVariants({ variant: "outline", size: "sm" })}>Трафик →</Link>}
panelClassName="px-3.5 pt-3.5 pb-2"
>
{dash.loading && !dash.traffic ? (
<div className="bg-muted/50 h-[220px] w-full animate-pulse rounded-md" />
) : !dash.traffic ? (
<p className="text-muted-foreground px-4 py-10 text-center text-sm">
Нет данных трафика за последний час.{" "}
<Link href="/traffic" className="underline underline-offset-2">Открыть трафик</Link>
</p>
) : (
<>
<div className="flex flex-wrap items-center gap-3 px-1 pb-3 text-xs">
{dash.traffic.demo ? <Badge variant="outline" size="sm">демо</Badge> : !dash.traffic.observationsKnown ? <Badge variant="outline" size="sm">Измерения не подтверждены API</Badge> : null}
<span className="tabular-nums">RX {dash.traffic.rxNow === null ? "—" : fmtRate(dash.traffic.rxNow)}</span>
<span className="tabular-nums">TX {dash.traffic.txNow === null ? "—" : fmtRate(dash.traffic.txNow)}</span>
</div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded />
</>
)}
</SectionFrame>
) : null}
{show("probes") ? (
<SectionFrame
title="Активные пробы"
description={<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>}
icon={<TableIcon />}
actions={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Мониторинг →</Link>}
>
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
<EmptyState
className="py-10"
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
action={<Link href="/uptime" className={buttonVariants({ variant: "outline", size: "sm" })}>Открыть мониторинг</Link>}
/>
) : (
<DashboardActiveProbesDataGrid probes={dash.activeProbes} catalog={dash.servers} isLoading={dash.probesLoading} emptyDescription="Нет проб с звездой на дашборде." />
)}
</SectionFrame>
) : null}
{show("links") ? (
<DashboardQuickLinks
links={[
{ id: "traffic", title: "Трафик", description: "Приём, передача и потоки IPFIX", href: "/traffic" },
{ id: "map", title: "Карта сети", description: "Топология GRE и WAN", href: "/network-map" },
{ id: "filters", title: "Фильтры", description: "Правила обхода и списки · цепочки filter / nat", href: "/filters" },
{ id: "backups", title: "Бэкапы", description: "Снапшоты и расписание", href: "/backups" },
{ id: "uptime", title: "Мониторинг", description: "Сессии и префиксы · пробы", href: "/uptime" },
]}
/>
) : null}
</TabsContent>
<TabsContent value="src" className="flex flex-col gap-5">
{failedSources.length > 0 ? (
<Alert variant="destructive">
<CircleAlertIcon />
<AlertTitle>Не обновлены источники: {failedSources.length}</AlertTitle>
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
</Alert>
) : null}
<SectionFrame title="Источники и время получения" description="Каждый источник дашборда: состояние, время получения и замера" icon={<ChartColumnIcon />}>
<div className="overflow-x-auto">
<table className="w-full min-w-[640px] text-sm">
<thead className="bg-muted/55 text-muted-foreground text-xs">
<tr className="h-10 border-b text-left">
<th className="px-3.5 font-medium">Источник</th>
<th className="px-3 font-medium">Статус</th>
<th className="px-3 font-medium">Получено</th>
<th className="px-3 font-medium">Замер</th>
<th className="px-3 font-medium">Ошибка</th>
</tr>
</thead>
<tbody>
{sourceRows.map((row) => (
<tr key={row.key} className="h-[52px] border-b last:border-b-0">
<td className="px-3.5 font-mono text-[13px] font-medium">{row.name}</td>
<td className="px-3"><ToneBadge tone={row.tone as Tone}>{row.label}</ToneBadge></td>
<td className="px-3 font-mono text-[12.5px]">{row.receivedAt != null ? new Date(row.receivedAt).toLocaleString("ru-RU") : "—"}</td>
<td className="px-3 font-mono text-[12.5px]">{row.sampledAt ? new Date(row.sampledAt).toLocaleString("ru-RU") : "—"}</td>
<td className="text-muted-foreground px-3 text-xs">{sourceErrorText(row) ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</div> </div>
<TrafficRxTxChart rx={dash.traffic.rx} tx={dash.traffic.tx} range="1h" embedded /> </SectionFrame>
</> </TabsContent>
)}
</OpsPanel>
<TabsContent value="rtt" className="flex flex-col gap-5">
<SectionFrame title="История RTT по источникам" description={latencyDescription} panelClassName="px-3.5 pt-3.5">
{latencyBody}
</SectionFrame>
</TabsContent>
</Tabs>
</div> </div>
<InternetPathPanel
model={dash.internetPath}
loading={dash.internetPathLoading}
error={dash.isLive ? dash.internetPathError : null}
/>
<OpsPanel
title="Активные пробы"
description={
<span className={dash.error && dash.isLive ? "text-destructive" : undefined}>{dash.probesSubtitle}</span>
}
headerRight={
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}>
Мониторинг →
</Link>
}
contentClassName="px-0 pb-0"
>
{dash.activeProbes.length === 0 && !dash.probesLoading ? (
<EmptyState
className="py-10"
title={dash.availability.probes ? "Нет проб на дашборде" : "Данные проб недоступны"}
description={dash.availability.probes ? "Включите пробу и отметьте ★ на странице мониторинга." : "Повторите обновление данных."}
action={
<Link href="/uptime" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
Открыть мониторинг
</Link>
}
/>
) : (
<DashboardActiveProbesDataGrid
probes={dash.activeProbes}
catalog={dash.servers}
isLoading={dash.probesLoading}
emptyDescription="Нет проб с звездой на дашборде."
/>
)}
</OpsPanel>
<QuickActionGrid
title="Быстрые переходы"
description="Другие разделы управления сетью"
actions={[
{
id: "traffic",
title: "Трафик",
description: "Приём, передача и потоки IPFIX",
href: "/traffic",
icon: <ActivityIcon />,
iconClassName: "text-info",
},
{
id: "map",
title: "Карта сети",
description: "Топология GRE и WAN",
href: "/network-map",
icon: <MapIcon />,
iconClassName: "text-primary",
},
{
id: "filters",
title: "Фильтры",
description: "Правила обхода и списки",
href: "/filters",
icon: <FilterIcon />,
iconClassName: "text-info",
},
{
id: "firewall",
title: "Firewall",
description: "Цепочки filter / nat",
href: "/firewall",
icon: <ShieldIcon />,
iconClassName: "text-warning",
},
{
id: "backups",
title: "Бэкапы",
description: "Снапшоты и расписание",
href: "/backups",
icon: <HardDriveIcon />,
iconClassName: "text-muted-foreground",
},
{
id: "bgp",
title: "BGP",
description: "Сессии и префиксы",
href: "/bgp",
icon: <GitMergeIcon />,
iconClassName: "text-primary",
},
]}
/>
</div> </div>
</div> </div>
</div> </div>
+1 -1
View File
@@ -22,7 +22,7 @@ export default function MainLayout({ children }: { children: ReactNode }) {
К содержимому К содержимому
</a> </a>
<AppSidebar /> <AppSidebar />
<SidebarInset tabIndex={-1} id="main-content" className="h-svh overflow-hidden"> <SidebarInset tabIndex={-1} id="main-content" className="h-svh overflow-hidden md:h-[calc(100svh-1rem)] md:peer-data-[variant=inset]:rounded-[calc(var(--radius)*1.6)] md:peer-data-[variant=inset]:border">
{children} {children}
</SidebarInset> </SidebarInset>
<CommandPalette /> <CommandPalette />
File diff suppressed because it is too large. Load diff
+202 -168
View File
@@ -1,17 +1,22 @@
"use client" "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 { useSearchParams } from "next/navigation"
import { import {
ActivityIcon, ActivityIcon,
ChartColumnIcon,
DatabaseIcon, DatabaseIcon,
GaugeIcon, GaugeIcon,
GlobeIcon,
ServerIcon, ServerIcon,
UsersIcon, UsersIcon,
} from "lucide-react" } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { PageHeader } from "@/components/page-header" import { PageHeader } from "@/components/page-header"
import { PageTitle } from "@/components/page-title"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" 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 { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar" import { DataPageToolbar } from "@/components/data-page-toolbar"
import { SegmentedControl } from "@/components/form-kit" import { SegmentedControl } from "@/components/form-kit"
@@ -35,6 +40,7 @@ import {
} from "@/lib/statistics-dims" } from "@/lib/statistics-dims"
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context" import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
import { readStatisticsRange } from "@/lib/statistics-range" import { readStatisticsRange } from "@/lib/statistics-range"
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
import { useDataSource } from "@/lib/data-source" import { useDataSource } from "@/lib/data-source"
import { fmtBps, formatBytes } from "@/lib/fmt-rate" import { fmtBps, formatBytes } from "@/lib/fmt-rate"
import { import {
@@ -102,8 +108,13 @@ function readDim(sp: URLSearchParams): StatisticsSliceKind {
return t && isStatisticsSliceKind(t) ? t : "users" return t && isStatisticsSliceKind(t) ? t : "users"
} }
function readView(sp: URLSearchParams): "explore" | "pivot" { type StatisticsView = "overview" | "explore" | "pivot"
return sp.get("view") === "pivot" ? "pivot" : "explore"
/** Вкладка макета 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" { function readPlanes(sp: URLSearchParams): "unique" | "all" {
@@ -241,7 +252,9 @@ function StatisticsPageInner() {
const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams]) const pivotCol = useMemo(() => readPivotDim(searchParams, "pivotCol", "service"), [searchParams])
const [retry, setRetry] = useState(0) 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<{ const [result, setResult] = useState<{
key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null key: string; data: StatisticsDto; pivot: StatisticsPivotDto; error: string | null
} | null>(null) } | null>(null)
@@ -249,7 +262,9 @@ function StatisticsPageInner() {
const loading = isLive && !rangeError && !paramsError && current === null const loading = isLive && !rangeError && !paramsError && current === null
const error = rangeError ?? paramsError ?? current?.error ?? null const error = rangeError ?? paramsError ?? current?.error ?? null
const dataReady = isLive && current !== null && !error const dataReady = isLive && current !== null && !error
const pivot = dataReady ? current.pivot : EMPTY_PIVOT // Демо-режим без API: показываем демо-куб, чтобы раздел выглядел как с данными.
const demo = useMemo(() => (isLive || rangeError ? null : demoStatistics(range.from, range.to, planes)), [isLive, rangeError, range, planes])
const pivot = dataReady ? current.pivot : demo && !paramsError ? demoStatisticsPivot(pivotRow, pivotCol) : EMPTY_PIVOT
const updateParams = useCallback( const updateParams = useCallback(
(patch: Record<string, string | undefined>) => { (patch: Record<string, string | undefined>) => {
@@ -295,7 +310,7 @@ function StatisticsPageInner() {
const dto = await getStatistics(backendUrl, query) const dto = await getStatistics(backendUrl, query)
if (cancelled) return if (cancelled) return
let matrix = EMPTY_PIVOT let matrix = EMPTY_PIVOT
if (view === "pivot" && pivotRow !== pivotCol) { if (pivotView && pivotRow !== pivotCol) {
matrix = await getStatisticsPivot(backendUrl, { matrix = await getStatisticsPivot(backendUrl, {
...query, ...query,
row: pivotRow, row: pivotRow,
@@ -313,11 +328,11 @@ function StatisticsPageInner() {
return () => { return () => {
cancelled = true 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 viewData = dataReady ? current.data : demo && !paramsError ? demo : EMPTY
const sliced = hasAnySlice(slices) const sliced = hasAnySlice(slices)
const emptyCube = !isLive || (!loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0) const emptyCube = !loading && viewData.kpis.bytes === 0 && viewData.interfaces.length === 0
function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) { function handleRowClick(kind: StatisticsSliceKind, row: StatisticsBreakdownRow) {
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
@@ -348,175 +363,194 @@ function StatisticsPageInner() {
: sliced : sliced
? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов` ? `${STATISTICS_DIMS.filter((d) => !hiddenKinds(slices).has(d.id)).length} разрезов`
: `${rowsForKind(viewData, dim).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 = (
<SegmentedControl
value={planes}
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
options={[
{ value: "all", label: "Все плоскости" },
{ value: "unique", label: "GRE/WG клиентов" },
]}
/>
)
const cubeState = isLive && !dataReady ? (
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div>
) : emptyCube ? (
<EmptyState
title="Нет данных куба"
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год."
/>
) : null
const sliceChips = (
<SliceChips
chips={chips}
onRemove={(key) => {
const next = { ...slices }
delete next[key as keyof CubeSlices]
setSlices(next)
}}
/>
)
const filters = <StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />
const tabTrigger = "h-auto flex-none px-3 py-2.5 after:bottom-[-1px]"
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<PageHeader <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Статистика" }]} />
crumbs={[{ label: "Обзор", href: "/dashboard" }, { label: "Статистика" }]}
actions={rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
/>
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-4 py-4 md:gap-6 md:px-6 md:py-5"> <div className="flex flex-1 flex-col gap-6 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
{!isLive ? ( <PageTitle
<Alert> icon={<ChartColumnIcon />}
<AlertTitle>Живые данные выключены</AlertTitle> title="Статистика"
<AlertDescription> description="Куб NetFlow: измерения, срезы и период · уникальный объём без дублей"
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт. actions={
</AlertDescription> <>
</Alert> {rangeError ? <Button type="button" variant="outline" onClick={() => setRange(rangeForPreset("7d"))}>Выбрать последние 7 дней</Button> : <PeriodSelector range={range} onChange={setRange} />}
) : null} <Button type="button" variant="outline" onClick={resetContext} disabled={!hasContext}>Сбросить параметры отчёта</Button>
</>
}
/>
{error ? ( <div className="flex flex-col gap-5">
<Alert variant="destructive" role="alert"> {!isLive ? (
<AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle> <Alert variant="warning">
<AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}{paramsError && <Button type="button" variant="outline" size="sm" onClick={() => updateParams(Object.fromEntries(STATISTICS_CONTEXT_KEYS.map(key => [key, undefined])))}>Сбросить параметры отчёта</Button>}</AlertDescription> <AlertTitle>Живые данные выключены</AlertTitle>
</Alert> <AlertDescription>
) : null} Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
</AlertDescription>
</Alert>
) : null}
{!slices.serverId && dataReady && !emptyCube ? ( {error ? (
<Alert> <Alert variant={paramsError ? "warning" : "destructive"} role="alert">
<AlertTitle>Уникальный объём</AlertTitle> <AlertTitle>{rangeError ? "Некорректный период" : paramsError ? "Параметры отчёта требуют внимания" : "Ошибка загрузки"}</AlertTitle>
<AlertDescription> <AlertDescription>{error}{!rangeError && !paramsError && <Button type="button" variant="outline" size="sm" onClick={() => setRetry(n => n + 1)}>Повторить загрузку</Button>}</AlertDescription>
Объём — трафик клиентов на GRE/WG, без повторного учёта JH↔EN и WAN. </Alert>
</AlertDescription> ) : null}
</Alert>
) : null}
{(dataReady || loading) && <KpiStatGrid {(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
aria-label="Сводка трафика" aria-label="Сводка трафика"
isLoading={loading} isLoading={loading}
skeletonCount={5} skeletonCount={4}
items={[ items={[
{ {
id: "bytes", id: "bytes",
label: "Объём", label: planes === "all" ? "Объём" : "Уникальный объём",
value: formatBytes(kpis.bytes), value: formatBytes(kpis.bytes),
hint: "GRE/WG клиентов, без hops", hint: slices.serverId ? (kpis.ifaces ? `${kpis.ifaces} iface` : undefined) : planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay",
icon: <DatabaseIcon />, icon: <DatabaseIcon />,
iconClassName: "text-muted-foreground", iconClassName: planes === "all" ? "text-muted-foreground" : "text-success",
}, },
{ {
id: "packets", id: "packets",
label: "Пакеты", label: "Пакеты",
value: kpis.packets.toLocaleString("ru-RU"), value: kpis.packets.toLocaleString("ru-RU"),
hint: kpis.topService ? `топ: ${kpis.topService}` : undefined, hint: kpis.topService ? `топ: ${kpis.topService}` : undefined,
icon: <ActivityIcon />, icon: <ActivityIcon />,
iconClassName: "text-muted-foreground", iconClassName: "text-muted-foreground",
}, },
{ {
id: "bps", id: "bps",
label: "Средний bitrate", label: "Средний bitrate",
value: fmtBps(kpis.avgBps), value: fmtBps(kpis.avgBps),
icon: <GaugeIcon />, icon: <GaugeIcon />,
iconClassName: "text-muted-foreground", iconClassName: "text-muted-foreground",
}, },
{ {
id: "users", id: "users",
label: "Пользователи", label: "Пользователи",
value: String(kpis.users), value: String(kpis.users),
icon: <UsersIcon />, hint: `Серверы: ${kpis.servers}`,
iconClassName: "text-muted-foreground", icon: <UsersIcon />,
}, 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: <ServerIcon />,
iconClassName: "text-muted-foreground",
},
]}
/>}
{dataReady && <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} />} <Tabs value={view} onValueChange={(next) => updateParams({ view: String(next) })} className="gap-5">
<TabsList variant="line" className="h-auto w-full justify-start gap-1 overflow-x-auto border-b p-0">
<TabsTrigger value="overview" className={tabTrigger}>Обзор</TabsTrigger>
<TabsTrigger value="pivot" className={tabTrigger}>Сводная (куб)</TabsTrigger>
<TabsTrigger value="explore" className={tabTrigger}>Срезы</TabsTrigger>
</TabsList>
<DataPageCard> <TabsContent value="overview" className="flex flex-col gap-5">
<DataPageToolbar {cubeState ?? (
leading={ <>
<div className="flex flex-wrap items-center gap-3"> <StatisticsVolumeChart series={viewData.series} grain={viewData.grain} scope={scope} actions={planesControl} />
<SegmentedControl <CapacityGrid
value={view} label="Доли объёма"
onChange={(next) => updateParams({ view: next === "pivot" ? "pivot" : "explore" })} items={[
options={[ bytesItem("users", "Пользователи", "GRE/WG клиентов, без hops", bytesOf(viewData.users), <UsersIcon />),
{ value: "explore", label: "Разрез" }, bytesItem("servers", "Серверы", planes === "all" ? "WAN и дубли в списке" : "без WAN и overlay", bytesOf(viewData.servers), <ServerIcon />),
{ value: "pivot", label: "Сводка" }, bytesItem("countries", "Страны", "Топ-10", bytesOf([...viewData.countries].sort((a, b) => b.bytes - a.bytes).slice(0, 10)), <GlobeIcon />),
]} ]}
/>
<SegmentedControl
value={planes}
onChange={(next) => updateParams({ planes: next === "all" ? "all" : undefined })}
options={[
{ value: "unique", label: "Уникальный" },
{ value: "all", label: "Все плоскости" },
]}
/>
{view === "explore" && !sliced ? (
<DimensionSelect
label="Критерий"
value={dim}
onChange={(next) => updateParams({ dim: next, tab: undefined })}
/> />
) : null} </>
{view === "pivot" ? ( )}
<> </TabsContent>
<PivotDimSelect
label="Строки" <TabsContent value="pivot">
value={pivotRow} <DataPageCard>
exclude={pivotCol} <DataPageToolbar
onChange={(next) => updateParams({ pivotRow: next })} leading={
/> <div className="flex flex-wrap items-center gap-3">
<PivotDimSelect {planesControl}
label="Колонки" <PivotDimSelect label="Строки" value={pivotRow} exclude={pivotCol} onChange={(next) => updateParams({ pivotRow: next })} />
value={pivotCol} <PivotDimSelect label="Колонки" value={pivotCol} exclude={pivotRow} onChange={(next) => updateParams({ pivotCol: next })} />
exclude={pivotRow} </div>
onChange={(next) => updateParams({ pivotCol: next })} }
/> filterControl={filters}
</> countLabel={dataReady ? countLabel : undefined}
) : null} />
</div> {sliceChips}
} {cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
filterControl={<StatisticsFilters key={JSON.stringify(slices)} slices={slices} onApply={setSlices} />} </DataPageCard>
countLabel={dataReady ? countLabel : undefined} </TabsContent>
/>
<SliceChips <TabsContent value="explore">
chips={chips} <DataPageCard>
onRemove={(key) => { <DataPageToolbar
const next = { ...slices } leading={
delete next[key as keyof CubeSlices] <div className="flex flex-wrap items-center gap-3">
setSlices(next) {planesControl}
}} {!sliced ? <DimensionSelect label="Критерий" value={dim} onChange={(next) => updateParams({ dim: next, tab: undefined })} /> : null}
/> </div>
{isLive && !dataReady ? ( }
<div role="status" className="p-6 text-sm text-muted-foreground">{loading ? "Загрузка статистики…" : rangeError || paramsError ? "Исправьте параметры отчёта для загрузки статистики." : "Статистика недоступна. Повторите загрузку."}</div> filterControl={filters}
) : emptyCube ? ( countLabel={dataReady ? countLabel : undefined}
<EmptyState />
title="Нет данных куба" {sliceChips}
description="За выбранный период нет IPFIX-фактов. Куб заполняется с момента деплоя, без бэкфилла за год." {cubeState ?? (sliced ? (
/> <BreakdownDashboard
) : view === "pivot" ? ( data={viewData}
<StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} /> hidden={hiddenKinds(slices)}
) : sliced ? ( selectedIdFor={(kind) => selectedIdForKind(kind, slices)}
<BreakdownDashboard onRowClick={handleRowClick}
data={viewData} isLoading={loading}
hidden={hiddenKinds(slices)} />
selectedIdFor={(kind) => selectedIdForKind(kind, slices)} ) : (
onRowClick={handleRowClick} <StatisticsBreakdownDataGrid
isLoading={loading} rows={rowsForKind(viewData, dim)}
/> kind={dim}
) : ( selectedId={selectedIdForKind(dim, slices)}
<StatisticsBreakdownDataGrid onRowClick={(row) => handleRowClick(dim, row)}
rows={rowsForKind(viewData, dim)} isLoading={loading}
kind={dim} />
selectedId={selectedIdForKind(dim, slices)} ))}
onRowClick={(row) => handleRowClick(dim, row)} </DataPageCard>
isLoading={loading} </TabsContent>
/> </Tabs>
)} </div>
</DataPageCard>
</div> </div>
</div> </div>
) )
+216 -166
View File
@@ -7,7 +7,9 @@ import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status" import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
import { TrafficDataTime } from "@/components/traffic/traffic-data-time" import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
import { PageHeader } from "@/components/page-header" 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, ToneBadge, type Tone } from "@/components/reui-kit/ops-blocks"
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid" import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart" import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart" import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
@@ -16,7 +18,7 @@ import { Sparkline } from "@/components/sparkline"
import { StatusDot } from "@/components/status-dot" import { StatusDot } from "@/components/status-dot"
import { Flag } from "@/components/flag" import { Flag } from "@/components/flag"
import { import {
RefreshCwIcon, TrendingUpIcon, TrendingDownIcon, RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon, ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon,
} from "lucide-react" } from "lucide-react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@@ -341,17 +343,6 @@ type SortDir = "asc" | "desc"
// ─── shared sub-components ──────────────────────────────────────────────────── // ─── shared sub-components ────────────────────────────────────────────────────
function StatChip({ icon, label, value }: { icon: ReactNode; label: string; value: string }) {
return (
<div className="flex items-center gap-2">
<div className="flex items-center justify-center size-7 rounded-md bg-muted shrink-0">{icon}</div>
<div className="leading-tight min-w-0 break-words">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="text-sm font-semibold tabular-nums">{value}</p>
</div>
</div>
)
}
// ─── left-panel entity cards ────────────────────────────────────────────────── // ─── left-panel entity cards ──────────────────────────────────────────────────
@@ -368,22 +359,22 @@ function ServerCard({ s, selected, onClick }: { s: ServerTraffic; selected: bool
<StatusDot status={s.status} /> <StatusDot status={s.status} />
<span className="text-xs font-medium truncate">{s.name}</span> <span className="text-xs font-medium truncate">{s.name}</span>
</div> </div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1"> <span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<Flag code={s.country} />{s.site} <Flag code={s.country} />{s.site}
</span> </span>
</div> </div>
<TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} /> <TrafficMiniChart rx={s.rxSeries} tx={s.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(s.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(s.txNow)}</span>
</div> </div>
{s.boundIfaces.length > 0 && ( {s.boundIfaces.length > 0 && (
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground"> <div className="flex items-center gap-0.5 text-xs text-muted-foreground">
<CableIcon className="size-3" />{s.boundIfaces.length} <CableIcon className="size-3" />{s.boundIfaces.length}
</div> </div>
)} )}
@@ -407,10 +398,10 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-medium truncate">{u.login}</p> <p className="text-xs font-medium truncate">{u.login}</p>
<p className="text-[10px] text-muted-foreground truncate">{u.displayName}</p> <p className="text-xs text-muted-foreground truncate">{u.displayName}</p>
</div> </div>
</div> </div>
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground shrink-0"> <div className="flex items-center gap-0.5 text-xs text-muted-foreground shrink-0">
<CableIcon className="size-3" />{u.interfaces.length} <CableIcon className="size-3" />{u.interfaces.length}
</div> </div>
</div> </div>
@@ -418,18 +409,18 @@ function UserCard({ u, selected, onClick }: { u: UserTraffic; selected: boolean;
<> <>
<TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} /> <TrafficMiniChart rx={u.rxSeries} tx={u.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(u.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(u.txNow)}</span>
</div> </div>
</div> </div>
</> </>
) : ( ) : (
<p className="text-[10px] text-muted-foreground">Нет привязанных интерфейсов</p> <p className="text-xs text-muted-foreground">Нет привязанных интерфейсов</p>
)} )}
</button> </button>
) )
@@ -447,20 +438,20 @@ function IfaceCard({ c, selected, onClick }: { c: BoundIfaceTraffic; selected: b
<StatusDot status={c.status} /> <StatusDot status={c.status} />
<div className="min-w-0"> <div className="min-w-0">
<p className="text-xs font-mono font-medium truncate">{boundIfaceLabel(c)}</p> <p className="text-xs font-mono font-medium truncate">{boundIfaceLabel(c)}</p>
<p className="text-[10px] text-muted-foreground truncate">{c.userLogin}</p> <p className="text-xs text-muted-foreground truncate">{c.userLogin}</p>
</div> </div>
</div> </div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1"> <span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
<Flag code={c.serverCountry} />{c.serverSite} <Flag code={c.serverCountry} />{c.serverSite}
</span> </span>
</div> </div>
<TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} /> <TrafficMiniChart rx={c.rxSeries} tx={c.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-emerald-500" /> <ArrowDownIcon className="size-3 text-emerald-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(c.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-blue-500" /> <ArrowUpIcon className="size-3 text-blue-500" />
<span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span> <span className="font-mono font-medium text-foreground">{fmtRate(c.txNow)}</span>
</div> </div>
@@ -487,12 +478,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<span className="text-xs font-mono font-semibold break-all">{boundIfaceLabel(c)}</span> <span className="text-xs font-mono font-semibold break-all">{boundIfaceLabel(c)}</span>
<Badge variant={TYPE_VARIANT[c.interfaceType]} size="sm">{IFACE_TYPE_LABEL[c.interfaceType]}</Badge> <Badge variant={TYPE_VARIANT[c.interfaceType]} size="sm">{IFACE_TYPE_LABEL[c.interfaceType]}</Badge>
{showServer && ( {showServer && (
<span className="inline-flex items-center gap-1 text-[10px] font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded"> <span className="inline-flex items-center gap-1 text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
<Flag code={c.serverCountry} />{c.serverSite} <Flag code={c.serverCountry} />{c.serverSite}
</span> </span>
)} )}
</div> </div>
<p className="text-[10px] text-muted-foreground truncate mt-0.5">{c.comment || c.userLogin}</p> <p className="text-xs text-muted-foreground truncate mt-0.5">{c.comment || c.userLogin}</p>
</div> </div>
<div className="shrink-0 text-right leading-tight"> <div className="shrink-0 text-right leading-tight">
<div className="flex items-center gap-1 justify-end text-xs font-mono font-medium text-emerald-600 dark:text-emerald-400"> <div className="flex items-center gap-1 justify-end text-xs font-mono font-medium text-emerald-600 dark:text-emerald-400">
@@ -502,12 +493,12 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
<ArrowUpIcon className="size-3" />{fmtRate(c.txNow)} <ArrowUpIcon className="size-3" />{fmtRate(c.txNow)}
</div> </div>
</div> </div>
<div className="shrink-0 text-right leading-tight text-[10px] text-muted-foreground w-[72px]"> <div className="shrink-0 text-right leading-tight text-xs text-muted-foreground w-[72px]">
<p className="tabular-nums">{fmtGiB(c.rxTotal)}</p> <p className="tabular-nums">{fmtGiB(c.rxTotal)}</p>
<p className="tabular-nums">{fmtGiB(c.txTotal)}</p> <p className="tabular-nums">{fmtGiB(c.txTotal)}</p>
</div> </div>
<span className={cn( <span className={cn(
"shrink-0 text-[10px] px-1.5 py-0.5 rounded-full font-medium tabular-nums", "shrink-0 text-xs px-1.5 py-0.5 rounded-full font-medium tabular-nums",
c.status === "online" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground", c.status === "online" ? "bg-success/10 text-success" : "bg-muted text-muted-foreground",
)}> )}>
{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"} {c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}
@@ -516,6 +507,61 @@ function IfaceRow({ c, showServer = false }: { c: BoundIfaceTraffic; showServer?
) )
} }
/** Интерфейсы выбранного сервера таблицей (блок «Интерфейсы сервера» макета v3). */
function ServerIfacesFrame({ server }: { server: ServerTraffic }) {
const cols = "grid-cols-[minmax(170px,1.6fr)_minmax(90px,1fr)_110px_100px_100px_150px]"
return (
<SectionFrame title="Интерфейсы сервера" description={`${server.name} · трафик по каждому интерфейсу`} icon={<CableIcon />} panelClassName="overflow-x-auto">
<div className="min-w-[740px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground grid h-10 items-center gap-x-3 border-b px-3.5 text-xs font-medium", cols)}>
<span>Интерфейс</span><span>Сервер</span><span>Статус</span><span>RX</span><span>TX</span><span>Учтено</span>
</div>
{server.boundIfaces.map((c) => (
<div key={c.id} className={cn("grid min-h-[52px] items-center gap-x-3 border-b px-3.5 last:border-b-0", cols, c.status === "offline" && "opacity-55")}>
<span className="flex min-w-0 items-center gap-2 py-2">
<StatusDot status={c.status} />
<span className="min-w-0">
<span className="block truncate font-mono text-[13px] font-medium">{boundIfaceLabel(c)}</span>
<span className="text-muted-foreground block truncate font-mono text-xs">{IFACE_TYPE_LABEL[c.interfaceType]} · {c.comment || c.userLogin}</span>
</span>
</span>
<span className="truncate font-mono text-xs">{server.name}</span>
<span><ToneBadge tone={c.status === "online" ? "ok" : c.status === "unknown" ? "mu" : "er"}>{c.status === "online" ? "Работает" : c.status === "unknown" ? "Нет данных" : "Неактивен"}</ToneBadge></span>
<span className="font-mono text-xs tabular-nums">{fmtRate(c.rxNow)}</span>
<span className="font-mono text-xs tabular-nums">{fmtRate(c.txNow)}</span>
<span className="text-muted-foreground font-mono text-xs tabular-nums">{fmtGiB(c.rxTotal)} / {fmtGiB(c.txTotal)}</span>
</div>
))}
</div>
</SectionFrame>
)
}
/** Доля RX по серверам с данными (блок rbl макета v3). */
function RxShareFrame({ servers }: { servers: ServerTraffic[] }) {
const rows = servers.filter((s) => typeof s.rxNow === "number" && s.rxNow > 0).sort((a, b) => (b.rxNow ?? 0) - (a.rxNow ?? 0)).slice(0, 5)
const total = rows.reduce((sum, s) => sum + (s.rxNow ?? 0), 0)
if (!rows.length || total <= 0) return null
const max = rows[0].rxNow ?? 1
const colors = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--muted-foreground)"]
return (
<SectionFrame title="Доля RX" description="сейчас · по серверам с данными" icon={<ChartPieIcon />} panelClassName="flex flex-col gap-1.5 p-2.5">
{rows.map((s, i) => (
<div key={s.id} className="flex min-w-0 items-center gap-2">
<span className="bg-muted/70 relative h-7 min-w-0 flex-1 overflow-hidden rounded-full">
<i className="absolute inset-y-0 left-0 rounded-full opacity-40" style={{ width: `${Math.round(((s.rxNow ?? 0) / max) * 100)}%`, background: colors[i] }} />
<span className="relative flex h-full items-center gap-1.5 truncate px-2.5 text-xs font-medium">
<span aria-hidden="true" className="size-1.5 shrink-0 rounded-full" style={{ background: colors[i] }} />{s.name}
</span>
</span>
<span className="min-w-[72px] text-right font-mono text-xs">{fmtRate(s.rxNow)}</span>
<span className="text-muted-foreground min-w-11 text-right font-mono text-xs">{Math.round(((s.rxNow ?? 0) / total) * 100)}%</span>
</div>
))}
</SectionFrame>
)
}
function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceTraffic[]; showServer?: boolean }) { function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceTraffic[]; showServer?: boolean }) {
if (clients.length === 0) if (clients.length === 0)
return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p> return <p className="text-xs text-muted-foreground py-1">Нет привязанных интерфейсов</p>
@@ -528,24 +574,46 @@ function BoundIfacesList({ clients, showServer = false }: { clients: BoundIfaceT
// ─── detail panel helpers ───────────────────────────────────────────────────── // ─── detail panel helpers ─────────────────────────────────────────────────────
function DetailHeader({ range, setRange, children }: { function DetailHeader({ range, setRange, children, status }: {
range: Range; setRange: (r: Range) => void; children: ReactNode range: Range; setRange: (r: Range) => void; children: ReactNode; status?: ReactNode
}) { }) {
return ( return (
<div className="flex flex-wrap items-start justify-between mb-3 gap-3"> <div className="mb-3 flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2 flex-wrap min-w-0">{children}</div> <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{children}</div>
<div className="flex flex-wrap gap-1"> {status}
<div className="bg-muted inline-flex h-9 items-center gap-0.5 rounded-lg p-[3px]">
{TRAFFIC_RANGE_KEYS.map((r) => ( {TRAFFIC_RANGE_KEYS.map((r) => (
<Button key={r} type="button" aria-pressed={range === r} size="sm" variant={r === range ? "default" : "ghost"} <button key={r} type="button" aria-pressed={range === r} onClick={() => setRange(r)}
className="h-7 px-2 text-xs" onClick={() => setRange(r)}> className={cn("text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors", range === r && "bg-background text-foreground shadow-sm")}>
{TRAFFIC_RANGE_LABELS[r]} {TRAFFIC_RANGE_LABELS[r]}
</Button> </button>
))} ))}
</div> </div>
</div> </div>
) )
} }
const SERVER_STATUS: Record<ServerTraffic["status"], { tone: Tone; label: string }> = {
online: { tone: "ok", label: "Онлайн" },
degraded: { tone: "wn", label: "Ухудшение" },
offline: { tone: "er", label: "Оффлайн" },
}
/** Текущие и пиковые скорости двумя колонками (блок kv макета v3). */
function KvStats({ label, items }: { label: string; items: Array<{ id: string; label: string; value: string; hint?: string }> }) {
return (
<div role="group" aria-label={label} className="mt-3 grid grid-cols-2 gap-x-3.5 gap-y-3 border-t pt-3.5">
{items.map((item) => (
<div key={item.id} className="min-w-0">
<small className="text-muted-foreground block text-xs">{item.label}</small>
<b className="font-mono text-[13px] font-medium tabular-nums">{item.value}</b>
{item.hint ? <span className="text-muted-foreground ml-2 text-xs">{item.hint}</span> : null}
</div>
))}
</div>
)
}
function OfflinePlaceholder({ text = "Нет данных — объект недоступен" }: { text?: string }) { function OfflinePlaceholder({ text = "Нет данных — объект недоступен" }: { text?: string }) {
return ( return (
<div className="flex items-center justify-center h-[220px] text-muted-foreground/40"> <div className="flex items-center justify-center h-[220px] text-muted-foreground/40">
@@ -596,63 +664,24 @@ function ServerDetail({
const txNow = liveTx ?? sel.txNow const txNow = liveTx ?? sel.txNow
return ( return (
<> <>
<DetailHeader range={range} setRange={setRange}> <DetailHeader range={range} setRange={setRange} status={<ToneBadge tone={SERVER_STATUS[sel.status].tone} size="lg">{SERVER_STATUS[sel.status].label}</ToneBadge>}>
<StatusDot status={sel.status} /> <div className="min-w-0">
<h2 className="text-base font-semibold break-all">{sel.name}</h2> <h2 className="text-sm font-semibold break-all">{sel.name}</h2>
<span className="text-xs font-mono bg-muted px-1.5 py-0.5 rounded flex items-center gap-1"> <p className="text-muted-foreground flex items-center gap-1 text-[0.78rem]"><Flag code={sel.country} />{sel.site}</p>
<Flag code={sel.country} />{sel.site} </div>
</span>
</DetailHeader> </DetailHeader>
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} /> <TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="mt-4 pt-4 border-t"> <KvStats
<KpiStatGrid label="Скорость выбранного сервера"
aria-label="Скорость выбранного сервера" items={[
items={[ { id: "rx-now", label: "RX сейчас", value: fmtRate(rxNow), hint: liveHint },
{ { id: "tx-now", label: "TX сейчас", value: fmtRate(txNow), hint: liveHint },
id: "rx-now", { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
label: "RX", { id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
value: fmtRate(rxNow), ]}
hint: liveHint, />
icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success",
},
{
id: "tx-now",
label: "TX",
value: fmtRate(txNow),
hint: liveHint,
icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info",
},
{
id: "rx-peak",
label: "Пик RX",
value: fmtRate(sel.rxPeak),
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
{
id: "tx-peak",
label: "Пик TX",
value: fmtRate(sel.txPeak),
icon: <TrendingDownIcon className="size-4" />,
iconClassName: "text-warning",
},
]}
/>
</div>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
{sel.boundIfaces.length > 0 && (
<div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
<CableIcon className="size-4 text-muted-foreground" />
Привязанные интерфейсы
<span className="text-xs text-muted-foreground font-normal">({sel.boundIfaces.length})</span>
</h3>
<BoundIfacesList clients={sel.boundIfaces} />
</div>
)}
</> </>
) )
} }
@@ -666,7 +695,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
<UsersIcon className="size-4 text-muted-foreground" /> <UsersIcon className="size-4 text-muted-foreground" />
</div> </div>
<div className="leading-tight"> <div className="leading-tight">
<h2 className="text-base font-semibold break-all">{sel.login}</h2> <h2 className="text-sm font-semibold break-all">{sel.login}</h2>
<p className="text-xs text-muted-foreground break-all">{sel.displayName} · {sel.role}</p> <p className="text-xs text-muted-foreground break-all">{sel.displayName} · {sel.role}</p>
</div> </div>
</DetailHeader> </DetailHeader>
@@ -675,12 +704,15 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
) : ( ) : (
<> <>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4 pt-4 border-t"> <KvStats
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} /> label="Скорость выбранного клиента"
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} /> items={[
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} /> { id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
<StatChip icon={<CableIcon className="size-3.5 text-purple-500" />} label="Интерфейсы" value={`${sel.interfaces.length}`} /> { id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
</div> { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "ifaces", label: "Интерфейсы", value: String(sel.interfaces.length) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t"> <div className="mt-4 pt-4 border-t">
<h3 className="text-sm font-semibold mb-2 flex items-center gap-2"> <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
@@ -702,7 +734,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
<DetailHeader range={range} setRange={setRange}> <DetailHeader range={range} setRange={setRange}>
<StatusDot status={sel.status} /> <StatusDot status={sel.status} />
<div className="leading-tight min-w-0"> <div className="leading-tight min-w-0">
<h2 className="text-base font-mono font-semibold break-all">{boundIfaceLabel(sel)}</h2> <h2 className="text-sm font-mono font-semibold break-all">{boundIfaceLabel(sel)}</h2>
<p className="text-xs text-muted-foreground truncate">{sel.comment || sel.userLogin}</p> <p className="text-xs text-muted-foreground truncate">{sel.comment || sel.userLogin}</p>
</div> </div>
<Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge> <Badge variant={TYPE_VARIANT[sel.interfaceType]} size="sm">{IFACE_TYPE_LABEL[sel.interfaceType]}</Badge>
@@ -711,12 +743,15 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
</span> </span>
</DetailHeader> </DetailHeader>
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} /> <TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4 pt-4 border-t"> <KvStats
<StatChip icon={<ArrowDownIcon className="size-3.5 text-emerald-500" />} label="RX" value={fmtRate(sel.rxNow)} /> label="Скорость выбранного интерфейса"
<StatChip icon={<ArrowUpIcon className="size-3.5 text-blue-500" />} label="TX" value={fmtRate(sel.txNow)} /> items={[
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик RX" value={fmtRate(sel.rxPeak)} /> { id: "rx", label: "RX сейчас", value: fmtRate(sel.rxNow) },
<StatChip icon={<TrendingUpIcon className="size-3.5 text-amber-500" />} label="Пик TX" value={fmtRate(sel.txPeak)} /> { id: "tx", label: "TX сейчас", value: fmtRate(sel.txNow) },
</div> { id: "rx-peak", label: "Пик RX", value: fmtRate(sel.rxPeak) },
{ id: "tx-peak", label: "Пик TX", value: fmtRate(sel.txPeak) },
]}
/>
<TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} /> <TotalsRow rxTotal={sel.rxTotal} txTotal={sel.txTotal} rxSeries={sel.rxSeries} txSeries={sel.txSeries} />
<div className="mt-4 pt-4 border-t grid grid-cols-2 sm:grid-cols-3 gap-4"> <div className="mt-4 pt-4 border-t grid grid-cols-2 sm:grid-cols-3 gap-4">
<div> <div>
@@ -1229,46 +1264,57 @@ export default function TrafficPage() {
}, },
] ]
const modeCount: Record<GroupMode, number | null> = {
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 ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-full">
<PageHeader <PageHeader crumbs={[{ label: "Главная", href: "/dashboard" }, { label: "Обзор" }, { label: "Трафик" }]} />
crumbs={[{ label: "Обзор" }, { label: "Трафик" }]}
actions={
<>
<Button
variant="outline"
size="sm"
onClick={() => {
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
else setTrafficRetry(value => value + 1)
}}
disabled={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
>
<RefreshCwIcon className={cn("size-4", isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading) && "animate-spin")} />Обновить
</Button>
</>
}
/>
{/* ── mode tab bar ── */} <div className="flex-1 min-w-0 overflow-y-auto px-4 pt-5 pb-10 md:px-7 md:pt-6">
<div className="border-b bg-background shrink-0"> <div className="flex flex-col gap-6">
<div role="group" aria-label="Разделы трафика" className="flex items-center overflow-x-auto px-3 sm:px-6"> <PageTitle
{GROUP_MODES.map(({ mode, icon, label }) => ( icon={<ActivityIcon />}
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)} title="Трафик"
className={cn( description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
"flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors -mb-px", actions={
effectiveMode === mode <>
? "border-primary text-foreground" <Button type="button" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
: "border-transparent text-muted-foreground hover:text-foreground hover:border-border", <Button
)}> type="button"
{icon}{label} onClick={() => {
</button> if (effectiveMode === "flows") setFlowRetry(value => value + 1)
))} else setTrafficRetry(value => value + 1)
</div> }}
</div> disabled={refreshBusy}
>
<div className="flex-1 min-w-0 overflow-y-auto p-3 sm:p-6"> <RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
</Button>
</>
}
/>
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
<div role="group" aria-label="Разделы трафика" className="flex items-center gap-1 overflow-x-auto border-b">
{GROUP_MODES.map(({ mode, label }) => (
<button type="button" aria-pressed={effectiveMode === mode} key={mode} onClick={() => handleModeChange(mode)}
className={cn(
"text-muted-foreground hover:text-foreground -mb-px inline-flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2.5 text-sm font-medium whitespace-nowrap transition-colors",
effectiveMode === mode && "border-foreground text-foreground",
)}>
{label}
{modeCount[mode] != null ? (
<em aria-hidden="true" className={cn("bg-muted text-muted-foreground inline-flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 font-mono text-xs not-italic", effectiveMode === mode && "bg-foreground/12 text-foreground")}>{modeCount[mode]}</em>
) : null}
</button>
))}
</div>
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid {!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)} isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
aria-label="Сводка трафика" aria-label="Сводка трафика"
@@ -1297,15 +1343,15 @@ export default function TrafficPage() {
{flowError} {flowError}
</div> </div>
)} )}
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-5 items-start"> <div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
<div className="flex flex-col gap-3"> <SectionFrame title={flowScope === "users" ? "Клиенты" : "Экспортёры"} description="Потоки IPFIX · сортировка и поиск" panelClassName="flex flex-col gap-3 p-2.5">
<div role="group" aria-label="Источник потоков" className="flex gap-1"> <div role="group" aria-label="Источник потоков" className="flex gap-1">
<button <button
type="button" type="button"
aria-pressed={flowScope === "servers"} aria-pressed={flowScope === "servers"}
onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }} onClick={() => { setFlowScope("servers"); setFlowIface("__all__") }}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-xs px-2 py-0.5 rounded border transition-colors",
flowScope === "servers" flowScope === "servers"
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1318,7 +1364,7 @@ export default function TrafficPage() {
aria-pressed={flowScope === "users"} aria-pressed={flowScope === "users"}
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }} onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-xs px-2 py-0.5 rounded border transition-colors",
flowScope === "users" flowScope === "users"
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1338,14 +1384,14 @@ export default function TrafficPage() {
/> />
</div> </div>
<div className={cn("flex gap-1 flex-wrap", range === "30d" && "hidden")}> <div className={cn("flex gap-1 flex-wrap", range === "30d" && "hidden")}>
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span> <span className="text-xs text-muted-foreground self-center mr-0.5">Сортировка:</span>
{visibleSortFields.map(({ field, label }) => ( {visibleSortFields.map(({ field, label }) => (
<button <button
key={field} key={field}
type="button" type="button"
onClick={() => toggleSort(field)} onClick={() => toggleSort(field)}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-xs px-2 py-0.5 rounded border transition-colors",
sortField === field sortField === field
? "border-primary bg-primary/10 text-primary font-medium" ? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground", : "border-border text-muted-foreground hover:text-foreground",
@@ -1371,8 +1417,8 @@ export default function TrafficPage() {
</p> </p>
) : null} ) : null}
</div> </div>
</div> </SectionFrame>
<Frame dense className="w-full min-w-0 flex flex-col"> <SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5"> <FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{analyticsLoading && <p role="status">Загрузка аналитики…</p>} {analyticsLoading && <p role="status">Загрузка аналитики…</p>}
{currentAnalytics?.error && <Alert variant="destructive" role="alert"><AlertTitle>Аналитика недоступна</AlertTitle><AlertDescription>{currentAnalytics.error}<Button size="sm" variant="outline" onClick={() => setAnalyticsRetry(value => value + 1)}>Повторить аналитику</Button></AlertDescription></Alert>} {currentAnalytics?.error && <Alert variant="destructive" role="alert"><AlertTitle>Аналитика недоступна</AlertTitle><AlertDescription>{currentAnalytics.error}<Button size="sm" variant="outline" onClick={() => setAnalyticsRetry(value => value + 1)}>Повторить аналитику</Button></AlertDescription></Alert>}
@@ -1399,7 +1445,7 @@ export default function TrafficPage() {
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)} emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
/> />
</FramePanel> </FramePanel>
</Frame> </SectionFrame>
</div> </div>
<FlowOverlaySheet <FlowOverlaySheet
open={overlayOpen} open={overlayOpen}
@@ -1410,9 +1456,10 @@ export default function TrafficPage() {
/> />
</div> </div>
) : ( ) : (
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-5 items-start"> <div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
{/* ── left panel ── */} {/* ── left panel ── */}
<div className="flex flex-col gap-3"> <div className="flex min-w-0 flex-col gap-4">
<SectionFrame title={listTitle} description={`${listShown} из ${modeCount[effectiveMode] ?? listShown} · сортировка и поиск`} panelClassName="flex flex-col gap-3 p-2.5">
{/* search */} {/* search */}
<div className="relative"> <div className="relative">
@@ -1422,20 +1469,17 @@ export default function TrafficPage() {
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
aria-label="Поиск трафика" placeholder="Поиск…" aria-label="Поиск трафика" placeholder="Поиск…"
className="w-full pl-8 pr-3 h-8 text-xs bg-muted/50 border border-border rounded-md outline-none focus:border-primary transition-colors" className="border-input bg-input/30 focus:border-ring h-8 w-full rounded-lg border pr-3 pl-8 text-[13px] outline-none transition-colors"
/> />
</div> </div>
{/* sort controls */} {/* sort controls */}
<div className="flex gap-1 flex-wrap"> <div role="group" aria-label="Сортировка" className="bg-muted inline-flex h-9 w-fit items-center gap-0.5 rounded-lg p-[3px]">
<span className="text-[10px] text-muted-foreground self-center mr-0.5">Сортировка:</span>
{visibleSortFields.map(({ field, label }) => ( {visibleSortFields.map(({ field, label }) => (
<button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)} <button type="button" aria-pressed={sortField === field} key={field} onClick={() => toggleSort(field)}
className={cn( className={cn(
"text-[10px] px-2 py-0.5 rounded border transition-colors", "text-muted-foreground hover:text-foreground h-[30px] rounded-md px-2.5 text-[13px] font-medium transition-colors",
sortField === field sortField === field && "bg-background text-foreground shadow-sm",
? "border-primary bg-primary/10 text-primary font-medium"
: "border-border text-muted-foreground hover:text-foreground",
)}> )}>
{label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""} {label}{sortField === field ? (sortDir === "desc" ? " ↓" : " ↑") : ""}
</button> </button>
@@ -1461,20 +1505,23 @@ export default function TrafficPage() {
<IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} /> <IfaceCard key={c.id} c={c} selected={c.id === selectedId} onClick={() => setSelectedId(c.id)} />
))} ))}
</div> </div>
</SectionFrame>
{effectiveMode === "servers" ? <RxShareFrame servers={activeServerTraffic} /> : null}
</div> </div>
{/* ── detail panel ── */} {/* ── detail panel ── */}
<Frame dense className="w-full min-w-0 flex flex-col"> <div className="flex min-w-0 flex-col gap-4">
<SectionFrame bare className="w-full min-w-0">
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5"> <FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
{isLive && effectiveMode === "servers" && ( {isLive && effectiveMode === "servers" && (
<div className="mb-3 pb-3 border-b"> <div className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-[11px] text-muted-foreground mr-1">Интерфейс:</span> <span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
<button <button
type="button" aria-pressed={hideDisabledIfaces} type="button" aria-pressed={hideDisabledIfaces}
onClick={() => setHideDisabledIfaces((v) => !v)} onClick={() => setHideDisabledIfaces((v) => !v)}
className={cn( className={cn(
"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
hideDisabledIfaces hideDisabledIfaces
? "bg-muted text-foreground border-border" ? "bg-muted text-foreground border-border"
: "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40", : "text-muted-foreground border-border hover:text-foreground hover:border-foreground/40",
@@ -1486,7 +1533,7 @@ export default function TrafficPage() {
type="button" aria-pressed={selectedIface === "__all__"} type="button" aria-pressed={selectedIface === "__all__"}
onClick={() => setSelectedIface("__all__")} onClick={() => setSelectedIface("__all__")}
className={cn( className={cn(
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
selectedIface === "__all__" selectedIface === "__all__"
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1502,7 +1549,7 @@ export default function TrafficPage() {
type="button" aria-pressed={active} type="button" aria-pressed={active}
onClick={() => setSelectedIface(iface.name)} onClick={() => setSelectedIface(iface.name)}
className={cn( className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
active active
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -1514,7 +1561,7 @@ export default function TrafficPage() {
</button> </button>
) )
})} })}
{detailBusy && <span className="text-[10px] text-muted-foreground ml-2">Загрузка...</span>} {detailBusy && <span className="text-xs text-muted-foreground ml-2">Загрузка...</span>}
</div> </div>
</div> </div>
)} )}
@@ -1550,11 +1597,14 @@ export default function TrafficPage() {
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />} {effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />} {effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
</FramePanel> </FramePanel>
</Frame> </SectionFrame>
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
</div>
</div> </div>
)} )}
</div> </div>
</div>
</div> </div>
</div> </div>
) )
@@ -14,6 +14,26 @@ const route: IxRouterObject = {
} }
const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }] const device = (rows: Record<string, Array<Record<string, string>>>) => [{ serverId: 17, source: "", rows }]
test("managed MSS rules are backfilled and removed without adopting a hand-written rule", () => {
const path = "/ip/firewall/mangle"
const from = { serverId: 17, path, fields: { comment: name + ":linux-mss-from-il-wg", action: "change-mss",
chain: "prerouting", "in-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const to = { serverId: 17, path, fields: { comment: name + ":linux-mss-to-il-wg", action: "change-mss",
chain: "postrouting", "out-interface": "il-wg", "new-mss": "1380", "tcp-mss": "1381-65535" } }
const manual = { ...to.fields, comment: "manual MSS", ".id": "*A" }
const fromRow = { ...from.fields, ".id": "*B" }
const toRow = { ...to.fields, ".id": "*C" }
const desired = [from, to]
const live = (rows: Array<Record<string, string>>) => device({ [path]: rows })
assert.deepEqual(planIxNative(id, desired, desired, live([manual])).map(task => [task.fields, task.placeBefore]),
[[from.fields, "*A"], [to.fields, "*A"]])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, manual])).map(task => task.fields), [to.fields])
assert.deepEqual(planIxNative(id, desired, desired, live([fromRow, toRow, manual])), [])
assert.deepEqual(planIxNative(id, [], desired, live([fromRow, toRow, manual])).map(task => task.rosId), ["*C", "*B"])
assert.throws(() => planIxNative(id, desired, [], live([fromRow, manual])), /незавершённой операции/)
assert.throws(() => planIxNative(id, desired, desired, live([{ ...fromRow, "new-mss": "1460" }, toRow])), /изменён вне операции/)
})
test("a new VRF is inserted before main and no foreign route is altered", () => { test("a new VRF is inserted before main and no foreign route is altered", () => {
const changes = planIxNative(id, [vrf, route], [], device({ const changes = planIxNative(id, [vrf, route], [], device({
"/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }], "/ip/vrf": [{ ".id": "*A", name: "main", interfaces: "all", builtin: "true" }],
@@ -98,6 +98,9 @@ export function planIxNative(id: string, desired: IxRouterObject[], previous: Ix
rows.some(row => egressObject(row.comment)))).map(device => device.serverId)) rows.some(row => egressObject(row.comment)))).map(device => device.serverId))
// An older applied revision had no egress list. A partial set still needs reconciliation. // An older applied revision had no egress list. A partial set still needs reconciliation.
previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId)) previous = previous.filter(object => !egressObject(object.fields.comment) || withEgressList.has(object.serverId))
// Older revisions were compiled without MSS rules. Backfill only absent managed MSS rules.
previous = previous.filter(object => !object.fields.comment?.startsWith(namespace + ":linux-mss-") ||
devices.some(device => device.serverId === object.serverId && managedRow(device, object)))
const desiredKeys = new Set(desired.map(deviceMarker)) const desiredKeys = new Set(desired.map(deviceMarker))
const previousByKey = new Map(previous.map(object => [deviceMarker(object), object])) const previousByKey = new Map(previous.map(object => [deviceMarker(object), object]))
const result: Task[] = [] const result: Task[] = []
@@ -356,7 +359,7 @@ async function configureIxLinuxTunnel(segment: IxSegment, input: IxLinuxClientRe
const binding: IxSite["interfaces"][number] = { const binding: IxSite["interfaces"][number] = {
name, kind: input.kind, prefixes: input.prefixes, name, kind: input.kind, prefixes: input.prefixes,
linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint, linux: { name: input.name, clientId: previous?.linux?.clientId, enabled: input.enabled, destinations: input.destinations, peerEndpoint: input.peerEndpoint,
exit: input.exit === "local-wan" ? localExit : input.exit }, tunnelMtu: input.tunnelMtu ?? previous?.linux?.tunnelMtu, exit: input.exit === "local-wan" ? localExit : input.exit },
} }
if (input.kind === "wireguard") { if (input.kind === "wireguard") {
const existing = previous?.provisionWireguard const existing = previous?.provisionWireguard
@@ -32,6 +32,8 @@ test("managed clients get their own return path and fail closed if both exit pro
provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900, provisionWireguard: { peerPublicKey: "A".repeat(43) + "=", listenPort: 51900,
localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } }) localAddress: "10.254.1.1/30", peerAddress: "10.254.1.2", hubEndpoint: "192.0.2.10" } })
const objects = compileIxConfiguration(id, value) const objects = compileIxConfiguration(id, value)
const clamp = objects.findIndex(object => object.fields.comment === table + ":linux-mss-from-linux-wg")
assert.ok(clamp >= 0 && clamp < objects.findIndex(object => object.fields.comment === table + ":linux-linux-wg-route"))
const clientTable = ixClientRoutingTable(table, "linux-wg") const clientTable = ixClientRoutingTable(table, "linux-wg")
const defaults = objects.filter(object => object.fields["routing-table"] === clientTable) const defaults = objects.filter(object => object.fields["routing-table"] === clientTable)
assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"]) assert.deepEqual(defaults.map(object => object.fields.distance), ["10", "11", "254"])
@@ -45,6 +47,35 @@ test("managed clients get their own return path and fail closed if both exit pro
assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1"))) assert.ok(objects.every(object => object.path !== "/ip/vrf" || !object.fields.interfaces.includes("ether1")))
}) })
test("managed Linux tunnels clamp TCP SYN in both directions before routing marks can end prerouting", () => {
const value = fixture(), site = value.sites[0]
site.interfaces.push(
{ name: "linux-wg", kind: "wireguard", prefixes: [], linux: { name: "vps", enabled: true, destinations: [] },
provisionWireguard: { localAddress: "10.254.0.1/30", peerAddress: "10.254.0.2", listenPort: 51820, peerPublicKey: "A".repeat(43) + "=" } },
{ name: "linux-gre", kind: "gre-ipsec", prefixes: [], endpoint: "192.0.2.90", localEndpoint: "192.0.2.17",
linux: { name: "vps", enabled: false, destinations: [] },
provisionGre: { localAddress: "10.254.0.5/30", peerAddress: "10.254.0.6", credentialId: id } },
{ name: "linux-wg6", kind: "wireguard", prefixes: [],
linux: { name: "vps6", enabled: true, destinations: [], tunnelMtu: 1360 },
provisionWireguard: { localAddress: "fd00:254::1/126", peerAddress: "fd00:254::2", listenPort: 51821, peerPublicKey: "B".repeat(43) + "=" } },
)
const rules = compileIxConfiguration(id, ixSegmentConfigurationSchema.parse(value)).filter(object => object.fields.action === "change-mss")
assert.equal(rules.length, 6)
for (const [binding, family, mss, disabled] of [
["linux-wg", "ip", 1380, "false"], ["linux-gre", "ip", 1380, "true"], ["linux-wg6", "ipv6", 1300, "false"],
] as const) {
const list = ixClientRoutingTable(table, binding) + "-src"
const shared = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled }
assert.deepEqual(rules.filter(object => object.fields.comment.endsWith("-" + binding)), [
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "prerouting", "in-interface": binding, "src-address-list": list, comment: table + ":linux-mss-from-" + binding } },
{ serverId: site.serverId, path: "/" + family + "/firewall/mangle",
fields: { ...shared, chain: "postrouting", "out-interface": binding, "dst-address-list": list, comment: table + ":linux-mss-to-" + binding } },
])
}
})
test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => { test("a managed remote exit prepares both CHRs and returns only prefixes of users assigned to it", () => {
const value = fixture(), site = value.sites[0] const value = fixture(), site = value.sites[0]
site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99, site.interfaces.push({ name: "it-abc", kind: "wireguard", prefixes: [], peerServerId: 99,
+13 -1
View File
@@ -84,6 +84,11 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
const permitted = privateTable + "-dst" const permitted = privateTable + "-dst"
const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])] const sourcesCidr = [...new Set([host(tunnel.peerAddress), ...binding.prefixes.map(canonicalBgpPolicyPrefix)])]
const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])] const destinations = [...new Set([host(tunnel.localAddress.split("/")[0]), ...policy.destinations.map(canonicalBgpPolicyPrefix)])]
// Use the WireGuard default as a conservative ceiling for both managed tunnel types.
const mss = (policy.tunnelMtu ?? 1420) - (family === 4 ? 40 : 60)
const clamp = { protocol: "tcp", "tcp-flags": "syn", "tcp-mss": (mss + 1) + "-65535",
action: "change-mss", "new-mss": String(mss), passthrough: "true", disabled: String(!policy.enabled) }
const mangle = ip + "/firewall/mangle"
const ingress = { chain: "prerouting", "in-interface": binding.name } const ingress = { chain: "prerouting", "in-interface": binding.name }
const exit = site.groups.find(group => group.id === policy.exit) const exit = site.groups.find(group => group.id === policy.exit)
const paths = exit ? groupPaths(exit) : [] const paths = exit ? groupPaths(exit) : []
@@ -114,6 +119,13 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace, add(filter, key + "-allow-inbound", { ...inbound, "src-address-list": permitted, "in-interface": namespace,
action: "accept", disabled: String(!policy.enabled) }) action: "accept", disabled: String(!policy.enabled) })
add(filter, key + "-deny-inbound", { ...inbound, action: "drop" }) add(filter, key + "-deny-inbound", { ...inbound, action: "drop" })
// The real VRF member is visible before routing and after routing, respectively.
add(mangle, "linux-mss-from-" + binding.name, {
...clamp, ...ingress, "src-address-list": sources,
})
add(mangle, "linux-mss-to-" + binding.name, {
...clamp, chain: "postrouting", "out-interface": binding.name, "dst-address-list": sources,
})
if (!exit) return if (!exit) return
add("/routing/table", key + "-table", { name: privateTable, fib: "true" }) add("/routing/table", key + "-table", { name: privateTable, fib: "true" })
for (const [index, path] of paths.entries()) { for (const [index, path] of paths.entries()) {
@@ -122,7 +134,7 @@ function compileLinuxPolicy(namespace: string, site: IxSite, binding: IxSite["in
}) })
} }
add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" }) add(routePath(family), key + "-default-drop", { "routing-table": privateTable, "dst-address": defaultRoute[family], blackhole: "yes", distance: "254" })
add(ip + "/firewall/mangle", key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted, add(mangle, key + "-route", { ...ingress, "src-address-list": sources, "dst-address-list": "!" + permitted,
action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) }) action: "mark-routing", "new-routing-mark": privateTable, passthrough: "false", disabled: String(!policy.enabled) })
const mainPaths = paths.filter(path => path.viaMain) const mainPaths = paths.filter(path => path.viaMain)
for (const [index, path] of mainPaths.entries()) { for (const [index, path] of mainPaths.entries()) {
+1 -1
View File
@@ -107,7 +107,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
}, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot]) }, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot])
return ( return (
<Sidebar collapsible="icon" {...props}> <Sidebar variant="inset" collapsible="icon" {...props}>
<SidebarHeader> <SidebarHeader>
<AppSwitcher /> <AppSwitcher />
</SidebarHeader> </SidebarHeader>
@@ -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 <div className="flex flex-col gap-2">
{failed.length > 0 && <Alert variant="destructive">
<AlertTitle>{summary}</AlertTitle>
<AlertDescription>Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.</AlertDescription>
</Alert>}
<div className="flex flex-wrap items-start justify-between gap-2">
<details className="min-w-0 text-sm" open={failed.length > 0 || undefined}>
<summary className="cursor-pointer">Источники и время получения</summary>
<ul className="mt-2 flex flex-col gap-1 text-xs">
{(Object.keys(DASHBOARD_SOURCES) as DashboardSource[]).map(key => {
const source = sources[key]
return <li key={key} data-source={key} className={`break-words ${source?.error ? "text-destructive" : "text-muted-foreground"}`}>
{DASHBOARD_SOURCES[key]}: {source?.error ? `ошибка обновления — ${source.error}. ` : ""}
{source?.receivedAt != null ? <>Получено <time dateTime={new Date(source.receivedAt).toISOString()}>{new Date(source.receivedAt).toLocaleString("ru-RU")}</time>{source.error ? " · данные могут быть устаревшими" : ""}</> : "Успешных загрузок ещё нет"}
{source?.sampledAt && Number.isFinite(Date.parse(source.sampledAt)) && <> · замер <time dateTime={source.sampledAt}>{new Date(source.sampledAt).toLocaleString("ru-RU")}</time></>}
</li>
})}
</ul>
</details>
<div className="flex items-center gap-2">
<span role="status" className="text-xs text-muted-foreground">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing}>Обновить данные</Button>
</div>
</div>
</div>
}
@@ -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<EventItem["level"], string> = {
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 <p className="text-muted-foreground px-5 py-6 text-sm">Загрузка событий…</p>
}
if (error && events.length === 0) {
return (
<div className="px-5 py-4">
<Alert variant="destructive">
<AlertTitle>События недоступны</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
</div>
)
}
if (events.length === 0) {
return (
<p className="text-muted-foreground px-5 py-6 text-sm">
Событий пока нет.{" "}
<Link href="/alerts" className="underline underline-offset-2">
Оповещения
</Link>
</p>
)
}
return (
<Timeline defaultValue={events.length} className="px-5 py-4">
{events.map((event, index) => (
<TimelineItem key={event.id} step={index + 1}>
<TimelineHeader>
<TimelineSeparator />
<TimelineDate>{formatEventAge(event.createdAt)}</TimelineDate>
<TimelineTitle className="text-[13px] leading-tight">{event.title}</TimelineTitle>
<TimelineIndicator className={cn(LEVEL_DOT[event.level])} />
</TimelineHeader>
<TimelineContent className="text-xs leading-snug">{event.message}</TimelineContent>
</TimelineItem>
))}
</Timeline>
)
}
@@ -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 (
<SectionFrame
title="Здоровье сети"
description="Сводный индекс — среднее долей исправных: пробы, задержка, свежесть данных, серверы и туннели"
actions={<ToneBadge tone={tone} size="lg">{badge}</ToneBadge>}
panelClassName="grid grid-cols-1 items-center gap-6 p-5 md:grid-cols-[200px_minmax(0,1fr)]"
>
<div className="flex flex-col items-center gap-1.5">
<div className="relative size-[150px]">
<svg viewBox="0 0 140 140" width="150" height="150" role="img" aria-label={score == null ? "Индекс здоровья сети неизвестен" : `Индекс здоровья сети ${score} из 100`}>
<circle cx="70" cy="70" r="52" fill="none" stroke="var(--muted)" strokeWidth="12" />
{score != null ? (
<circle cx="70" cy="70" r="52" fill="none" stroke={TONE_COLOR[tone]} strokeWidth="12" strokeLinecap="round" strokeDasharray={`${(circumference * score) / 100} ${circumference}`} transform="rotate(-90 70 70)" />
) : null}
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<b className="text-[34px] leading-none font-semibold tabular-nums">{score ?? "—"}</b>
<span className="text-muted-foreground mt-0.5 text-xs">из 100</span>
</div>
</div>
<span className="text-muted-foreground text-xs">{known.length} из {factors.length} факторов с данными</span>
</div>
<div className="flex flex-col gap-2.5">
{factors.map((factor) => (
<div key={factor.label} className="grid grid-cols-[130px_minmax(0,1fr)_auto] items-center gap-2.5 text-[13px]">
<span>{factor.label}</span>
<span aria-hidden="true" className="bg-muted h-1.5 overflow-hidden rounded-[3px]">
{factor.ratio != null ? (
<i className="block h-full rounded-[3px]" style={{ width: `${Math.round(factor.ratio * 100)}%`, background: TONE_COLOR[factorTone(factor.ratio)] }} />
) : null}
</span>
<span className="min-w-11 text-right font-mono">{factor.value}</span>
</div>
))}
</div>
</SectionFrame>
)
}
const LEVEL: Record<EventItem["level"], { tone: Tone; label: string }> = {
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 = <p className="text-muted-foreground px-4 py-6 text-sm">Загрузка событий…</p>
else if (error && events.length === 0) {
body = (
<div className="p-4">
<Alert variant="destructive">
<AlertTitle>События недоступны</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
</div>
)
} else if (events.length === 0) body = <p className="text-muted-foreground px-4 py-6 text-sm">Событий пока нет.</p>
else {
body = (
<ol className="py-1.5">
{events.map((event, index) => {
const level = LEVEL[event.level] ?? LEVEL.info
return (
<li key={event.id} className="grid grid-cols-[62px_16px_minmax(0,1fr)] items-start gap-2.5 px-4 py-2 text-[13px]">
<time dateTime={event.createdAt} className="text-muted-foreground pt-px font-mono text-xs">{hhmm(event.createdAt)}</time>
<span aria-hidden="true" className="flex h-full flex-col items-center">
<i className="mt-1 size-[9px] rounded-full" style={{ background: TONE_COLOR[level.tone] }} />
{index < events.length - 1 ? <u className="bg-border mt-0.5 min-h-[18px] w-px flex-1" /> : null}
</span>
<span className="min-w-0">
<ToneBadge tone={level.tone} mark={false} className="mr-2">{level.label}</ToneBadge>
<b className="font-medium">{event.title}</b>
{event.message ? <span className="text-muted-foreground mt-0.5 block text-xs">{event.message}</span> : null}
</span>
</li>
)
})}
</ol>
)
}
return (
<SectionFrame
title="Лента инцидентов"
description="Последние события · причины и связанные объекты"
actions={<Link href="/alerts" className={buttonVariants({ variant: "outline", size: "sm" })}>Все события</Link>}
>
{body}
</SectionFrame>
)
}
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 (
<SectionFrame title="Требует внимания" description="Серверы · Туннели · Проверки" icon={<TableIcon />} bare>
<div role="tablist" aria-label="Виды" className="flex flex-wrap gap-x-1 border-b px-2.5">
{tabs.map((tab) => (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={view === tab.id}
onClick={() => { setView(tab.id); setVisible(PAGE) }}
className={cn(
"text-muted-foreground hover:text-foreground -mb-px inline-flex h-[38px] items-center gap-1.5 border-b-2 border-transparent px-2 text-[13px] font-medium transition-colors",
view === tab.id && "border-foreground text-foreground",
)}
>
{tab.label}{" "}
<em className={cn("bg-muted text-muted-foreground inline-flex h-5 min-w-5 items-center justify-center rounded-md px-1.5 font-mono text-xs not-italic", view === tab.id && "bg-foreground/12 text-foreground")}>{tab.count}</em>
</button>
))}
</div>
<div className="flex flex-wrap items-center gap-2 px-2.5 py-2">
<label className="border-input bg-input/30 text-muted-foreground focus-within:border-ring flex h-8 min-w-[180px] flex-[0_1_320px] items-center gap-2 rounded-lg border px-2.5 transition-colors">
<SearchIcon aria-hidden="true" className="size-3.5 shrink-0" />
<input value={query} onChange={(event) => { setQuery(event.target.value); setVisible(PAGE) }} placeholder="Поиск по имени и полям…" aria-label="Поиск в таблице" className="text-foreground placeholder:text-muted-foreground min-w-0 flex-1 bg-transparent text-[13px] outline-none" />
</label>
{q ? <span className="text-muted-foreground ml-auto text-xs tabular-nums">{shown.length} из {rows.length}</span> : null}
</div>
<FramePanel className="max-h-[560px] overflow-auto p-0">
<div className="min-w-[640px]">
<div aria-hidden="true" className="bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 grid-cols-[minmax(200px,2fr)_112px_minmax(120px,1fr)_minmax(160px,2fr)] items-center gap-x-3 border-b px-3.5 text-xs font-medium">
<span>Объект</span>
<span>Статус</span>
<span>Тип</span>
<span>Сообщение</span>
</div>
{shown.length === 0 ? (
<p className="text-muted-foreground px-4 py-8 text-center text-sm">{rows.length === 0 ? "Проблем не обнаружено" : "Ничего не найдено"}</p>
) : (
shown.slice(0, visible).map((row) => (
<Link
key={`${row.kind}:${row.id}`}
href={row.href}
className="hover:bg-muted/45 focus-visible:ring-ring grid min-h-[52px] grid-cols-[minmax(200px,2fr)_112px_minmax(120px,1fr)_minmax(160px,2fr)] items-center gap-x-3 border-b px-3.5 transition-colors outline-none last:border-b-0 focus-visible:ring-2 focus-visible:ring-inset"
>
<span className="flex min-w-0 items-center gap-2 py-2">
<ToneDot tone={row.tone} />
<span className="min-w-0">
<span className="block truncate font-mono text-[13px] font-medium">{row.title}</span>
<span className="text-muted-foreground block font-mono text-xs">{row.kind}</span>
</span>
</span>
<span><ToneBadge tone={row.tone}>{row.tone === "er" ? "Сбой" : row.confirmed ? "Внимание" : "Неизвестно"}</ToneBadge></span>
<span className="font-mono text-[12.5px]">{row.kind}</span>
<span className="min-w-0 font-mono text-[12.5px] wrap-anywhere">{row.hint}</span>
</Link>
))
)}
</div>
{shown.length > visible ? (
<div className="flex justify-center border-t p-2">
<Button type="button" variant="ghost" size="sm" onClick={() => setVisible((count) => count + PAGE)}>Показать ещё {Math.min(PAGE, shown.length - visible)}</Button>
</div>
) : null}
</FramePanel>
{emptyNotes.length ? (
<div className="text-muted-foreground flex flex-wrap gap-x-3 gap-y-1 px-4 py-2 text-xs">
{emptyNotes.map((note) => <span key={note}>{note}</span>)}
</div>
) : null}
</SectionFrame>
)
}
export type QuickLink = { id: string; title: string; description: string; href: string }
/** Быстрые переходы (блок cards макета v3). */
export function DashboardQuickLinks({ links }: { links: QuickLink[] }) {
return (
<SectionFrame title="Быстрые переходы" description="Другие разделы управления сетью" panelClassName="grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3 p-3">
{links.map((link) => (
<Link key={link.id} href={link.href} className="bg-muted/25 hover:bg-muted/50 focus-visible:ring-ring rounded-lg border p-3.5 transition-colors outline-none focus-visible:ring-2">
<div className="flex items-center justify-between gap-2">
<b className="text-sm font-semibold">{link.title}</b>
<ToneBadge tone="in" mark={false}>Открыть</ToneBadge>
</div>
<div className="text-muted-foreground mt-1.5 text-[13px]">{link.description}</div>
</Link>
))}
</SectionFrame>
)
}
@@ -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<DashboardSource, ReactNode> = {
servers: <ServerIcon />, probes: <ActivityIcon />, bgp: <RouteIcon />, gre: <LinkIcon />, wg: <LockIcon />,
vxlan: <BoxIcon />, traffic: <ChartColumnIcon />, internetPath: <GlobeIcon />, events: <BellIcon />,
}
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 <b className="text-foreground font-mono font-medium">—</b>
const date = new Date(at)
return (
<time dateTime={typeof at === "string" ? at : date.toISOString()} className="text-foreground font-mono font-medium">
{date.toLocaleTimeString("ru-RU")}
</time>
)
}
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 (
<SectionFrame
title="Сводка источников"
description="Время получения и замера по каждому источнику дашборда · подробности — на вкладке «Источники и время получения»"
icon={<DatabaseIcon />}
bare
actions={
<>
<span role="status" className="text-muted-foreground text-xs">{refreshing ? "Обновление данных…" : "Обновление завершено"}</span>
<Button type="button" size="sm" variant="outline" onClick={onRefresh} disabled={refreshing} aria-label="Обновить данные источников">Обновить данные</Button>
</>
}
>
<FramePanel className="grid grid-cols-1 p-0 min-[1100px]:grid-cols-[260px_minmax(0,1fr)]">
<div className="flex min-w-0 flex-col gap-2 border-b px-[18px] py-4 min-[1100px]:border-r min-[1100px]:border-b-0">
<div className="text-muted-foreground text-[0.8rem]">Источники обновлены</div>
<div className="flex items-baseline gap-0.5">
<span className="text-[30px] leading-tight font-semibold tracking-tight tabular-nums">{ok}</span>
<span className="text-muted-foreground ml-0.5 text-base">/ {rows.length}</span>
</div>
<div className="text-muted-foreground text-xs">{sub}</div>
<div role="img" aria-label={segments.map(([, label, n]) => `${label}: ${n}`).join(", ")} className="mt-1.5 flex h-2 gap-[3px]">
{segments.map(([tone, label, n]) => (
<i key={label} className="block h-full min-w-1.5 rounded-full" style={{ flex: n, background: TONE_COLOR[tone] }} />
))}
</div>
<div className="text-muted-foreground grid grid-cols-2 gap-x-3.5 gap-y-1.5 text-xs">
{segments.map(([tone, label, n]) => (
<span key={label} className="flex min-w-0 items-center gap-1.5">
<i aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[tone] }} />
{label}
<b className="text-foreground ml-auto font-medium tabular-nums">{n}</b>
</span>
))}
</div>
<p className="text-muted-foreground mt-auto border-t border-dashed pt-2.5 text-xs leading-snug">
Последние полученные данные сохранены. Если источник ещё не загрузился, его показатели неизвестны.
</p>
</div>
<ul className="grid grid-cols-2 min-[1100px]:grid-cols-3">
{rows.map((row) => {
const error = sourceErrorText(row)
return (
<li
key={row.key}
data-source={row.key}
className="flex min-w-0 flex-col gap-2 border-r border-b px-3.5 py-3 max-[1099px]:even:border-r-0 min-[1100px]:[&:nth-child(3n)]:border-r-0 min-[1100px]:[&:nth-last-child(-n+3)]:border-b-0"
>
<div className="flex min-w-0 items-center gap-2.5">
<IconTile variant="outline" size="sm" aria-hidden="true" style={{ color: row.tone === "ok" || row.tone === "mu" ? "var(--muted-foreground)" : TONE_COLOR[row.tone] }}>
{SOURCE_ICON[row.key]}
</IconTile>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{row.name}</span>
<ToneBadge tone={row.tone} size="default">{row.label}</ToneBadge>
</div>
<div className="text-muted-foreground flex flex-wrap gap-x-3.5 gap-y-1 text-xs">
<span>Получено <Clock at={row.receivedAt} /></span>
<span>Замер <Clock at={row.sampledAt} /></span>
</div>
{error ? (
<p className={cn("text-xs leading-snug", row.tone === "wn" ? "text-warning-foreground" : "text-destructive-foreground")}>{error}</p>
) : null}
</li>
)
})}
</ul>
</FramePanel>
</SectionFrame>
)
}
-401
View File
@@ -1,401 +0,0 @@
"use client"
import { useMemo, useState } from "react"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import { Maximize2Icon, ZoomInIcon, ZoomOutIcon } from "lucide-react"
type Pt = { x: number; y: number }
type ServerKind = "home-router" | "jump-host" | "exit-node"
const W = 1060
const H = 420
const ZOOM_MIN = 0.2
const ZOOM_MAX = 6
const STATUS_STYLE = {
unknown: { fill: "var(--muted)", stroke: "var(--muted-foreground)", glow: "transparent" },
online: { fill: "#0f2d1f", stroke: "#4ade80", glow: "rgba(74,222,128,0.15)" },
degraded: { fill: "#2d1e06", stroke: "#fbbf24", glow: "rgba(251,191,36,0.15)" },
offline: { fill: "#2d0f0f", stroke: "#f87171", glow: "transparent" },
}
const TYPE_STYLE: Record<ServerKind, { label: string; fill: string; r: number }> = {
"home-router": { label: "HR", fill: "#16a34a", r: 40 },
"jump-host": { label: "JH", fill: "#7c3aed", r: 34 },
"exit-node": { label: "EN", fill: "#0369a1", r: 30 },
}
const WAN_COLORS = ["#0ea5e9", "#f97316", "#a855f7", "#ec4899", "#14b8a6"]
function pingColor(ms: number | null) {
if (ms == null) return "#f87171"
if (ms < 15) return "#4ade80"
if (ms < 50) return "#fbbf24"
return "#fb923c"
}
function edgeBadgePosition(x1: number, y1: number, x2: number, y2: number, t: number, normalPx: number): { mx: number; my: number } {
const px = x1 + (x2 - x1) * t
const py = y1 + (y2 - y1) * t
const dx = x2 - x1
const dy = y2 - y1
const len = Math.hypot(dx, dy) || 1
const nx = -dy / len
const ny = dx / len
return { mx: px + nx * normalPx, my: py + ny * normalPx }
}
function ZoomControls({ zoom, onZoomIn, onZoomOut, onFit }: {
zoom: number
onZoomIn: () => void
onZoomOut: () => void
onFit: () => void
}) {
return (
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-20 flex items-center gap-0 rounded-xl border border-white/10 bg-black/75 backdrop-blur-md shadow-xl overflow-hidden">
<button onClick={onZoomOut} className="px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors">
<ZoomOutIcon className="size-3.5" />
</button>
<span className="px-3 py-2 text-xs font-mono text-white/70 min-w-[52px] text-center border-x border-white/10 select-none">
{Math.round(zoom * 100)}%
</span>
<button onClick={onZoomIn} className="px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors">
<ZoomInIcon className="size-3.5" />
</button>
<div className="w-px h-5 bg-white/10" />
<button onClick={onFit} className="px-3 py-2 text-white/60 hover:text-white hover:bg-white/5 transition-colors">
<Maximize2Icon className="size-3.5" />
</button>
</div>
)
}
function PingBadge({
mx,
my,
ping,
dl,
ul,
color,
monitored,
}: {
mx: number
my: number
ping: number | null
dl: number | null
ul: number | null
color: string
monitored?: boolean
}) {
const hasSpeed = dl != null || ul != null
const dlText = dl != null ? Math.round(dl) : "—"
const ulText = ul != null ? Math.round(ul) : "—"
return (
<g transform={`translate(${mx},${my})`}>
<rect x="-34" y={-20} width="68" height={hasSpeed ? 42 : 24} rx="4" fill="#060d1a" stroke={color} strokeWidth="0.7" opacity="0.92" />
<text textAnchor="middle" y={hasSpeed ? "-5" : "4"} fontSize="8.5" fontWeight="600" fill={color} fontFamily="ui-monospace,monospace">
{ping == null ? "—" : `${ping} мс`}
</text>
{hasSpeed && (
<text textAnchor="middle" y="8" fontSize="7" fill="#64748b" fontFamily="ui-monospace,monospace">
{`↓${dlText} ↑${ulText}`}
</text>
)}
{monitored && (
<text textAnchor="middle" y={hasSpeed ? "17" : "14"} fontSize="6" fill="#38bdf8" fontFamily="ui-monospace,monospace">
mon
</text>
)}
</g>
)
}
function ServerNode({
pos,
type,
name,
site,
country,
status,
selected,
onClick,
}: {
pos: Pt
type: ServerKind
name: string
site: string
country: string
status: "online" | "offline" | "degraded" | "unknown"
selected: boolean
onClick: () => void
}) {
const ss = STATUS_STYLE[status]
const ts = TYPE_STYLE[type]
return (
<g transform={`translate(${pos.x},${pos.y})`} style={{ cursor: "pointer" }} onClick={onClick}>
{status === "online" && (
<circle r={ts.r + 14} fill={ss.glow} opacity="0.7">
<animate attributeName="r" values={`${ts.r + 10};${ts.r + 18};${ts.r + 10}`} dur="3s" repeatCount="indefinite" />
<animate attributeName="opacity" values="0.8;0.15;0.8" dur="3s" repeatCount="indefinite" />
</circle>
)}
{selected && (
<circle r={ts.r + 10} fill="none" stroke="rgba(255,255,255,0.45)" strokeWidth="1.5" strokeDasharray="4 3" />
)}
<circle r={ts.r} fill={ss.fill} stroke={ss.stroke} strokeWidth={selected ? 2.5 : 1.8} />
<g transform={`translate(${ts.r - 10},-${ts.r - 10})`}>
<circle r="10" fill={ts.fill} />
<text textAnchor="middle" y="4" fontSize="6.5" fontWeight="bold" fill="#fff">{ts.label}</text>
</g>
<foreignObject x={-110} y={-22} width={220} height={28} style={{ overflow: "visible", pointerEvents: "none" }}>
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, width: "100%", height: "100%", fontFamily: "ui-monospace, monospace" }} {...({ xmlns: "http://www.w3.org/1999/xhtml" } as Record<string, string>)}>
<span style={{ flexShrink: 0, lineHeight: 0 }}>
<Flag code={country || "UN"} size={16} />
</span>
<span style={{ maxWidth: 170, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: 700, fontSize: 11, color: "#f1f5f9", lineHeight: 1.25 }}>
{site || name}
</span>
</div>
</foreignObject>
<text textAnchor="middle" y={ts.r + 18} fontSize="8.5" fill="#94a3b8" fontFamily="ui-monospace,monospace">
{name}
</text>
</g>
)
}
export function InternetPathMapCanvas({ model }: { model: InternetPathViewModel | null }) {
const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 })
const [isDragging, setIsDragging] = useState(false)
const [dragStart, setDragStart] = useState<{ x: number; y: number } | null>(null)
const [selectedNode, setSelectedNode] = useState<"home" | "jh" | "en" | "wan" | null>("home")
const mapData = useMemo(() => {
if (!model) return null
const hop = model.currentHop ?? model.primaryHop ?? (
model.activeWanUplink && model.fallbackJumpHost && model.fallbackExitNode
? {
home: model.homeRouter,
wan: model.activeWanUplink,
jumpHost: model.fallbackJumpHost,
exitNode: model.fallbackExitNode,
wanJhMetrics: {
pingMs: null,
dlMbps: null,
ulMbps: null,
fromMonitoring: false,
},
jhExitMetrics: {
pingMs: null,
dlMbps: null,
ulMbps: null,
fromMonitoring: false,
},
}
: null
)
if (!hop) return null
const axisY = 220
const homePos = { x: 180, y: axisY }
const wanPos = { x: 400, y: axisY }
const jhPos = { x: 660, y: axisY }
const enPos = { x: 900, y: axisY }
const directPos = { x: 900, y: axisY + 110 }
const pathDiff =
model.primaryPath &&
model.currentPath &&
(model.primaryPath.wanId !== model.currentPath.wanId || model.primaryPath.jhId !== model.currentPath.jhId || model.primaryPath.exitId !== model.currentPath.exitId)
return { hop, homePos, wanPos, jhPos, enPos, directPos, pathDiff, directWan: model.directWan }
}, [model])
function onWheel(e: React.WheelEvent<SVGSVGElement>) {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
const px = e.clientX - rect.left
const py = e.clientY - rect.top
const worldX = (px - pan.x) / zoom
const worldY = (py - pan.y) / zoom
const factor = e.deltaY < 0 ? 1.1 : 1 / 1.1
const next = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, zoom * factor))
setZoom(next)
setPan({ x: px - worldX * next, y: py - worldY * next })
}
return (
<div className="flex flex-col gap-3">
{!model && (
<div className="h-[240px] rounded-md border border-dashed border-border grid place-items-center text-sm text-muted-foreground">
Недостаточно данных для построения маршрута
</div>
)}
{model && mapData && (
<div
className="relative rounded-lg border border-[#1f2a3d] bg-gradient-to-b from-[#0a1424] to-[#060d17] overflow-hidden overscroll-contain"
onWheelCapture={(e) => {
// Когда курсор над картой, колесо управляет только картой (без прокрутки страницы).
e.preventDefault()
e.stopPropagation()
}}
>
<svg
viewBox={`0 0 ${W} ${H}`}
className={cn("w-full h-[320px] select-none", isDragging ? "cursor-grabbing" : "cursor-grab")}
onMouseDown={(e) => {
setIsDragging(true)
setDragStart({ x: e.clientX - pan.x, y: e.clientY - pan.y })
}}
onMouseMove={(e) => {
if (!isDragging || !dragStart) return
setPan({ x: e.clientX - dragStart.x, y: e.clientY - dragStart.y })
}}
onMouseUp={() => { setIsDragging(false); setDragStart(null) }}
onMouseLeave={() => { setIsDragging(false); setDragStart(null) }}
onWheel={onWheel}
>
<g transform={`translate(${pan.x} ${pan.y}) scale(${zoom})`}>
<line x1={mapData.homePos.x} y1={mapData.homePos.y} x2={mapData.wanPos.x} y2={mapData.wanPos.y} stroke={WAN_COLORS[0]} strokeWidth="2.2" opacity="0.75" />
<line
x1={mapData.wanPos.x}
y1={mapData.wanPos.y}
x2={mapData.jhPos.x}
y2={mapData.jhPos.y}
stroke={mapData.pathDiff ? "#fbbf24" : "#4ade80"}
strokeWidth={3.2}
/>
<line
x1={mapData.jhPos.x}
y1={mapData.jhPos.y}
x2={mapData.enPos.x}
y2={mapData.enPos.y}
stroke={mapData.pathDiff ? "#fbbf24" : "#4ade80"}
strokeWidth={3.2}
/>
{mapData.directWan.enabled && (
<line
x1={mapData.wanPos.x}
y1={mapData.wanPos.y}
x2={mapData.directPos.x}
y2={mapData.directPos.y}
stroke="#38bdf8"
strokeWidth="2.4"
opacity="0.9"
/>
)}
<g transform={`translate(${mapData.wanPos.x},${mapData.wanPos.y})`} onClick={() => setSelectedNode("wan")} style={{ cursor: "pointer" }}>
<circle r={24} fill={`${WAN_COLORS[0]}1a`} stroke={WAN_COLORS[0]} strokeWidth="2" />
<path d="M -5 2 Q 0 -5 5 2" fill="none" stroke={WAN_COLORS[0]} strokeWidth="1.5" strokeLinecap="round" />
<path d="M -8 5 Q 0 -10 8 5" fill="none" stroke={WAN_COLORS[0]} strokeWidth="1" strokeLinecap="round" opacity="0.6" />
<circle cx="0" cy="4" r="2" fill={WAN_COLORS[0]} />
<text textAnchor="middle" y="36" fontSize="8" fontWeight="700" fill={WAN_COLORS[0]} fontFamily="ui-monospace,monospace">
{mapData.hop.wan.name}
</text>
</g>
<ServerNode
pos={mapData.homePos}
type="home-router"
name={mapData.hop.home.name}
site={mapData.hop.home.site}
country={mapData.hop.home.country}
status={mapData.hop.home.status}
selected={selectedNode === "home"}
onClick={() => setSelectedNode("home")}
/>
{mapData.directWan.enabled && (
<g transform={`translate(${mapData.directPos.x},${mapData.directPos.y})`}>
<circle r={22} fill="#08243a" stroke="#38bdf8" strokeWidth="1.8" />
<text textAnchor="middle" y="4" fontSize="10" fontWeight="700" fill="#38bdf8">NET</text>
<text textAnchor="middle" y="34" fontSize="8" fill="#7dd3fc" fontFamily="ui-monospace,monospace">
{mapData.directWan.provider ?? "Direct WAN"}
</text>
</g>
)}
<ServerNode
pos={mapData.jhPos}
type="jump-host"
name={mapData.hop.jumpHost.name}
site={mapData.hop.jumpHost.site}
country={mapData.hop.jumpHost.country}
status={mapData.hop.jumpHost.status}
selected={selectedNode === "jh"}
onClick={() => setSelectedNode("jh")}
/>
<ServerNode
pos={mapData.enPos}
type="exit-node"
name={mapData.hop.exitNode.name}
site={mapData.hop.exitNode.site}
country={mapData.hop.exitNode.country}
status={mapData.hop.exitNode.status}
selected={selectedNode === "en"}
onClick={() => setSelectedNode("en")}
/>
<PingBadge
{...edgeBadgePosition(mapData.wanPos.x, mapData.wanPos.y, mapData.jhPos.x, mapData.jhPos.y, 0.52, -24)}
ping={mapData.hop.wanJhMetrics.pingMs}
dl={mapData.hop.wanJhMetrics.dlMbps}
ul={mapData.hop.wanJhMetrics.ulMbps}
color={pingColor(mapData.hop.wanJhMetrics.pingMs)}
monitored={mapData.hop.wanJhMetrics.fromMonitoring}
/>
<PingBadge
{...edgeBadgePosition(mapData.jhPos.x, mapData.jhPos.y, mapData.enPos.x, mapData.enPos.y, 0.5, -24)}
ping={mapData.hop.jhExitMetrics.pingMs}
dl={mapData.hop.jhExitMetrics.dlMbps}
ul={mapData.hop.jhExitMetrics.ulMbps}
color={pingColor(mapData.hop.jhExitMetrics.pingMs)}
monitored={mapData.hop.jhExitMetrics.fromMonitoring}
/>
{mapData.directWan.enabled && (
<PingBadge
{...edgeBadgePosition(mapData.wanPos.x, mapData.wanPos.y, mapData.directPos.x, mapData.directPos.y, 0.55, -22)}
ping={null}
dl={null}
ul={null}
color="#38bdf8"
monitored={false}
/>
)}
</g>
</svg>
<ZoomControls
zoom={zoom}
onZoomOut={() => setZoom((z) => Math.max(ZOOM_MIN, z * 0.9))}
onZoomIn={() => setZoom((z) => Math.min(ZOOM_MAX, z * 1.1))}
onFit={() => { setZoom(1); setPan({ x: 0, y: 0 }) }}
/>
</div>
)}
{model && !mapData && (
<div className="h-[240px] rounded-md border border-dashed border-border grid place-items-center text-sm text-muted-foreground">
Нет полного набора узлов для визуализации пути
</div>
)}
{model && (
<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">
<div className={cn("rounded-md border p-2", model.pathState === "failover" ? "border-amber-500/40 bg-amber-500/5" : "border-emerald-500/40 bg-emerald-500/5")}>
<p className="font-medium">Рекомендация оптимизатора</p>
<p className="text-muted-foreground mt-1">{model.primaryPath?.reason ?? "Не определен"}</p>
</div>
<div className={cn("rounded-md border p-2", model.pathState === "failover" ? "border-amber-500/40 bg-amber-500/5" : "border-emerald-500/40 bg-emerald-500/5")}>
<p className="font-medium">Наблюдаемый default route</p>
<p className="text-muted-foreground mt-1">{model.currentPath?.reason ?? "Не определен"}</p>
</div>
{model.directWan.enabled && (
<div className="rounded-md border p-2 border-sky-500/40 bg-sky-500/5 md:col-span-2">
<p className="font-medium">Direct WAN path</p>
<p className="text-muted-foreground mt-1">
{`gateway: ${model.directWan.gateway ?? "—"} · iface: ${model.directWan.iface ?? "—"} · dhcp ip: ${model.directWan.leasedIp ?? "—"} · isp: ${model.directWan.provider ?? "—"}`}
</p>
</div>
)}
</div>
)}
</div>
)
}
+72 -74
View File
@@ -1,35 +1,62 @@
"use client" "use client"
import { useEffect, useState } from "react"
import Link from "next/link" import Link from "next/link"
import { ChevronDownIcon } from "lucide-react"
import { OpsPanel } from "@/components/ops-panel"
import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
import { buttonVariants } from "@/components/ui/button" import { buttonVariants } from "@/components/ui/button"
import { import { Alert, AlertDescription, AlertTitle } from "@/components/reui/alert"
Collapsible, import { SectionFrame, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { cn } from "@/lib/utils"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path" import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import { InternetPathMapCanvas } from "@/components/dashboard/internet-path-map" import type { ServerStatus } from "@/lib/data"
import { InternetPathSummary } from "@/components/dashboard/internet-path-summary" import { InternetPathSummary } from "@/components/dashboard/internet-path-summary"
const PATH_MAP_OPEN_LS = "mm:dashboard-path-map-open" const STATUS_TONE: Record<ServerStatus, Tone> = { online: "ok", degraded: "wn", offline: "er", unknown: "mu" }
const X = [13, 37, 62, 86]
function readMapOpen(): boolean { type TopoNode = { label: string; sub: string; tone: Tone }
if (typeof window === "undefined") return true
try { /** Схема пути Home → WAN → JH → Exit (блок topo макета v3); участок WAN→JH — модель связности, пунктиром. */
const raw = localStorage.getItem(PATH_MAP_OPEN_LS) function InternetPathTopo({ model }: { model: InternetPathViewModel | null }) {
if (raw === "0") return false const hop = model?.currentHop ?? model?.primaryHop ?? null
if (raw === "1") return true const wan = hop?.wan ?? model?.activeWanUplink ?? null
} catch { const jh = hop?.jumpHost ?? model?.fallbackJumpHost ?? null
/* ignore */ const exit = hop?.exitNode ?? model?.fallbackExitNode ?? null
if (!model || !jh || !exit) {
return <p className="text-muted-foreground flex h-[300px] items-center justify-center text-sm">Нет полного набора узлов для схемы пути</p>
} }
return true const nodes: TopoNode[] = [
{ label: model.homeRouter.name, sub: "Home Router", tone: STATUS_TONE[model.homeRouter.status] },
{ label: wan ? wan.isp || wan.name : "WAN", sub: wan ? `WAN-аплинк ${wan.iface}` : "WAN не определён", tone: wan ? "ok" : "mu" },
{ label: jh.name, sub: "JumpHost", tone: STATUS_TONE[jh.status] },
{ label: exit.name, sub: `Exit Node${exit.country ? ` · ${exit.country}` : ""}`, tone: STATUS_TONE[exit.status] },
]
const links: Array<{ label: string | null; dashed: boolean }> = [
{ label: null, dashed: false },
{ label: hop?.wanJhMetrics.pingMs != null ? String(hop.wanJhMetrics.pingMs) : null, dashed: true },
{ label: hop?.jhExitMetrics.pingMs != null ? String(hop.jhExitMetrics.pingMs) : null, dashed: false },
]
return (
<div className="relative h-[300px]" role="img" aria-label={`Путь: ${nodes.map((n) => n.label).join(" → ")}`}>
<svg className="absolute inset-0 size-full" aria-hidden="true">
{links.map((link, i) => (
<line key={i} x1={`${X[i]}%`} y1="50%" x2={`${X[i + 1]}%`} y2="50%" stroke={link.dashed ? "var(--warning)" : "var(--success)"} strokeWidth="1.5" strokeDasharray={link.dashed ? "5 5" : undefined} />
))}
</svg>
{links.map((link, i) => link.label ? (
<span key={i} className="bg-card absolute -translate-1/2 rounded-[5px] border px-2 py-0.5 font-mono text-xs" style={{ left: `${(X[i] + X[i + 1]) / 2}%`, top: "50%" }}>{link.label}</span>
) : null)}
{nodes.map((node, i) => (
<div key={i} className="bg-card absolute flex min-w-[132px] -translate-1/2 items-center gap-2 rounded-[9px] border-[1.5px] py-1.5 pr-3 pl-2.5" style={{ left: `${X[i]}%`, top: "50%", borderColor: TONE_COLOR[node.tone] }}>
<span className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[node.tone] }} />
<span className="min-w-0">
<b className="block text-[13px] font-semibold whitespace-nowrap">{node.label}</b>
<span className="text-muted-foreground block text-xs whitespace-nowrap">{node.sub}</span>
</span>
</div>
))}
</div>
)
} }
/** Internet path и Сводка маршрута — два блока макета v3 (topo и kv). */
export function InternetPathPanel({ export function InternetPathPanel({
model, model,
loading, loading,
@@ -39,59 +66,30 @@ export function InternetPathPanel({
loading?: boolean loading?: boolean
error?: string | null error?: string | null
}) { }) {
const [open, setOpen] = useState(true)
const [hydrated, setHydrated] = useState(false)
useEffect(() => {
queueMicrotask(() => {
setOpen(readMapOpen())
setHydrated(true)
})
}, [])
function handleOpenChange(next: boolean) {
setOpen(next)
try {
localStorage.setItem(PATH_MAP_OPEN_LS, next ? "1" : "0")
} catch {
/* ignore */
}
}
return ( return (
<OpsPanel <>
title="Internet path" <SectionFrame
description="Home → WAN → JH → Exit" title="Internet path"
headerRight={ description="Home → WAN → JH → Exit · пунктир WAN→JH — модель связности, маршрут не подтверждён"
<Link href="/network-map" className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 text-xs")}> actions={<Link href="/network-map" className={buttonVariants({ variant: "outline", size: "sm" })}>Карта сети →</Link>}
Карта сети → panelClassName="overflow-x-auto bg-[radial-gradient(var(--border)_1px,transparent_1px)] bg-size-[20px_20px]"
</Link> >
} {error ? (
contentClassName="flex flex-col gap-3 px-5 pb-4" <Alert variant="destructive" className="m-3 w-auto">
> <AlertTitle>Не удалось загрузить путь</AlertTitle>
{error ? ( <AlertDescription>{error}</AlertDescription>
<Alert variant="destructive"> </Alert>
<AlertTitle>Не удалось загрузить путь</AlertTitle> ) : null}
<AlertDescription>{error}</AlertDescription> <div className="min-w-[720px]">
</Alert> {loading && !model ? <div className="bg-muted/40 m-4 h-[268px] animate-pulse rounded-md" /> : <InternetPathTopo model={model} />}
) : null} </div>
{loading && !model ? ( </SectionFrame>
<div className="h-20 animate-pulse rounded-md bg-muted/40" /> <SectionFrame
) : ( title="Сводка маршрута"
<InternetPathSummary model={model} /> description={`Модель связности; маршрут не подтверждён. ${model?.currentPath?.reason ?? "Текущий маршрут не подтверждён"}`}
)} >
{loading && !model ? <div className="bg-muted/40 m-4 h-20 animate-pulse rounded-md" /> : <InternetPathSummary model={model} />}
<Collapsible open={hydrated ? open : true} onOpenChange={handleOpenChange}> </SectionFrame>
<CollapsibleTrigger </>
className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "h-7 w-fit gap-1.5 text-xs")}
>
<ChevronDownIcon className={cn("size-3.5 transition-transform", open && "rotate-180")} />
{open ? "Скрыть карту" : "Показать карту"}
</CollapsibleTrigger>
<CollapsibleContent>
<InternetPathMapCanvas model={model} />
</CollapsibleContent>
</Collapsible>
</OpsPanel>
) )
} }
+30 -85
View File
@@ -3,13 +3,10 @@
import type { ReactNode } from "react" import type { ReactNode } from "react"
import Link from "next/link" import Link from "next/link"
import { Badge } from "@/components/reui/badge" import { Badge } from "@/components/reui/badge"
import { IconTile } from "@/components/reui/icon-tile"
import { StatusBadge } from "@/components/status-badge" import { StatusBadge } from "@/components/status-badge"
import { Flag } from "@/components/flag" import { Flag } from "@/components/flag"
import type { InternetPathViewModel } from "@/lib/dashboard-internet-path" import type { InternetPathViewModel } from "@/lib/dashboard-internet-path"
import type { ServerStatus } from "@/lib/data" import type { ServerStatus } from "@/lib/data"
import { cn } from "@/lib/utils"
import { ArrowRightIcon, HomeIcon, RadioIcon, ServerIcon, GlobeIcon } from "lucide-react"
function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): ServerStatus { function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): ServerStatus {
if (state === "healthy") return "online" if (state === "healthy") return "online"
@@ -17,44 +14,32 @@ function pathStateToServerStatus(state: InternetPathViewModel["pathState"]): Ser
return "unknown" return "unknown"
} }
function HopChip({ function Kv({ label, children }: { label: string; children: ReactNode }) {
label,
name,
country,
icon,
iconClassName,
}: {
label: string
name: string
country?: string
icon: ReactNode
iconClassName?: string
}) {
return ( return (
<div className="flex min-w-0 items-center gap-2 rounded-md border border-border/60 px-2 py-1.5"> <div className="min-w-0">
<IconTile variant="elevated" size="sm" className={cn("shrink-0", iconClassName)} aria-hidden="true"> <small className="text-muted-foreground block text-xs">{label}</small>
{icon} <b className="mt-0.5 flex min-w-0 items-center gap-1.5 font-mono text-[13px] font-medium">{children}</b>
</IconTile>
<div className="min-w-0">
<p className="text-muted-foreground text-[10px] font-medium uppercase tracking-wide">{label}</p>
<p className="flex items-center gap-1 truncate text-sm font-medium">
{country ? <Flag code={country} className="shrink-0" /> : null}
<span className="truncate">{name}</span>
</p>
</div>
</div> </div>
) )
} }
function Node({ name, country }: { name: string; country?: string }) {
return (
<>
{country ? <Flag code={country} className="shrink-0" /> : null}
<span className="truncate">{name}</span>
</>
)
}
/** /**
* Compact live path strip (Frame-friendly). Canvas lives separately. * Сводка маршрута (блок kv макета v3): узлы пути и последние подтверждённые метрики участка WAN → JH.
* Preview: https://reui.io/preview/base/stats-12 * Docs: https://reui.io/docs/components/base/frame
* Docs: https://reui.io/docs/components/base/icon-tile
*/ */
export function InternetPathSummary({ model }: { model: InternetPathViewModel | null }) { export function InternetPathSummary({ model }: { model: InternetPathViewModel | null }) {
if (!model) { if (!model) {
return ( return (
<p className="text-muted-foreground text-sm"> <p className="text-muted-foreground px-4 py-3.5 text-sm">
Недостаточно данных для пути. Добавьте home-router и проверьте{" "} Недостаточно данных для пути. Добавьте home-router и проверьте{" "}
<Link href="/network-map" className="underline underline-offset-2"> <Link href="/network-map" className="underline underline-offset-2">
карту сети карту сети
@@ -71,61 +56,21 @@ export function InternetPathSummary({ model }: { model: InternetPathViewModel |
const dl = hop?.wanJhMetrics.dlMbps const dl = hop?.wanJhMetrics.dlMbps
return ( return (
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3 px-4 py-3.5">
<div className="flex flex-wrap items-center gap-2"> <div className="grid grid-cols-1 gap-x-3.5 gap-y-3 sm:grid-cols-2">
<StatusBadge status={pathStateToServerStatus(model.pathState)} /> <Kv label="Маршрут">Home → WAN → JH → Exit</Kv>
{model.pathState === "failover" ? ( <Kv label="Состояние">
<Badge variant="warning-light" size="sm">failover</Badge> <StatusBadge status={pathStateToServerStatus(model.pathState)} />
) : null} {model.pathState === "failover" ? <Badge variant="warning-light" size="sm">failover</Badge> : null}
{ping != null ? ( </Kv>
<Badge variant="outline" size="sm" className="tabular-nums"> <Kv label="RTT WAN → JH">{ping != null ? <span className="tabular-nums">{`${ping} мс`}</span> : "—"}</Kv>
{ping} мс <Kv label="Загрузка WAN → JH">{dl != null ? <span className="tabular-nums">{`${Math.round(dl)} ↓ Мбит/с`}</span> : "—"}</Kv>
</Badge> <Kv label="Home"><Node name={model.homeRouter.name} country={model.homeRouter.country} /></Kv>
) : null} <Kv label="Активный WAN"><span className="truncate">{`${wanName} · ${wanIsp}`}</span></Kv>
{dl != null ? ( <Kv label="JumpHost"><Node name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"} country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country} /></Kv>
<Badge variant="outline" size="sm" className="tabular-nums"> <Kv label="Exit"><Node name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"} country={hop?.exitNode.country ?? model.fallbackExitNode?.country} /></Kv>
{Math.round(dl)} ↓ Мбит/с
</Badge>
) : null}
</div> </div>
<p className="text-muted-foreground border-t border-dashed pt-2.5 text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
<p className="text-muted-foreground text-xs">JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.</p>
<div className="flex flex-col gap-2 @3xl:flex-row @3xl:items-center">
<HopChip
label="Home"
name={model.homeRouter.name}
country={model.homeRouter.country}
icon={<HomeIcon />}
iconClassName="text-success"
/>
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
<HopChip
label="WAN"
name={`${wanName} · ${wanIsp}`}
icon={<RadioIcon />}
iconClassName="text-info"
/>
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
<HopChip
label="JH"
name={hop?.jumpHost.name ?? model.fallbackJumpHost?.name ?? "—"}
country={hop?.jumpHost.country ?? model.fallbackJumpHost?.country}
icon={<ServerIcon />}
iconClassName="text-primary"
/>
<ArrowRightIcon className="text-muted-foreground hidden size-4 shrink-0 @3xl:block" aria-hidden="true" />
<HopChip
label="Exit"
name={hop?.exitNode.name ?? model.fallbackExitNode?.name ?? "—"}
country={hop?.exitNode.country ?? model.fallbackExitNode?.country}
icon={<GlobeIcon />}
iconClassName="text-muted-foreground"
/>
</div>
<p className="text-muted-foreground text-xs leading-relaxed">
{model.currentPath?.reason ?? "Текущий маршрут не подтверждён"}
</p>
</div> </div>
) )
} }
+22
View File
@@ -0,0 +1,22 @@
import { StatusDot } from "@/components/status-dot"
interface DataFreshnessProps {
/** Время последнего успешного получения данных (мс), null — данных ещё нет. */
at: number | null
live: boolean
}
/** Свежесть данных в шапке страницы: «Обновлено 14:02 · Live» или «Демо-данные». */
export function DataFreshness({ at, live }: DataFreshnessProps) {
const text = !live
? "Демо-данные"
: at == null
? "Данные ещё не получены"
: `Обновлено ${new Date(at).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · Live`
return (
<span role="status" className="text-muted-foreground hidden h-[30px] shrink-0 items-center gap-2 rounded-lg border px-2.5 text-xs min-[1320px]:inline-flex">
<StatusDot status={live && at != null ? "online" : "unknown"} />
{live && at != null ? <time dateTime={new Date(at).toISOString()}>{text}</time> : text}
</span>
)
}
+8 -5
View File
@@ -1,17 +1,20 @@
"use client" "use client"
import { useEffect, useRef } from "react" import { useEffect, useRef } from "react"
import { InfoIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge" import { Badge } from "@/components/ui/badge"
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) { export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
const details = useRef<HTMLDetailsElement>(null) const details = useRef<HTMLDetailsElement>(null)
useEffect(() => { useEffect(() => {
if ((compact || window.matchMedia("(max-width: 767px)").matches) && details.current) details.current.open = false if (compact && details.current) details.current.open = false
}, [compact]) }, [compact])
return ( return (
<details ref={details} open data-map-legend className="absolute left-3 top-3 z-20 max-w-[calc(100%-1.5rem)] rounded-lg border bg-popover text-popover-foreground shadow-sm"> <details ref={details} data-map-legend className="relative">
<summary className="cursor-pointer px-3 py-2 text-xs font-semibold focus-visible:outline-2 focus-visible:outline-ring">Легенда карты</summary> <summary className="border-border/60 text-muted-foreground hover:text-foreground flex h-7 cursor-pointer list-none items-center gap-1.5 rounded-md border px-2.5 text-xs transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
<div role="region" aria-label="Легенда карты" className="flex max-h-[42vh] w-44 max-w-full flex-col gap-2 overflow-y-auto border-t px-3 py-2 text-[11px]"> <InfoIcon aria-hidden="true" className="size-3.5" />Легенда
</summary>
<div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 max-sm:fixed max-sm:inset-x-4 max-sm:top-auto max-sm:w-auto flex max-h-[60vh] w-56 max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border px-3 py-2 text-xs shadow-md">
<div> <div>
<p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p> <p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p>
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5"> <div className="grid grid-cols-2 gap-x-2 gap-y-1.5">
@@ -23,7 +26,7 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<p className="font-medium text-muted-foreground">Тип узла</p> <p className="font-medium text-muted-foreground">Тип узла</p>
{[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"], ["IX", "IX Node", "var(--chart-4)"]].map(([label, name, color]) => ( {[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"], ["IX", "IX Node", "var(--chart-4)"]].map(([label, name, color]) => (
<span key={label} className="flex items-center gap-2"><Badge variant="secondary" style={{ color }} className="min-w-8 justify-center text-[10px]">{label}</Badge><span>{name}</span></span> <span key={label} className="flex items-center gap-2"><Badge variant="secondary" style={{ color }} className="min-w-8 justify-center text-xs">{label}</Badge><span>{name}</span></span>
))} ))}
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded-full border border-current" />WAN · аплинк</span> <span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded-full border border-current" />WAN · аплинк</span>
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded border border-current" />Сервис / страна</span> <span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded border border-current" />Сервис / страна</span>
+166
View File
@@ -0,0 +1,166 @@
"use client"
import type { ReactNode } from "react"
import { FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean }
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string }
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
return (
<div className="max-h-[420px] overflow-auto">
<div className="min-w-[720px]">
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}>
{head.map((h) => <span key={h}>{h}</span>)}
</div>
{empty ? <p className="text-muted-foreground px-4 py-8 text-center text-sm">{empty}</p> : children}
</div>
</div>
)
}
function Row({ cols, hl, children }: { cols: string; hl?: boolean; children: ReactNode }) {
return <div className={cn("grid min-h-11 items-center gap-x-3 border-b px-4 py-1.5 text-[13px] last:border-b-0", cols, hl && "bg-primary/8")}>{children}</div>
}
const FLOW_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_minmax(140px,1.2fr)_110px_100px]"
const RTT_COLS = "grid-cols-[minmax(140px,1fr)_minmax(200px,1.6fr)_90px_minmax(120px,1fr)_110px]"
const DEST_COLS = "grid-cols-[minmax(160px,1.4fr)_minmax(120px,1fr)_110px_minmax(140px,1fr)]"
const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]"
/**
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
* Строки выбранного объекта подсвечены.
*/
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, eventsError, stat }: {
tab: MapBottomTab
onTab: (tab: MapBottomTab) => void
flows: MapFlowRow[]
rtt: MapRttRow[]
destinations: MapDestRow[]
events: MapEventRow[]
eventsError: string | null
stat: string
}) {
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
{ id: "rtt", label: "RTT каналов", count: rtt.length },
{ id: "dest", label: "Назначения", count: destinations.length },
{ id: "events", label: "События", count: events.length },
]
return (
<SectionFrame aria-label="Рабочая панель карты" bare>
<Tabs value={tab} onValueChange={(value) => onTab(value as MapBottomTab)} className="gap-1">
<div className="flex flex-wrap items-center gap-3 px-2 pt-1.5 pb-1">
<TabsList aria-label="Рабочая панель">
{tabs.map((t) => (
<TabsTrigger key={t.id} value={t.id} className="px-2.5">
{t.label}
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
</TabsTrigger>
))}
</TabsList>
<span className="text-muted-foreground ml-auto text-xs">{stat}</span>
</div>
<FramePanel className="p-0">
<TabsContent value="flows">
<Table head={["Источник", "Exit", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
{flows.map((r) => (
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.client}</span>
<span className="truncate font-mono">{r.exit}</span>
<span className="truncate">{r.dest}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="rtt">
<Table head={["Туннель", "Участок", "RTT", "Скорость ↓/↑", "Статус"]} cols={RTT_COLS} empty={rtt.length ? null : "GRE-туннелей на карте нет"}>
{rtt.map((r) => (
<Row key={r.id} cols={RTT_COLS} hl={r.hl}>
<span className="truncate font-mono">{r.name}</span>
<span className="truncate font-mono">{r.route}</span>
<span className="font-mono tabular-nums">{r.rtt}</span>
<span className="font-mono tabular-nums">{r.speed}</span>
<span><ToneBadge tone={r.tone}>{r.status}</ToneBadge></span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="dest">
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
{destinations.map((r) => (
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
<span className="truncate font-medium">{r.label}</span>
<span className="text-muted-foreground truncate">{r.category}</span>
<span className="font-mono tabular-nums">{r.rate}</span>
<span className="flex items-center gap-2">
<span className="bg-muted h-1.5 w-20 overflow-hidden rounded-full"><i className="block h-full rounded-full" style={{ width: `${Math.round(Math.min(1, r.share) * 100)}%`, background: "var(--chart-4)" }} /></span>
<span className="font-mono text-xs tabular-nums">{Math.round(r.share * 100)}%</span>
</span>
</Row>
))}
</Table>
</TabsContent>
<TabsContent value="events">
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={eventsError ? `События недоступны: ${eventsError}` : events.length ? null : "Событий пока нет"}>
{events.map((r) => (
<Row key={r.id} cols={EVENT_COLS}>
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
<span className="truncate font-medium">{r.title}</span>
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
</Row>
))}
</Table>
</TabsContent>
</FramePanel>
</Tabs>
</SectionFrame>
)
}
/**
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
*/
export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; now: number; onPick: (event: MapEventRow) => void }) {
const from = now - 24 * 3_600_000
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
const pos = (ts: number) => `calc(10px + (100% - 20px) * ${((ts - from) / (now - from)).toFixed(4)})`
return (
<div className="flex shrink-0 items-center gap-3 border-t px-3 py-2">
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative h-8 min-w-0 flex-1">
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-1/2 h-px" />
{[0, 0.75, 0.9583].map((t, i) => (
<span key={i} aria-hidden="true" className="text-muted-foreground absolute top-0 -translate-x-1/2 text-xs leading-none" style={{ left: `calc(10px + (100% - 20px) * ${t})` }}>{["−24 ч", "−6 ч", "−1 ч"][i]}</span>
))}
{marks.map((e) => (
<button
key={e.id}
type="button"
onClick={() => onPick(e)}
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
className="focus-visible:ring-ring absolute top-1/2 size-3 -translate-1/2 rounded-full border-2 border-[var(--card)] outline-none focus-visible:ring-2"
style={{ left: pos(e.ts), background: TONE_COLOR[e.tone] }}
/>
))}
<span className="text-success absolute top-1/2 right-0 flex translate-x-1/2 -translate-y-1/2 items-center gap-1 text-xs font-medium">
<ToneDot tone="ok" />Live
</span>
</div>
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small>
</div>
)
}
+102
View File
@@ -0,0 +1,102 @@
"use client"
import type { Server } from "@/lib/data"
import { fmtRate } from "@/lib/fmt-rate"
import { TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
import { cn } from "@/lib/utils"
type StatusFilter = "online" | "degraded" | "offline"
const STATUS: Array<{ key: StatusFilter; label: string; tone: Tone }> = [
{ key: "online", label: "Онлайн", tone: "ok" },
{ key: "degraded", label: "Внимание", tone: "wn" },
{ key: "offline", label: "Оффлайн", tone: "er" },
]
function Seg({ parts }: { parts: Array<{ n: number; color: string }> }) {
const shown = parts.filter((part) => part.n > 0)
return (
<div aria-hidden="true" className="flex h-1.5 gap-0.5">
{shown.length ? shown.map((part, i) => <i key={i} className="block h-full min-w-1.5 rounded-full" style={{ flex: part.n, background: part.color }} />) : <i className="bg-muted block h-full flex-1 rounded-full" />}
</div>
)
}
function Card({ title, value, unit, children }: { title: string; value: string; unit: string; children: React.ReactNode }) {
return (
<div className="bg-card flex min-w-0 flex-col gap-2 rounded-xl border px-4 py-3.5">
<small className="text-muted-foreground text-xs font-medium">{title}</small>
<div className="flex items-baseline gap-1.5 text-2xl leading-tight font-semibold tracking-tight tabular-nums">
{value}
<em className="text-muted-foreground text-[13px] font-normal tracking-normal not-italic">{unit}</em>
</div>
{children}
</div>
)
}
/**
* KPI-полоса над картой (макет v3): узлы, GRE-туннели, NetFlow и узлы, требующие внимания.
* Счётчики статусов фильтруют карту, строки проблем открывают узел.
*/
export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter, onFilter, onSelect, className }: {
servers: Server[]
tunnels: Array<{ status: "up" | "down" | "degraded" }>
/** Байты NetFlow за окно; null — потоки не загружены. */
netflowBytes: number | null
windowSec: number
filter: string
onFilter: (key: StatusFilter | "all") => void
onSelect: (server: Server) => void
className?: string
}) {
const count = (status: Server["status"]) => servers.filter((server) => server.status === status).length
const up = tunnels.filter((tunnel) => tunnel.status === "up").length
const degraded = tunnels.filter((tunnel) => tunnel.status === "degraded").length
const problems = servers.filter((server) => server.enabled !== false && server.status !== "online")
const minutes = Math.max(1, Math.round(windowSec / 60))
return (
<div className={cn("grid grid-cols-[repeat(auto-fit,minmax(min(240px,100%),1fr))] gap-3", className)}>
<Card title="Узлы на карте" value={String(servers.length)} unit="устройств">
<Seg parts={STATUS.map((s) => ({ n: count(s.key), color: TONE_COLOR[s.tone] }))} />
<div className="-mx-1.5 -mb-1 flex flex-wrap gap-0.5">
{STATUS.map((s) => (
<button
key={s.key}
type="button"
aria-pressed={filter === s.key}
onClick={() => onFilter(filter === s.key ? "all" : s.key)}
className={cn("text-muted-foreground hover:bg-muted/70 inline-flex h-[26px] items-center gap-1.5 rounded-md border border-transparent px-1.5 text-[12.5px] transition-colors", filter === s.key && "bg-muted border-border text-foreground")}
>
<span aria-hidden="true" className="size-2 rounded-full" style={{ background: TONE_COLOR[s.tone] }} />
{s.label}{" "}
<b className="text-foreground font-semibold tabular-nums">{count(s.key)}</b>
</button>
))}
</div>
</Card>
<Card title="GRE-туннели на карте" value={tunnels.length ? `${up} из ${tunnels.length}` : "—"} unit="работают">
<Seg parts={[{ n: up, color: TONE_COLOR.ok }, { n: degraded, color: TONE_COLOR.wn }, { n: tunnels.length - up - degraded, color: TONE_COLOR.er }]} />
<div className="text-muted-foreground text-xs">{tunnels.length ? `Деградация: ${degraded} · недоступны: ${tunnels.length - up - degraded}` : "Туннелей на карте нет"}</div>
</Card>
<Card title={`NetFlow · окно ${minutes} мин`} value={netflowBytes == null ? "—" : fmtRate((netflowBytes * 8) / Math.max(1, windowSec))} unit="в среднем за окно">
<Seg parts={[{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
<div className="text-muted-foreground text-xs">{netflowBytes == null ? "Потоки ещё не загружены" : "Все потоки NetFlow за окно"}</div>
</Card>
<Card title="Требуют внимания" value={String(problems.length)} unit="узлов">
{problems.length ? (
<div className="-mx-1.5 -mb-1 flex flex-col">
{problems.slice(0, 3).map((server) => (
<button key={server.id} type="button" onClick={() => onSelect(server)} className="hover:bg-muted/70 flex min-h-[26px] items-center gap-2 rounded-md px-1.5 text-left text-[12.5px] transition-colors">
<span aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ background: TONE_COLOR[server.status === "offline" ? "er" : server.status === "degraded" ? "wn" : "mu"] }} />
<span className="min-w-0 flex-1 truncate">{server.name} — {server.status === "offline" ? "нет ответа" : server.status === "degraded" ? "ухудшение" : "статус неизвестен"}</span>
</button>
))}
</div>
) : (
<div className="text-muted-foreground text-xs">Проблемных узлов нет</div>
)}
</Card>
</div>
)
}
+5 -2
View File
@@ -22,10 +22,12 @@ interface Crumb {
interface PageHeaderProps { interface PageHeaderProps {
crumbs: Crumb[] crumbs: Crumb[]
actions?: ReactNode actions?: ReactNode
/** Состояние данных страницы в шапке, например `<DataFreshness />`. */
status?: ReactNode
} }
/** Header chrome — AppsMenu + SystemMonitor; theme in NavUser. @see https://reui.io/preview/base/app-shell-12 */ /** Header chrome — AppsMenu + SystemMonitor; theme in NavUser. @see https://reui.io/preview/base/app-shell-12 */
export function PageHeader({ crumbs, actions }: PageHeaderProps) { export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
return ( return (
<header className="bg-background sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 md:px-6"> <header className="bg-background sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 md:px-6">
<SidebarTrigger className="-ml-1" /> <SidebarTrigger className="-ml-1" />
@@ -34,7 +36,7 @@ export function PageHeader({ crumbs, actions }: PageHeaderProps) {
<BreadcrumbList className="flex-nowrap"> <BreadcrumbList className="flex-nowrap">
{crumbs.map((crumb, i) => ( {crumbs.map((crumb, i) => (
<Fragment key={i}> <Fragment key={i}>
{i > 0 && <BreadcrumbSeparator className="hidden shrink-0 sm:block" />} {i > 0 && <BreadcrumbSeparator className="text-muted-foreground hidden shrink-0 sm:block">/</BreadcrumbSeparator>}
<BreadcrumbItem className={i < crumbs.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}> <BreadcrumbItem className={i < crumbs.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
{i < crumbs.length - 1 && crumb.href ? ( {i < crumbs.length - 1 && crumb.href ? (
<BreadcrumbLink href={crumb.href}>{crumb.label}</BreadcrumbLink> <BreadcrumbLink href={crumb.href}>{crumb.label}</BreadcrumbLink>
@@ -51,6 +53,7 @@ export function PageHeader({ crumbs, actions }: PageHeaderProps) {
<div className={`ml-auto flex max-w-full items-center gap-2 ${actions ? "w-full xl:w-auto" : "shrink-0"}`}> <div className={`ml-auto flex max-w-full items-center gap-2 ${actions ? "w-full xl:w-auto" : "shrink-0"}`}>
{actions ? <div role="group" aria-label="Действия страницы" className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{actions}</div> : null} {actions ? <div role="group" aria-label="Действия страницы" className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{actions}</div> : null}
<div className="ml-auto flex shrink-0 items-center gap-2"> <div className="ml-auto flex shrink-0 items-center gap-2">
{status}
<AppsMenu /> <AppsMenu />
<SystemMonitorPopover /> <SystemMonitorPopover />
</div> </div>
+36
View File
@@ -0,0 +1,36 @@
import type { ReactNode } from "react"
import { IconTile } from "@/components/reui/icon-tile"
import { cn } from "@/lib/utils"
interface PageTitleProps {
icon?: ReactNode
title: ReactNode
description?: ReactNode
/** Главные действия страницы — одна основная кнопка и не больше двух вторичных. */
actions?: ReactNode
className?: string
}
/** Заголовочный блок страницы макета v3: иконка, h1, описание и действия справа. */
export function PageTitle({ icon, title, description, actions, className }: PageTitleProps) {
return (
<div className={cn("flex min-w-0 flex-wrap items-start justify-between gap-3", className)}>
<div className="flex min-w-0 items-center gap-3">
{icon ? (
<IconTile variant="outline" aria-hidden="true" className="text-muted-foreground shrink-0">
{icon}
</IconTile>
) : null}
<div className="flex min-w-0 flex-col gap-0.5">
<h1 className="text-xl font-semibold">{title}</h1>
{description ? <p className="text-muted-foreground text-sm">{description}</p> : null}
</div>
</div>
{actions ? (
<div role="group" aria-label="Действия страницы" className="flex flex-wrap items-center gap-2">
{actions}
</div>
) : null}
</div>
)
}
+240
View File
@@ -0,0 +1,240 @@
"use client"
import { useId, type ComponentProps, type ReactNode } from "react"
import Link from "next/link"
import { Frame, FramePanel } from "@/components/reui/frame"
import { Badge } from "@/components/reui/badge"
import { IconTile } from "@/components/reui/icon-tile"
import { cn } from "@/lib/utils"
/** Тон состояния из макета v3: ok — в норме, wn — внимание, er — сбой, in — инфо, mu — нет данных. */
export type Tone = "ok" | "wn" | "er" | "in" | "mu"
export const TONE_COLOR: Record<Tone, string> = {
ok: "var(--success)",
wn: "var(--warning)",
er: "var(--destructive)",
in: "var(--chart-4)",
mu: "var(--muted-foreground)",
}
const TONE_BADGE = {
ok: "success-light",
wn: "warning-light",
er: "destructive-light",
in: "info-light",
mu: "outline",
} as const
const TONE_MARK: Record<Tone, string | null> = { ok: "●", wn: "▲", er: "✕", in: null, mu: "○" }
/** Чип состояния макета: светлый Badge с маркером тона (форма дублирует цвет). */
export function ToneBadge({ tone, size = "sm", mark = true, className, children }: {
tone: Tone
size?: "sm" | "default" | "lg"
mark?: boolean
className?: string
children: ReactNode
}) {
const glyph = mark ? TONE_MARK[tone] : null
return (
<Badge variant={TONE_BADGE[tone]} size={size} className={cn("shrink-0", className)}>
{glyph ? <span aria-hidden="true" className="text-[0.5rem] leading-none">{glyph}</span> : null}
{children}
</Badge>
)
}
/** Точка состояния 8px. */
export function ToneDot({ tone, className }: { tone: Tone; className?: string }) {
return <span aria-hidden="true" className={cn("size-2 shrink-0 rounded-full", className)} style={{ background: TONE_COLOR[tone] }} />
}
interface SectionFrameProps extends Omit<ComponentProps<"section">, "title"> {
title?: ReactNode
description?: ReactNode
icon?: ReactNode
actions?: ReactNode
/** Без внутренней панели: дети сами рендерят FramePanel и полосы под шапкой. */
bare?: boolean
panelClassName?: string
}
/**
* Секция макета v3: Frame с шапкой (иконка, заголовок, описание, действия) и одной панелью.
* @see https://reui.io/docs/components/base/frame
*/
export function SectionFrame({ title, description, icon, actions, bare, panelClassName, className, children, ...props }: SectionFrameProps) {
const headingId = useId()
return (
<section aria-labelledby={title ? headingId : undefined} className={cn("min-w-0", className)} {...props}>
<Frame className="gap-1 bg-muted/40 p-1 [--frame-radius:calc(var(--radius)*1.6)] *:data-[slot=frame-panel]:rounded-[calc(var(--radius)*1.25)]">
{title ? (
<div className="flex flex-wrap items-center gap-3 px-2.5 pt-2 pb-1.5">
{icon ? <IconTile variant="outline" size="sm" aria-hidden="true" className="text-muted-foreground">{icon}</IconTile> : null}
<div className="min-w-0 flex-[1_1_200px]">
<h2 id={headingId} className="text-sm font-semibold">{title}</h2>
{description ? <p className="text-muted-foreground mt-px text-[0.78rem]">{description}</p> : null}
</div>
{actions ? <div className="flex flex-wrap items-center gap-2">{actions}</div> : null}
</div>
) : null}
{bare ? children : <FramePanel className={cn("p-0", panelClassName)}>{children}</FramePanel>}
</Frame>
</section>
)
}
/** Сегментная шкала заполнения: 40 делений, заполненные — цветом тона. */
export function SegmentMeter({ ratio, tone, segments = 40, label }: { ratio: number; tone: Tone; segments?: number; label: string }) {
const filled = Math.round(Math.min(1, Math.max(0, ratio)) * segments)
return (
<div role="img" aria-label={label} className="flex h-5 gap-[3px]">
{Array.from({ length: segments }, (_, i) => (
<span key={i} className="flex-1 rounded-full bg-muted" style={i < filled ? { background: TONE_COLOR[tone] } : undefined} />
))}
</div>
)
}
export type CapacityItem = {
id: string
title: string
caption: ReactNode
/** null — значение неизвестно, показывается «—». */
value: number | null
total: number | null
/** Доля заполнения шкалы 0–1; по умолчанию value/total. */
ratio?: number
tone: Tone
icon: ReactNode
href?: string
/** Подпись значения вместо числа (например «2,9»), unit — вместо «из M» (например «ТБ»). */
valueText?: string
unit?: string
}
function pct(ratio: number) {
return `${Math.round(ratio * 100)}%`
}
/**
* Ряд ёмкости «N из M» с сегментной шкалой (блок cap макета v3).
* @see https://reui.io/preview/base/stats-12
*/
export function CapacityGrid({ items, label }: { items: CapacityItem[]; label: string }) {
return (
<SectionFrame aria-label={label} panelClassName="grid grid-cols-1 gap-px bg-border xl:grid-cols-3">
{items.map((item) => {
const known = item.value != null && item.total != null
const ratio = item.ratio ?? (known && item.total! > 0 ? item.value! / item.total! : 0)
const body = (
<>
<div className="flex items-center gap-3">
<IconTile variant="elevated" aria-hidden="true">{item.icon}</IconTile>
<div className="min-w-0">
<h3 className="text-sm font-medium">{item.title}</h3>
<p className="text-muted-foreground text-xs">{item.caption}</p>
</div>
</div>
<div className="flex flex-col gap-3">
<div className="flex items-baseline justify-between">
<p className="flex items-baseline">
<span className="text-2xl font-semibold tracking-tight tabular-nums">{known ? item.valueText ?? item.value : "—"}</span>
{known ? <span className="text-muted-foreground ml-1.5 text-sm">{item.unit ?? `из ${item.total}`}</span> : null}
</p>
{known ? <span className="text-sm font-medium tabular-nums">{pct(ratio)}</span> : null}
</div>
<SegmentMeter ratio={known ? ratio : 0} tone={item.tone} label={`${item.title}: ${known ? `${item.valueText ?? item.value} ${item.unit ?? `из ${item.total}`}` : "нет данных"}`} />
</div>
</>
)
const cell = "bg-card flex min-w-0 flex-col gap-6 p-5"
return item.href ? (
<Link key={item.id} href={item.href} className={cn(cell, "hover:bg-muted/30 focus-visible:ring-ring transition-colors outline-none focus-visible:ring-2 focus-visible:ring-inset")}>
{body}
</Link>
) : (
<div key={item.id} className={cell}>{body}</div>
)
})}
</SectionFrame>
)
}
/** Мини-график 76×32 без осей (k4 sparkline макета). */
export function Sparkline({ values, className }: { values: number[]; className?: string }) {
const finite = values.filter(Number.isFinite)
if (finite.length < 2) return null
const min = Math.min(...finite)
const max = Math.max(...finite)
const span = max - min || 1
const points = finite
.map((v, i) => `${(2 + (i * 72) / (finite.length - 1)).toFixed(1)},${(30 - ((v - min) / span) * 26).toFixed(1)}`)
.join(" ")
return (
<svg viewBox="0 0 76 32" aria-hidden="true" className={cn("absolute top-5 right-4 h-8 w-[76px]", className)}>
<polyline fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" strokeLinejoin="round" points={points} />
</svg>
)
}
export type SparkKpiItem = {
id: string
title: string
value: ReactNode
unit?: string
series?: number[]
delta?: { text: string; tone: Tone } | null
footnote?: ReactNode
href?: string
}
/** Изменение за окно ряда: «↗ 1,2%», тон по направлению (рост — ok, падение — er, если не задано иначе). */
export function seriesDelta(series: number[] | undefined, upTone: Tone = "ok", downTone: Tone = "er"): SparkKpiItem["delta"] {
const finite = (series ?? []).filter(Number.isFinite)
if (finite.length < 2) return null
const first = finite[0]
const last = finite[finite.length - 1]
if (first === 0) return null
const change = ((last - first) / Math.abs(first)) * 100
const text = `${change >= 0 ? "↗" : "↘"} ${Math.abs(change).toLocaleString("ru-RU", { maximumFractionDigits: 1 })}%`
return { text, tone: change >= 0 ? upTone : downTone }
}
/**
* Четыре KPI со спарклайном и чипом изменения (блок spark макета v3).
* @see https://reui.io/preview/base/stats-12
*/
export function SparkKpiGrid({ items, label }: { items: SparkKpiItem[]; label: string }) {
return (
<SectionFrame aria-label={label} panelClassName="grid grid-cols-1 gap-px bg-border sm:grid-cols-2 xl:grid-cols-4">
{items.map((item) => {
const body = (
<>
{item.series ? <Sparkline values={item.series} /> : null}
<div className="pr-24">
<div className="text-xl font-semibold tabular-nums">
{item.value}
{item.unit ? <span className="text-muted-foreground/40 pl-0.5 font-semibold">{item.unit}</span> : null}
</div>
<h3 className="text-muted-foreground mt-0.5 text-xs leading-none font-normal">{item.title}</h3>
</div>
<div className="text-muted-foreground mt-5 flex items-center gap-2 text-xs">
{item.delta ? <ToneBadge tone={item.delta.tone} mark={false}>{item.delta.text}</ToneBadge> : null}
{item.footnote ? <span className="min-w-0 truncate">{item.footnote}</span> : null}
</div>
</>
)
const cell = "bg-card relative block min-h-[102px] overflow-hidden p-4"
return item.href ? (
<Link key={item.id} href={item.href} className={cn(cell, "hover:bg-muted/30 focus-visible:ring-ring transition-colors outline-none focus-visible:ring-2 focus-visible:ring-inset")}>
{body}
</Link>
) : (
<div key={item.id} className={cell}>{body}</div>
)
})}
</SectionFrame>
)
}
@@ -1,7 +1,8 @@
"use client" "use client"
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts" import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts"
import { Frame, FramePanel } from "@/components/reui/frame" import type { ReactNode } from "react"
import { SectionFrame } from "@/components/reui-kit/ops-blocks"
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart" import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
import { formatBytes } from "@/lib/fmt-rate" import { formatBytes } from "@/lib/fmt-rate"
import type { StatisticsSeriesPoint } from "@mmapp/contracts/statistics" import type { StatisticsSeriesPoint } from "@mmapp/contracts/statistics"
@@ -45,9 +46,14 @@ function CustomTooltip({
export function StatisticsVolumeChart({ export function StatisticsVolumeChart({
series, series,
grain, grain,
scope,
actions,
}: { }: {
series: StatisticsSeriesPoint[] series: StatisticsSeriesPoint[]
grain: "hour" | "day" grain: "hour" | "day"
/** Какие плоскости в объёме, для подписи под заголовком. */
scope?: string
actions?: ReactNode
}) { }) {
const data = series.map((p) => ({ const data = series.map((p) => ({
t: p.t, t: p.t,
@@ -57,14 +63,12 @@ export function StatisticsVolumeChart({
const tickEvery = Math.max(1, Math.ceil(data.length / 8)) const tickEvery = Math.max(1, Math.ceil(data.length / 8))
return ( return (
<Frame className="w-full"> <SectionFrame
<FramePanel className="flex flex-col gap-4"> title="Объём по времени"
<div className="flex items-baseline justify-between gap-2"> description={[scope, grain === "hour" ? "по часам" : "по суткам"].filter(Boolean).join(" · ")}
<h2 className="text-sm font-medium">Объём по времени</h2> actions={actions}
<span className="text-muted-foreground text-xs"> panelClassName="px-3.5 pt-3.5 pb-2"
{grain === "hour" ? "по часам" : "по суткам"} >
</span>
</div>
{data.length === 0 ? ( {data.length === 0 ? (
<p className="text-muted-foreground py-10 text-center text-sm">Нет данных за выбранный период</p> <p className="text-muted-foreground py-10 text-center text-sm">Нет данных за выбранный период</p>
) : ( ) : (
@@ -99,7 +103,6 @@ export function StatisticsVolumeChart({
</AreaChart> </AreaChart>
</ChartContainer> </ChartContainer>
)} )}
</FramePanel> </SectionFrame>
</Frame>
) )
} }
+9 -9
View File
@@ -74,22 +74,22 @@ export function FlowEntityCardView({
<StatusDot status={card.status} /> <StatusDot status={card.status} />
<span className="text-xs font-medium truncate">{card.name}</span> <span className="text-xs font-medium truncate">{card.name}</span>
</div> </div>
<span className="text-[10px] font-mono text-muted-foreground shrink-0 flex items-center gap-1"> <span className="text-xs font-mono text-muted-foreground shrink-0 flex items-center gap-1">
{card.country !== "UN" ? <Flag code={card.country} /> : null} {card.country !== "UN" ? <Flag code={card.country} /> : null}
{card.site} {card.site}
</span> </span>
</div> </div>
<TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} /> <TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />
<div className="flex justify-between mt-2 gap-2"> <div className="flex justify-between mt-2 gap-2">
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowDownIcon className="size-3 text-success" /> <ArrowDownIcon className="size-3 text-success" />
<span className="font-mono font-medium text-success">{fmtRate(card.rxNow)}</span> <span className="font-mono font-medium text-success">{fmtRate(card.rxNow)}</span>
</div> </div>
<div className="flex items-center gap-1 text-[11px]"> <div className="flex items-center gap-1 text-xs">
<ArrowUpIcon className="size-3 text-info" /> <ArrowUpIcon className="size-3 text-info" />
<span className="font-mono font-medium text-info">{fmtRate(card.txNow)}</span> <span className="font-mono font-medium text-info">{fmtRate(card.txNow)}</span>
</div> </div>
<div className="flex items-center gap-0.5 text-[10px] text-muted-foreground"> <div className="flex items-center gap-0.5 text-xs text-muted-foreground">
<GitBranchIcon className="size-3" />{card.sessions} <GitBranchIcon className="size-3" />{card.sessions}
</div> </div>
</div> </div>
@@ -265,7 +265,7 @@ function FlowPathsGrid({
cell: ({ row }) => ( cell: ({ row }) => (
<span className="flex min-w-0 flex-col gap-0.5 text-xs"> <span className="flex min-w-0 flex-col gap-0.5 text-xs">
<span className="font-mono">{row.original.dst}</span> <span className="font-mono">{row.original.dst}</span>
<span className="text-[10px] text-muted-foreground truncate"> <span className="text-xs text-muted-foreground truncate">
{[row.original.category, row.original.service].filter(Boolean).join(" · ")} {[row.original.category, row.original.service].filter(Boolean).join(" · ")}
</span> </span>
</span> </span>
@@ -445,12 +445,12 @@ export function FlowAnalyticsDetail({
{analytics?.ifaces && analytics.ifaces.length > 0 ? ( {analytics?.ifaces && analytics.ifaces.length > 0 ? (
<div className="mb-3 pb-3 border-b"> <div className="mb-3 pb-3 border-b">
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2 flex-wrap">
<span className="text-[11px] text-muted-foreground mr-1">Интерфейс:</span> <span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
<button <button
type="button" type="button"
onClick={() => onIface("__all__")} onClick={() => onIface("__all__")}
className={cn( className={cn(
"inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
selectedIface === "__all__" selectedIface === "__all__"
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -466,7 +466,7 @@ export function FlowAnalyticsDetail({
type="button" type="button"
onClick={() => onIface(iface.name)} onClick={() => onIface(iface.name)}
className={cn( className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-medium transition-all", "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium transition-all",
active active
? "bg-foreground text-background border-foreground" ? "bg-foreground text-background border-foreground"
: "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40", : "border-border text-muted-foreground hover:text-foreground hover:border-foreground/40",
@@ -477,7 +477,7 @@ export function FlowAnalyticsDetail({
) )
})} })}
</div> </div>
<p className="text-[10px] text-muted-foreground mt-1.5">по iface, без дедупа</p> <p className="text-xs text-muted-foreground mt-1.5">по iface, без дедупа</p>
</div> </div>
) : null} ) : null}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+23 -2
View File
@@ -7,6 +7,7 @@ import {
greTunnels as mockGreTunnels, greTunnels as mockGreTunnels,
pingProbes, pingProbes,
servers as mockServers, servers as mockServers,
systemEvents as mockEvents,
traffic as mockTraffic, traffic as mockTraffic,
vxlanTunnels as mockVxlan, vxlanTunnels as mockVxlan,
type GreTunnel, type GreTunnel,
@@ -581,6 +582,25 @@ export function useDashboardLive() {
})) }))
}, [enabledProbes]) }, [enabledProbes])
// Демо-режим: события и Internet path из моков, чтобы раздел выглядел как с данными.
const [mockNow] = useState(() => Date.now())
const mockRecentEvents = useMemo<EventItem[]>(() => {
const unit: Record<string, number> = { м: 60_000, ч: 3_600_000, д: 86_400_000 }
return mockEvents.map((event) => {
const match = /^(d+)([мчд])$/.exec(event.when)
const ago = match ? Number(match[1]) * unit[match[2]] : 0
return {
id: event.id, title: event.title, message: event.message,
level: event.sev === "destructive" ? "critical" : event.sev === "warning" ? "warning" : "info",
sourceModule: "system", eventType: "demo", createdAt: new Date(mockNow - ago).toISOString(),
entityId: null, entityType: null, payload: {},
} as EventItem
})
}, [mockNow])
const mockInternetPath = useMemo(() => buildDashboardInternetPath({
servers: mockServers, greTunnels: mockGreTunnels, probes: [], filtersRulesets: [], routeLookupByServerId: {}, wanRuntimeByHomeId: {},
}), [])
const onlineCount = servers.filter((s) => s.status === "online").length const onlineCount = servers.filter((s) => s.status === "online").length
const probeDown = enabledProbes.filter((p) => p.status === "down").length const probeDown = enabledProbes.filter((p) => p.status === "down").length
const probeWarn = enabledProbes.filter((p) => p.status === "warn").length const probeWarn = enabledProbes.filter((p) => p.status === "warn").length
@@ -622,6 +642,7 @@ export function useDashboardLive() {
}, },
servers, servers,
activeProbes, activeProbes,
enabledProbes,
overlay, overlay,
bgp: isLive ? bgp : { prefixSum: 8432, establishedCount: 3 }, bgp: isLive ? bgp : { prefixSum: 8432, establishedCount: 3 },
traffic, traffic,
@@ -635,10 +656,10 @@ export function useDashboardLive() {
probeCount: enabledProbes.length, probeCount: enabledProbes.length,
unknownProbeCount:enabledProbes.filter(p=>p.status==="unknown").length, unknownProbeCount:enabledProbes.filter(p=>p.status==="unknown").length,
latency, latency,
recentEvents, recentEvents: !prefsHydrated ? [] : isLive ? recentEvents : mockRecentEvents,
eventsLoading, eventsLoading,
eventsError, eventsError,
internetPath, internetPath: !prefsHydrated ? null : isLive ? internetPath : mockInternetPath,
internetPathLoading: isLive && internetPathLoading && !internetPath, internetPathLoading: isLive && internetPathLoading && !internetPath,
internetPathError, internetPathError,
attentionServers, attentionServers,
+81 -36
View File
@@ -37,14 +37,51 @@ export function greTunnelProbe(t: GreTunnel, demo = false): TunnelProbe {
} }
const W = 1240 const W = 1240
const H = 580 const H = 640
const MARGIN = 72
const SERVICE_COL_W = 150
export { SERVICE_COL_W }
/** Карточка конечного сервиса на карте (центр = позиция узла). */ /**
export const MAP_SERVICE_NODE_W = 86 * Полосы карты макета v3 слева направо: Home Router · WAN · JumpHost · Exit (и IX) · назначения.
export const MAP_SERVICE_NODE_H = 58 * x0/x1 — границы полосы на холсте, cx — центр карточек.
*/
export const MAP_LANES = {
home: { x0: 8, x1: 215, cx: 112 },
wan: { x0: 215, x1: 425, cx: 320 },
jh: { x0: 425, x1: 660, cx: 542 },
en: { x0: 660, x1: 900, cx: 780 },
dest: { x0: 900, x1: 1232, cx: 1080 },
} as const
/** Карточка устройства (HR/JH/EN/IX) и «таблетка» WAN-аплинка. */
export const MAP_CARD_W = 160
export const MAP_CARD_H = 56
export const MAP_WAN_W = 150
export const MAP_WAN_H = 44
/** Строка назначения; в раскрытой стране обе колонки компактные. */
export const MAP_SERVICE_NODE_W = 280
export const MAP_SERVICE_NODE_H = 48
export const MAP_SERVICE_COMPACT_W = 150
/** Сдвиг колонки стран влево, когда справа раскрыты сервисы одной страны. */
export const SERVICE_COL_W = 130
const NESTED_SERVICE_X = 1160
const MIN_NODE_Y = 80
const MAX_NODE_Y = H - 44
/**
* Плавная связь между боковыми гранями двух карточек: горизонтальная кривая Безье, как в макете.
* Если карточки в одной полосе — дуга справа от обеих.
*/
export function mapLinkPath(
a: { x: number; y: number }, aHalfW: number,
b: { x: number; y: number }, bHalfW: number,
): { d: string; x1: number; y1: number; x2: number; y2: number } {
if (Math.abs(b.x - a.x) < aHalfW + bHalfW) {
const x1 = a.x + aHalfW, x2 = b.x + bHalfW, bend = Math.max(x1, x2) + 48
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y }
}
const dir = b.x > a.x ? 1 : -1
const x1 = a.x + dir * aHalfW, x2 = b.x - dir * bHalfW, mx = (x1 + x2) / 2
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y }
}
/** Одна горизонтальная «полка» на карте: Home → JH → Exit слева направо. */ /** Одна горизонтальная «полка» на карте: Home → JH → Exit слева направо. */
export const NETWORK_MAP_PIPELINE_Y = 300 export const NETWORK_MAP_PIPELINE_Y = 300
@@ -79,7 +116,7 @@ function layerOfServer(s: Server): number | null {
*/ */
export const NETWORK_MAP_W = W export const NETWORK_MAP_W = W
export const NETWORK_MAP_H = H export const NETWORK_MAP_H = H
export const NETWORK_MAP_LAYOUT_REVISION = 7 export const NETWORK_MAP_LAYOUT_REVISION = 8
export interface WanJhEdge { export interface WanJhEdge {
homeId: string homeId: string
@@ -266,9 +303,12 @@ export function computeNetworkMapLayout(
const nodePos: Record<string, { x: number; y: number }> = {} const nodePos: Record<string, { x: number; y: number }> = {}
const wanSatPos: Record<string, { x: number; y: number }[]> = {} const wanSatPos: Record<string, { x: number; y: number }[]> = {}
const span = W - 2 * MARGIN - SERVICE_COL_W const laneCenterX: Record<ServerType, number> = {
const laneGap = Math.min(44, span * 0.04) "home-router": MAP_LANES.home.cx,
const laneW = (span - 2 * laneGap) / 3 "jump-host": MAP_LANES.jh.cx,
"exit-node": MAP_LANES.en.cx,
"ix-node": MAP_LANES.en.cx,
}
// Жёсткое позиционирование по иерархическим слоям: // Жёсткое позиционирование по иерархическим слоям:
// - HR: левая полоса (0–20%), // - HR: левая полоса (0–20%),
@@ -277,9 +317,9 @@ export function computeNetworkMapLayout(
const laneOrder: ServerType[] = ["home-router", "jump-host", "exit-node"] const laneOrder: ServerType[] = ["home-router", "jump-host", "exit-node"]
if (servers.some(server => server.type === "ix-node")) laneOrder.splice(2, 0, "ix-node") if (servers.some(server => server.type === "ix-node")) laneOrder.splice(2, 0, "ix-node")
const laneByType = new Map<ServerType, Server[]>() const laneByType = new Map<ServerType, Server[]>()
const minNodeY = MARGIN + 70 const minNodeY = MIN_NODE_Y
const maxNodeY = H - 72 const maxNodeY = MAX_NODE_Y
const laneMinGap = 110 const laneMinGap = MAP_CARD_H + 18
const typeYOffset: Record<ServerType, number> = { const typeYOffset: Record<ServerType, number> = {
"home-router": -14, "home-router": -14,
"jump-host": 0, "jump-host": 0,
@@ -309,7 +349,6 @@ export function computeNetworkMapLayout(
siteY.set(site, spreadInSegment(siteNames.length, i, minNodeY, maxNodeY)) siteY.set(site, spreadInSegment(siteNames.length, i, minNodeY, maxNodeY))
}) })
const fallbackY = (minNodeY + maxNodeY) / 2 const fallbackY = (minNodeY + maxNodeY) / 2
let xLane = MARGIN
for (const type of laneOrder) { for (const type of laneOrder) {
const group = servers const group = servers
.filter((s) => s.type === type) .filter((s) => s.type === type)
@@ -317,22 +356,17 @@ export function computeNetworkMapLayout(
.sort((a, b) => `${a.site}|${a.name}|${a.id}`.localeCompare(`${b.site}|${b.name}|${b.id}`)) .sort((a, b) => `${a.site}|${a.name}|${a.id}`.localeCompare(`${b.site}|${b.name}|${b.id}`))
laneByType.set(type, group) laneByType.set(type, group)
const xMin = xLane
const xMax = xLane + laneW
const laneCenterX = (xMin + xMax) / 2
group.forEach((s) => { group.forEach((s) => {
const baseline = siteY.get(s.site) ?? fallbackY const baseline = siteY.get(s.site) ?? fallbackY
const siblings = group.filter((g) => g.site === s.site) const siblings = group.filter((g) => g.site === s.site)
const sibIdx = siblings.findIndex((g) => g.id === s.id) const sibIdx = siblings.findIndex((g) => g.id === s.id)
const spread = siblings.length <= 1 ? 0 : (sibIdx - (siblings.length - 1) / 2) * 34 const spread = siblings.length <= 1 ? 0 : (sibIdx - (siblings.length - 1) / 2) * 34
nodePos[s.id] = { nodePos[s.id] = {
x: laneCenterX, x: laneCenterX[type],
y: clamp(baseline + typeYOffset[type] + spread, minNodeY, maxNodeY), y: clamp(baseline + typeYOffset[type] + spread, minNodeY, maxNodeY),
} }
}) })
xLane += laneW + laneGap
} }
const homes = laneByType.get("home-router") ?? [] const homes = laneByType.get("home-router") ?? []
@@ -412,30 +446,41 @@ export function computeNetworkMapLayout(
resolveLaneCollisions(exits.map((s) => s.id), nodePos, minNodeY, maxNodeY, laneMinGap) resolveLaneCollisions(exits.map((s) => s.id), nodePos, minNodeY, maxNodeY, laneMinGap)
} }
// IX-узлы делят полосу Exit: разводим их вместе с EN, чтобы карточки не наезжали.
const ixs = laneByType.get("ix-node") ?? []
if (ixs.length) resolveLaneCollisions([...exits, ...ixs].map((s) => s.id), nodePos, minNodeY, maxNodeY, laneMinGap)
const hr = homes const hr = homes
/** Центр колонки jump-host — спутники WAN ставим на X между HR и JH (как на схеме «шлюз → провайдеры → JH»). */
const jhColumnCenterX = MARGIN + laneW + laneGap + laneW / 2
for (const r of hr) { for (const r of hr) {
const wans = r.wanUplinks?.length ? r.wanUplinks : [] const wans = r.wanUplinks?.length ? r.wanUplinks : []
const base = nodePos[r.id] ?? { x: W / 2, y: NETWORK_MAP_PIPELINE_Y } const base = nodePos[r.id] ?? { x: W / 2, y: NETWORK_MAP_PIPELINE_Y }
const n = wans.length const n = wans.length
const satX = (base.x + jhColumnCenterX) / 2 const satX = MAP_LANES.wan.cx
const rowY = base.y const rowY = base.y
const maxV = H - 2 * MARGIN - 96 const maxV = MAX_NODE_Y - MIN_NODE_Y
// Разносим WAN-аплинки по высоте заметнее для читаемости подписей/бейджей. // Своя полоса WAN: «таблетки» аплинков друг под другом напротив роутера.
const preferredGap = 140 const preferredGap = MAP_WAN_H + 46
const vGap = const vGap =
n <= 1 ? 0 : Math.min(preferredGap, maxV / Math.max(1, n - 1)) n <= 1 ? 0 : Math.min(preferredGap, maxV / Math.max(1, n - 1))
const positions: { x: number; y: number }[] = [] const positions: { x: number; y: number }[] = []
for (let i = 0; i < n; i++) { for (let i = 0; i < n; i++) {
const rawY = n === 1 ? rowY : rowY + (i - (n - 1) / 2) * vGap const rawY = n === 1 ? rowY : rowY + (i - (n - 1) / 2) * vGap
const y = Math.max(MARGIN + 48, Math.min(H - 72, rawY)) const y = Math.max(MIN_NODE_Y, Math.min(MAX_NODE_Y, rawY))
positions.push({ x: satX, y }) positions.push({ x: satX, y })
} }
wanSatPos[r.id] = positions wanSatPos[r.id] = positions
} }
// Аплинки всех роутеров делят одну полосу: раздвигаем «таблетки», чтобы не наезжали друг на друга.
const sats = Object.values(wanSatPos).flat().sort((a, b) => a.y - b.y)
for (let i = 1; i < sats.length; i++) {
const min = sats[i - 1].y + MAP_WAN_H + 12
if (sats[i].y < min) sats[i].y = min
}
const overflow = (sats[sats.length - 1]?.y ?? 0) - MAX_NODE_Y
if (overflow > 0) for (const p of sats) p.y = Math.max(MIN_NODE_Y, p.y - overflow)
return { nodePos, wanSatPos } return { nodePos, wanSatPos }
} }
@@ -446,13 +491,13 @@ export function placeServiceNodes(
): Record<string, { x: number; y: number }> { ): Record<string, { x: number; y: number }> {
const out: Record<string, { x: number; y: number }> = {} const out: Record<string, { x: number; y: number }> = {}
if (serviceIds.length === 0) return out if (serviceIds.length === 0) return out
const minY = MARGIN + 70 const minY = MIN_NODE_Y
const maxY = H - 72 const maxY = MAX_NODE_Y
const x = W - MARGIN - SERVICE_COL_W / 2 const x = MAP_LANES.dest.cx
const enYs = enPositions.map((p) => p.y).filter((y) => Number.isFinite(y)) const enYs = enPositions.map((p) => p.y).filter((y) => Number.isFinite(y))
const centerY = enYs.length ? enYs.reduce((a, b) => a + b, 0) / enYs.length : (minY + maxY) / 2 const centerY = enYs.length ? enYs.reduce((a, b) => a + b, 0) / enYs.length : (minY + maxY) / 2
const n = serviceIds.length const n = serviceIds.length
const gap = Math.min(96, (maxY - minY) / Math.max(1, n)) const gap = Math.min(MAP_SERVICE_NODE_H + 14, (maxY - minY) / Math.max(1, n))
const span = gap * (n - 1) const span = gap * (n - 1)
const start = clamp(centerY - span / 2, minY, maxY - span) const start = clamp(centerY - span / 2, minY, maxY - span)
serviceIds.forEach((id, i) => { serviceIds.forEach((id, i) => {
@@ -468,11 +513,11 @@ export function placeCountryServiceNodes(
): Record<string, { x: number; y: number }> { ): Record<string, { x: number; y: number }> {
const out: Record<string, { x: number; y: number }> = {} const out: Record<string, { x: number; y: number }> = {}
if (serviceIds.length === 0 || !parentPos) return out if (serviceIds.length === 0 || !parentPos) return out
const minY = MARGIN + 70 const minY = MIN_NODE_Y
const maxY = H - 72 const maxY = MAX_NODE_Y
const x = W - MARGIN - SERVICE_COL_W / 2 const x = NESTED_SERVICE_X
const n = serviceIds.length const n = serviceIds.length
const gap = Math.min(80, (maxY - minY) / Math.max(1, n)) const gap = Math.min(MAP_SERVICE_NODE_H + 8, (maxY - minY) / Math.max(1, n))
const span = gap * (n - 1) const span = gap * (n - 1)
const start = clamp(parentPos.y - span / 2, minY, maxY - span) const start = clamp(parentPos.y - span / 2, minY, maxY - span)
serviceIds.forEach((id, i) => { serviceIds.forEach((id, i) => {
+60
View File
@@ -0,0 +1,60 @@
import type { StatisticsBreakdownRow, StatisticsDto, StatisticsPivotDim, StatisticsPivotDto } from "@mmapp/contracts/statistics"
import { servers as mockServers } from "@/lib/data"
const GB = 1_000_000_000
function rows(items: Array<[string, string, number]>, total: number, seconds: number): StatisticsBreakdownRow[] {
return items.map(([id, label, gb]) => {
const bytes = gb * GB
return { id, label, bytes, packets: Math.round(bytes / 1200), bps: Math.round((bytes * 8) / seconds), percent: Math.round((bytes / total) * 1000) / 10 }
})
}
const DIM_ROWS: Record<StatisticsPivotDim, Array<[string, string, number]>> = {
country: [["US", "США", 1310], ["DE", "Германия", 720], ["NL", "Нидерланды", 540], ["FI", "Финляндия", 260], ["SE", "Швеция", 180]],
service: [["youtube", "YouTube", 1140], ["cloudflare", "Cloudflare", 690], ["microsoft", "Microsoft", 430], ["telegram", "Telegram", 260], ["aws", "AWS", 210]],
asn: [["15169", "AS15169 Google", 1160], ["13335", "AS13335 Cloudflare", 700], ["8075", "AS8075 Microsoft", 430], ["16509", "AS16509 Amazon", 230]],
server: mockServers.slice(0, 5).map((s, i): [string, string, number] => [s.id, s.name, [1480, 1120, 640, 420, 210][i] ?? 100]),
user: [["u1", "admin-laptop", 980], ["u2", "ivanov-phone", 720], ["u3", "office-gw", 610], ["u4", "petrova-pc", 380], ["u5", "guest-wifi", 210]],
iface: [["wg0", "wg0", 1120], ["wg1", "wg1", 760], ["gre-nov", "gre-nov", 540], ["gre-fra", "gre-fra", 380]],
} as Record<StatisticsPivotDim, Array<[string, string, number]>>
/** Демо-куб для режима без живого API: стабильные числа, масштаб по длине периода и плоскостям. */
export function demoStatistics(from: string, to: string, planes: "unique" | "all"): StatisticsDto {
const start = Date.parse(from + "T00:00:00Z")
const end = Date.parse(to + "T00:00:00Z")
const days = Number.isFinite(start) && Number.isFinite(end) ? Math.max(1, Math.round((end - start) / 86_400_000) + 1) : 7
const scale = (days / 7) * (planes === "all" ? 1.27 : 1)
const scaled = (items: Array<[string, string, number]>) => items.map(([id, label, gb]): [string, string, number] => [id, label, Math.round(gb * scale * 10) / 10])
const users = scaled(DIM_ROWS.user)
const total = users.reduce((sum, [, , gb]) => sum + gb, 0) * GB * 1.65
const seconds = days * 86_400
const series = Array.from({ length: days }, (_, i) => ({
t: new Date(start + i * 86_400_000).toISOString(),
bytes: Math.round((total / days) * (0.82 + 0.36 * Math.abs(Math.sin(i * 1.7)))),
}))
return {
from, to, grain: "day",
kpis: { bytes: total, packets: Math.round(total / 1200), avgBps: Math.round((total * 8) / seconds), users: users.length, servers: DIM_ROWS.server.length, ifaces: DIM_ROWS.iface.length, topCountry: "США", topService: "YouTube" },
series,
users: rows(users, total, seconds),
servers: rows(scaled(DIM_ROWS.server), total, seconds),
interfaces: rows(scaled(DIM_ROWS.iface), total, seconds),
countries: rows(scaled(DIM_ROWS.country), total, seconds),
services: rows(scaled(DIM_ROWS.service), total, seconds),
asns: rows(scaled(DIM_ROWS.asn), total, seconds),
}
}
/** Демо-сводная: строки и колонки из тех же списков, ячейка — доля строки по весу колонки. */
export function demoStatisticsPivot(rowDim: StatisticsPivotDim, colDim: StatisticsPivotDim): StatisticsPivotDto {
const rowItems = DIM_ROWS[rowDim] ?? []
const colItems = DIM_ROWS[colDim] ?? []
const colWeight = colItems.reduce((sum, [, , gb]) => sum + gb, 0) || 1
const outRows = rowItems.map(([id, label, gb]) => {
const cells = Object.fromEntries(colItems.map(([cid, , cgb]) => [cid, Math.round(gb * (cgb / colWeight) * GB)]))
return { id, label, total: gb * GB, cells }
})
const columns = colItems.map(([id, label]) => ({ id, label, total: outRows.reduce((sum, row) => sum + (row.cells[id] ?? 0), 0) }))
return { rowDim, colDim, metric: "bytes", columns, rows: outRows, otherBytes: 0 }
}
@@ -48,6 +48,7 @@ const linuxPolicy = z.object({
clientId: z.string().uuid().optional(), clientId: z.string().uuid().optional(),
enabled: z.boolean(), enabled: z.boolean(),
destinations: z.array(prefix).max(64), destinations: z.array(prefix).max(64),
tunnelMtu: z.number().int().min(1280).max(1420).optional(),
exit: key.optional(), exit: key.optional(),
peerEndpoint: address.optional(), peerEndpoint: address.optional(),
}).strict() }).strict()
@@ -152,6 +153,7 @@ export const ixLinuxClientRequest = z.object({
peerAddress: address.optional(), peerAddress: address.optional(),
prefixes: z.array(prefix).max(64).default([]), prefixes: z.array(prefix).max(64).default([]),
destinations: linuxPolicy.shape.destinations.default([]), destinations: linuxPolicy.shape.destinations.default([]),
tunnelMtu: linuxPolicy.shape.tunnelMtu,
exit: key.optional(), exit: key.optional(),
transit: ixTransitOptions.optional(), transit: ixTransitOptions.optional(),
rotate: z.boolean().optional(), rotate: z.boolean().optional(),
+26 -29
View File
@@ -51,15 +51,9 @@ test("Дашборд: очередь над измерениями, полный
await setup(page, false, 7) await setup(page, false, 7)
await expect(refresh(page)).toBeEnabled() await expect(refresh(page)).toBeEnabled()
const queue = page.getByRole("region", { name: "Требует внимания", exact: true }) const queue = page.getByRole("region", { name: "Требует внимания", exact: true })
await expect(queue.getByText("7", { exact: true })).toBeVisible() await expect(queue.getByRole("tab", { name: /^Все \d+$/ })).toBeVisible()
const serverLinks = queue.getByRole("link", { name: /^Узел \d/ }) const serverLinks = queue.getByRole("link", { name: /^Узел \d/ })
await expect(serverLinks).toHaveCount(5)
const more = queue.locator("summary").filter({ hasText: "Ещё 2" })
await more.focus()
await more.press("Enter")
await expect(serverLinks).toHaveCount(7) await expect(serverLinks).toHaveCount(7)
await more.press("Enter")
await expect(serverLinks).toHaveCount(5)
const queueBox = await queue.boundingBox() const queueBox = await queue.boundingBox()
const measurementBox = await page.getByText("Задержка до серверов", { exact: true }).boundingBox() const measurementBox = await page.getByText("Задержка до серверов", { exact: true }).boundingBox()
expect(queueBox!.y + queueBox!.height).toBeLessThan(measurementBox!.y) expect(queueBox!.y + queueBox!.height).toBeLessThan(measurementBox!.y)
@@ -80,7 +74,10 @@ test("Дашборд: очередь над измерениями, полный
test("Дашборд: первоначальная ошибка не подменяется нулями и исправным состоянием", async ({ page }) => { test("Дашборд: первоначальная ошибка не подменяется нулями и исправным состоянием", async ({ page }) => {
const control = await setup(page, true) const control = await setup(page, true)
await expect(refresh(page)).toBeEnabled() await expect(refresh(page)).toBeEnabled()
await expect(page.getByText("Не обновлены источники: 9", { exact: true }).first()).toBeVisible() await expect(page.getByText("Не все источники доступны.", { exact: true })).toBeVisible()
await page.getByRole("button", { name: "Объяснить", exact: true }).click()
await expect(page.getByRole("tab", { name: /^Источники и время получения/ })).toHaveAttribute("aria-selected", "true")
await expect(page.getByText("Не обновлены источники: 9", { exact: true })).toBeVisible()
await expect(page.getByRole("link").filter({ hasText: "Серверы онлайн" })).toContainText("—") await expect(page.getByRole("link").filter({ hasText: "Серверы онлайн" })).toContainText("—")
await expect(bgp(page)).toContainText("—") await expect(bgp(page)).toContainText("—")
await expect(page.getByText("Серверы без проблем", { exact: true })).toHaveCount(0) await expect(page.getByText("Серверы без проблем", { exact: true })).toHaveCount(0)
@@ -88,7 +85,7 @@ test("Дашборд: первоначальная ошибка не подме
control.failed = false control.failed = false
await refresh(page).click() await refresh(page).click()
await expect(bgp(page)).toContainText("321") await expect(bgp(page)).toContainText("321")
await expect(page.getByText("Не обновлены источники: 9", { exact: true })).toHaveCount(0) await expect(page.getByText("Не все источники доступны.", { exact: true })).toHaveCount(0)
}) })
test("Дашборд: частичный сбой сохраняет данные, события и время последнего успеха", async ({ page }) => { test("Дашборд: частичный сбой сохраняет данные, события и время последнего успеха", async ({ page }) => {
@@ -99,12 +96,12 @@ test("Дашборд: частичный сбой сохраняет данны
const receivedAt = await source.locator("time").getAttribute("datetime") const receivedAt = await source.locator("time").getAttribute("datetime")
control.partial = true control.partial = true
await refresh(page).click() await refresh(page).click()
await expect(source).toContainText("ошибка обновления") await expect(source).toContainText(/ошибка обновления/i)
await expect(source.locator("time")).toHaveAttribute("datetime", receivedAt!) await expect(source.locator("time")).toHaveAttribute("datetime", receivedAt!)
await expect(bgp(page)).toContainText("321") await expect(bgp(page)).toContainText("321")
await expect(page.getByText("Событие сохранено", { exact: true })).toBeVisible() await expect(page.getByText("Событие сохранено", { exact: true })).toBeVisible()
await expect(page.getByText("GRE сохранён", { exact: true })).toBeVisible() await expect(page.getByText("GRE сохранён", { exact: true })).toBeVisible()
await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка") await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i)
await page.screenshot({ path: "test-results/dashboard-data-desktop.png", fullPage: true }) await page.screenshot({ path: "test-results/dashboard-data-desktop.png", fullPage: true })
await page.setViewportSize({ width: 390, height: 844 }) await page.setViewportSize({ width: 390, height: 844 })
await expect(source).toBeVisible() await expect(source).toBeVisible()
@@ -113,7 +110,7 @@ test("Дашборд: частичный сбой сохраняет данны
control.prefixes = 654 control.prefixes = 654
await refresh(page).click() await refresh(page).click()
await expect(bgp(page)).toContainText("654") await expect(bgp(page)).toContainText("654")
await expect(page.getByText(/Не обновлены источники:/)).toHaveCount(0) await expect(page.getByText("Не все источники доступны.", { exact: true })).toHaveCount(0)
}) })
test("Дашборд: поздний ответ не заменяет свежие данные при фоновом обновлении", async ({ page }) => { test("Дашборд: поздний ответ не заменяет свежие данные при фоновом обновлении", async ({ page }) => {
@@ -209,50 +206,50 @@ test('Сквозная приёмка: проблема → опрос серв
for(const broken of ["missing","partial","duplicate","counter","conflict"])test("Dashboard strict BGP unknown and last good/"+broken,async({page})=>{ for(const broken of ["missing","partial","duplicate","counter","conflict"])test("Dashboard strict BGP unknown and last good/"+broken,async({page})=>{
const sessions=[bgpSession()],failure={serverId:2,serverName:"Узел без ответа",error:"timeout"};const payload=broken==="missing"?{sessions:[]}:broken==="partial"?{sessions,failures:[failure]}:broken==="duplicate"?{sessions:[...sessions,...sessions],failures:[]}:broken==="counter"?{sessions:[bgpSession(1,-1)],failures:[]}:{sessions,failures:[{...failure,serverId:1}]}; const sessions=[bgpSession()],failure={serverId:2,serverName:"Узел без ответа",error:"timeout"};const payload=broken==="missing"?{sessions:[]}:broken==="partial"?{sessions,failures:[failure]}:broken==="duplicate"?{sessions:[...sessions,...sessions],failures:[]}:broken==="counter"?{sessions:[bgpSession(1,-1)],failures:[]}:{sessions,failures:[{...failure,serverId:1}]};
const control=await setup(page,false,1,payload);const source=page.locator('[data-source="bgp"]');await expect(refresh(page)).toBeEnabled();await expect(source).toContainText("ошибка");await expect(bgp(page)).toContainText("—"); const control=await setup(page,false,1,payload);const source=page.locator('[data-source="bgp"]');await expect(refresh(page)).toBeEnabled();await expect(source).toContainText(/ошибка/i);await expect(bgp(page)).toContainText("—");
control.bgpPayload=undefined;await refresh(page).click();await expect(bgp(page)).toContainText("321");const receivedAt=await source.locator("time").getAttribute("datetime");control.bgpPayload=payload;await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(bgp(page)).toContainText("321");await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка"); control.bgpPayload=undefined;await refresh(page).click();await expect(bgp(page)).toContainText("321");const receivedAt=await source.locator("time").getAttribute("datetime");control.bgpPayload=payload;await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(bgp(page)).toContainText("321");await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);
control.bgpPayload=undefined;control.prefixes=999;await refresh(page).click();await expect(bgp(page)).toContainText("999");await expect(source).not.toContainText("ошибка"); control.bgpPayload=undefined;control.prefixes=999;await refresh(page).click();await expect(bgp(page)).toContainText("999");await expect(source).not.toContainText(/ошибка/i);
}) })
for(const unknown of ["prefix","state"])test("Dashboard BGP accepts observed unknown without inventing zero/"+unknown,async({page})=>{ for(const unknown of ["prefix","state"])test("Dashboard BGP accepts observed unknown without inventing zero/"+unknown,async({page})=>{
const control=await setup(page);await expect(bgp(page)).toContainText("321");await expect(refresh(page)).toBeEnabled();control.bgpPayload={sessions:[unknown==="prefix"?bgpSession(1,null):{...bgpSession(),state:"Unknown"}],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("—");await expect(bgp(page)).toContainText("префиксы неизвестны");await expect(bgp(page)).toContainText(unknown==="prefix"?"Сессий установлено: 1":"Сессий установлено: неизвестно");await expect(page.locator('[data-source="bgp"]')).not.toContainText("ошибка"); const control=await setup(page);await expect(bgp(page)).toContainText("321");await expect(refresh(page)).toBeEnabled();control.bgpPayload={sessions:[unknown==="prefix"?bgpSession(1,null):{...bgpSession(),state:"Unknown"}],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("—");await expect(bgp(page)).toContainText("префиксы неизвестны");await expect(bgp(page)).toContainText(unknown==="prefix"?"Сессий установлено: 1":"Сессий установлено: неизвестно");await expect(page.locator('[data-source="bgp"]')).not.toContainText(/ошибка/i);
control.bgpPayload={sessions:[],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("Сессий установлено: 0");await expect(bgp(page)).not.toContainText("—"); control.bgpPayload={sessions:[],failures:[]};await refresh(page).click();await expect(bgp(page)).toContainText("Сессий установлено: 0");await expect(bgp(page)).not.toContainText("—");
}) })
for(const broken of ["missing","duplicate","counter","null","length"])test("Dashboard traffic rejects unconfirmed totals and keeps last good/"+broken,async({page})=>{ for(const broken of ["missing","duplicate","counter","null","length"])test("Dashboard traffic rejects unconfirmed totals and keeps last good/"+broken,async({page})=>{
const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(source.locator("time")).toHaveCount(2);const receivedAt=await source.locator("time").first().getAttribute("datetime");const rate={id:"1",rxNow:1000,txNow:500,rxSeries:[1000],txSeries:[500],observations:{rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-09-20T00:00:00Z"}};control.trafficPayload=broken==="missing"?{}:broken==="duplicate"?{servers:[rate,rate]}:broken==="counter"?{servers:[{...rate,rxNow:-1}]}:broken==="null"?{servers:[{...rate,rxNow:null}]}:{servers:[{...rate,txSeries:[]}]};await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time").first()).toHaveAttribute("datetime",receivedAt!);await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");control.trafficPayload={servers:[]};await refresh(page).click();await expect(source).not.toContainText("ошибка");await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible();await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible(); const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(source.locator("time")).toHaveCount(2);const receivedAt=await source.locator("time").first().getAttribute("datetime");const rate={id:"1",rxNow:1000,txNow:500,rxSeries:[1000],txSeries:[500],observations:{rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-09-20T00:00:00Z"}};control.trafficPayload=broken==="missing"?{}:broken==="duplicate"?{servers:[rate,rate]}:broken==="counter"?{servers:[{...rate,rxNow:-1}]}:broken==="null"?{servers:[{...rate,rxNow:null}]}:{servers:[{...rate,txSeries:[]}]};await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time").first()).toHaveAttribute("datetime",receivedAt!);await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);control.trafficPayload={servers:[]};await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible();await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();
}) })
for(const state of ["legacy","unobserved","measured-zero","reset-rx","invalid-time","invalid-mask"])test("Dashboard traffic observation metadata/"+state,async({page})=>{ for(const state of ["legacy","unobserved","measured-zero","reset-rx","invalid-time","invalid-mask"])test("Dashboard traffic observation metadata/"+state,async({page})=>{
const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();const rate={id:"1",rxNow:0,txNow:0,rxSeries:[0],txSeries:[0]};const observations={rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-10-03T00:00:00Z"};control.trafficPayload={servers:[state==="legacy"?rate:{...rate,observations:state==="unobserved"?{rxNow:false,txNow:false,rxSeries:[false],txSeries:[false],sampledAt:null}:state==="reset-rx"?{...observations,rxNow:false,rxSeries:[false]}:state==="invalid-time"?{...observations,sampledAt:"invalid"}:state==="invalid-mask"?{...observations,rxSeries:[]}:observations}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled(); const control=await setup(page);const source=page.locator('[data-source="traffic"]');await expect(refresh(page)).toBeEnabled();await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();const rate={id:"1",rxNow:0,txNow:0,rxSeries:[0],txSeries:[0]};const observations={rxNow:true,txNow:true,rxSeries:[true],txSeries:[true],sampledAt:"2026-10-03T00:00:00Z"};control.trafficPayload={servers:[state==="legacy"?rate:{...rate,observations:state==="unobserved"?{rxNow:false,txNow:false,rxSeries:[false],txSeries:[false],sampledAt:null}:state==="reset-rx"?{...observations,rxNow:false,rxSeries:[false]}:state==="invalid-time"?{...observations,sampledAt:"invalid"}:state==="invalid-mask"?{...observations,rxSeries:[]}:observations}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled();
if(state.startsWith("invalid")){await expect(source).toContainText("ошибка обновления");await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();return} if(state.startsWith("invalid")){await expect(source).toContainText(/ошибка обновления/i);await expect(page.getByText("RX 1.00 Гбит/с",{exact:true})).toBeVisible();return}
await expect(source).not.toContainText("ошибка");if(state==="measured-zero"){await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByRole("region",{name:"История RX/TX",exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toHaveCount(0)}else{await expect(page.getByText("RX —",{exact:true})).toBeVisible();if(state==="reset-rx"){await expect(page.getByText("TX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByText("Нет измерений RX за выбранный период",{exact:true})).toBeVisible()}else{await expect(page.getByText("TX —",{exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible()}} await expect(source).not.toContainText(/ошибка/i);if(state==="measured-zero"){await expect(page.getByText("RX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByRole("region",{name:"История RX/TX",exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toHaveCount(0)}else{await expect(page.getByText("RX —",{exact:true})).toBeVisible();if(state==="reset-rx"){await expect(page.getByText("TX 0 Кбит/с",{exact:true})).toBeVisible();await expect(page.getByText("Нет измерений RX за выбранный период",{exact:true})).toBeVisible()}else{await expect(page.getByText("TX —",{exact:true})).toBeVisible();await expect(page.getByText("Нет исторических измерений за выбранный период",{exact:true})).toBeVisible()}}
if(state==="legacy")await expect(page.getByText("Измерения не подтверждены API",{exact:true})).toBeVisible() if(state==="legacy")await expect(page.getByText("Измерения не подтверждены API",{exact:true})).toBeVisible()
}) })
for(const kind of ["servers","probes"])for(const broken of ["missing","duplicate","numeric"])test("Dashboard strict catalog keeps source cache/"+kind+"/"+broken,async({page})=>{ for(const kind of ["servers","probes"])for(const broken of ["missing","duplicate","numeric"])test("Dashboard strict catalog keeps source cache/"+kind+"/"+broken,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]');const receivedAt=await source.locator("time").getAttribute("datetime");const server={id:1,name:"Узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:"online",latency:1,os:"7",model:"CHR",sessions:0};const probe={id:"p1",srcServerId:"1",name:"Тест",target:"192.0.2.2",filter:"main",rtt:1,loss:0,status:"up",series:[1],enabled:true,showOnDashboard:true}; const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]');const receivedAt=await source.locator("time").getAttribute("datetime");const server={id:1,name:"Узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:"online",latency:1,os:"7",model:"CHR",sessions:0};const probe={id:"p1",srcServerId:"1",name:"Тест",target:"192.0.2.2",filter:"main",rtt:1,loss:0,status:"up",series:[1],enabled:true,showOnDashboard:true};
if(kind==="servers")control.serversPayload=broken==="missing"?{}:broken==="duplicate"?[server,server]:[{...server,latency:-1}];else control.probesPayload=broken==="missing"?{}:broken==="duplicate"?{probes:[probe,probe]}:{probes:[{...probe,loss:101}]};await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);if(kind==="servers")await expect(page.getByRole("link").filter({hasText:"Серверы онлайн"})).toContainText("1 / 1");else await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0); if(kind==="servers")control.serversPayload=broken==="missing"?{}:broken==="duplicate"?[server,server]:[{...server,latency:-1}];else control.probesPayload=broken==="missing"?{}:broken==="duplicate"?{probes:[probe,probe]}:{probes:[{...probe,loss:101}]};await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);if(kind==="servers")await expect(page.getByRole("link").filter({hasText:"Серверы онлайн"})).toContainText("из 1");else await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0);
control.serversPayload=undefined;control.probesPayload=undefined;await refresh(page).click();await expect(source).not.toContainText("ошибка"); control.serversPayload=undefined;control.probesPayload=undefined;await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);
}) })
test("Dashboard unknown server status is not reported offline or healthy",async({page})=>{ test("Dashboard unknown server status is not reported offline or healthy",async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();control.serversPayload=[{id:1,name:"Неопрошенный узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:null,latency:null,os:null,model:null,sessions:0}];await refresh(page).click();const tile=page.getByRole("link").filter({hasText:"Серверы онлайн"});await expect(tile).toContainText("Статус неизвестен: 1");await expect(tile).not.toContainText("не в сети");await expect(page.getByRole("region",{name:"Требует внимания",exact:true}).getByRole("link",{name:/Неопрошенный узел/})).toContainText("Статус неизвестен");await expect(page.getByText("Серверы без проблем",{exact:true})).toHaveCount(0);await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка"); const control=await setup(page);await expect(refresh(page)).toBeEnabled();control.serversPayload=[{id:1,name:"Неопрошенный узел",host:"192.0.2.1",site:"TEST",country:"RU",asn:"64512",type:"exit-node",enabled:true,status:null,latency:null,os:null,model:null,sessions:0}];await refresh(page).click();const tile=page.getByRole("link").filter({hasText:"Серверы онлайн"});await expect(tile).toContainText("Статус неизвестен: 1");await expect(tile).not.toContainText("не в сети");await expect(page.getByRole("region",{name:"Требует внимания",exact:true}).getByRole("link",{name:/Неопрошенный узел/})).toContainText("Статус неизвестен");await expect(page.getByText("Серверы без проблем",{exact:true})).toHaveCount(0);await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);
}) })
for(const state of ["legacy","unmeasured","zero","failure","gaps","invalid"])test("Dashboard ping distinguishes observed and missing measurements/"+state,async({page})=>{ for(const state of ["legacy","unmeasured","zero","failure","gaps","invalid"])test("Dashboard ping distinguishes observed and missing measurements/"+state,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const probe={id:"ping-observation",srcServerId:"1",name:"Измерение ping",target:"192.0.2.2",filter:"main",rtt:0,loss:0,status:"up",series:[0],enabled:true,showOnDashboard:true};const sample=(minute:number,rtt:number|null,status="up",loss=0)=>({sampledAt:"2026-10-03T00:"+String(minute).padStart(2,"0")+":00Z",rtt,status,loss});const samples=state==="unmeasured"?[]:state==="failure"?[sample(30,null,"down",100)]:state==="gaps"?[sample(29,5),sample(30,6),sample(32,0)]:state==="invalid"?[sample(30,0),sample(30,0)]:[sample(30,0)];control.probesPayload=state==="legacy"?{probes:[probe]}:{rangeStartAt:"2026-10-03T00:00:00Z",rangeEndAt:"2026-10-03T01:00:00Z",probes:[{...probe,observations:{samples}}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="probes"]');if(state==="invalid"){await expect(source).toContainText("ошибка обновления");return}await expect(source).not.toContainText("ошибка");const row=page.locator('tr[data-row-id]').filter({hasText:"Измерение ping"});await expect(row).toHaveCount(1); const control=await setup(page);await expect(refresh(page)).toBeEnabled();const probe={id:"ping-observation",srcServerId:"1",name:"Измерение ping",target:"192.0.2.2",filter:"main",rtt:0,loss:0,status:"up",series:[0],enabled:true,showOnDashboard:true};const sample=(minute:number,rtt:number|null,status="up",loss=0)=>({sampledAt:"2026-10-03T00:"+String(minute).padStart(2,"0")+":00Z",rtt,status,loss});const samples=state==="unmeasured"?[]:state==="failure"?[sample(30,null,"down",100)]:state==="gaps"?[sample(29,5),sample(30,6),sample(32,0)]:state==="invalid"?[sample(30,0),sample(30,0)]:[sample(30,0)];control.probesPayload=state==="legacy"?{probes:[probe]}:{rangeStartAt:"2026-10-03T00:00:00Z",rangeEndAt:"2026-10-03T01:00:00Z",probes:[{...probe,observations:{samples}}]};await refresh(page).click();await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="probes"]');if(state==="invalid"){await expect(source).toContainText(/ошибка обновления/i);return}await expect(source).not.toContainText(/ошибка/i);const row=page.locator('tr[data-row-id]').filter({hasText:"Измерение ping"});await expect(row).toHaveCount(1);
if(state==="legacy"||state==="unmeasured"){await expect(row).toContainText("Неизвестно");await expect(page.getByRole("link").filter({hasText:"Проверки с проблемами"})).toContainText("неизвестны: 1");await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0);await expect(row).not.toContainText("100%");await expect(page.locator('[data-latency-source]')).toHaveCount(0)}else if(state==="failure"){await expect(row).toContainText("Оффлайн");await expect(row).toContainText("100%");await expect(page.getByRole("link").filter({hasText:"Проверки с проблемами"})).toContainText("1 ошибок")}else{await expect(row).toContainText("Онлайн");await expect(row).toContainText("0%");await expect(page.locator('[data-latency-isolated]')).toHaveCount(1);if(state==="gaps"){await expect(page.locator('.recharts-line-curve')).toHaveAttribute("d",/M.*M/);for(const width of [1440,320]){await page.setViewportSize({width,height:900});await page.getByRole("region",{name:"История RTT по источникам",exact:true}).scrollIntoViewIfNeeded();expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.screenshot({path:"docs/ux-ui/screens/dashboard-observed-ping-"+width+".png",animations:"disabled"})}}else await expect(page.locator('[data-latency-segment]')).toHaveCount(0);await expect(source.locator("time").last()).toHaveAttribute("datetime",new Date(samples.at(-1)!.sampledAt).toISOString())} if(state==="legacy"||state==="unmeasured"){await expect(row).toContainText("Неизвестно");await expect(page.getByRole("link").filter({hasText:"Проверки с проблемами"})).toContainText("неизвестны: 1");await expect(page.getByText("Проверки без ошибок",{exact:true})).toHaveCount(0);await expect(row).not.toContainText("100%");await expect(page.locator('[data-latency-source]')).toHaveCount(0)}else if(state==="failure"){await expect(row).toContainText("Оффлайн");await expect(row).toContainText("100%");await expect(page.getByRole("link").filter({hasText:"Проверки с проблемами"})).toContainText("1 ошибок")}else{await expect(row).toContainText("Онлайн");await expect(row).toContainText("0%");await expect(page.locator('[data-latency-isolated]')).toHaveCount(1);if(state==="gaps"){await expect(page.locator('.recharts-line-curve')).toHaveAttribute("d",/M.*M/);for(const width of [1440,320]){await page.setViewportSize({width,height:900});await page.getByRole("region",{name:"История RTT по источникам",exact:true}).scrollIntoViewIfNeeded();expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await page.screenshot({path:"docs/ux-ui/screens/dashboard-observed-ping-"+width+".png",animations:"disabled"})}}else await expect(page.locator('[data-latency-segment]')).toHaveCount(0);await expect(source.locator("time").last()).toHaveAttribute("datetime",new Date(samples.at(-1)!.sampledAt).toISOString())}
}) })
for(const kind of ["gre","wg","vxlan"] as const)for(const broken of ["missing","partial","duplicate"])test("Dashboard overlay complete source and cache/"+kind+"/"+broken,async({page})=>{ for(const kind of ["gre","wg","vxlan"] as const)for(const broken of ["missing","partial","duplicate"])test("Dashboard overlay complete source and cache/"+kind+"/"+broken,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]'),controlKey=kind==="gre"?"grePayload":kind==="wg"?"wgPayload":"vxlanPayload",rowsKey=kind==="wg"?"interfaces":"tunnels",row=kind==="gre"?dashboardGre:kind==="wg"?dashboardWg:dashboardVxlan;control[controlKey]={[rowsKey]:[row],failures:[]};await refresh(page).click();await expect(source).not.toContainText("ошибка");const receivedAt=await source.locator("time").getAttribute("datetime");control[controlKey]=broken==="missing"?{}:broken==="partial"?{[rowsKey]:[row],failures:[{serverId:"2",serverName:"Узел без ответа",error:"timeout"}]}:{[rowsKey]:[row,row],failures:[]};await refresh(page).click();await expect(source).toContainText("ошибка обновления");await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(page.getByRole("link").filter({hasText:"Туннели работают"})).toContainText("Последний успешный снимок");await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка");if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toBeVisible();control[controlKey]={[rowsKey]:[],failures:[]};await refresh(page).click();await expect(source).not.toContainText("ошибка");if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toHaveCount(0) const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="'+kind+'"]'),controlKey=kind==="gre"?"grePayload":kind==="wg"?"wgPayload":"vxlanPayload",rowsKey=kind==="wg"?"interfaces":"tunnels",row=kind==="gre"?dashboardGre:kind==="wg"?dashboardWg:dashboardVxlan;control[controlKey]={[rowsKey]:[row],failures:[]};await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);const receivedAt=await source.locator("time").getAttribute("datetime");control[controlKey]=broken==="missing"?{}:broken==="partial"?{[rowsKey]:[row],failures:[{serverId:"2",serverName:"Узел без ответа",error:"timeout"}]}:{[rowsKey]:[row,row],failures:[]};await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);await expect(source.locator("time")).toHaveAttribute("datetime",receivedAt!);await expect(page.getByRole("link").filter({hasText:"Туннели работают"})).toContainText("Последний успешный снимок");await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toBeVisible();control[controlKey]={[rowsKey]:[],failures:[]};await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);if(kind==="gre")await expect(page.getByText("GRE сохранён",{exact:true})).toHaveCount(0)
}) })
for(const broken of ["missing","incomplete","foreign","invalid-date","corrupt-null","legacy","filters","speed"])test("Dashboard Internet path keeps last confirmed source/"+broken,async({page})=>{ for(const broken of ["missing","incomplete","foreign","invalid-date","corrupt-null","legacy","filters","speed"])test("Dashboard Internet path keeps last confirmed source/"+broken,async({page})=>{
const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="internetPath"]');await expect(source).not.toContainText("ошибка");const times=await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime"))); const control=await setup(page);await expect(refresh(page)).toBeEnabled();const source=page.locator('[data-source="internetPath"]');await expect(source).not.toContainText(/ошибка/i);const times=await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")));
if(broken==="filters"||broken==="speed"){control.fallback=true;if(broken==="filters")control.filterPayload={rulesets:[],stale:true};else control.speedPayload={}} if(broken==="filters"||broken==="speed"){control.fallback=true;if(broken==="filters")control.filterPayload={rulesets:[],stale:true};else control.speedPayload={}}
else control.pathPayload=broken==="missing"?{}:broken==="corrupt-null"?{snapshot:null,sampledAt:"2026-09-20T00:00:00Z"}:{snapshot:{collectionComplete:broken==="legacy"?undefined:true,sampledAt:broken==="invalid-date"?"invalid":"2026-09-20T00:00:00Z",servers:[],greTunnels:[],filtersRulesets:[],speedProbes:broken==="incomplete"?undefined:[],routeLookupByServerId:broken==="foreign"?{"99":null}:{},wanRuntimeByHomeId:{}}}; else control.pathPayload=broken==="missing"?{}:broken==="corrupt-null"?{snapshot:null,sampledAt:"2026-09-20T00:00:00Z"}:{snapshot:{collectionComplete:broken==="legacy"?undefined:true,sampledAt:broken==="invalid-date"?"invalid":"2026-09-20T00:00:00Z",servers:[],greTunnels:[],filtersRulesets:[],speedProbes:broken==="incomplete"?undefined:[],routeLookupByServerId:broken==="foreign"?{"99":null}:{},wanRuntimeByHomeId:{}}};
await refresh(page).click();await expect(source).toContainText("ошибка обновления");expect(await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")))).toEqual(times);await expect(page.locator('[data-source="servers"]')).not.toContainText("ошибка"); await refresh(page).click();await expect(source).toContainText(/ошибка обновления/i);expect(await source.locator("time").evaluateAll(nodes=>nodes.map(n=>n.getAttribute("datetime")))).toEqual(times);await expect(page.locator('[data-source="servers"]')).not.toContainText(/ошибка/i);
control.pathPayload=undefined;control.filterPayload=undefined;control.speedPayload=undefined;control.fallback=false;await refresh(page).click();await expect(source).not.toContainText("ошибка"); control.pathPayload=undefined;control.filterPayload=undefined;control.speedPayload=undefined;control.fallback=false;await refresh(page).click();await expect(source).not.toContainText(/ошибка/i);
}) })
for(const state of ["unmeasured","measured","failed","unknown"])test("Dashboard Internet path hop observations/"+state,async({page})=>{ for(const state of ["unmeasured","measured","failed","unknown"])test("Dashboard Internet path hop observations/"+state,async({page})=>{
@@ -260,14 +257,14 @@ for(const state of ["unmeasured","measured","failed","unknown"])test("Dashboard
const nodes=["home-router","jump-host","exit-node"].map((type,i)=>({id:i+1,name:"Path node "+(i+1),host:"192.0.2."+(i+1),site:"TEST",country:"RU",asn:"64512",type,enabled:true,status:state==="unknown"&&i===0?null:"online",latency:99,os:"7",model:"CHR",sessions:0,wanUplinks:i===0?[{id:"wan1",name:"WAN",isp:"Test ISP",iface:"ether1",ip:"192.0.2.10",maxDl:999,maxUl:888}]:[]})); const nodes=["home-router","jump-host","exit-node"].map((type,i)=>({id:i+1,name:"Path node "+(i+1),host:"192.0.2."+(i+1),site:"TEST",country:"RU",asn:"64512",type,enabled:true,status:state==="unknown"&&i===0?null:"online",latency:99,os:"7",model:"CHR",sessions:0,wanUplinks:i===0?[{id:"wan1",name:"WAN",isp:"Test ISP",iface:"ether1",ip:"192.0.2.10",maxDl:999,maxUl:888}]:[]}));
const probe={id:"hop1",srcServerId:"1",dstServerId:"2",srcInterface:"ether1",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0,lastRxAvgMbps:5,lastPingAt:state==="unmeasured"?null:at,lastRunAt:state==="unmeasured"?null:at,lastStatus:state==="failed"?"error":"done",lastError:state==="failed"?"denied":null,lastPingError:state==="failed"?"denied":null}; const probe={id:"hop1",srcServerId:"1",dstServerId:"2",srcInterface:"ether1",dstInterface:"",enabled:true,lastPingRttMs:0,lastPingLossPct:0,lastTxAvgMbps:0,lastRxAvgMbps:5,lastPingAt:state==="unmeasured"?null:at,lastRunAt:state==="unmeasured"?null:at,lastStatus:state==="failed"?"error":"done",lastError:state==="failed"?"denied":null,lastPingError:state==="failed"?"denied":null};
control.pathPayload={snapshot:{collectionComplete:true,sampledAt:at,servers:nodes,greTunnels:[],filtersRulesets:[],speedProbes:[probe],routeLookupByServerId:{"1":{gateway:"192.0.2.254",routingMark:null}},wanRuntimeByHomeId:{"1":{defaultGateway:"192.0.2.254",defaultInterface:"ether1",uplinks:[{id:"wan1",name:"WAN",isp:"Test ISP",iface:"ether1",configuredIp:"192.0.2.10",leasedIp:"192.0.2.10",dhcpStatus:"bound",isDefault:true}]}}}}; control.pathPayload={snapshot:{collectionComplete:true,sampledAt:at,servers:nodes,greTunnels:[],filtersRulesets:[],speedProbes:[probe],routeLookupByServerId:{"1":{gateway:"192.0.2.254",routingMark:null}},wanRuntimeByHomeId:{"1":{defaultGateway:"192.0.2.254",defaultInterface:"ether1",uplinks:[{id:"wan1",name:"WAN",isp:"Test ISP",iface:"ether1",configuredIp:"192.0.2.10",leasedIp:"192.0.2.10",dhcpStatus:"bound",isDefault:true}]}}}};
await refresh(page).click();await expect(refresh(page)).toBeEnabled();await expect(page.locator('[data-source="internetPath"]')).not.toContainText("ошибка");const strip=page.getByText("JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.",{exact:true}).locator("..");await expect(strip).toBeVisible();await expect(strip).not.toContainText("999");await expect(strip).not.toContainText("99 мс"); await refresh(page).click();await expect(refresh(page)).toBeEnabled();await expect(page.locator('[data-source="internetPath"]')).not.toContainText(/ошибка/i);const strip=page.getByText("JH/Exit — схема кандидатов. Default route подтверждает только WAN. Метрики — последние подтверждённые пробы участков.",{exact:true}).locator("..");await expect(strip).toBeVisible();await expect(strip).not.toContainText("999");await expect(strip).not.toContainText("99 мс");
if(state==="measured"||state==="unknown"){await expect(strip.getByText("0 мс",{exact:true})).toBeVisible();await expect(strip.getByText("5 ↓ Мбит/с",{exact:true})).toBeVisible()}else{await expect(strip.getByText("0 мс",{exact:true})).toHaveCount(0);await expect(strip.getByText("5 ↓ Мбит/с",{exact:true})).toHaveCount(0)} if(state==="measured"||state==="unknown"){await expect(strip.getByText("0 мс",{exact:true})).toBeVisible();await expect(strip.getByText("5 ↓ Мбит/с",{exact:true})).toBeVisible()}else{await expect(strip.getByText("0 мс",{exact:true})).toHaveCount(0);await expect(strip.getByText("5 ↓ Мбит/с",{exact:true})).toHaveCount(0)}
if(state==="unknown"){await expect(strip.getByText("Неизвестно",{exact:true})).toBeVisible();await expect(strip.getByText("Оффлайн",{exact:true})).toHaveCount(0)} if(state==="unknown"){await expect(strip.getByText("Неизвестно",{exact:true})).toBeVisible();await expect(strip.getByText("Оффлайн",{exact:true})).toHaveCount(0)}
await page.setViewportSize({width:320,height:900});await expect(strip).toBeVisible();expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true) await page.setViewportSize({width:320,height:900});await expect(strip).toBeVisible();expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
}) })
test("Dashboard large attention queue mounts rows on demand",async({page},info)=>{ test("Dashboard large attention queue mounts rows on demand",async({page},info)=>{
test.setTimeout(90000);const start=Date.now();await setup(page,false,1000);await expect(refresh(page)).toBeEnabled();const queue=page.getByRole("region",{name:"Требует внимания",exact:true});const links=queue.locator('a[href^="/servers?server="]');await expect(links).toHaveCount(5);const sample={fixtureRows:1000,readyMs:Date.now()-start,renderedAttentionRows:await links.count(),domNodes:await page.locator("*").count()};console.log(JSON.stringify(sample));await info.attach("large-attention-metrics",{body:JSON.stringify(sample),contentType:"application/json"});const summary=queue.locator("summary").filter({hasText:"Ещё 995"});await summary.focus();await summary.press("Enter");await expect(links).toHaveCount(55);await queue.getByRole("button",{name:"Показать ещё 50",exact:true}).click();await expect(links).toHaveCount(105);await summary.focus();await summary.press("Enter");await expect(links).toHaveCount(5);await summary.press("Enter");await expect(links).toHaveCount(55);await page.setViewportSize({width:320,height:900});expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await links.first().click();await expect(page).toHaveURL(/servers\?server=1$/);await expect(page.getByRole("status",{name:"Сервер по ссылке"})).toContainText("Узел 1") test.setTimeout(90000);const start=Date.now();await setup(page,false,1000);await expect(refresh(page)).toBeEnabled();const queue=page.getByRole("region",{name:"Требует внимания",exact:true});const links=queue.locator('a[href^="/servers?server="]');await expect(links).toHaveCount(50);const sample={fixtureRows:1000,readyMs:Date.now()-start,renderedAttentionRows:await links.count(),domNodes:await page.locator("*").count()};console.log(JSON.stringify(sample));await info.attach("large-attention-metrics",{body:JSON.stringify(sample),contentType:"application/json"});await queue.getByRole("button",{name:"Показать ещё 50",exact:true}).click();await expect(links).toHaveCount(100);await page.setViewportSize({width:320,height:900});expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);await links.first().click();await expect(page).toHaveURL(/servers\?server=1$/);await expect(page.getByRole("status",{name:"Сервер по ссылке"})).toContainText("Узел 1")
}) })
test("Dashboard active probes retain page after refreshed measurements",async({page})=>{ test("Dashboard active probes retain page after refreshed measurements",async({page})=>{
+2 -2
View File
@@ -40,10 +40,10 @@ test("Карта: неизвестный статус не становится
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],status:null}]:data})}) await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],status:null}]:data})})
await page.goto("/network-map") await page.goto("/network-map")
await expect(page.getByText("1 неизвестно",{exact:true})).toBeVisible() await expect(page.getByText("1 неизвестно",{exact:true})).toBeVisible()
await expect(page.getByText("0 оффлайн",{exact:true})).toBeVisible() await expect(page.getByRole("button",{name:"Оффлайн 0",exact:true})).toBeVisible()
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click() await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible() await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
await page.getByRole("button",{name:"Неизвестно",exact:true}).click() await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true})).toBeVisible() await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true})).toBeVisible()
}) })
+2 -2
View File
@@ -20,7 +20,7 @@ test("Карта: модель WAN не утверждает активный м
await page.goto("/network-map");await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible() await page.goto("/network-map");await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0) await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click() await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible() await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
await expect(page.getByText("primary",{exact:true})).toHaveCount(0);await expect(page.getByText("backup",{exact:true})).toHaveCount(0) await expect(page.getByText("primary",{exact:true})).toHaveCount(0);await expect(page.getByText("backup",{exact:true})).toHaveCount(0)
}) })
test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{ test("Карта: выбранный GRE обновляется и неизвестный IPsec не означает Plain",async({page})=>{
@@ -31,7 +31,7 @@ test("Карта: выбранный GRE обновляется и неизве
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible() await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click() changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible() await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible() await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
}) })
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{ test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
+1
View File
@@ -59,6 +59,7 @@ test("Карта: пропорции камеры, ручной масштаб
await page.getByRole("button",{name:"Вписать карту",exact:true}).click() await page.getByRole("button",{name:"Вписать карту",exact:true}).click()
expect(await map.getAttribute("viewBox")).not.toBe(manual) expect(await map.getAttribute("viewBox")).not.toBe(manual)
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1") await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click()
const wan=page.getByRole("button",{name:"WAN WAN",exact:true});await wan.focus();await wan.press("Enter") const wan=page.getByRole("button",{name:"WAN WAN",exact:true});await wan.focus();await wan.press("Enter")
await expect(page).toHaveURL(/wan=0/);await expect(wan).toHaveAttribute("aria-pressed","true") await expect(page).toHaveURL(/wan=0/);await expect(wan).toHaveAttribute("aria-pressed","true")
}) })
+2
View File
@@ -18,6 +18,8 @@ test.beforeEach(async ({ page }) => {
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => { test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
await page.goto("/network-map") await page.goto("/network-map")
const legend = page.getByRole("region", { name: "Легенда карты" }) const legend = page.getByRole("region", { name: "Легенда карты" })
await expect(legend).not.toBeVisible()
await page.locator("[data-map-legend] summary").click()
await expect(legend).toBeVisible() await expect(legend).toBeVisible()
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Поток NetFlow"]) await expect(legend.getByText(text, { exact: true })).toBeVisible() for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Поток NetFlow"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
await expect(legend).toContainText("нет измерения") await expect(legend).toContainText("нет измерения")
+1 -1
View File
@@ -10,7 +10,7 @@ test("Карта URL: устройство/WAN, фильтр, поиск, наз
await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible() await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
await expect(page.getByRole("textbox",{name:"Поиск узла",exact:true})).toHaveValue("Router") await expect(page.getByRole("textbox",{name:"Поиск узла",exact:true})).toHaveValue("Router")
await page.reload();await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible() await page.reload();await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
await page.getByRole("button",{name:"Онлайн",exact:true}).click() await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Онлайн",exact:true}).click()
await expect(page).toHaveURL(/filter=online/);await page.goBack();await expect(page).toHaveURL(/filter=unknown/) await expect(page).toHaveURL(/filter=online/);await page.goBack();await expect(page).toHaveURL(/filter=unknown/)
await page.getByRole("button",{name:"Сервисы",exact:true}).click();await expect(page).not.toHaveURL(/dest=countries/);await page.goBack();await expect(page).toHaveURL(/dest=countries/) await page.getByRole("button",{name:"Сервисы",exact:true}).click();await expect(page).not.toHaveURL(/dest=countries/);await page.goBack();await expect(page).toHaveURL(/dest=countries/)
await page.getByRole("textbox",{name:"Поиск узла",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL") await page.getByRole("textbox",{name:"Поиск узла",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
+9 -8
View File
@@ -45,11 +45,11 @@ test('Статистика: смена периода скрывает стар
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible() await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible()
control.hold = true control.hold = true
const waiting = page.waitForRequest(r => r.url().includes('/api/statistics?') && r.url().includes('from=2026-09-02')) const waiting = page.waitForRequest(r => r.url().includes('/api/statistics?') && r.url().includes('from=2026-09-02'))
await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-02&to=2026-09-03')) await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-02&to=2026-09-03&dim=users'))
await waiting await waiting
await expect(page.getByText('Загрузка статистики…', { exact: true })).toBeVisible() await expect(page.getByText('Загрузка статистики…', { exact: true })).toBeVisible()
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toHaveCount(0) await expect(page.getByText('Данные 2026-09-01', { exact: true })).toHaveCount(0)
await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-03&to=2026-09-03')) await page.evaluate(() => window.history.pushState(null, '', '/statistics?from=2026-09-03&to=2026-09-03&dim=users'))
await expect(page.getByText('Данные 2026-09-03', { exact: true })).toBeVisible() await expect(page.getByText('Данные 2026-09-03', { exact: true })).toBeVisible()
const old = page.waitForResponse(r => r.url().includes('/api/statistics?') && r.url().includes('from=2026-09-02')) const old = page.waitForResponse(r => r.url().includes('/api/statistics?') && r.url().includes('from=2026-09-02'))
control.release() control.release()
@@ -62,7 +62,7 @@ test('Статистика: ошибка pivot не показывает мет
await setup(page) await setup(page)
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible() await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible()
await page.route('**/api/statistics/pivot?**', route => route.fulfill({ status: 500, json: { error: 'Сводка недоступна' } })) await page.route('**/api/statistics/pivot?**', route => route.fulfill({ status: 500, json: { error: 'Сводка недоступна' } }))
await page.getByRole('button', { name: 'Сводка', exact: true }).click() await page.getByRole('tab', { name: 'Сводная (куб)', exact: true }).click()
await expect(page.getByRole('alert').filter({ hasText: 'Ошибка загрузки' })).toContainText('Сводка недоступна') await expect(page.getByRole('alert').filter({ hasText: 'Ошибка загрузки' })).toContainText('Сводка недоступна')
await expect(page.getByLabel('Сводка трафика')).toHaveCount(0) await expect(page.getByLabel('Сводка трафика')).toHaveCount(0)
await expect(page.getByText('Нет данных куба', { exact: true })).toHaveCount(0) await expect(page.getByText('Нет данных куба', { exact: true })).toHaveCount(0)
@@ -108,7 +108,8 @@ for (const query of ['serverId=bad', 'planes=unknown', 'country=RU&country=DE'])
await expect(page.getByLabel('Сводка трафика')).toHaveCount(0) await expect(page.getByLabel('Сводка трафика')).toHaveCount(0)
expect(requests).toHaveLength(before) expect(requests).toHaveLength(before)
await page.getByRole('button', { name: 'Сбросить параметры отчёта', exact: true }).click() await page.getByRole('button', { name: 'Сбросить параметры отчёта', exact: true }).click()
await expect(page.getByText('Данные 2026-09-01', { exact: true })).toBeVisible() await expect(page.getByLabel('Сводка трафика')).toBeVisible()
await expect(page.getByRole('tab', { name: 'Обзор', exact: true })).toHaveAttribute('aria-selected', 'true')
const url = new URL(page.url()) const url = new URL(page.url())
expect(url.searchParams.get('from')).toBe('2026-09-01') expect(url.searchParams.get('from')).toBe('2026-09-01')
expect(url.searchParams.get('keep')).toBe('1') expect(url.searchParams.get('keep')).toBe('1')
@@ -156,11 +157,11 @@ test('Статистика: клавиатурный выбор среза и д
await expect(page.getByRole('listbox')).toHaveCount(0) await expect(page.getByRole('listbox')).toHaveCount(0)
await expect(criterion).toBeFocused() await expect(criterion).toBeFocused()
await page.route('**/api/statistics/pivot?**', route => route.fulfill({ json: { rowDim: 'country', colDim: 'service', metric: 'bytes', columns: [], rows: [], otherBytes: 0 } })) await page.route('**/api/statistics/pivot?**', route => route.fulfill({ json: { rowDim: 'country', colDim: 'service', metric: 'bytes', columns: [], rows: [], otherBytes: 0 } }))
const pivot = page.getByRole('button', { name: 'Сводка', exact: true }) const pivot = page.getByRole('tab', { name: 'Сводная (куб)', exact: true })
await pivot.focus() await pivot.focus()
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await expect(pivot).toHaveAttribute('aria-pressed', 'true') await expect(pivot).toHaveAttribute('aria-selected', 'true')
await expect(page.getByRole('button', { name: 'Разрез', exact: true })).toHaveAttribute('aria-pressed', 'false') await expect(page.getByRole('tab', { name: 'Срезы', exact: true })).toHaveAttribute('aria-selected', 'false')
await expect(page.getByRole('combobox', { name: 'Строки', exact: true })).toBeVisible() await expect(page.getByRole('combobox', { name: 'Строки', exact: true })).toBeVisible()
await expect(page.getByRole('combobox', { name: 'Колонки', exact: true })).toBeVisible() await expect(page.getByRole('combobox', { name: 'Колонки', exact: true })).toBeVisible()
}) })
@@ -172,7 +173,7 @@ for (const pivot of [false, true]) {
const crashes: string[] = [] const crashes: string[] = []
page.on('pageerror', error => crashes.push(error.message)) page.on('pageerror', error => crashes.push(error.message))
await page.route(pivot ? '**/api/statistics/pivot?**' : '**/api/statistics?**', route => route.fulfill({ json: {} })) await page.route(pivot ? '**/api/statistics/pivot?**' : '**/api/statistics?**', route => route.fulfill({ json: {} }))
if (pivot) await page.getByRole('button', { name: 'Сводка', exact: true }).click() if (pivot) await page.getByRole('tab', { name: 'Сводная (куб)', exact: true }).click()
else await page.reload() else await page.reload()
await expect(page.getByRole('alert').filter({ hasText: 'Ошибка загрузки' })).toContainText(pivot ? 'Некорректный ответ сводной статистики' : 'Некорректный ответ статистики') await expect(page.getByRole('alert').filter({ hasText: 'Ошибка загрузки' })).toContainText(pivot ? 'Некорректный ответ сводной статистики' : 'Некорректный ответ статистики')
await expect(page.getByRole('button', { name: 'Повторить загрузку', exact: true })).toBeVisible() await expect(page.getByRole('button', { name: 'Повторить загрузку', exact: true })).toBeVisible()