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

feat(reports): hourly and daily granularity only (#1033)

* feat(reports): add hourly range to availability endpoint (#1032)

New range=hour on GET /api/reports/availability: per-hour availability
over the last N hours (default 24, max 48) computed from raw metrics
(metrics_daily has no hourly granularity). Buckets are labelled with the
UTC hour in truncated ISO form ("2026-10-02T14").

Unlike day/week/month, hours without samples inside the window are
emitted with upMin/days/upPct 0 (gap fill), because at hourly scale the
recent gap is exactly what the view is for; only routers with at least
one sample in the window appear, same as the other ranges. The current
hour divisor counts only the elapsed minutes, matching the current-day
rule (#987). rxTotal/txTotal are emitted as 0: raw rows store rates
(bps), not totals.

The CSV/JSON response tail is shared via writeAvailability; day, week
and month ranges keep their existing semantics.

* feat(reports): hourly and daily granularity only in reports UI (#1032)

Weekly and monthly tabs did not add value; the reports page now offers
hourly (last 6/12/24/48 h, default 24) and daily ranges, with daily as
the default tab. The endpoint keeps week/month for API and CSV compat.

The hour-aware bar tooltips label buckets with localized date + hour in
UTC and the current hour shows the data cutoff time. Filled gap hours
(upPct 0) cannot recover the divisor from upMin/upPct, so bucketMinutes
derives it from the clock: 60 min for a closed hour, elapsed minutes
for the current one. The minimum-coverage rule now uses the window unit
(hours or days) instead of n/24 days: with n/24 the floor of 2 would
dominate and a router with 2 scattered hours in a 48 h window would get
a summary percentage that represents nothing.

i18n es+en: added reports.tabHour, reports.windowHour,
reports.tipCurrentHour and reports.coverageHours; removed the orphaned
reports.tabWeek, reports.tabMonth, reports.windowWeek and
reports.windowMonth; the footnote now says "measurable time" so it
fits both granularities.
Nacho 2 месяцев назад
Родитель
Сommit
de50d470ec

+ 5 - 5
app/public/locales/en/translation.json

@@ -1070,6 +1070,7 @@
   "reports": {
     "availability": "Availability per router",
     "coverage": "{{days}}/{{total}} days with data",
+    "coverageHours": "{{days}}/{{total}} hours with data",
     "downNone": "No gaps",
     "downTime": "{{duration}} with no data",
     "downloadCsv": "Download as CSV",
@@ -1077,7 +1078,7 @@
     "error": "Could not load the report. Check the connection and try again.",
     "explain": "Minutes with data received from each router during {{window}} (5-minute resolution). 100% means no gaps.",
     "fleetAvg": "Fleet average",
-    "footnote": "Availability = minutes with data received (5-minute buckets) over the days with data in the window; the current period is shown as partial. A gap usually means the router was down, but it can also mean the monitor had no data. Green: at least 99%. Amber: at least 95%. Red: below 95%, needs attention.",
+    "footnote": "Availability = minutes with data received (5-minute buckets) over the measurable time in the window; the current period is shown as partial. A gap usually means the router was down, but it can also mean the monitor had no data. Green: at least 99%. Amber: at least 95%. Red: below 95%, needs attention.",
     "insufficient": "Not enough data",
     "loading": "Loading report…",
     "noApi": "Available only with a live backend.",
@@ -1086,13 +1087,12 @@
     "status_ok": "Stable",
     "status_warn": "Minor gaps",
     "tabDay": "Daily",
-    "tabMonth": "Monthly",
-    "tabWeek": "Weekly",
+    "tabHour": "Hourly",
+    "tipCurrentHour": "Current hour, data up to {{time}}",
     "tipToday": "Today, data up to {{time}} (in progress)",
     "totalDown": "Total time without data",
     "windowDay": "the last {{n}} days",
-    "windowMonth": "the last {{n}} months",
-    "windowWeek": "the last {{n}} weeks",
+    "windowHour": "the last {{n}} hours",
     "worstRouter": "Router with most gaps"
   },
   "topology": {

+ 5 - 5
app/public/locales/es/translation.json

@@ -1070,6 +1070,7 @@
   "reports": {
     "availability": "Disponibilidad por router",
     "coverage": "{{days}}/{{total}} días con datos",
+    "coverageHours": "{{days}}/{{total}} horas con datos",
     "downNone": "Sin huecos",
     "downTime": "{{duration}} sin datos",
     "downloadCsv": "Descargar como CSV",
@@ -1077,7 +1078,7 @@
     "error": "No se pudo cargar el informe. Comprueba la conexión e inténtalo de nuevo.",
     "explain": "Minutos con datos recibidos de cada router durante {{window}} (resolución de 5 min). 100% significa sin huecos.",
     "fleetAvg": "Media de la red",
-    "footnote": "Disponibilidad = minutos con datos recibidos (buckets de 5 min) sobre los días con datos de la ventana; el período en curso se muestra parcial. Un hueco suele ser el router caído, pero también puede ser el monitor sin datos. Verde: al menos 99%. Ámbar: al menos 95%. Rojo: menos del 95%, requiere atención.",
+    "footnote": "Disponibilidad = minutos con datos recibidos (buckets de 5 min) sobre el tiempo medible de la ventana; el período en curso se muestra parcial. Un hueco suele ser el router caído, pero también puede ser el monitor sin datos. Verde: al menos 99%. Ámbar: al menos 95%. Rojo: menos del 95%, requiere atención.",
     "insufficient": "Sin datos suficientes",
     "loading": "Cargando informe…",
     "noApi": "Disponible solo con backend en vivo.",
@@ -1086,13 +1087,12 @@
     "status_ok": "Estable",
     "status_warn": "Huecos menores",
     "tabDay": "Diario",
-    "tabMonth": "Mensual",
-    "tabWeek": "Semanal",
+    "tabHour": "Horario",
+    "tipCurrentHour": "Hora en curso, datos hasta las {{time}}",
     "tipToday": "Hoy, datos hasta las {{time}} (en curso)",
     "totalDown": "Tiempo sin datos total",
     "windowDay": "los últimos {{n}} días",
-    "windowMonth": "los últimos {{n}} meses",
-    "windowWeek": "las últimas {{n}} semanas",
+    "windowHour": "las últimas {{n}} horas",
     "worstRouter": "Router con más huecos"
   },
   "topology": {

+ 61 - 67
app/src/pages/Reports.tsx

@@ -15,8 +15,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
 
 interface AvailabilityEntry {
   routerId: string
-  bucket: string // day "2026-08-07" | week "2026-W31" | month "2026-07"
-  days: number
+  bucket: string // hour "2026-10-02T14" | day "2026-08-07" (el server conserva week/month para API/CSV)
+  days: number // en hour: 1 si la hora tiene datos, 0 si es un hueco rellenado (#1032)
   upMin: number
   upPct: number
   latAvg: number | null
@@ -26,16 +26,17 @@ interface AvailabilityEntry {
   ramAvg: number
 }
 
-type Range = 'day' | 'week' | 'month'
+// #1032: la UI solo ofrece granularidad horaria y diaria (la semanal y la
+// mensual no aportaban); el endpoint conserva week/month para API y CSV.
+type Range = 'hour' | 'day'
 
 const N_OPTIONS: Record<Range, number[]> = {
+  hour: [6, 12, 24, 48],
   day: [7, 14, 30, 60],
-  week: [2, 4, 8, 12],
-  month: [3, 6, 12, 24],
 }
-const DEFAULT_N: Record<Range, number> = { day: 30, week: 8, month: 12 }
-const SUFFIX: Record<Range, string> = { day: 'd', week: 'w', month: 'm' }
-const RANGE_TABS: Range[] = ['day', 'week', 'month']
+const DEFAULT_N: Record<Range, number> = { hour: 24, day: 30 }
+const SUFFIX: Record<Range, string> = { hour: 'h', day: 'd' }
+const RANGE_TABS: Range[] = ['hour', 'day']
 
 // ---------------------------------------------------------------------------
 // Umbrales de color (issue #973): el rojo solo marca un problema accionable.
@@ -68,33 +69,43 @@ const STATUS_TEXT: Record<Status, string> = {
 }
 
 /**
- * Minutos medibles de un bucket según la semántica del server (#987): el
- * divisor de upPct son los minutos del bucket en los que se puede afirmar
- * algo (1440 por día con datos; el día en curso solo cuenta los minutos
- * transcurridos, medidos del raw). Como upPct = upMin/divisor, se recupera
- * el divisor sin rehacer aritmética de fechas en el cliente.
+ * Minutos medibles de un bucket según la semántica del server (#987, #1032):
+ * el divisor de upPct son los minutos del bucket en los que se puede afirmar
+ * algo (1440 por día con datos; 60 por hora; el período en curso solo cuenta
+ * los minutos transcurridos). Como upPct = upMin/divisor, se recupera el
+ * divisor sin rehacer aritmética de fechas en el cliente.
+ *
+ * Excepción: un bucket con upPct 0 no permite recuperar el divisor (0/0). En
+ * day no ocurre (solo se emiten días con datos), pero en hour el server
+ * RELLENA las horas sin muestras con upMin 0 (#1032), así que el divisor se
+ * deriva del reloj: 60 min por hora cerrada, los minutos transcurridos en la
+ * hora en curso.
  */
-function bucketMinutes(e: AvailabilityEntry): number {
+function bucketMinutes(e: AvailabilityEntry, range: Range): number {
   if (e.upPct > 0) return e.upMin / (e.upPct / 100)
+  if (range === 'hour') {
+    const start = Date.parse(`${e.bucket}:00:00Z`)
+    if (!Number.isFinite(start)) return 0
+    const elapsedMin = (Date.now() - start) / 60000
+    return Math.min(60, Math.max(0, elapsedMin))
+  }
   return e.days * 1440
 }
 
 /** Minutos sin datos de un bucket = duración medible - minutos con datos. */
-function bucketDownMin(e: AvailabilityEntry): number {
-  return Math.max(0, bucketMinutes(e) - e.upMin)
-}
-
-/** Días que cubre la ventana seleccionada (mes = media de 30,44 días). */
-function expectedDays(range: Range, n: number): number {
-  if (range === 'day') return n
-  if (range === 'week') return n * 7
-  return Math.round(n * 30.44)
+function bucketDownMin(e: AvailabilityEntry, range: Range): number {
+  return Math.max(0, bucketMinutes(e, range) - e.upMin)
 }
 
 /**
  * Cobertura mínima para resumir la ventana con un número (#987): con menos
- * de la mitad de los días con datos, un % o un tiempo sin datos no representa
- * la ventana y la UI dice "sin datos suficientes" en vez de inventar cifras.
+ * de la mitad de las unidades de la ventana (horas o días, según la pestaña)
+ * con datos, un % o un tiempo sin datos no representa la ventana y la UI
+ * dice "sin datos suficientes" en vez de inventar cifras. El suelo de 2
+ * unidades evita resumir una ventana con un único bucket aislado. En hour la
+ * unidad es la hora (no n/24 días): con n/24 el suelo de 2 dominaría y un
+ * router con 2 horas sueltas en una ventana de 48 h recibiría un % que no
+ * representa nada (#1032).
  */
 const MIN_COVERAGE = 0.5
 
@@ -115,26 +126,11 @@ interface RouterSummary {
   pct: number
   downMin: number
   status: Status
-  days: number // días con datos en la ventana
+  days: number // unidades (horas o días) con datos en la ventana
   sufficient: boolean // cobertura suficiente para resumir la ventana (#987)
   buckets: AvailabilityEntry[] // ordenados de más antiguo a más reciente
 }
 
-/** Lunes y domingo (UTC) de una semana ISO "2026-W31", para el tooltip de la barra (#993). */
-function isoWeekSpan(bucket: string): [Date, Date] | null {
-  const m = /^(\d{4})-W(\d{2})$/.exec(bucket)
-  if (!m) return null
-  const year = Number(m[1])
-  const week = Number(m[2])
-  const jan4 = new Date(Date.UTC(year, 0, 4))
-  const dow = jan4.getUTCDay() || 7 // lunes = 1
-  const monday = new Date(jan4)
-  monday.setUTCDate(jan4.getUTCDate() - dow + 1 + (week - 1) * 7)
-  const sunday = new Date(monday)
-  sunday.setUTCDate(monday.getUTCDate() + 6)
-  return [monday, sunday]
-}
-
 /** Página `/reports` - Informe de disponibilidad (reports.md, rediseño #973). */
 export default function Reports() {
   const { t, i18n } = useTranslation()
@@ -146,13 +142,13 @@ export default function Reports() {
     const n = routerName(id)
     return n !== id ? `${n} (${id})` : id
   }
-  const [range, setRange] = useState<Range>('week')
-  const [n, setN] = useState<number>(DEFAULT_N.week)
+  const [range, setRange] = useState<Range>('day')
+  const [n, setN] = useState<number>(DEFAULT_N.day)
   const [items, setItems] = useState<AvailabilityEntry[]>([])
-  // #1029: rango de los items cargados. Al cambiar de pestaña (p.ej. week ->
-  // day) el render inmediato aún ve los items VIEJOS con el rango NUEVO, y
-  // bucketLabel formateaba buckets semanales ("2026-W40") como si fueran
-  // días o meses: Invalid Date -> RangeError -> pantalla en blanco.
+  // #1029: rango de los items cargados. Al cambiar de pestaña (p.ej. day ->
+  // hour) el render inmediato aún ve los items VIEJOS con el rango NUEVO, y
+  // bucketLabel formateaba buckets diarios ("2026-10-02") como si fueran
+  // horas: Invalid Date -> RangeError -> pantalla en blanco.
   const [itemsRange, setItemsRange] = useState<Range | null>(null)
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState(false)
@@ -237,7 +233,7 @@ export default function Reports() {
     .sort()
     .map((id) => {
       const rows = viewItems.filter((i) => i.routerId === id)
-      const totalMin = rows.reduce((a, r) => a + bucketMinutes(r), 0)
+      const totalMin = rows.reduce((a, r) => a + bucketMinutes(r, range), 0)
       const upMin = rows.reduce((a, r) => a + r.upMin, 0)
       const days = rows.reduce((a, r) => a + r.days, 0)
       const pct = totalMin > 0 ? Math.min(100, (upMin / totalMin) * 100) : 100
@@ -247,7 +243,7 @@ export default function Reports() {
         downMin: Math.max(0, totalMin - upMin),
         status: statusOf(pct),
         days,
-        sufficient: days >= Math.max(2, expectedDays(range, n) * MIN_COVERAGE),
+        sufficient: days >= Math.max(2, n * MIN_COVERAGE),
         buckets: [...rows].sort((a, b) => a.bucket.localeCompare(b.bucket)),
       }
     })
@@ -259,16 +255,18 @@ export default function Reports() {
   const worst = rated.length ? rated.reduce((a, r) => (r.pct < a.pct ? r : a)) : null
   const totalDown = rated.reduce((a, r) => a + r.downMin, 0)
 
-  const windowText = t(range === 'day' ? 'reports.windowDay' : range === 'week' ? 'reports.windowWeek' : 'reports.windowMonth', { n })
+  const windowText = t(range === 'hour' ? 'reports.windowHour' : 'reports.windowDay', { n })
 
   // -- Barra de disponibilidad estilo Uptime Kuma (#993) -------------------
-  // Un segmento por bucket (día/semana/mes según la pestaña, la granularidad
-  // real del endpoint). El tooltip muestra la fecha del segmento; el día en
-  // curso, único bucket con hora real, muestra además la hora de corte.
-  const dayFmt = new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', timeZone: 'UTC' })
+  // Un segmento por bucket (hora o día según la pestaña, la granularidad
+  // real del endpoint). El tooltip muestra la fecha del segmento; el período
+  // en curso, único bucket con hora real, muestra además la hora de corte.
+  // Todo en UTC (timeZone explícito) para que las etiquetas coincidan con
+  // los buckets del server, que son UTC.
   const dayYearFmt = new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })
-  const monthFmt = new Intl.DateTimeFormat(i18n.language, { month: 'long', year: 'numeric', timeZone: 'UTC' })
+  const hourFmt = new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'UTC' })
   const todayKey = new Date().toISOString().slice(0, 10)
+  const currentHourKey = new Date().toISOString().slice(0, 13) // "2026-10-02T14"
   const nowTime = new Date().toLocaleTimeString(i18n.language, { hour: '2-digit', minute: '2-digit' })
 
   /** Formatea solo fechas finitas: un bucket inesperado cae al texto crudo
@@ -277,16 +275,12 @@ export default function Reports() {
     Number.isFinite(d.getTime()) ? fmt.format(d) : fallback
 
   function bucketLabel(b: AvailabilityEntry): string {
-    if (range === 'day') {
-      if (b.bucket === todayKey) return t('reports.tipToday', { time: nowTime })
-      return fmtDate(new Date(`${b.bucket}T00:00:00Z`), dayYearFmt, b.bucket)
-    }
-    if (range === 'week') {
-      const span = isoWeekSpan(b.bucket)
-      if (!span) return b.bucket
-      return `${fmtDate(span[0], dayFmt, b.bucket)} - ${fmtDate(span[1], dayYearFmt, b.bucket)}`
+    if (range === 'hour') {
+      if (b.bucket === currentHourKey) return t('reports.tipCurrentHour', { time: nowTime })
+      return fmtDate(new Date(`${b.bucket}:00:00Z`), hourFmt, b.bucket)
     }
-    return fmtDate(new Date(`${b.bucket}-01T00:00:00Z`), monthFmt, b.bucket)
+    if (b.bucket === todayKey) return t('reports.tipToday', { time: nowTime })
+    return fmtDate(new Date(`${b.bucket}T00:00:00Z`), dayYearFmt, b.bucket)
   }
 
   const initial = reduce ? false : { opacity: 0, y: 12 }
@@ -379,7 +373,7 @@ export default function Reports() {
               range === r ? 'bg-accent/15 text-accent' : 'text-text-muted hover:text-text-secondary',
             )}
           >
-            {r === 'day' ? t('reports.tabDay') : r === 'week' ? t('reports.tabWeek') : t('reports.tabMonth')}
+            {r === 'hour' ? t('reports.tabHour') : t('reports.tabDay')}
           </button>
         ))}
       </div>
@@ -480,7 +474,7 @@ export default function Reports() {
                       sin datos. Atenuada si la cobertura es insuficiente (#987) */}
                   <div className={cn('flex min-w-24 flex-1 items-center gap-0.5', !r.sufficient && 'opacity-60')}>
                     {r.buckets.map((b) => {
-                      const down = bucketDownMin(b)
+                      const down = bucketDownMin(b, range)
                       const st = statusOf(b.upPct)
                       const label = bucketLabel(b)
                       const pctText = b.upPct >= 99.9 ? '100%' : `${b.upPct.toFixed(1)}%`
@@ -523,7 +517,7 @@ export default function Reports() {
                       </>
                     ) : (
                       <p className="text-caption text-text-muted">
-                        {t('reports.coverage', { days: r.days, total: expectedDays(range, n) })}
+                        {t(range === 'hour' ? 'reports.coverageHours' : 'reports.coverage', { days: r.days, total: n })}
                       </p>
                     )}
                   </div>

+ 154 - 1
server-go/internal/httpapi/availability_test.go

@@ -232,7 +232,7 @@ func TestAvailabilityAgenteOnlineNoInventaDowntime(t *testing.T) {
 // TestAvailabilityValidaParametros: range inválido y n fuera de rango → 400.
 func TestAvailabilityValidaParametros(t *testing.T) {
 	ts := makeTestServer(t)
-	for _, q := range []string{"?range=bogus", "?range=day&n=0", "?range=day&n=999", "?range=month&n=abc", "?range=week&n=-1"} {
+	for _, q := range []string{"?range=bogus", "?range=day&n=0", "?range=day&n=999", "?range=month&n=abc", "?range=week&n=-1", "?range=hour&n=0", "?range=hour&n=49"} {
 		status, _ := getAvailability(t, ts, q)
 		if status != http.StatusBadRequest {
 			t.Fatalf("query %q → status %d, esperaba 400", q, status)
@@ -243,4 +243,157 @@ func TestAvailabilityValidaParametros(t *testing.T) {
 	if status != http.StatusOK {
 		t.Fatalf("range=day sin n → status %d, esperaba 200", status)
 	}
+	if status, _ := getAvailability(t, ts, "?range=hour"); status != http.StatusOK {
+		t.Fatalf("range=hour sin n → status %d, esperaba 200", status)
+	}
+}
+
+// ---------------------------------------------------------------------------
+// range=hour (#1032): disponibilidad por hora desde el raw (metrics), con
+// relleno de horas sin datos dentro de la ventana.
+// ---------------------------------------------------------------------------
+
+// insertRawAt siembra una muestra raw del router r en el instante tsMs
+// (epoch ms). El rango hour se mide del raw: metrics_daily no tiene
+// granularidad horaria.
+func insertRawAt(t *testing.T, ts *testServer, routerID string, tsMs int64) {
+	t.Helper()
+	_, err := ts.db.Exec(
+		"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES (?,?,?,?,?,?,?,?)",
+		routerID, tsMs, 20, 60, 40, 1.5, 1e6, 5e5)
+	if err != nil {
+		t.Fatalf("insert raw %s@%d: %v", routerID, tsMs, err)
+	}
+}
+
+// fillHour siembra nBuckets muestras (una al inicio de cada bucket de 5 min)
+// a partir del inicio de la hora hourStart. 12 = hora completa con datos.
+func fillHour(t *testing.T, ts *testServer, routerID string, hourStart time.Time, nBuckets int) {
+	t.Helper()
+	for i := 0; i < nBuckets; i++ {
+		insertRawAt(t, ts, routerID, hourStart.Add(time.Duration(i)*5*time.Minute).UnixMilli())
+	}
+}
+
+// skipNearHourFlip evita flakiness cuando el reloj está a punto de cambiar de
+// hora: los tests siembran relativo a now.Truncate(hour) y el handler
+// recalcula "ahora" al servir; un cambio de hora entre ambos movería las
+// etiquetas esperadas (mismo criterio que el skip de medianoche en
+// TestAvailabilityDayActualNoPenaliza).
+func skipNearHourFlip(t *testing.T) {
+	t.Helper()
+	if m := time.Now().UTC().Minute(); m == 0 || m >= 58 {
+		t.Skipf("minuto %d: demasiado cerca del cambio de hora para aserciones estables", m)
+	}
+}
+
+// TestAvailabilityHourAgrupaPorHoraYRellenaHuecos: una fila por router y
+// hora de la ventana (incluida la en curso); las horas sin muestras se
+// emiten con upMin/days/upPct 0 (#1032).
+func TestAvailabilityHourAgrupaPorHoraYRellenaHuecos(t *testing.T) {
+	ts := makeTestServer(t)
+	skipNearHourFlip(t)
+	hourStart := time.Now().UTC().Truncate(time.Hour)
+
+	// gw: hora completa hace 3 h (12 buckets = 60 min), media hora hace 1 h
+	// (6 buckets = 30 min). La hora de hace 2 h queda vacía → hueco rellenado.
+	full := hourStart.Add(-3 * time.Hour)
+	half := hourStart.Add(-1 * time.Hour)
+	fillHour(t, ts, "gw", full, 12)
+	fillHour(t, ts, "gw", half, 6)
+
+	status, items := getAvailability(t, ts, "?range=hour&n=6")
+	if status != http.StatusOK {
+		t.Fatalf("status %d, esperaba 200", status)
+	}
+	// 6 horas de ventana (hace 5 h .. hora en curso), todas emitidas.
+	if len(items) != 6 {
+		t.Fatalf("items = %d, esperaba 6 (ventana rellenada): %+v", len(items), items)
+	}
+	byBucket := map[string]availabilityEntry{}
+	for _, it := range items {
+		if it.RouterID != "gw" {
+			t.Fatalf("router inesperado %q: %+v", it.RouterID, it)
+		}
+		byBucket[it.Bucket] = it
+	}
+	fullKey := full.Format("2006-01-02T15")
+	halfKey := half.Format("2006-01-02T15")
+	gapKey := hourStart.Add(-2 * time.Hour).Format("2006-01-02T15")
+
+	f := byBucket[fullKey]
+	if f.Days != 1 || f.UpMin != 60 || f.UpPct < 99.9 {
+		t.Fatalf("hora completa: days=%d upMin=%d upPct=%v, esperaba 1/60/~100", f.Days, f.UpMin, f.UpPct)
+	}
+	h := byBucket[halfKey]
+	if h.Days != 1 || h.UpMin != 30 || h.UpPct < 49.9 || h.UpPct > 50.1 {
+		t.Fatalf("media hora: days=%d upMin=%d upPct=%v, esperaba 1/30/~50", h.Days, h.UpMin, h.UpPct)
+	}
+	g := byBucket[gapKey]
+	if g.Days != 0 || g.UpMin != 0 || g.UpPct != 0 {
+		t.Fatalf("hueco rellenado: days=%d upMin=%d upPct=%v, esperaba 0/0/0", g.Days, g.UpMin, g.UpPct)
+	}
+	// Orden: bucket DESC → la hora en curso primero.
+	if items[0].Bucket != hourStart.Format("2006-01-02T15") {
+		t.Fatalf("items[0].bucket = %q, esperaba la hora en curso %s", items[0].Bucket, hourStart.Format("2006-01-02T15"))
+	}
+}
+
+// TestAvailabilityHourActualNoPenaliza: la hora en curso se normaliza por
+// los minutos transcurridos, no por 60 (mismo criterio que el día en curso,
+// #987). Un router online desde el inicio de la hora da ~100%.
+func TestAvailabilityHourActualNoPenaliza(t *testing.T) {
+	ts := makeTestServer(t)
+	skipNearHourFlip(t)
+	now := time.Now().UTC()
+	hourStart := now.Truncate(time.Hour)
+	nowMin := now.Minute()
+
+	// Cobertura continua desde el inicio de la hora: una muestra al inicio
+	// de cada bucket de 5 min transcurrido.
+	fillHour(t, ts, "gw", hourStart, nowMin/5+1)
+
+	_, items := getAvailability(t, ts, "?range=hour&n=6")
+	var cur *availabilityEntry
+	for i := range items {
+		if items[i].Bucket == hourStart.Format("2006-01-02T15") {
+			cur = &items[i]
+		}
+	}
+	if cur == nil {
+		t.Fatalf("no se devolvió fila para la hora en curso: %+v", items)
+	}
+	// upMin se tope a los minutos transcurridos (el bucket actual parcial
+	// cuenta entero) y upPct = 100. Margen de ±1 min por si el reloj cruza
+	// un minuto entre test y handler.
+	if cur.UpMin < int64(nowMin)-1 || cur.UpMin > int64(nowMin)+1 {
+		t.Fatalf("hora en curso upMin=%d, esperaba ~%d (minutos transcurridos)", cur.UpMin, nowMin)
+	}
+	if cur.UpPct < 99.9 || cur.UpPct > 100.1 {
+		t.Fatalf("hora en curso upPct=%v, esperaba ~100 (router online)", cur.UpPct)
+	}
+}
+
+// TestAvailabilityHourRouterSinMuestrasNoAparece: un router sin ninguna
+// muestra en TODA la ventana no aparece (igual que en los demás rangos); el
+// relleno de huecos solo aplica a routers presentes en la ventana.
+func TestAvailabilityHourRouterSinMuestrasNoAparece(t *testing.T) {
+	ts := makeTestServer(t)
+	skipNearHourFlip(t)
+	hourStart := time.Now().UTC().Truncate(time.Hour)
+
+	// old: muestras de hace 3 días (dentro de la retención raw de 7 días,
+	// fuera de la ventana de 6 h). gw: activo ahora.
+	fillHour(t, ts, "old", hourStart.Add(-72*time.Hour), 12)
+	fillHour(t, ts, "gw", hourStart.Add(-1*time.Hour), 12)
+
+	_, items := getAvailability(t, ts, "?range=hour&n=6")
+	if len(items) != 6 {
+		t.Fatalf("items = %d, esperaba 6 (solo gw, ventana rellenada): %+v", len(items), items)
+	}
+	for _, it := range items {
+		if it.RouterID != "gw" {
+			t.Fatalf("router fuera de ventana %q no debería aparecer: %+v", it.RouterID, it)
+		}
+	}
 }

+ 155 - 8
server-go/internal/httpapi/reports.go

@@ -218,17 +218,20 @@ func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
 }
 
 // ---------------------------------------------------------------------------
-// GET /api/reports/availability?range=day|week|month&n=N — Fase 15.1
+// GET /api/reports/availability?range=hour|day|week|month&n=N - Fase 15.1
 //
-// Disponibilidad por router agregada por día, semana ISO o mes, sobre los
-// últimos N buckets (day: 30, week: 8, month: 12 por defecto). Reutiliza la
-// semántica de buckets del weekly (ver cabecera del fichero, #987).
+// Disponibilidad por router agregada por hora, día, semana ISO o mes, sobre
+// los últimos N buckets (hour: 24, day: 30, week: 8, month: 12 por defecto).
+// Reutiliza la semántica de buckets del weekly (ver cabecera del fichero,
+// #987). El rango hour (#1032) no puede salir de metrics_daily (granularidad
+// día): se calcula del raw y tiene su propia semántica de huecos (ver
+// availabilityHour).
 // ---------------------------------------------------------------------------
 
 type availabilityEntry struct {
 	RouterID string   `json:"routerId"`
-	Bucket   string   `json:"bucket"` // day "2026-08-07" | week "2026-W31" | month "2026-07"
-	Days     int      `json:"days"`   // días con datos en el bucket
+	Bucket   string   `json:"bucket"` // hour "2026-10-02T14" | day "2026-08-07" | week "2026-W31" | month "2026-07"
+	Days     int      `json:"days"`   // unidades con datos en el bucket (en hour: 1 si la hora tiene datos, 0 si es hueco rellenado)
 	UpMin    int64    `json:"upMin"`  // minutos con datos en el bucket (buckets de 5 min * 5)
 	UpPct    float64  `json:"upPct"`  // % de cobertura sobre los minutos medibles
 	LatAvg   *float64 `json:"latAvg"`
@@ -250,6 +253,8 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 	var groupExpr string
 	nDef, nMax := 8, 52
 	switch rangeParam {
+	case "hour":
+		nDef, nMax = 24, 48
 	case "day":
 		groupExpr = "strftime('%Y-%m-%d', date)"
 		nDef, nMax = 30, 90
@@ -260,7 +265,7 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 		groupExpr = "strftime('%Y-%m', date)"
 		nDef, nMax = 12, 24
 	default:
-		writeError(w, http.StatusBadRequest, "invalid_query", "range must be day, week or month")
+		writeError(w, http.StatusBadRequest, "invalid_query", "range must be hour, day, week or month")
 		return
 	}
 
@@ -275,6 +280,17 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 		n = v
 	}
 
+	// El rango hour (#1032) se calcula del raw, no del daily: camino propio.
+	if rangeParam == "hour" {
+		out, err := s.availabilityHour(n)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "db_error")
+			return
+		}
+		writeAvailability(w, q.Get("format") == "csv", rangeParam, n, out)
+		return
+	}
+
 	// Ventana hacia atrás desde hoy (UTC).
 	now := time.Now().UTC()
 	var since string
@@ -394,7 +410,13 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 		return out[i].RouterID < out[j].RouterID
 	})
 
-	if q.Get("format") == "csv" {
+	writeAvailability(w, q.Get("format") == "csv", rangeParam, n, out)
+}
+
+// writeAvailability emite el informe de disponibilidad en JSON o CSV. El
+// formato de etiqueta del bucket depende del rango (ver availabilityEntry).
+func writeAvailability(w http.ResponseWriter, csvWanted bool, rangeParam string, n int, out []availabilityEntry) {
+	if csvWanted {
 		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
 		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=netpulse-availability-%s.csv", rangeParam))
 		cw := csv.NewWriter(w)
@@ -416,3 +438,128 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 	}
 	writeJSON(w, http.StatusOK, map[string]any{"items": out, "range": rangeParam, "n": n})
 }
+
+// hourMS es el tamaño del bucket horario en ms (range=hour, #1032).
+const hourMS = 60 * 60 * 1000
+
+// availabilityHour calcula range=hour: disponibilidad por router y hora
+// sobre las últimas n horas, incluida la en curso. La fuente es el raw
+// (tabla metrics, retención 7 días, de sobra para el máximo de 48 h) porque
+// metrics_daily no tiene granularidad horaria. La etiqueta del bucket es la
+// hora UTC en formato ISO recortado: "2006-01-02T15" (p.ej. "2026-10-02T14").
+//
+// Diferencia de semántica con day/week/month (#1032): las horas SIN muestras
+// dentro de la ventana se EMITEN con upMin 0, days 0 y upPct 0 (bucket
+// rellenado), porque a escala horaria el hueco reciente es justo lo que
+// interesa ver; un día sin datos, en cambio, no se emite (puede ser un
+// router aún no monitorizado). Solo se rellenan horas de routers con al
+// menos una muestra en la ventana: un router sin ninguna muestra en toda la
+// ventana no aparece, igual que en los demás rangos.
+//
+// Divisor de upPct: 60 min por hora cerrada; la hora en curso solo cuenta
+// los minutos transcurridos (mismo criterio que el día en curso, #987), con
+// upMin tope al divisor y upPct clavado a 100. latAvg/cpuAvg/ramAvg son
+// medias de las muestras raw de la hora; rxTotal/txTotal se emiten a 0: el
+// raw guarda tasas (bps), no totales, y agregarlas inventaría un dato.
+func (s *server) availabilityHour(n int) ([]availabilityEntry, error) {
+	now := time.Now().UTC()
+	hourStart := now.Truncate(time.Hour)
+	sinceMS := hourStart.Add(-time.Duration(n-1) * time.Hour).UnixMilli()
+
+	rows, err := s.db.Query(`
+		SELECT
+			router_id,
+			ts / ?,
+			COUNT(DISTINCT ts / ?),
+			AVG(latency_ms),
+			AVG(cpu),
+			AVG(ram)
+		FROM metrics
+		WHERE ts >= ?
+		GROUP BY router_id, ts / ?`, hourMS, db.BucketMS, sinceMS, hourMS)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+
+	type hourData struct {
+		buckets int64
+		lat     *float64
+		cpu     float64
+		ram     float64
+	}
+	byRouter := map[string]map[int64]hourData{}
+	for rows.Next() {
+		var rid string
+		var hourEpoch, buckets int64
+		var lat, cpu, ram sql.NullFloat64
+		if err := rows.Scan(&rid, &hourEpoch, &buckets, &lat, &cpu, &ram); err != nil {
+			continue
+		}
+		m := byRouter[rid]
+		if m == nil {
+			m = map[int64]hourData{}
+			byRouter[rid] = m
+		}
+		d := hourData{buckets: buckets}
+		if lat.Valid {
+			d.lat = &lat.Float64
+		}
+		if cpu.Valid {
+			d.cpu = cpu.Float64
+		}
+		if ram.Valid {
+			d.ram = ram.Float64
+		}
+		m[hourEpoch] = d
+	}
+	if err := rows.Err(); err != nil {
+		return nil, err
+	}
+
+	out := []availabilityEntry{}
+	currentHourEpoch := hourStart.UnixMilli() / hourMS
+	for rid, hours := range byRouter {
+		for i := 0; i < n; i++ {
+			hStart := hourStart.Add(-time.Duration(i) * time.Hour)
+			epoch := hStart.UnixMilli() / hourMS
+			e := availabilityEntry{
+				RouterID: rid,
+				Bucket:   hStart.Format("2006-01-02T15"),
+			}
+			// Divisor: 60 min por hora cerrada; la hora en curso solo los
+			// minutos transcurridos (now.Minute(), reloj UTC).
+			divisor := float64(60)
+			if epoch == currentHourEpoch {
+				divisor = float64(now.Minute())
+			}
+			if d, ok := hours[epoch]; ok {
+				e.Days = 1
+				e.UpMin = d.buckets * minPerBucket
+				e.LatAvg = d.lat
+				e.CPUAvg = d.cpu
+				e.RAMAvg = d.ram
+			}
+			if divisor <= 0 {
+				// Hora en curso en el minuto 0: aún no hay nada medible.
+				e.UpMin = 0
+			} else {
+				if float64(e.UpMin) > divisor {
+					e.UpMin = int64(divisor)
+				}
+				e.UpPct = float64(e.UpMin) / divisor * 100
+				if e.UpPct > 100 {
+					e.UpPct = 100
+				}
+			}
+			out = append(out, e)
+		}
+	}
+	sort.Slice(out, func(i, j int) bool {
+		if out[i].Bucket != out[j].Bucket {
+			return out[i].Bucket > out[j].Bucket
+		}
+		return out[i].RouterID < out[j].RouterID
+	})
+	return out, nil
+}