Actualizar automatizaciones.html

This commit is contained in:
2026-02-13 21:41:27 +00:00
parent af36e41bd0
commit a14a12fefe

View File

@@ -4,238 +4,244 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Automatizaciones - IntegraRepara</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">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
/* Estilos críticos para que encaje con el sidebar de Integra Repara */
body { background-color: #f8fafc; overflow-x: hidden; }
/* Contenedor principal que deja espacio a la barra lateral */
#main-content {
margin-left: 260px; /* Ancho exacto de tu sidebar azul */
padding: 2rem;
margin-top: 60px; /* Espacio para la cabecera superior */
min-height: calc(100vh - 60px);
transition: all 0.3s ease;
}
.service-card {
border: none;
border-radius: 12px;
background: white;
border-left: 5px solid #22c55e;
margin-bottom: 1rem;
transition: transform 0.2s;
}
.service-card:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.05); }
.badge-provider { font-weight: 800; font-size: 0.7rem; padding: 4px 10px; border-radius: 20px; text-transform: uppercase; }
.multiasistencia { background: #dbeafe; color: #1e40af; }
.homeserve { background: #fee2e2; color: #991b1b; }
/* Ajuste para móviles: el margen desaparece si el menú se oculta */
@media (max-width: 992px) {
#main-content { margin-left: 0; padding: 1rem; }
}
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.service-card { transition: all 0.2s ease; }
.service-card:hover { transform: translateY(-2px); }
</style>
</head>
<body>
<body class="bg-gray-50 text-gray-800 font-sans h-screen overflow-hidden flex">
<div id="layout-header"></div>
<div id="layout-sidebar"></div>
<div id="sidebar-container" class="h-full shrink-0"></div>
<div id="main-content">
<div class="container-fluid">
<div class="row mb-4">
<div class="col-md-8">
<h2 class="fw-bold mb-0">🤖 Buzón de Automatizaciones</h2>
<p class="text-muted">Revisa, edita e importa los servicios detectados.</p>
<div class="flex-1 flex flex-col h-full relative min-w-0">
<div id="header-container"></div>
<main class="flex-1 overflow-hidden flex flex-col relative">
<div class="bg-white border-b border-gray-200 p-4 shrink-0 z-10 shadow-sm">
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div>
<h2 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
<i data-lucide="bot" class="text-blue-600"></i> Buzón de Automatizaciones
</h2>
<p class="text-xs text-gray-500 mt-1">Revisa e importa servicios detectados por Multiasistencia y HomeServe.</p>
</div>
<div class="col-md-4 text-end">
<button onclick="loadInbox()" class="btn btn-primary rounded-pill px-4 shadow-sm">
<i class="fas fa-sync-alt me-2"></i>Actualizar Buzón
<button onclick="loadInbox()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition-colors shadow-lg shadow-blue-100">
<i data-lucide="refresh-cw" class="w-4 h-4"></i> Actualizar Buzón
</button>
</div>
</div>
<div id="inboxContainer">
<div class="text-center py-5">
<div class="spinner-border text-primary"></div>
<p class="mt-2">Conectando con los robots...</p>
</div>
</div>
<div class="flex-1 overflow-y-auto p-6 space-y-4" id="inboxContainer">
<div class="flex flex-col items-center justify-center py-20 text-gray-400">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mb-4"></div>
<p>Sincronizando con los robots...</p>
</div>
</div>
<div class="modal fade" id="editImportModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content border-0 shadow-lg">
<div class="modal-header bg-dark text-white p-4">
<h5 class="modal-title fw-bold"><i class="fas fa-edit me-2"></i>Validar Datos del Servicio</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</main>
</div>
<div class="modal-body p-4">
<form id="importForm" class="row g-3">
<input type="hidden" id="scrapedId">
<div class="col-md-7">
<label class="form-label small fw-bold">NOMBRE COMPLETO</label>
<input type="text" id="imp_name" class="form-control border-2">
<div id="importModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center backdrop-blur-sm">
<div class="bg-white rounded-xl shadow-2xl w-full max-w-lg p-6 animate-slide-in flex flex-col max-h-[90vh] overflow-y-auto">
<div class="flex justify-between items-center mb-4 border-b pb-2">
<h3 class="text-lg font-bold text-gray-800 flex items-center gap-2">
<i data-lucide="file-check" class="text-green-600"></i> Validar Datos de Importación
</h3>
<button onclick="closeModal()" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-5 h-5"></i></button>
</div>
<div class="col-md-5">
<label class="form-label small fw-bold">TELÉFONO</label>
<input type="text" id="imp_phone" class="form-control border-2">
<form id="importForm" onsubmit="handleFinalImport(event)" class="space-y-4">
<input type="hidden" id="impScrapedId">
<div class="grid grid-cols-2 gap-3">
<div class="col-span-2">
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Nombre del Cliente</label>
<input type="text" id="impName" required class="w-full border p-2 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div class="col-md-12">
<label class="form-label small fw-bold">DIRECCIÓN COMPLETA</label>
<div class="input-group">
<span class="input-group-text bg-white border-2"><i class="fas fa-map-marker-alt text-primary"></i></span>
<input type="text" id="imp_address" class="form-control border-2">
<div>
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Teléfono</label>
<input type="text" id="impPhone" required class="w-full border p-2 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div>
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Compañía</label>
<input type="text" id="impCompany" class="w-full border p-2 rounded-lg text-sm bg-gray-50 font-medium" readonly>
</div>
</div>
<div class="col-md-12">
<label class="form-label small fw-bold">DESCRIPCIÓN DE LA AVERÍA</label>
<textarea id="imp_description" class="form-control border-2" rows="5"></textarea>
<div>
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Dirección Completa</label>
<div class="relative">
<i data-lucide="map-pin" class="w-4 h-4 absolute left-3 top-2.5 text-gray-400"></i>
<input type="text" id="impAddress" required class="w-full border pl-9 pr-3 py-2 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="col-md-4">
<label class="form-label small fw-bold">EXPEDIENTE REF.</label>
<input type="text" id="imp_ref" class="form-control bg-light" readonly>
</div>
<div class="col-md-4">
<label class="form-label small fw-bold">COMPAÑÍA ORIGEN</label>
<input type="text" id="imp_company" class="form-control bg-light" readonly>
<div>
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Descripción de la Avería</label>
<textarea id="impDesc" rows="4" class="w-full border p-2 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none" placeholder="Detalles extraídos por el robot..."></textarea>
</div>
<div class="col-md-4">
<label class="form-label small fw-bold">TIPO AVISO</label>
<select id="imp_urgent" class="form-select border-2">
<option value="false">Servicio Normal</option>
<option value="true">🚨 URGENTE</option>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Referencia Externa</label>
<input type="text" id="impRef" class="w-full border p-2 rounded-lg text-sm bg-gray-50" readonly>
</div>
<div>
<label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Prioridad</label>
<select id="impUrgent" class="w-full border p-2 rounded-lg text-sm bg-white outline-none">
<option value="false">Normal</option>
<option value="true">🚨 Urgente</option>
</select>
</div>
</div>
<div class="pt-4">
<button type="submit" class="w-full bg-green-600 text-white px-4 py-3 rounded-xl text-sm font-bold hover:bg-green-700 shadow-lg shadow-green-100 flex items-center justify-center gap-2 transition-all">
<i data-lucide="save" class="w-4 h-4"></i> CONFIRMAR Y GUARDAR EN CRM
</button>
</div>
</form>
</div>
<div class="modal-footer bg-light p-3">
<button type="button" class="btn btn-secondary rounded-pill px-4" data-bs-dismiss="modal">Cerrar</button>
<button onclick="saveToCRM()" class="btn btn-success rounded-pill px-5 fw-bold shadow">
<i class="fas fa-save me-2"></i>CONFIRMAR E IMPORTAR
</button>
</div>
</div>
</div>
</div>
<script src="./js/layout.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<div id="toast" class="fixed bottom-5 right-5 bg-slate-800 text-white px-6 py-3 rounded-lg shadow-2xl hidden z-[100] translate-y-0 transition-all duration-300">
<span id="toastMsg"></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";
await loadInbox();
lucide.createIcons();
});
async function loadInbox() {
const container = document.getElementById('inboxContainer');
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')}` }})
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 (!svcData.services || svcData.services.length === 0) {
container.innerHTML = '<div class="alert alert-light text-center py-5 border-dashed">No hay nuevos expedientes detectados por el robot.</div>';
if (allScraped.length === 0) {
container.innerHTML = `
<div class="flex flex-col items-center justify-center py-20 text-gray-400 bg-white rounded-xl border-2 border-dashed">
<i data-lucide="check-circle" class="w-12 h-12 mb-2 text-green-500"></i>
<p class="font-medium">No hay servicios nuevos pendientes.</p>
</div>`;
lucide.createIcons();
return;
}
container.innerHTML = '';
svcData.services.forEach(svc => {
allScraped.forEach(svc => {
const raw = svc.raw_data || {};
const myMap = globalMappings.filter(m => m.provider === svc.provider);
// Mapeo dinámico para el listado
const name = raw[myMap.find(m => m.target_key === 'clientName')?.original_key] || "No detectado";
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 div = document.createElement('div');
div.innerHTML = `
<div class="service-card shadow-sm p-4 d-flex justify-content-between align-items-center">
<div class="row w-100 align-items-center">
<div class="col-md-2 border-end">
<span class="badge-provider ${svc.provider}">${svc.provider}</span>
<div class="small fw-bold mt-2 text-primary">#${svc.service_ref}</div>
const card = document.createElement('div');
card.className = "service-card bg-white p-4 rounded-xl border border-gray-200 shadow-sm flex items-center gap-4 fade-in";
card.innerHTML = `
<div class="w-20 h-20 rounded-lg 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-[10px] font-black uppercase tracking-tighter">${svc.provider}</span>
<i data-lucide="${svc.provider === 'homeserve' ? 'home' : 'briefcase'}" class="w-6 h-6 my-1"></i>
<span class="text-[10px] font-bold">#${svc.service_ref.slice(-4)}</span>
</div>
<div class="col-md-3">
<div class="small text-muted fw-bold">CLIENTE</div>
<div class="fw-bold text-uppercase">${name}</div>
<div class="flex-1 min-w-0">
<h4 class="font-bold text-gray-900 truncate">${name}</h4>
<p class="text-xs text-gray-500 flex items-center gap-1 mt-0.5 truncate"><i data-lucide="map-pin" class="w-3 h-3"></i> ${addr}</p>
<div class="flex gap-2 mt-2">
<span class="text-[10px] bg-gray-100 px-2 py-0.5 rounded font-bold text-gray-600"><i data-lucide="phone" class="w-2.5 h-2.5 inline mr-1"></i>${phone}</span>
</div>
<div class="col-md-4">
<div class="small text-muted fw-bold">UBICACIÓN</div>
<div class="text-truncate" title="${addr}">${addr}</div>
</div>
<div class="col-md-2 text-center">
<div class="small text-muted fw-bold">TELÉFONO</div>
<div class="badge bg-light text-dark border">${phone}</div>
</div>
<div class="col-md-1 text-end">
<button onclick="editAndImport(${svc.id}, '${svc.provider}')" class="btn btn-success rounded-circle shadow">
<i class="fas fa-check"></i>
<button onclick="openEditor(${svc.id})" class="bg-white border-2 border-green-500 text-green-600 p-3 rounded-full hover:bg-green-50 transition-colors shadow-sm shadow-green-50">
<i data-lucide="check" class="w-6 h-6"></i>
</button>
</div>
</div>
</div>
`;
container.appendChild(div);
container.appendChild(card);
});
lucide.createIcons();
} catch (e) {
container.innerHTML = '<div class="alert alert-danger">Error de conexión con el servidor Integra Repara.</div>';
showToast("Error al cargar datos", true);
}
}
async function editAndImport(scrapedId, provider) {
const res = await fetch(`${API_URL}/providers/scraped`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }});
const data = await res.json();
const svc = data.services.find(s => s.id === scrapedId);
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 === provider);
const myMap = globalMappings.filter(m => m.provider === svc.provider);
// Rellenar formulario modal con los datos mapeados
document.getElementById('scrapedId').value = scrapedId;
document.getElementById('imp_name').value = raw[myMap.find(m => m.target_key === 'clientName')?.original_key] || "";
document.getElementById('imp_phone').value = raw[myMap.find(m => m.target_key === 'phone')?.original_key] || raw['Teléfono'] || "";
document.getElementById('imp_address').value = raw[myMap.find(m => m.target_key === 'address')?.original_key] || "";
document.getElementById('imp_ref').value = svc.service_ref;
document.getElementById('imp_company').value = raw[myMap.find(m => m.target_key === 'compania')?.original_key] || provider.toUpperCase();
document.getElementById('imp_description').value = raw[myMap.find(m => m.target_key === 'descripcion')?.original_key] || raw['Descripción'] || "";
document.getElementById('imp_urgent').value = (raw['Urgente'] === 'Sí').toString();
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();
new bootstrap.Modal(document.getElementById('editImportModal')).show();
document.getElementById('importModal').classList.remove('hidden');
lucide.createIcons();
}
async function saveToCRM() {
const id = document.getElementById('scrapedId').value;
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('imp_name').value,
phone: document.getElementById('imp_phone').value,
address: document.getElementById('imp_address').value,
description: document.getElementById('imp_description').value,
company_ref: document.getElementById('imp_ref').value,
is_urgent: document.getElementById('imp_urgent').value === 'true'
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 ((await res.json()).ok) {
bootstrap.Modal.getInstance(document.getElementById('editImportModal')).hide();
if (res.ok) {
showToast("✅ Servicio importado al CRM");
closeModal();
loadInbox();
alert("✅ Expediente importado y guardado en Servicios.");
} else {
showToast("Error al importar", true);
}
} catch (e) { showToast("Error de conexión", true); }
}
document.addEventListener('DOMContentLoaded', loadInbox);
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-2xl z-[100] flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white font-medium`;
m.innerText = msg; t.classList.remove('hidden');
setTimeout(() => t.classList.add('hidden'), 3000);
}
</script>
</body>
</html>