fix(ui): перенести таблицы оптимизатора маршрутов на ReUI v9

This commit is contained in:
Denozordec committed 2026-09-14 22:01:11 +07:00
1 parent 1ea07f65b2
commit bdba83b2b6
6 files changed
+132 -45

No files matched your search

@@ -1,22 +1,22 @@
"use client"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { useMemo } from "react"
import {
type ColumnDef,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table-v8"
useTable,
} from "@tanstack/react-table"
import type { CommRec } from "@/lib/route-optimizer-data"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { DataGridShell } from "@/components/data-grids/shared/legacy-data-grid-shell"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import {
DATA_GRID_CELL_PAD,
DATA_GRID_CELL_PAD_FIRST,
DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/legacy-data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/legacy-data-grid-sort-header"
} from "@/components/data-grids/shared/data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
import { ArrowRightIcon, PinIcon, RefreshCwIcon } from "lucide-react"
function Chip({ children, color }: { children: React.ReactNode; color?: string }) {
@@ -70,7 +70,7 @@ function RouteOptimizerCommRecsDataGrid({
[homeId, recs],
)
const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(
const columns = useMemo<ColumnDef<DataGridFeatures, (typeof rows)[number]>[]>(
() => [
{
id: "community",
@@ -231,11 +231,11 @@ function RouteOptimizerCommRecsDataGrid({
[applied, applying, homeId, onApply, onPin, pinned],
)
const table = useReactTable({
const table = useTable({
features: dataGridFeatures,
manualPagination: true,
data: rows,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getRowId: (row) => row._rowKey,
})
@@ -1,23 +1,22 @@
"use client"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { useMemo, useState } from "react"
import {
type ColumnDef,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table-v8"
useTable,
} from "@tanstack/react-table"
import type { FullRoute } from "@/lib/route-optimizer-data"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { DataGridShell } from "@/components/data-grids/shared/legacy-data-grid-shell"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import {
DATA_GRID_CELL_PAD,
DATA_GRID_CELL_PAD_FIRST,
DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/legacy-data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/legacy-data-grid-sort-header"
} from "@/components/data-grids/shared/data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
import { ArrowRightIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
function Chip({ children, color }: { children: React.ReactNode; color?: string }) {
@@ -73,7 +72,7 @@ function RouteOptimizerFullRoutesDataGrid({
[visibleRoutes],
)
const columns = useMemo<ColumnDef<FullRoute & { _index: number }>[]>(
const columns = useMemo<ColumnDef<DataGridFeatures, FullRoute & { _index: number }>[]>(
() => [
{
id: "index",
@@ -249,11 +248,11 @@ function RouteOptimizerFullRoutesDataGrid({
[bestId],
)
const table = useReactTable({
const table = useTable({
features: dataGridFeatures,
manualPagination: true,
data: indexed,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getRowId: (row) => row.id,
})
@@ -1,20 +1,19 @@
"use client"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { useMemo } from "react"
import {
type ColumnDef,
getCoreRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table-v8"
import { cn } from "@/lib/utils"
import { DataGridShell } from "@/components/data-grids/shared/legacy-data-grid-shell"
useTable,
} from "@tanstack/react-table"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import {
DATA_GRID_CELL_PAD,
DATA_GRID_CELL_PAD_FIRST,
DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/legacy-data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/legacy-data-grid-sort-header"
} from "@/components/data-grids/shared/data-grid-layout"
import { DataGridSortHeader } from "@/components/data-grids/shared/data-grid-sort-header"
import { EmptyState } from "@/components/empty-state"
import { NetworkIcon } from "lucide-react"
@@ -40,7 +39,7 @@ function RouteOptimizerOspfPreviewDataGrid({
error,
loading,
}: RouteOptimizerOspfPreviewDataGridProps) {
const columns = useMemo<ColumnDef<OspfPreviewInterfaceRow>[]>(
const columns = useMemo<ColumnDef<DataGridFeatures, OspfPreviewInterfaceRow>[]>(
() => [
{
id: "interface",
@@ -111,11 +110,11 @@ function RouteOptimizerOspfPreviewDataGrid({
[],
)
const table = useReactTable({
const table = useTable({
features: dataGridFeatures,
manualPagination: true,
data: rows,
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getRowId: (row) => row.id,
})
@@ -1,20 +1,21 @@
"use client"
import { dataGridFeatures, type DataGridFeatures } from "@/components/reui/data-grid"
import { useMemo } from "react"
import {
type ColumnDef,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table-v8"
useTable,
} from "@tanstack/react-table"
import type { HomeRouter, JumpHost, WanJhLeg } from "@/lib/route-optimizer-data"
import { Flag } from "@/components/flag"
import { cn } from "@/lib/utils"
import { DataGridShell } from "@/components/data-grids/shared/legacy-data-grid-shell"
import { DataGridShell } from "@/components/data-grids/shared/data-grid-shell"
import {
DATA_GRID_CELL_PAD,
DATA_GRID_CELL_PAD_FIRST,
DATA_GRID_CELL_PAD_LAST,
} from "@/components/data-grids/shared/legacy-data-grid-layout"
} from "@/components/data-grids/shared/data-grid-layout"
import { WifiIcon } from "lucide-react"
function LossChip({ loss }: { loss: number }) {
@@ -39,8 +40,8 @@ function RouteOptimizerWanMatrixDataGrid({
}: RouteOptimizerWanMatrixDataGridProps) {
const bestScore = legs.length ? Math.max(...legs.map((l) => l.score)) : 0
const columns = useMemo<ColumnDef<HomeRouter["wans"][number]>[]>(() => {
const base: ColumnDef<HomeRouter["wans"][number]>[] = [
const columns = useMemo<ColumnDef<DataGridFeatures, HomeRouter["wans"][number]>[]>(() => {
const base: ColumnDef<DataGridFeatures, HomeRouter["wans"][number]>[] = [
{
id: "wan",
accessorKey: "name",
@@ -96,7 +97,7 @@ function RouteOptimizerWanMatrixDataGrid({
},
]
const jhCols: ColumnDef<HomeRouter["wans"][number]>[] = jumpHosts.map((jh) => ({
const jhCols: ColumnDef<DataGridFeatures, HomeRouter["wans"][number]>[] = jumpHosts.map((jh) => ({
id: `jh-${jh.id}`,
header: () => (
<div className="text-center">
@@ -163,10 +164,12 @@ function RouteOptimizerWanMatrixDataGrid({
return [...base, ...jhCols]
}, [bestScore, jumpHosts, legs])
const table = useReactTable({
const table = useTable({
features: dataGridFeatures,
manualPagination: true,
manualSorting: true,
data: home.wans,
columns,
getCoreRowModel: getCoreRowModel(),
getRowId: (row) => row.id,
})
+10
View File
@@ -302,6 +302,16 @@ Production build блока 7: `npm run build` прошёл, 34 статичес
После блока использовано 95% пятичасовой квоты. Следующий блок — четыре `route-optimizer-*-data-grid`, затем общие legacy-потребители/`data-table`, старые Filters и удаление v8 с полной регрессией. Этап 4 не завершён. Этот блок сохранить локальным коммитом без push.
## Этап 4 — блок 10: оптимизатор маршрутов (2026-09-14)
Четыре `route-optimizer-*-data-grid` перенесены на установленный ReUI/TanStack v9. Сохранены динамические колонки WAN × JH, отсутствие сортировки матрицы, раскрытие списка комбинаций (5 → все), сортировка и ключи Community, состояния загрузки/ошибки/пустого OSPF preview. Удалены два неиспользуемых импорта.
Проверки: TypeScript до и после Playwright — успешно; ESLint всех четырёх компонентов и нового теста — без замечаний. `route-optimizer-tables.spec.ts`: 4 passed, включая 12 WAN, 12 комбинаций, сортировку и закрепление выбранной Community, 12 интерфейсов OSPF и числовую сортировку, пустой ответ и HTTP 500 preview. Первый прогон имел запрос при завершении теста к отключённому backend; добавлено ожидание загрузки основной таблицы, повторный прогон без этого сообщения. Проверки используют live-ветку с HTTP-моками; применение RouterOS не выполнялось.
Обнаруженный исходный долг для этапов 5/10: `applyRec` страницы имитирует успех через таймер даже в live-режиме; `buildLiveOptimizerData` рассчитывает вероятности Community из длины строки и использует оценочные ping/bandwidth при отсутствии замеров. Тест закрепления не подтверждает реальность применения или достоверность этих оценок. Алгоритмы в блоке миграции не менялись.
Квота: новое окно 0% на старте, 13% использовано после проверок, недельная — 91%. Остаток Data Grid: `components/data-table.tsx`, layout-импорты `DataPageCard`/`DataPageToolbar` и затем удаление общей legacy-основы/v8. Старые Filters остаются у BGP, statistics, backups, backups-history и в fallback DataPageToolbar. Этап 4 не завершён; сохранить блок локальным коммитом без push.
## Карта миграции (исходная инвентаризация этапа 0)
Текущая связка: @tanstack/react-table ^8.21.3, @tanstack/react-virtual ^3.14.4, base-nova. Актуальный ReUI MCP ранее подтвердил useTable/dataGridFeatures для Data Grid и дерево FilterQuery вместо filters/onChange для Filters. Перед установкой перепроверить совместимые версии, сохранить семантику существующих фильтров (простые условия → AND) и закрепить lockfile.
+76
View File
@@ -0,0 +1,76 @@
import { test, expect, type Page } from "@playwright/test"
import type { OptimizerApiServer } from "../../lib/route-optimizer-data"
const ids = Array.from({ length: 12 }, (_, i) => i + 1)
const servers: OptimizerApiServer[] = (["home-router", "jump-host", "exit-node"] as const).map((type, i) => ({
id: i + 1, name: `Роутер ${i + 1}`, host: `192.0.2.${i + 1}`, type,
site: "TEST", country: "RU", enabled: true, status: "online", latency: 10, model: "CHR",
...(i === 0 ? { wanUplinks: ids.map(id => ({ id: `wan${id}`, name: `WAN${id}`, isp: "ISP", iface: `ether${id}`, ip: `198.51.100.${id}`, maxDl: 100, maxUl: 100 })) } : {}),
}))
async function setup(page: Page, preview: "ok" | "empty" | "error" = "ok") {
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
if (path.endsWith("/ospf/optimize/preview")) {
if (preview === "error") return route.fulfill({ status: 500, json: { error: "Расчёт недоступен" } })
const interfaces = preview === "empty" ? [] : ids.map(i => ({ interface: `ether${i}`, currentCost: i, optimalCost: 20, score: i, pingMs: i, dlMbps: 100, ulMbps: 50 }))
return route.fulfill({ json: { interfaces, changes: interfaces, changedCount: interfaces.length, interfacesTotal: interfaces.length } })
}
return route.fulfill({ json: path === "/api/servers" ? servers
: path === "/api/auth/config" ? { required: false }
: path === "/api/evobgp/settings" ? { enabled: false, baseUrl: "", secretConfigured: false }
: path === "/api/filters/rules" ? { rulesets: [{ serverId: "1", rules: ids.map(i => ({ id: String(i), community: `65001:${i}`, communityName: `Сервис ${i}`, gateway: "192.0.2.2", gatewayTunnelId: "", description: "" })) }] }
: path === "/api/uptime/speed-probes" ? { probes: [] }
: path.endsWith("/ospf") ? { interfaces: [], instances: [], neighbors: [], bfdSessions: [] } : {} })
})
await page.goto("/route-optimizer")
await expect(page.getByRole("table").filter({ hasText: "WAN-аплинк" }).locator("tr[data-row-id]")).toHaveCount(12)
}
test("Оптимизатор: 12 WAN, все комбинации и закрепление Community после сортировки", async ({ page }) => {
const errors: string[] = []
page.on("pageerror", e => errors.push(e.message))
await setup(page)
const matrix = page.getByRole("table").filter({ hasText: "WAN-аплинк" })
await expect(matrix.locator("tr[data-row-id]")).toHaveCount(12)
await expect(matrix.getByRole("columnheader", { name: /Роутер 2/ })).toBeVisible()
await expect(matrix.locator('tr[data-row-id="wan12"]')).toContainText("WAN12")
await page.getByRole("button", { name: "Маршруты (12)", exact: true }).click()
const routes = page.getByRole("table").filter({ hasText: "# Маршрут" })
await expect(routes.locator("tr[data-row-id]")).toHaveCount(5)
await page.getByRole("button", { name: "Показать все 12 комбинаций", exact: true }).click()
await expect(routes.locator("tr[data-row-id]")).toHaveCount(12)
await routes.getByRole("button", { name: "P(opt)", exact: true }).click()
await routes.getByRole("button", { name: "P(opt)", exact: true }).click()
await expect(routes.locator("tr[data-row-id]").first()).toHaveAttribute("data-row-id", "1-wan12-2-3")
await page.getByRole("button", { name: "Свернуть", exact: true }).click()
await expect(routes.locator("tr[data-row-id]")).toHaveCount(5)
await page.getByRole("button", { name: "BGP community (12)", exact: true }).click()
const recs = page.getByRole("table").filter({ hasText: "Community" })
await expect(recs.locator("tr[data-row-id]")).toHaveCount(12)
await recs.getByRole("button", { name: "Community", exact: true }).click()
await recs.getByRole("button", { name: "Community", exact: true }).click()
const selected = recs.locator("tr[data-row-id]").first()
await expect(selected).toContainText("65001:12")
await selected.getByRole("button", { name: "Закрепить", exact: true }).click()
await expect(selected.getByRole("button", { name: "Открепить", exact: true })).toBeVisible()
await expect(selected.getByRole("button", { name: "Применить", exact: true })).toHaveCount(0)
expect(errors).toEqual([])
})
test("OSPF preview: 12 интерфейсов и числовая сортировка", async ({ page }) => {
await setup(page)
const table = page.getByRole("table").filter({ hasText: "Speed (dl/ul)" })
await expect(table.locator("tr[data-row-id]")).toHaveCount(12)
await table.getByRole("button", { name: "Cost", exact: true }).click()
await expect(table.locator("tr[data-row-id]").first()).toContainText("ether12")
})
for (const state of ["empty", "error"] as const) {
test(`OSPF preview: состояние ${state}`, async ({ page }) => {
await setup(page, state)
await expect(page.getByText(state === "empty" ? "Интерфейсы OSPF не найдены для выбранного сервера" : /Ошибка preview:.*Расчёт недоступен/)).toBeVisible()
await expect(page.getByRole("table").filter({ hasText: "Speed (dl/ul)" })).toHaveCount(0)
})
}