feat: multi-query/upload .sql en query runner + selector BD por rol

This commit is contained in:
Lizandro Guarnizo
2026-07-30 09:19:24 -05:00
parent 28affb5a55
commit 1d7bfd3596
8 changed files with 337 additions and 14 deletions
+136 -2
View File
@@ -136,6 +136,19 @@
Limpiar
</button>
<!-- Batch mode toggle -->
<button @click="batchMode = !batchMode; if(!batchMode) batchResults = []"
class="px-3 py-1.5 text-xs border rounded transition"
:class="batchMode ? 'bg-amber-500 text-white border-amber-500' : 'hover:bg-gray-50'">
<span x-text="batchMode ? '📚 Lote ON' : '📄 Lote OFF'"></span>
</button>
<!-- Subir .sql -->
<label x-show="!isMongo && !isRedis" class="px-3 py-1.5 text-xs border rounded hover:bg-gray-50 cursor-pointer transition">
📁 Subir .sql
<input type="file" accept=".sql" @change="uploadSQLFile($event)" class="hidden">
</label>
<!-- Botón AI -->
<button @click="askAI()" :disabled="aiLoading || !sqlText.trim()"
class="flex items-center gap-1 px-3 py-1.5 text-xs rounded transition disabled:opacity-40"
@@ -555,13 +568,68 @@
<!-- ── TAB: Resultados ── -->
<div x-show="activeTab === 'results'" class="flex-1 overflow-auto border rounded-lg">
<div x-show="results.length === 0 && !loadingQuery" class="flex flex-col items-center justify-center h-40 text-gray-400 text-sm gap-2">
<!-- Sin resultados -->
<div x-show="!batchMode && results.length === 0 && !loadingQuery" class="flex flex-col items-center justify-center h-40 text-gray-400 text-sm gap-2">
<svg class="w-10 h-10 opacity-30" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M20.25 6.375c0 2.278-3.694 4.125-8.25 4.125S3.75 8.653 3.75 6.375m16.5 0c0-2.278-3.694-4.125-8.25-4.125S3.75 4.097 3.75 6.375m16.5 0v11.25c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125V6.375m16.5 5.625c0 2.278-3.694 4.125-8.25 4.125s-8.25-1.847-8.25-4.125"/>
</svg>
<span>Sin resultados. Ejecuta una consulta.</span>
</div>
<table x-show="results.length > 0" class="table-auto w-full text-xs">
<!-- Batch results tabs -->
<div x-show="batchMode && batchResults.length > 0" class="flex flex-col h-full">
<div class="flex items-center gap-1 px-2 py-1.5 border-b bg-gray-50 sticky top-0 overflow-x-auto shrink-0">
<template x-for="(br, i) in batchResults" :key="i">
<button @click="batchActiveIdx = i"
class="px-2.5 py-1 text-[10px] rounded whitespace-nowrap font-mono transition flex items-center gap-1"
:class="batchActiveIdx === i
? (br.status === 'error' ? 'bg-red-100 text-red-700 border border-red-200' : 'bg-[#8eb02f] text-white')
: (br.status === 'error' ? 'bg-red-50 text-red-500 border border-red-100' : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50')">
<span x-text="'#' + (i+1)"></span>
<span class="truncate max-w-[100px]" x-text="br.sql.substring(0, 30)"></span>
<span x-show="br.status === 'ok'" class="text-green-500"></span>
<span x-show="br.status === 'error'" class="text-red-500"></span>
</button>
</template>
</div>
<!-- Resultado activo del batch -->
<template x-for="(br, i) in batchResults" :key="i">
<div x-show="batchActiveIdx === i" class="flex-1 overflow-auto">
<div x-show="br.status === 'error'" class="p-4 text-xs text-red-600 bg-red-50 font-mono" x-text="br.error"></div>
<div x-show="br.status === 'ok' && (!br.columns || br.columns.length === 0)" class="p-4 text-xs text-green-700 bg-green-50">
✅ Consulta ejecutada — <span x-text="br.rows + ' filas afectadas'"></span> · <span x-text="br.duration"></span>
</div>
<table x-show="br.status === 'ok' && br.columns && br.columns.length > 0" class="table-auto w-full text-xs">
<thead class="sticky top-0 bg-gray-50 z-10">
<tr>
<th class="py-2 px-3 border-b text-left font-semibold text-gray-500 w-10">#</th>
<template x-for="col in br.columns" :key="col">
<th class="py-2 px-3 border-b text-left font-semibold text-gray-600 whitespace-nowrap" x-text="col"></th>
</template>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<template x-for="(row, idx) in br.data" :key="idx">
<tr class="hover:bg-gray-50">
<td class="py-2 px-3 text-gray-400 select-none" x-text="idx+1"></td>
<template x-for="col in br.columns" :key="col">
<td class="py-2 px-3 font-mono max-w-xs truncate" :title="nullStr(row[col])" x-text="nullStr(row[col])"></td>
</template>
</tr>
</template>
</tbody>
</table>
<div x-show="br.status === 'ok'" class="px-3 py-1.5 text-[10px] text-gray-400 border-t bg-gray-50">
<span x-text="(br.data || []).length + ' filas'"></span> ·
<span x-text="br.duration"></span>
</div>
</div>
</template>
</div>
<!-- Single results table (modo normal) -->
<table x-show="!batchMode && results.length > 0" class="table-auto w-full text-xs">
<thead class="sticky top-0 bg-gray-50 z-10">
<tr>
<th class="py-2 px-3 border-b text-left font-semibold text-gray-500 w-10">#</th>
@@ -704,6 +772,9 @@ document.addEventListener('alpine:init', () => {
results: [],
history: [],
activeTab: 'results',
batchMode: false,
batchResults: [],
batchActiveIdx: 0,
statusMsg: '',
statusOk: true,
testMsg: '',
@@ -1374,6 +1445,10 @@ document.addEventListener('alpine:init', () => {
async runQuery() {
if (!this.selectedConxId || !this.sqlText.trim()) return;
if (this.batchMode) {
await this.runBatch();
return;
}
this.loadingQuery = true;
this.statusMsg = '';
this.results = [];
@@ -1407,6 +1482,65 @@ document.addEventListener('alpine:init', () => {
await this.loadHistory();
},
// ── Batch mode ──────────────────────────────────────────────
extractSQLStatements(text) {
// Split by semicolons, trim whitespace, remove empty
return text
.split(';')
.map(s => s.trim())
.filter(s => s.length > 0 && !s.toUpperCase().startsWith('--') && !s.startsWith('#'));
},
uploadSQLFile(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
this.sqlText = content;
this.batchMode = true;
this.showToast(`📁 Archivo "${file.name}" cargado (${(content.length / 1024).toFixed(1)} KB)`);
};
reader.readAsText(file);
// Reset input so re-selecting same file triggers change
event.target.value = '';
},
async runBatch() {
if (!this.selectedConxId) return;
const sqls = this.extractSQLStatements(this.sqlText);
if (sqls.length === 0) {
this.showToast('No se encontraron sentencias SQL válidas', 'error');
return;
}
this.loadingQuery = true;
this.statusMsg = '';
this.batchResults = [];
this.batchActiveIdx = 0;
this.activeTab = 'results';
try {
const formData = new FormData();
formData.append('conx_db_id', this.selectedConxId);
formData.append('database', this.selectedDb || '');
sqls.forEach((sql, i) => formData.append('sqls[]', sql));
const res = await axios.post('/app/query-runner/run-batch', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
this.batchResults = res.data.results || [];
const okCount = this.batchResults.filter(r => r.status === 'ok').length;
const errCount = this.batchResults.filter(r => r.status === 'error').length;
this.statusOk = errCount === 0;
this.statusMsg = `${okCount} consultas ejecutadas, ${errCount} con error — ${res.data.duration || ''}`;
} catch (e) {
this.statusOk = false;
this.statusMsg = '✗ ' + (e.response?.data?.error || 'Error al ejecutar batch');
if (e.response?.data?.results) {
this.batchResults = e.response.data.results;
}
}
this.loadingQuery = false;
},
async loadHistory() {
if (!this.selectedConxId) return;
try {
+43 -6
View File
@@ -120,6 +120,7 @@
Name = registro.name;
Description = registro.description;
Submodules = [...registro.submodules];
ConxDBs = [...(registro.conx_dbs || [])];
EsPortalCliente = registro.es_portal_cliente || false;
EsPortalPartner = registro.es_portal_partner || false;
HomeUrl = registro.home_url || '';
@@ -254,6 +255,20 @@
</template>
</select>
</div>
<div class="mt-4 p-3 border rounded-md bg-slate-50">
<p class="font-semibold text-sm mb-2">Bases de datos permitidas (Query Runner)</p>
<div class="grid grid-cols-2 gap-1 max-h-32 overflow-y-auto">
<template x-for="con in conexiones" :key="con.ID">
<div>
<input type="checkbox" :value="con.ID" :id="'edit-conxdb-' + con.ID"
:checked="ConxDBs.some(c => c.ID === con.ID)"
@change="if($event.target.checked) { ConxDBs.push(con) } else { ConxDBs = ConxDBs.filter(c => c.ID !== con.ID) }"
class="mr-2">
<label :for="'edit-conxdb-' + con.ID" x-text="con.nombre" class="text-xs"></label>
</div>
</template>
</div>
</div>
<div class="mt-4 flex justify-between">
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar Cambios</button>
<button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
@@ -326,6 +341,20 @@
</template>
</select>
</div>
<div class="mt-4 p-3 border rounded-md bg-slate-50">
<p class="font-semibold text-sm mb-2">Bases de datos permitidas (Query Runner)</p>
<div class="grid grid-cols-2 gap-1 max-h-32 overflow-y-auto">
<template x-for="con in conexiones" :key="con.ID">
<div>
<input type="checkbox" :value="con.ID" :id="'add-conxdb-' + con.ID"
:checked="newConxDBs.some(c => c.ID === con.ID)"
@change="if($event.target.checked) { newConxDBs.push(con) } else { newConxDBs = newConxDBs.filter(c => c.ID !== con.ID) }"
class="mr-2">
<label :for="'add-conxdb-' + con.ID" x-text="con.nombre" class="text-xs"></label>
</div>
</template>
</div>
</div>
<div class="mt-4 flex justify-between">
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar</button>
<button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
@@ -378,6 +407,9 @@
sinregistro: '',
modules: [],
conexiones: [],
ConxDBs: [],
newConxDBs: [],
@@ -405,10 +437,11 @@
fetch(`/app/loadroles?page=${page}${search}`)
.then(response => response.json())
.then(data => {
this.totalRecords = data.total; // Establece el total de registros aquí
this.totalRecords = data.total;
this.modulos = data.modules;
this.registros = data.roles; // Asignar
this.totalPages = data.totalPages; // Asignar total de páginas
this.registros = data.roles;
this.conexiones = data.conexiones || [];
this.totalPages = data.totalPages;
this.createPagination(this.totalPages, page);
if (data.roles.length === 0) {
this.sinregistro = true;
@@ -496,7 +529,8 @@
es_portal_cliente: this.newEsPortalCliente,
es_portal_partner: this.newEsPortalPartner,
home_url: this.newHomeUrl,
submodules: selectedSubmodules.flatMap(modulo => modulo.submodules)
submodules: selectedSubmodules.flatMap(modulo => modulo.submodules),
conx_dbs: this.newConxDBs
};
fetch('/app/roles', {
@@ -510,8 +544,9 @@
this.newDescription = '';
this.newEsPortalCliente = false;
this.newEsPortalPartner = false;
this.newConxDBs = [];
this.modulos.forEach(modulo => {
modulo.submodules.forEach(submodulo => submodulo.checked = false); // Reset checkboxes
modulo.submodules.forEach(submodulo => submodulo.checked = false);
});
this.closeModal();
@@ -557,7 +592,8 @@
es_portal_cliente: this.EsPortalCliente,
es_portal_partner: this.EsPortalPartner,
home_url: this.HomeUrl,
submodules: this.submodulos
submodules: this.submodulos,
conx_dbs: this.ConxDBs
})
})
.then(response => response.json())
@@ -567,6 +603,7 @@
this.EsPortalCliente = false;
this.EsPortalPartner = false;
this.submodulos = [];
this.ConxDBs = [];
this.modulos.forEach(modulo => {
modulo.submodules.forEach(submodulo => {
submodulo.checked = false;