🧩
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 '
| Cuándo | Key | Qué pasó | Quién | ' +
+ 'Detalle | Hasta |
' + usos.map(filaEvento).join('') + '
';
+ }
+
+ 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 = '
| Key | Estado | Entregas | Pausas | ' +
+ 'Agotamientos | Último evento |
' + filas.map(function (k) {
+ var ult = k.ultimo_evento;
+ return '| ' + esc(k.provider) + '/' + esc(k.identificador) + ' | ' + estadoHtml(k) + ' | ' +
+ '' + k.eventos.dispensada + ' | ' + k.eventos.pausada + ' | ' +
+ '' + k.eventos.agotada + ' | ' +
+ '' + (ult ? eventoTexto(ult.evento) + ' ' + fmtRelative(ult.en) + ' ' : '—') + ' |
';
+ }).join('') + '
';
+ }
+
+ 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')