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>
<div class="bg-blue-100 text-blue-700 px-4 py-2 rounded-lg flex items-center gap-2 font-bold text-sm"> <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> <i data-lucide="refresh-cw" class="w-4 h-4 animate-spin"></i>
Actualizando cada 30s En Vivo
</div> </div>
</div> </div>
@@ -49,8 +49,7 @@
<th class="p-4 text-right">Acción</th> <th class="p-4 text-right">Acción</th>
</tr> </tr>
</thead> </thead>
<tbody id="failed-list" class="divide-y divide-gray-50 text-sm"> <tbody id="failed-list" class="divide-y divide-gray-50 text-sm"></tbody>
</tbody>
</table> </table>
</div> </div>
</div> </div>
@@ -62,29 +61,33 @@
<script src="js/layout.js"></script> <script src="js/layout.js"></script>
<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", () => { document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; } if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; }
loadAutomations(); loadAutomations();
setInterval(loadAutomations, 30000); // Recarga cada 30 seg setInterval(loadAutomations, 20000); // Recarga datos del servidor cada 20s
}); });
async function loadAutomations() { async function loadAutomations() {
try { try {
// Obtenemos los servicios en estado 'in_progress' o 'failed'
const res = await fetch(`${API_URL}/providers/scraped`, { 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(); const data = await res.json();
if (data.ok) { if (data.ok) {
// Limpiamos intervalos antiguos para no saturar memoria
activeIntervals.forEach(clearInterval);
activeIntervals = [];
renderCards(data.services.filter(s => s.automation_status === 'in_progress')); renderCards(data.services.filter(s => s.automation_status === 'in_progress'));
renderFailedTable(data.services.filter(s => s.automation_status === 'failed')); renderFailedTable(data.services.filter(s => s.automation_status === 'failed'));
} }
} catch (e) { console.error(e); } } catch (e) { console.error(e); }
} }
function renderCards(activeServices) { function renderCards(activeServices) {
const container = document.getElementById('automation-list'); const container = document.getElementById('automation-list');
if (activeServices.length === 0) { if (activeServices.length === 0) {
container.innerHTML = `<div class="col-span-full py-12 text-center border-2 border-dashed border-gray-200 rounded-2xl"> container.innerHTML = `<div class="col-span-full py-12 text-center border-2 border-dashed border-gray-200 rounded-2xl">
@@ -97,15 +100,11 @@ function renderCards(activeServices) {
container.innerHTML = activeServices.map(s => { container.innerHTML = activeServices.map(s => {
const raw = s.raw_data; const raw = s.raw_data;
// Calculamos el tiempo restante para la barra de progreso const cardId = `card-${s.id}`;
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
return ` return `
<div class="bg-white rounded-2xl border-2 border-blue-50 shadow-sm overflow-hidden flex flex-col fade-in"> <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"> <div class="p-5 border-b border-gray-50 bg-blue-50/30 text-left">
<div class="flex justify-between items-start mb-2"> <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-[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> <span class="text-xs font-black text-blue-600">Ref: ${s.service_ref}</span>
@@ -114,7 +113,7 @@ function renderCards(activeServices) {
<p class="text-[10px] text-gray-500 font-bold uppercase tracking-tighter">📍 CP: ${raw["Código Postal"] || raw["C.P."] || '---'}</p> <p class="text-[10px] text-gray-500 font-bold uppercase tracking-tighter">📍 CP: ${raw["Código Postal"] || raw["C.P."] || '---'}</p>
</div> </div>
<div class="p-5 flex-1 space-y-4"> <div class="p-5 flex-1 space-y-4 text-left">
<div class="flex items-center gap-3"> <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"> <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center text-green-600">
<i data-lucide="user"></i> <i data-lucide="user"></i>
@@ -127,11 +126,11 @@ function renderCards(activeServices) {
<div class="space-y-1"> <div class="space-y-1">
<div class="flex justify-between text-[10px] font-bold uppercase tracking-widest text-blue-500"> <div class="flex justify-between text-[10px] font-bold uppercase tracking-widest text-blue-500">
<span>Respuesta en</span> <span>Caduca en</span>
<span>${Math.floor(diff / 60)}m ${diff % 60}s</span> <span id="timer-${s.id}">--:--</span>
</div> </div>
<div class="w-full bg-gray-100 h-1.5 rounded-full overflow-hidden"> <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 id="progress-${s.id}" class="bg-blue-500 h-full progress-bar" style="width: 100%"></div>
</div> </div>
</div> </div>
</div> </div>
@@ -144,29 +143,62 @@ function renderCards(activeServices) {
</div> </div>
`; `;
}).join(''); }).join('');
// Iniciar contadores dinámicos
activeServices.forEach(s => {
startLocalTimer(s.id, s.token_expires_at);
});
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) { function renderFailedTable(failedServices) {
const tbody = document.getElementById('failed-list'); const tbody = document.getElementById('failed-list');
tbody.innerHTML = failedServices.map(s => { tbody.innerHTML = failedServices.map(s => {
return ` 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 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"><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"> <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> </td>
</tr> </tr>`;
`;
}).join(''); }).join('');
} }
async function stopAutomation(id) { 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 { try {
// Endpoint para volver el estado a manual
const res = await fetch(`${API_URL}/providers/scraped/${id}`, { const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
@@ -175,7 +207,7 @@ function renderCards(activeServices) {
}, },
body: JSON.stringify({ automation_status: 'manual' }) body: JSON.stringify({ automation_status: 'manual' })
}); });
if (await res.json()) { if (res.ok) {
showToast("Proceso detenido"); showToast("Proceso detenido");
loadAutomations(); loadAutomations();
} }