Actualizar calendario.html

This commit is contained in:
2026-02-22 17:56:04 +00:00
parent c671320192
commit bc5e48ee44

View File

@@ -13,172 +13,147 @@
.no-scrollbar::-webkit-scrollbar { display: none; } .no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
.safe-bottom-nav { padding-bottom: calc(env(safe-area-inset-bottom) + 12px); } .main-content { padding-bottom: 120px; }
.main-content { padding-bottom: calc(env(safe-area-inset-bottom) + 90px); }
.day-card { transition: all 0.2s; } .day-card { transition: all 0.2s; }
.day-active { background-color: #2563eb; color: white; border-color: #2563eb; transform: scale(1.05); box-shadow: 0 10px 15px -3px rgba(37,99,235,0.4); } .day-active { background-color: #2563eb; color: white; border-color: #2563eb; transform: scale(1.05); box-shadow: 0 10px 15px -3px rgba(37,99,235,0.4); }
.day-inactive { background-color: white; color: #64748b; border-color: #e2e8f0; } .day-inactive { background-color: white; color: #64748b; border-color: #e2e8f0; }
/* Mejora del modal interior */ /* Arreglo del Scroll del Modal */
.modal-body-scroll { height: calc(100vh - 60px); overflow-y: auto; padding-bottom: 40px; } #serviceModal { position: fixed; inset: 0; z-index: 100; display: none; flex-direction: column; background: #f8fafc; }
.desc-box { max-height: 180px; overflow-y: auto; } .modal-scroll-area { flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-bottom: 100px; }
</style> </style>
</head> </head>
<body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative"> <body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative">
<header class="bg-white px-5 pt-safe mt-6 pb-4 shadow-sm z-20 shrink-0 border-b border-slate-100"> <header class="bg-white px-5 pt-safe mt-6 pb-4 shadow-sm z-20 shrink-0 border-b border-slate-100">
<div class="flex items-center gap-3 mb-4"> <div class="flex items-center gap-3 mb-4">
<a href="menu.html" class="w-10 h-10 shrink-0 bg-slate-50 rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-100"> <a href="menu.html" class="w-10 h-10 shrink-0 bg-slate-50 rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:scale-95 transition-transform">
<i data-lucide="arrow-left" class="w-5 h-5"></i> <i data-lucide="arrow-left" class="w-5 h-5"></i>
</a> </a>
<div class="flex-1 min-w-0"> <div class="flex-1 min-w-0">
<p class="text-[10px] font-black text-blue-500 uppercase tracking-widest mb-0.5 truncate" id="monthYearDisplay">Cargando...</p> <p class="text-[10px] font-black text-blue-500 uppercase tracking-widest mb-0.5 truncate" id="monthYearDisplay">Cargando...</p>
<h1 class="text-xl font-black tracking-tight text-slate-800 leading-none truncate">Mi Agenda</h1> <h1 class="text-xl font-black tracking-tight text-slate-800 leading-none truncate">Mi Agenda</h1>
</div> </div>
<div class="flex gap-1 shrink-0"> <div class="flex gap-1 shrink-0">
<button onclick="changeWeek(-1)" class="w-10 h-10 bg-white rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-50 shadow-sm active:scale-95 transition-transform"><i data-lucide="chevron-left" class="w-5 h-5"></i></button> <button onclick="changeWeek(-1)" class="w-10 h-10 bg-white rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-50 shadow-sm"><i data-lucide="chevron-left" class="w-5 h-5"></i></button>
<button onclick="changeWeek(1)" class="w-10 h-10 bg-white rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-50 shadow-sm active:scale-95 transition-transform"><i data-lucide="chevron-right" class="w-5 h-5"></i></button> <button onclick="changeWeek(1)" class="w-10 h-10 bg-white rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-50 shadow-sm"><i data-lucide="chevron-right" class="w-5 h-5"></i></button>
</div> </div>
</div> </div>
<div class="overflow-x-auto no-scrollbar py-2 -mx-5 px-5 flex gap-3" id="weekStrip"></div> <div class="overflow-x-auto no-scrollbar py-2 -mx-5 px-5 flex gap-3" id="weekStrip"></div>
</header> </header>
<main class="flex-1 overflow-y-auto no-scrollbar p-5 main-content relative z-10" id="mainArea"> <main class="flex-1 overflow-y-auto no-scrollbar p-5 main-content relative z-10" id="mainArea">
<div id="loader" class="text-center py-10 opacity-50"> <div id="loader" class="text-center py-10 opacity-50">
<i data-lucide="loader-2" class="w-8 h-8 animate-spin mx-auto text-blue-500 mb-2"></i> <i data-lucide="loader-2" class="w-8 h-8 animate-spin mx-auto text-blue-500 mb-2"></i>
<p class="text-xs font-bold uppercase tracking-widest">Cargando agenda...</p> <p class="text-xs font-bold uppercase tracking-widest">Cargando datos...</p>
</div> </div>
<div id="dayTitle" class="font-black text-slate-400 uppercase tracking-widest text-[10px] mb-4 hidden">Servicios</div>
<div id="dayTitle" class="font-black text-slate-400 uppercase tracking-widest text-[10px] mb-4 hidden">Servicios para hoy</div>
<div id="servicesList" class="space-y-4 hidden fade-in"></div> <div id="servicesList" class="space-y-4 hidden fade-in"></div>
</main> </main>
<nav class="bg-white/90 backdrop-blur-md border-t border-slate-200 z-20 absolute bottom-0 left-0 w-full shadow-[0_-10px_30px_rgba(0,0,0,0.05)] rounded-t-[2rem]"> <nav class="bg-white/90 backdrop-blur-md border-t border-slate-200 z-20 absolute bottom-0 left-0 w-full shadow-[0_-10px_30px_rgba(0,0,0,0.05)] rounded-t-[2rem]">
<div class="flex justify-around items-center px-3 pt-3 safe-bottom-nav"> <div class="flex justify-around items-center px-3 pt-3 pb-8">
<a href="menu.html" class="flex flex-col items-center p-2 text-slate-400 hover:text-blue-600 transition-transform active:scale-95 w-20"> <a href="menu.html" class="flex flex-col items-center p-2 text-slate-400 hover:text-blue-600 w-20">
<i data-lucide="layout-grid" class="w-6 h-6 mb-1"></i> <i data-lucide="layout-grid" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-black uppercase tracking-widest">Inicio</span> <span class="text-[9px] font-black uppercase tracking-widest">Inicio</span>
</a> </a>
<a href="calendario.html" class="flex flex-col items-center p-2 text-blue-600 transition-transform active:scale-95 w-20"> <a href="calendario.html" class="flex flex-col items-center p-2 text-blue-600 w-20">
<i data-lucide="calendar-days" class="w-6 h-6 mb-1"></i> <i data-lucide="calendar-days" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-black uppercase tracking-widest">Agenda</span> <span class="text-[9px] font-black uppercase tracking-widest">Agenda</span>
</a> </a>
<button onclick="logout()" class="flex flex-col items-center p-2 text-slate-400 hover:text-red-500 transition-transform active:scale-95 w-20"> <button onclick="logout()" class="flex flex-col items-center p-2 text-slate-400 w-20">
<i data-lucide="log-out" class="w-6 h-6 mb-1"></i> <i data-lucide="log-out" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-bold uppercase tracking-widest">Salir</span> <span class="text-[9px] font-bold uppercase tracking-widest">Salir</span>
</button> </button>
</div> </div>
</nav> </nav>
<div id="serviceModal" class="fixed inset-0 bg-slate-100 z-[100] hidden flex-col translate-y-full transition-transform duration-300"> <div id="serviceModal" class="translate-y-full transition-transform duration-300">
<div class="pt-safe bg-white border-b border-slate-100 flex justify-between items-center p-4 shrink-0 shadow-sm">
<div class="pt-safe bg-slate-100 flex justify-between items-center p-4 pb-2 shrink-0 z-20"> <button onclick="closeModal()" class="bg-slate-100 p-2.5 rounded-full text-slate-600 active:scale-90 transition-transform"><i data-lucide="chevron-down" class="w-6 h-6"></i></button>
<button onclick="closeModal()" class="bg-white p-3 rounded-full shadow-sm text-slate-600 active:scale-95 transition-transform"><i data-lucide="chevron-down" class="w-6 h-6"></i></button> <div class="flex items-center gap-2 bg-blue-50 px-4 py-1.5 rounded-full border border-blue-100">
<div class="bg-white px-4 py-2 rounded-full shadow-sm flex items-center gap-2"> <i data-lucide="clock" class="w-4 h-4 text-blue-600"></i>
<i data-lucide="clock" class="w-4 h-4 text-blue-500"></i> <span class="font-black text-xs text-blue-700 uppercase" id="modTime">--:--</span>
<span class="font-black text-sm uppercase tracking-widest text-slate-800" id="modTime">10:00</span>
</div> </div>
<div class="w-10"></div>
</div> </div>
<div class="modal-body-scroll px-4 space-y-4 no-scrollbar"> <div class="modal-scroll-area p-4 space-y-4 no-scrollbar">
<input type="hidden" id="detId"> <input type="hidden" id="detId">
<input type="hidden" id="detPhoneRaw"> <input type="hidden" id="detPhoneRaw">
<div id="urgentBanner" class="hidden bg-rose-500 text-white p-3 rounded-2xl flex items-center justify-center gap-2 shadow-lg shadow-rose-200 animate-pulse"> <div id="urgentBanner" class="hidden bg-rose-600 text-white p-4 rounded-3xl flex items-center justify-center gap-3 shadow-xl shadow-rose-200 animate-pulse">
<i data-lucide="siren" class="w-6 h-6"></i> <i data-lucide="alert-octagon" class="w-6 h-6"></i>
<span class="font-black text-sm uppercase tracking-widest">Servicio Urgente</span> <span class="font-black text-sm uppercase tracking-widest">¡SERVICIO URGENTE!</span>
</div> </div>
<div class="grid grid-cols-2 gap-3"> <div class="grid grid-cols-2 gap-3">
<button onclick="quickUpdate('camino')" class="bg-indigo-50 border border-indigo-200 text-indigo-700 font-black p-4 rounded-2xl flex flex-col items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm"> <button onclick="quickUpdate('camino')" class="bg-indigo-600 text-white font-black p-5 rounded-3xl flex flex-col items-center gap-2 shadow-lg shadow-indigo-200 active:scale-95 transition-transform">
<i data-lucide="car" class="w-7 h-7"></i> <i data-lucide="car" class="w-8 h-8"></i>
<span class="text-[10px] uppercase tracking-widest">De Camino</span> <span class="text-[10px] uppercase tracking-widest">De Camino</span>
</button> </button>
<button onclick="quickUpdate('trabajando')" class="bg-amber-50 border border-amber-200 text-amber-700 font-black p-4 rounded-2xl flex flex-col items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm"> <button onclick="quickUpdate('trabajando')" class="bg-amber-500 text-white font-black p-5 rounded-3xl flex flex-col items-center gap-2 shadow-lg shadow-amber-200 active:scale-95 transition-transform">
<i data-lucide="wrench" class="w-7 h-7"></i> <i data-lucide="wrench" class="w-8 h-8"></i>
<span class="text-[10px] uppercase tracking-widest">He Llegado</span> <span class="text-[10px] uppercase tracking-widest">He Llegado</span>
</button> </button>
</div> </div>
<div class="bg-white p-5 rounded-3xl shadow-sm border border-slate-200 relative"> <div class="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-200">
<span id="detRef" class="absolute top-4 right-5 text-[10px] font-black text-slate-400 bg-slate-100 px-2 py-1 rounded-md uppercase tracking-widest"></span> <div class="flex justify-between items-start mb-1">
<p class="text-[9px] font-black text-blue-600 uppercase tracking-widest" id="detCompany">Compañía</p>
<p class="text-[9px] font-black text-blue-500 uppercase tracking-widest mb-1" id="detCompany">Compañía</p> <span id="detRef" class="text-[9px] font-black text-slate-400 uppercase"></span>
<h2 id="detName" class="text-2xl font-black text-slate-800 uppercase leading-tight pr-16"></h2>
<div class="mt-4 flex gap-3">
<button onclick="callClient()" class="flex-1 bg-blue-600 text-white font-black py-3 rounded-xl shadow-md shadow-blue-200 active:scale-95 transition-transform flex items-center justify-center gap-2 uppercase text-xs tracking-widest">
<i data-lucide="phone-call" class="w-4 h-4"></i> Llamar
</button>
<button onclick="openWhatsApp()" class="w-14 bg-emerald-50 text-emerald-600 font-black rounded-xl border border-emerald-100 active:scale-95 transition-transform flex items-center justify-center shadow-sm">
<i data-lucide="message-circle" class="w-6 h-6"></i>
</button>
</div> </div>
<h2 id="detName" class="text-2xl font-black text-slate-900 uppercase leading-none mb-6">Nombre Cliente</h2>
<button onclick="callClient()" class="w-full bg-blue-600 text-white font-black py-4 rounded-2xl shadow-xl shadow-blue-200 flex items-center justify-center gap-3 uppercase text-sm tracking-widest active:scale-95 transition-all">
<i data-lucide="phone" class="w-5 h-5 fill-current"></i> Llamar al Cliente
</button>
<button onclick="openWhatsApp()" class="w-full mt-3 bg-emerald-50 text-emerald-700 font-black py-3 rounded-2xl border border-emerald-100 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all">
<i data-lucide="message-circle" class="w-4 h-4"></i> Abrir WhatsApp
</button>
</div> </div>
<div class="bg-slate-800 text-white p-5 rounded-3xl shadow-lg relative overflow-hidden"> <div class="bg-slate-900 text-white p-6 rounded-[2.5rem] shadow-2xl relative overflow-hidden">
<i data-lucide="map" class="absolute -right-4 -bottom-4 w-32 h-32 text-white/5 pointer-events-none"></i> <i data-lucide="map" class="absolute -right-6 -bottom-6 w-40 h-40 text-white/5 pointer-events-none"></i>
<div class="relative z-10 flex gap-4 items-start"> <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Ubicación</p>
<div class="w-10 h-10 bg-white/10 rounded-full flex items-center justify-center shrink-0"> <p id="detAddress" class="text-base font-bold uppercase leading-tight mb-6">Dirección Completa...</p>
<i data-lucide="map-pin" class="w-5 h-5 text-blue-300"></i>
</div>
<div class="min-w-0">
<p class="text-[10px] font-black text-blue-300 uppercase tracking-widest mb-1">Dirección del Servicio</p>
<p id="detAddress" class="font-bold text-sm uppercase leading-snug"></p>
</div>
</div>
<div class="relative z-10 mt-4 pt-4 border-t border-white/10 flex items-center justify-between"> <div class="flex items-center justify-between bg-white/10 p-4 rounded-2xl backdrop-blur-md">
<div id="gpsLoading" class="text-xs font-bold text-blue-200 flex items-center gap-2"> <div id="gpsLoading" class="text-xs font-bold text-slate-300 flex items-center gap-2"><i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> Calculando...</div>
<i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> GPS... <div id="gpsResult" class="hidden flex gap-4">
</div> <div class="text-center"><p class="text-xl font-black leading-none" id="gpsMins">--</p><p class="text-[8px] font-bold text-slate-400 uppercase">min</p></div>
<div id="gpsResult" class="hidden flex items-center gap-3">
<div>
<span class="text-xl font-black leading-none" id="gpsMins">--</span> <span class="text-[10px] font-bold text-slate-400">MIN</span>
</div>
<div class="w-px h-6 bg-white/20"></div> <div class="w-px h-6 bg-white/20"></div>
<div> <div class="text-center"><p class="text-xl font-black leading-none" id="gpsKm">--</p><p class="text-[8px] font-bold text-slate-400 uppercase">km</p></div>
<span class="text-xl font-black leading-none" id="gpsKm">--</span> <span class="text-[10px] font-bold text-slate-400">KM</span>
</div>
</div> </div>
<button onclick="openMaps()" class="bg-blue-500 hover:bg-blue-400 text-white p-2 rounded-lg text-[9px] font-black uppercase tracking-widest shadow-sm active:scale-95">Ir (Maps)</button> <button onclick="openMaps()" class="bg-white text-slate-900 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest shadow-lg active:scale-90 transition-transform">Ver Mapa</button>
</div> </div>
</div> </div>
<div class="bg-amber-50 border border-amber-200 p-5 rounded-3xl shadow-sm"> <div class="bg-amber-50 border border-amber-200 p-6 rounded-[2.5rem]">
<p class="text-[10px] font-black text-amber-600 uppercase tracking-widest mb-2 flex items-center gap-1.5"> <p class="text-[10px] font-black text-amber-700 uppercase tracking-widest mb-3 flex items-center gap-2"><i data-lucide="file-text" class="w-4 h-4"></i> Notas del Servicio</p>
<i data-lucide="align-left" class="w-4 h-4"></i> Descripción y Notas <div id="detDesc" class="text-sm font-bold text-slate-700 leading-relaxed max-h-60 overflow-y-auto no-scrollbar">--</div>
</p> </div>
<div id="detDesc" class="text-sm font-bold text-slate-700 leading-relaxed desc-box no-scrollbar pr-2">
<div class="bg-slate-50 border border-slate-200 rounded-3xl overflow-hidden">
<button onclick="document.getElementById('extraDataBox').classList.toggle('hidden')" class="w-full p-4 flex justify-between items-center text-[10px] font-black text-slate-500 uppercase tracking-widest">
<span>Ficha Completa de la Compañía</span>
<i data-lucide="chevron-right" class="w-4 h-4"></i>
</button>
<div id="extraDataBox" class="hidden p-5 space-y-3 bg-white border-t border-slate-100" id="detExtraInfo">
</div> </div>
</div> </div>
<div class="bg-white border border-slate-200 rounded-3xl shadow-sm overflow-hidden"> <div class="pt-4">
<button onclick="document.getElementById('extraDataBox').classList.toggle('hidden')" class="w-full p-4 flex justify-between items-center bg-slate-50 hover:bg-slate-100 transition-colors"> <button onclick="quickUpdate('finalizado')" class="w-full bg-emerald-500 text-white font-black py-5 rounded-[2rem] shadow-xl shadow-emerald-100 flex items-center justify-center gap-3 uppercase text-sm tracking-widest active:scale-95 transition-all">
<span class="text-[10px] font-black text-slate-500 uppercase tracking-widest flex items-center gap-2"><i data-lucide="file-json" class="w-4 h-4"></i> Ver todos los datos (Ficha técnica)</span> <i data-lucide="check-circle" class="w-6 h-6"></i> Finalizar y Cerrar
<i data-lucide="chevron-down" class="w-4 h-4 text-slate-400"></i>
</button> </button>
<div id="extraDataBox" class="hidden p-5 space-y-3 bg-white border-t border-slate-100"> <p class="text-center text-[9px] font-bold text-slate-400 mt-4 uppercase tracking-widest">IntegraRepara Mobile v2.0</p>
<div id="detExtraInfo"></div>
</div>
</div> </div>
<div class="grid grid-cols-1 gap-3 pt-2">
<button onclick="quickUpdate('finalizado')" class="bg-emerald-500 text-white font-black py-4 rounded-2xl flex justify-center items-center gap-2 active:scale-95 transition-all shadow-md shadow-emerald-200">
<i data-lucide="check-circle" class="w-5 h-5"></i>
<span class="text-[11px] uppercase tracking-widest">Finalizar Trabajo</span>
</button>
</div>
</div> </div>
</div> </div>
<div id="toast" class="fixed top-5 left-1/2 -translate-x-1/2 bg-slate-800 text-white px-5 py-3 rounded-full shadow-2xl z-[200] font-bold text-xs uppercase tracking-widest flex items-center gap-2 transition-all duration-300 opacity-0 pointer-events-none transform -translate-y-10"> <div id="toast" class="fixed top-8 left-1/2 -translate-x-1/2 bg-slate-900 text-white px-6 py-3 rounded-full shadow-2xl z-[200] font-bold text-xs uppercase tracking-widest flex items-center gap-2 transition-all duration-300 opacity-0 pointer-events-none transform -translate-y-10">
<i data-lucide="check-circle" class="w-4 h-4 text-emerald-400"></i> <i data-lucide="check" class="w-4 h-4 text-emerald-400"></i>
<span id="toastMsg">Guardado</span> <span id="toastMsg">Guardado</span>
</div> </div>
@@ -195,7 +170,7 @@
function safeLoadIcons() { function safeLoadIcons() {
try { if (typeof lucide !== 'undefined') lucide.createIcons(); } try { if (typeof lucide !== 'undefined') lucide.createIcons(); }
catch(e) { console.warn("Iconos no cargados"); } catch(e) { }
} }
function toISODate(dateObj) { function toISODate(dateObj) {
@@ -220,17 +195,13 @@
window.location.href = "index.html"; return; window.location.href = "index.html"; return;
} }
safeLoadIcons(); safeLoadIcons();
const today = new Date();
try { currentWeekStart = getMonday(today);
const today = new Date(); selectedDateStr = toISODate(today);
currentWeekStart = getMonday(today); buildWeekCalendar();
selectedDateStr = toISODate(today); loadStatuses();
buildWeekCalendar(); await loadGuilds();
refreshData();
loadStatuses();
await loadGuilds();
refreshData();
} catch(error) { alert("Error iniciando calendario"); }
}); });
async function loadGuilds() { async function loadGuilds() {
@@ -242,41 +213,31 @@
} }
function buildWeekCalendar() { function buildWeekCalendar() {
try { const strip = document.getElementById('weekStrip');
const strip = document.getElementById('weekStrip'); strip.innerHTML = '';
strip.innerHTML = ''; const monthName = currentWeekStart.toLocaleDateString('es-ES', { month: 'long', year: 'numeric' });
document.getElementById('monthYearDisplay').innerText = monthName;
const monthName = currentWeekStart.toLocaleDateString('es-ES', { month: 'long', year: 'numeric' }); for(let i = 0; i < 7; i++) {
document.getElementById('monthYearDisplay').innerText = monthName; let d = new Date(currentWeekStart);
d.setDate(currentWeekStart.getDate() + i);
for(let i = 0; i < 7; i++) { const isoDate = toISODate(d);
let d = new Date(currentWeekStart); const dayName = d.toLocaleDateString('es-ES', { weekday: 'short' }).replace('.', '');
d.setDate(currentWeekStart.getDate() + i); const dayNum = d.getDate();
const isSelected = isoDate === selectedDateStr;
const isoDate = toISODate(d); strip.innerHTML += `
const dayName = d.toLocaleDateString('es-ES', { weekday: 'short' }).replace('.', ''); <button onclick="selectDate('${isoDate}')" class="day-card ${isSelected ? 'day-active' : 'day-inactive'} border min-w-[4.2rem] rounded-2xl p-4 flex flex-col items-center justify-center shrink-0">
const dayNum = d.getDate(); <span class="text-[9px] font-black uppercase opacity-70">${dayName}</span>
<span class="text-xl font-black mt-1">${dayNum}</span>
const isSelected = isoDate === selectedDateStr; <div class="mt-2 w-full flex justify-center h-1.5"><span id="badge-${isoDate}" class="bg-rose-500 w-1.5 h-1.5 rounded-full hidden"></span></div>
const baseClass = isSelected ? 'day-active' : 'day-inactive'; </button>`;
}
strip.innerHTML += ` updateBadges();
<button onclick="selectDate('${isoDate}')" id="btn-date-${isoDate}" class="day-card ${baseClass} border min-w-[4rem] rounded-2xl p-3 flex flex-col items-center justify-center shrink-0"> safeLoadIcons();
<span class="text-[9px] font-black uppercase tracking-widest opacity-80">${dayName}</span>
<span class="text-xl font-black leading-none mt-1">${dayNum}</span>
<div class="mt-2 w-full flex justify-center h-1.5">
<span id="badge-${isoDate}" class="bg-rose-500 w-1.5 h-1.5 rounded-full hidden"></span>
</div>
</button>
`;
}
if(localServices.length > 0) updateBadges();
safeLoadIcons();
} catch(e) {}
} }
function changeWeek(offsetWeeks) { function changeWeek(offset) {
currentWeekStart.setDate(currentWeekStart.getDate() + (offsetWeeks * 7)); currentWeekStart.setDate(currentWeekStart.getDate() + (offset * 7));
selectedDateStr = toISODate(currentWeekStart); selectedDateStr = toISODate(currentWeekStart);
buildWeekCalendar(); buildWeekCalendar();
renderServices(); renderServices();
@@ -299,18 +260,13 @@
async function refreshData() { async function refreshData() {
document.getElementById('servicesList').classList.add('hidden'); document.getElementById('servicesList').classList.add('hidden');
document.getElementById('loader').classList.remove('hidden'); document.getElementById('loader').classList.remove('hidden');
try { try {
const res = await fetch(`${API_URL}/services/active`, { const res = await fetch(`${API_URL}/services/active`, { 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) {
localServices = data.services.filter(s => { localServices = data.services.filter(s => {
const raw = s.raw_data || {}; const raw = s.raw_data || {};
const dateStr = String(raw.scheduled_date || "").trim(); return String(raw.scheduled_date || "").trim() !== "";
return dateStr !== "";
}); });
buildWeekCalendar(); buildWeekCalendar();
renderServices(); renderServices();
@@ -337,92 +293,48 @@
} }
function renderServices() { function renderServices() {
try { const container = document.getElementById('servicesList');
const container = document.getElementById('servicesList'); const displayDate = selectedDateStr.split('-').reverse().join('/');
const displayDate = selectedDateStr.split('-').reverse().join('/'); document.getElementById('dayTitle').innerText = `DÍA ${displayDate}`;
document.getElementById('dayTitle').innerText = `Servicios del ${displayDate}`;
const dayServices = localServices.filter(s => { const dayServices = localServices.filter(s => String(s.raw_data.scheduled_date || "").trim() === selectedDateStr);
const d = String(s.raw_data.scheduled_date || "").trim(); dayServices.sort((a, b) => String(a.raw_data.scheduled_time || "23:59").localeCompare(String(b.raw_data.scheduled_time || "23:59")));
return d === selectedDateStr;
});
dayServices.sort((a, b) => { if (dayServices.length === 0) {
const timeA = String(a.raw_data.scheduled_time || "23:59"); container.innerHTML = `<div class="text-center py-20 bg-white rounded-[3rem] border border-slate-100 shadow-sm mt-4"><i data-lucide="coffee" class="w-12 h-12 text-slate-200 mx-auto mb-3"></i><h3 class="font-black text-slate-800">Día de Descanso</h3><p class="text-xs text-slate-400 font-medium">No tienes servicios para este día.</p></div>`;
const timeB = String(b.raw_data.scheduled_time || "23:59"); safeLoadIcons(); return;
return timeA.localeCompare(timeB); }
});
if (dayServices.length === 0) { container.innerHTML = dayServices.map(s => {
container.innerHTML = ` const raw = s.raw_data || {};
<div class="text-center py-10 bg-white rounded-3xl border border-slate-100 shadow-sm mt-4 fade-in"> const time = raw.scheduled_time || "--:--";
<i data-lucide="party-popper" class="w-12 h-12 text-slate-200 mx-auto mb-3"></i> if (s.provider === 'SYSTEM_BLOCK') {
<h3 class="font-black text-slate-800">Día Libre</h3> return `<div class="bg-rose-50/80 p-5 rounded-3xl border border-rose-100 flex gap-4"><div class="flex flex-col items-center justify-center border-r border-rose-200 pr-4 shrink-0"><i data-lucide="lock" class="w-5 h-5 text-rose-500"></i><span class="font-black text-rose-800 text-sm mt-1">${time}</span></div><div class="min-w-0 flex-1"><h3 class="font-black text-rose-800 text-sm uppercase">BLOQUEADO</h3><p class="text-[10px] font-bold text-rose-400 mt-1 uppercase">${raw["Descripción"] || ""}</p></div></div>`;
<p class="text-xs text-slate-400 font-medium mt-1">No tienes citas agendadas para hoy.</p>
</div>`;
safeLoadIcons();
return;
} }
container.innerHTML = dayServices.map(s => { const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
const raw = s.raw_data || {}; const addr = raw["Dirección"] || "---";
const time = raw.scheduled_time || "A convenir"; let compShort = (raw["Compañía"] || "Particular").split('-')[0].trim().substring(0, 15);
const guildObj = systemGuilds.find(g => String(g.id) === String(s.guild_id || raw.guild_id));
if (s.provider === 'SYSTEM_BLOCK') { return `
const desc = raw["Descripción"] || "Operario no disponible"; <div onclick="openService(${s.id})" class="bg-white p-6 rounded-[2.5rem] border border-slate-200 shadow-sm active:scale-95 transition-transform flex gap-4 relative overflow-hidden">
return ` ${s.is_urgent ? '<div class="absolute top-0 right-0 bg-rose-600 text-white text-[8px] font-black px-3 py-1.5 rounded-bl-xl uppercase tracking-widest z-10">Urgente</div>' : ''}
<div class="bg-rose-50 p-5 rounded-3xl border border-rose-200 shadow-sm flex gap-4 fade-in"> <div class="flex flex-col items-center justify-center border-r border-slate-100 pr-4 shrink-0 min-w-[70px]">
<div class="flex flex-col items-center justify-center border-r border-rose-200 pr-4 shrink-0"> <i data-lucide="clock" class="w-6 h-6 text-blue-500 mb-1"></i>
<i data-lucide="lock" class="w-4 h-4 text-rose-500 mb-1"></i> <span class="font-black text-slate-900 text-base">${time}</span>
<span class="font-black text-rose-800 text-sm mt-1">${time}</span> </div>
</div> <div class="min-w-0 flex-1">
<div class="min-w-0 flex-1 py-1"> <div class="flex flex-wrap gap-1.5 mb-2">
<h3 class="font-black text-rose-800 text-sm uppercase leading-tight truncate">Bloqueado</h3> <span class="text-[8px] font-black bg-blue-50 text-blue-600 px-2 py-0.5 rounded uppercase border border-blue-100">${compShort}</span>
<p class="text-[10px] font-bold text-rose-600 mt-1 truncate uppercase">${desc}</p> <span class="text-[8px] font-black bg-slate-100 text-slate-500 px-2 py-0.5 rounded uppercase border border-slate-200">${guildObj ? guildObj.name : 'Reparación'}</span>
</div>
</div>`;
}
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
const addr = raw["Dirección"] || "Sin dirección";
const pop = raw["Población"] || "";
const isUrgent = s.is_urgent;
let compRaw = raw["Compañía"] || raw["COMPAÑIA"] || raw["Procedencia"] || "Particular";
let compShort = compRaw.split('-')[0].trim().substring(0, 15);
if(compRaw.includes("MULTI")) compShort = "MULTIASISTENCIA";
if(compRaw.includes("HOME")) compShort = "HOMESERVE";
const rawGuildId = s.guild_id || raw.guild_id || raw['guild_id'];
const guildObj = systemGuilds.find(g => String(g.id) === String(rawGuildId));
const guildName = guildObj ? guildObj.name : "Reparación";
return `
<div onclick="openService(${s.id})" class="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm active:scale-95 transition-transform flex gap-4 cursor-pointer fade-in relative overflow-hidden">
${isUrgent ? '<div class="absolute top-0 right-0 bg-rose-500 text-white text-[8px] font-black px-3 py-1.5 rounded-bl-xl uppercase tracking-widest shadow-sm z-10 flex items-center gap-1"><i data-lucide="siren" class="w-3 h-3"></i> Urgente</div>' : ''}
<div class="flex flex-col items-center justify-center border-r border-slate-100 pr-4 shrink-0 min-w-[65px]">
<i data-lucide="clock" class="w-5 h-5 text-blue-500 mb-1"></i>
<span class="font-black text-slate-800 text-sm mt-1">${time}</span>
</div> </div>
<h3 class="font-black text-slate-800 text-sm uppercase leading-tight truncate">${name}</h3>
<div class="min-w-0 flex-1"> <p class="text-[10px] font-bold text-slate-400 mt-1 truncate uppercase flex items-center gap-1.5"><i data-lucide="map-pin" class="w-3 h-3 shrink-0"></i> ${addr}</p>
<div class="flex flex-wrap gap-1.5 mb-2"> </div>
<span class="text-[8px] font-black bg-blue-50 text-blue-700 px-2 py-0.5 rounded uppercase tracking-widest truncate max-w-[120px] border border-blue-100">${compShort}</span> </div>`;
<span class="text-[8px] font-black bg-slate-100 text-slate-600 px-2 py-0.5 rounded uppercase tracking-widest truncate border border-slate-200">${guildName}</span> }).join('');
</div> safeLoadIcons();
<h3 class="font-black text-slate-800 text-sm uppercase leading-tight line-clamp-2">${name}</h3>
<p class="text-[10px] font-bold text-slate-500 mt-1.5 truncate uppercase flex items-center gap-1.5">
<i data-lucide="map-pin" class="w-3 h-3 shrink-0 text-slate-400"></i> ${addr}, ${pop}
</p>
</div>
</div>`;
}).join('');
safeLoadIcons();
} catch(e) { console.error("Render error:", e); }
} }
let currentServiceId = null; let currentServiceId = null;
@@ -434,166 +346,104 @@
currentServiceId = id; currentServiceId = id;
document.getElementById('detId').value = s.id; document.getElementById('detId').value = s.id;
document.getElementById('modTime').innerText = raw.scheduled_time || "S/H"; document.getElementById('modTime').innerText = raw.scheduled_time || "--:--";
document.getElementById('detRef').innerText = s.service_ref || "S/R"; document.getElementById('detRef').innerText = `#${s.service_ref || "---"}`;
document.getElementById('detCompany').innerText = raw["Compañía"] || "Particular";
let compRaw = raw["Compañía"] || raw["COMPAÑIA"] || raw["Procedencia"] || "Particular";
document.getElementById('detCompany').innerText = compRaw;
document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado"; document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado";
const fullAddress = `${raw["Dirección"] || ""}, ${raw["Código Postal"] || ""} ${raw["Población"] || ""}`; const fullAddress = `${raw["Dirección"] || ""}, ${raw["Código Postal"] || ""} ${raw["Población"] || ""}`;
document.getElementById('detAddress').innerText = fullAddress; document.getElementById('detAddress').innerText = fullAddress;
// Extraer teléfono
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || ""; const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/); const matchPhone = String(rawPhone).match(/[6789]\d{8}/);
document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : ""; document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : "";
// Urgencia
const isUrgent = s.is_urgent;
const banner = document.getElementById('urgentBanner'); const banner = document.getElementById('urgentBanner');
if (isUrgent) banner.classList.remove('hidden'); if (s.is_urgent) banner.classList.remove('hidden');
else banner.classList.add('hidden'); else banner.classList.add('hidden');
// Descripción principal document.getElementById('detDesc').innerHTML = (raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.").replace(/\n/g, '<br>');
let desc = raw["Descripción"] || raw["DESCRIPCION"] || "No hay notas de avería.";
document.getElementById('detDesc').innerHTML = desc.replace(/\n/g, '<br>');
// VOLCAR TODOS LOS DATOS EXTRA const extraContainer = document.getElementById('extraDataBox');
const detailsContainer = document.getElementById('detExtraInfo');
let detailsHtml = ''; let detailsHtml = '';
const skipKeys = ["Nombre Cliente", "CLIENTE", "Dirección", "DOMICILIO", "Población", "POBLACION-PROVINCIA", "scheduled_date", "scheduled_time", "status_operativo", "assigned_to", "guild_id", "Código Postal", "assigned_to_name", "Descripción", "DESCRIPCION", "Compañía", "COMPAÑIA"]; const skipKeys = ["Nombre Cliente", "CLIENTE", "Dirección", "DOMICILIO", "Población", "POBLACION-PROVINCIA", "scheduled_date", "scheduled_time", "status_operativo", "assigned_to", "guild_id", "Código Postal", "assigned_to_name", "Descripción", "DESCRIPCION", "Compañía", "COMPAÑIA"];
for(let key in raw) { for(let key in raw) {
if(skipKeys.includes(key)) continue; if(skipKeys.includes(key)) continue;
let val = raw[key]; let val = raw[key];
if(typeof val === 'object') val = JSON.stringify(val); // ARREGLO TYPEERROR: Verificamos si val es string antes del trim
if(!val || val.trim() === "") continue; let valStr = String(val || "");
if(valStr.trim() === "") continue;
detailsHtml += ` detailsHtml += `<div class="border-b border-slate-100 pb-2 mb-2 last:border-0 flex flex-col gap-0.5"><span class="text-[8px] font-black text-slate-400 uppercase tracking-widest">${key}</span><span class="text-[11px] font-bold text-slate-700 break-words">${valStr}</span></div>`;
<div class="border-b border-slate-200 pb-2 mb-2 last:border-0 last:mb-0 last:pb-0 flex flex-col md:flex-row justify-between md:items-center gap-1">
<span class="text-[9px] font-black text-slate-400 uppercase tracking-widest min-w-[100px]">${key}</span>
<span class="text-xs font-bold text-slate-700 md:text-right break-words">${val}</span>
</div>
`;
} }
extraContainer.innerHTML = detailsHtml || '<p class="text-xs text-slate-400">Sin datos adicionales.</p>';
if(detailsHtml === '') detailsHtml = '<p class="text-xs text-slate-400 font-medium">No hay más datos proporcionados.</p>';
detailsContainer.innerHTML = detailsHtml;
const modal = document.getElementById('serviceModal'); const modal = document.getElementById('serviceModal');
modal.classList.remove('hidden'); modal.style.display = 'flex';
setTimeout(() => modal.classList.remove('translate-y-full'), 10); setTimeout(() => modal.classList.remove('translate-y-full'), 10);
calculateDistance(fullAddress); calculateDistance(fullAddress);
} }
function closeModal() { function closeModal() {
const modal = document.getElementById('serviceModal'); const modal = document.getElementById('serviceModal');
modal.classList.add('translate-y-full'); modal.classList.add('translate-y-full');
setTimeout(() => modal.classList.add('hidden'), 300); setTimeout(() => modal.style.display = 'none', 300);
document.getElementById('gpsLoading').classList.remove('hidden'); document.getElementById('gpsLoading').classList.remove('hidden');
document.getElementById('gpsResult').classList.add('hidden'); document.getElementById('gpsResult').classList.add('hidden');
document.getElementById('extraDataBox').classList.add('hidden'); // Resetear caja extra
} }
function callClient() { function callClient() { const p = document.getElementById('detPhoneRaw').value; if (p) window.location.href = `tel:+34${p}`; else alert("Sin teléfono"); }
const phone = document.getElementById('detPhoneRaw').value; function openWhatsApp() { const p = document.getElementById('detPhoneRaw').value; if (p) window.open(`https://wa.me/34${p}`, '_blank'); else alert("Sin teléfono"); }
if (phone) window.location.href = `tel:+34${phone}`; function openMaps() { const a = document.getElementById('detAddress').innerText; if (a) window.open(`maps://?q=${encodeURIComponent(a)}`, '_blank'); }
else alert("No hay un teléfono válido guardado.");
}
function openWhatsApp() { async function calculateDistance(dest) {
const phone = document.getElementById('detPhoneRaw').value; if(!navigator.geolocation) { showGpsError("No GPS"); return; }
if (phone) window.open(`https://wa.me/34${phone}`, '_blank'); navigator.geolocation.getCurrentPosition(async (pos) => {
else alert("No hay un teléfono válido guardado."); const lat = pos.coords.latitude; const lon = pos.coords.longitude;
}
function openMaps() {
const address = document.getElementById('detAddress').innerText;
if (address) {
const encodedAddr = encodeURIComponent(address);
// Intenta abrir en la app de Apple Maps o Google Maps nativa del movil
window.open(`maps://?q=${encodedAddr}`, '_blank');
// Fallback a web si falla
setTimeout(() => { window.open(`https://maps.google.com/?q=${encodedAddr}`, '_blank'); }, 500);
}
}
async function calculateDistance(destAddress) {
if(!navigator.geolocation) { showGpsError("GPS no soportado"); return; }
navigator.geolocation.getCurrentPosition(async (position) => {
const userLat = position.coords.latitude;
const userLon = position.coords.longitude;
try { try {
const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(destAddress + ', España')}`); const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(dest + ', España')}`);
const data = await res.json(); const data = await res.json();
if (data && data.length > 0) { if (data && data[0]) {
const destLat = parseFloat(data[0].lat); const R = 6371; const dLat = (data[0].lat - lat) * Math.PI / 180; const dLon = (data[0].lon - lon) * Math.PI / 180;
const destLon = parseFloat(data[0].lon); const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat * Math.PI / 180) * Math.cos(data[0].lat * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2);
const R = 6371;
const dLat = (destLat - userLat) * Math.PI / 180;
const dLon = (destLon - userLon) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(userLat * Math.PI / 180) * Math.cos(destLat * Math.PI / 180) * Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const distanceKm = R * c; const km = R * c;
const mins = Math.round((distanceKm / 35) * 60) + 5;
document.getElementById('gpsLoading').classList.add('hidden'); document.getElementById('gpsLoading').classList.add('hidden');
document.getElementById('gpsResult').classList.remove('hidden'); document.getElementById('gpsResult').classList.remove('hidden');
document.getElementById('gpsKm').innerText = distanceKm.toFixed(1); document.getElementById('gpsKm').innerText = km.toFixed(1);
document.getElementById('gpsMins').innerText = mins; document.getElementById('gpsMins').innerText = Math.round((km/35)*60)+5;
} else { showGpsError("Dirección no encontrada en el mapa"); } } else { showGpsError("Sin ubicación"); }
} catch(e) { showGpsError("Error de red GPS"); } } catch(e) { showGpsError("Error GPS"); }
}, (err) => { showGpsError("Permiso de GPS denegado"); }, { enableHighAccuracy: true }); }, () => showGpsError("GPS off"), { enableHighAccuracy: true });
} }
function showGpsError(msg) { function showGpsError(m) { document.getElementById('gpsLoading').innerHTML = `<span class="text-rose-400 font-bold">${m}</span>`; }
document.getElementById('gpsLoading').innerHTML = `<i data-lucide="alert-circle" class="w-4 h-4 text-rose-400"></i> ${msg}`;
safeLoadIcons();
}
async function quickUpdate(action) { async function quickUpdate(action) {
if(!currentServiceId) return; if(!currentServiceId) return;
let searchWord = ""; let confirmMsg = ""; let word = ""; let msg = "";
if(action === 'camino') { searchWord = "camino"; confirmMsg = "¿Avisar al cliente que estás de camino?"; } if(action === 'camino') { word = "camino"; msg = "¿Enviar 'De Camino'?"; }
if(action === 'trabajando') { searchWord = "trabaja"; confirmMsg = "¿Confirmar llegada e iniciar reparación?"; } if(action === 'trabajando') { word = "trabaja"; msg = "¿Iniciar trabajo?"; }
if(action === 'finalizado') { searchWord = "finaliza"; confirmMsg = "¿Cerrar expediente definitivamente?"; } if(action === 'finalizado') { word = "finaliza"; msg = "¿Finalizar expediente?"; }
if(action === 'encuesta') { searchWord = "finaliza"; confirmMsg = "¿Finalizar y mandar encuesta al cliente?"; } if(action === 'encuesta') { word = "finaliza"; msg = "¿Enviar encuesta?"; }
if(!confirm(confirmMsg)) return; if(!confirm(msg)) return;
const st = systemStatuses.find(s => s.name.toLowerCase().includes(word));
const st = systemStatuses.find(s => s.name.toLowerCase().includes(searchWord)); if(!st) return alert("Estado no encontrado");
if(!st) return alert("Error: El estado no existe en la base de datos.");
try { try {
showToast("Procesando...");
const res = await fetch(`${API_URL}/providers/scraped/${currentServiceId}`, { const res = await fetch(`${API_URL}/providers/scraped/${currentServiceId}`, {
method: 'PUT', method: 'PUT', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status_operativo: st.id }) body: JSON.stringify({ status_operativo: st.id })
}); });
if(res.ok) { showToast("¡Hecho!"); closeModal(); refreshData(); }
if(res.ok) { } catch (e) { alert("Error"); }
showToast("Estado actualizado correctamente");
closeModal();
refreshData();
} else { alert("Error guardando estado"); }
} catch (e) { alert("Error de conexión al servidor"); }
} }
function showToast(msg) { function showToast(m) {
const t = document.getElementById('toast'); const t = document.getElementById('toast'); document.getElementById('toastMsg').innerText = m;
document.getElementById('toastMsg').innerText = msg; t.classList.remove('opacity-0', '-translate-y-10'); t.classList.add('translate-y-0');
t.classList.remove('opacity-0', 'pointer-events-none', '-translate-y-10'); setTimeout(() => { t.classList.add('opacity-0', '-translate-y-10'); t.classList.remove('translate-y-0'); }, 2000);
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"; } function logout() { localStorage.clear(); window.location.href = "index.html"; }