diff --git a/index.html b/index.html index 7036400..6c55eda 100644 --- a/index.html +++ b/index.html @@ -14,13 +14,6 @@ .blob { position: absolute; filter: blur(60px); z-index: -1; opacity: 0.4; } .no-scrollbar::-webkit-scrollbar { display: none; } .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } - - /* Animación fluida para la barra de ruta del camión */ - @keyframes movingLine { - 0% { transform: translateX(-100%); } - 100% { transform: translateX(200%); } - } - .animate-moving-line { animation: movingLine 2s linear infinite; }
@@ -82,6 +75,7 @@ : 'https://integrarepara-api.integrarepara.es'; let urlToken = ""; + let etasToInit = []; // Para procesar los tiempos de llegada al cargar document.addEventListener("DOMContentLoaded", async () => { lucide.createIcons(); @@ -99,20 +93,16 @@ if (!data.ok) throw new Error("Token inválido"); renderPortal(data.client, data.company, data.services); } catch (e) { - console.error(e); showError(); } }); function showError() { - const loader = document.getElementById('loader'); - const errorScreen = document.getElementById('errorScreen'); - - loader.classList.add('opacity-0', 'pointer-events-none'); + document.getElementById('loader').classList.add('opacity-0', 'pointer-events-none'); setTimeout(() => { - loader.classList.add('hidden'); - errorScreen.classList.remove('hidden'); - errorScreen.classList.add('flex'); + document.getElementById('loader').classList.add('hidden'); + document.getElementById('errorScreen').classList.remove('hidden'); + document.getElementById('errorScreen').classList.add('flex'); }, 300); } @@ -162,7 +152,7 @@ allServices.forEach(srv => { const isFinalized = srv.status_name === 'Terminado'; - const isPendingWorker = (!srv.assigned_worker || srv.assigned_worker === 'Pendiente'); + const raw = srv.raw_data || {}; const descLimpia = summarizeDescription(srv.description); let statusHtml = ''; @@ -173,21 +163,22 @@ `; } else if (srv.status_name === 'Técnico de Camino') { - // NUEVO DISEÑO ANIMADO Y LIMPIO PARA "DE CAMINO" SIN MAPA + // Preparamos la dirección para calcular la ETA + const fullAddr = `${raw["Dirección"] || ""}, ${raw["Código Postal"] || ""} ${raw["Población"] || ""}`; + etasToInit.push({ id: srv.id, address: fullAddr }); + + // ESTRUCTURA BASE DE LA BARRA DE PROGRESO (SE LLENA CON JS) statusHtml = `En ruta hacia tu domicilio
-Prepárate, el técnico está a punto de llegar a tu ubicación.
+Calculando ruta...
+El técnico está conduciendo hacia tu domicilio.
`; + return; + } + + const wLat = parseFloat(data.location.lat); + const wLon = parseFloat(data.location.lng); + + // 2. Buscamos las coordenadas del cliente + let geoRes = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(destAddress + ', España')}`); + let geoData = await geoRes.json(); + + if (!geoData || geoData.length === 0) { + const parts = destAddress.split(','); + const fallbackDest = parts.length > 1 ? parts[parts.length - 1].trim() : destAddress; + geoRes = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(fallbackDest + ', España')}`); + geoData = await geoRes.json(); + } + + if (geoData && geoData.length > 0) { + const cLat = parseFloat(geoData[0].lat); + const cLon = parseFloat(geoData[0].lon); + + // 3. Calculamos la distancia en línea recta (Fórmula de Haversine) + const R = 6371; + const dLat = (cLat - wLat) * Math.PI / 180; + const dLon = (cLon - wLon) * Math.PI / 180; + const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(wLat * Math.PI / 180) * Math.cos(cLat * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + const km = R * c; + + // 4. Estimamos los minutos totales (velocidad media ciudad 35km/h + 5min atascos/aparcar) + const totalMins = Math.round((km/35)*60) + 5; + + // 5. EL TRUCO MAGICO: Restar los minutos que ya han pasado desde que salió + const startedAt = new Date(data.location.updated_at).getTime(); + const now = new Date().getTime(); + const diffMins = Math.floor((now - startedAt) / 60000); + + let remainingMins = totalMins - diffMins; + if (remainingMins < 1) remainingMins = 1; // Para que no ponga 0 o negativo + + // Calculamos el % para la barra visual + let progressPercent = (diffMins / totalMins) * 100; + if (progressPercent > 95) progressPercent = 95; + if (progressPercent < 5) progressPercent = 5; + + // Dibujamos la barra visual + container.innerHTML = ` ++ Llegada en aprox. ${remainingMins} min +
+Saliendo
+A ${km.toFixed(1)} km
+El técnico está conduciendo hacia tu domicilio.
`; + } + } catch(e) { + container.innerHTML = `El técnico está conduciendo hacia tu domicilio.
`; + } + }