Añadir automatizaciones.html

This commit is contained in:
2026-02-12 23:10:48 +00:00
parent 1ae1328390
commit 26999a6fa5

310
automatizaciones.html Normal file
View File

@@ -0,0 +1,310 @@
<!DOCTYPE html>
<html lang="es">
<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>
<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; }
</style>
</head>
<body class="bg-gray-100 text-gray-800 font-sans h-screen overflow-hidden flex">
<div id="sidebar-container" class="h-full shrink-0"></div>
<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>
<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
</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>
</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) ---
async function loadScrapedServices() {
const list = document.getElementById('inboxList');
try {
const res = await fetch(`${API_URL}/providers/scraped`, {
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();
return;
}
list.innerHTML = "";
services.forEach(s => {
const info = s.raw_data;
const isMulti = s.provider === 'multiasistencia';
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>
</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>
</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
</button>
</div>
`;
list.appendChild(el);
});
lucide.createIcons();
} catch(e) { console.error(e); }
}
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}...`);
try {
const res = await fetch(`${API_URL}/providers/import/${id}`, {
method: 'POST',
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(() => {
loadScrapedServices(); // Recargar lista
}, 300);
} else {
log(`❌ Error al importar: ${data.error}`, "error");
showToast("Error: " + data.error, true);
btn.disabled = false;
btn.innerHTML = originalContent;
}
} catch (e) {
log(`❌ Error de conexión al importar.`, "error");
btn.disabled = false;
btn.innerHTML = originalContent;
}
}
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>
</body>
</html>