Ver Fonte

A4(D65-7d/e + D65-8): Mi sesión Nombre (PUT + fallback localStorage, toast), bloque Sistema en Acerca de, i18n es/en

agent há 4 meses atrás
pai
commit
4f11f266f4

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

@@ -534,7 +534,17 @@
       "madeAtHome": "Support the project on Ko-fi",
       "privacy": "100% private · 0% cloud",
       "title": "About",
-      "versionNote": "v1.0.0"
+      "versionNote": "v1.0.0",
+      "system": "System",
+      "sysApp": "App",
+      "sysGo": "Go",
+      "sysReact": "React",
+      "sysOs": "OS",
+      "sysKernel": "Kernel",
+      "sysCpu": "CPU",
+      "sysRam": "RAM",
+      "sysUptime": "Uptime",
+      "demoNoServer": "Server data unavailable (demo)"
     },
     "accent": "Accent",
     "accentAmber": "Amber",
@@ -634,6 +644,9 @@
       "demoCaption": "Local simulated data, no connection to your network.",
       "exitDemo": "Exit demo mode",
       "changePassword": "Change my password",
+      "name": "Name",
+      "nameHint": "This is how the Summary greets you; it's not your username",
+      "nameSaved": "Name saved",
       "pwCurrent": "Current password",
       "pwNew": "New password",
       "pwConfirm": "Repeat password",
@@ -657,6 +670,7 @@
       "gateway": "Is the gateway",
       "gatewayBadge": "Main",
       "add": "Add",
+      "addDevice": "Add device",
       "adding": "Adding…",
       "delete": "Delete",
       "deleteConfirm": "Delete {name}? Metrics history is kept.",
@@ -682,6 +696,7 @@
       "roleAdmin": "Admin",
       "you": "You",
       "add": "Create user",
+      "createUser": "Create user",
       "adding": "Creating…",
       "delete": "Delete",
       "deleteConfirm": "Delete user {name}?",
@@ -701,6 +716,7 @@
       "user": "GL UI username",
       "pass": "GL UI password",
       "passKeep": "Saved (type to change)",
+      "edit": "Edit",
       "configured": "Configured",
       "notConfigured": "Not configured",
       "save": "Save",

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

@@ -534,7 +534,17 @@
       "madeAtHome": "Apoya el proyecto en Ko-fi",
       "privacy": "100% privado · 0% nube",
       "title": "Acerca de",
-      "versionNote": "v1.0.0"
+      "versionNote": "v1.0.0",
+      "system": "Sistema",
+      "sysApp": "App",
+      "sysGo": "Go",
+      "sysReact": "React",
+      "sysOs": "SO",
+      "sysKernel": "Kernel",
+      "sysCpu": "CPU",
+      "sysRam": "RAM",
+      "sysUptime": "Tiempo activo",
+      "demoNoServer": "Datos del servidor no disponibles (demo)"
     },
     "accent": "Acento",
     "accentAmber": "Ámbar",
@@ -634,6 +644,9 @@
       "demoCaption": "Datos simulados locales, sin conexión a tu red.",
       "exitDemo": "Salir del modo demo",
       "changePassword": "Cambiar mi contraseña",
+      "name": "Nombre",
+      "nameHint": "Así te saluda el Resumen; no es tu nombre de usuario",
+      "nameSaved": "Nombre guardado",
       "pwCurrent": "Contraseña actual",
       "pwNew": "Nueva contraseña",
       "pwConfirm": "Repite la contraseña",
@@ -657,6 +670,7 @@
       "gateway": "Es la puerta de enlace",
       "gatewayBadge": "Principal",
       "add": "Añadir",
+      "addDevice": "Añadir dispositivo",
       "adding": "Añadiendo…",
       "delete": "Eliminar",
       "deleteConfirm": "¿Eliminar {name}? El histórico de métricas se conserva.",
@@ -682,6 +696,7 @@
       "roleAdmin": "Admin",
       "you": "Tú",
       "add": "Crear usuario",
+      "createUser": "Crear usuario",
       "adding": "Creando…",
       "delete": "Eliminar",
       "deleteConfirm": "¿Eliminar al usuario {name}?",
@@ -701,6 +716,7 @@
       "user": "Usuario de la interfaz GL",
       "pass": "Contraseña de la interfaz GL",
       "passKeep": "Guardada (escribe para cambiar)",
+      "edit": "Editar",
       "configured": "Configurado",
       "notConfigured": "Sin configurar",
       "save": "Guardar",

+ 206 - 1
app/src/pages/Settings.tsx

@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router-dom'
 import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'
@@ -1085,6 +1085,114 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
 }
 
 
+// ---------------------------------------------------------------------------
+// Bloque «Sistema» en Acerca de (SPEC-65 D65-6/7e): GET /api/system/info
+// ---------------------------------------------------------------------------
+
+interface SystemInfoData {
+  version: string
+  goVersion: string
+  os: string
+  arch: string
+  distro: string
+  kernel: string
+  cpuModel: string
+  cpuCores: number
+  memTotalMb: number
+  uptimeS: number
+  demo: boolean
+}
+
+function fmtUptime(s: number): string {
+  if (!s || s <= 0) return '—'
+  const d = Math.floor(s / 86400)
+  const h = Math.floor((s % 86400) / 3600)
+  const m = Math.floor((s % 3600) / 60)
+  if (d > 0) return `${d}d ${h}h`
+  if (h > 0) return `${h}h ${m}m`
+  if (m > 0) return `${m}m`
+  return `${Math.floor(s)}s`
+}
+
+function SystemInfoBlock() {
+  const { t } = useTranslation()
+  const [info, setInfo] = useState<SystemInfoData | null>(null)
+  const [failed, setFailed] = useState(false)
+
+  useEffect(() => {
+    let disposed = false
+    void (async () => {
+      try {
+        const res = await fetch('/api/system/info')
+        // La preview estática responde HTML con 200: no es el endpoint
+        if (!res.ok || !(res.headers.get('content-type') ?? '').includes('application/json')) {
+          throw new Error(`HTTP ${res.status}`)
+        }
+        const json = (await res.json()) as SystemInfoData
+        if (!disposed) setInfo(json)
+      } catch {
+        if (!disposed) setFailed(true)
+      }
+    })()
+    return () => {
+      disposed = true
+    }
+  }, [])
+
+  // Fetch fallido o servidor en demo: solo App + React + caption (SPEC-65 D65-7e)
+  const server = info && !info.demo ? info : null
+  const rows: { label: string; value: string }[] = [
+    { label: t('settings.about.sysApp'), value: `v${server?.version || pkg.version}` },
+    ...(server ? [{ label: t('settings.about.sysGo'), value: server.goVersion || '—' }] : []),
+    { label: t('settings.about.sysReact'), value: React.version },
+    ...(server
+      ? [
+          { label: t('settings.about.sysOs'), value: `${server.distro || server.os} ${server.arch}`.trim() || '—' },
+          { label: t('settings.about.sysKernel'), value: server.kernel || '—' },
+          {
+            label: t('settings.about.sysCpu'),
+            value: server.cpuModel ? `${server.cpuModel} (${server.cpuCores})` : server.cpuCores > 0 ? `${server.cpuCores}` : '—',
+          },
+          {
+            label: t('settings.about.sysRam'),
+            value: server.memTotalMb > 0 ? `${(server.memTotalMb / 1024).toFixed(1)} GiB` : '—',
+          },
+          { label: t('settings.about.sysUptime'), value: fmtUptime(server.uptimeS) },
+        ]
+      : []),
+  ]
+
+  return (
+    <div className="mt-5 border-t border-border pt-4">
+      <div className="text-caption font-semibold uppercase tracking-[0.06em] text-text-muted">
+        {t('settings.about.system')}
+      </div>
+      {!info && !failed ? (
+        <div className="mt-2.5 grid animate-pulse grid-cols-1 gap-x-6 gap-y-2.5 sm:grid-cols-2" aria-hidden="true">
+          {Array.from({ length: 4 }).map((_, i) => (
+            <div key={i} className="flex items-baseline justify-between gap-3">
+              <span className="h-3 w-14 rounded bg-elevated" />
+              <span className="h-3 w-24 rounded bg-elevated" />
+            </div>
+          ))}
+        </div>
+      ) : (
+        <>
+          <dl className="mt-2.5 grid grid-cols-1 gap-x-6 gap-y-1.5 sm:grid-cols-2">
+            {rows.map((r) => (
+              <div key={r.label} className="flex items-baseline justify-between gap-3">
+                <dt className="shrink-0 text-caption text-text-muted">{r.label}</dt>
+                <dd className="truncate font-mono text-caption text-text-secondary">{r.value}</dd>
+              </div>
+            ))}
+          </dl>
+          {!server && <p className="mt-2 text-caption text-text-muted">{t('settings.about.demoNoServer')}</p>}
+        </>
+      )}
+    </div>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // Página Ajustes `/settings` (settings.md)
 // ---------------------------------------------------------------------------
@@ -1394,6 +1502,69 @@ export default function Settings() {
     }
   }, [pwBusy, pwCurrent, pwNew, pwConfirm, t, notify])
 
+  // ——— Nombre para el saludo del Resumen (SPEC-65 D65-5/7d) ———
+  const [nameDraft, setNameDraft] = useState('')
+  const [nameBaseline, setNameBaseline] = useState('')
+  const [nameBusy, setNameBusy] = useState(false)
+  const [nameError, setNameError] = useState<string | null>(null)
+  useEffect(() => {
+    let v = auth?.displayName ?? ''
+    if (isDemo) {
+      try {
+        v = localStorage.getItem('netpulse-displayname') ?? v
+      } catch {
+        /* modo privado */
+      }
+    }
+    setNameBaseline(v)
+    setNameDraft(v)
+  }, [isDemo, auth?.displayName])
+
+  const saveDisplayName = useCallback(async () => {
+    const v = nameDraft.trim()
+    if (nameBusy || v === nameBaseline) return
+    setNameBusy(true)
+    setNameError(null)
+    if (isDemo) {
+      try {
+        localStorage.setItem('netpulse-displayname', v)
+      } catch {
+        /* modo privado */
+      }
+      window.dispatchEvent(new Event('netpulse-auth-refresh'))
+      setNameBaseline(v)
+      setNameDraft(v)
+      setNameBusy(false)
+      notify()
+      return
+    }
+    try {
+      const res = await fetch('/api/users/me/display-name', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ displayName: v }),
+      })
+      if (res.status === 404 || res.status === 405) {
+        // Endpoint aún no desplegado: fallback local (mismo almacén que el demo)
+        try {
+          localStorage.setItem('netpulse-displayname', v)
+        } catch {
+          /* modo privado */
+        }
+      } else if (!res.ok && res.status !== 204) {
+        throw new Error(`HTTP ${res.status}`)
+      }
+      window.dispatchEvent(new Event('netpulse-auth-refresh'))
+      setNameBaseline(v)
+      setNameDraft(v)
+      notify()
+    } catch {
+      setNameError(t('settings.users.errorGeneric'))
+    } finally {
+      setNameBusy(false)
+    }
+  }, [nameDraft, nameBaseline, nameBusy, isDemo, notify, t])
+
 
   // ——— Tema (compatible con ThemeToggle: 'netpulse-theme' = light|dark) ———
   const [mode, setMode] = useStoredState<ThemeMode>(
@@ -1925,6 +2096,37 @@ export default function Settings() {
         {/* Mi sesión: cambiar contraseña + cerrar sesión (patrón easyzfs) */}
         <div className="lg:col-span-12">
           <Card title={t('settings.session.title')} index={5} reduce={reduce}>
+            {/* Nombre para el saludo del Resumen (SPEC-65 D65-7d) */}
+            <div className="mb-4 max-w-md">
+              <label htmlFor="session-display-name" className="text-sm font-medium text-text-primary">
+                {t('settings.session.name')}
+              </label>
+              <div className="mt-2 flex items-center gap-2">
+                <input
+                  id="session-display-name"
+                  type="text"
+                  value={nameDraft}
+                  maxLength={40}
+                  onChange={(e) => setNameDraft(e.target.value)}
+                  placeholder={auth?.user ?? ''}
+                  className="h-10 min-w-0 flex-1 rounded-lg border border-border bg-elevated px-3 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                />
+                <button
+                  type="button"
+                  onClick={() => void saveDisplayName()}
+                  disabled={nameBusy || nameDraft.trim() === nameBaseline}
+                  className="flex h-10 shrink-0 items-center rounded-lg bg-accent px-4 text-sm font-semibold text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"
+                >
+                  {t('settings.adguard.save')}
+                </button>
+              </div>
+              <p className="mt-1.5 text-caption text-text-muted">{t('settings.session.nameHint')}</p>
+              {nameError && (
+                <p role="alert" className="mt-1.5 text-caption text-danger">
+                  {nameError}
+                </p>
+              )}
+            </div>
             <div className="flex flex-wrap items-center gap-3">
               {!isDemo && (
                 <button
@@ -2101,6 +2303,9 @@ export default function Settings() {
 
             </div>
 
+            {/* Sistema: datos del servidor (SPEC-65 D65-7e) */}
+            <SystemInfoBlock />
+
             <p className="mt-5 border-t border-border pt-3 font-mono text-caption text-text-muted">
               {t('settings.about.footer')}
             </p>