diff --git a/servicios/nexxa/organismo/VERSION b/servicios/nexxa/organismo/VERSION index f0bb29e7..88c5fb89 100644 --- a/servicios/nexxa/organismo/VERSION +++ b/servicios/nexxa/organismo/VERSION @@ -1 +1 @@ -1.3.0 +1.4.0 diff --git a/servicios/nexxa/organismo/lib_pools.rb b/servicios/nexxa/organismo/lib_pools.rb index f64d7540..b73287b0 100644 --- a/servicios/nexxa/organismo/lib_pools.rb +++ b/servicios/nexxa/organismo/lib_pools.rb @@ -74,6 +74,39 @@ module Nexxa true end + # Deja el pool EXACTAMENTE con estas refs (editar desde nexxa-web, P335/Fase 12). Valida todas antes de escribir: + # una sola inválida y no se toca nada. Lista vacía = vaciar el pool. => refs finales + def reemplazar(individuo:, rol:, refs:, existe: nil) + validar!(individuo, rol) + existe ||= ->(p, i) { Nexxa::Registro.todas.any? { |k| k['provider'] == p && k['identificador'] == i } } + refs = Array(refs).map(&:to_s).uniq + malas = refs.reject { |r| (p, i = r.split('/', 2)) && i && existe.call(p, i) } + raise "Key(s) no encontrada(s): #{malas.join(', ')}" unless malas.empty? + + state = leer + roles = (state['individuos'][individuo] ||= {}) + refs.empty? ? roles.delete(rol) : roles[rol] = refs + state['individuos'].delete(individuo) if roles.empty? + guardar(state) + refs + end + + # Pasa una key del rol 'de' al otro rol del mismo individuo, en una sola escritura. => rol destino + def mover(individuo:, de:, provider:, identificador:) + validar!(individuo, de) + a = (ROLES - [de.to_s]).first + r = ref(provider, identificador) + state = leer + roles = state.dig('individuos', individuo) + raise "#{r} no está en #{individuo}/#{de}" unless roles && Array(roles[de]).include?(r) + + roles[de].delete(r) + roles.delete(de) if roles[de].empty? + (roles[a] ||= []) << r unless Array(roles[a]).include?(r) + guardar(state) + a + end + # Al eliminar una key del registro, se saca de todos los pools (sin referencias colgadas). def olvidar_key(provider:, identificador:) state = leer @@ -86,6 +119,23 @@ module Nexxa cambio end + # Al revocar un individuo (sin token ya no puede pedir) sus pools se borran: sin referencias colgadas (P335/F12) + def olvidar_individuo(individuo) + state = leer + return false unless state['individuos'].delete(individuo.to_s) + + guardar(state) + true + end + + # Resumen por rol para la sección Individuos y el Dashboard: { 'mente' => {'total'=>, 'disponibles'=>}, ... } + def resumen(individuo) + ROLES.to_h do |rol| + filas = Nexxa::Registro.estado_en(refs(individuo, rol)) + [rol, { 'total' => filas.size, 'disponibles' => filas.count { |f| f['estado'] == 'disponible' } }] + end + end + # Pools en los que está una key. => [{ 'individuo' =>, 'rol' => }] def de_key(provider, identificador, state = leer) r = ref(provider, identificador) diff --git a/servicios/nexxa/organismo/server.rb b/servicios/nexxa/organismo/server.rb index 57e02ccb..83b4e555 100644 --- a/servicios/nexxa/organismo/server.rb +++ b/servicios/nexxa/organismo/server.rb @@ -228,7 +228,9 @@ class KeysServlet < WEBrick::HTTPServlet::AbstractServlet res.content_type = 'application/json' res.status = 200 - res.body = Nexxa::Registro.todas.to_json + # Cada key trae en qué pools está (P335/Fase 12): la sección APIs lo muestra y avisa al eliminar + pools = Nexxa::Pools.leer + res.body = Nexxa::Registro.todas.map { |k| k.merge('pools' => Nexxa::Pools.de_key(k['provider'], k['identificador'], pools)) }.to_json end # POST /keys///liberar — admin libera una key agotada o reservada (P335/Fase 7) @@ -320,6 +322,8 @@ server.mount '/keys', KeysServlet # asignar/quitar solo admin (ME-682/ME-683, gate explícito en cada escritura). # GET /pools # POST /pools// body {provider, identificador} +# PUT /pools// body {refs: ["prov/id", ...]} (reemplaza; [] = vaciar) +# POST /pools/////mover (al otro rol) # DELETE /pools//// class PoolsServlet < WEBrick::HTTPServlet::AbstractServlet def partes_de(req) @@ -343,7 +347,11 @@ class PoolsServlet < WEBrick::HTTPServlet::AbstractServlet return rechazar_no_admin(res) unless admin_autenticado?(req) partes = partes_de(req) - return responder(res, 400, { error: 'Uso: POST /pools// {provider, identificador}' }) if partes.size != 2 + if partes.size == 5 && partes[4] == 'mover' + a = Nexxa::Pools.mover(individuo: partes[0], de: partes[1], provider: partes[2], identificador: partes[3]) + return responder(res, 200, { individuo: partes[0], de: partes[1], a: a }) + end + return responder(res, 400, { error: 'Uso: POST /pools// {provider, identificador} | POST /pools/////mover' }) if partes.size != 2 body = begin JSON.parse(req.body.to_s) @@ -357,6 +365,27 @@ class PoolsServlet < WEBrick::HTTPServlet::AbstractServlet responder(res, 400, { error: e.message }) end + # Editar el pool entero desde nexxa-web (P335/Fase 12): valida todas las refs antes de escribir + def do_PUT(req, res) + return rechazar_no_autenticado(res) unless operador_autenticado?(req) + return rechazar_no_admin(res) unless admin_autenticado?(req) + + partes = partes_de(req) + return responder(res, 400, { error: 'Uso: PUT /pools// {refs: ["provider/identificador", ...]}' }) if partes.size != 2 + + body = begin + JSON.parse(req.body.to_s) + rescue JSON::ParserError + return responder(res, 400, { error: 'JSON inválido' }) + end + return responder(res, 400, { error: "Falta 'refs' (lista; vacía = vaciar el pool)" }) unless body['refs'].is_a?(Array) + + pool = Nexxa::Pools.reemplazar(individuo: partes[0], rol: partes[1], refs: body['refs']) + responder(res, 200, { individuo: partes[0], rol: partes[1], pool: pool }) + rescue RuntimeError => e + responder(res, 400, { error: e.message }) + end + def do_DELETE(req, res) return rechazar_no_autenticado(res) unless operador_autenticado?(req) return rechazar_no_admin(res) unless admin_autenticado?(req) @@ -402,7 +431,8 @@ class ConsumidoresServlet < WEBrick::HTTPServlet::AbstractServlet res.content_type = 'application/json' res.status = 200 - res.body = Nexxa::Tokens.listar.to_json + # Cada individuo trae el resumen de sus pools (P335/Fase 12): Individuos y Dashboard lo muestran + res.body = Nexxa::Tokens.listar.map { |c| c.merge('pools' => Nexxa::Pools.resumen(c['individuo'])) }.to_json end def do_POST(req, res) @@ -443,6 +473,7 @@ class ConsumidoresServlet < WEBrick::HTTPServlet::AbstractServlet end revocado = Nexxa::Tokens.revocar(individuo) + Nexxa::Pools.olvidar_individuo(individuo) if revocado # sin token no pide: sus pools no quedan colgados if revocado res.status = 200 res.body = { ok: true }.to_json diff --git a/servicios/nexxa/test/humo_http_test.rb b/servicios/nexxa/test/humo_http_test.rb index 0a80dd7f..041eca39 100644 --- a/servicios/nexxa/test/humo_http_test.rb +++ b/servicios/nexxa/test/humo_http_test.rb @@ -89,6 +89,41 @@ class HumoHttpTest < Minitest::Test assert_equal 200, pedir('get', '/disponible/groq?dry_run=1', token: TOKEN_LIB)[0] end + # Fase 12: CRUD completo (individuo propio 'crud-humo', se deja vacío al final: no interfiere con los otros tests) + def test_crud_editar_mover_vaciar_y_pools_por_key + base = '/pools/crud-humo/mente' + assert_equal 403, pedir('put', base, cuerpo: { refs: %w[gemini/g-01] }, sesion: SES_OPER)[0] + c, b = pedir('put', base, cuerpo: { refs: %w[gemini/g-01 deepseek/d-01] }, sesion: SES_ADMIN) + assert_equal [200, %w[gemini/g-01 deepseek/d-01]], [c, b['pool']] + # una ref mala: 400 y no cambia nada + assert_equal 400, pedir('put', base, cuerpo: { refs: %w[gemini/g-01 gemini/no-existe] }, sesion: SES_ADMIN)[0] + assert_equal 400, pedir('put', base, cuerpo: { otra: 1 }, sesion: SES_ADMIN)[0] + filas = pedir('get', '/pools', sesion: SES_OPER)[1].dig('individuos', 'crud-humo', 'mente').map { |f| f['identificador'] } + assert_equal %w[g-01 d-01].sort, filas.sort + # la key sabe en qué pools está + g01 = pedir('get', '/keys', sesion: SES_OPER)[1].find { |k| k['identificador'] == 'g-01' } + assert_includes g01['pools'], { 'individuo' => 'crud-humo', 'rol' => 'mente' } + # mover al otro rol + c, b = pedir('post', "#{base}/gemini/g-01/mover", sesion: SES_ADMIN) + assert_equal [200, 'red'], [c, b['a']] + assert_equal 400, pedir('post', "#{base}/gemini/g-01/mover", sesion: SES_ADMIN)[0] # ya no está en mente + # vaciar los dos roles + assert_equal 200, pedir('put', base, cuerpo: { refs: [] }, sesion: SES_ADMIN)[0] + assert_equal 200, pedir('put', '/pools/crud-humo/red', cuerpo: { refs: [] }, sesion: SES_ADMIN)[0] + assert_nil pedir('get', '/pools', sesion: SES_OPER)[1].dig('individuos', 'crud-humo') + end + + # Fase 12: Individuos con resumen de pools; revocar borra sus pools (individuo propio, creado y revocado acá) + def test_individuos_con_pools_y_revocar_los_limpia + assert_equal 201, pedir('post', '/consumidores', cuerpo: { individuo: 'revocar-humo' }, sesion: SES_ADMIN)[0] + assert_equal 200, pedir('put', '/pools/revocar-humo/mente', cuerpo: { refs: %w[gemini/g-01] }, sesion: SES_ADMIN)[0] + c = pedir('get', '/consumidores', sesion: SES_OPER)[1].find { |x| x['individuo'] == 'revocar-humo' } + assert_equal({ 'total' => 1, 'disponibles' => 1 }, c.dig('pools', 'mente')) + assert_equal({ 'total' => 0, 'disponibles' => 0 }, c.dig('pools', 'red')) + assert_equal 200, pedir('delete', '/consumidores/revocar-humo', sesion: SES_ADMIN)[0] + assert_nil pedir('get', '/pools', sesion: SES_OPER)[1].dig('individuos', 'revocar-humo') + end + def test_sin_token_ni_sesion assert_equal 401, pedir('get', '/disponible/mente')[0] assert_equal 401, pedir('get', '/pools')[0] diff --git a/servicios/nexxa/test/pools_test.rb b/servicios/nexxa/test/pools_test.rb index 44e17d56..403f137b 100644 --- a/servicios/nexxa/test/pools_test.rb +++ b/servicios/nexxa/test/pools_test.rb @@ -103,4 +103,23 @@ class PoolsTest < Minitest::Test asignar('gemma', 'red', 'gemini', 'g-red') assert_equal ['g-red'], P.con_estado.dig('gemma', 'red').map { |f| f['identificador'] } end + + # --- Fase 12: CRUD completo + def test_reemplazar_deja_el_pool_exacto_y_valida_todo_antes + asignar('gemma', 'mente', 'gemini', 'g-01') + assert_equal %w[deepseek/d-01 gemini/g-red], P.reemplazar(individuo: 'gemma', rol: 'mente', refs: %w[deepseek/d-01 gemini/g-red]) + assert_equal %w[deepseek/d-01 gemini/g-red], P.refs('gemma', 'mente') + assert_raises(RuntimeError) { P.reemplazar(individuo: 'gemma', rol: 'mente', refs: %w[gemini/g-01 gemini/no-existe]) } + assert_equal %w[deepseek/d-01 gemini/g-red], P.refs('gemma', 'mente') # nada cambió + P.reemplazar(individuo: 'gemma', rol: 'mente', refs: []) + assert_equal({ 'individuos' => {} }, P.leer) + end + + def test_mover_entre_roles + asignar('gemma', 'mente', 'gemini', 'g-01') + assert_equal 'red', P.mover(individuo: 'gemma', de: 'mente', provider: 'gemini', identificador: 'g-01') + assert_equal [], P.refs('gemma', 'mente') + assert_equal ['gemini/g-01'], P.refs('gemma', 'red') + assert_raises(RuntimeError) { P.mover(individuo: 'gemma', de: 'mente', provider: 'gemini', identificador: 'g-01') } + end end diff --git a/servicios/nexxa/web/css/estilos.css b/servicios/nexxa/web/css/estilos.css index 66d1f54b..8117fb4b 100644 --- a/servicios/nexxa/web/css/estilos.css +++ b/servicios/nexxa/web/css/estilos.css @@ -1039,8 +1039,23 @@ border: 1px solid var(--border); border-radius: 8px; } - .pool-agregar { display: flex; gap: 6px; } - .pool-agregar select { flex: 1; min-width: 0; } @media (max-width: 640px) { .key-card.pool-card { grid-template-columns: 1fr; } } + + /* Editor de pools (P335/Fase 12) */ + .pool-col-titulo { display: flex; align-items: center; justify-content: space-between; gap: 8px; } + .pool-key .card-icon-actions { justify-self: end; } + .pool-editor { display: flex; flex-direction: column; gap: 8px; padding: 8px; border: 1px dashed var(--border); border-radius: 8px; } + .pool-editor-grupo { display: flex; flex-direction: column; gap: 4px; } + .pool-editor-item { display: flex; align-items: center; gap: 6px; cursor: pointer; } + .pool-editor-acciones { display: flex; gap: 6px; } + .pools-chips { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; } + .pool-chip { font-size: 11px; padding: 1px 6px; border-radius: 999px; background: var(--accent-soft); color: var(--accent); } + .pool-chip.red { background: var(--warn-soft); color: var(--warn); } + + /* Alta de key: un campo más ("Asignar a pool", P335/Fase 12) solo en esta fila */ + #add-key-form > .inline-add-row:first-child { grid-template-columns: 1fr 1fr 1fr 1fr 1fr auto; } + @media (max-width: 640px) { + #add-key-form > .inline-add-row:first-child { grid-template-columns: 1fr 1fr; } + } diff --git a/servicios/nexxa/web/index.html b/servicios/nexxa/web/index.html index 44230bfa..9458d2ae 100644 --- a/servicios/nexxa/web/index.html +++ b/servicios/nexxa/web/index.html @@ -57,6 +57,10 @@
Consumidores
—
+
+
Mentes sin keys
+
—
+
@@ -129,6 +133,10 @@
+
+ + +
diff --git a/servicios/nexxa/web/js/app.js b/servicios/nexxa/web/js/app.js index fae6ac3e..ba7e71e7 100644 --- a/servicios/nexxa/web/js/app.js +++ b/servicios/nexxa/web/js/app.js @@ -102,6 +102,7 @@ cargarKeys(); setInterval(cargarKeys, 30000); cargarCheckins().then(cargarConsumidores); + setInterval(cargarConsumidores, 30000); // resumen de pools y 'Mentes sin keys' al día (P335/Fase 12) cargarUsos(); setInterval(cargarUsos, 30000); cargarVersion(); @@ -142,6 +143,14 @@ }); } + // Chips "individuo · rol" de los pools de una key (P335/Fase 12): fuente única para APIs e Individuos + function chipsPools(pools) { + if (!pools || !pools.length) return ''; + return '
' + pools.map(function (p) { + return '' + esc(p.individuo) + ' · ' + esc(p.rol) + ''; + }).join('') + '
'; + } + function fmtClock(iso) { var d = new Date(iso); return d.toLocaleString("es-AR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }); @@ -261,7 +270,13 @@ function renderConsumidores() { document.getElementById("stat-consumidores").textContent = consumidores.length; + // Mente con keys asignadas pero ninguna disponible: NEXXA ya le informa 'agotado' y el individuo decide (red) + var sinMente = consumidores.filter(function (c) { var m = (c.pools || {}).mente; return m && m.total > 0 && m.disponibles === 0; }); + var statMente = document.getElementById("stat-mente-agotada"); + statMente.textContent = sinMente.length; + statMente.title = sinMente.map(function (c) { return c.individuo; }).join(', '); + actualizarOpcionesPoolAlta(); var list = document.getElementById("consumidores-list"); if (!consumidores.length) { list.innerHTML = '
Sin individuos con token todavía. Generá el primero abajo.
'; @@ -269,14 +284,16 @@ } list.innerHTML = consumidores.map(function (c) { - return '
' + + return '
' + '
' + - '
' + c.individuo + '
' + + '
' + esc(c.individuo) + '
' + + '
' + resumenPoolsHtml(c.pools) + '
' + '
token creado ' + fmtRelative(c.creado) + ' · ' + fmtClock(c.creado) + '
' + '
' + checkinBadgeHtml(c.individuo) + '
' + '
' + (esAdmin ? '
' + + '' + '' + '' + '
' @@ -285,6 +302,30 @@ }).join(''); } + // "🧠 Mente 3/4 · 🪫 Red 1/1" (disponibles/total) — P335/Fase 12 + function resumenPoolsHtml(pools) { + if (!pools) return ''; + return [['mente', '🧠 Mente'], ['red', '🪫 Red']].map(function (r) { + var p = pools[r[0]] || { total: 0, disponibles: 0 }; + if (!p.total) return r[1] + ' vacío'; + var clase = p.disponibles === 0 ? ' class="warn"' : ''; + return r[1] + ' ' + p.disponibles + '/' + p.total + ' disponibles'; + }).join(' · '); + } + + // Alta de key: asignarla a un pool en el mismo paso (opcional, P335/Fase 12) + function actualizarOpcionesPoolAlta() { + var sel = document.getElementById("f-pool"); + var actual = sel.value; + sel.innerHTML = '' + consumidores.map(function (c) { + return ['mente', 'red'].map(function (rol) { + var v = esc(c.individuo) + '/' + rol; + return ''; + }).join(''); + }).join(''); + sel.value = actual; + } + function generarToken(individuo) { return fetch('/consumidores', { method: 'POST', @@ -359,13 +400,16 @@ return cargarConsumidores(); }) .catch(function (err) { mostrarErrorConsumidores('No se pudo rotar el token: ' + err.message); }); + } else if (action === "pools") { + selectSection("pools"); } else if (action === "revocar") { abrirModalConfirmacion({ titulo: "Revocar acceso", confirmValue: individuo, accion: "Sí, revocar", accionEnCurso: "Revocando…", - bodyHtml: '¿Revocar el acceso de ' + individuo + '? Esta acción no se puede deshacer — el individuo no va a poder pedir keys hasta que se le genere un token nuevo.', + bodyHtml: '¿Revocar el acceso de ' + esc(individuo) + '? Esta acción no se puede deshacer — el individuo no va a poder pedir keys hasta que se le genere un token nuevo.' + + '

⚠️ También se borran sus pools Mente y Red (sin token no los puede usar).', onConfirm: function () { return fetch('/consumidores/' + encodeURIComponent(individuo), { method: 'DELETE' }) .then(function (r) { @@ -650,13 +694,22 @@ deleteModalInput.focus(); } + // Qué pools pierden la key al eliminarla (P335/Fase 12): NEXXA la saca de todos, sin referencias colgadas + function avisoPoolsKey(provider, identificador) { + var k = keys.find(function (kk) { return kk.provider === provider && kk.identificador === identificador; }); + if (!k || !k.pools || !k.pools.length) return ''; + return '

⚠️ También sale de ' + k.pools.length + ' pool(s): ' + + k.pools.map(function (p) { return '' + esc(p.individuo) + ' · ' + esc(p.rol) + ''; }).join(', ') + '.'; + } + function abrirModalEliminar(provider, identificador) { abrirModalConfirmacion({ titulo: "Eliminar key", confirmValue: identificador, accion: "Sí, eliminar", accionEnCurso: "Eliminando…", - bodyHtml: '¿Eliminar ' + identificador + ' (' + provider + ')? Esta acción no se puede deshacer — el historial de uso en usos.log se conserva, pero la key deja de existir en el registro.', + bodyHtml: '¿Eliminar ' + esc(identificador) + ' (' + esc(provider) + ')? Esta acción no se puede deshacer — el historial de uso en usos.log se conserva, pero la key deja de existir en el registro.' + + avisoPoolsKey(provider, identificador), onConfirm: function () { return deleteKey(provider, identificador); }, onDone: cargarKeys }); @@ -824,6 +877,7 @@ '
Identificador
' + '
' + esc(k.identificador) + '
' + '
' + esc(k.provider) + ' · cuenta: ' + esc(k.cuenta_origen) + '
' + + chipsPools(k.pools) + '
' + '
' + '
Estado
' + @@ -1086,6 +1140,7 @@ function limpiarAddKeyForm() { document.getElementById("f-identificador").value = ""; document.getElementById("f-cuenta-origen").value = ""; + document.getElementById("f-pool").value = ""; valorInput.value = ""; valorInput.type = "password"; toggleValor.textContent = "mostrar"; @@ -1152,8 +1207,19 @@ } lastCreated = { provider: provider, identificador: identificador }; - addKeyToggler.cerrar(); - return cargarKeys(); + var pool = document.getElementById("f-pool").value; + var asignar = Promise.resolve(); + if (pool) { + var partes = pool.split('/'); + asignar = pedirJson('/pools/' + encodeURIComponent(partes[0]) + '/' + partes[1], { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ provider: provider, identificador: identificador }) + }); + } + return asignar.then(function () { + addKeyToggler.cerrar(); + return cargarKeys(); + }); }) .catch(function (e) { addKeyErrorTitle.textContent = e.message; @@ -1186,7 +1252,11 @@ function cargarPools() { poolsError.classList.remove('visible'); return Promise.all([pedirJson('/pools'), pedirJson('/consumidores')]) - .then(function (res) { renderPools(res[0].individuos || {}, res[1] || []); }) + .then(function (res) { + consumidores = res[1] || []; + renderConsumidores(); // el resumen de pools de Individuos y el Dashboard quedan al día + renderPools(res[0].individuos || {}, consumidores); + }) .catch(function (e) { poolsError.textContent = 'No se pudieron cargar los pools (' + e.message + ').'; poolsError.classList.add('visible'); @@ -1203,7 +1273,14 @@ (detalle ? '
' + detalle + '
' : ''); } + // Estado de la vista (P335/Fase 12): lo último que se leyó y qué columna se está editando ('individuo|rol') + var ultimoPools = {}; + var ultimosConsumidores = []; + var editandoPool = null; + function renderPools(pools, consumidoresLista) { + ultimoPools = pools; + ultimosConsumidores = consumidoresLista; var nombres = {}; consumidoresLista.forEach(function (c) { nombres[c.individuo] = true; }); Object.keys(pools).forEach(function (n) { nombres[n] = true; }); @@ -1216,27 +1293,12 @@ poolsLista.innerHTML = lista.map(function (ind) { var columnas = ROLES_POOL.map(function (r) { var filas = (pools[ind] && pools[ind][r.rol]) || []; - var enPool = {}; - filas.forEach(function (f) { enPool[f.provider + '/' + f.identificador] = true; }); - var items = filas.length ? filas.map(function (f) { - return '
' + - '
' + esc(f.identificador) + ' ' + esc(f.provider) + '
' + - '
' + pillEstado(f) + '
' + - (esAdmin ? '' : '') + - '
'; - }).join('') : '
— vacío: NEXXA responde pool_vacio —
'; - var opciones = keys.filter(function (k) { return !enPool[k.provider + '/' + k.identificador]; }) - .map(function (k) { - var v = esc(k.provider + '/' + k.identificador); - return ''; - }).join(''); - var agregar = esAdmin && opciones - ? '
' + - '
' - : ''; + var cuerpo = editandoPool === ind + '|' + r.rol ? editorPoolHtml(filas) : vistaPoolHtml(filas, r); return '
' + - '
' + r.titulo + ' · ' + r.ayuda + '
' + - items + agregar + '
'; + '
' + r.titulo + ' · ' + r.ayuda + '' + + (esAdmin && editandoPool !== ind + '|' + r.rol + ? '' : '') + + '
' + cuerpo + '
'; }).join(''); return '
' + '
Individuo
' + esc(ind) + '
' + @@ -1244,31 +1306,105 @@ }).join(''); } + // Ver (R): cada key con su estado; el admin puede moverla al otro rol (⇄) o quitarla (✕) + function vistaPoolHtml(filas, r) { + if (!filas.length) return '
— vacío: NEXXA responde pool_vacio —
'; + var otro = r.rol === 'mente' ? 'Red' : 'Mente'; + return filas.map(function (f) { + return '
' + + '
' + esc(f.identificador) + ' ' + esc(f.provider) + '
' + + '
' + pillEstado(f) + '
' + + (esAdmin + ? '
' + + '' + + '
' + : '') + + '
'; + }).join(''); + } + + // Editar (C/U/D en un paso): todas las keys con casillas, agrupadas por provider; Guardar deja el pool exactamente así + function editorPoolHtml(filas) { + var enPool = {}; + filas.forEach(function (f) { enPool[f.provider + '/' + f.identificador] = true; }); + var porProvider = {}; + keys.forEach(function (k) { (porProvider[k.provider] = porProvider[k.provider] || []).push(k); }); + var grupos = Object.keys(porProvider).sort().map(function (prov) { + return '
' + esc(prov) + '
' + + porProvider[prov].map(function (k) { + var ref = k.provider + '/' + k.identificador; + return ''; + }).join('') + '
'; + }).join(''); + return '
' + (grupos || '
No hay keys cargadas.
') + + '
' + + '' + + '
'; + } + + function errorPools(err) { + poolsError.textContent = 'No se pudo cambiar el pool: ' + err.message; + poolsError.classList.add('visible'); + } + + function guardarPool(base, refs) { + return pedirJson(base, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refs: refs }) }) + .then(function () { editandoPool = null; return cargarPools(); }); + } + poolsLista.addEventListener("click", function (e) { var btn = e.target.closest("[data-action]"); if (!btn) return; var card = btn.closest(".pool-card"); var col = btn.closest(".pool-col"); - var base = '/pools/' + encodeURIComponent(card.getAttribute("data-individuo")) + '/' + col.getAttribute("data-rol"); - var accion; - if (btn.getAttribute("data-action") === "pool-agregar") { - var ref = col.querySelector("select").value.split('/'); - accion = pedirJson(base, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ provider: ref[0], identificador: ref.slice(1).join('/') }) - }); - } else if (btn.getAttribute("data-action") === "pool-quitar") { - var item = btn.closest(".pool-key"); - accion = pedirJson(base + '/' + encodeURIComponent(item.getAttribute("data-provider")) + '/' + - encodeURIComponent(item.getAttribute("data-identificador")), { method: 'DELETE' }); + var ind = card.getAttribute("data-individuo"); + var rol = col.getAttribute("data-rol"); + var base = '/pools/' + encodeURIComponent(ind) + '/' + rol; + var accion = btn.getAttribute("data-action"); + var item = btn.closest(".pool-key"); + var refItem = item ? encodeURIComponent(item.getAttribute("data-provider")) + '/' + encodeURIComponent(item.getAttribute("data-identificador")) : null; + + if (accion === "pool-editar") { + editandoPool = ind + '|' + rol; + renderPools(ultimoPools, ultimosConsumidores); + return; + } + if (accion === "pool-cancelar") { + editandoPool = null; + renderPools(ultimoPools, ultimosConsumidores); + return; + } + if (accion === "pool-guardar") { + var refs = Array.prototype.map.call(col.querySelectorAll('.pool-editor input:checked'), function (c) { return c.value; }); + if (!refs.length && ((ultimoPools[ind] || {})[rol] || []).length) { + // Vaciar es destructivo: confirmación escribiendo el nombre del individuo (mismo modal que eliminar una key) + abrirModalConfirmacion({ + titulo: "Vaciar pool", + confirmValue: ind, + accion: "Sí, vaciar", + accionEnCurso: "Vaciando…", + bodyHtml: '¿Dejar vacío el pool ' + esc(rol) + ' de ' + esc(ind) + '? Mientras esté vacío, NEXXA le responde pool_vacio cuando pida por ese rol.', + onConfirm: function () { return guardarPool(base, []); }, + onDone: function () { return Promise.resolve(); } + }); + return; + } + btn.disabled = true; + guardarPool(base, refs).catch(function (err) { btn.disabled = false; errorPools(err); }); + return; + } + + var pedido; + if (accion === "pool-mover") { + pedido = pedirJson(base + '/' + refItem + '/mover', { method: 'POST' }); + } else if (accion === "pool-quitar") { + pedido = pedirJson(base + '/' + refItem, { method: 'DELETE' }); } else { return; } btn.disabled = true; - accion.then(cargarPools).catch(function (err) { - btn.disabled = false; - poolsError.textContent = 'No se pudo cambiar el pool: ' + err.message; - poolsError.classList.add('visible'); - }); + pedido.then(cargarPools).catch(function (err) { btn.disabled = false; errorPools(err); }); }); })();