From 9af0de60d1041c709077820a4021697d1e6aa44d Mon Sep 17 00:00:00 2001 From: Ricardo Monla Date: Mon, 5 Oct 2026 03:35:53 -0300 Subject: [PATCH] =?UTF-8?q?feat(nexxa-web):=20dashboard=20con=20estados=20?= =?UTF-8?q?AHORA=20y=20=C3=BAltimas=2024=20h,=20Registro=20filtrable=20y?= =?UTF-8?q?=20estado=20en=20palabras=20desde=20el=20servidor=20(P337/F2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Co-Authored-By: GEMMA --- servicios/nexxa/test/lib_servidor_prueba.rb | 2 +- .../test/ui/04_dashboard_y_registro.json | 64 ++++ servicios/nexxa/web/css/estilos.css | 25 +- servicios/nexxa/web/index.html | 41 ++- servicios/nexxa/web/js/app.js | 300 ++++++++++-------- 5 files changed, 291 insertions(+), 141 deletions(-) create mode 100644 servicios/nexxa/test/ui/04_dashboard_y_registro.json diff --git a/servicios/nexxa/test/lib_servidor_prueba.rb b/servicios/nexxa/test/lib_servidor_prueba.rb index 4778f2a1..8af8847b 100644 --- a/servicios/nexxa/test/lib_servidor_prueba.rb +++ b/servicios/nexxa/test/lib_servidor_prueba.rb @@ -28,7 +28,7 @@ module ServidorPrueba %w[lib_cripto lib_registro lib_tokens lib_auth lib_pools].each { |f| require File.join(org, f) } Nexxa::MasterKey.generar_si_falta! KEYS.each do |p, i| - Nexxa::Registro.registrar(provider: p, identificador: i, cuenta_origen: 'prueba', reset_segundos: 86_400, valor: "falso-#{i}") + Nexxa::Registro.registrar(provider: p, identificador: i, cuenta_origen: 'prueba', reset_segundos: 86_400, valor: "falso-#{i}", por: 'prueba') end USUARIOS.each { |u, (pw, perfil)| Nexxa::Auth.crear_usuario(usuario: u, password: pw, perfil: perfil) } tokens = individuos.to_h { |ind| [ind, Nexxa::Tokens.generar(ind)] } diff --git a/servicios/nexxa/test/ui/04_dashboard_y_registro.json b/servicios/nexxa/test/ui/04_dashboard_y_registro.json new file mode 100644 index 00000000..6f606e44 --- /dev/null +++ b/servicios/nexxa/test/ui/04_dashboard_y_registro.json @@ -0,0 +1,64 @@ +{ + "nombre": "Dashboard con estados AHORA y últimas 24 h, Por key y Registro filtrable (P337/Fase 2), solo lectura", + "produccion": true, + "acciones": [ + { + "tipo": "click", + "selector": "button[data-section=dashboard]" + }, + { + "tipo": "esperar", + "segundos": 2 + }, + { + "tipo": "js", + "retorna": true, + "espera": "^6 estados con [1-9]\\d* keys; 4 contadores 24 h$", + "codigo": "var s=document.querySelectorAll('#stats-ahora .stat'); var n=0; s.forEach(function(x){n+=parseInt(x.querySelector('.stat-value').textContent,10)}); return s.length+' estados con '+n+' keys; '+document.querySelectorAll('#stats-24h .stat').length+' contadores 24 h'" + }, + { + "tipo": "js", + "retorna": true, + "espera": "^por key [1-9]\\d*$", + "codigo": "return 'por key '+document.querySelectorAll('#por-key tbody tr').length" + }, + { + "tipo": "captura", + "destino": "/home/rmonla/Documentos/GitHub/dtic-GEMMA/_temp/p337/ui_dashboard.png" + }, + { + "tipo": "click", + "selector": "[data-ir-registro]" + }, + { + "tipo": "esperar", + "segundos": 2 + }, + { + "tipo": "js", + "retorna": true, + "espera": "^Registro: [1-9]\\d* fila\\(s\\)$", + "codigo": "return document.getElementById('page-title').textContent+': '+document.querySelectorAll('#registro-lista tbody tr').length+' fila(s)'" + }, + { + "tipo": "captura", + "destino": "/home/rmonla/Documentos/GitHub/dtic-GEMMA/_temp/p337/ui_registro.png" + }, + { + "tipo": "js", + "retorna": true, + "espera": "^filtro [a-z-]+$", + "codigo": "var t=document.querySelector('#registro-lista tbody tr td:nth-child(3)').textContent; var sel=document.getElementById('reg-evento'); var o=Array.prototype.find.call(sel.options,function(x){return x.text===t}); sel.value=o.value; sel.dispatchEvent(new Event('change')); return 'filtro '+o.value" + }, + { + "tipo": "esperar", + "segundos": 2 + }, + { + "tipo": "js", + "retorna": true, + "espera": "^filtrado [1-9]\\d* todas iguales$", + "codigo": "var c=Array.prototype.map.call(document.querySelectorAll('#registro-lista tbody tr td:nth-child(3)'),function(x){return x.textContent}); return 'filtrado '+c.length+(c.every(function(x){return x===c[0]})?' todas iguales':' mezcladas')" + } + ] +} \ No newline at end of file diff --git a/servicios/nexxa/web/css/estilos.css b/servicios/nexxa/web/css/estilos.css index 8117fb4b..37b9c5d4 100644 --- a/servicios/nexxa/web/css/estilos.css +++ b/servicios/nexxa/web/css/estilos.css @@ -361,7 +361,7 @@ } .panel-tall #actividad-lista, - .panel-tall #reportes-individuo { + .panel-tall #por-key { overflow-y: auto; flex: 1; } @@ -785,6 +785,9 @@ .pill.info { background: var(--accent-soft); color: var(--accent); } .pill.info .dot { background: var(--accent); } + /* P337/Fase 2: en pausa (límite del proveedor, vuelve en minutos) se distingue de agotada (cuota) */ + .pill.pause { background: var(--warn-soft); color: var(--text); border: 1px dashed var(--warn); } + .pill.pause .dot { background: var(--warn); opacity: 0.6; } .timing { font-size: 12.5px; @@ -1059,3 +1062,23 @@ @media (max-width: 640px) { #add-key-form > .inline-add-row:first-child { grid-template-columns: 1fr 1fr; } } + +/* P337/Fase 2: registro y dashboard concretos */ +.stats-titulo { font-weight: 600; margin: 4px 0 6px; } +.stats-titulo .stats-sub { font-weight: 400; color: var(--text-faint); font-size: 0.85em; margin-left: 6px; } +.tabla-registro { width: 100%; border-collapse: collapse; font-size: 0.9em; } +.tabla-registro th { text-align: left; color: var(--text-faint); font-weight: 500; padding: 6px 8px; border-bottom: 1px solid var(--border-soft); } +.tabla-registro td { padding: 6px 8px; border-bottom: 1px solid var(--border-soft); vertical-align: top; } +.tabla-registro .nowrap { white-space: nowrap; } +.registro-filtros { display: flex; flex-wrap: wrap; gap: 12px; align-items: end; margin-bottom: 12px; } +.registro-filtros label { display: flex; flex-direction: column; gap: 4px; font-size: 0.85em; color: var(--text-faint); } +.registro-cuenta { margin-left: auto; color: var(--text-faint); } +.panel-link { float: right; font-size: 0.85em; font-weight: 400; } +#section-registro { overflow-x: auto; } +/* Las tablas del dashboard ocupan el ancho completo (en un panel angosto se desbordaban) y las 6 cajas de estado + entran en una fila en pantallas comunes */ +.dash-panels .panel-tall { grid-column: 1 / -1; } +.panel-tall #actividad-lista, .panel-tall #por-key { overflow-x: auto; } +#stats-ahora { grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); } +#stats-ahora .stat-label .pill { font-size: 10.5px; } + diff --git a/servicios/nexxa/web/index.html b/servicios/nexxa/web/index.html index 9458d2ae..b8cdec05 100644 --- a/servicios/nexxa/web/index.html +++ b/servicios/nexxa/web/index.html @@ -21,6 +21,7 @@ + @@ -36,6 +37,11 @@
+ +
Ahora estado de cada key
+
+
Últimas 24 h qué pasó con las keys
+
Keys registradas
@@ -45,14 +51,6 @@
Providers
—
-
-
Agotadas ahora
-
—
-
-
-
Reservadas ahora
-
—
-
Consumidores
—
@@ -70,17 +68,17 @@
-
Dispensas por día (últimos 7 días)
+
Entregas por día (últimos 7 días)
-
Reportes por individuo
-
+
Por key (últimas 24 h)
+
-
Actividad reciente
+
Últimos eventos ver registro completo →
@@ -159,6 +157,25 @@
+ +
+
+ + + + + +
+
+
+
🧩 diff --git a/servicios/nexxa/web/js/app.js b/servicios/nexxa/web/js/app.js index 623bb422..f95531fa 100644 --- a/servicios/nexxa/web/js/app.js +++ b/servicios/nexxa/web/js/app.js @@ -36,7 +36,7 @@ var sidebarToggle = document.getElementById("sidebar-toggle"); var navItems = document.querySelectorAll(".nav-item"); var pageTitle = document.getElementById("page-title"); - var sectionTitles = { dashboard: "Dashboard", apis: "APIs", nodos: "Individuos", pools: "Pools", usuarios: "Usuarios" }; + var sectionTitles = { dashboard: "Dashboard", apis: "APIs", nodos: "Individuos", pools: "Pools", registro: "Registro", usuarios: "Usuarios" }; function selectSection(which) { navItems.forEach(function (item) { @@ -51,6 +51,7 @@ document.getElementById("section-apis").classList.toggle("active", which === "apis"); document.getElementById("section-nodos").classList.toggle("active", which === "nodos"); document.getElementById("section-pools").classList.toggle("active", which === "pools"); + document.getElementById("section-registro").classList.toggle("active", which === "registro"); document.getElementById("section-usuarios").classList.toggle("active", which === "usuarios"); pageTitle.textContent = sectionTitles[which]; @@ -60,6 +61,8 @@ cargarCheckins().then(cargarConsumidores); } else if (which === "pools") { cargarPools(); + } else if (which === "registro") { + cargarRegistro(); } else if (which === "usuarios") { usuariosErrorBanner.classList.remove('visible'); cargarUsuarios(); @@ -105,6 +108,8 @@ setInterval(cargarConsumidores, 30000); // resumen de pools y 'Mentes sin keys' al día (P335/Fase 12) cargarUsos(); setInterval(cargarUsos, 30000); + cargarResumen(); + setInterval(cargarResumen, 30000); cargarVersion(); }); @@ -156,6 +161,60 @@ return d.toLocaleString("es-AR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }); } + // P337/Fase 2: el ESTADO viene del servidor (taxonomía única, Registro.estado_de); acá solo se muestra en palabras, + // con hora absoluta y relativa. Nunca se recalcula en el navegador. + var ESTADO_UI = { + disponible: { clase: 'ok', texto: 'disponible' }, + en_uso: { clase: 'info', texto: 'en uso' }, + en_pausa: { clase: 'pause', texto: 'en pausa' }, + agotada: { clase: 'warn', texto: 'agotada' }, + desactivada: { clase: 'inactive', texto: 'desactivada' }, + sin_valor: { clase: 'inactive', texto: 'sin valor' } + }; + var ESTADOS_ORDEN = ['disponible', 'en_uso', 'en_pausa', 'agotada', 'desactivada', 'sin_valor']; + + function cuando(iso) { + return iso ? fmtClock(iso) + ' (' + fmtRelative(iso) + ')' : ''; + } + + function detalleEstado(f) { + switch (f.estado) { + case 'en_uso': return 'por ' + esc(f.por || '?') + ' · hasta ' + cuando(f.hasta); + case 'en_pausa': return 'límite del proveedor · vuelve ' + cuando(f.hasta) + (f.motivo ? ' · ' + esc(f.motivo) : ''); + case 'agotada': return 'cuota agotada · vuelve ' + cuando(f.hasta) + (f.por ? ' · reportó ' + esc(f.por) : '') + + (f.motivo ? ' · ' + esc(f.motivo) : ''); + case 'sin_valor': return 'cargada sin la clave: no se puede entregar'; + default: return ''; + } + } + + function estadoHtml(f) { + var e = ESTADO_UI[f.estado] || { clase: 'inactive', texto: f.estado || '?' }; + var d = detalleEstado(f); + return '' + e.texto + '' + + (d ? '
' + d + '
' : ''); + } + + // Eventos del registro en palabras (P337/Fase 2): UNA tabla. Los códigos son los que guarda el servidor. + var EVENTO_UI = { + dispensada: ['🟢', 'entregada'], + liberada: ['⚪', 'devuelta'], + renovada: ['🔄', 'reserva renovada'], + pausada: ['🟡', 'en pausa por límite del proveedor'], + agotada: ['🔴', 'agotada (cuota)'], + revertida: ['↩️', 'reporte deshecho'], + 'liberada-admin': ['🛠', 'liberada por admin'], + alta: ['➕', 'dada de alta'], + editada: ['✏️', 'editada'], + renombrada: ['🏷', 'renombrada'], + baja: ['🗑', 'dada de baja'] + }; + + function eventoTexto(e) { + var u = EVENTO_UI[e] || ['•', e]; + return u[0] + ' ' + u[1]; + } + function actionsHtml(k, keyId, activo, bloqueada) { if (!esAdmin) return ''; return '
' + @@ -772,19 +831,9 @@ }); var providers = Object.keys(byProvider).sort(); - var ahora = Date.now(); - // P204/Fase3: agotada = disponible_desde en el futuro (agotamiento REAL, - // reportado por el consumidor) — reservada = bajo reserva corta de - // contención (reservado_hasta en el futuro), no es lo mismo. - var agotadas = keys.filter(function (k) { return new Date(k.disponible_desde).getTime() > ahora; }).length; - var reservadas = keys.filter(function (k) { - return k.reservado_hasta && new Date(k.reservado_hasta).getTime() > ahora; - }).length; - + // Los conteos por estado salen de /resumen (cargarResumen, P337/Fase 2), no de un cálculo acá document.getElementById("stat-total").textContent = keys.length; document.getElementById("stat-providers").textContent = providers.length; - document.getElementById("stat-agotadas").textContent = agotadas; - document.getElementById("stat-reservadas").textContent = reservadas; renderGauges(byProvider); @@ -833,9 +882,8 @@ // puede estar reservada sin estar agotada, y viceversa nunca (agotada // siempre libera la reserva). Reflejar exactamente el mismo filtro // que usa Registro.disponible en el backend (Armonía Integral). - var agotada = new Date(k.disponible_desde).getTime() > ahora; - var reservada = !agotada && k.reservado_hasta && new Date(k.reservado_hasta).getTime() > ahora; - var disponible = activo && !agotada && !reservada; + // P337/Fase 2: el estado lo calcula el servidor (k.estado/hasta/por/motivo); acá no se recalcula + var bloqueada = ['en_uso', 'en_pausa', 'agotada'].indexOf(k.estado) >= 0; var isNew = lastCreated && lastCreated.provider === k.provider && lastCreated.identificador === k.identificador; var card = document.createElement("div"); card.className = "key-card" + (isNew ? " is-new" : ""); @@ -846,26 +894,9 @@ // por propósito real — el timing es una aclaración del estado, no // un dato independiente) — pill arriba, "vence en X"/"libera en X" // como subtexto, sin ocupar una columna propia. - var estadoHtml, timingSub; - if (!activo) { - estadoHtml = 'desactivada'; - timingSub = ''; - } else if (disponible) { - estadoHtml = 'disponible'; - timingSub = ''; - } else if (reservada) { - estadoHtml = 'reservada'; - timingSub = 'vence ' + fmtRelative(k.reservado_hasta); - } else { - estadoHtml = 'agotada'; - timingSub = 'libera ' + fmtRelative(k.disponible_desde) + - (k.agotada_por ? ' · por ' + esc(k.agotada_por) : '') + - (k.motivo_agotada ? ' · ' + esc(k.motivo_agotada) : ''); - } - var asignadaHtml; - if (reservada && k.reservado_por) { - asignadaHtml = '
' + esc(k.reservado_por) + '
'; + if (k.estado === 'en_uso' && k.por) { + asignadaHtml = '
' + esc(k.por) + '
'; } else if (k.ultimo_individuo) { asignadaHtml = '
último: ' + esc(k.ultimo_individuo) + '
'; } else { @@ -890,8 +921,7 @@ '
' + '
' + '
Estado
' + - estadoHtml + - (timingSub ? '
' + timingSub + '
' : '') + + estadoHtml(k) + '
' + '
' + '
Último uso
' + @@ -901,7 +931,7 @@ '
Asignada a
' + asignadaHtml + '
' + - (editing === keyId ? editPanelHtml(k) : actionsHtml(k, keyId, activo, activo && (agotada || reservada))); + (editing === keyId ? editPanelHtml(k) : actionsHtml(k, keyId, activo, activo && bloqueada)); list.appendChild(card); }); @@ -960,30 +990,64 @@ // Actividad reciente + gráfico de dispensas por día (P204/Fase4) — ambos // proporcionados al volumen real de usos.log (hoy escaso): la lista muestra // lo que hay sin inventar agregados, el gráfico crece solo con el uso real. - function renderActividad(usos) { - var el = document.getElementById("actividad-lista"); - if (!el) return; - - if (!usos.length) { - el.innerHTML = '
Sin actividad registrada todavía.
'; - return; - } - - el.innerHTML = usos.slice(0, 15).map(function (u) { - var agotada = u.evento === 'agotada'; - var icon = agotada ? '🔴' : '🟢'; - var accion = agotada ? 'reportó agotada' : 'pidió'; - return ( - '
' + - '' + icon + '' + - '' + u.individuo + ' ' + accion + ' ' + u.provider + '/' + u.identificador + '' + - '' + fmtRelative(u.en) + '' + - '
' - ); - }).join(''); + // Una fila del registro (P337/Fase 2): la usan "Últimos eventos" y la sección Registro + function filaEvento(u) { + return ( + '' + + '' + fmtClock(u.en) + '
' + fmtRelative(u.en) + '
' + + '' + esc(u.provider) + '/' + esc(u.identificador) + '' + + '' + eventoTexto(u.evento) + '' + + '' + esc(u.individuo || '—') + '' + + '' + esc(u.motivo || '') + '' + + '' + (u.hasta ? cuando(u.hasta) : '') + '' + + '' + ); } - function renderBarChart(usos) { + function tablaEventos(usos, vacio) { + if (!usos.length) return '
' + vacio + '
'; + return '' + + '' + usos.map(filaEvento).join('') + '
CuándoKeyQué pasóQuiénDetalleHasta
'; + } + + function statHtml(etiqueta, valor, clase, ayuda) { + return '
' + etiqueta + + '
' + valor + '
'; + } + + // Dashboard desde /resumen (P337/Fase 2): estados AHORA (todos, también en 0) y lo que pasó en 24 h + function cargarResumen() { + return pedirJson('/resumen?horas=24').then(function (r) { + document.getElementById('stats-ahora').innerHTML = ESTADOS_ORDEN.map(function (e) { + var u = ESTADO_UI[e]; + return statHtml('' + u.texto + '', r.ahora[e] || 0); + }).join(''); + var ev = r.eventos; + var cambios = ev.alta + ev.editada + ev.renombrada + ev.baja + ev['liberada-admin']; + document.getElementById('stats-24h').innerHTML = + statHtml('Entregas', ev.dispensada, '', 'keys entregadas a un consumidor') + + statHtml('Pausas por límite', ev.pausada, 'warn', 'el proveedor contestó límite por minuto: la key vuelve sola en minutos') + + statHtml('Agotamientos de cuota', ev.agotada, 'warn', 'cuota del ciclo agotada: vuelve al reiniciarse la cuota') + + statHtml('Cambios de admin', cambios, '', 'altas, ediciones, renombres, bajas y liberaciones por admin'); + renderPorKey(r.por_key); + }).catch(function () { /* cargarKeys ya avisa los problemas de conexión */ }); + } + + function renderPorKey(filas) { + var el = document.getElementById('por-key'); + if (!el) return; + if (!filas.length) { el.innerHTML = '
Sin keys registradas.
'; return; } + el.innerHTML = '' + + '' + filas.map(function (k) { + var ult = k.ultimo_evento; + return '' + + '' + + '' + + ''; + }).join('') + '
KeyEstadoEntregasPausasAgotamientosÚltimo evento
' + esc(k.provider) + '/' + esc(k.identificador) + '' + estadoHtml(k) + '' + k.eventos.dispensada + '' + k.eventos.pausada + '' + k.eventos.agotada + '' + (ult ? eventoTexto(ult.evento) + '
' + fmtRelative(ult.en) + '
' : '—') + '
'; + } + + function renderBarChart(entregas) { var el = document.getElementById("bar-chart"); if (!el) return; @@ -991,12 +1055,12 @@ for (var i = 6; i >= 0; i--) { var d = new Date(); d.setDate(d.getDate() - i); - dias.push(d.toISOString().slice(0, 10)); + dias.push(d.toLocaleDateString('sv-SE')); // AAAA-MM-DD en hora LOCAL (antes UTC: el día cambiaba a las 21 h) } var counts = {}; dias.forEach(function (d) { counts[d] = 0; }); - usos.forEach(function (u) { - var d = String(u.en).slice(0, 10); + entregas.forEach(function (u) { + var d = new Date(u.en).toLocaleDateString('sv-SE'); if (counts.hasOwnProperty(d)) counts[d]++; }); var max = Math.max.apply(null, dias.map(function (d) { return counts[d]; }).concat([1])); @@ -1004,7 +1068,7 @@ el.innerHTML = dias.map(function (d) { var h = Math.max(2, Math.round((counts[d] / max) * 60)); return ( - '
' + + '
' + '
' + '
' + d.slice(5) + '
' + '
' @@ -1012,67 +1076,54 @@ }).join(''); } - // Reportes por individuo (P204/Fase4, pedido del Operador) — mismo /usos, - // otra lectura: no "cuándo" sino "quién reporta qué" — barra apilada - // sana+liberada (verde) vs agotada (naranja) por individuo, ordenado por - // volumen total. - function renderReportesPorIndividuo(usos) { - var el = document.getElementById("reportes-individuo"); - if (!el) return; - - var counts = {}; - usos.forEach(function (u) { - counts[u.individuo] = counts[u.individuo] || { ok: 0, agotada: 0 }; - if (u.evento === 'agotada') counts[u.individuo].agotada++; - else counts[u.individuo].ok++; - }); - - var individuos = Object.keys(counts).sort(function (a, b) { - var totalA = counts[a].ok + counts[a].agotada; - var totalB = counts[b].ok + counts[b].agotada; - return totalB - totalA; - }); - - if (!individuos.length) { - el.innerHTML = '
Sin reportes todavía.
'; - return; + // Sección Registro (P337/Fase 2): filtros que el SERVIDOR aplica (/usos); las opciones salen de los datos reales + function opcionesRegistro() { + var ev = document.getElementById('reg-evento'); + if (ev.options.length === 1) { + Object.keys(EVENTO_UI).forEach(function (e) { ev.add(new Option(eventoTexto(e), e)); }); } - - var max = Math.max.apply(null, individuos.map(function (i) { return counts[i].ok + counts[i].agotada; })); - - el.innerHTML = individuos.map(function (ind) { - var c = counts[ind]; - var total = c.ok + c.agotada; - var pctOk = max ? (c.ok / max) * 100 : 0; - var pctAgotada = max ? (c.agotada / max) * 100 : 0; - return ( - '
' + - '
' + ind + '
' + - '
' + - '
' + - '
' + - '
' + - '
' + total + '
' + - '
' - ); - }).join(''); + var sel = document.getElementById('reg-key'); + var actual = sel.value; + sel.length = 1; + keys.map(function (k) { return k.provider + '/' + k.identificador; }).sort().forEach(function (ref) { sel.add(new Option(ref, ref)); }); + sel.value = actual; } + function cargarRegistro() { + opcionesRegistro(); + var q = ['horas=' + encodeURIComponent(document.getElementById('reg-horas').value), 'limit=500']; + var ev = document.getElementById('reg-evento').value; + var key = document.getElementById('reg-key').value; + var quien = document.getElementById('reg-individuo').value.trim(); + if (ev) q.push('evento=' + encodeURIComponent(ev)); + if (key) { + var partes = key.split('/'); + q.push('provider=' + encodeURIComponent(partes[0]), 'identificador=' + encodeURIComponent(partes.slice(1).join('/'))); + } + if (quien) q.push('individuo=' + encodeURIComponent(quien)); + return pedirJson('/usos?' + q.join('&')).then(function (usos) { + document.getElementById('reg-cuenta').textContent = usos.length + (usos.length === 500 ? '+ (los 500 más recientes)' : '') + ' evento(s)'; + document.getElementById('registro-lista').innerHTML = tablaEventos(usos, 'Ningún evento con esos filtros.'); + }).catch(function (e) { + document.getElementById('registro-lista').innerHTML = '
No se pudo leer el registro (' + esc(e.message) + ').
'; + }); + } + + ['reg-horas', 'reg-evento', 'reg-key'].forEach(function (id) { + document.getElementById(id).addEventListener('change', cargarRegistro); + }); + document.getElementById('reg-individuo').addEventListener('keydown', function (e) { if (e.key === 'Enter') cargarRegistro(); }); + document.querySelector('[data-ir-registro]').addEventListener('click', function (e) { e.preventDefault(); selectSection('registro'); }); + + // Últimos eventos y entregas por día desde /usos YA filtrado en el servidor (antes: los últimos 100 eventos de todo + // tipo, y el gráfico contaba como entrega cualquier evento) function cargarUsos() { - return fetch('/usos') - .then(function (r) { - if (!r.ok) throw new Error('HTTP ' + r.status); - return r.json(); - }) - .then(function (usos) { - renderActividad(usos); - renderBarChart(usos); - renderReportesPorIndividuo(usos); - }) - .catch(function () { - // Silencioso a propósito — cargarKeys ya reporta problemas de conexión - // en el banner principal, no hace falta duplicar el aviso acá. - }); + return Promise.all([ + pedirJson('/usos?horas=24&limit=12').then(function (usos) { + document.getElementById('actividad-lista').innerHTML = tablaEventos(usos, 'Nada en las últimas 24 h.'); + }), + pedirJson('/usos?evento=dispensada&horas=168&limit=2000').then(renderBarChart) + ]).catch(function () { /* cargarKeys ya avisa los problemas de conexión */ }); } function cargarKeys() { @@ -1273,14 +1324,9 @@ }); } + // Misma presentación que APIs (P337/Fase 2): una sola función de estado function pillEstado(f) { - var clase = { disponible: 'ok', reservada: 'info', agotada: 'warn', inactiva: 'inactive' }[f.estado] || 'inactive'; - var detalle = f.estado === 'agotada' - ? (f.libera_en ? ' · libera ' + fmtRelative(f.libera_en) : '') + (f.agotada_por ? ' · por ' + esc(f.agotada_por) : '') + - (f.motivo ? ' · ' + esc(f.motivo) : '') - : (f.estado === 'reservada' && f.reservado_por ? ' · ' + esc(f.reservado_por) : ''); - return '' + esc(f.estado) + '' + - (detalle ? '
' + detalle + '
' : ''); + return estadoHtml(f); } // Estado de la vista (P335/Fase 12): lo último que se leyó y qué columna se está editando ('individuo|rol')