Jelajahi Sumber

fix(push): localize alert notifications in the service worker (#689) (#706)

The push payload carried server-side Spanish literals, so an English
UI still got Spanish notifications. The server now also sends the
stable alert type slug and its interpolation vars; the service worker
translates them with the app catalogs (alerts.types.*, alerts.hints.*)
using the device language, falling back to the literals when the type
or catalog is missing. Pure helpers live in src/lib/push-i18n.ts.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 bulan lalu
induk
melakukan
2fbecfd078

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- **Las notificaciones push de alertas se traducen al idioma del dispositivo (#689)**: el payload viajaba con los literales en español, así que un usuario con la app en inglés recibía los avisos en español. Ahora el server añade el slug del tipo y sus variables (`type`/`vars`) y el service worker traduce con el catálogo de la app (`alerts.types.*` / `alerts.hints.*`) según el idioma del navegador, manteniendo los literales como fallback.
 - **Los nombres de la topología ya no se montan sobre los iconos (#692)**: los labels de los APs se dibujaban a los lados y chocaban con el abanico de clientes cableados (que sale al oeste) y con los chips wifi; los de los peers WireGuard se montaban sobre su propio icono y el del peer vecino. Ahora ambos van centrados bajo el nodo: el modelo ya excluye el ángulo del label al repartir los chips wifi, así que ese sector queda libre por construcción.
 - **El resumen de alertas de la Home ya no muestra "ahora mismo" para todo (#698)**: `AlertItem` (y el aviso de temperatura del detalle de router) pintaban el campo `time` legacy, que el backend rellena con "ahora mismo" fijo en las alertas en vivo; una alerta de ayer seguía diciendo "ahora mismo". Ahora usan `alertRelTime`, que calcula el relativo real desde `ts` y solo cae al string legacy si falta el timestamp.
 - **El "Visto" de la flota de agentes ya no oscila (#691)**: el contador de "último push" solo se recalculaba en renders esporádicos (con la llegada de snapshots), así que se congelaba entre actualizaciones y saltaba hacia atrás con cada push del agente (oscilación tipo 39-44-18-23 s). Un único reloj compartido de 1 s alimenta ahora toda la tabla: la celda avanza segundo a segundo y solo cae cuando llega un push realmente nuevo.

+ 60 - 0
app/src/lib/push-i18n.ts

@@ -0,0 +1,60 @@
+/**
+ * i18n de las notificaciones push (#689).
+ *
+ * El motor de alertas del server compone el push con literales en español y,
+ * desde #689, envía también el slug del tipo (`type`) y sus variables (`vars`).
+ * El Service Worker traduce con el idioma del dispositivo usando los mismos
+ * catálogos de la app (`public/locales/<lang>/translation.json`), sin duplicar
+ * textos: claves `alerts.types.<slug>.title|.description` y `alerts.hints.<slug>`.
+ *
+ * Funciones puras para poder probarlas fuera del SW.
+ */
+
+/** Subconjunto del catálogo de traducciones que necesita el push. */
+export interface PushCatalog {
+  alerts?: {
+    types?: Record<string, { title?: string; description?: string }>
+    hints?: Record<string, string>
+  }
+}
+
+export interface PushFallback {
+  title?: string
+  body?: string
+  hint?: string
+}
+
+export interface LocalizedPush {
+  title: string
+  body: string
+  hint?: string
+}
+
+/** Idioma de la notificación a partir del idioma del navegador (en* → en, resto → es). */
+export function pushLang(navLang: string | undefined): 'es' | 'en' {
+  return (navLang ?? '').toLowerCase().startsWith('en') ? 'en' : 'es'
+}
+
+/** Interpola `{{var}}` con las variables del evento (mismo formato que i18next). */
+export function interpolate(tpl: string, vars: Record<string, string> | undefined): string {
+  if (!vars) return tpl
+  return tpl.replace(/\{\{(\w+)\}\}/g, (match, key: string) => (key in vars ? vars[key]! : match))
+}
+
+/**
+ * Traduce title/description/hint de un evento tipado. Si no hay `type`, falta
+ * la clave o el catálogo no cargó, cae a los literales del server (fallback).
+ */
+export function localizePush(
+  catalog: PushCatalog | null,
+  type: string | undefined,
+  vars: Record<string, string> | undefined,
+  fallback: PushFallback,
+): LocalizedPush {
+  const entry = type ? catalog?.alerts?.types?.[type] : undefined
+  const title = entry?.title ? interpolate(entry.title, vars) : fallback.title || 'NetPulse'
+  const body = entry?.description ? interpolate(entry.description, vars) : fallback.body ?? ''
+  // El hint solo se muestra si el evento traía uno; se prefiere la clave i18n.
+  const hint = fallback.hint ? (type ? catalog?.alerts?.hints?.[type] ?? fallback.hint : fallback.hint) : undefined
+  return { title, body, hint }
+}

+ 45 - 3
app/src/sw.ts

@@ -15,6 +15,7 @@
 import { clientsClaim } from 'workbox-core'
 import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching'
 import { NavigationRoute, registerRoute } from 'workbox-routing'
+import { localizePush, pushLang, type PushCatalog } from '@/lib/push-i18n'
 
 declare let self: ServiceWorkerGlobalScope
 
@@ -37,12 +38,16 @@ if (!import.meta.env.DEV) {
 
 // ---------------------------------------------------------------------------
 // Web Push (SPEC-PUSH §2)
-// Payload: {title, body, category, severity, url:"/alerts", tag}
+// Payload: {title, body, type, vars, category, severity, url:"/alerts", tag}
 // ---------------------------------------------------------------------------
 
 interface PushPayload {
   title?: string
   body?: string
+  /** slug estable del tipo de alerta (#689); permite traducir en el SW */
+  type?: string
+  /** variables de interpolación del tipo (#689) */
+  vars?: Record<string, string>
   category?: string
   severity?: string
   url?: string
@@ -50,6 +55,29 @@ interface PushPayload {
   hint?: string
 }
 
+const I18N_CACHE = 'netpulse-i18n-v1'
+
+/**
+ * Catálogo de traducciones del idioma dado, cache-first (#689). Los locales
+ * viven en public/ y se sirven como estáticos; el SW los cachea la primera vez
+ * para no depender de la red en cada push.
+ */
+async function pushCatalog(lang: 'es' | 'en'): Promise<PushCatalog | null> {
+  const url = `/locales/${lang}/translation.json`
+  try {
+    const cache = await caches.open(I18N_CACHE)
+    let res = await cache.match(url)
+    if (!res) {
+      res = await fetch(url)
+      if (res.ok) await cache.put(url, res.clone())
+    }
+    if (!res || !res.ok) return null
+    return (await res.json()) as PushCatalog
+  } catch {
+    return null
+  }
+}
+
 self.addEventListener('push', (event: PushEvent) => {
   event.waitUntil(onPush(event))
 })
@@ -62,8 +90,22 @@ async function onPush(event: PushEvent): Promise<void> {
     // Payload no-JSON: notificación genérica (nunca romper el handler)
     payload = {}
   }
-  await self.registration.showNotification(payload.title || 'NetPulse', {
-    body: [payload.body, payload.hint].filter(Boolean).join('\n'),
+  let title = payload.title || 'NetPulse'
+  let body = [payload.body, payload.hint].filter(Boolean).join('\n')
+  // #689: si el evento trae el slug del tipo, traduce al idioma del dispositivo
+  // (catálogo de la app); si falla, se conservan los literales del server.
+  if (payload.type) {
+    const catalog = await pushCatalog(pushLang(navigator.language))
+    const loc = localizePush(catalog, payload.type, payload.vars, {
+      title: payload.title,
+      body: payload.body,
+      hint: payload.hint,
+    })
+    title = loc.title
+    body = [loc.body, loc.hint].filter(Boolean).join('\n')
+  }
+  await self.registration.showNotification(title, {
+    body,
     icon: '/icon-192.png',
     badge: '/icon-192.png',
     // tag = dedup nativo del navegador (SPEC: tag = id del evento)

+ 15 - 7
server-go/internal/push/notifier.go

@@ -35,14 +35,20 @@ const (
 
 // payload es el JSON cifrado que recibe el Service Worker (contrato con
 // app/src/sw.ts: {title, body, category, severity, url, tag, hint}).
+// Desde #689 viaja además {type, vars}: el slug estable del tipo de alerta y
+// sus variables de interpolación, para que el SW traduzca la notificación al
+// idioma del dispositivo. Los literales title/body/hint se mantienen como
+// fallback (SW antiguo o tipo sin clave i18n).
 type payload struct {
-	Title    string `json:"title"`
-	Body     string `json:"body"`
-	Category string `json:"category"`
-	Severity string `json:"severity"`
-	URL      string `json:"url"`
-	Tag      string `json:"tag"`            // alertId: dedup nativo del navegador
-	Hint     string `json:"hint,omitempty"` // sugerencia accionable (issue #310)
+	Title    string            `json:"title"`
+	Body     string            `json:"body"`
+	Type     string            `json:"type,omitempty"`
+	Vars     map[string]string `json:"vars,omitempty"`
+	Category string            `json:"category"`
+	Severity string            `json:"severity"`
+	URL      string            `json:"url"`
+	Tag      string            `json:"tag"`            // alertId: dedup nativo del navegador
+	Hint     string            `json:"hint,omitempty"` // sugerencia accionable (issue #310)
 }
 
 // Notifier implementa alerts.Notifier con entrega asíncrona.
@@ -111,6 +117,8 @@ func payloadJSON(ev alerts.AlertEvent) ([]byte, error) {
 	return json.Marshal(payload{
 		Title:    ev.Title,
 		Body:     ev.Description,
+		Type:     ev.Type,
+		Vars:     ev.Vars,
 		Category: ev.Category,
 		Severity: ev.Severity,
 		URL:      "/alerts",

+ 15 - 7
server-go/internal/push/push_test.go

@@ -204,6 +204,8 @@ func testEvent() alerts.AlertEvent {
 		Title:       "Router sin respuesta",
 		Description: "Sin respuesta de 192.168.8.1",
 		Hint:        "Revisa la alimentación del router",
+		Type:        "router-down",
+		Vars:        map[string]string{"router": "192.168.8.1"},
 	}
 }
 
@@ -268,13 +270,15 @@ func TestNotifierSendsEncryptedPayload(t *testing.T) {
 
 	plain := decryptAES128GCM(t, ua, req.body)
 	var p struct {
-		Title    string `json:"title"`
-		Body     string `json:"body"`
-		Category string `json:"category"`
-		Severity string `json:"severity"`
-		URL      string `json:"url"`
-		Tag      string `json:"tag"`
-		Hint     string `json:"hint"`
+		Title    string            `json:"title"`
+		Body     string            `json:"body"`
+		Type     string            `json:"type"`
+		Vars     map[string]string `json:"vars"`
+		Category string            `json:"category"`
+		Severity string            `json:"severity"`
+		URL      string            `json:"url"`
+		Tag      string            `json:"tag"`
+		Hint     string            `json:"hint"`
 	}
 	if err := json.Unmarshal(plain, &p); err != nil {
 		t.Fatalf("payload no es JSON: %v (%q)", err, plain)
@@ -286,6 +290,10 @@ func TestNotifierSendsEncryptedPayload(t *testing.T) {
 	if p.Hint != "Revisa la alimentación del router" {
 		t.Fatalf("payload hint: %q", p.Hint)
 	}
+	// #689: el slug y las vars viajan para que el SW pueda traducir el push.
+	if p.Type != "router-down" || p.Vars["router"] != "192.168.8.1" {
+		t.Fatalf("payload type/vars: type=%q vars=%v", p.Type, p.Vars)
+	}
 }
 
 // Un push service que responde 410 (suscripción expirada) provoca la purga