This commit is contained in:
Lizandro Guarnizo
2026-05-14 22:30:31 -05:00
parent 277ad6bb63
commit 61b3eca31d
16 changed files with 1341 additions and 25 deletions
+220 -4
View File
@@ -25,7 +25,7 @@
<th class="py-2 px-3">Email</th>
<th class="py-2 px-3">Teléfono</th>
<th class="py-2 px-3">Estado</th>
<th class="py-2 px-3 w-24"></th>
<th class="py-2 px-3 w-32"></th>
</tr>
</thead>
<tbody class="text-gray-600">
@@ -40,10 +40,13 @@
</td>
<td class="py-2 px-3">
<div class="flex gap-2">
<button @click="openEdit(d)" class="text-gray-400 hover:text-[#8eb02f]">
<button @click="openDocs(d)" title="Documentos" class="text-gray-400 hover:text-blue-500">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 0 1-6.364-6.364l10.94-10.94A3 3 0 1 1 19.5 7.372L8.552 18.32m.009-.01-.01.01m5.699-9.941-7.81 7.81a1.5 1.5 0 0 0 2.112 2.13"/></svg>
</button>
<button @click="openEdit(d)" title="Editar" class="text-gray-400 hover:text-[#8eb02f]">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"/></svg>
</button>
<button @click="openDelete(d)" class="text-gray-400 hover:text-red-500">
<button @click="openDelete(d)" title="Eliminar" class="text-gray-400 hover:text-red-500">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/></svg>
</button>
</div>
@@ -129,6 +132,120 @@
</div>
</div>
<!-- ─── Modal Documentos ──────────────────────────────────────────────── -->
<div x-show="docsModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 flex flex-col max-h-[90vh]" @click.stop>
<!-- Header -->
<div class="flex items-center justify-between px-6 py-4 border-b">
<div>
<h2 class="text-lg font-semibold">Documentos</h2>
<p class="text-xs text-gray-400" x-text="'Cliente: ' + (docsCliente?.nombre || '')"></p>
</div>
<button @click="docsModal=false" class="text-gray-400 hover:text-gray-600">
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
</button>
</div>
<!-- Cuerpo scrollable -->
<div class="overflow-y-auto flex-1 px-6 py-4 space-y-4">
<!-- Formulario de subida -->
<div class="border rounded-lg p-4 bg-gray-50">
<p class="text-sm font-medium text-gray-700 mb-3">Subir documentos</p>
<!-- Fecha de expedición compartida -->
<div class="mb-3">
<label class="text-xs font-medium text-gray-600">Fecha de expedición (opcional, aplica a todos los archivos)</label>
<input type="date" x-model="docsUpload.fechaExpedicion"
class="mt-1 w-full border rounded px-3 py-2 text-sm" />
</div>
<!-- Zona de arrastre / selección de archivos -->
<div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-[#8eb02f] transition-colors"
@click="$refs.fileInput.click()"
@dragover.prevent
@drop.prevent="handleDrop($event)">
<svg class="w-8 h-8 mx-auto text-gray-400 mb-2" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5"/></svg>
<p class="text-sm text-gray-500">Haz clic o arrastra archivos aquí</p>
<p class="text-xs text-gray-400 mt-1">PDF, Word, Excel, imágenes, ZIP — máx. 20 MB c/u</p>
<input type="file" x-ref="fileInput" multiple class="hidden"
@change="addFiles($event.target.files)" />
</div>
<!-- Lista de archivos pendientes -->
<template x-if="docsUpload.files.length > 0">
<div class="mt-3 space-y-2">
<template x-for="(f, i) in docsUpload.files" :key="i">
<div class="flex items-center gap-3 bg-white border rounded px-3 py-2 text-sm">
<svg class="w-4 h-4 text-gray-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/></svg>
<span class="flex-1 truncate" x-text="f.name"></span>
<span class="text-gray-400 text-xs" x-text="formatSize(f.size)"></span>
<button @click="removeFile(i)" class="text-red-400 hover:text-red-600">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
</button>
</div>
</template>
<button @click="uploadDocs()" :disabled="docsUploading"
class="w-full mt-2 bg-[#8eb02f] text-white py-2 rounded text-sm font-medium disabled:opacity-50">
<span x-text="docsUploading ? 'Subiendo…' : 'Subir ' + docsUpload.files.length + ' archivo(s)'"></span>
</button>
</div>
</template>
</div>
<!-- Lista de documentos guardados -->
<div>
<p class="text-sm font-medium text-gray-700 mb-2">Documentos guardados
<span class="text-gray-400 font-normal" x-text="'(' + documentos.length + ')'"></span>
</p>
<div x-show="docsLoading" class="text-center text-gray-400 text-sm py-4">Cargando…</div>
<div x-show="!docsLoading && documentos.length === 0" class="text-center text-gray-400 text-sm py-4">
Sin documentos
</div>
<div class="space-y-2">
<template x-for="doc in documentos" :key="doc.ID">
<div class="flex items-center gap-3 border rounded px-3 py-2 text-sm hover:bg-gray-50">
<svg class="w-4 h-4 text-blue-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/></svg>
<div class="flex-1 min-w-0">
<p class="font-medium truncate" x-text="doc.nombre || doc.original_name"></p>
<p class="text-xs text-gray-400">
<span x-text="formatSize(doc.tamanio)"></span>
<template x-if="doc.fecha_expedicion">
<span> · Exp: <span x-text="fmtDate(doc.fecha_expedicion)"></span></span>
</template>
</p>
</div>
<a :href="`/app/api/clientes/${docsCliente.ID}/documentos/${doc.ID}/download`"
target="_blank"
class="text-gray-400 hover:text-blue-500" title="Descargar">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
</a>
<button @click="confirmDeleteDoc(doc)" class="text-gray-400 hover:text-red-500" title="Eliminar">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/></svg>
</button>
</div>
</template>
</div>
</div>
</div>
</div>
</div>
<!-- Confirm eliminar documento -->
<div x-show="deleteDocModal" x-cloak class="fixed inset-0 z-[60] flex items-center justify-center bg-black/50">
<div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-sm mx-4 text-center" @click.stop>
<p class="font-semibold mb-1">¿Eliminar documento?</p>
<p class="text-sm text-gray-400 mb-5" x-text="selectedDoc?.nombre || selectedDoc?.original_name"></p>
<div class="flex justify-center gap-3">
<button @click="deleteDocModal=false" class="px-4 py-2 border rounded text-sm">Cancelar</button>
<button @click="deleteDoc()" class="px-4 py-2 bg-red-500 text-white rounded text-sm">Eliminar</button>
</div>
</div>
</div>
<div x-show="toast.show" x-cloak x-transition
class="fixed bottom-4 right-4 z-[100] px-4 py-3 rounded shadow-lg text-sm text-white"
:class="toast.type==='error' ? 'bg-red-500' : 'bg-[#8eb02f]'"
@@ -146,6 +263,16 @@ document.addEventListener('alpine:init', () => {
form: { nombre:'', empresa:'', email:'', email_cc:'', telefono:'', documento:'', notas:'', activo:true },
toast: { show: false, msg: '', type: 'ok' },
// ── Documentos ──────────────────────────────────────────────────────
docsModal: false,
docsCliente: null,
documentos: [],
docsLoading: false,
docsUploading: false,
docsUpload: { fechaExpedicion: '', files: [] },
deleteDocModal: false,
selectedDoc: null,
async init() { await this.loadData(); },
async loadData() {
@@ -201,7 +328,96 @@ document.addEventListener('alpine:init', () => {
showToast(msg, type='ok') {
this.toast = { show: true, msg, type };
setTimeout(() => this.toast.show = false, 3000);
}
},
// ── Documentos: métodos ─────────────────────────────────────────────
async openDocs(d) {
this.docsCliente = d;
this.docsModal = true;
this.docsUpload = { fechaExpedicion: '', files: [] };
await this.loadDocs();
},
async loadDocs() {
this.docsLoading = true;
try {
const { data } = await axios.get(`/app/api/clientes/${this.docsCliente.ID}/documentos`);
this.documentos = data || [];
} catch(e) {
this.showToast('Error cargando documentos', 'error');
}
this.docsLoading = false;
},
addFiles(fileList) {
for (const f of fileList) {
if (!this.docsUpload.files.find(x => x.name === f.name && x.size === f.size)) {
this.docsUpload.files.push(f);
}
}
},
handleDrop(event) {
this.addFiles(event.dataTransfer.files);
},
removeFile(i) {
this.docsUpload.files.splice(i, 1);
},
async uploadDocs() {
if (this.docsUpload.files.length === 0) return;
this.docsUploading = true;
try {
const fd = new FormData();
for (const f of this.docsUpload.files) {
fd.append('archivos', f);
}
if (this.docsUpload.fechaExpedicion) {
fd.append('fecha_expedicion', this.docsUpload.fechaExpedicion);
}
await axios.post(`/app/api/clientes/${this.docsCliente.ID}/documentos`, fd, {
headers: { 'Content-Type': 'multipart/form-data' }
});
this.showToast('Archivos subidos correctamente');
this.docsUpload.files = [];
this.docsUpload.fechaExpedicion = '';
this.$refs.fileInput && (this.$refs.fileInput.value = '');
await this.loadDocs();
} catch(e) {
this.showToast(e.response?.data?.error || 'Error al subir', 'error');
}
this.docsUploading = false;
},
confirmDeleteDoc(doc) {
this.selectedDoc = doc;
this.deleteDocModal = true;
},
async deleteDoc() {
try {
await axios.delete(`/app/api/clientes/${this.docsCliente.ID}/documentos/${this.selectedDoc.ID}`);
this.showToast('Documento eliminado');
this.deleteDocModal = false;
this.selectedDoc = null;
await this.loadDocs();
} catch(e) {
this.showToast(e.response?.data?.error || 'Error al eliminar', 'error');
}
},
formatSize(bytes) {
if (!bytes) return '0 B';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024*1024) return (bytes/1024).toFixed(1) + ' KB';
return (bytes/(1024*1024)).toFixed(1) + ' MB';
},
fmtDate(iso) {
if (!iso) return '';
return iso.substring(0, 10);
},
}));
});
</script>
+26 -4
View File
@@ -55,7 +55,7 @@
:class="d.urgencia==='rojo' ? 'bg-red-100 text-red-700' : d.urgencia==='amarillo' ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700'"
x-text="d.dias_restantes <= 0 ? 'Vencido' : d.dias_restantes+' días'"></span>
</td>
<td class="py-2 px-3" x-text="Number(d.precio_acordado).toFixed(2)"></td>
<td class="py-2 px-3" x-text="fmtPrecio(d.precio_acordado, d.moneda)"></td>
<td class="py-2 px-3">
<span class="px-2 py-0.5 rounded text-xs font-medium"
:class="{
@@ -161,9 +161,18 @@
<label class="text-xs font-medium text-gray-600">Precio acordado</label>
<input x-model="form.precio_acordado" type="number" step="0.01" class="mt-1 w-full border rounded px-3 py-2 text-sm" />
<p class="text-xs text-gray-400 mt-0.5" x-show="precioSugerido > 0">
Sugerido: <span class="font-medium text-gray-600" x-text="precioSugerido.toFixed(2)"></span>
Sugerido: <span class="font-medium text-gray-600" x-text="fmtPrecio(precioSugerido, form.moneda)"></span>
</p>
</div>
<div>
<label class="text-xs font-medium text-gray-600">Moneda</label>
<select x-model="form.moneda" class="mt-1 w-full border rounded px-3 py-2 text-sm">
<option value="COP">COP — Pesos colombianos</option>
<option value="USD">USD — Dólares</option>
<option value="MXN">MXN — Pesos mexicanos</option>
<option value="EUR">EUR — Euros</option>
</select>
</div>
<div x-show="editModal">
<label class="text-xs font-medium text-gray-600">Estado</label>
<select x-model="form.estado" class="mt-1 w-full border rounded px-3 py-2 text-sm">
@@ -342,7 +351,7 @@ document.addEventListener('alpine:init', () => {
clientes: [], servicios: [], reglas: [], reglasBienvenida: [],
selectedId: null,
verificandoID: null,
form: { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, estado:'activo', auto_renovar:false, notas:'' },
form: { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, moneda:'COP', estado:'activo', auto_renovar:false, notas:'' },
toast: { show: false, msg: '', type: 'ok' },
async init() {
@@ -398,6 +407,7 @@ document.addEventListener('alpine:init', () => {
fecha_inicio: d.fecha_inicio ? d.fecha_inicio.substring(0,10) : '',
fecha_vencimiento: d.fecha_vencimiento ? d.fecha_vencimiento.substring(0,10) : '',
precio_acordado: d.precio_acordado,
moneda: d.moneda || 'COP',
estado: d.estado,
auto_renovar: d.auto_renovar,
notas: d.notas
@@ -409,7 +419,7 @@ document.addEventListener('alpine:init', () => {
closeModals() {
this.addModal = this.editModal = this.deleteModal = false;
this.selectedId = null;
this.form = { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, estado:'activo', auto_renovar:false, notas:'' };
this.form = { cliente_id:'', servicio_ids:[], fecha_inicio:'', fecha_vencimiento:'', precio_acordado:0, moneda:'COP', estado:'activo', auto_renovar:false, notas:'' };
},
async save() {
@@ -532,6 +542,18 @@ document.addEventListener('alpine:init', () => {
if (!raw) return '—';
return new Date(raw).toLocaleDateString('es-ES', { day:'2-digit', month:'2-digit', year:'numeric' });
},
fmtPrecio(valor, moneda) {
const v = parseFloat(valor) || 0;
const cur = moneda || 'COP';
// COP y MXN: sin decimales, separador de miles
const sinDecimales = ['COP', 'MXN'];
const opts = sinDecimales.includes(cur)
? { minimumFractionDigits: 0, maximumFractionDigits: 0 }
: { minimumFractionDigits: 2, maximumFractionDigits: 2 };
const num = v.toLocaleString('es-CO', opts);
return cur + ' ' + num;
},
prevPage() { if(this.page>1){ this.page--; this.loadData(); } },
nextPage() { if(this.page<this.totalPages){ this.page++; this.loadData(); } },
showToast(msg, type='ok') {
+41 -3
View File
@@ -29,6 +29,7 @@
<th class="py-2 px-4 border-b">Servicio vinculado</th>
<th class="py-2 px-4 border-b">Orden</th>
<th class="py-2 px-4 border-b w-10">Estado</th>
<th class="py-2 px-4 border-b w-20 text-center">Health</th>
<th class="py-2 px-4 border-b w-24"></th>
</tr>
</thead>
@@ -47,6 +48,23 @@
:class="item.activo ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
class="text-xs px-2 py-0.5 rounded-full"></span>
</td>
<!-- Health check -->
<td class="py-2 px-4 text-center">
<template x-if="!item.health_url">
<span class="inline-block w-3 h-3 rounded-full bg-gray-300" title="Sin URL de health"></span>
</template>
<template x-if="item.health_url">
<div class="flex flex-col items-center gap-1">
<span :class="healthStatus[item.ID] === 'ok' ? 'bg-green-400' : healthStatus[item.ID] === 'fail' ? 'bg-red-400' : 'bg-yellow-300'"
class="inline-block w-3 h-3 rounded-full"
:title="healthInfo[item.ID] || 'Click para verificar'"></span>
<button @click="checkHealth(item)" class="text-xs text-gray-400 hover:text-[#8eb02f]" title="Verificar">
<span x-show="healthLoading[item.ID]"></span>
<span x-show="!healthLoading[item.ID]">check</span>
</button>
</div>
</template>
</td>
<td class="py-2 px-4 flex gap-2 justify-end">
<a :href="`/docs/${item.slug}`" target="_blank" title="Ver documentación" class="text-green-500 hover:text-green-700">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
@@ -111,6 +129,12 @@
<input type="text" x-model="form.logo_url"
class="border border-gray-300 rounded w-full p-2 text-sm">
</div>
<div class="col-span-2">
<label class="block text-xs font-medium mb-1">Health Check URL <span class="text-gray-400 font-normal">(opcional)</span></label>
<input type="url" x-model="form.health_url" placeholder="https://api.tuservicio.com/health"
class="border border-gray-300 rounded w-full p-2 text-sm font-mono">
<p class="text-xs text-gray-400 mt-0.5">Se usará para verificar que el servicio está activo. Debe devolver HTTP 2xx.</p>
</div>
<div class="col-span-2">
<label class="block text-xs font-medium mb-1">Servicio vinculado <span class="text-gray-400 font-normal">(opcional)</span></label>
<select x-model.number="form.servicio_id" class="border border-gray-300 rounded w-full p-2 text-sm">
@@ -160,7 +184,8 @@ function saasApp() {
loading: false,
showModal: false, showDeleteModal: false,
editId: null, deleteId: null,
form: { nombre: '', slug: '', descripcion: '', logo_url: '', servicio_id: null, activo: true, orden: 0 },
form: { nombre: '', slug: '', descripcion: '', logo_url: '', health_url: '', servicio_id: null, activo: true, orden: 0 },
healthStatus: {}, healthInfo: {}, healthLoading: {},
init() { this.load(1); },
@@ -190,7 +215,7 @@ function saasApp() {
openAdd() {
this.editId = null;
this.form = { nombre: '', slug: '', descripcion: '', logo_url: '', servicio_id: null, activo: true, orden: 0 };
this.form = { nombre: '', slug: '', descripcion: '', logo_url: '', health_url: '', servicio_id: null, activo: true, orden: 0 };
this.showModal = true;
},
@@ -198,12 +223,25 @@ function saasApp() {
this.editId = item.ID;
this.form = {
nombre: item.nombre, slug: item.slug, descripcion: item.descripcion,
logo_url: item.logo_url, servicio_id: item.servicio_id,
logo_url: item.logo_url, health_url: item.health_url || '',
servicio_id: item.servicio_id,
activo: item.activo, orden: item.orden
};
this.showModal = true;
},
async checkHealth(item) {
this.$set(this.healthLoading, item.ID, true);
const res = await fetch(`/app/saas/${item.ID}/health`);
const d = await res.json();
this.$set(this.healthStatus, item.ID, d.ok ? 'ok' : 'fail');
const info = d.ok
? `HTTP ${d.http_status} · ${d.latency_ms}ms`
: (d.error || `HTTP ${d.http_status}`);
this.$set(this.healthInfo, item.ID, info);
this.$set(this.healthLoading, item.ID, false);
},
submitForm() {
const url = this.editId ? `/app/saas/${this.editId}` : '/app/saas';
const method = this.editId ? 'PUT' : 'POST';
+68
View File
@@ -55,6 +55,12 @@
class="text-xs px-2 py-0.5 rounded-full"></span>
</td>
<td class="py-2 px-4 flex gap-2 justify-end">
<button @click="openProbar(item)" title="Probar endpoint" class="text-[#8eb02f] hover:text-[#6d8a24]">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"/>
<path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</button>
<button @click="openEdit(item)" title="Editar" class="text-blue-500 hover:text-blue-700">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
@@ -83,6 +89,48 @@
</div>
</div>
<!-- ── Modal Probar endpoint ─────────────────────────────────────────── -->
<div x-show="probarModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-screen overflow-y-auto">
<div class="flex justify-between items-center p-5 border-b">
<div>
<h2 class="text-lg font-semibold">Probar endpoint</h2>
<p class="text-xs text-gray-500 mt-0.5" x-text="probarItem ? probarItem.metodo + ' ' + probarItem.endpoint_url : ''"></p>
</div>
<button @click="closeProbar()" class="text-gray-400 hover:text-gray-600 text-xl"></button>
</div>
<div class="p-5 space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Payload JSON (editable)</label>
<textarea x-model="probarPayload" rows="8"
class="border rounded w-full p-2 text-sm font-mono"
placeholder='{"contrato_id":1,"email":"test@example.com"}'></textarea>
<p class="text-xs text-gray-400 mt-0.5">Se enviará tal cual al endpoint. Si está vacío se envía sin body.</p>
</div>
<button @click="runProbar()" :disabled="probarLoading" class="bg-[#8eb02f] text-white px-5 py-2 rounded text-sm disabled:opacity-50">
<span x-show="!probarLoading">▶ Enviar petición</span>
<span x-show="probarLoading">Enviando…</span>
</button>
<!-- Resultado -->
<div x-show="probarResult" class="border rounded">
<div class="flex items-center gap-3 px-4 py-2 border-b bg-gray-50">
<span class="text-sm font-semibold">HTTP</span>
<span x-text="probarResult && probarResult.http_status"
:class="probarResult && probarResult.ok ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
class="text-xs px-2 py-0.5 rounded-full font-mono font-bold"></span>
<span class="text-xs text-gray-500" x-text="probarResult ? probarResult.latency_ms + ' ms' : ''"></span>
<span x-show="probarResult && !probarResult.ok" x-text="probarResult && probarResult.error" class="text-xs text-red-600 ml-auto"></span>
</div>
<pre x-text="probarResult && probarResult.body"
class="p-4 text-xs font-mono whitespace-pre-wrap break-all bg-gray-900 text-green-300 rounded-b max-h-64 overflow-auto"></pre>
</div>
</div>
<div class="flex justify-end p-5 border-t">
<button @click="closeProbar()" class="px-4 py-2 border rounded text-sm">Cerrar</button>
</div>
</div>
</div>
<!-- ── Modal crear / editar ────────────────────────────────────────────── -->
<div x-show="showModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-screen overflow-y-auto">
@@ -190,6 +238,7 @@ function saasApiApp() {
loading: false, showModal: false, editMode: false,
saving: false, error: '',
form: {},
probarModal: false, probarItem: null, probarPayload: '', probarResult: null, probarLoading: false,
defaultForm() {
return { saas_id: 0, nombre: '', pasarela: 'ambas', endpoint_url: '', metodo: 'POST', api_key_header: '', api_key_value: '', payload_template: '', timeout_seg: 10, activo: true };
},
@@ -250,6 +299,25 @@ function saasApiApp() {
await fetch(`/app/saas-api/${id}`, { method: 'DELETE' });
await this.load(this.page);
},
openProbar(item) {
this.probarItem = item;
this.probarPayload = item.payload_template || '';
this.probarResult = null;
this.probarModal = true;
},
closeProbar() { this.probarModal = false; },
async runProbar() {
this.probarLoading = true;
this.probarResult = null;
const body = { payload: this.probarPayload };
const res = await fetch(`/app/saas-api/${this.probarItem.ID}/probar`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
this.probarResult = await res.json();
this.probarLoading = false;
},
};
}
</script>
+318
View File
@@ -0,0 +1,318 @@
<!-- Vista: Configuración de Telegram -->
<div x-data="telegramApp()" x-init="init()" @keydown.escape="closeModal()" class="bg-white rounded-lg shadow">
<div class="container mx-auto p-6 w-full">
<h1 class="text-2xl font-bold mb-1">Notificaciones Telegram</h1>
<p class="text-sm text-gray-500 mb-4">
Configura bots de Telegram para enviar notificaciones dinámicas desde el panel.
Cada bot requiere un <code class="bg-gray-100 px-1 rounded">bot_token</code> y un <code class="bg-gray-100 px-1 rounded">chat_id</code> (puede ser un canal, grupo o usuario).
</p>
<!-- Tabs -->
<div class="flex gap-4 border-b mb-6 text-sm font-medium">
<button @click="tab='configs'"
:class="tab==='configs' ? 'border-b-2 border-[#8eb02f] text-[#8eb02f]' : 'text-gray-500 hover:text-gray-700'"
class="pb-2">Configuraciones</button>
<button @click="tab='send'"
:class="tab==='send' ? 'border-b-2 border-[#8eb02f] text-[#8eb02f]' : 'text-gray-500 hover:text-gray-700'"
class="pb-2">Enviar mensaje</button>
<button @click="tab='logs'; loadLogs(1)"
:class="tab==='logs' ? 'border-b-2 border-[#8eb02f] text-[#8eb02f]' : 'text-gray-500 hover:text-gray-700'"
class="pb-2">Historial</button>
</div>
<!-- ── Tab: Configuraciones ──────────────────────────────────────────── -->
<div x-show="tab==='configs'">
<div class="flex justify-end mb-4">
<button @click="openAdd()" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">+ Nueva configuración</button>
</div>
<template x-if="configs.length === 0">
<p class="text-gray-400 text-sm text-center py-8">Sin configuraciones. Agrega una para comenzar.</p>
</template>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<template x-for="cfg in configs" :key="cfg.ID">
<div class="border rounded-lg p-4 flex flex-col gap-2 hover:shadow-sm transition-shadow">
<div class="flex items-start justify-between gap-2">
<div>
<p class="font-semibold text-gray-800 text-sm" x-text="cfg.nombre"></p>
<p class="text-xs text-gray-400 mt-0.5">Chat ID: <span class="font-mono" x-text="cfg.chat_id"></span></p>
</div>
<span :class="cfg.activo ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
x-text="cfg.activo ? 'Activo' : 'Inactivo'"
class="text-xs px-2 py-0.5 rounded-full whitespace-nowrap"></span>
</div>
<p x-show="cfg.notas" x-text="cfg.notas" class="text-xs text-gray-500 italic"></p>
<div class="flex gap-2 mt-auto pt-2 border-t">
<button @click="testConfig(cfg)" :disabled="testLoading[cfg.ID]"
class="flex-1 text-xs border border-[#8eb02f] text-[#8eb02f] px-3 py-1.5 rounded hover:bg-[#8eb02f] hover:text-white transition-colors disabled:opacity-50">
<span x-show="!testLoading[cfg.ID]">🔔 Probar</span>
<span x-show="testLoading[cfg.ID]">Enviando…</span>
</button>
<button @click="openEdit(cfg)"
class="text-xs border border-blue-400 text-blue-500 px-3 py-1.5 rounded hover:bg-blue-50">Editar</button>
<button @click="confirmDelete(cfg.ID)"
class="text-xs border border-red-300 text-red-400 px-3 py-1.5 rounded hover:bg-red-50">Eliminar</button>
</div>
<p x-show="testResult[cfg.ID]" x-text="testResult[cfg.ID]"
:class="testOk[cfg.ID] ? 'text-green-600' : 'text-red-600'"
class="text-xs mt-1"></p>
</div>
</template>
</div>
</div>
<!-- ── Tab: Enviar mensaje ───────────────────────────────────────────── -->
<div x-show="tab==='send'" class="max-w-lg">
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Destinos <span class="text-red-500">*</span></label>
<div class="border rounded p-3 space-y-2 max-h-48 overflow-y-auto">
<template x-for="cfg in configs.filter(c => c.activo)" :key="cfg.ID">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" :value="cfg.ID" x-model.number="sendForm.config_ids" class="w-4 h-4">
<span class="text-sm" x-text="cfg.nombre"></span>
<span class="text-xs text-gray-400 font-mono ml-auto" x-text="cfg.chat_id"></span>
</label>
</template>
<p x-show="configs.filter(c => c.activo).length === 0" class="text-xs text-gray-400">No hay configuraciones activas.</p>
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Título (opcional)</label>
<input type="text" x-model="sendForm.titulo" placeholder="Ej: Alerta de servidor caído"
class="border rounded w-full p-2 text-sm">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Mensaje <span class="text-red-500">*</span></label>
<textarea x-model="sendForm.mensaje" rows="5"
placeholder="Escribe el mensaje. Puedes usar HTML básico: &lt;b&gt;negrita&lt;/b&gt;, &lt;i&gt;cursiva&lt;/i&gt;, &lt;code&gt;código&lt;/code&gt;"
class="border rounded w-full p-2 text-sm"></textarea>
<p class="text-xs text-gray-400 mt-0.5">Soporta HTML básico de Telegram: &lt;b&gt;, &lt;i&gt;, &lt;code&gt;, &lt;pre&gt;</p>
</div>
<div class="flex items-center gap-3">
<button @click="sendMessage()" :disabled="sendLoading"
class="bg-[#8eb02f] text-white px-5 py-2 rounded text-sm disabled:opacity-50">
<span x-show="!sendLoading">📤 Enviar</span>
<span x-show="sendLoading">Enviando…</span>
</button>
<p x-show="sendResult" x-text="sendResult"
:class="sendOk ? 'text-green-600' : 'text-red-600'"
class="text-sm"></p>
</div>
</div>
</div>
<!-- ── Tab: Historial ────────────────────────────────────────────────── -->
<div x-show="tab==='logs'">
<div class="overflow-x-auto">
<table class="table-auto w-full text-sm">
<thead class="border-b border-gray-200 text-left font-semibold text-gray-600">
<tr>
<th class="py-2 px-4">Bot / Config</th>
<th class="py-2 px-4">Título</th>
<th class="py-2 px-4">Mensaje</th>
<th class="py-2 px-4">Estado</th>
<th class="py-2 px-4">Fecha</th>
</tr>
</thead>
<tbody class="text-gray-500">
<template x-if="logs.length === 0">
<tr><td colspan="5" class="py-4 text-center text-gray-400">Sin registros</td></tr>
</template>
<template x-for="log in logs" :key="log.ID">
<tr class="hover:bg-gray-50 border-b border-gray-100">
<td class="py-2 px-4 text-xs" x-text="log.TelegramConfig ? log.TelegramConfig.nombre : '-'"></td>
<td class="py-2 px-4 text-xs" x-text="log.titulo || '-'"></td>
<td class="py-2 px-4 text-xs max-w-xs truncate" x-text="log.mensaje"></td>
<td class="py-2 px-4">
<span :class="log.estado === 'ok' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'"
x-text="log.estado" class="text-xs px-2 py-0.5 rounded-full"></span>
<span x-show="log.error_msg" x-text="log.error_msg" class="text-xs text-red-500 ml-1"></span>
</td>
<td class="py-2 px-4 text-xs text-gray-400" x-text="fmtDate(log.CreatedAt)"></td>
</tr>
</template>
</tbody>
</table>
</div>
<!-- Paginación logs -->
<div class="flex justify-between items-center mt-4 text-sm text-gray-500">
<span>Total: <b x-text="logTotal"></b></span>
<div class="flex gap-1">
<button @click="loadLogs(logPage-1)" :disabled="logPage<=1" class="px-3 py-1 border rounded disabled:opacity-40"></button>
<span class="px-3 py-1" x-text="'Pág. ' + logPage + ' / ' + logTotalPages"></span>
<button @click="loadLogs(logPage+1)" :disabled="logPage>=logTotalPages" class="px-3 py-1 border rounded disabled:opacity-40"></button>
</div>
</div>
</div>
</div>
<!-- ── Modal Crear / Editar config ────────────────────────────────────────── -->
<div x-show="showModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" style="display:none">
<div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
<div class="flex justify-between items-center p-5 border-b">
<h2 class="text-lg font-semibold" x-text="editMode ? 'Editar configuración' : 'Nueva configuración'"></h2>
<button @click="closeModal()" class="text-gray-400 hover:text-gray-600 text-xl"></button>
</div>
<div class="p-5 space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Nombre / etiqueta <span class="text-red-500">*</span></label>
<input type="text" x-model="form.nombre" placeholder="Ej: Bot Alertas Producción"
class="border rounded w-full p-2 text-sm">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Bot Token <span class="text-red-500">*</span></label>
<input type="password" x-model="form.bot_token"
:placeholder="editMode ? '••••••• (dejar vacío para no cambiar)' : 'Token del bot de @BotFather'"
class="border rounded w-full p-2 text-sm font-mono">
<p class="text-xs text-gray-400 mt-0.5">Obtén el token en <a href="https://t.me/BotFather" target="_blank" class="underline text-blue-500">@BotFather</a></p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Chat ID <span class="text-red-500">*</span></label>
<input type="text" x-model="form.chat_id" placeholder="Ej: -1001234567890 o @micanal"
class="border rounded w-full p-2 text-sm font-mono">
<p class="text-xs text-gray-400 mt-0.5">ID del chat, grupo o canal. Para canales usa el formato <code>@nombre_canal</code>.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Notas internas</label>
<textarea x-model="form.notas" rows="2" placeholder="Para qué se usa este bot..."
class="border rounded w-full p-2 text-sm"></textarea>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" id="tg-activo" x-model="form.activo" class="w-4 h-4">
<label for="tg-activo" class="text-sm">Activo</label>
</div>
<p x-show="formError" x-text="formError" class="text-red-500 text-sm"></p>
</div>
<div class="flex justify-end gap-3 p-5 border-t">
<button @click="closeModal()" class="px-4 py-2 border rounded text-sm">Cancelar</button>
<button @click="save()" :disabled="saving"
class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm disabled:opacity-50">
<span x-show="!saving">Guardar</span>
<span x-show="saving">Guardando…</span>
</button>
</div>
</div>
</div>
<!-- ── Modal Confirmar eliminar ────────────────────────────────────────────── -->
<div x-show="deleteModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" style="display:none">
<div class="bg-white rounded-lg shadow-xl w-full max-w-sm mx-4 p-6">
<h2 class="text-lg font-bold mb-3">Confirmar eliminación</h2>
<p class="text-gray-600 mb-4 text-sm">¿Eliminar esta configuración de Telegram?</p>
<div class="flex justify-end gap-2">
<button @click="doDelete()" class="bg-red-500 text-white px-4 py-2 rounded text-sm">Eliminar</button>
<button @click="deleteModal=false" class="bg-gray-500 text-white px-4 py-2 rounded text-sm">Cancelar</button>
</div>
</div>
</div>
</div>
<script>
function telegramApp() {
return {
tab: 'configs',
configs: [],
showModal: false, editMode: false, saving: false, formError: '',
deleteModal: false, deleteId: null,
form: { nombre: '', bot_token: '', chat_id: '', notas: '', activo: true },
testLoading: {}, testResult: {}, testOk: {},
sendForm: { config_ids: [], titulo: '', mensaje: '' },
sendLoading: false, sendResult: '', sendOk: true,
logs: [], logPage: 1, logTotalPages: 1, logTotal: 0,
async init() {
await this.loadConfigs();
},
async loadConfigs() {
const res = await fetch('/app/loadtelegram');
this.configs = await res.json();
},
openAdd() {
this.editMode = false;
this.form = { nombre: '', bot_token: '', chat_id: '', notas: '', activo: true };
this.formError = '';
this.showModal = true;
},
openEdit(cfg) {
this.editMode = true;
this.form = { id: cfg.ID, nombre: cfg.nombre, bot_token: '', chat_id: cfg.chat_id, notas: cfg.notas || '', activo: cfg.activo };
this.formError = '';
this.showModal = true;
},
closeModal() { this.showModal = false; },
async save() {
this.formError = '';
if (!this.form.nombre.trim()) { this.formError = 'El nombre es requerido.'; return; }
if (!this.editMode && !this.form.bot_token.trim()) { this.formError = 'El bot_token es requerido.'; return; }
if (!this.form.chat_id.trim()) { this.formError = 'El chat_id es requerido.'; return; }
this.saving = true;
const url = this.editMode ? `/app/telegram/${this.form.id}` : '/app/telegram';
const method = this.editMode ? 'PUT' : 'POST';
const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.form) });
this.saving = false;
if (!res.ok) { const d = await res.json(); this.formError = d.error || 'Error al guardar.'; return; }
this.closeModal();
await this.loadConfigs();
},
confirmDelete(id) { this.deleteId = id; this.deleteModal = true; },
async doDelete() {
await fetch(`/app/telegram/${this.deleteId}`, { method: 'DELETE' });
this.deleteModal = false;
await this.loadConfigs();
},
async testConfig(cfg) {
this.$set(this.testLoading, cfg.ID, true);
this.$set(this.testResult, cfg.ID, '');
const res = await fetch(`/app/telegram/${cfg.ID}/test`, { method: 'POST' });
const d = await res.json();
this.$set(this.testOk, cfg.ID, d.ok);
this.$set(this.testResult, cfg.ID, d.ok ? '✅ Mensaje enviado correctamente.' : ('❌ ' + (d.error || 'Error')));
this.$set(this.testLoading, cfg.ID, false);
},
async sendMessage() {
this.sendResult = '';
if (!this.sendForm.mensaje.trim()) { this.sendResult = 'El mensaje no puede estar vacío.'; this.sendOk = false; return; }
if (!this.sendForm.config_ids.length) { this.sendResult = 'Selecciona al menos un destino.'; this.sendOk = false; return; }
this.sendLoading = true;
const res = await fetch('/app/telegram/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.sendForm),
});
const d = await res.json();
this.sendOk = d.ok;
this.sendResult = d.ok
? `✅ Enviado a ${d.enviados} destino(s).`
: `⚠️ Enviados: ${d.enviados}, Fallidos: ${d.fallidos}`;
this.sendLoading = false;
},
async loadLogs(p = 1) {
if (p < 1 || p > this.logTotalPages && this.logTotalPages > 0) return;
this.logPage = p;
const res = await fetch(`/app/telegram/logs?page=${p}`);
const d = await res.json();
this.logs = d.items || [];
this.logTotal = d.total;
this.logTotalPages = d.totalPages || 1;
},
fmtDate(s) {
if (!s) return '-';
const d = new Date(s);
return d.toLocaleString('es-CO', { dateStyle: 'short', timeStyle: 'short' });
},
};
}
</script>