1603 lines
90 KiB
HTML
1603 lines
90 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>
|
|
<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>
|
|
|
|
<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>
|
|
</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>
|
|
|
|
<div>
|
|
<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 (Máx)</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 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 Técnica</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="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="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>
|
|
|
|
<div class="w-full">
|
|
<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">
|
|
<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
|
|
|
|
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);
|
|
});
|
|
|
|
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;
|
|
|
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
const matchPhone = String(rawPhone).match(/[6789]\d{8}/);
|
|
document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : "";
|
|
|
|
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 || "";
|
|
document.getElementById('durationInput').value = raw.duration_minutes || "60";
|
|
|
|
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);
|
|
}
|
|
|
|
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"); }
|
|
}
|
|
|
|
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' && navigator.geolocation) {
|
|
navigator.geolocation.getCurrentPosition(async (pos) => {
|
|
await fetch(`${API_URL}/services/${currentServiceId}/location`, {
|
|
method: 'POST',
|
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
|
body: JSON.stringify({ lat: pos.coords.latitude, lng: pos.coords.longitude })
|
|
});
|
|
}, () => {}, { enableHighAccuracy: false, timeout: 10000 });
|
|
}
|
|
|
|
closeModal();
|
|
refreshData();
|
|
}
|
|
} catch (e) { alert("Error al actualizar"); }
|
|
}
|
|
|
|
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.");
|
|
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;
|
|
|
|
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) {}
|
|
}
|
|
|
|
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;
|
|
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) {
|
|
let [newH, newM] = time.split(':').map(Number);
|
|
let newStartMin = newH * 60 + newM;
|
|
let newEndMin = newStartMin + duration;
|
|
|
|
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 === 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;
|
|
return (newStartMin < sEndMin && newEndMin > sStartMin);
|
|
}
|
|
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(); }
|
|
}
|
|
|
|
async function saveNewServiceApp(e) {
|
|
e.preventDefault();
|
|
|
|
const date = document.getElementById('nsDate').value;
|
|
const time = document.getElementById('nsTime').value;
|
|
const duration = parseInt(document.getElementById('nsDuration').value) || 60;
|
|
|
|
// 🛑 RADAR ANTI-SOLAPAMIENTO EN CREACIÓN (PERMISIVO)
|
|
if (date && time) {
|
|
let [newH, newM] = time.split(':').map(Number);
|
|
let newStartMin = newH * 60 + newM;
|
|
let newEndMin = newStartMin + duration;
|
|
|
|
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 === 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;
|
|
return (newStartMin < sEndMin && newEndMin > sStartMin);
|
|
}
|
|
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> |