Просмотр исходного кода

fase6(app): tipos AlertEvent{category,urgent,ts} + alertConfig (defaults SPEC §2, localStorage demo) + DataProvider (config GET/PUT, read/read-all server, unread demo con config) + mock/feed con ts escalonados + relTimeFromTs

agent 4 месяцев назад
Родитель
Сommit
d6dd7d539e
6 измененных файлов с 337 добавлено и 20 удалено
  1. 134 3
      app/src/data/DataProvider.tsx
  2. 83 0
      app/src/data/alertConfig.ts
  3. 57 1
      app/src/data/alertFeed.ts
  4. 15 10
      app/src/data/mock.ts
  5. 19 2
      app/src/data/types.ts
  6. 29 4
      app/src/i18n.ts

+ 134 - 3
app/src/data/DataProvider.tsx

@@ -15,8 +15,11 @@
 import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
 import type {
   AdGuardStats,
+  AlertCategory,
+  AlertConfigLevel,
   AlertEvent,
   AlertQuery,
+  AlertsConfig,
   Device,
   DeviceQuery,
   DeviceTotals,
@@ -42,6 +45,12 @@ import {
   wan as mockWan,
   wireguard as mockWireguard,
 } from '@/data/mock'
+import {
+  countUnreadAlerts,
+  loadDemoAlertsConfig,
+  normalizeAlertsConfig,
+  saveDemoAlertsConfig,
+} from '@/data/alertConfig'
 import { buildClientDevices } from '@/pages/devices-data'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import type { RouterExtras } from '@/components/routers/routerExtras'
@@ -94,6 +103,17 @@ export interface NetPulseApi extends NetPulseData {
   getRouterDetail: (id: string) => Promise<RouterDetailData | null>
   getDevices: (params?: DeviceQuery) => Promise<Paged<Device>>
   getAlerts: (params?: AlertQuery) => Promise<Paged<AlertEvent>>
+  /**
+   * Configuración de alertas por categoría (SPEC-ALERTAS §2). Live: GET/PUT
+   * /api/alerts/config (kv en backend). Demo: localStorage (UI demostrable).
+   */
+  alertsConfig: AlertsConfig
+  /** Cambia el nivel de UNA categoría (PUT parcial en live). Resuelve true si persistió. */
+  setAlertConfig: (category: AlertCategory, level: AlertConfigLevel) => Promise<boolean>
+  /** Read state en SERVIDOR (live): POST /api/alerts/read. Demo: estado local. Optimista. */
+  markAlertsRead: (ids: string[]) => void
+  /** POST /api/alerts/read-all (live). Demo: estado local. Optimista. */
+  markAllAlertsRead: () => void
 }
 
 // ---------------------------------------------------------------------------
@@ -276,11 +296,16 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   // Marca temporal del último snapshot fresco (el botón "Refrescar" gira
   // hasta que esto avanza o expira su timeout de seguridad)
   const [lastSnapshotAt, setLastSnapshotAt] = useState(0)
+  // Config de alertas: arranca con la demo (localStorage); en live la
+  // reemplaza GET /api/alerts/config durante el boot
+  const [alertsConfig, setAlertsConfigState] = useState<AlertsConfig>(loadDemoAlertsConfig)
 
   // Refs para closures estables (getters async con la misma firma en ambos modos)
   const bundleRef = useRef(bundle)
   bundleRef.current = bundle
   const modeRef = useRef<'boot' | 'live' | 'demo'>('boot')
+  const configRef = useRef(alertsConfig)
+  configRef.current = alertsConfig
 
   const applyOverview = useCallback((o: OverviewBundle) => {
     setLastSnapshotAt(Date.now())
@@ -398,12 +423,24 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       }
     }
 
+    const fetchAlertsConfig = async (): Promise<void> => {
+      try {
+        const res = await fetchJson('/api/alerts/config')
+        if (!res.ok) return
+        const cfg = normalizeAlertsConfig(await res.json())
+        if (!disposed) setAlertsConfigState(cfg)
+      } catch {
+        /* sin config: se quedan los defaults del SPEC §2 */
+      }
+    }
+
     const startLive = async () => {
       modeRef.current = 'live'
       setIsDemo(false)
       setBundle(emptyBundle()) // live: cero datos del mockup, solo backend
       const ok = await fetchOverview()
       await fetchDevices()
+      await fetchAlertsConfig()
       if (disposed) return
       if (ok) setConnectionStatus('connected')
       else {
@@ -417,6 +454,8 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       modeRef.current = 'demo'
       setIsDemo(true)
       setConnectionStatus('demo')
+      // Demo: el badge de no leídas respeta la config guardada (SPEC §2)
+      setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, configRef.current) }))
       tickId = window.setInterval(() => {
         if (!disposed) setBundle((prev) => demoTick(prev))
       }, DEMO_TICK_MS)
@@ -473,6 +512,91 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
   }, [])
 
+  // -- Alertas: config + read state (SPEC-ALERTAS §2/§4) -----------------------
+
+  /** Aplica una config nueva al estado y, en demo, la persiste y recalcula el badge. */
+  const applyAlertsConfig = useCallback((cfg: AlertsConfig) => {
+    configRef.current = cfg
+    setAlertsConfigState(cfg)
+    if (modeRef.current !== 'live') {
+      saveDemoAlertsConfig(cfg)
+      setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, cfg) }))
+    }
+  }, [])
+
+  const setAlertConfig = useCallback(
+    async (category: AlertCategory, level: AlertConfigLevel): Promise<boolean> => {
+      const optimistic = { ...configRef.current, [category]: level }
+      applyAlertsConfig(optimistic)
+      if (modeRef.current !== 'live') return true
+      try {
+        const res = await fetch('/api/alerts/config', {
+          method: 'PUT',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ [category]: level }),
+        })
+        if (res.status === 401) redirectLogin()
+        if (!res.ok) {
+          // Resync con la verdad del servidor (p. ej. 400 por valor inválido)
+          const g = await fetch('/api/alerts/config')
+          if (g.status === 401) redirectLogin()
+          if (g.ok) applyAlertsConfig(normalizeAlertsConfig(await g.json()))
+          return false
+        }
+        applyAlertsConfig(normalizeAlertsConfig(await res.json()))
+        refresh() // la lista/badge pueden cambiar con la nueva config
+        return true
+      } catch {
+        return false
+      }
+    },
+    [applyAlertsConfig, refresh],
+  )
+
+  /** Marca leídas de forma optimista; en live además POST /api/alerts/read. */
+  const markAlertsRead = useCallback((ids: string[]) => {
+    if (ids.length === 0) return
+    const idSet = new Set(ids)
+    setBundle((prev) => {
+      const alerts = prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a))
+      const unreadAlerts =
+        modeRef.current === 'live'
+          ? alerts.filter((a) => !a.read).length
+          : countUnreadAlerts(alerts, configRef.current)
+      return { ...prev, alerts, unreadAlerts }
+    })
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/read', {
+          method: 'POST',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ ids }),
+        })
+        if (res.status === 401) redirectLogin()
+      } catch {
+        /* el próximo snapshot/SSE resincroniza el read state */
+      }
+    })()
+  }, [])
+
+  const markAllAlertsRead = useCallback(() => {
+    setBundle((prev) => ({
+      ...prev,
+      alerts: prev.alerts.map((a) => ({ ...a, read: true })),
+      unreadAlerts: 0,
+    }))
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/read-all', { method: 'POST' })
+        if (res.status === 401) redirectLogin()
+      } catch {
+        /* idem: resync por snapshot */
+      }
+    })()
+  }, [])
+
   const getRouterDetail = useCallback(async (id: string): Promise<RouterDetailData | null> => {
     if (modeRef.current === 'live') {
       const res = await fetch(`/api/routers/${encodeURIComponent(id)}`)
@@ -543,15 +667,17 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   }, [])
 
   const getAlerts = useCallback(async (params: AlertQuery = {}): Promise<Paged<AlertEvent>> => {
-    const { severity, page = 1, pageSize = 20 } = params
+    const { severity, category, unread, page = 1, pageSize = 20 } = params
     if (modeRef.current === 'live') {
-      const res = await fetch(`/api/alerts${toQuery({ severity, page, pageSize })}`)
+      const res = await fetch(`/api/alerts${toQuery({ severity, category, unread: unread ? 1 : undefined, page, pageSize })}`)
       if (res.status === 401) redirectLogin()
       if (!res.ok) throw new Error(`GET /api/alerts → ${res.status}`)
       return (await res.json()) as Paged<AlertEvent>
     }
     let items = bundleRef.current.alerts
     if (severity) items = items.filter((a) => a.severity === severity)
+    if (category) items = items.filter((a) => a.category === category)
+    if (unread) items = items.filter((a) => !a.read)
     const start = (page - 1) * pageSize
     return { items: items.slice(start, start + pageSize), total: items.length, page, pageSize }
   }, [])
@@ -567,8 +693,13 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       getRouterDetail,
       getDevices,
       getAlerts,
+      alertsConfig,
+      setAlertConfig,
+      markAlertsRead,
+      markAllAlertsRead,
     }),
-    [bundle, connectionStatus, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts],
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+    [bundle, connectionStatus, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 83 - 0
app/src/data/alertConfig.ts

@@ -0,0 +1,83 @@
+/**
+ * NetPulse — Configuración de alertas por categoría (SPEC-ALERTAS §2).
+ *
+ * Niveles: "urgent" (solo eventos urgentes) · "all" (todo) · "none" (se
+ * descarta: no se guarda, no cuenta, no empuja). En modo live la fuente de
+ * verdad es el backend (GET/PUT /api/alerts/config, persistencia kv); en demo
+ * (sin backend) vive en localStorage para que la UI sea demostrable.
+ */
+
+import type { AlertCategory, AlertConfigLevel, AlertEvent, AlertsConfig } from '@/data/types'
+
+export const ALERT_CATEGORIES: readonly AlertCategory[] = [
+  'router',
+  'internet',
+  'clients',
+  'signal',
+  'vpn',
+  'system',
+]
+
+export const ALERT_CONFIG_LEVELS: readonly AlertConfigLevel[] = ['urgent', 'all', 'none']
+
+/** Defaults del SPEC §2 (mismo JSON que `alerts.config.v1` en el backend). */
+export const DEFAULT_ALERTS_CONFIG: AlertsConfig = {
+  router: 'urgent',
+  internet: 'urgent',
+  clients: 'urgent',
+  signal: 'none',
+  vpn: 'none',
+  system: 'all',
+}
+
+const DEMO_CONFIG_KEY = 'netpulse-alerts-config-v1'
+
+const isLevel = (v: unknown): v is AlertConfigLevel =>
+  typeof v === 'string' && (ALERT_CONFIG_LEVELS as readonly string[]).includes(v)
+
+/** Normaliza un mapa cualquiera a las 6 claves (rellena defaults, descarta inválidos). */
+export function normalizeAlertsConfig(raw: unknown): AlertsConfig {
+  const cfg = { ...DEFAULT_ALERTS_CONFIG }
+  if (raw && typeof raw === 'object') {
+    for (const cat of ALERT_CATEGORIES) {
+      const v = (raw as Record<string, unknown>)[cat]
+      if (isLevel(v)) cfg[cat] = v
+    }
+  }
+  return cfg
+}
+
+/** Config demo: localStorage con defaults si no hay nada guardado. */
+export function loadDemoAlertsConfig(): AlertsConfig {
+  try {
+    const raw = localStorage.getItem(DEMO_CONFIG_KEY)
+    if (raw) return normalizeAlertsConfig(JSON.parse(raw))
+  } catch {
+    /* localStorage no disponible o JSON corrupto → defaults */
+  }
+  return { ...DEFAULT_ALERTS_CONFIG }
+}
+
+export function saveDemoAlertsConfig(cfg: AlertsConfig): void {
+  try {
+    localStorage.setItem(DEMO_CONFIG_KEY, JSON.stringify(cfg))
+  } catch {
+    /* sin localStorage: la config vive solo en estado */
+  }
+}
+
+/**
+ * ¿Pasa un evento el filtro de su categoría? (semántica §2: none descarta,
+ * urgent solo deja los urgentes). Categoría desconocida → 'all' (no esconder).
+ */
+export function passesAlertConfig(ev: Pick<AlertEvent, 'category' | 'urgent'>, cfg: AlertsConfig): boolean {
+  const level: AlertConfigLevel = cfg[ev.category] ?? 'all'
+  if (level === 'none') return false
+  if (level === 'urgent') return ev.urgent
+  return true
+}
+
+/** No leídas que pasan la config — el contador de la campana en demo. */
+export function countUnreadAlerts(alerts: Pick<AlertEvent, 'category' | 'urgent' | 'read'>[], cfg: AlertsConfig): number {
+  return alerts.filter((a) => !a.read && passesAlertConfig(a, cfg)).length
+}

+ 57 - 1
app/src/data/alertFeed.ts

@@ -94,6 +94,10 @@ export function buildAlertFeed(
   const canon = new Proxy(byId as Record<string, AlertEvent>, {
     get: (target, id: string) => target[id] ?? fallbackCanon[id],
   })
+  // Ts de los eventos de presentación (no canónicos): escalonados en
+  // coherencia con su string "hace X" (SPEC-ALERTAS §5)
+  const now = Math.floor(Date.now() / 1000)
+  const ago = (s: number) => now - s
 
   return [
   // ————— Hoy —————
@@ -146,10 +150,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-pico-trafico',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Pico de tráfico',
     description: '412 Mbps de bajada — streaming 4K en TV Samsung',
     time: 'hace 1 h',
+    ts: ago(3600),
     read: true,
     routerId: 'flint2',
     day: 'hoy',
@@ -168,10 +175,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-backup-nas',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Backup del NAS completado',
     description: 'Copia nocturna adelantada — pico de subida de 96 Mbps',
     time: 'hace 1 h',
+    ts: ago(3600),
     read: true,
     routerId: 'flint2',
     day: 'hoy',
@@ -199,10 +209,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-dns-robot',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Consultas DNS inusuales',
     description: "AdGuard: +340 % desde 'Robot aspirador' (reintentos)",
     time: 'hace 5 h',
+    ts: ago(5 * 3600),
     read: true,
     routerId: 'patio',
     day: 'hoy',
@@ -220,10 +233,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-wg-trabajo',
+    category: 'vpn',
+    urgent: false,
     severity: 'info',
     title: 'Túnel WireGuard cerrado',
     description: 'Portátil trabajo se desconectó tras 6 h de sesión',
     time: 'hace 6 h',
+    ts: ago(6 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'hoy',
@@ -256,10 +272,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-macbook-vpn',
+    category: 'vpn',
+    urgent: false,
     severity: 'info',
     title: 'MacBook Air conectado por VPN',
     description: 'Handshake desde 79.153.x.x · túnel 10.0.0.3',
     time: 'hace 1 día',
+    ts: ago(24 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'ayer',
@@ -277,10 +296,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-canal-patio',
+    category: 'signal',
+    urgent: false,
     severity: 'info',
     title: 'Canal 2.4 GHz cambiado',
     description: 'Patio: canal 6 → 11 (selección automática)',
     time: 'hace 1 día',
+    ts: ago(24 * 3600),
     read: true,
     routerId: 'patio',
     day: 'ayer',
@@ -295,10 +317,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-perdida-ok',
+    category: 'internet',
+    urgent: false,
     severity: 'ok',
     title: 'Pérdida de paquetes resuelta',
     description: 'La WAN vuelve a estar estable (0 % de pérdida)',
     time: 'hace 1 día',
+    ts: ago(25 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'ayer',
@@ -314,10 +339,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-nest-hub',
+    category: 'clients',
+    urgent: false,
     severity: 'info',
     title: 'Nuevo dispositivo',
     description: "'Nest Hub' se ha unido a Estudio",
     time: 'hace 1 día',
+    ts: ago(26 * 3600),
     read: true,
     routerId: 'estudio',
     day: 'ayer',
@@ -334,10 +362,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-adguard-listas',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'Listas de AdGuard actualizadas',
     description: '218 442 reglas activas en 6 listas de filtros',
     time: 'hace 1 día',
+    ts: ago(27 * 3600),
     read: true,
     routerId: 'flint2',
     day: 'ayer',
@@ -348,10 +379,13 @@ export function buildAlertFeed(
   // ————— 12 nov (arranque del historial, 32 días) —————
   {
     id: 'evt-reinicio-gateway',
+    category: 'router',
+    urgent: false,
     severity: 'info',
     title: 'Reinicio programado del Gateway',
     description: 'Mantenimiento a las 03:12 — el uptime actual arranca aquí',
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     routerId: 'flint2',
     day: '12nov',
@@ -366,10 +400,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-wg-setup',
+    category: 'vpn',
+    urgent: false,
     severity: 'info',
     title: 'WireGuard configurado',
     description: `Servidor ${wg.interface} activo con ${wg.peers.length} peers (${wg.subnet})`,
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     routerId: 'flint2',
     day: '12nov',
@@ -378,10 +415,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-adguard-on',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'AdGuard Home activado',
     description: 'DNS de la red apuntando a 192.168.8.1:3000',
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     routerId: 'flint2',
     day: '12nov',
@@ -390,10 +430,13 @@ export function buildAlertFeed(
   },
   {
     id: 'evt-netpulse-start',
+    category: 'system',
+    urgent: false,
     severity: 'info',
     title: 'NetPulse empezó a monitorizar',
     description: 'Primer evento del historial — bienvenido a bordo',
     time: 'hace 32 días',
+    ts: ago(32 * 24 * 3600),
     read: true,
     day: '12nov',
     kind: 'sistema',
@@ -416,12 +459,25 @@ const LIVE_KIND: [RegExp, AlertKind][] = [
   [/^alert-(nuevo|device)/, 'dispositivos'],
 ]
 
+/** Respaldo por categoría (SPEC-ALERTAS §1) cuando el id no casa con LIVE_KIND. */
+const KIND_BY_CATEGORY: Record<AlertEvent['category'], AlertKind> = {
+  router: 'router',
+  internet: 'router',
+  clients: 'dispositivos',
+  signal: 'router',
+  vpn: 'wireguard',
+  system: 'sistema',
+}
+
 /** Mapea las alertas reales a FeedEvent sin contexto inventado. */
 export function buildLiveFeed(canonAlerts: AlertEvent[]): FeedEvent[] {
   return canonAlerts.map((a) => ({
     ...a,
     day: 'hoy' as FeedDay,
-    kind: LIVE_KIND.find(([re]) => re.test(a.id))?.[1] ?? (a.routerId ? 'router' : 'sistema'),
+    kind:
+      LIVE_KIND.find(([re]) => re.test(a.id))?.[1] ??
+      KIND_BY_CATEGORY[a.category] ??
+      (a.routerId ? 'router' : 'sistema'),
   }))
 }
 

+ 15 - 10
app/src/data/mock.ts

@@ -441,26 +441,31 @@ export const wireguard: WireGuardStats = {
 // Alertas (canon §11)
 // ---------------------------------------------------------------------------
 
+// Ts unix SEGUNDOS escalonados en coherencia con el string legado
+// ("38s ago" → now-38, "12 min ago" → now-720, ...) — espejo del canon Go
+// (server-go/internal/adapters/demo_dataset.go canonAlerts, SPEC-ALERTAS §5).
+const alertNow = Math.floor(Date.now() / 1000)
+
 export const alerts: AlertEvent[] = [
   {
-    id: 'alert-temp-patio', severity: 'warn', title: 'High temperature on Patio',
-    description: '71 °C, above the threshold (65 °C)', time: '12 min ago', read: false, routerId: 'patio',
+    id: 'alert-temp-patio', category: 'router', urgent: true, severity: 'warn', title: 'High temperature on Patio',
+    description: '71 °C, above the threshold (65 °C)', time: '12 min ago', ts: alertNow - 12 * 60, read: false, routerId: 'patio',
   },
   {
-    id: 'alert-firmware-estudio', severity: 'warn', title: 'Firmware available',
-    description: 'OpenWrt 24.10.1 for Study', time: '3h ago', read: false, routerId: 'estudio',
+    id: 'alert-firmware-estudio', category: 'system', urgent: false, severity: 'warn', title: 'Firmware available',
+    description: 'OpenWrt 24.10.1 for Study', time: '3h ago', ts: alertNow - 3 * 3600, read: false, routerId: 'estudio',
   },
   {
-    id: 'alert-nuevo-tab', severity: 'info', title: 'New device',
-    description: "'Galaxy Tab S9' joined Living Room", time: '26 min ago', read: true, routerId: 'living',
+    id: 'alert-nuevo-tab', category: 'clients', urgent: false, severity: 'info', title: 'New device',
+    description: "'Galaxy Tab S9' joined Living Room", time: '26 min ago', ts: alertNow - 26 * 60, read: true, routerId: 'living',
   },
   {
-    id: 'alert-handshake-wg', severity: 'info', title: 'WireGuard handshake',
-    description: 'Pixel 8 Pro connected from 5.224.x.x', time: '38s ago', read: true, routerId: 'flint2',
+    id: 'alert-handshake-wg', category: 'vpn', urgent: false, severity: 'info', title: 'WireGuard handshake',
+    description: 'Pixel 8 Pro connected from 5.224.x.x', time: '38s ago', ts: alertNow - 38, read: true, routerId: 'flint2',
   },
   {
-    id: 'alert-backup-adguard', severity: 'ok', title: 'AdGuard backup completed',
-    description: 'Configuration and lists backed up to the NAS', time: '1 day ago', read: true, routerId: 'flint2',
+    id: 'alert-backup-adguard', category: 'system', urgent: false, severity: 'ok', title: 'AdGuard backup completed',
+    description: 'Configuration and lists backed up to the NAS', time: '1 day ago', ts: alertNow - 24 * 3600, read: true, routerId: 'flint2',
   },
 ]
 

+ 19 - 2
app/src/data/types.ts

@@ -201,13 +201,28 @@ export interface DistributionNode {
 
 export type AlertSeverity = 'warn' | 'critical' | 'info' | 'ok'
 
+/** Taxonomía de categorías de alerta (SPEC-ALERTAS §1, espejo del backend Go). */
+export type AlertCategory = 'router' | 'internet' | 'clients' | 'signal' | 'vpn' | 'system'
+
+/** Nivel de configuración por categoría (SPEC-ALERTAS §2). */
+export type AlertConfigLevel = 'urgent' | 'all' | 'none'
+
+/** Configuración de alertas: las 6 categorías con su nivel. */
+export type AlertsConfig = Record<AlertCategory, AlertConfigLevel>
+
 export interface AlertEvent {
   id: string
+  /** Categoría del evento (filtrado + configuración por nivel) */
+  category: AlertCategory
+  /** true = "rompe silencio" (badge URGENTE; push en Bloque C) */
+  urgent: boolean
   severity: AlertSeverity
   title: string
   description: string
-  /** Timestamp relativo ya formateado: "hace 12 min" */
+  /** LEGADO display: "hace 12 min" — fallback si `ts` no es válido */
   time: string
+  /** Unix SEGUNDOS; el frontend calcula el tiempo relativo */
+  ts: number
   read: boolean
   routerId?: string
 }
@@ -264,9 +279,11 @@ export interface DeviceQuery {
   pageSize?: number
 }
 
-/** Parámetros de `GET /api/alerts?severity=&page=&pageSize=`. */
+/** Parámetros de `GET /api/alerts?severity=&category=&unread=&page=&pageSize=`. */
 export interface AlertQuery {
   severity?: AlertSeverity
+  category?: AlertCategory
+  unread?: boolean
   page?: number
   pageSize?: number
 }

+ 29 - 4
app/src/i18n.ts

@@ -40,18 +40,43 @@ export function numLocale(): string {
 }
 
 const REL_RE = /^hace\s+(\d+)\s*(s|min|h|días?|d)$/
+const REL_RE_EN = /^(\d+)\s*(s|sec|min|h|hr|d|days?)\s+ago$/
 
-/** Convierte tiempos relativos canónicos del dataset ("hace 12 min", "hoy") al idioma activo */
+/** Convierte tiempos relativos canónicos del dataset ("hace 12 min", "12 min ago", "hoy") al idioma activo */
 export function relTime(s: string): string {
   const t = s.trim()
-  if (t === 'hoy') return i18n.t('common.today')
-  const m = REL_RE.exec(t)
+  if (t === 'hoy' || t.toLowerCase() === 'today') return i18n.t('common.today')
+  const m = REL_RE.exec(t) ?? REL_RE_EN.exec(t)
   if (!m) return s
   const n = Number(m[1])
-  const unit = m[2] === 's' ? 's' : m[2] === 'min' ? 'min' : m[2] === 'h' ? 'h' : 'd'
+  const u = m[2]
+  const unit = u === 's' || u === 'sec' ? 's' : u === 'min' ? 'min' : u === 'h' || u === 'hr' ? 'h' : 'd'
   return i18n.t(`common.ago.${unit}`, { count: n, n })
 }
 
+/**
+ * Tiempo relativo desde un timestamp unix en SEGUNDOS (SPEC-ALERTAS §1: el
+ * frontend calcula el relativo; el string `time` queda como fallback legado).
+ * Devuelve null si `ts` no es usable (0/NaN/futuro lejano) → usar `relTime(time)`.
+ */
+export function relTimeFromTs(ts: number | undefined, nowMs = Date.now()): string | null {
+  if (!ts || !Number.isFinite(ts) || ts <= 0) return null
+  const diffS = Math.floor(nowMs / 1000) - ts
+  if (diffS < 0) return null
+  if (diffS < 60) return i18n.t('common.ago.s', { count: diffS, n: diffS })
+  const min = Math.floor(diffS / 60)
+  if (min < 60) return i18n.t('common.ago.min', { count: min, n: min })
+  const h = Math.floor(min / 60)
+  if (h < 24) return i18n.t('common.ago.h', { count: h, n: h })
+  const d = Math.floor(h / 24)
+  return i18n.t('common.ago.d', { count: d, n: d })
+}
+
+/** Relativo de una alerta: desde `ts` si es válido; si no, el string legado. */
+export function alertRelTime(ev: { ts?: number; time: string }): string {
+  return relTimeFromTs(ev.ts) ?? relTime(ev.time)
+}
+
 /** Uptime canónico tipo "12d 4h" → "12 días, 4 h" / "12 days, 4 h" */
 export function fmtUptime(uptime: string): string {
   const m = /^(\d+)d\s*(\d+)h$/.exec(uptime.trim())