Actualizar automatizaciones.html

This commit is contained in:
2026-02-15 20:04:33 +00:00
parent 9d8fe96aff
commit c16115dddb

View File

@@ -29,7 +29,7 @@
</div>
<div class="bg-blue-100 text-blue-700 px-4 py-2 rounded-lg flex items-center gap-2 font-bold text-sm">
<i data-lucide="refresh-cw" class="w-4 h-4 animate-spin"></i>
Actualizando cada 30s
En Vivo
</div>
</div>
@@ -49,8 +49,7 @@
<th class="p-4 text-right">Acción</th>
</tr>
</thead>
<tbody id="failed-list" class="divide-y divide-gray-50 text-sm">
</tbody>
<tbody id="failed-list" class="divide-y divide-gray-50 text-sm"></tbody>
</table>
</div>
</div>
@@ -62,111 +61,144 @@
<script src="js/layout.js"></script>
<script>
const API_URL = "https://integrarepara-api.integrarepara.es"; // Cambia a tu URL real
const API_URL = "https://integrarepara-api.integrarepara.es";
let activeIntervals = [];
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; }
loadAutomations();
setInterval(loadAutomations, 30000); // Recarga cada 30 seg
setInterval(loadAutomations, 20000); // Recarga datos del servidor cada 20s
});
async function loadAutomations() {
try {
// Obtenemos los servicios en estado 'in_progress' o 'failed'
const res = await fetch(`${API_URL}/providers/scraped`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
// Limpiamos intervalos antiguos para no saturar memoria
activeIntervals.forEach(clearInterval);
activeIntervals = [];
renderCards(data.services.filter(s => s.automation_status === 'in_progress'));
renderFailedTable(data.services.filter(s => s.automation_status === 'failed'));
}
} catch (e) { console.error(e); }
}
function renderCards(activeServices) {
const container = document.getElementById('automation-list');
if (activeServices.length === 0) {
container.innerHTML = `<div class="col-span-full py-12 text-center border-2 border-dashed border-gray-200 rounded-2xl">
<i data-lucide="ghost" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i>
<p class="text-gray-400 font-bold uppercase text-xs">No hay automatismos en curso</p>
</div>`;
lucide.createIcons();
return;
}
function renderCards(activeServices) {
const container = document.getElementById('automation-list');
if (activeServices.length === 0) {
container.innerHTML = `<div class="col-span-full py-12 text-center border-2 border-dashed border-gray-200 rounded-2xl">
<i data-lucide="ghost" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i>
<p class="text-gray-400 font-bold uppercase text-xs">No hay automatismos en curso</p>
</div>`;
lucide.createIcons();
return;
}
container.innerHTML = activeServices.map(s => {
const raw = s.raw_data;
// Calculamos el tiempo restante para la barra de progreso
const now = new Date();
const expires = new Date(s.token_expires_at);
const diff = Math.max(0, Math.floor((expires - now) / 1000));
const percent = Math.min(100, (diff / 300) * 100); // 300 seg = 5 min
container.innerHTML = activeServices.map(s => {
const raw = s.raw_data;
const cardId = `card-${s.id}`;
return `
<div class="bg-white rounded-2xl border-2 border-blue-50 shadow-sm overflow-hidden flex flex-col fade-in">
<div class="p-5 border-b border-gray-50 bg-blue-50/30">
<div class="flex justify-between items-start mb-2">
<span class="text-[10px] font-black bg-blue-600 text-white px-2 py-0.5 rounded uppercase">${s.provider}</span>
<span class="text-xs font-black text-blue-600">Ref: ${s.service_ref}</span>
</div>
<h4 class="font-black text-slate-800 uppercase truncate">${raw["Nombre Cliente"] || raw["CLIENTE"] || 'Sin nombre'}</h4>
<p class="text-[10px] text-gray-500 font-bold uppercase tracking-tighter">📍 CP: ${raw["Código Postal"] || raw["C.P."] || '---'}</p>
</div>
<div class="p-5 flex-1 space-y-4">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600">
<i data-lucide="user"></i>
return `
<div id="${cardId}" class="bg-white rounded-2xl border-2 border-blue-50 shadow-sm overflow-hidden flex flex-col fade-in">
<div class="p-5 border-b border-gray-50 bg-blue-50/30 text-left">
<div class="flex justify-between items-start mb-2">
<span class="text-[10px] font-black bg-blue-600 text-white px-2 py-0.5 rounded uppercase">${s.provider}</span>
<span class="text-xs font-black text-blue-600">Ref: ${s.service_ref}</span>
</div>
<h4 class="font-black text-slate-800 uppercase truncate">${raw["Nombre Cliente"] || raw["CLIENTE"] || 'Sin nombre'}</h4>
<p class="text-[10px] text-gray-500 font-bold uppercase tracking-tighter">📍 CP: ${raw["Código Postal"] || raw["C.P."] || '---'}</p>
</div>
<div>
<p class="text-[10px] text-gray-400 font-bold uppercase leading-none">Turno actual:</p>
<p class="font-black text-slate-700 uppercase">${s.current_worker_name || 'Buscando...'}</p>
<div class="p-5 flex-1 space-y-4 text-left">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600">
<i data-lucide="user"></i>
</div>
<div>
<p class="text-[10px] text-gray-400 font-bold uppercase leading-none">Turno actual:</p>
<p class="font-black text-slate-700 uppercase">${s.current_worker_name || 'Buscando...'}</p>
</div>
</div>
<div class="space-y-1">
<div class="flex justify-between text-[10px] font-bold uppercase tracking-widest text-blue-500">
<span>Caduca en</span>
<span id="timer-${s.id}">--:--</span>
</div>
<div class="w-full bg-gray-100 h-1.5 rounded-full overflow-hidden">
<div id="progress-${s.id}" class="bg-blue-500 h-full progress-bar" style="width: 100%"></div>
</div>
</div>
</div>
<div class="p-3 bg-gray-50 flex gap-2">
<button onclick="stopAutomation(${s.id})" class="flex-1 bg-white border border-red-200 text-red-500 py-2 rounded-lg text-[10px] font-black uppercase hover:bg-red-50 transition-colors">
Abortar Rueda
</button>
</div>
</div>
`;
}).join('');
<div class="space-y-1">
<div class="flex justify-between text-[10px] font-bold uppercase tracking-widest text-blue-500">
<span>Respuesta en</span>
<span>${Math.floor(diff / 60)}m ${diff % 60}s</span>
</div>
<div class="w-full bg-gray-100 h-1.5 rounded-full overflow-hidden">
<div class="bg-blue-500 h-full progress-bar" style="width: ${percent}%"></div>
</div>
</div>
</div>
// Iniciar contadores dinámicos
activeServices.forEach(s => {
startLocalTimer(s.id, s.token_expires_at);
});
<div class="p-3 bg-gray-50 flex gap-2">
<button onclick="stopAutomation(${s.id})" class="flex-1 bg-white border border-red-200 text-red-500 py-2 rounded-lg text-[10px] font-black uppercase hover:bg-red-50 transition-colors">
Abortar Rueda
</button>
</div>
</div>
`;
}).join('');
lucide.createIcons();
}
lucide.createIcons();
}
function startLocalTimer(id, expiryDate) {
if(!expiryDate) return;
const timerEl = document.getElementById(`timer-${id}`);
const progressEl = document.getElementById(`progress-${id}`);
const update = () => {
const now = new Date().getTime();
const distance = new Date(expiryDate).getTime() - now;
if (distance < 0) {
timerEl.innerText = "EXPIRADO";
progressEl.style.width = "0%";
return;
}
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
timerEl.innerText = `${minutes}m ${seconds}s`;
// Asumimos turnos de 5 minutos (300 segundos) para el porcentaje
const percent = (distance / (5 * 60 * 1000)) * 100;
progressEl.style.width = `${percent}%`;
};
update();
const interval = setInterval(update, 1000);
activeIntervals.push(interval);
}
function renderFailedTable(failedServices) {
const tbody = document.getElementById('failed-list');
tbody.innerHTML = failedServices.map(s => {
return `
<tr class="hover:bg-red-50/30 transition">
<tr class="hover:bg-red-50/30 transition text-left">
<td class="p-4 font-bold text-slate-700">${s.service_ref}</td>
<td class="p-4 text-xs font-medium text-gray-500">CP: ${s.raw_data["Código Postal"]}</td>
<td class="p-4 text-xs font-medium text-gray-500">CP: ${s.raw_data["Código Postal"] || '---'}</td>
<td class="p-4"><span class="text-[10px] font-black text-red-500 uppercase bg-red-100 px-2 py-0.5 rounded">Nadie respondió</span></td>
<td class="p-4 text-right">
<button onclick="window.location.href='proveedores.html'" class="text-blue-600 font-black text-[10px] uppercase hover:underline">Asignar Manual</button>
<button onclick="window.location.href='validar.html'" class="text-blue-600 font-black text-[10px] uppercase hover:underline">Asignar Manual</button>
</td>
</tr>
`;
</tr>`;
}).join('');
}
async function stopAutomation(id) {
if(!confirm("¿Seguro que quieres detener el proceso automático para este servicio?")) return;
if(!confirm("¿Seguro que quieres detener el proceso automático?")) return;
try {
// Endpoint para volver el estado a manual
const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: {
@@ -175,7 +207,7 @@ function renderCards(activeServices) {
},
body: JSON.stringify({ automation_status: 'manual' })
});
if (await res.json()) {
if (res.ok) {
showToast("Proceso detenido");
loadAutomations();
}