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

fix(alerts): keep read alerts out of the home summary by default (#2217) (#2218)

Nacho 6 дней назад
Родитель
Сommit
b77d40198d

+ 3 - 1
CHANGELOG.md

@@ -13,11 +13,13 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Changed
 
-- The "Unread only" filter of the alerts page carries the number of unread alerts it would show and starts off, so the whole log is visible by default. When the filter is the only thing emptying the list, the empty state says so and offers one click back to the full log in all four languages (#2214).
+- The "Unread only" filter of the alerts page carries the number of unread alerts it would show. When the filter is the only thing emptying the list, the empty state says so and offers one click back to the full log in all four languages (#2214).
 - Marking an alert as read has a bigger target, 32 px (36 px on touch), in the feed and in the home card, so the main action of the row is no longer its smallest button (#2214).
+- The unread-only view preference is one setting shared by the alerts log and the home card, and it starts on. The card kept its own key and its own default, so on a fresh install it listed read alerts. This restores the default of #1122 and reverts the off-by-default from #2215 (#2217).
 
 ### Fixed
 
+- The alert card of the home summary no longer lists read alerts and drops one as soon as it is marked read. When the filter leaves it empty it says so, offers one click back to the whole list and a link to the alert log, and its badge no longer subtracts the same read alert twice (#2217).
 - A NetGrip panel whose embedded agent carries an old token never recovered. The rearm restarted the panel and then rotated the token in the native agent's environment file, which NetGrip does not read, so the panel kept answering 401 every cycle and the supervisor kept restarting it on each cooldown. The token now goes into `/etc/netgrip/netpulse.env`, the file the embedded agent reads, and the panel is restarted after it (#2208).
 
 ## [2.55.1] - 2026-11-28

+ 3 - 0
app/public/locales/en/translation.json

@@ -751,7 +751,10 @@
     "recentAlerts": {
       "allRead": "All caught up. No unread alerts.",
       "emptyTitle": "No alerts",
+      "emptyUnreadDesc": "Every alert is read. Turn off the filter to see the whole log.",
+      "emptyUnreadTitle": "No unread alerts",
       "lastCheck": "Last check 30s ago",
+      "openLog": "Open the alert log",
       "recheck": "Check again",
       "unreadOnly": "Unread only"
     },

+ 3 - 0
app/public/locales/es/translation.json

@@ -751,7 +751,10 @@
     "recentAlerts": {
       "allRead": "Todo en orden. No hay alertas sin leer.",
       "emptyTitle": "Sin alertas",
+      "emptyUnreadDesc": "Todas las alertas están leídas. Desactiva el filtro para ver el registro completo.",
+      "emptyUnreadTitle": "No hay alertas sin leer",
       "lastCheck": "Última comprobación hace 30 s",
+      "openLog": "Abrir el registro de alertas",
       "recheck": "Volver a comprobar",
       "unreadOnly": "Solo no leídas"
     },

+ 3 - 0
app/public/locales/ru/translation.json

@@ -756,7 +756,10 @@
     "recentAlerts": {
       "allRead": "Всё прочитано. Непрочитанных оповещений нет.",
       "emptyTitle": "Оповещений нет",
+      "emptyUnreadDesc": "Все оповещения прочитаны. Отключите фильтр, чтобы увидеть весь журнал.",
+      "emptyUnreadTitle": "Нет непрочитанных оповещений",
       "lastCheck": "Последняя проверка 30 с назад",
+      "openLog": "Открыть журнал оповещений",
       "recheck": "Проверить снова",
       "unreadOnly": "Только непрочитанные"
     },

+ 3 - 0
app/public/locales/zh/translation.json

@@ -146,7 +146,10 @@
     "recentAlerts": {
       "allRead": "已全部处理,没有未读告警。",
       "emptyTitle": "无告警",
+      "emptyUnreadDesc": "所有告警均已读。关闭筛选即可查看完整记录。",
+      "emptyUnreadTitle": "没有未读告警",
       "lastCheck": "上次检查 30 秒前",
+      "openLog": "打开告警记录",
       "recheck": "重新检查",
       "unreadOnly": "仅未读"
     },

+ 45 - 0
app/src/lib/alertViewPrefs.ts

@@ -0,0 +1,45 @@
+/**
+ * #2217: una sola preferencia de vista "solo no leídas" para el registro de
+ * alertas (`/alerts`) y la tarjeta del Resumen. Antes cada vista guardaba su
+ * clave y su default: la tarjeta arrancaba mostrando el feed completo (leídas
+ * incluidas) y la página, filtrada.
+ *
+ * Default: activada. Quien no tiene preferencia guardada no ve leídas.
+ */
+
+export const UNREAD_ONLY_KEY = 'netpulse-alerts-onlyUnread'
+
+/** Clave de la tarjeta del Resumen anterior a #2217: se migra al leerla. */
+const LEGACY_RECENT_UNREAD_ONLY_KEY = 'netpulse-recentalerts-unread-only'
+
+/** Valores guardados aceptados: '1' activo, '0' desactivado. */
+function storedBoolean(raw: string | null): boolean | null {
+  if (raw === '1') return true
+  if (raw === '0') return false
+  return null
+}
+
+export function readUnreadOnly(): boolean {
+  try {
+    const current = storedBoolean(localStorage.getItem(UNREAD_ONLY_KEY))
+    if (current !== null) return current
+    // Migración: la preferencia antigua de la tarjeta pasa a la clave común.
+    const legacy = storedBoolean(localStorage.getItem(LEGACY_RECENT_UNREAD_ONLY_KEY))
+    if (legacy !== null) {
+      localStorage.setItem(UNREAD_ONLY_KEY, legacy ? '1' : '0')
+      localStorage.removeItem(LEGACY_RECENT_UNREAD_ONLY_KEY)
+      return legacy
+    }
+  } catch {
+    /* modo privado: se aplica el default */
+  }
+  return true
+}
+
+export function writeUnreadOnly(value: boolean): void {
+  try {
+    localStorage.setItem(UNREAD_ONLY_KEY, value ? '1' : '0')
+  } catch {
+    /* modo privado */
+  }
+}

+ 8 - 7
app/src/pages/Alerts.tsx

@@ -58,6 +58,7 @@ import {
 import { buildAlertFeed, buildLiveFeed, DAY_ORDER } from '@/data/alertFeed'
 import type { FeedDay, FeedEvent, FeedSpark } from '@/data/alertFeed'
 import { useNetPulse } from '@/data/DataProvider'
+import { readUnreadOnly, writeUnreadOnly } from '@/lib/alertViewPrefs'
 import { RulesManager } from '@/components/RulesManager'
 import { cn } from '@/lib/utils'
 
@@ -94,8 +95,8 @@ const CATEGORY_META: Record<AlertCategory, { icon: LucideIcon; tile: string }> =
 
 const LEVEL_ORDER: readonly AlertConfigLevel[] = ['urgent', 'all', 'none']
 
-// #1122: preferencia de vista persistida en localStorage.
-const UNREAD_ONLY_KEY = 'netpulse-alerts-onlyUnread'
+// #1122/#2217: la preferencia de vista "solo no leídas" vive en
+// `@/lib/alertViewPrefs`, compartida con la tarjeta del Resumen.
 
 // ---------------------------------------------------------------------------
 // Filtros
@@ -687,12 +688,12 @@ export default function Alerts() {
   const [sev, setSev] = useState<SevFilter>('todas')
   const [cats, setCats] = useState<ReadonlySet<AlertCategory>>(new Set())
   const [searchParams] = useSearchParams()
-  // Persistencia de la opción de vista: sobrevive a recargas y sesiones.
-  // #2214: sin preferencia guardada arranca mostrando el registro completo;
-  // el chip "Solo no leídas" y ?unread=1 en la URL activan el filtro.
+  // Persistencia de la opción de vista: sobrevive a recargas y sesiones, y es
+  // la misma que usa la tarjeta del Resumen (#2217). Sin preferencia guardada
+  // arranca mostrando solo las no leídas; `?unread=1` la fuerza desde la URL.
   const [onlyUnread, setOnlyUnread] = useState(() => {
     if (searchParams.get('unread') === '1') return true
-    return localStorage.getItem(UNREAD_ONLY_KEY) === '1'
+    return readUnreadOnly()
   })
   const [expandedId, setExpandedId] = useState<string | null>(null)
   const [burst, setBurst] = useState(0)
@@ -717,7 +718,7 @@ export default function Alerts() {
   const unreadInFeed = useMemo(() => alertFeed.filter((ev) => !ev.read).length, [alertFeed])
 
   const setOnlyUnreadPersisted = (v: boolean) => {
-    localStorage.setItem(UNREAD_ONLY_KEY, v ? '1' : '0')
+    writeUnreadOnly(v)
     setOnlyUnread(v)
   }
 

+ 40 - 23
app/src/sections/RecentAlerts.tsx

@@ -1,12 +1,13 @@
 import { useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
-import { useNavigate } from 'react-router'
+import { Link, useNavigate } from 'react-router'
 import { motion } from 'framer-motion'
 import { RefreshCw, ShieldCheck } from 'lucide-react'
 import { AlertItem } from '@/components/AlertItem'
 import { SectionHeader } from '@/components/SectionHeader'
 import { useNetPulse } from '@/data/DataProvider'
 import { isHiddenByLevel } from '@/data/alertConfig'
+import { readUnreadOnly, writeUnreadOnly } from '@/lib/alertViewPrefs'
 import { cn } from '@/lib/utils'
 
 /** ⑥ Alertas recientes (home.md §⑥) */
@@ -28,30 +29,26 @@ export function RecentAlerts() {
     [alerts, alertsConfig],
   )
   const recent = feed.slice(0, 4)
-  // #916: toggle "solo no leídas" para mantener la tarjeta limpia en
-  // operación normal. Persistente en localStorage (preferencia de vista,
-  // no de negocio).
-  const [unreadOnly, setUnreadOnly] = useState(() => {
-    try {
-      return localStorage.getItem('netpulse-recentalerts-unread-only') === '1'
-    } catch {
-      return false
-    }
-  })
+  // #916/#2217: toggle "solo no leídas", activado por defecto y compartido con
+  // la página Alertas (misma clave y mismo helper). Persistente en
+  // localStorage (preferencia de vista, no de negocio).
+  const [unreadOnly, setUnreadOnly] = useState(readUnreadOnly)
   const toggleUnreadOnly = () => {
     setUnreadOnly((prev) => {
       const next = !prev
-      try {
-        localStorage.setItem('netpulse-recentalerts-unread-only', next ? '1' : '0')
-      } catch {
-        /* modo privado */
-      }
+      writeUnreadOnly(next)
       return next
     })
   }
   const visible = (unreadOnly ? feed.filter((a) => !a.read && !readIds.has(a.id)) : recent).slice(0, 4)
-  // El badge muestra el total de no leídas (como la campana), no solo de las 4 visibles
-  const unread = Math.max(0, unreadAlerts - readIds.size)
+  // El badge muestra el total de no leídas (como la campana), no solo de las
+  // visibles. `readIds` descuenta lo marcado aquí mientras llega el snapshot
+  // del servidor (#891), sin restar dos veces cuando el provider ya recalculó
+  // el contador (#2217).
+  const unread = useMemo(
+    () => Math.max(0, unreadAlerts - feed.filter((a) => readIds.has(a.id) && !a.read).length),
+    [unreadAlerts, feed, readIds],
+  )
 
   const markReadAndGo = (id: string) => {
     setReadIds((prev) => new Set(prev).add(id))
@@ -84,11 +81,31 @@ export function RecentAlerts() {
       <div className="-mx-3 flex flex-1 flex-col space-y-1">
         {visible.length === 0 && (
           // Estado vacío (#992): icono + microtexto, centrado en la tarjeta.
-          <div className="flex flex-1 flex-col items-center justify-center gap-2 px-3 py-6 text-center">
-            <ShieldCheck className="h-8 w-8 text-ok" strokeWidth={1.5} aria-hidden="true" />
-            <p className="text-sm font-medium text-text-secondary">{t('home.recentAlerts.emptyTitle')}</p>
-            <p className="text-caption text-text-muted">{t('home.recentAlerts.allRead')}</p>
-          </div>
+          // #2217: con el filtro activo y todo leído, el estado lo dice y
+          // ofrece ver todas (desactiva el filtro) o abrir el registro.
+          unreadOnly && feed.length > 0 ? (
+            <div className="flex flex-1 flex-col items-center justify-center gap-2 px-3 py-6 text-center">
+              <ShieldCheck className="h-8 w-8 text-ok" strokeWidth={1.5} aria-hidden="true" />
+              <p className="text-sm font-medium text-text-secondary">{t('home.recentAlerts.emptyUnreadTitle')}</p>
+              <p className="text-caption text-text-muted">{t('home.recentAlerts.emptyUnreadDesc')}</p>
+              <button
+                type="button"
+                onClick={toggleUnreadOnly}
+                className="mt-1 rounded-lg border border-accent/40 bg-accent/15 px-2.5 py-1 text-[11px] font-medium text-accent transition-colors hover:bg-accent/20"
+              >
+                {t('alerts.emptyFilteredAction')}
+              </button>
+              <Link to="/alerts" className="text-caption font-medium text-accent transition-colors hover:text-accent/80">
+                {t('home.recentAlerts.openLog')}
+              </Link>
+            </div>
+          ) : (
+            <div className="flex flex-1 flex-col items-center justify-center gap-2 px-3 py-6 text-center">
+              <ShieldCheck className="h-8 w-8 text-ok" strokeWidth={1.5} aria-hidden="true" />
+              <p className="text-sm font-medium text-text-secondary">{t('home.recentAlerts.emptyTitle')}</p>
+              <p className="text-caption text-text-muted">{t('home.recentAlerts.allRead')}</p>
+            </div>
+          )
         )}
         {visible.map((a, i) => (
           <motion.div