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

fix(alerts): localize scheduled auto-update alert by result code (#796) (#802)

fix(alerts): localize the auto-update result alert (#796)
Nacho 2 месяцев назад
Родитель
Сommit
7e833c2ef1

+ 7 - 1
app/public/locales/en/translation.json

@@ -237,7 +237,13 @@
       },
       "autoupdate": {
         "title": "Scheduled auto-update",
-        "description": "{{detail}}"
+        "description": "{{detail}}",
+        "results": {
+          "applied": "Scheduled update started: {{version}} (binary only, with health verification and automatic rollback)",
+          "check-failed": "Update check failed (reason: {{reason}}); it will retry on the next scheduled run",
+          "cannot-apply": "An update is available but this install cannot apply it now (check readiness in Settings)",
+          "apply-busy": "The scheduled update could not start (another update in progress?)"
+        }
       }
     }
   },

+ 7 - 1
app/public/locales/es/translation.json

@@ -237,7 +237,13 @@
       },
       "autoupdate": {
         "title": "Auto-actualización programada",
-        "description": "{{detail}}"
+        "description": "{{detail}}",
+        "results": {
+          "applied": "Actualización programada iniciada: {{version}} (solo binario, con verificación y rollback automático)",
+          "check-failed": "No se pudo comprobar la actualización (razón: {{reason}}); se reintentará en el próximo disparo",
+          "cannot-apply": "Hay una actualización disponible pero esta instalación no puede aplicarla ahora (revisa readiness en Ajustes)",
+          "apply-busy": "La actualización programada no pudo arrancar (¿otra actualización en curso?)"
+        }
       }
     }
   },

+ 11 - 0
app/src/lib/alerts-i18n.ts

@@ -30,6 +30,17 @@ export function alertDescription(t: TFunction, ev: AlertEvent): string {
     const vars = formatAlertTempVars(ev.type, ev.vars, readTempUnit())
     return t(`alerts.types.${ev.type}.descriptionUnit`, { defaultValue: ev.description, ...(vars ?? {}) })
   }
+  // #796: los tipos con descripciones por resultado (vars.result, p. ej. la
+  // alerta de auto-update) traducen con alerts.types.<slug>.results.<result>;
+  // el literal del server en español queda solo como fallback.
+  const resultKey = ev.vars?.result
+  if (resultKey) {
+    const translated = t(`alerts.types.${ev.type}.results.${resultKey}`, {
+      defaultValue: '',
+      ...(ev.vars ?? {}),
+    })
+    if (translated !== '') return translated
+  }
   return t(`alerts.types.${ev.type}.description`, { defaultValue: ev.description, ...(ev.vars ?? {}) })
 }
 

+ 10 - 2
app/src/lib/push-i18n.ts

@@ -13,7 +13,7 @@
 /** Subconjunto del catálogo de traducciones que necesita el push. */
 export interface PushCatalog {
   alerts?: {
-    types?: Record<string, { title?: string; description?: string }>
+    types?: Record<string, { title?: string; description?: string; results?: Record<string, string> }>
     hints?: Record<string, string>
   }
 }
@@ -44,6 +44,8 @@ export function interpolate(tpl: string, vars: Record<string, string> | undefine
 /**
  * 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).
+ * Los tipos con descripciones por resultado (vars.result, #796) usan
+ * `results.<result>` antes que la descripción genérica.
  */
 export function localizePush(
   catalog: PushCatalog | null,
@@ -53,7 +55,13 @@ export function localizePush(
 ): 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 ?? ''
+  const resultKey = vars?.result
+  const resultTpl = resultKey ? entry?.results?.[resultKey] : undefined
+  const body = resultTpl
+    ? interpolate(resultTpl, vars)
+    : 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 }

+ 13 - 6
server-go/internal/updater/autosched.go

@@ -123,26 +123,29 @@ func (s *Scheduler) shot(st AutoUpdateSettings, prev autoRunState) {
 	switch {
 	case status.CheckFailed:
 		saveAutoResult(s.db, "check-failed")
-		s.alert(false, fmt.Sprintf("No se pudo comprobar (razón: %s); se reintentará en el próximo disparo", status.CheckErr), status.CheckErr)
+		s.alert(false, "check-failed", fmt.Sprintf("No se pudo comprobar (razón: %s); se reintentará en el próximo disparo", status.CheckErr), map[string]string{"reason": status.CheckErr})
 	case !status.UpdateAvailable:
 		saveAutoResult(s.db, "up-to-date")
 	case !status.CanApply:
 		// Readiness o layout sin apply: se avisa (hay novedad esperando y no
 		// se podrá aplicar hasta que el admin lo resuelva).
 		saveAutoResult(s.db, "cannot-apply")
-		s.alert(false, "Hay una actualización disponible pero este layout no puede aplicarla ahora (revisa readiness en Ajustes)", "cannot-apply")
+		s.alert(false, "cannot-apply", "Hay una actualización disponible pero este layout no puede aplicarla ahora (revisa readiness en Ajustes)", nil)
 	default:
 		saveAutoResult(s.db, "applied")
 		if s.ua.ApplyBy("scheduled") {
-			s.alert(true, fmt.Sprintf("Actualización programada iniciada: %s (solo binario, con verificación y rollback automático)", statusLatestDeref(status)), "")
+			s.alert(true, "applied", fmt.Sprintf("Actualización programada iniciada: %s (solo binario, con verificación y rollback automático)", statusLatestDeref(status)), map[string]string{"version": statusLatestDeref(status)})
 		} else {
-			s.alert(false, "La actualización programada no pudo arrancar (¿otra actualización en curso?)", "apply-busy")
+			s.alert(false, "apply-busy", "La actualización programada no pudo arrancar (¿otra actualización en curso?)", nil)
 		}
 	}
 }
 
 // alert emite la notificación del disparo (info en éxito, warn en aviso).
-func (s *Scheduler) alert(ok bool, desc, code string) {
+// result es el código estable que el frontend usa para elegir la traducción
+// (alerts.types.autoupdate.results.<result>); desc es el literal en español
+// que sirve de fallback para servidores viejos (#796).
+func (s *Scheduler) alert(ok bool, result, desc string, extra map[string]string) {
 	s.logf("%s", desc)
 	if s.emit == nil {
 		return
@@ -151,6 +154,10 @@ func (s *Scheduler) alert(ok bool, desc, code string) {
 	if ok {
 		sev = "info"
 	}
+	vars := map[string]string{"result": result, "detail": desc}
+	for k, v := range extra {
+		vars[k] = v
+	}
 	s.emit.Emit(alerts.AlertEvent{
 		ID:          fmt.Sprintf("alert-autoupdate-%d", s.now().UnixMilli()),
 		Category:    alerts.CatSystem,
@@ -161,7 +168,7 @@ func (s *Scheduler) alert(ok bool, desc, code string) {
 		Time:        "ahora mismo",
 		Ts:          s.now().Unix(),
 		Type:        "autoupdate",
-		Vars:        map[string]string{"result": code, "detail": desc},
+		Vars:        vars,
 	})
 }