Files
web/automatizaciones.html

269 lines
16 KiB
HTML

<!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; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
/* Forzamos el ancho del sidebar para que no colapse */
#layout-sidebar { width: 260px; height: 100vh; shrink: 0; }
.service-card { transition: all 0.2s ease; border-left-width: 6px; }
.service-card:hover { transform: translateY(-2px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); }
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans h-screen overflow-hidden flex">
<div id="layout-sidebar" class="h-full"></div>
<div class="flex-1 flex flex-col h-full relative min-w-0">
<div id="layout-header"></div>
<main class="flex-1 overflow-hidden flex flex-col relative">
<div class="bg-white border-b border-gray-200 p-6 shrink-0 shadow-sm z-10">
<div class="flex flex-col md:flex-row justify-between items-center gap-4">
<div>
<h2 class="text-2xl font-extrabold text-gray-800 flex items-center gap-3">
<span class="bg-blue-600 p-2 rounded-lg text-white">
<i data-lucide="bot" class="w-6 h-6"></i>
</span>
Buzón de Automatizaciones
</h2>
<p class="text-sm text-gray-500 mt-1">Valida e importa los expedientes capturados por los robots.</p>
</div>
<button onclick="loadInbox()" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 transition-all shadow-lg shadow-blue-200 active:scale-95">
<i data-lucide="refresh-cw" class="w-4 h-4"></i> Actualizar Listado
</button>
</div>
</div>
<div class="flex-1 overflow-y-auto p-6 space-y-4 bg-slate-50/50" id="inboxContainer">
</div>
</main>
</div>
<div id="importModal" class="fixed inset-0 bg-slate-900/60 hidden z-[999] flex items-center justify-center backdrop-blur-md p-4">
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden animate-slide-in flex flex-col max-h-[95vh]">
<div class="bg-slate-800 text-white p-6 flex justify-between items-center">
<div>
<h3 class="text-xl font-bold flex items-center gap-2">
<i data-lucide="file-edit" class="text-blue-400"></i> Revisar Expediente
</h3>
<p class="text-slate-400 text-xs mt-1">Verifica la información antes de enviarla al CRM.</p>
</div>
<button onclick="closeModal()" class="text-slate-400 hover:text-white transition-colors">
<i data-lucide="x" class="w-6 h-6"></i>
</button>
</div>
<form id="importForm" onsubmit="handleFinalImport(event)" class="p-8 space-y-6 overflow-y-auto">
<input type="hidden" id="impScrapedId">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Nombre del Cliente</label>
<input type="text" id="impName" required class="w-full border-2 border-slate-100 bg-slate-50 p-3 rounded-xl text-sm focus:border-blue-500 focus:bg-white outline-none transition-all">
</div>
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Teléfono Principal</label>
<input type="text" id="impPhone" required class="w-full border-2 border-slate-100 bg-slate-50 p-3 rounded-xl text-sm focus:border-blue-500 focus:bg-white outline-none transition-all">
</div>
</div>
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Dirección de Trabajo</label>
<div class="relative">
<i data-lucide="map-pin" class="w-4 h-4 absolute left-4 top-3.5 text-slate-400"></i>
<input type="text" id="impAddress" required class="w-full border-2 border-slate-100 bg-slate-50 pl-11 pr-4 py-3 rounded-xl text-sm focus:border-blue-500 focus:bg-white outline-none transition-all">
</div>
</div>
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Descripción de Daños / Trabajos</label>
<textarea id="impDesc" rows="5" class="w-full border-2 border-slate-100 bg-slate-50 p-4 rounded-xl text-sm focus:border-blue-500 focus:bg-white outline-none transition-all" placeholder="Escribe aquí los detalles..."></textarea>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Ref. Robot</label>
<input type="text" id="impRef" class="w-full border-2 border-slate-100 bg-slate-100 p-3 rounded-xl text-sm font-bold text-slate-600" readonly>
</div>
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Proveedor</label>
<input type="text" id="impCompany" class="w-full border-2 border-slate-100 bg-slate-100 p-3 rounded-xl text-sm font-bold text-slate-600" readonly>
</div>
<div class="space-y-1">
<label class="text-[11px] font-black text-slate-500 uppercase tracking-wider">Urgencia</label>
<select id="impUrgent" class="w-full border-2 border-slate-100 bg-white p-3 rounded-xl text-sm font-bold outline-none focus:border-blue-500 transition-all">
<option value="false">Servicio Normal</option>
<option value="true">⚠️ URGENTE</option>
</select>
</div>
</div>
<div class="pt-4">
<button type="submit" class="w-full bg-emerald-600 text-white py-4 rounded-2xl font-black text-sm hover:bg-emerald-700 shadow-xl shadow-emerald-100 flex items-center justify-center gap-3 transition-all active:scale-95">
<i data-lucide="cloud-upload" class="w-5 h-5"></i> IMPORTAR AL CRM AHORA
</button>
</div>
</form>
</div>
</div>
<div id="toast" class="fixed bottom-8 right-8 bg-slate-900 text-white px-8 py-4 rounded-2xl shadow-2xl hidden z-[1000] border border-slate-700 animate-bounce-in">
<span id="toastMsg" class="font-bold text-sm"></span>
</div>
<script src="js/layout.js"></script>
<script>
let globalMappings = [];
let allScraped = [];
document.addEventListener('DOMContentLoaded', async () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
// Damos un pequeño tiempo para que layout.js termine de pintar
setTimeout(() => {
loadInbox();
lucide.createIcons();
}, 100);
});
async function loadInbox() {
const container = document.getElementById('inboxContainer');
container.innerHTML = '<div class="flex flex-col items-center justify-center py-20 text-blue-600"><div class="animate-spin rounded-full h-10 w-10 border-b-2 border-current mb-4"></div><p class="font-bold text-slate-400">Leyendo a los robots...</p></div>';
try {
const [svcRes, mapRes] = await Promise.all([
fetch(`${API_URL}/providers/scraped`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }),
fetch(`${API_URL}/discovery/mappings`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } })
]);
const svcData = await svcRes.json();
globalMappings = await mapRes.json();
allScraped = svcData.services || [];
if (allScraped.length === 0) {
container.innerHTML = `<div class="bg-white p-12 rounded-3xl border-2 border-dashed border-slate-200 text-center flex flex-col items-center">
<div class="bg-green-50 text-green-500 p-4 rounded-full mb-4"><i data-lucide="check-circle-2" class="w-10 h-10"></i></div>
<h3 class="text-xl font-black text-slate-800">¡Buzón Limpio!</h3>
<p class="text-slate-400 mt-2">No hay nuevos expedientes para procesar.</p>
</div>`;
lucide.createIcons();
return;
}
container.innerHTML = '';
allScraped.forEach(svc => {
const raw = svc.raw_data || {};
const myMap = globalMappings.filter(m => m.provider === svc.provider);
const name = raw[myMap.find(m => m.target_key === 'clientName')?.original_key] || "Nombre no identificado";
const addr = raw[myMap.find(m => m.target_key === 'address')?.original_key] || "Sin dirección";
const phone = raw[myMap.find(m => m.target_key === 'phone')?.original_key] || raw['Teléfono'] || "S/T";
const card = document.createElement('div');
card.className = "service-card bg-white p-5 rounded-2xl border border-slate-200 flex items-center gap-6 fade-in shadow-sm";
card.style.borderLeftColor = svc.provider === 'homeserve' ? '#ef4444' : '#3b82f6';
card.innerHTML = `
<div class="w-20 h-20 rounded-2xl flex flex-col items-center justify-center shrink-0 ${svc.provider === 'homeserve' ? 'bg-red-50 text-red-600' : 'bg-blue-50 text-blue-600'}">
<span class="text-[9px] font-black uppercase tracking-widest mb-1">${svc.provider}</span>
<i data-lucide="${svc.provider === 'homeserve' ? 'home' : 'briefcase'}" class="w-7 h-7"></i>
<span class="text-[10px] font-black mt-1">#${svc.service_ref.slice(-4)}</span>
</div>
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<h4 class="font-black text-slate-800 text-lg truncate">${name}</h4>
${svc.raw_data.Urgente === 'Sí' ? '<span class="bg-red-100 text-red-600 text-[9px] font-black px-2 py-0.5 rounded-full">URGENTE</span>' : ''}
</div>
<p class="text-sm text-slate-500 flex items-center gap-1.5 mt-1 truncate">
<i data-lucide="map-pin" class="w-3.5 h-3.5 text-slate-400"></i> ${addr}
</p>
<div class="flex gap-3 mt-3">
<span class="flex items-center gap-1.5 text-xs font-bold text-slate-600 bg-slate-100 px-3 py-1 rounded-lg">
<i data-lucide="phone" class="w-3 h-3 text-slate-400"></i> ${phone}
</span>
<span class="text-xs font-bold text-slate-400 flex items-center gap-1.5">
<i data-lucide="clock" class="w-3 h-3"></i> Detectado: ${new Date(svc.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
</span>
</div>
</div>
<button onclick="openEditor(${svc.id})" class="bg-emerald-500 hover:bg-emerald-600 text-white p-4 rounded-2xl shadow-lg shadow-emerald-100 transition-all active:scale-90">
<i data-lucide="arrow-right-circle" class="w-7 h-7"></i>
</button>
`;
container.appendChild(card);
});
lucide.createIcons();
} catch (e) {
showToast("Error al conectar con la API", true);
}
}
function openEditor(scrapedId) {
const svc = allScraped.find(s => s.id === scrapedId);
if (!svc) return;
const raw = svc.raw_data;
const myMap = globalMappings.filter(m => m.provider === svc.provider);
document.getElementById('impScrapedId').value = scrapedId;
document.getElementById('impName').value = raw[myMap.find(m => m.target_key === 'clientName')?.original_key] || "";
document.getElementById('impPhone').value = raw[myMap.find(m => m.target_key === 'phone')?.original_key] || raw['Teléfono'] || "";
document.getElementById('impAddress').value = raw[myMap.find(m => m.target_key === 'address')?.original_key] || "";
document.getElementById('impRef').value = svc.service_ref;
document.getElementById('impCompany').value = raw[myMap.find(m => m.target_key === 'compania')?.original_key] || svc.provider.toUpperCase();
document.getElementById('impDesc').value = raw[myMap.find(m => m.target_key === 'descripcion')?.original_key] || raw['Descripción'] || "";
document.getElementById('impUrgent').value = (raw['Urgente'] === 'Sí' || raw['Urgente'] === 'true').toString();
document.getElementById('importModal').classList.remove('hidden');
lucide.createIcons();
}
function closeModal() { document.getElementById('importModal').classList.add('hidden'); }
async function handleFinalImport(e) {
e.preventDefault();
const id = document.getElementById('impScrapedId').value;
const payload = {
name: document.getElementById('impName').value,
phone: document.getElementById('impPhone').value,
address: document.getElementById('impAddress').value,
description: document.getElementById('impDesc').value,
company_ref: document.getElementById('impRef').value,
is_urgent: document.getElementById('impUrgent').value === 'true'
};
try {
const res = await fetch(`${API_URL}/providers/import/${id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` },
body: JSON.stringify(payload)
});
if (res.ok) {
showToast("🚀 ¡Expediente enviado al CRM!");
closeModal();
loadInbox();
} else {
showToast("Error al guardar", true);
}
} catch (e) { showToast("Error de conexión", true); }
}
function showToast(msg, isError = false) {
const t = document.getElementById('toast'), m = document.getElementById('toastMsg');
t.className = `fixed bottom-8 right-8 px-8 py-4 rounded-2xl shadow-2xl z-[1000] flex items-center gap-3 transition-all ${isError ? 'bg-red-600' : 'bg-slate-900'} text-white border border-white/10`;
m.innerText = msg; t.classList.remove('hidden');
setTimeout(() => t.classList.add('hidden'), 4000);
}
</script>
</body>
</html>