fix(ui): демо-куб статистики и честная подпись фактора здоровья
Без живого API статистика показывает демо-куб вместо пустого состояния, как в макете v3. Фактор «Задержка (RTT)» переименован в «Пробы в норме»: его полоса — доля проб в норме, а не задержка. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
5fd028800a
commit
8781f68674
3 files changed
+70
-9
No files matched your search
@@ -145,8 +145,6 @@ export default function DashboardPage() {
|
||||
|
||||
const probesMeasured = useMemo(() => dash.enabledProbes.filter((p) => p.status !== "unknown"), [dash.enabledProbes])
|
||||
const avgLoss = probesMeasured.length ? probesMeasured.reduce((sum, p) => sum + (p.loss ?? 0), 0) / probesMeasured.length : null
|
||||
const rtts = probesMeasured.map((p) => p.rtt).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
|
||||
const avgRtt = rtts.length ? Math.round(rtts.reduce((sum, v) => sum + v, 0) / rtts.length) : null
|
||||
const okSources = sourceRows.filter((row) => row.tone === "ok").length
|
||||
|
||||
const attentionRows = [
|
||||
@@ -311,7 +309,7 @@ export default function DashboardPage() {
|
||||
<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: "Задержка (RTT)", value: avgRtt == null ? "—" : `${avgRtt} мс`, ratio: probesMeasured.length ? probesMeasured.filter((p) => p.status === "up").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 },
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
} from "@/lib/statistics-dims"
|
||||
import { statisticsContextError, STATISTICS_CONTEXT_KEYS } from "@/lib/statistics-context"
|
||||
import { readStatisticsRange } from "@/lib/statistics-range"
|
||||
import { demoStatistics, demoStatisticsPivot } from "@/lib/statistics-demo"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { fmtBps, formatBytes } from "@/lib/fmt-rate"
|
||||
import {
|
||||
@@ -261,7 +262,9 @@ function StatisticsPageInner() {
|
||||
const loading = isLive && !rangeError && !paramsError && current === null
|
||||
const error = rangeError ?? paramsError ?? current?.error ?? null
|
||||
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(
|
||||
(patch: Record<string, string | undefined>) => {
|
||||
@@ -327,9 +330,9 @@ function StatisticsPageInner() {
|
||||
}
|
||||
}, [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 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) {
|
||||
if (kind === "users" && row.id === STATISTICS_UNBOUND_USER_ID) return
|
||||
@@ -422,7 +425,7 @@ function StatisticsPageInner() {
|
||||
<Alert variant="warning">
|
||||
<AlertTitle>Живые данные выключены</AlertTitle>
|
||||
<AlertDescription>
|
||||
Куб статистики строится из IPFIX. Переключитесь на живой источник, чтобы увидеть отчёт.
|
||||
Показан демо-куб. Статистика строится из IPFIX — переключитесь на живой источник, чтобы увидеть свой отчёт.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
@@ -434,7 +437,7 @@ function StatisticsPageInner() {
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
{(dataReady || loading) && <KpiStatGrid
|
||||
{(dataReady || loading || (demo && !paramsError)) && <KpiStatGrid
|
||||
aria-label="Сводка трафика"
|
||||
isLoading={loading}
|
||||
skeletonCount={4}
|
||||
@@ -510,7 +513,7 @@ function StatisticsPageInner() {
|
||||
countLabel={dataReady ? countLabel : undefined}
|
||||
/>
|
||||
{sliceChips}
|
||||
{cubeState ?? <StatisticsPivotGrid data={isLive ? pivot : EMPTY_PIVOT} onCellClick={handlePivotCell} isLoading={loading} />}
|
||||
{cubeState ?? <StatisticsPivotGrid data={pivot} onCellClick={handlePivotCell} isLoading={loading} />}
|
||||
</DataPageCard>
|
||||
</TabsContent>
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
Reference in new issue
Block a user