Files
App/calendario.html
marsalva 8b2fbe4138 Añade Ficha del Cliente: botón en el calendario + nueva página cliente.html
calendario.html: nuevo botón "Ficha del Cliente" en el modal de detalle del servicio (junto a Llamar/WhatsApp). cliente.html: página nueva con datos de contacto, historial de servicios anteriores (todas las compañías) y notas del equipo tipo trazabilidad.
2026-09-07 07:00:06 +00:00

2198 lines
128 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Calendario - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<style>
/* VARIABLES DINÁMICAS: Se actualizarán por JS desde la base de datos */
:root {
--primary: #1e3a8a;
--secondary: #2563eb;
--app-bg: #f8fafc;
}
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
.fade-in { animation: fadeIn 0.3s ease-out forwards; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
.main-content { padding-bottom: 120px; }
.day-card { transition: all 0.2s; }
/* Uso de variables para los estados activos */
.day-active {
background-color: var(--primary) !important;
color: white !important;
border-color: var(--primary) !important;
transform: scale(1.05);
box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
}
.day-inactive { background-color: white; color: #64748b; border-color: #e2e8f0; }
/* Ajustes de color dinámicos para botones y cabeceras */
.bg-primary-dynamic { background-color: var(--primary) !important; }
.text-primary-dynamic { color: var(--primary) !important; }
.border-primary-dynamic { border-color: var(--primary) !important; }
/* Scroll del Modal */
#serviceModal { position: fixed; inset: 0; z-index: 100; display: none; flex-direction: column; background: var(--app-bg); }
.modal-scroll-area { flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; padding-bottom: 100px; }
/* Caja de descripción sobria */
.desc-box { background: white; border: 1px solid #e2e8f0; border-radius: 1.5rem; padding: 1.25rem; }
/* Estilos para el chat */
.msg-me { background-color: #dcfce7; border-bottom-right-radius: 4px; border: 1px solid #bbf7d0; align-self: flex-end; }
.msg-other { background-color: #f1f5f9; border-bottom-left-radius: 4px; border: 1px solid #e2e8f0; align-self: flex-start; }
/* Modal Nuevo Servicio */
.input-modern { @apply w-full bg-slate-50 border border-slate-200 px-4 py-3 rounded-xl text-sm font-semibold text-slate-700 outline-none transition-all focus:border-blue-500 focus:bg-white focus:ring-2 focus:ring-blue-100; }
.label-modern { @apply block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1.5 ml-1; }
</style>
</head>
<body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative text-left">
<header class="bg-white px-5 pt-safe mt-6 pb-4 shadow-sm z-20 shrink-0 border-b border-slate-200">
<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:scale-95 transition-transform">
<i data-lucide="arrow-left" class="w-5 h-5"></i>
</a>
<div class="flex-1 min-w-0 text-left">
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-0.5 truncate" id="monthYearDisplay">Cargando...</p>
<div class="flex items-center gap-2" onclick="if(lastUnreadCount > 0) showNotifList()">
<h1 class="text-xl font-black tracking-tight text-slate-900 leading-none truncate">Mi Agenda</h1>
<div id="topNotificationBadge" class="hidden bg-red-500 text-white text-[10px] font-black px-1.5 py-0.5 rounded-full animate-bounce shadow-sm border border-white">!</div>
</div>
</div>
<button onclick="openNewServiceModal()" class="w-10 h-10 shrink-0 bg-primary-dynamic rounded-full flex items-center justify-center text-white shadow-md active:scale-90 transition-transform mr-1">
<i data-lucide="plus" class="w-5 h-5"></i>
</button>
<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"><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-right" class="w-5 h-5"></i></button>
</div>
</div>
<div class="overflow-x-auto no-scrollbar py-2 -mx-5 px-5 flex gap-3" id="weekStrip"></div>
</header>
<div id="notifPanel" class="hidden absolute top-32 left-5 right-5 bg-white rounded-3xl shadow-2xl z-50 border border-blue-100 fade-in overflow-hidden">
<div class="p-4 bg-blue-600 text-white flex justify-between items-center">
<span class="text-xs font-black uppercase tracking-widest">Mensajes Pendientes</span>
<button onclick="document.getElementById('notifPanel').classList.add('hidden')"><i data-lucide="x" class="w-4 h-4"></i></button>
</div>
<div id="notifList" class="max-h-60 overflow-y-auto p-2 space-y-2 bg-slate-50">
</div>
</div>
<audio id="notifSound" src="https://assets.mixkit.co/active_storage/sfx/2358/2358-preview.mp3" preload="auto"></audio>
<main class="flex-1 overflow-y-auto no-scrollbar p-5 main-content relative z-10" id="mainArea">
<div id="searchContainer" class="hidden mb-4 relative fade-in">
<i data-lucide="search" class="w-5 h-5 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
<input type="text" id="searchInput" oninput="renderServices()" placeholder="Buscar cliente, dirección o avería..." class="w-full bg-white border border-slate-200 pl-12 pr-4 py-3.5 rounded-2xl text-sm font-bold shadow-sm outline-none focus:ring-2 focus:ring-primary-dynamic transition-all">
</div>
<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-primary-dynamic mb-2"></i>
<p class="text-xs font-bold uppercase tracking-widest text-slate-400">Consultando Base de Datos...</p>
</div>
<div id="dayTitle" class="font-black text-slate-400 uppercase tracking-widest text-[10px] mb-4 hidden text-left">Servicios</div>
<div id="servicesList" class="space-y-4 hidden fade-in"></div>
</main>
<nav class="bg-white/95 backdrop-blur-md border-t border-slate-200 z-20 absolute bottom-0 left-0 w-full rounded-t-[2rem] shadow-[0_-10px_30px_rgba(0,0,0,0.03)]">
<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-primary-dynamic w-20">
<i data-lucide="layout-grid" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-black uppercase tracking-widest">Inicio</span>
</a>
<a href="calendario.html" class="flex flex-col items-center p-2 text-primary-dynamic w-20">
<i data-lucide="calendar-days" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-black uppercase tracking-widest">Agenda</span>
</a>
<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>
<span class="text-[9px] font-bold uppercase tracking-widest">Salir</span>
</button>
</div>
</nav>
<div id="serviceModal" class="translate-y-full transition-transform duration-300">
<div class="pt-safe bg-white border-b border-slate-200 flex justify-between items-center p-4 shrink-0 shadow-sm">
<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>
<div class="flex items-center gap-2 bg-slate-900 px-4 py-1.5 rounded-full">
<i data-lucide="clock" class="w-4 h-4 text-blue-300"></i>
<span class="font-black text-xs text-white uppercase" id="modTime">--:--</span>
</div>
<div class="w-10"></div>
</div>
<div class="modal-scroll-area p-4 space-y-4 no-scrollbar">
<input type="hidden" id="detId">
<input type="hidden" id="detPhoneRaw">
<div id="urgentBanner" class="hidden bg-primary-dynamic text-white p-4 rounded-3xl flex items-center justify-center gap-3 shadow-lg border-b-4 border-slate-700/30">
<i data-lucide="alert-circle" class="w-6 h-6 text-white/80"></i>
<span class="font-black text-sm uppercase tracking-widest">Prioridad Máxima</span>
</div>
<div class="grid grid-cols-2 gap-3">
<button onclick="quickUpdate('camino')" class="bg-white border border-slate-200 text-primary-dynamic font-black p-5 rounded-3xl flex flex-col items-center gap-2 shadow-sm active:bg-slate-50 transition-all text-center">
<i data-lucide="car" class="w-8 h-8"></i>
<span class="text-[10px] uppercase tracking-widest">De Camino</span>
</button>
<button onclick="quickUpdate('trabajando')" class="bg-white border border-slate-200 text-primary-dynamic font-black p-5 rounded-3xl flex flex-col items-center gap-2 shadow-sm active:bg-slate-50 transition-all text-center">
<i data-lucide="hammer" class="w-8 h-8"></i>
<span class="text-[10px] uppercase tracking-widest">He Llegado</span>
</button>
</div>
<div class="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-200 text-left">
<div class="flex justify-between items-center mb-3">
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest truncate max-w-[65%]" id="detCompany">Compañía</p>
<span id="detRef" class="text-xs font-black bg-slate-100 text-slate-600 px-3 py-1 rounded-lg uppercase border border-slate-200 shadow-sm shrink-0"></span>
</div>
<div class="mb-4 flex justify-center w-full">
<span id="detStatusCia" class="bg-blue-50 text-primary-dynamic border border-blue-200 font-black text-[10px] sm:text-xs px-4 py-1.5 rounded-xl uppercase tracking-widest inline-flex justify-center text-center shadow-sm leading-tight max-w-full break-words">
--
</span>
</div>
<h2 id="detName" class="text-2xl font-black text-slate-900 uppercase leading-none mb-3">Nombre Cliente</h2>
<button onclick="copyAndOpenPortal()" id="btnPortal" class="w-full mb-6 bg-indigo-50 text-indigo-700 hover:bg-indigo-100 font-black py-2.5 rounded-xl border border-indigo-200 flex items-center justify-center gap-2 text-[10px] uppercase tracking-widest active:scale-95 transition-all text-center">
<i data-lucide="external-link" class="w-4 h-4"></i> Copiar y Abrir Portal
</button>
<div id="phoneSelectorRow" class="hidden flex items-center gap-2 mb-3 overflow-x-auto no-scrollbar"></div>
<button onclick="callClient()" class="w-full bg-primary-dynamic text-white font-black py-4 rounded-2xl shadow-xl 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-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center">
<i data-lucide="message-circle" class="w-4 h-4 text-emerald-500"></i> WhatsApp
</button>
<button onclick="abrirFichaCliente()" class="w-full mt-3 bg-slate-50 text-slate-700 font-black py-3 rounded-2xl border border-slate-200 flex items-center justify-center gap-2 text-xs uppercase tracking-widest active:scale-95 transition-all text-center">
<i data-lucide="user-round" class="w-4 h-4 text-primary-dynamic"></i> Ficha del Cliente
</button>
</div>
<div class="bg-white border border-slate-200 rounded-3xl overflow-hidden shadow-sm text-left">
<button onclick="toggleChat()" class="w-full p-5 flex justify-between items-center text-xs font-black text-slate-800 uppercase tracking-widest bg-blue-50/50">
<div class="flex items-center gap-2 text-blue-600">
<i data-lucide="message-square" class="w-5 h-5"></i> Chat con Oficina
</div>
<i data-lucide="chevron-down" id="chatChevron" class="w-5 h-5 text-blue-400 transition-transform"></i>
</button>
<div id="chatContainer" class="hidden flex-col h-80 bg-slate-50">
<div id="chatBox" class="flex-1 overflow-y-auto p-4 space-y-3 flex flex-col no-scrollbar bg-slate-100">
</div>
<div class="p-3 bg-white border-t border-slate-200 shrink-0 flex gap-2">
<input type="text" id="chatInput" placeholder="Mensaje para oficina..." class="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm font-medium outline-none focus:ring-2 focus:ring-blue-500">
<button onclick="sendChatMessage()" class="bg-blue-600 text-white p-3 rounded-xl shadow-md active:scale-95 shrink-0">
<i data-lucide="send" class="w-5 h-5"></i>
</button>
</div>
</div>
</div>
<div class="bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-200 relative overflow-hidden text-left">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Ubicación</p>
<p id="detAddress" class="text-base font-bold text-slate-900 uppercase leading-tight mb-6"></p>
<div class="flex items-center justify-between bg-slate-50 p-4 rounded-2xl border border-slate-100">
<div id="gpsLoading" class="text-xs font-bold text-slate-400 flex items-center gap-2"><i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> GPS...</div>
<div id="gpsResult" class="hidden flex gap-4 text-slate-900">
<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 class="w-px h-6 bg-slate-200"></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>
</div>
<button onclick="openMaps()" class="bg-primary-dynamic text-white px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest shadow-md active:scale-90 transition-transform">Ver Mapa</button>
</div>
</div>
<div class="bg-white border border-slate-200 rounded-3xl p-5 shadow-sm space-y-4 text-left">
<p class="text-[10px] font-black text-blue-600 uppercase tracking-widest border-b border-slate-100 pb-2 flex items-center gap-1.5"><i data-lucide="calendar-clock" class="w-4 h-4"></i> Asignar Fechas y Tiempos</p>
<div class="grid grid-cols-2 gap-3 text-left">
<div>
<label class="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1 ml-1">Fecha</label>
<input type="date" id="dateInput" onchange="renderModalAgenda()" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
</div>
<div>
<label class="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1 ml-1">Hora Inicio</label>
<input type="time" id="timeInput" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
</div>
</div>
<div id="modalAgendaContainer" class="hidden mt-3 text-left bg-slate-50 border border-slate-200 rounded-xl p-3">
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="eye" class="w-3 h-3"></i> Ocupación del día seleccionado</p>
<div id="modalAgendaList" class="flex flex-wrap gap-2"></div>
</div>
<label class="flex items-center gap-2 bg-amber-50 border border-amber-100 rounded-xl px-3 py-2.5 cursor-pointer">
<input type="checkbox" id="multiDayToggle" onchange="toggleMultiDay(this.checked)" class="w-4 h-4 rounded text-amber-600">
<span class="text-[10px] font-black text-amber-700 uppercase tracking-widest">Obra / instalación de varios días</span>
</label>
<div id="singleDayDuration">
<label class="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1 ml-1 text-left">Duración Estimada</label>
<div class="relative text-left">
<select id="durationInput" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all appearance-none pr-8 cursor-pointer">
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="45">45 min</option>
<option value="60" selected>1 h</option>
<option value="75">1 h 15 min</option>
<option value="90">1 h 30 min</option>
<option value="105">1 h 45 min</option>
<option value="120">2 h</option>
<option value="150">2 h 30 min</option>
<option value="180">3 h</option>
<option value="210">3 h 30 min</option>
<option value="240">4 h</option>
</select>
<i data-lucide="clock" class="w-4 h-4 absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
<div id="multiDayFields" class="hidden">
<label class="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1 ml-1 text-left">Fin de la obra</label>
<div class="grid grid-cols-2 gap-3 text-left">
<input type="date" id="endDateInput" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none">
<input type="time" id="endTimeInput" value="18:00" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none">
</div>
</div>
<div class="pt-2 text-left">
<p class="text-[10px] font-black text-slate-800 uppercase ml-1 flex items-center gap-1.5 mb-1.5"><i data-lucide="arrow-right-left" class="w-4 h-4 text-blue-500"></i> Cambio de Estado</p>
<div class="relative text-left">
<select id="detStatusMap" class="w-full bg-slate-50 border border-slate-200 text-slate-800 p-3.5 rounded-xl text-xs font-black shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all cursor-pointer appearance-none pr-10">
</select>
<i data-lucide="chevron-down" class="w-5 h-5 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
</div>
<button id="btnSaveAppt" onclick="saveAppointment()" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-3.5 rounded-xl shadow-lg transition-all uppercase tracking-widest text-xs flex items-center justify-center gap-2 mt-2 text-center">
<i data-lucide="save" class="w-4 h-4"></i> Guardar Cambios
</button>
</div>
<div class="desc-box text-left">
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-3 flex items-center gap-2"><i data-lucide="file-text" class="w-4 h-4"></i> Descripción del Servicio</p>
<div id="detDesc" class="text-sm font-bold text-slate-600 leading-relaxed max-h-60 overflow-y-auto no-scrollbar">--</div>
</div>
<div class="bg-white border border-slate-200 rounded-3xl overflow-hidden shadow-sm text-left">
<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 bg-slate-50">
<span>Ficha técnica completa</span>
<i data-lucide="chevron-right" class="w-4 h-4 text-slate-400"></i>
</button>
<div id="extraDataBox" class="hidden p-5 space-y-3 bg-white border-t border-slate-100">
</div>
</div>
<div class="bg-white p-5 rounded-[2rem] shadow-sm border border-slate-200 text-left">
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-3 flex items-center gap-1.5"><i data-lucide="clipboard-signature" class="w-4 h-4"></i> Parte de Trabajo</p>
<button onclick="openWorkReportModal()" class="w-full bg-slate-800 text-white font-black py-3.5 rounded-xl shadow-md flex items-center justify-center gap-2 uppercase text-xs tracking-widest active:scale-95 transition-all">
<i data-lucide="file-signature" class="w-4 h-4"></i> Crear Parte de Trabajo
</button>
</div>
<div class="pt-4 text-center">
<button onclick="askToFinish()" class="w-full bg-emerald-600 text-white font-black py-5 rounded-[2rem] shadow-xl flex items-center justify-center gap-3 uppercase text-sm tracking-widest active:scale-95 transition-all">
<i data-lucide="check-circle" class="w-6 h-6"></i> Finalizar Trabajo
</button>
<p class="text-center text-[9px] font-bold text-slate-400 mt-6 uppercase tracking-widest">IntegraRepara Mobile</p>
</div>
</div>
</div>
<div id="workReportModal" class="translate-y-full transition-transform duration-300 fixed inset-0 z-[160] flex flex-col bg-slate-50" style="display:none;">
<div class="pt-safe bg-white border-b border-slate-200 flex justify-between items-center p-4 shrink-0 shadow-sm">
<button type="button" onclick="closeWorkReportModal()" class="bg-slate-100 p-2.5 rounded-full text-slate-600 active:scale-90 transition-transform"><i data-lucide="x" class="w-6 h-6"></i></button>
<h2 class="font-black text-slate-800 text-sm uppercase tracking-widest text-center">Parte de Trabajo</h2>
<div class="w-10"></div>
</div>
<div class="flex-1 overflow-y-auto p-5 space-y-5 no-scrollbar pb-40">
<div class="bg-white p-5 rounded-3xl shadow-sm border border-slate-200 space-y-3 text-left">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5"><i data-lucide="pencil-line" class="w-4 h-4 text-blue-500"></i> Descripción del trabajo realizado</p>
<textarea id="wrText" rows="6" placeholder="Escribe aquí, con tus palabras, lo que has hecho (diagnóstico, piezas, reparación...)" class="input-modern w-full resize-none leading-relaxed"></textarea>
<button type="button" id="btnImproveAI" onclick="improveReportWithAI()" class="w-full bg-indigo-50 text-indigo-700 hover:bg-indigo-100 font-black py-3 rounded-xl border border-indigo-200 flex items-center justify-center gap-2 text-[10px] uppercase tracking-widest active:scale-95 transition-all">
<i data-lucide="sparkles" class="w-4 h-4"></i> Mejorar con IA
</button>
<p class="text-[9px] text-slate-400 font-medium leading-relaxed">La IA redacta el texto de forma profesional. Puedes seguir editándolo después a mano.</p>
</div>
<div class="bg-white p-5 rounded-3xl shadow-sm border border-slate-200 space-y-3 text-left">
<div class="flex justify-between items-center">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5"><i data-lucide="signature" class="w-4 h-4 text-blue-500"></i> Firma del cliente</p>
<button type="button" onclick="clearSignature()" class="text-[9px] font-black text-slate-400 uppercase tracking-widest active:scale-95">Borrar</button>
</div>
<canvas id="signatureCanvas" class="w-full h-44 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-300" style="touch-action:none;"></canvas>
<p class="text-[9px] text-slate-400 font-medium">Pásale el móvil al cliente para que firme aquí antes de enviar el parte.</p>
</div>
<div class="bg-white p-5 rounded-3xl shadow-sm border border-slate-200 space-y-3 text-left">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5"><i data-lucide="phone-forwarded" class="w-4 h-4 text-blue-500"></i> Enviar también a otro número (opcional)</p>
<input type="tel" id="wrExtraPhone" placeholder="Ej: 600123456" class="input-modern w-full">
<p class="text-[9px] text-slate-400 font-medium">El parte se envía siempre al teléfono del cliente. Si quieres, aquí puedes añadir un número extra (p.ej. la aseguradora).</p>
</div>
<button type="button" id="btnGenerateReport" onclick="generateAndSendWorkReport()" class="w-full bg-primary-dynamic text-white font-black py-4 rounded-2xl shadow-xl flex items-center justify-center gap-2 uppercase tracking-widest active:scale-95 transition-all text-xs">
<i data-lucide="send" class="w-5 h-5"></i> Generar PDF y Enviar por WhatsApp
</button>
<div class="pt-2">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="history" class="w-4 h-4"></i> Partes anteriores de este servicio</p>
<div id="wrHistoryListModal" class="space-y-2"></div>
</div>
</div>
</div>
<div id="wr-pdf-wrapper" class="hidden">
<div id="wr-pdf-content" style="background-color: white; color: #1e293b; font-family: Arial, Helvetica, sans-serif; width: 800px; min-height: 1120px; position: relative; padding: 30px 40px; box-sizing: border-box;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; border-bottom: 2px solid #e2e8f0; padding-bottom: 15px; margin-bottom: 20px;">
<div style="max-width: 250px; max-height: 80px;">
<img id="wrPdfLogo" src="" alt="Logo Empresa" style="max-width: 100%; max-height: 80px; object-fit: contain; display: none;">
<h2 id="wrPdfLogoFallback" style="margin:0; color:#1e3a8a; font-size: 22px; font-weight: 900; display: none;">IntegraRepara</h2>
</div>
<div style="text-align: right; font-size: 11px; color: #64748b; line-height: 1.4;">
<div id="wrPdfCompanyName" style="font-size: 14px; font-weight: 900; color: #0f172a; margin-bottom: 2px;">Empresa S.L.</div>
<div id="wrPdfCompanyDni"></div>
<div id="wrPdfCompanyAddress"></div>
<div id="wrPdfCompanyLocation"></div>
</div>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
<div>
<h1 style="font-size: 24px; font-weight: 900; color: #1e3a8a; margin: 0 0 5px 0; letter-spacing: -1px;">PARTE DE TRABAJO</h1>
<div style="font-size: 12px; color: #64748b; line-height: 1.4;">
<strong>Expediente:</strong> <span id="wrPdfRef">#---</span><br>
<strong>Fecha:</strong> <span id="wrPdfDate">01/01/2026</span><br>
<strong>Atendido por:</strong> <span id="wrPdfOperatorName">-</span>
</div>
</div>
<div style="background-color: #f8fafc; border: 1px solid #e2e8f0; padding: 12px 15px; border-radius: 8px; width: 280px;">
<h3 style="margin: 0 0 5px 0; font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; font-weight: 800;">Cliente:</h3>
<p id="wrPdfClientName" style="font-size: 14px; font-weight: 800; color: #0f172a; margin: 0 0 4px 0;">Nombre Cliente</p>
<p style="font-size: 12px; margin: 0; color: #475569; line-height: 1.4;">
<span id="wrPdfClientPhone">Teléfono</span><br>
<span id="wrPdfClientAddress">Dirección</span>
</p>
</div>
</div>
<div style="margin-bottom: 30px;">
<h3 style="margin: 0 0 8px 0; font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; font-weight: 800;">Trabajo realizado</h3>
<div id="wrPdfText" style="font-size: 12px; color: #334155; line-height: 1.7; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px; white-space: pre-wrap;"></div>
</div>
<div style="position: absolute; bottom: 30px; left: 40px; right: 40px;">
<div style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px; margin-bottom: 15px;">
<p style="margin: 0 0 8px 0; font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; font-weight: 800;">Firma del cliente (conforme al trabajo realizado)</p>
<img id="wrPdfSignatureImg" src="" style="max-height: 90px; display: none;">
<p id="wrPdfSignaturePlaceholder" style="font-size: 11px; color: #94a3b8; font-style: italic; display: none;">Sin firma</p>
</div>
<div style="text-align: center; font-size: 9px; color: #94a3b8; border-top: 1px solid #e2e8f0; padding-top: 10px;">
Documento generado por IntegraRepara - Sistema de Gestión de Asistencias
</div>
</div>
</div>
</div>
<div id="newServiceModal" class="translate-y-full transition-transform duration-300 fixed inset-0 z-[150] flex flex-col bg-slate-50" style="display:none;">
<div class="pt-safe bg-white border-b border-slate-200 flex justify-between items-center p-4 shrink-0 shadow-sm">
<button type="button" onclick="closeNewServiceModal()" class="bg-slate-100 p-2.5 rounded-full text-slate-600 active:scale-90 transition-transform"><i data-lucide="x" class="w-6 h-6"></i></button>
<h2 class="font-black text-slate-800 text-sm uppercase tracking-widest text-center">Nuevo Aviso</h2>
<div class="w-10"></div>
</div>
<form onsubmit="saveNewServiceApp(event)" class="flex-1 overflow-y-auto p-5 space-y-5 no-scrollbar pb-32">
<div class="bg-white p-5 rounded-3xl shadow-sm border border-slate-200 space-y-4 text-left">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5"><i data-lucide="user" class="w-4 h-4 text-blue-500"></i> Datos Cliente</p>
<div>
<label class="label-modern">Teléfono</label>
<input type="tel" id="nsPhone" oninput="searchClientApp(this.value)" placeholder="Ej: 600123456" class="input-modern" required>
</div>
<div>
<label class="label-modern">Nombre</label>
<input type="text" id="nsName" placeholder="Nombre completo" class="input-modern" required>
</div>
<div>
<label class="label-modern">Dirección</label>
<input type="text" id="nsAddress" placeholder="Calle, número, piso..." class="input-modern" required>
</div>
</div>
<div class="bg-white p-5 rounded-3xl shadow-sm border border-slate-200 space-y-5 text-left flex flex-col w-full">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5 w-full"><i data-lucide="calendar" class="w-4 h-4 text-emerald-500"></i> Cita y Avería</p>
<div class="grid grid-cols-2 gap-3 w-full">
<div class="w-full">
<label class="label-modern">Día</label>
<input type="date" id="nsDate" onchange="renderNewServiceAgenda()" class="input-modern w-full" required>
</div>
<div class="w-full">
<label class="label-modern">Hora</label>
<input type="time" id="nsTime" class="input-modern w-full" required>
</div>
</div>
<div id="nsAgendaContainer" class="hidden mt-2 text-left bg-blue-50/50 border border-blue-100 rounded-xl p-4 w-full">
<p class="text-[9px] font-black text-blue-500 uppercase tracking-widest mb-3 flex items-center gap-1.5"><i data-lucide="map" class="w-4 h-4"></i> Tu ruta para este día</p>
<div id="nsAgendaList" class="flex flex-col gap-2 w-full"></div>
</div>
<label class="w-full flex items-center gap-2 bg-amber-50 border border-amber-100 rounded-xl px-3 py-2.5 cursor-pointer">
<input type="checkbox" id="multiDayToggleNew" onchange="toggleMultiDayNew(this.checked)" class="w-4 h-4 rounded text-amber-600">
<span class="text-[10px] font-black text-amber-700 uppercase tracking-widest">Obra / instalación de varios días</span>
</label>
<div class="w-full" id="singleDayDurationNew">
<label class="label-modern">Tiempo Estimado</label>
<div class="relative w-full">
<select id="nsDuration" class="input-modern w-full appearance-none pr-8 cursor-pointer">
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="45">45 min</option>
<option value="60" selected>1 h</option>
<option value="90">1.5 h</option>
<option value="120">2 h</option>
<option value="180">3 h</option>
<option value="240">4 h</option>
</select>
<i data-lucide="chevron-down" class="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
<div class="w-full hidden" id="multiDayFieldsNew">
<label class="label-modern">Fin de la obra</label>
<div class="grid grid-cols-2 gap-3 w-full">
<input type="date" id="endDateInputNew" class="input-modern w-full">
<input type="time" id="endTimeInputNew" value="18:00" class="input-modern w-full">
</div>
</div>
<div class="w-full">
<label class="label-modern">Descripción del Trabajo</label>
<textarea id="nsDesc" rows="4" placeholder="Detalle de la avería..." class="input-modern w-full resize-none leading-relaxed" required></textarea>
</div>
</div>
<button type="submit" id="btnSaveNewApp" class="w-full bg-primary-dynamic text-white font-black py-4 rounded-2xl shadow-xl flex items-center justify-center gap-2 uppercase tracking-widest active:scale-95 transition-all text-xs">
<i data-lucide="check-circle" class="w-5 h-5"></i> Crear y Citar
</button>
</form>
</div>
<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" class="w-4 h-4 text-emerald-400"></i>
<span id="toastMsg">Guardado</span>
</div>
<script>
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
? 'http://localhost:3000'
: 'https://integrarepara-api.integrarepara.es';
let localServices = [];
let systemStatuses = [];
let systemGuilds = [];
let currentWeekStart = new Date();
let selectedDateStr = "";
let activeNotifications = []; // Variable global para guardar IDs con mensajes
// 🛰️ SEGUIMIENTO GPS EN VIVO MIENTRAS EL AVISO ESTÁ "DE CAMINO"
let gpsPingIntervalId = null;
const GPS_PING_KEY = 'active_camino_service';
const GPS_PING_INTERVAL_MS = 25000; // cada 25s, mientras la página siga abierta
const GPS_PING_MAX_MS = 3 * 60 * 60 * 1000; // corte de seguridad: 3h sin cambiar de estado
async function applyTheme() {
try {
let theme = JSON.parse(localStorage.getItem('app_theme'));
const res = await fetch(`${API_URL}/config/company`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if(data.ok && data.config && data.config.portal_settings && data.config.portal_settings.app_settings) {
theme = data.config.portal_settings.app_settings;
localStorage.setItem('app_theme', JSON.stringify(theme));
}
if(theme) {
document.documentElement.style.setProperty('--primary', theme.primary);
document.documentElement.style.setProperty('--secondary', theme.secondary);
document.documentElement.style.setProperty('--app-bg', theme.bg);
}
} catch (e) { console.warn("Usando tema por defecto"); }
}
function safeLoadIcons() {
try { if (typeof lucide !== 'undefined') lucide.createIcons(); }
catch(e) { }
}
function toISODate(dateObj) {
try {
if (!dateObj || isNaN(dateObj)) return "";
const y = dateObj.getFullYear();
const m = String(dateObj.getMonth() + 1).padStart(2, '0');
const d = String(dateObj.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
} catch(e) { return ""; }
}
function getMonday(d) {
const date = new Date(d);
const day = date.getDay();
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
document.addEventListener("DOMContentLoaded", async () => {
const currentRole = localStorage.getItem("role");
if (!localStorage.getItem("token") || (currentRole !== 'operario' && currentRole !== 'operario_cerrado')) {
window.location.href = "index.html"; return;
}
await applyTheme();
safeLoadIcons();
const today = new Date();
currentWeekStart = getMonday(today);
selectedDateStr = toISODate(today);
buildWeekCalendar();
loadStatuses();
await loadGuilds();
refreshData();
// Comprobar notificaciones al cargar y cada 30 segundos
checkNotifications();
setInterval(checkNotifications, 30000);
// Si veníamos de marcar "De Camino" y se recargó la página (o se reabrió la app),
// retomamos el envío periódico de posición para ese mismo aviso.
try {
const tracked = JSON.parse(localStorage.getItem(GPS_PING_KEY) || 'null');
if (tracked && tracked.id && (Date.now() - tracked.startedAt) < GPS_PING_MAX_MS) {
startGpsTracking(tracked.id);
}
} catch (e) { /* localStorage corrupto o no disponible: seguimos sin reanudar */ }
});
let lastUnreadCount = 0; // Para saber si el número ha subido y sonar
async function checkNotifications() {
try {
const res = await fetch(`${API_URL}/worker/notifications`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
activeNotifications = data.serviceIds;
const badge = document.getElementById('topNotificationBadge');
const panel = document.getElementById('topNotificationBadge').parentElement; // El contenedor para el click
if (data.unreadCount > 0) {
badge.classList.remove('hidden');
badge.innerText = data.unreadCount;
// Si hay más mensajes que antes, ¡SUENA!
if (data.unreadCount > lastUnreadCount) {
document.getElementById('notifSound').play().catch(e => console.warn("Audio bloqueado por el navegador"));
}
// Hacer que el globo sea clicable
badge.style.cursor = 'pointer';
badge.onclick = (e) => { e.stopPropagation(); showNotifList(); };
} else {
badge.classList.add('hidden');
}
lastUnreadCount = data.unreadCount;
renderServices(); // Refrescamos iconos en tarjetas
}
} catch (e) {}
}
async function showNotifList() {
const panel = document.getElementById('notifPanel');
const list = document.getElementById('notifList');
panel.classList.remove('hidden');
list.innerHTML = '<p class="text-center p-4 text-xs font-bold text-slate-400">Cargando...</p>';
// Obtenemos los nombres de los siniestros con mensajes
list.innerHTML = activeNotifications.map(id => {
const s = localServices.find(x => x.id === id);
const name = s ? (s.raw_data["Nombre Cliente"] || "Expediente") : "Nuevo Mensaje";
const ref = s ? s.service_ref : id;
return `
<div onclick="openService(${id}); document.getElementById('notifPanel').classList.add('hidden')" class="bg-white p-3 rounded-xl border border-slate-200 flex items-center justify-between active:scale-95 transition-all">
<div class="flex flex-col">
<span class="text-[10px] font-black text-blue-600 uppercase">#${ref}</span>
<span class="text-xs font-bold text-slate-700">${name}</span>
</div>
<i data-lucide="chevron-right" class="w-4 h-4 text-slate-300"></i>
</div>
`;
}).join('');
safeLoadIcons();
}
async function loadGuilds() {
try {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) systemGuilds = data.guilds;
} catch(e){}
}
function buildWeekCalendar() {
const strip = document.getElementById('weekStrip');
strip.innerHTML = '';
const monthName = currentWeekStart.toLocaleDateString('es-ES', { month: 'long', year: 'numeric' });
document.getElementById('monthYearDisplay').innerText = monthName;
for(let i = 0; i < 7; i++) {
let d = new Date(currentWeekStart);
d.setDate(currentWeekStart.getDate() + i);
const isoDate = toISODate(d);
const dayName = d.toLocaleDateString('es-ES', { weekday: 'short' }).replace('.', '');
const dayNum = d.getDate();
const isSelected = isoDate === selectedDateStr;
strip.innerHTML += `
<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">
<span class="text-[9px] font-black uppercase opacity-70">${dayName}</span>
<span class="text-xl font-black mt-1">${dayNum}</span>
<div class="mt-2 w-full flex justify-center h-1.5"><span id="badge-${isoDate}" class="bg-primary-dynamic w-1.5 h-1.5 rounded-full hidden opacity-50"></span></div>
</button>`;
}
updateBadges();
safeLoadIcons();
}
function changeWeek(offset) {
currentWeekStart.setDate(currentWeekStart.getDate() + (offset * 7));
selectedDateStr = toISODate(currentWeekStart);
buildWeekCalendar();
renderServices();
}
function selectDate(isoDate) {
selectedDateStr = isoDate;
buildWeekCalendar();
renderServices();
}
async function loadStatuses() {
try {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
systemStatuses = data.statuses;
const modalSelect = document.getElementById('detStatusMap');
modalSelect.innerHTML = '';
systemStatuses.forEach(st => {
modalSelect.innerHTML += `<option value="${st.id}">${st.name.toUpperCase()}</option>`;
});
}
} catch (e) {}
}
async function refreshData() {
document.getElementById('servicesList').classList.add('hidden');
document.getElementById('loader').classList.remove('hidden');
try {
const res = await fetch(`${API_URL}/services/active`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
localServices = data.services.filter(s => {
const raw = s.raw_data || {};
return String(raw.scheduled_date || "").trim() !== "";
});
buildWeekCalendar();
renderServices();
}
} catch (e) {
} finally {
document.getElementById('loader').classList.add('hidden');
document.getElementById('searchContainer').classList.remove('hidden'); // <-- Enciende el buscador
document.getElementById('dayTitle').classList.remove('hidden');
document.getElementById('servicesList').classList.remove('hidden');
}
}
function updateBadges() {
document.querySelectorAll('[id^="badge-"]').forEach(el => el.classList.add('hidden'));
const counts = {};
localServices.forEach(s => {
const date = String(s.raw_data.scheduled_date || "").trim();
if(date) counts[date] = (counts[date] || 0) + 1;
});
for (const [date, qty] of Object.entries(counts)) {
const badge = document.getElementById(`badge-${date}`);
if (badge) badge.classList.remove('hidden');
}
}
const colorMap = {
'gray': { text: 'text-slate-500', bg: 'bg-slate-100', border: 'border-slate-200' },
'blue': { text: 'text-blue-600', bg: 'bg-blue-50', border: 'border-blue-100' },
'amber': { text: 'text-amber-600', bg: 'bg-amber-50', border: 'border-amber-100' },
'emerald': { text: 'text-emerald-600', bg: 'bg-emerald-50', border: 'border-emerald-100' },
'indigo': { text: 'text-indigo-600', bg: 'bg-indigo-50', border: 'border-indigo-100' },
'orange': { text: 'text-orange-600', bg: 'bg-orange-50', border: 'border-orange-100' },
'red': { text: 'text-red-600', bg: 'bg-red-50', border: 'border-red-100' },
'rose': { text: 'text-rose-600', bg: 'bg-rose-50', border: 'border-rose-100' },
'purple': { text: 'text-purple-600', bg: 'bg-purple-50', border: 'border-purple-100' }
};
function renderServices() {
const container = document.getElementById('servicesList');
const dayTitle = document.getElementById('dayTitle');
const displayDate = selectedDateStr.split('-').reverse().join('/');
const queryInput = document.getElementById('searchInput');
const query = queryInput ? queryInput.value.toLowerCase().trim() : "";
let servicesToRender = [];
// 🔥 MODO BÚSQUEDA GLOBAL O MODO DÍA NORMAL 🔥
if (query === "") {
// Modo Normal: Solo mostramos el día seleccionado en el carrusel
dayTitle.innerText = `DÍA ${displayDate}`;
servicesToRender = localServices.filter(s => String(s.raw_data.scheduled_date || "").trim() === selectedDateStr);
// Ordenar por hora
servicesToRender.sort((a, b) => String(a.raw_data.scheduled_time || "23:59").localeCompare(String(b.raw_data.scheduled_time || "23:59")));
} else {
// Modo Búsqueda: Ignoramos el día y buscamos en TODA la agenda
dayTitle.innerText = `RESULTADOS DE BÚSQUEDA TOTA LES`;
servicesToRender = localServices.filter(s => {
const raw = s.raw_data || {};
const searchString = `
${s.service_ref || ""}
${raw["Nombre Cliente"] || raw["CLIENTE"] || ""}
${raw["Dirección"] || raw["DOMICILIO"] || ""}
${raw["Población"] || raw["POBLACION-PROVINCIA"] || ""}
${raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"] || ""}
${raw["Compañía"] || raw["Procedencia"] || ""}
`.toLowerCase();
return searchString.includes(query);
});
// Ordenar por fecha y luego por hora
servicesToRender.sort((a, b) => {
const dateA = String(a.raw_data.scheduled_date || "9999-12-31");
const dateB = String(b.raw_data.scheduled_date || "9999-12-31");
if (dateA !== dateB) return dateA.localeCompare(dateB);
return String(a.raw_data.scheduled_time || "23:59").localeCompare(String(b.raw_data.scheduled_time || "23:59"));
});
}
// Si la lista final está vacía (ya sea por descanso o porque la búsqueda no coincide)
if (servicesToRender.length === 0) {
const isSearch = query !== "";
container.innerHTML = `
<div class="text-center py-20 bg-white rounded-[3rem] border border-slate-100 shadow-sm mt-4">
<i data-lucide="${isSearch ? 'search-x' : 'coffee'}" class="w-12 h-12 text-slate-200 mx-auto mb-3"></i>
<h3 class="font-black text-slate-800">${isSearch ? 'Sin resultados' : 'Día de Descanso'}</h3>
<p class="text-xs text-slate-400 font-medium">${isSearch ? 'No hay coincidencias en toda tu agenda.' : 'No tienes servicios para este día.'}</p>
</div>`;
safeLoadIcons(); return;
}
container.innerHTML = servicesToRender.map(s => {
const raw = s.raw_data || {};
let time = raw.scheduled_time || "--:--";
// 🔥 DETALLE PRO: Si estamos buscando, mostramos el día de la cita en la tarjeta
if (query !== "" && raw.scheduled_date) {
const [y, m, d] = raw.scheduled_date.split('-');
time = `<span class="text-[9px] text-slate-400 font-bold block leading-none mb-0.5">${d}/${m}</span>${time}`;
}
// ¿Tiene este siniestro un mensaje nuevo?
const hasNewMessage = activeNotifications.includes(s.id);
if (s.provider === 'SYSTEM_BLOCK') {
return `<div class="bg-blue-50/50 p-5 rounded-3xl border border-slate-200 flex gap-4"><div class="flex flex-col items-center justify-center border-r border-slate-200 pr-4 shrink-0 text-center"><i data-lucide="lock" class="w-5 h-5 text-primary-dynamic mx-auto"></i><span class="font-black text-primary-dynamic text-sm mt-1">${time}</span></div><div class="min-w-0 flex-1"><h3 class="font-black text-primary-dynamic text-sm uppercase">BLOQUEADO</h3><p class="text-[10px] font-bold text-slate-400 mt-1 uppercase">${raw["Descripción"] || ""}</p></div></div>`;
}
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
const addr = raw["Dirección"] || "---";
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));
let iconName = "clock";
const dbStatId = raw.status_operativo;
const statusObj = systemStatuses.find(st => String(st.id) === String(dbStatId));
const stName = (statusObj?.name || "").toLowerCase();
const stColor = (statusObj?.color || "gray");
if (stName.includes('camino')) iconName = "car";
else if (stName.includes('trabajando') || stName.includes('llegado') || stName.includes('reparación')) iconName = "hammer";
else if (stName.includes('incidencia') || stName.includes('pausa')) iconName = "alert-triangle";
else if (stName.includes('citado')) iconName = "calendar";
else if (stName.includes('finalizado') || stName.includes('terminado') || statusObj?.is_final) iconName = "check-circle";
const cMap = colorMap[stColor] || colorMap['gray'];
// 🛑 NUEVO: EXTRAER ESTADO DE LA COMPAÑÍA
const estadoCia = raw['ACTUALMENTE EN'] || raw['Estado'] || raw['ESTADO'] || raw['Situación'] || "";
const tagEstado = estadoCia ? `<span class="text-[8px] font-black bg-amber-50 text-amber-600 px-2 py-0.5 rounded uppercase border border-amber-200 truncate max-w-[150px]" title="${estadoCia}">${estadoCia}</span>` : '';
// 🛑 NUEVO: EXTRAER Y PINTAR LOS ICONOS DE CANDADO Y OJOS
const hasLock = raw.has_lock === true || String(raw.has_lock) === 'true';
const hasEyes = raw.has_eyes === true || String(raw.has_eyes) === 'true';
let alertBadges = '';
if (hasLock) alertBadges += `<span class="bg-slate-800 text-white px-1.5 py-0.5 rounded text-[10px] shadow-sm inline-flex items-center" title="Gestora (Candado)"><i data-lucide="lock" class="w-3 h-3"></i></span>`;
if (hasEyes) alertBadges += `<span class="bg-amber-500 text-white px-1.5 py-0.5 rounded animate-pulse text-[10px] shadow-sm inline-flex items-center" title="Requiere Información (Ojos)"><i data-lucide="eye" class="w-3 h-3"></i></span>`;
// 👻 NUEVO: EFECTO FANTASMA PARA FINALIZADOS O ANULADOS
let opacityClass = '';
let watermark = '';
if (s.status === 'archived' || stName.includes('finalizado') || stName.includes('terminado') || stName.includes('anulado') || statusObj?.is_final) {
opacityClass = 'opacity-60 grayscale-[50%]'; // Vuelve la tarjeta translúcida y gris
if (stName.includes('anulado')) {
watermark = `<div class="absolute inset-0 z-0 flex items-center justify-center pointer-events-none overflow-hidden">
<span class="text-4xl font-black text-slate-700 opacity-30 -rotate-12 uppercase tracking-widest">Cerrado</span>
</div>`;
} else {
watermark = `<div class="absolute inset-0 z-0 flex items-center justify-center pointer-events-none overflow-hidden">
<span class="text-4xl font-black text-emerald-700 opacity-30 -rotate-12 uppercase tracking-widest">Finalizado</span>
</div>`;
}
}
return `
<div onclick="openService(${s.id})" class="${opacityClass} bg-white p-6 rounded-[2.5rem] border ${hasNewMessage ? 'border-blue-400 ring-2 ring-blue-50' : 'border-slate-200'} shadow-sm active:scale-95 transition-transform flex gap-4 relative overflow-hidden text-left">
${watermark}
${hasNewMessage ? `
<div class="absolute top-2 right-12 flex items-center gap-1 bg-blue-600 text-white text-[8px] font-black px-2 py-1 rounded-full shadow-lg animate-pulse">
<i data-lucide="message-square" class="w-2.5 h-2.5"></i> MENSAJE
</div>
` : ''}
${s.is_urgent ? '<div class="absolute top-0 right-0 bg-primary-dynamic text-white text-[8px] font-black px-3 py-1.5 rounded-bl-xl uppercase tracking-widest z-10">Urgente</div>' : ''}
<div class="flex flex-col items-center justify-center border-r border-slate-100 pr-4 shrink-0 min-w-[70px] text-center">
<div class="${cMap.bg} ${cMap.text} p-2 rounded-xl mb-1 ${cMap.border} border shadow-sm mx-auto">
<i data-lucide="${iconName}" class="w-5 h-5"></i>
</div>
<span class="font-black text-slate-900 text-sm mt-1">${time}</span>
</div>
<div class="min-w-0 flex-1">
<div class="flex flex-wrap gap-1.5 mb-2">
<span class="text-[8px] font-black bg-slate-100 text-slate-500 px-2 py-0.5 rounded uppercase border border-slate-200">${compShort}</span>
<span class="text-[8px] font-black bg-blue-50 text-blue-600 px-2 py-0.5 rounded uppercase border border-blue-100">${guildObj ? guildObj.name : 'Reparación'}</span>
${tagEstado}
</div>
<div class="flex items-center gap-1.5">
<h3 class="font-black text-slate-800 text-sm uppercase leading-tight truncate">${name}</h3>
${alertBadges}
</div>
<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>
</div>`;
}).join('');
// 🛑 NUEVO: Colchón invisible para que el menú inferior no tape la última tarjeta
container.innerHTML += `<div class="h-24 w-full shrink-0 opacity-0 pointer-events-none"></div>`;
safeLoadIcons();
}
let currentServiceId = null;
// --- NUEVA FUNCIÓN: Mostrar la agenda de un día en el Modal ---
function renderModalAgenda() {
const dateInput = document.getElementById('dateInput').value;
const agendaContainer = document.getElementById('modalAgendaContainer');
const agendaList = document.getElementById('modalAgendaList');
const currentId = document.getElementById('detId').value; // Para no mostrarse a sí mismo
if (!dateInput) {
agendaContainer.classList.add('hidden');
return;
}
// Filtrar servicios agendados en la fecha seleccionada que no sean el actual
const dayServices = localServices.filter(s => {
const date = String(s.raw_data.scheduled_date || "").trim();
return date === dateInput && String(s.id) !== String(currentId);
});
// Ordenar cronológicamente
dayServices.sort((a, b) => {
const tA = String(a.raw_data.scheduled_time || "23:59");
const tB = String(b.raw_data.scheduled_time || "23:59");
return tA.localeCompare(tB);
});
if (dayServices.length === 0) {
agendaList.innerHTML = `<span class="text-xs font-bold text-emerald-600 bg-emerald-50 px-3 py-1 rounded-lg border border-emerald-100 w-full text-center">¡Día totalmente libre!</span>`;
} else {
agendaList.innerHTML = dayServices.map(s => {
const time = s.raw_data.scheduled_time || "--:--";
const dur = parseInt(s.raw_data.duration_minutes || 60);
// Calculamos la hora de fin
let endTime = "--:--";
if (time.includes(':')) {
let [h, m] = time.split(':').map(Number);
m += dur;
h += Math.floor(m / 60);
m = m % 60;
endTime = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
}
const city = s.raw_data["Población"] || "Sin Zona";
return `
<div class="bg-white border border-slate-200 rounded-lg p-2 text-xs w-full flex justify-between items-center shadow-sm">
<div class="flex items-center gap-2">
<div class="bg-red-50 text-red-600 font-black px-2 py-1 rounded-md text-[10px]">
${time} - ${endTime}
</div>
<span class="font-bold text-slate-700 truncate max-w-[120px]">${city}</span>
</div>
${s.provider === 'SYSTEM_BLOCK' ? '<i data-lucide="lock" class="w-3.5 h-3.5 text-slate-400"></i>' : ''}
</div>
`;
}).join('');
}
agendaContainer.classList.remove('hidden');
safeLoadIcons();
}
async function openService(id) {
let s = localServices.find(x => x.id === id);
// 🔥 1. Si no lo encontramos en memoria, lo pedimos al servidor
if (!s) {
showToast("Cargando expediente...");
try {
const res = await fetch(`${API_URL}/services/active`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
s = data.services.find(x => x.id === id);
if (s) {
localServices.push(s);
}
}
} catch (e) {
console.error("Error buscando servicio:", e);
}
}
// 👻 2. EL MATA-FANTASMAS: Si definitivamente NO existe (está archivado o reasignado)
if (!s || s.provider === 'SYSTEM_BLOCK') {
try {
// Lo marcamos como leído a la fuerza en la base de datos para matar el globo rojo
await fetch(`${API_URL}/services/${id}/chat/read`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${localStorage.getItem("token")}` }
});
// Refrescamos las notificaciones visuales
if (typeof checkNotifications === "function") checkNotifications();
} catch(e) {}
showToast("Expediente archivado o reasignado. Notificación borrada.", true);
return;
}
// 3. Si existe, lo abrimos normalmente
const raw = s.raw_data;
currentServiceId = id;
document.getElementById('detId').value = s.id;
document.getElementById('modTime').innerText = raw.scheduled_time || "--:--";
document.getElementById('detRef').innerText = `#${s.service_ref || "---"}`;
document.getElementById('detCompany').innerText = raw["Compañía"] || "Particular";
// Rellenar el nuevo campo de estado (Limpio de fechas)
let estadoCia = raw['ACTUALMENTE EN'] || raw['Estado'] || raw['ESTADO'] || raw['Situación'] || "SIN ESTADO";
// Si el estado tiene un paréntesis "(", cortamos todo lo que haya desde ahí
if (estadoCia.includes('(')) {
estadoCia = estadoCia.split('(')[0];
}
// Quitamos espacios extra que hayan podido quedar al cortar
document.getElementById('detStatusCia').innerText = estadoCia.trim();
document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado";
const fullAddress = `${raw["Dirección"] || ""}, ${raw["Código Postal"] || ""} ${raw["Población"] || ""}`;
document.getElementById('detAddress').innerText = fullAddress;
// 📞 Usamos los teléfonos ya extraídos y priorizados (móvil primero) por la API.
// Si por caché no vinieran, caemos al match simple de siempre.
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
const matchPhone = String(rawPhone).match(/[6789]\d{8}/);
const fallbackPhone = matchPhone ? matchPhone[0] : "";
const detailPhones = Array.isArray(s.phones) && s.phones.length > 0
? s.phones
: (fallbackPhone ? [{ number: fallbackPhone, isMobile: /^[67]/.test(fallbackPhone), horario: '', contacto: '' }] : []);
document.getElementById('detPhoneRaw').value = detailPhones[0]?.number || "";
renderPhoneSelector(detailPhones);
const banner = document.getElementById('urgentBanner');
if (s.is_urgent) banner.classList.remove('hidden');
else banner.classList.add('hidden');
document.getElementById('detDesc').innerHTML = (raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.").replace(/\n/g, '<br>');
const extraContainer = document.getElementById('extraDataBox');
extraContainer.innerHTML = '';
let detailsHtml = '';
const skipKeys = ["Nombre Cliente", "CLIENTE", "Dirección", "DOMICILIO", "Población", "POBLACION-PROVINCIA", "scheduled_date", "scheduled_time", "status_operativo", "duration_minutes", "assigned_to", "guild_id", "Código Postal", "assigned_to_name", "Descripción", "DESCRIPCION", "Compañía", "COMPAÑIA", "called_times", "appointment_status"];
for(let key in raw) {
if(skipKeys.includes(key)) continue;
let valStr = String(raw[key] || "");
if(valStr.trim() === "" || valStr === "null") continue;
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>`;
}
extraContainer.innerHTML = detailsHtml || '<p class="text-xs text-slate-400">Sin datos adicionales.</p>';
document.getElementById('dateInput').value = raw.scheduled_date || "";
document.getElementById('timeInput').value = raw.scheduled_time || "";
const existingDuration = parseInt(raw.duration_minutes || 60);
// 🏗️ Si la duración guardada no cabe en el mismo día (p.ej. una obra de varios
// días), abrimos el modal ya en modo "varios días" con la fecha/hora de fin
// calculada, en vez de forzar el desplegable de horas (que solo llega a 4h).
if (raw.scheduled_date && raw.scheduled_time && existingDuration > 240) {
const startDT = new Date(`${raw.scheduled_date}T${raw.scheduled_time}`);
const endDT = new Date(startDT.getTime() + existingDuration * 60000);
document.getElementById('multiDayToggle').checked = true;
document.getElementById('endDateInput').value = toISODate(endDT);
document.getElementById('endTimeInput').value = `${String(endDT.getHours()).padStart(2,'0')}:${String(endDT.getMinutes()).padStart(2,'0')}`;
document.getElementById('durationInput').value = "60";
} else {
document.getElementById('multiDayToggle').checked = false;
document.getElementById('durationInput').value = existingDuration || "60";
}
toggleMultiDay(document.getElementById('multiDayToggle').checked);
const dbStat = raw.status_operativo;
if(dbStat) document.getElementById('detStatusMap').value = dbStat;
renderModalAgenda();
const modal = document.getElementById('serviceModal');
modal.style.display = 'flex';
setTimeout(() => modal.classList.remove('translate-y-full'), 10);
calculateDistance(fullAddress);
// 🔥 AL ABRIR DESDE NOTIFICACIÓN, ABRIMOS EL CHAT AUTOMÁTICAMENTE
if (activeNotifications.includes(id)) {
document.getElementById('chatContainer').classList.remove('hidden');
document.getElementById('chatContainer').classList.add('flex');
document.getElementById('chatChevron').classList.add('rotate-180');
loadChat(id);
} else {
document.getElementById('chatContainer').classList.add('hidden');
document.getElementById('chatContainer').classList.remove('flex');
document.getElementById('chatChevron').classList.remove('rotate-180');
}
safeLoadIcons();
}
function closeModal() {
const modal = document.getElementById('serviceModal');
modal.classList.add('translate-y-full');
setTimeout(() => modal.style.display = 'none', 300);
}
// ==========================================
// 🧾 PARTE DE TRABAJO (texto con IA + firma táctil + PDF + envío WhatsApp)
// ==========================================
let wrOriginalText = "";
let sigCtx = null, sigDrawing = false, sigHasContent = false;
function initSignatureCanvas() {
const canvas = document.getElementById('signatureCanvas');
const ratio = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * ratio;
canvas.height = rect.height * ratio;
sigCtx = canvas.getContext('2d');
sigCtx.scale(ratio, ratio);
sigCtx.strokeStyle = '#0f172a';
sigCtx.lineWidth = 2.5;
sigCtx.lineCap = 'round';
sigCtx.lineJoin = 'round';
sigHasContent = false;
const getPos = (e) => {
const r = canvas.getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
return { x: clientX - r.left, y: clientY - r.top };
};
const start = (e) => { e.preventDefault(); sigDrawing = true; const p = getPos(e); sigCtx.beginPath(); sigCtx.moveTo(p.x, p.y); };
const move = (e) => { if (!sigDrawing) return; e.preventDefault(); const p = getPos(e); sigCtx.lineTo(p.x, p.y); sigCtx.stroke(); sigHasContent = true; };
const end = (e) => { if (e) e.preventDefault(); sigDrawing = false; };
canvas.onmousedown = start; canvas.onmousemove = move; canvas.onmouseup = end; canvas.onmouseleave = end;
canvas.ontouchstart = start; canvas.ontouchmove = move; canvas.ontouchend = end;
}
function clearSignature() {
const canvas = document.getElementById('signatureCanvas');
if (sigCtx) sigCtx.clearRect(0, 0, canvas.width, canvas.height);
sigHasContent = false;
}
async function openWorkReportModal() {
if (!currentServiceId) return;
document.getElementById('wrText').value = '';
wrOriginalText = '';
document.getElementById('wrExtraPhone').value = '';
const modal = document.getElementById('workReportModal');
modal.style.display = 'flex';
setTimeout(() => modal.classList.remove('translate-y-full'), 10);
setTimeout(() => { initSignatureCanvas(); safeLoadIcons(); }, 60);
loadWorkReportHistory(currentServiceId);
}
function closeWorkReportModal() {
const modal = document.getElementById('workReportModal');
modal.classList.add('translate-y-full');
setTimeout(() => modal.style.display = 'none', 300);
}
async function improveReportWithAI() {
const textarea = document.getElementById('wrText');
const text = textarea.value.trim();
if (!text) { showToast("Escribe primero unas notas del trabajo", true); return; }
wrOriginalText = text;
const btn = document.getElementById('btnImproveAI');
const original = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Mejorando...';
safeLoadIcons();
try {
const res = await fetch(`${API_URL}/work-reports/improve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` },
body: JSON.stringify({ text })
});
const data = await res.json();
if (data.ok) {
textarea.value = data.text;
showToast("Texto mejorado. Puedes editarlo antes de enviar.");
} else {
showToast(data.error || "No se pudo mejorar el texto", true);
}
} catch (e) {
showToast("Error de conexión con la IA", true);
} finally {
btn.disabled = false; btn.innerHTML = original; safeLoadIcons();
}
}
async function generateAndSendWorkReport() {
const text = document.getElementById('wrText').value.trim();
if (!text) { showToast("Escribe el texto del parte de trabajo", true); return; }
if (!sigHasContent) {
if (!confirm("No hay firma del cliente. ¿Generar el parte sin firma?")) return;
}
const btn = document.getElementById('btnGenerateReport');
const original = btn.innerHTML;
btn.disabled = true;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Generando PDF...';
safeLoadIcons();
try {
// 1. Datos de la empresa (mismo patrón que en Presupuestos)
let empNombre = "IntegraRepara", empDni = "", empAddress = "", empCity = "", empState = "", empZip = "", empLogo = null;
try {
const confRes = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const confData = await confRes.json();
if (confData.ok && confData.config) {
empLogo = confData.config.company_logo || null;
if (confData.config.billing_settings) {
const b = confData.config.billing_settings;
empNombre = b.name || confData.config.full_name || empNombre;
empDni = b.dni ? `CIF/NIF: ${b.dni}` : "";
empAddress = b.address || "";
empCity = b.city || ""; empState = b.state || ""; empZip = b.zip || "";
} else {
empNombre = confData.config.full_name || empNombre;
}
}
} catch (e) {}
// 2. Nombre del operario logueado
let operatorName = "";
try {
const meRes = await fetch(`${API_URL}/auth/me`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const meData = await meRes.json();
if (meData.ok && meData.user) operatorName = meData.user.full_name || "";
} catch (e) {}
// 3. Rellenar la plantilla oculta del PDF
document.getElementById('wrPdfCompanyName').innerText = empNombre;
document.getElementById('wrPdfCompanyDni').innerText = empDni;
document.getElementById('wrPdfCompanyAddress').innerText = empAddress;
document.getElementById('wrPdfCompanyLocation').innerText = [empZip, empCity, empState ? `(${empState})` : ''].filter(Boolean).join(' ');
const logoImg = document.getElementById('wrPdfLogo');
const logoTxt = document.getElementById('wrPdfLogoFallback');
if (empLogo) { logoImg.src = empLogo; logoImg.style.display = 'block'; logoTxt.style.display = 'none'; }
else { logoImg.style.display = 'none'; logoTxt.innerText = empNombre; logoTxt.style.display = 'block'; }
document.getElementById('wrPdfRef').innerText = document.getElementById('detRef').innerText || '#---';
document.getElementById('wrPdfDate').innerText = new Date().toLocaleDateString('es-ES');
document.getElementById('wrPdfOperatorName').innerText = operatorName || "-";
document.getElementById('wrPdfClientName').innerText = document.getElementById('detName').innerText || "Cliente";
document.getElementById('wrPdfClientPhone').innerText = document.getElementById('detPhoneRaw').value || "-";
document.getElementById('wrPdfClientAddress').innerText = document.getElementById('detAddress').innerText || "-";
document.getElementById('wrPdfText').innerText = text;
const sigCanvas = document.getElementById('signatureCanvas');
const sigImg = document.getElementById('wrPdfSignatureImg');
const sigPlaceholder = document.getElementById('wrPdfSignaturePlaceholder');
let signatureDataUrl = null;
if (sigHasContent) {
signatureDataUrl = sigCanvas.toDataURL('image/png');
sigImg.src = signatureDataUrl;
sigImg.style.display = 'block';
sigPlaceholder.style.display = 'none';
} else {
sigImg.style.display = 'none';
sigPlaceholder.style.display = 'block';
}
// 4. Generar el PDF en base64 a partir de la plantilla oculta
const wrapper = document.getElementById('wr-pdf-wrapper');
wrapper.classList.remove('hidden');
wrapper.style.position = 'absolute';
wrapper.style.left = '-9999px';
const element = document.getElementById('wr-pdf-content');
await new Promise(r => setTimeout(r, 400));
const pdfDataUri = await html2pdf().set({
margin: 0,
image: { type: 'jpeg', quality: 1 },
html2canvas: { scale: 2, useCORS: true, logging: false },
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
}).from(element).outputPdf('datauristring');
wrapper.classList.add('hidden');
wrapper.style.position = '';
wrapper.style.left = '';
// 5. Guardar el parte en el backend
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
safeLoadIcons();
const saveRes = await fetch(`${API_URL}/services/${currentServiceId}/work-report`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` },
body: JSON.stringify({
raw_text: wrOriginalText || text,
final_text: text,
signature_data: signatureDataUrl,
pdf_base64: pdfDataUri
})
});
const saveData = await saveRes.json();
if (!saveData.ok) { showToast(saveData.error || "Error al guardar el parte", true); return; }
// 6. Enviarlo por WhatsApp: al cliente automáticamente + número extra si se indicó
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Enviando por WhatsApp...';
safeLoadIcons();
const extraPhone = document.getElementById('wrExtraPhone').value.trim();
const phones = [];
if (saveData.report.client_phone) phones.push(saveData.report.client_phone);
if (extraPhone) phones.push(extraPhone);
const sendRes = await fetch(`${API_URL}/work-reports/${saveData.report.id}/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` },
body: JSON.stringify({ phones })
});
const sendData = await sendRes.json();
if (sendData.ok) {
showToast("✅ Parte generado y enviado por WhatsApp");
} else {
const firstFail = (sendData.results || []).find(r => !r.ok);
showToast("⚠️ Parte guardado, pero no se pudo enviar por WhatsApp" + (firstFail?.detail ? `: ${firstFail.detail}` : ""), true);
}
closeWorkReportModal();
sendLog("Parte de Trabajo", "Se ha generado un parte de trabajo para este servicio.");
} catch (e) {
console.error(e);
showToast("❌ Error generando el parte de trabajo", true);
} finally {
btn.disabled = false; btn.innerHTML = original; safeLoadIcons();
}
}
async function loadWorkReportHistory(serviceId) {
const list = document.getElementById('wrHistoryListModal');
list.innerHTML = '<p class="text-center text-[10px] text-slate-400 font-bold py-3">Cargando...</p>';
try {
const res = await fetch(`${API_URL}/services/${serviceId}/work-reports`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } });
const data = await res.json();
if (!data.ok || !data.reports || data.reports.length === 0) {
list.innerHTML = '<p class="text-center text-[10px] text-slate-400 font-bold py-3">Sin partes anteriores.</p>';
return;
}
list.innerHTML = data.reports.map(r => {
const d = new Date(r.created_at).toLocaleString('es-ES', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' });
const wasSent = Array.isArray(r.sent_to) && r.sent_to.length > 0;
const sentBadge = wasSent
? `<span class="text-[8px] font-black bg-emerald-50 text-emerald-600 px-2 py-0.5 rounded uppercase border border-emerald-100">Enviado</span>`
: `<span class="text-[8px] font-black bg-amber-50 text-amber-600 px-2 py-0.5 rounded uppercase border border-amber-100">No enviado</span>`;
const preview = (r.final_text || '').substring(0, 60);
return `
<div class="bg-white border border-slate-200 rounded-xl p-3 flex items-center justify-between gap-2">
<div class="min-w-0 flex-1">
<div class="flex items-center gap-1.5 mb-0.5">${sentBadge}<span class="text-[9px] font-bold text-slate-400">${d}</span></div>
<p class="text-[10px] font-bold text-slate-600 truncate">${preview}</p>
</div>
<div class="flex gap-1.5 shrink-0">
<button onclick="viewWorkReportPdf(${r.id})" class="w-8 h-8 bg-slate-50 border border-slate-200 rounded-full flex items-center justify-center active:scale-90"><i data-lucide="eye" class="w-3.5 h-3.5 text-slate-500"></i></button>
<button onclick="resendWorkReport(${r.id})" class="w-8 h-8 bg-slate-50 border border-slate-200 rounded-full flex items-center justify-center active:scale-90"><i data-lucide="send" class="w-3.5 h-3.5 text-blue-500"></i></button>
</div>
</div>`;
}).join('');
safeLoadIcons();
} catch (e) {
list.innerHTML = '<p class="text-center text-[10px] text-rose-400 font-bold py-3">Error al cargar el historial.</p>';
}
}
async function viewWorkReportPdf(reportId) {
try {
const res = await fetch(`${API_URL}/work-reports/${reportId}/pdf`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` } });
const data = await res.json();
if (!data.ok || !data.pdf_base64) return showToast("No se pudo abrir el PDF", true);
const base64 = data.pdf_base64.includes(',') ? data.pdf_base64.split(',').pop() : data.pdf_base64;
const byteChars = atob(base64);
const byteNumbers = new Array(byteChars.length);
for (let i = 0; i < byteChars.length; i++) byteNumbers[i] = byteChars.charCodeAt(i);
const blob = new Blob([new Uint8Array(byteNumbers)], { type: 'application/pdf' });
window.open(URL.createObjectURL(blob), '_blank');
} catch (e) {
showToast("Error al abrir el PDF", true);
}
}
async function resendWorkReport(reportId) {
if (!confirm("¿Reenviar este parte por WhatsApp al teléfono del cliente?")) return;
try {
const res = await fetch(`${API_URL}/work-reports/${reportId}/send`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` },
body: JSON.stringify({})
});
const data = await res.json();
if (data.ok) { showToast("✅ Reenviado por WhatsApp"); loadWorkReportHistory(currentServiceId); }
else showToast("❌ No se pudo reenviar", true);
} catch (e) { showToast("Error de conexión", true); }
}
function sendLog(action, details) {
if(!currentServiceId) return;
fetch(`${API_URL}/services/${currentServiceId}/log`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ action, details })
}).catch(()=>{});
}
function callClient() {
const p = document.getElementById('detPhoneRaw').value;
if (p) {
sendLog("Llamada Telefónica", "El operario ha pulsado el botón de llamar al cliente.");
window.location.href = `tel:+34${p}`;
} else { alert("Sin teléfono"); }
}
function openWhatsApp() {
const p = document.getElementById('detPhoneRaw').value;
if (p) {
sendLog("WhatsApp Abierto", "El operario ha abierto el chat de WhatsApp con el cliente.");
window.open(`https://wa.me/34${p}`, '_blank');
} else { alert("Sin teléfono"); }
}
// 🧑‍🔧 Abre la ficha del cliente (historial de servicios + notas del equipo) con los
// datos que ya tenemos cargados en el modal, para no tener que volver a pedirlos.
function abrirFichaCliente() {
const p = document.getElementById('detPhoneRaw').value;
if (!p) { alert("Este servicio no tiene un teléfono válido para localizar al cliente."); return; }
const nombre = document.getElementById('detName').innerText || "";
const direccion = document.getElementById('detAddress').innerText || "";
const params = new URLSearchParams({ phone: p, nombre, direccion });
window.location.href = `cliente.html?${params.toString()}`;
}
// 📞 Cuando el servicio trae más de un teléfono (típico de HomeServe), pintamos un
// selector de chips para que el operario elija cuál usar antes de Llamar/WhatsApp.
// Con un solo teléfono no mostramos nada (para no añadir ruido visual de más).
function renderPhoneSelector(phones) {
const row = document.getElementById('phoneSelectorRow');
if (!row) return;
if (!phones || phones.length <= 1) { row.innerHTML = ''; row.classList.add('hidden'); return; }
const active = document.getElementById('detPhoneRaw').value;
row.innerHTML = phones.map(p => {
const isActive = p.number === active;
return `
<button type="button" onclick="selectPhone('${p.number}')" class="shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-[10px] font-black uppercase tracking-widest ${isActive ? 'bg-primary-dynamic text-white border-primary-dynamic' : 'bg-white text-slate-500 border-slate-200'}">
<i data-lucide="${p.isMobile ? 'smartphone' : 'phone'}" class="w-3 h-3"></i> ${p.number}
</button>`;
}).join('');
row.classList.remove('hidden');
lucide.createIcons();
}
function selectPhone(number) {
document.getElementById('detPhoneRaw').value = number;
const s = localServices.find(x => String(x.id) === String(document.getElementById('detId').value));
renderPhoneSelector(Array.isArray(s?.phones) && s.phones.length > 0 ? s.phones : [{number, isMobile:/^[67]/.test(number)}]);
}
async function copyAndOpenPortal() {
const btn = document.getElementById('btnPortal');
const originalHtml = btn.innerHTML;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Generando...';
lucide.createIcons();
try {
const phone = document.getElementById('detPhoneRaw').value;
const name = document.getElementById('detName').innerText;
const address = document.getElementById('detAddress').innerText;
if (!phone) {
showToast("Sin teléfono no hay portal", true);
return;
}
const res = await fetch(`${API_URL}/clients/ensure`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ phone, name, address })
});
const data = await res.json();
if (data.ok && data.client.portal_token) {
const link = `https://portal.integrarepara.es/?token=${data.client.portal_token}&service=${currentServiceId}`;
try {
await navigator.clipboard.writeText(link);
showToast("¡Enlace copiado al portapapeles!");
} catch (err) {
console.warn("Navegador bloqueó el copiado automático");
}
sendLog("Portal Generado", "El operario ha generado y abierto el enlace al Portal del Cliente.");
window.open(link, '_blank');
} else {
showToast("Error al obtener el enlace", true);
}
} catch (e) {
showToast("Error de conexión", true);
} finally {
btn.innerHTML = originalHtml;
lucide.createIcons();
}
}
function openMaps() {
const a = document.getElementById('detAddress').innerText;
if (a) {
window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(a)}`, '_blank');
}
}
async function calculateDistance(dest) {
const loading = document.getElementById('gpsLoading');
const result = document.getElementById('gpsResult');
if(!navigator.geolocation) {
loading.innerHTML = '<span class="text-[9px]">GPS Inactivo</span>';
lucide.createIcons();
return;
}
loading.classList.remove('hidden');
loading.innerHTML = '<i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> GPS...';
result.classList.add('hidden');
lucide.createIcons();
const gpsOptions = {
enableHighAccuracy: false,
timeout: 8000,
maximumAge: 300000
};
navigator.geolocation.getCurrentPosition(async (pos) => {
const lat = pos.coords.latitude;
const lon = pos.coords.longitude;
try {
let res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(dest + ', España')}`);
let data = await res.json();
if (!data || data.length === 0) {
const parts = dest.split(',');
const fallbackDest = parts.length > 1 ? parts[parts.length - 1].trim() : dest;
res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(fallbackDest + ', España')}`);
data = await res.json();
}
if (data && data.length > 0) {
const R = 6371; const dLat = (data[0].lat - lat) * Math.PI / 180; const dLon = (data[0].lon - lon) * Math.PI / 180;
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 c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
const km = R * c;
loading.classList.add('hidden');
result.classList.remove('hidden');
document.getElementById('gpsKm').innerText = km.toFixed(1);
document.getElementById('gpsMins').innerText = Math.round((km/35)*60)+5;
} else {
loading.innerHTML = '<span class="text-[9px]">No calculable</span>';
}
} catch(e) {
loading.innerHTML = '<span class="text-[9px]">Error de red</span>';
}
}, (err) => {
loading.innerHTML = '<span class="text-[9px]">GPS Lento/Denegado</span>';
}, gpsOptions);
}
async function quickUpdate(action) {
if(!currentServiceId) return;
let word = ""; let msg = "";
if(action === 'camino') { word = "camino"; msg = "¿Enviar estado 'De Camino'?"; }
if(action === 'trabajando') { word = "trabaja"; msg = "¿Iniciar trabajo?"; }
if(!confirm(msg)) return;
const st = systemStatuses.find(s => s.name.toLowerCase().includes(word));
if(!st) return alert("Estado no encontrado");
try {
const res = await fetch(`${API_URL}/services/set-appointment/${currentServiceId}`, {
method: 'PUT', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status_operativo: st.id })
});
if(res.ok) {
showToast("¡Actualizado!");
if (action === 'camino') {
// Arranca (o retoma) el envío periódico de posición mientras dure el desplazamiento
startGpsTracking(currentServiceId);
} else {
// Cualquier otro cambio de estado (p.ej. "Trabajando") significa que ya ha llegado:
// paramos el seguimiento GPS de este aviso si estaba activo.
stopGpsTrackingIfMatches(currentServiceId);
}
closeModal();
refreshData();
}
} catch (e) { alert("Error al actualizar"); }
}
// Envía una posición puntual del operario para el aviso indicado.
async function sendLocationPing(serviceId) {
if (!navigator.geolocation) return;
navigator.geolocation.getCurrentPosition(async (pos) => {
try {
await fetch(`${API_URL}/services/${serviceId}/location`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ lat: pos.coords.latitude, lng: pos.coords.longitude })
});
} catch (e) { /* fallo puntual de red: lo reintentamos en el siguiente ciclo */ }
}, () => { /* permiso denegado o GPS lento: lo reintentamos en el siguiente ciclo */ }, { enableHighAccuracy: false, timeout: 10000, maximumAge: 15000 });
}
// Arranca el ciclo de posición en vivo para un aviso "De Camino" (o lo retoma si ya estaba en curso).
function startGpsTracking(serviceId) {
if (gpsPingIntervalId) clearInterval(gpsPingIntervalId);
let tracked = null;
try { tracked = JSON.parse(localStorage.getItem(GPS_PING_KEY) || 'null'); } catch (e) {}
const startedAt = (tracked && tracked.id === serviceId) ? tracked.startedAt : Date.now();
localStorage.setItem(GPS_PING_KEY, JSON.stringify({ id: serviceId, startedAt }));
sendLocationPing(serviceId); // envío inmediato, sin esperar al primer ciclo
gpsPingIntervalId = setInterval(() => {
let cur = null;
try { cur = JSON.parse(localStorage.getItem(GPS_PING_KEY) || 'null'); } catch (e) {}
if (!cur || cur.id !== serviceId || (Date.now() - cur.startedAt) > GPS_PING_MAX_MS) {
stopGpsTracking();
return;
}
sendLocationPing(serviceId);
}, GPS_PING_INTERVAL_MS);
}
function stopGpsTracking() {
if (gpsPingIntervalId) { clearInterval(gpsPingIntervalId); gpsPingIntervalId = null; }
localStorage.removeItem(GPS_PING_KEY);
}
// Para el seguimiento solo si el aviso que se está rastreando es este mismo (evita cortar
// el rastreo de OTRO aviso "de camino" si el operario cambia el estado de uno distinto).
function stopGpsTrackingIfMatches(serviceId) {
let cur = null;
try { cur = JSON.parse(localStorage.getItem(GPS_PING_KEY) || 'null'); } catch (e) {}
if (cur && cur.id === serviceId) stopGpsTracking();
}
async function askToFinish() {
if(!currentServiceId) return;
const stFinalizado = systemStatuses.find(s => s.name.toLowerCase().includes('finaliza'));
if(!stFinalizado) return alert("El sistema no tiene un estado Finalizado válido.");
const sendSurvey = confirm("¿Deseas enviar la encuesta de satisfacción al cliente antes de finalizar?");
try {
const res = await fetch(`${API_URL}/services/set-appointment/${currentServiceId}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({
status_operativo: stFinalizado.id,
skip_survey: !sendSurvey
})
});
if(res.ok) {
showToast(sendSurvey ? "Expediente finalizado y encuesta enviada." : "Expediente finalizado.");
stopGpsTrackingIfMatches(currentServiceId);
closeModal();
refreshData();
}
} catch (e) { alert("Error al finalizar."); }
}
async function saveAppointment() {
const id = document.getElementById('detId').value;
const date = document.getElementById('dateInput').value;
const time = document.getElementById('timeInput').value;
const duration = parseInt(document.getElementById('durationInput').value) || 60;
const statusMap = document.getElementById('detStatusMap').value;
const selectedSt = systemStatuses.find(st => String(st.id) === String(statusMap));
if (selectedSt && !selectedSt.is_final && !date && !selectedSt.name.toLowerCase().includes('pausa') && !selectedSt.name.toLowerCase().includes('asignar')) {
if(!confirm("No has asignado Fecha para este estado. ¿Deseas continuar?")) return;
}
// 🛑 NUEVO: RADAR ANTI-SOLAPAMIENTO (Solo si hay fecha y hora)
if (date && time) {
let [newH, newM] = time.split(':').map(Number);
let newStartMin = newH * 60 + newM;
let newEndMin = newStartMin + duration;
const solapamiento = localServices.find(s => {
// Obviamos el propio servicio que estamos editando
if (String(s.id) === String(id)) return false;
const sDate = String(s.raw_data.scheduled_date || "").trim();
const sTime = String(s.raw_data.scheduled_time || "").trim();
// Si coinciden en fecha, miramos las horas
if (sDate === date && sTime && sTime.includes(':')) {
let [sH, sM] = sTime.split(':').map(Number);
let sDur = parseInt(s.raw_data.duration_minutes || 60);
let sStartMin = sH * 60 + sM;
let sEndMin = sStartMin + sDur;
// La fórmula mágica para saber si dos franjas chocan
return (newStartMin < sEndMin && newEndMin > sStartMin);
}
return false;
});
// Si choca, bloqueamos el guardado
if (solapamiento) {
const horaConflicto = solapamiento.raw_data.scheduled_time;
const zonaConflicto = solapamiento.raw_data["Población"] || "otra zona";
alert(`⚠️ SOLAPAMIENTO DETECTADO\n\nEstás pisando otra cita que empieza a las ${horaConflicto} en ${zonaConflicto}.\n\nPor favor, revisa la agenda visual arriba y cambia la hora o la duración.`);
return; // Abortamos aquí, no llega a guardar nada
}
}
// 🛑 FIN DEL RADAR
const btn = document.getElementById('btnSaveAppt');
const originalContent = btn.innerHTML;
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...`;
btn.disabled = true;
safeLoadIcons();
try {
const res = await fetch(`${API_URL}/services/set-appointment/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ date, time, duration_minutes: duration, status_operativo: statusMap })
});
if (res.ok) {
showToast("Estado actualizado");
closeModal();
refreshData();
} else {
alert("Error al guardar");
}
} catch (e) { alert("Error de conexión"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; safeLoadIcons(); }
}
// --- SISTEMA DE CHAT OPERARIO ---
function toggleChat() {
const container = document.getElementById('chatContainer');
const chevron = document.getElementById('chatChevron');
if (container.classList.contains('hidden')) {
container.classList.remove('hidden');
container.classList.add('flex');
chevron.classList.add('rotate-180');
loadChat(currentServiceId);
} else {
container.classList.add('hidden');
container.classList.remove('flex');
chevron.classList.remove('rotate-180');
}
}
async function loadChat(serviceId) {
// 🔔 MARCAR COMO LEÍDO AL ABRIR EL CHAT
try {
fetch(`${API_URL}/services/${serviceId}/chat/read`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem("token")}`
}
}).then(() => {
// Refrescar el globo de notificaciones inmediatamente para que desaparezca
if (typeof checkNotifications === "function") checkNotifications();
});
} catch (e) {
console.error("Error al marcar lectura:", e);
}
const chatBox = document.getElementById('chatBox');
chatBox.innerHTML = '<div class="text-center text-xs font-bold text-slate-400 mt-10 uppercase tracking-widest"><i data-lucide="loader-2" class="w-4 h-4 animate-spin mx-auto mb-2"></i> Cargando...</div>';
safeLoadIcons();
try {
const res = await fetch(`${API_URL}/services/${serviceId}/chat`, {
headers: { 'Authorization': `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
chatBox.innerHTML = '';
if (data.messages.length === 0) {
chatBox.innerHTML = '<div class="text-center text-xs font-bold text-slate-400 mt-10 uppercase tracking-widest">No hay mensajes aún</div>';
return;
}
data.messages.forEach(msg => {
if (msg.is_internal) return;
const isMe = msg.sender_role === 'operario' || msg.sender_role === 'operario_cerrado';
const time = new Date(msg.created_at).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
const date = new Date(msg.created_at).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' });
let bubbleClass = isMe ? 'msg-me' : 'msg-other';
let headerColor = isMe ? 'text-emerald-700' : 'text-slate-600';
const bubbleHtml = `
<div class="flex flex-col p-3 shadow-sm ${bubbleClass} max-w-[85%]">
<div class="flex justify-between items-center border-b ${isMe ? 'border-emerald-200' : 'border-slate-200'} pb-1 mb-1.5 gap-4">
<span class="text-[9px] font-black uppercase ${headerColor} truncate">${isMe ? 'Tú' : msg.sender_name}</span>
<span class="text-[8px] font-bold text-slate-400 shrink-0">${date} ${time}</span>
</div>
<p class="text-xs font-medium text-slate-700 whitespace-pre-wrap">${msg.message}</p>
</div>
`;
chatBox.innerHTML += bubbleHtml;
});
setTimeout(() => { chatBox.scrollTop = chatBox.scrollHeight; }, 100);
}
} catch (e) {
chatBox.innerHTML = '<div class="text-center text-xs font-bold text-red-400 mt-10 uppercase tracking-widest">Error de carga</div>';
}
}
async function sendChatMessage() {
if(!currentServiceId) return;
const input = document.getElementById('chatInput');
const message = input.value.trim();
if (!message) return;
input.disabled = true;
try {
const res = await fetch(`${API_URL}/services/${currentServiceId}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ message, is_internal: false })
});
if (res.ok) {
input.value = '';
loadChat(currentServiceId);
} else {
showToast("Error al enviar mensaje");
}
} catch (e) {
showToast("Error de conexión");
} finally {
input.disabled = false;
}
}
function showToast(m, isError = false) {
const t = document.getElementById('toast');
document.getElementById('toastMsg').innerText = m;
if(isError) {
t.classList.replace('bg-slate-900', 'bg-red-600');
t.innerHTML = `<i data-lucide="alert-circle" class="w-4 h-4 text-white"></i> <span id="toastMsg">${m}</span>`;
} else {
t.classList.replace('bg-red-600', 'bg-slate-900');
t.innerHTML = `<i data-lucide="check" class="w-4 h-4 text-emerald-400"></i> <span id="toastMsg">${m}</span>`;
}
safeLoadIcons();
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'); }, 2000);
}
// =====================================
// FUNCIONES DE ALTA RÁPIDA (OPERARIO)
// =====================================
function openNewServiceModal() {
document.getElementById('nsPhone').value = "";
document.getElementById('nsName').value = "";
document.getElementById('nsAddress').value = "";
document.getElementById('nsDesc').value = "";
document.getElementById('nsTime').value = "";
document.getElementById('nsDate').value = selectedDateStr;
document.getElementById('multiDayToggleNew').checked = false;
document.getElementById('endDateInputNew').value = "";
toggleMultiDayNew(false);
renderNewServiceAgenda(); // <-- Cargamos la ruta del día
const modal = document.getElementById('newServiceModal');
modal.style.display = 'flex';
setTimeout(() => modal.classList.remove('translate-y-full'), 10);
safeLoadIcons();
}
// Dibuja los huecos ocupados para que el operario sepa por dónde se mueve
function renderNewServiceAgenda() {
const dateInput = document.getElementById('nsDate').value;
const agendaContainer = document.getElementById('nsAgendaContainer');
const agendaList = document.getElementById('nsAgendaList');
if (!dateInput) {
agendaContainer.classList.add('hidden');
return;
}
const dayServices = localServices.filter(s => String(s.raw_data.scheduled_date || "").trim() === dateInput);
dayServices.sort((a, b) => {
const tA = String(a.raw_data.scheduled_time || "23:59");
const tB = String(b.raw_data.scheduled_time || "23:59");
return tA.localeCompare(tB);
});
if (dayServices.length === 0) {
agendaList.innerHTML = `<span class="text-[10px] font-bold text-emerald-600 bg-emerald-50 px-3 py-1 rounded-lg border border-emerald-100 text-center">¡Día totalmente libre!</span>`;
} else {
agendaList.innerHTML = dayServices.map(s => {
const time = s.raw_data.scheduled_time || "--:--";
const dur = parseInt(s.raw_data.duration_minutes || 60);
let endTime = "--:--";
if (time.includes(':')) {
let [h, m] = time.split(':').map(Number);
m += dur;
h += Math.floor(m / 60);
m = m % 60;
endTime = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
}
const city = s.raw_data["Población"] || "Sin Zona";
return `
<div class="bg-white border border-blue-100 rounded-lg p-2 text-xs flex justify-between items-center shadow-sm">
<div class="flex items-center gap-2">
<div class="bg-blue-50 text-blue-600 font-black px-2 py-1 rounded-md text-[10px]">
${time} - ${endTime}
</div>
<span class="font-bold text-slate-700 truncate max-w-[150px]">${city}</span>
</div>
</div>
`;
}).join('');
}
agendaContainer.classList.remove('hidden');
safeLoadIcons();
}
function closeNewServiceModal() {
const modal = document.getElementById('newServiceModal');
modal.classList.add('translate-y-full');
setTimeout(() => modal.style.display = 'none', 300);
}
async function searchClientApp(phone) {
if (phone.length < 9) {
document.getElementById('nsName').classList.remove('bg-emerald-50');
return;
}
try {
const res = await fetch(`${API_URL}/clients/search?phone=${phone}`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok && data.client) {
const nameInput = document.getElementById('nsName');
if (!nameInput.value) {
nameInput.value = data.client.full_name;
nameInput.classList.add('bg-emerald-50');
}
if (!document.getElementById('nsAddress').value && data.client.addresses?.length > 0) {
document.getElementById('nsAddress').value = data.client.addresses[0];
}
}
} catch (e) {}
}
// 🏗️ Obras/instalaciones de varios días: en vez de una duración en minutos que
// encaja dentro del mismo día, dejamos indicar fecha+hora de fin (puede ser un día
// distinto). Seguimos usando el mismo modelo de siempre (scheduled_date +
// scheduled_time + duration_minutes): la duración se calcula como los minutos
// reales entre el inicio y el fin.
function toggleMultiDay(checked) {
document.getElementById('singleDayDuration').classList.toggle('hidden', checked);
document.getElementById('multiDayFields').classList.toggle('hidden', !checked);
}
function getAppointmentDuration() {
if (!document.getElementById('multiDayToggle').checked) {
return parseInt(document.getElementById('durationInput').value) || 60;
}
const date = document.getElementById('dateInput').value;
const time = document.getElementById('timeInput').value;
const endDate = document.getElementById('endDateInput').value;
const endTime = document.getElementById('endTimeInput').value || "18:00";
if (!date || !time || !endDate) return null;
const start = new Date(`${date}T${time}`);
const end = new Date(`${endDate}T${endTime}`);
if (isNaN(start) || isNaN(end) || end <= start) return null;
return Math.round((end - start) / 60000);
}
async function saveAppointment() {
const id = document.getElementById('detId').value;
const date = document.getElementById('dateInput').value;
const time = document.getElementById('timeInput').value;
const isMultiDay = document.getElementById('multiDayToggle').checked;
const duration = getAppointmentDuration();
if (isMultiDay && duration === null) return alert("Revisa las fechas/horas de inicio y fin de la obra.");
let statusMap = document.getElementById('detStatusMap').value;
const selectedSt = systemStatuses.find(st => String(st.id) === String(statusMap));
if (selectedSt && !selectedSt.is_final && !date && !selectedSt.name.toLowerCase().includes('pausa') && !selectedSt.name.toLowerCase().includes('asignar')) {
if(!confirm("No has asignado Fecha para este estado. ¿Deseas continuar?")) return;
}
// 🛑 RADAR ANTI-SOLAPAMIENTO (PERMISIVO)
if (date && time) {
const newStart = new Date(`${date}T${time}`);
const newEnd = new Date(newStart.getTime() + duration * 60000);
const solapamiento = localServices.find(s => {
if (String(s.id) === String(id)) return false;
const sDate = String(s.raw_data.scheduled_date || "").trim();
const sTime = String(s.raw_data.scheduled_time || "").trim();
if (sDate && sTime && sTime.includes(':')) {
const sStart = new Date(`${sDate}T${sTime}`);
const sDur = parseInt(s.raw_data.duration_minutes || 60);
const sEnd = new Date(sStart.getTime() + sDur * 60000);
return (newStart < sEnd && newEnd > sStart);
}
return false;
});
if (solapamiento) {
const horaC = solapamiento.raw_data.scheduled_time;
const zonaC = solapamiento.raw_data["Población"] || "otra zona";
// AHORA ES UN CONFIRM: Te avisa, pero te deja pasar si quieres
const forzar = confirm(`⚠️ SOLAPAMIENTO DETECTADO\n\nYa tienes una cita a las ${horaC} en ${zonaC}.\n\n¿Deseas FORZAR el guardado y agendarla en el mismo hueco?`);
if (!forzar) return; // Si cancela, abortamos
}
}
const btn = document.getElementById('btnSaveAppt');
const originalContent = btn.innerHTML;
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...`;
btn.disabled = true;
try {
const res = await fetch(`${API_URL}/services/set-appointment/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ date, time, duration_minutes: duration, status_operativo: statusMap })
});
if (res.ok) {
showToast("Estado actualizado");
closeModal();
refreshData();
} else { alert("Error al guardar"); }
} catch (e) { alert("Error de conexión"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; safeLoadIcons(); }
}
function toggleMultiDayNew(checked) {
document.getElementById('singleDayDurationNew').classList.toggle('hidden', checked);
document.getElementById('multiDayFieldsNew').classList.toggle('hidden', !checked);
}
async function saveNewServiceApp(e) {
e.preventDefault();
const date = document.getElementById('nsDate').value;
const time = document.getElementById('nsTime').value;
let duration;
if (document.getElementById('multiDayToggleNew').checked) {
const endDate = document.getElementById('endDateInputNew').value;
const endTime = document.getElementById('endTimeInputNew').value || "18:00";
if (!date || !time || !endDate) { alert("Revisa las fechas/horas de inicio y fin de la obra."); return; }
const start = new Date(`${date}T${time}`);
const end = new Date(`${endDate}T${endTime}`);
if (isNaN(start) || isNaN(end) || end <= start) { alert("Revisa las fechas/horas de inicio y fin de la obra."); return; }
duration = Math.round((end - start) / 60000);
} else {
duration = parseInt(document.getElementById('nsDuration').value) || 60;
}
// 🛑 RADAR ANTI-SOLAPAMIENTO EN CREACIÓN (PERMISIVO) — comparamos por fecha/hora
// completas para detectar cruces aunque la obra ocupe varios días.
if (date && time) {
const newStart = new Date(`${date}T${time}`);
const newEnd = new Date(newStart.getTime() + duration * 60000);
const solapamiento = localServices.find(s => {
const sDate = String(s.raw_data.scheduled_date || "").trim();
const sTime = String(s.raw_data.scheduled_time || "").trim();
if (sDate && sTime && sTime.includes(':')) {
const sStart = new Date(`${sDate}T${sTime}`);
const sDur = parseInt(s.raw_data.duration_minutes || 60);
const sEnd = new Date(sStart.getTime() + sDur * 60000);
return (newStart < sEnd && newEnd > sStart);
}
return false;
});
if (solapamiento) {
const horaC = solapamiento.raw_data.scheduled_time;
const zonaC = solapamiento.raw_data["Población"] || "otra zona";
const forzar = confirm(`⚠️ SOLAPAMIENTO DETECTADO\n\nYa tienes una cita a las ${horaC} en ${zonaC}.\n\n¿Deseas FORZAR la creación de este aviso en el mismo hueco?`);
if (!forzar) return;
}
}
const btn = document.getElementById('btnSaveNewApp');
const originalHTML = btn.innerHTML;
btn.innerHTML = `<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Procesando...`;
btn.disabled = true;
try {
const token = localStorage.getItem("token");
const payloadDecoded = JSON.parse(atob(token.split('.')[1]));
const myWorkerId = payloadDecoded.sub;
const createData = {
phone: document.getElementById('nsPhone').value,
name: document.getElementById('nsName').value,
address: document.getElementById('nsAddress').value,
description: document.getElementById('nsDesc').value,
guild_id: null,
assigned_to: myWorkerId,
duration_minutes: duration,
is_urgent: false,
is_company: false,
company_name: 'Particular',
company_ref: null,
mode: 'manual'
};
const resCreate = await fetch(`${API_URL}/services/manual-high`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` },
body: JSON.stringify(createData)
});
const dataCreate = await resCreate.json();
if (!dataCreate.ok || !dataCreate.id) throw new Error("No se pudo crear el servicio");
const citadoSt = systemStatuses.find(st => st.name.toLowerCase().includes('citado'));
const statusMapId = citadoSt ? String(citadoSt.id) : null;
await fetch(`${API_URL}/services/set-appointment/${dataCreate.id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` },
body: JSON.stringify({
date: date,
time: time,
duration_minutes: duration,
status_operativo: statusMapId
})
});
closeNewServiceModal();
showToast("¡Aviso Creado y Citado!");
refreshData();
} catch (err) {
showToast("Error al guardar", true);
} finally {
btn.innerHTML = originalHTML;
btn.disabled = false;
safeLoadIcons();
}
}
function logout() { localStorage.clear(); window.location.href = "index.html"; }
</script>
</body>
</html>