From f3b8091e4749e3ed1e5827dccff985804b4515a5 Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 22 Feb 2026 16:34:12 +0000 Subject: [PATCH] Actualizar calendario.html --- calendario.html | 125 ++++++++++++------------------------------------ 1 file changed, 31 insertions(+), 94 deletions(-) diff --git a/calendario.html b/calendario.html index ee1b2c7..a2aac7e 100644 --- a/calendario.html +++ b/calendario.html @@ -150,10 +150,9 @@ let localServices = []; let systemStatuses = []; - let currentWeekStart = new Date(); // Lunes de la semana que estamos viendo - let selectedDateStr = ""; // Día exacto que el usuario ha pinchado + let currentWeekStart = new Date(); + let selectedDateStr = ""; - // Formateador seguro a YYYY-MM-DD function toISODate(dateObj) { const y = dateObj.getFullYear(); const m = String(dateObj.getMonth() + 1).padStart(2, '0'); @@ -161,11 +160,10 @@ return `${y}-${m}-${d}`; } - // Obtener el Lunes de cualquier fecha function getMonday(d) { const date = new Date(d); const day = date.getDay(); - const diff = date.getDate() - day + (day === 0 ? -6 : 1); // Ajuste si es Domingo (0) + const diff = date.getDate() - day + (day === 0 ? -6 : 1); return new Date(date.setDate(diff)); } @@ -176,7 +174,6 @@ lucide.createIcons(); - // Iniciamos con la semana actual y el día de hoy seleccionado const today = new Date(); currentWeekStart = getMonday(today); selectedDateStr = toISODate(today); @@ -186,16 +183,13 @@ refreshData(); }); - // 1. CONSTRUIR EL CALENDARIO SUPERIOR (Lunes a Domingo) function buildWeekCalendar() { const strip = document.getElementById('weekStrip'); strip.innerHTML = ''; - // Actualizar etiqueta del mes arriba const monthName = currentWeekStart.toLocaleDateString('es-ES', { month: 'long', year: 'numeric' }); document.getElementById('monthYearDisplay').innerText = monthName; - // Generar 7 días desde el Lunes for(let i = 0; i < 7; i++) { let d = new Date(currentWeekStart); d.setDate(currentWeekStart.getDate() + i); @@ -217,26 +211,20 @@ `; } - // Asegurarnos de pintar los puntitos rojos en la nueva semana si ya hay datos if(localServices.length > 0) updateBadges(); } - // Función para los botones de < y > de las semanas function changeWeek(offsetWeeks) { - // Sumamos o restamos 7 días al Lunes actual currentWeekStart.setDate(currentWeekStart.getDate() + (offsetWeeks * 7)); - - // Auto-seleccionar el Lunes de esa nueva semana selectedDateStr = toISODate(currentWeekStart); - buildWeekCalendar(); renderServices(); } function selectDate(isoDate) { selectedDateStr = isoDate; - buildWeekCalendar(); // Re-render visual de la tira superior - renderServices(); // Filtrar las tarjetas de abajo + buildWeekCalendar(); + renderServices(); } async function loadStatuses() { @@ -258,14 +246,14 @@ const data = await res.json(); if (data.ok) { - // Filtramos: Solo servicios que NO sean bloqueos y que SÍ tengan fecha + // Ahora SÍ permitimos los SYSTEM_BLOCK y servicios con fecha localServices = data.services.filter(s => { const raw = s.raw_data || {}; const hasDate = raw.scheduled_date && raw.scheduled_date.trim() !== ""; - return s.provider !== 'SYSTEM_BLOCK' && hasDate; + return hasDate; }); - buildWeekCalendar(); // Actualiza puntitos de la semana vista + buildWeekCalendar(); renderServices(); } } catch (e) { @@ -277,9 +265,7 @@ } } - // Poner el puntito rojo bajo los días que tengan trabajo en la semana actual function updateBadges() { - // Ocultar todos primero document.querySelectorAll('[id^="badge-"]').forEach(el => el.classList.add('hidden')); const counts = {}; @@ -296,17 +282,14 @@ function renderServices() { const container = document.getElementById('servicesList'); - // Formatear fecha para el título (DD/MM/YYYY) const displayDate = selectedDateStr.split('-').reverse().join('/'); document.getElementById('dayTitle').innerText = `Servicios del ${displayDate}`; - // Filtrar servicios exactos para el día seleccionado const dayServices = localServices.filter(s => { const d = (s.raw_data.scheduled_date || "").trim(); return d === selectedDateStr; }); - // Ordenar por hora dayServices.sort((a, b) => { const timeA = a.raw_data.scheduled_time || "23:59"; const timeB = b.raw_data.scheduled_time || "23:59"; @@ -326,14 +309,33 @@ container.innerHTML = dayServices.map(s => { const raw = s.raw_data || {}; + const time = raw.scheduled_time || "A convenir"; + + // RENDERIZADO ESPECIAL PARA BLOQUEOS + if (s.provider === 'SYSTEM_BLOCK') { + const desc = raw["Descripción"] || "Operario no disponible"; + return ` +
+
+ + ${time} +
+
+

Bloqueado

+

${desc}

+
+
+ `; + } + + // RENDERIZADO NORMAL PARA REPARACIONES const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado"; const addr = raw["Dirección"] || "Sin dirección"; const pop = raw["Población"] || ""; - const time = raw.scheduled_time || "A convenir"; const isUrgent = s.is_urgent; return ` -
+
${time} @@ -357,7 +359,7 @@ function openService(id) { const s = localServices.find(x => x.id === id); - if (!s) return; + if (!s || s.provider === 'SYSTEM_BLOCK') return; const raw = s.raw_data; currentServiceId = id; @@ -434,69 +436,4 @@ } }, (err) => { showGpsError("Permiso de GPS denegado"); - }, { enableHighAccuracy: true }); - } - - function showGpsError(msg) { - document.getElementById('gpsLoading').innerHTML = ` ${msg}`; - lucide.createIcons(); - } - - // --- ACTUALIZACIÓN DE ESTADOS CON BOTONES GIGANTES --- - async function quickUpdate(action) { - if(!currentServiceId) return; - - // Mapeamos la acción al nombre del estado que queremos buscar en BD - let searchWord = ""; - let confirmMsg = ""; - - if(action === 'camino') { searchWord = "camino"; confirmMsg = "¿Avisar al cliente que estás de camino?"; } - if(action === 'trabajando') { searchWord = "trabaja"; confirmMsg = "¿Confirmar llegada e iniciar reparación?"; } - if(action === 'finalizado') { searchWord = "finaliza"; confirmMsg = "¿Cerrar expediente definitivamente?"; } - if(action === 'encuesta') { searchWord = "finaliza"; confirmMsg = "¿Finalizar y mandar encuesta al cliente?"; } - - if(!confirm(confirmMsg)) return; - - // Buscar el ID del estado exacto en la base de datos - const st = systemStatuses.find(s => s.name.toLowerCase().includes(searchWord)); - if(!st) return alert("Error: El estado no existe en la base de datos de tu empresa."); - - try { - showToast("Procesando..."); - // La ruta PUT ya está programada en el backend para disparar WhatsApps (Encuesta, Camino, etc) - const res = await fetch(`${API_URL}/providers/scraped/${currentServiceId}`, { - method: 'PUT', - headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, - body: JSON.stringify({ status_operativo: st.id }) - }); - - if(res.ok) { - showToast("Estado actualizado correctamente"); - closeModal(); - refreshData(); // Recargamos para que cambien las tarjetas - } else { - alert("Error guardando estado"); - } - } catch (e) { - alert("Error de conexión al servidor"); - } - } - - function showToast(msg) { - const t = document.getElementById('toast'); - document.getElementById('toastMsg').innerText = msg; - t.classList.remove('opacity-0', 'pointer-events-none', '-translate-y-10'); - t.classList.add('translate-y-0'); - setTimeout(() => { - t.classList.add('opacity-0', 'pointer-events-none', '-translate-y-10'); - t.classList.remove('translate-y-0'); - }, 2500); - } - - function logout() { - localStorage.clear(); - window.location.href = "index.html"; - } - - - \ No newline at end of file + }, { enableHigh \ No newline at end of file