Actualizar automatizaciones.html
This commit is contained in:
@@ -3,308 +3,137 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Automatizaciones - IntegraRepara</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script src="https://unpkg.com/lucide@latest"></script>
|
||||
<title>Robots y Automatizaciones - Integra Repara</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<style>
|
||||
.fade-in { animation: fadeIn 0.3s ease-in-out; }
|
||||
.scroller::-webkit-scrollbar { width: 6px; }
|
||||
.scroller::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; }
|
||||
.console-log { font-family: 'Courier New', Courier, monospace; }
|
||||
body { background-color: #f8fafc; font-family: 'Inter', sans-serif; }
|
||||
.card-robot { border: none; border-radius: 12px; transition: all 0.3s ease; border-left: 5px solid #cbd5e1; }
|
||||
.card-robot.active { border-left-color: #22c55e; }
|
||||
.card-robot.inactive { border-left-color: #ef4444; }
|
||||
.service-item { border-radius: 10px; background: white; border: 1px solid #e2e8f0; }
|
||||
.badge-provider { font-size: 0.7rem; font-weight: 800; text-transform: uppercase; padding: 4px 8px; }
|
||||
.provider-homeserve { background-color: #fee2e2; color: #991b1b; }
|
||||
.provider-multiasistencia { background-color: #dbeafe; color: #1e40af; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-gray-100 text-gray-800 font-sans h-screen overflow-hidden flex">
|
||||
<body>
|
||||
|
||||
<div id="sidebar-container" class="h-full shrink-0"></div>
|
||||
<div class="container-fluid py-4">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<h4 class="mb-4 fw-bold">🤖 Gestión de Robots</h4>
|
||||
|
||||
<div class="flex-1 flex flex-col h-full min-w-0">
|
||||
<div id="header-container"></div>
|
||||
|
||||
<main class="flex-1 overflow-y-auto p-6 no-scrollbar">
|
||||
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
|
||||
<i data-lucide="bot" class="text-purple-600"></i> Robots & Automatizaciones
|
||||
</h2>
|
||||
<p class="text-sm text-gray-500">Gestiona la descarga automática de servicios.</p>
|
||||
<div id="robotsContainer">
|
||||
</div>
|
||||
<button onclick="loadScrapedServices()" class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-50 shadow-sm flex items-center gap-2 text-sm font-bold transition">
|
||||
<i data-lucide="refresh-cw" class="w-4 h-4"></i> Actualizar Buzón
|
||||
|
||||
<div class="card shadow-sm mt-4 bg-dark text-white">
|
||||
<div class="card-body">
|
||||
<h6 class="text-secondary small">LOG DE ACTIVIDAD</h6>
|
||||
<div id="logConsole" class="small font-monospace" style="height: 150px; overflow-y: auto;">
|
||||
> Sistema iniciado...<br>
|
||||
> Esperando sincronización...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-8">
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h4 class="fw-bold">Buzón de Servicios Detectados</h4>
|
||||
<button onclick="loadScrapedServices()" class="btn btn-outline-primary btn-sm rounded-pill">
|
||||
<i class="fas fa-sync-alt me-2"></i>Actualizar Buzón
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 h-full pb-10">
|
||||
|
||||
<div class="space-y-6">
|
||||
|
||||
<div class="bg-white p-5 rounded-xl shadow-sm border-l-4 border-blue-600 relative overflow-hidden">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="bg-blue-100 p-2 rounded-lg text-blue-700 font-bold">M</div>
|
||||
<h3 class="font-bold text-gray-700">Multiasistencia</h3>
|
||||
</div>
|
||||
<div id="status-multi" class="text-[10px] bg-gray-100 text-gray-500 px-2 py-1 rounded-full font-mono">Inactivo</div>
|
||||
</div>
|
||||
<form onsubmit="saveCreds(event, 'multiasistencia')" class="space-y-3">
|
||||
<input type="text" id="user_multiasistencia" placeholder="Usuario Web" class="w-full bg-gray-50 border border-gray-200 rounded px-3 py-2 text-sm outline-none focus:border-blue-500">
|
||||
<input type="password" id="pass_multiasistencia" placeholder="Contraseña" class="w-full bg-gray-50 border border-gray-200 rounded px-3 py-2 text-sm outline-none focus:border-blue-500">
|
||||
<button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded text-xs font-bold transition">Guardar Credenciales</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="bg-white p-5 rounded-xl shadow-sm border-l-4 border-red-600 relative overflow-hidden">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="bg-red-100 p-2 rounded-lg text-red-700 font-bold">H</div>
|
||||
<h3 class="font-bold text-gray-700">HomeServe</h3>
|
||||
</div>
|
||||
<div id="status-homeserve" class="text-[10px] bg-gray-100 text-gray-500 px-2 py-1 rounded-full font-mono">Inactivo</div>
|
||||
</div>
|
||||
<form onsubmit="saveCreds(event, 'homeserve')" class="space-y-3">
|
||||
<input type="text" id="user_homeserve" placeholder="Código Proveedor" class="w-full bg-gray-50 border border-gray-200 rounded px-3 py-2 text-sm outline-none focus:border-red-500">
|
||||
<input type="password" id="pass_homeserve" placeholder="Contraseña" class="w-full bg-gray-50 border border-gray-200 rounded px-3 py-2 text-sm outline-none focus:border-red-500">
|
||||
<button type="submit" class="w-full bg-red-600 hover:bg-red-700 text-white py-2 rounded text-xs font-bold transition">Guardar Credenciales</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="bg-slate-900 rounded-xl shadow-lg p-4 text-slate-300 h-64 flex flex-col">
|
||||
<div class="flex justify-between items-center border-b border-slate-700 pb-2 mb-2">
|
||||
<span class="text-xs font-bold uppercase tracking-wider text-slate-500">Log de Actividad</span>
|
||||
<i data-lucide="terminal" class="w-4 h-4 text-slate-500"></i>
|
||||
</div>
|
||||
<div id="consoleOutput" class="flex-1 overflow-y-auto scroller console-log text-xs space-y-1">
|
||||
<p class="text-slate-500">> Sistema iniciado.</p>
|
||||
<p class="text-slate-500">> Esperando sincronización...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="lg:col-span-2 flex flex-col h-full">
|
||||
<div class="bg-white rounded-xl shadow-sm border border-gray-200 flex flex-col h-full overflow-hidden">
|
||||
<div class="p-4 border-b bg-gray-50 flex justify-between items-center">
|
||||
<div>
|
||||
<h3 class="font-bold text-gray-800">Buzón de Servicios Detectados</h3>
|
||||
<p class="text-xs text-gray-500">Estos servicios han sido encontrados por el robot pero aún no están en tu CRM.</p>
|
||||
</div>
|
||||
<span id="badgeCount" class="bg-blue-100 text-blue-800 text-xs font-bold px-3 py-1 rounded-full">0 Pendientes</span>
|
||||
</div>
|
||||
|
||||
<div id="inboxList" class="flex-1 overflow-y-auto p-4 space-y-3 bg-gray-50/50">
|
||||
<div class="text-center py-20 text-gray-400">
|
||||
<i data-lucide="inbox" class="w-12 h-12 mx-auto mb-3 opacity-50"></i>
|
||||
<p>Cargando servicios...</p>
|
||||
</div>
|
||||
<div id="servicesInbox" class="d-flex flex-column gap-3">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<div id="toast" class="fixed bottom-5 right-5 bg-slate-800 text-white px-6 py-3 rounded-lg shadow-xl translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center gap-3"><span id="toastMsg"></span></div>
|
||||
|
||||
<script src="js/layout.js"></script>
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (!localStorage.getItem("token")) window.location.href = "index.html";
|
||||
|
||||
// 1. Cargar estado de credenciales
|
||||
loadProviderStatus();
|
||||
|
||||
// 2. Cargar buzón
|
||||
loadScrapedServices();
|
||||
|
||||
// Auto-refresh cada 30 segundos para ver si el robot trajo cosas nuevas
|
||||
setInterval(loadScrapedServices, 30000);
|
||||
});
|
||||
|
||||
function log(msg, type = 'info') {
|
||||
const consoleDiv = document.getElementById('consoleOutput');
|
||||
const time = new Date().toLocaleTimeString();
|
||||
let color = 'text-slate-300';
|
||||
if(type === 'success') color = 'text-green-400';
|
||||
if(type === 'error') color = 'text-red-400';
|
||||
|
||||
const p = document.createElement('p');
|
||||
p.className = `${color}`;
|
||||
p.innerHTML = `<span class="opacity-50">[${time}]</span> ${msg}`;
|
||||
consoleDiv.appendChild(p);
|
||||
consoleDiv.scrollTop = consoleDiv.scrollHeight;
|
||||
}
|
||||
|
||||
// --- CREDENCIALES ---
|
||||
async function loadProviderStatus() {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/providers/credentials`, {
|
||||
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (data.ok) {
|
||||
data.credentials.forEach(cred => {
|
||||
// Marcar visualmente como activo
|
||||
const statusBadge = document.getElementById(`status-${cred.provider}`);
|
||||
if (statusBadge) {
|
||||
statusBadge.className = "text-[10px] bg-green-100 text-green-700 px-2 py-1 rounded-full font-bold uppercase";
|
||||
statusBadge.innerText = "ACTIVO";
|
||||
}
|
||||
|
||||
// Rellenar usuario (pero no password)
|
||||
const userInput = document.getElementById(`user_${cred.provider}`);
|
||||
const passInput = document.getElementById(`pass_${cred.provider}`);
|
||||
if (userInput) userInput.value = cred.username;
|
||||
if (passInput) passInput.placeholder = "•••••••• (Guardada)";
|
||||
});
|
||||
log("Credenciales cargadas correctamente.", "info");
|
||||
}
|
||||
} catch (e) { log("Error verificando credenciales.", "error"); }
|
||||
}
|
||||
|
||||
async function saveCreds(e, provider) {
|
||||
e.preventDefault();
|
||||
const user = document.getElementById(`user_${provider}`).value;
|
||||
const pass = document.getElementById(`pass_${provider}`).value;
|
||||
|
||||
if(!user || !pass) {
|
||||
showToast("Faltan datos", true);
|
||||
return;
|
||||
}
|
||||
|
||||
log(`Guardando acceso para ${provider}...`);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/providers/credentials`, {
|
||||
method: 'POST',
|
||||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||
body: JSON.stringify({ provider, username: user, password: pass })
|
||||
});
|
||||
|
||||
if(res.ok) {
|
||||
showToast("Guardado correctamente");
|
||||
log(`✅ Acceso a ${provider} actualizado. El robot lo usará en el próximo ciclo.`, "success");
|
||||
loadProviderStatus(); // Refrescar UI visual
|
||||
} else {
|
||||
log(`❌ Error guardando ${provider}`, "error");
|
||||
}
|
||||
} catch(e) { showToast("Error conexión", true); }
|
||||
}
|
||||
|
||||
// --- BUZÓN DE ENTRADA (SCRAPED) ---
|
||||
<script src="./js/layout.js"></script>
|
||||
<script>
|
||||
// 1. CARGAR SERVICIOS DEL ROBOT
|
||||
async function loadScrapedServices() {
|
||||
const list = document.getElementById('inboxList');
|
||||
const inbox = document.getElementById('servicesInbox');
|
||||
inbox.innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary"></div></div>';
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/providers/scraped`, {
|
||||
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
||||
headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if(!data.ok) return;
|
||||
|
||||
const services = data.services || [];
|
||||
document.getElementById('badgeCount').innerText = `${services.length} Pendientes`;
|
||||
|
||||
if(services.length === 0) {
|
||||
list.innerHTML = `
|
||||
<div class="text-center py-20 text-gray-400 flex flex-col items-center">
|
||||
<i data-lucide="check-circle" class="w-16 h-16 text-green-100 mb-4"></i>
|
||||
<p class="font-medium">Todo al día</p>
|
||||
<p class="text-xs mt-1">El robot seguirá buscando automáticamente...</p>
|
||||
</div>`;
|
||||
lucide.createIcons();
|
||||
if (data.services.length === 0) {
|
||||
inbox.innerHTML = '<div class="alert alert-light text-center border-dashed py-5">No hay servicios nuevos pendientes.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = "";
|
||||
services.forEach(s => {
|
||||
const info = s.raw_data;
|
||||
const isMulti = s.provider === 'multiasistencia';
|
||||
inbox.innerHTML = '';
|
||||
data.services.forEach(svc => {
|
||||
const raw = svc.raw_data;
|
||||
// NOTA: Aquí usamos los campos "_fixed" que crea el robot inteligente
|
||||
// o fallbacks manuales para que no salga 'undefined'
|
||||
const name = raw.clientName_fixed || raw.clientName || "Cliente sin nombre";
|
||||
const addr = raw.address_fixed || raw.address || "Sin dirección";
|
||||
const phone = raw.phone_fixed || raw.phone || "Sin teléfono";
|
||||
|
||||
const el = document.createElement('div');
|
||||
el.className = "bg-white p-4 rounded-xl border border-gray-200 hover:shadow-md transition flex flex-col md:flex-row gap-4 items-start md:items-center";
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="flex-1 w-full">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<span class="text-[10px] font-bold px-2 py-0.5 rounded ${isMulti ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700'} uppercase tracking-wide">
|
||||
${s.provider}
|
||||
</span>
|
||||
<span class="font-mono text-xs text-gray-500 font-bold">#${s.service_ref}</span>
|
||||
<span class="text-[10px] text-gray-400 flex items-center gap-1">
|
||||
<i data-lucide="clock" class="w-3 h-3"></i> ${new Date(s.created_at).toLocaleTimeString()}
|
||||
</span>
|
||||
const card = document.createElement('div');
|
||||
card.className = 'service-item p-3 shadow-sm d-flex justify-content-between align-items-center';
|
||||
card.innerHTML = `
|
||||
<div class="flex-grow-1">
|
||||
<div class="d-flex align-items-center gap-2 mb-1">
|
||||
<span class="badge badge-provider provider-${svc.provider}">${svc.provider}</span>
|
||||
<span class="text-muted small">#${svc.service_ref}</span>
|
||||
<span class="text-muted small"><i class="far fa-clock ms-2"></i> ${new Date(svc.created_at).toLocaleTimeString()}</span>
|
||||
</div>
|
||||
|
||||
<h4 class="font-bold text-gray-800 text-lg leading-tight">${info.clientName}</h4>
|
||||
<div class="text-sm text-gray-600 mt-1 flex items-center gap-4">
|
||||
<span class="flex items-center gap-1"><i data-lucide="map-pin" class="w-3 h-3 text-gray-400"></i> ${info.address || 'Sin dirección'}</span>
|
||||
<span class="flex items-center gap-1"><i data-lucide="phone" class="w-3 h-3 text-gray-400"></i> ${info.phone || 'Sin teléfono'}</span>
|
||||
<h6 class="mb-1 fw-bold">${name}</h6>
|
||||
<div class="small text-secondary">
|
||||
<i class="fas fa-map-marker-alt me-1"></i> ${addr} |
|
||||
<i class="fas fa-phone ms-2 me-1"></i> ${phone}
|
||||
</div>
|
||||
<p class="text-xs text-gray-400 mt-2 italic truncate max-w-lg">${info.description || 'Sin descripción'}</p>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 flex gap-2 w-full md:w-auto">
|
||||
<button onclick="importService(${s.id}, this)" class="flex-1 md:flex-none bg-green-600 hover:bg-green-700 text-white px-5 py-2.5 rounded-lg text-sm font-bold shadow-sm transition flex items-center justify-center gap-2">
|
||||
<i data-lucide="download" class="w-4 h-4"></i> Importar
|
||||
<div>
|
||||
<button onclick="importService(${svc.id})" class="btn btn-success btn-sm px-4">
|
||||
<i class="fas fa-download me-2"></i>Importar
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
list.appendChild(el);
|
||||
inbox.appendChild(card);
|
||||
});
|
||||
lucide.createIcons();
|
||||
|
||||
} catch(e) { console.error(e); }
|
||||
} catch (e) {
|
||||
inbox.innerHTML = '<div class="alert alert-danger">Error al conectar con el servidor.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function importService(id, btn) {
|
||||
const originalContent = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
||||
lucide.createIcons();
|
||||
|
||||
log(`Importando servicio ID ${id}...`);
|
||||
// 2. IMPORTAR SERVICIO AL CRM
|
||||
async function importService(id) {
|
||||
if (!confirm("¿Importar este servicio a tu CRM usando tus reglas de mapeo?")) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/providers/import/${id}`, {
|
||||
method: 'POST',
|
||||
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
||||
headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.ok) {
|
||||
log(`✅ Servicio importado con éxito.`, "success");
|
||||
showToast("Servicio importado al CRM");
|
||||
|
||||
// Animación de salida
|
||||
const card = btn.closest('.bg-white');
|
||||
card.style.transform = "translateX(100px)";
|
||||
card.style.opacity = "0";
|
||||
setTimeout(() => {
|
||||
alert("✅ Servicio importado correctamente.");
|
||||
loadScrapedServices(); // Recargar lista
|
||||
}, 300);
|
||||
} else {
|
||||
log(`❌ Error al importar: ${data.error}`, "error");
|
||||
showToast("Error: " + data.error, true);
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalContent;
|
||||
alert("❌ Error: " + data.error);
|
||||
}
|
||||
} catch (e) {
|
||||
log(`❌ Error de conexión al importar.`, "error");
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalContent;
|
||||
alert("Error en la conexión.");
|
||||
}
|
||||
}
|
||||
|
||||
function showToast(msg, isError = false) {
|
||||
const t = document.getElementById('toast'), m = document.getElementById('toastMsg');
|
||||
t.className = `fixed bottom-5 right-5 px-6 py-3 rounded-lg shadow-xl transition-all duration-300 z-50 flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white font-medium`;
|
||||
m.innerText = msg; t.classList.remove('translate-y-20', 'opacity-0');
|
||||
setTimeout(() => t.classList.add('translate-y-20', 'opacity-0'), 3000);
|
||||
}
|
||||
</script>
|
||||
// Inicializar al cargar
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
loadScrapedServices();
|
||||
// Aquí podrías cargar también las credenciales si quieres el panel completo
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user