Actualizar asignados.html
This commit is contained in:
342
asignados.html
342
asignados.html
@@ -9,37 +9,38 @@
|
|||||||
<style>
|
<style>
|
||||||
/* VARIABLES CORPORATIVAS DINÁMICAS */
|
/* VARIABLES CORPORATIVAS DINÁMICAS */
|
||||||
:root {
|
:root {
|
||||||
--primary: #f59e0b;
|
--primary: #f59e0b;
|
||||||
--secondary: #2563eb;
|
--secondary: #2563eb;
|
||||||
--app-bg: #f4f7f9;
|
--app-bg: #f4f7f9;
|
||||||
}
|
}
|
||||||
|
|
||||||
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
|
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
|
||||||
.fade-in { animation: fadeIn 0.3s ease-out forwards; }
|
.fade-in { animation: fadeIn 0.3s ease-out forwards; }
|
||||||
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
|
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
|
||||||
.no-scrollbar::-webkit-scrollbar { display: none; }
|
.no-scrollbar::-webkit-scrollbar { display: none; }
|
||||||
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
|
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
|
||||||
.bottom-nav-safe { padding-bottom: env(safe-area-inset-bottom); }
|
.bottom-nav-safe { padding-bottom: env(safe-area-inset-bottom); }
|
||||||
|
|
||||||
/* Clases dinámicas */
|
/* Clases dinámicas */
|
||||||
.text-primary-dynamic { color: var(--primary) !important; }
|
.text-primary-dynamic { color: var(--primary) !important; }
|
||||||
.bg-primary-dynamic { background-color: var(--primary) !important; }
|
.bg-primary-dynamic { background-color: var(--primary) !important; }
|
||||||
.border-primary-dynamic { border-color: var(--primary) !important; }
|
.border-primary-dynamic { border-color: var(--primary) !important; }
|
||||||
|
|
||||||
/* Carrusel de fechas */
|
/* Carrusel de fechas */
|
||||||
.day-chip { transition: all 0.2s; border: 2px solid transparent; }
|
.day-chip { transition: all 0.2s; border: 2px solid transparent; }
|
||||||
.day-chip.active { background-color: var(--primary) !important; color: white !important; border-color: var(--primary) !important; transform: scale(1.05); shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
|
.day-chip.active { background-color: var(--primary) !important; color: white !important; border-color: var(--primary) !important; transform: scale(1.05); shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
|
||||||
.day-chip.inactive { background-color: #f8fafc; color: #64748b; border-color: #e2e8f0; }
|
.day-chip.inactive { background-color: #f8fafc; color: #64748b; border-color: #e2e8f0; }
|
||||||
|
|
||||||
/* Chips de Horas */
|
/* Chips de Horas */
|
||||||
.time-chip { transition: all 0.2s; }
|
.time-chip { transition: all 0.2s; }
|
||||||
.time-chip.active { background-color: var(--primary) !important; color: white !important; font-weight: 900; box-shadow: 0 4px 10px rgba(0,0,0,0.15); border-color: var(--primary) !important; }
|
.time-chip.active { background-color: var(--primary) !important; color: white !important; font-weight: 900; box-shadow: 0 4px 10px rgba(0,0,0,0.15); border-color: var(--primary) !important; }
|
||||||
.time-chip.inactive { background-color: white; color: #475569; border-color: #cbd5e1; }
|
.time-chip.inactive { background-color: white; color: #475569; border-color: #cbd5e1; }
|
||||||
.time-chip:disabled { background-color: #f1f5f9; color: #cbd5e1; border-color: #e2e8f0; text-decoration: line-through; cursor: not-allowed; }
|
.time-chip:disabled { background-color: #f1f5f9; color: #cbd5e1; border-color: #e2e8f0; text-decoration: line-through; cursor: not-allowed; }
|
||||||
|
|
||||||
|
/* Descripción expandible al tocar */
|
||||||
|
.desc-box { cursor: pointer; }
|
||||||
|
.desc-toggle-icon { transition: transform 0.2s ease; }
|
||||||
|
.desc-toggle-icon.rotate-180 { transform: rotate(180deg); }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative">
|
<body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative">
|
||||||
|
|
||||||
<header class="bg-white px-5 pt-8 pb-4 shadow-sm z-20 shrink-0 border-b border-slate-100 flex justify-between items-center relative">
|
<header class="bg-white px-5 pt-8 pb-4 shadow-sm z-20 shrink-0 border-b border-slate-100 flex justify-between items-center relative">
|
||||||
<div>
|
<div>
|
||||||
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-0.5">Por Agendar</p>
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-0.5">Por Agendar</p>
|
||||||
@@ -49,19 +50,17 @@
|
|||||||
<i data-lucide="arrow-left" class="w-5 h-5"></i>
|
<i data-lucide="arrow-left" class="w-5 h-5"></i>
|
||||||
</a>
|
</a>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main class="flex-1 overflow-y-auto no-scrollbar p-5 relative z-10" id="mainArea">
|
<main class="flex-1 overflow-y-auto no-scrollbar p-5 relative z-10" id="mainArea">
|
||||||
<div id="loader" class="text-center py-10 opacity-50">
|
<div id="loader" class="text-center py-10 opacity-50">
|
||||||
<i data-lucide="loader-2" class="w-8 h-8 animate-spin mx-auto text-primary-dynamic mb-2"></i>
|
<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 mt-2 text-slate-400">Sincronizando...</p>
|
<p class="text-xs font-bold uppercase tracking-widest mt-2 text-slate-400">Sincronizando...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="contentWrapper" class="hidden pb-24 fade-in">
|
|
||||||
|
|
||||||
|
<div id="contentWrapper" class="hidden pb-24 fade-in">
|
||||||
<div id="searchContainer" class="mb-6 relative">
|
<div id="searchContainer" class="mb-6 relative">
|
||||||
<i data-lucide="search" class="w-5 h-5 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
|
<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="filterServices()" placeholder="Buscar expediente, cliente, zona 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">
|
<input type="text" id="searchInput" oninput="filterServices()" placeholder="Buscar expediente, cliente, zona 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>
|
||||||
<div id="requestsSection" class="mb-6 hidden">
|
<div id="requestsSection" class="mb-6 hidden">
|
||||||
<h2 class="text-xs font-black text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-2">
|
<h2 class="text-xs font-black text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-2">
|
||||||
@@ -74,16 +73,13 @@
|
|||||||
<div id="requestsList" class="space-y-4">
|
<div id="requestsList" class="space-y-4">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="noDateSection">
|
<div id="noDateSection">
|
||||||
<h2 class="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">Pendientes de Fecha</h2>
|
<h2 class="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">Pendientes de Fecha</h2>
|
||||||
<div id="servicesList" class="space-y-4">
|
<div id="servicesList" class="space-y-4">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<nav class="bg-white border-t border-slate-200 shrink-0 pb-safe z-20 absolute bottom-0 w-full shadow-[0_-10px_30px_rgba(0,0,0,0.05)] rounded-t-3xl">
|
<nav class="bg-white border-t border-slate-200 shrink-0 pb-safe z-20 absolute bottom-0 w-full shadow-[0_-10px_30px_rgba(0,0,0,0.05)] rounded-t-3xl">
|
||||||
<div class="flex justify-around items-center p-3 bottom-nav-safe">
|
<div class="flex justify-around items-center p-3 bottom-nav-safe">
|
||||||
<a href="menu.html" class="flex flex-col items-center p-2 text-slate-400 hover:text-primary-dynamic transition-transform active:scale-95">
|
<a href="menu.html" class="flex flex-col items-center p-2 text-slate-400 hover:text-primary-dynamic transition-transform active:scale-95">
|
||||||
@@ -100,10 +96,9 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div id="actionModal" class="fixed inset-0 bg-slate-900/60 z-[100] hidden flex-col justify-end transition-opacity duration-300 opacity-0">
|
<div id="actionModal" class="fixed inset-0 bg-slate-900/60 z-[100] hidden flex-col justify-end transition-opacity duration-300 opacity-0">
|
||||||
<div id="modalContent" class="bg-white rounded-t-[2rem] p-6 pb-12 transform translate-y-full transition-transform duration-300 shadow-2xl max-h-[90vh] flex flex-col">
|
<div id="modalContent" class="bg-white rounded-t-[2rem] p-6 pb-12 transform translate-y-full transition-transform duration-300 shadow-2xl max-h-[90vh] flex flex-col">
|
||||||
|
|
||||||
<div class="flex justify-between items-center mb-6 shrink-0">
|
<div class="flex justify-between items-center mb-6 shrink-0">
|
||||||
<div>
|
<div>
|
||||||
<span id="detRef" class="text-[10px] font-black text-slate-400 uppercase tracking-widest"></span>
|
<span id="detRef" class="text-[10px] font-black text-slate-400 uppercase tracking-widest"></span>
|
||||||
@@ -111,16 +106,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<button onclick="closeModal('actionModal', 'modalContent')" class="w-8 h-8 bg-slate-100 rounded-full flex items-center justify-center text-slate-500 hover:text-red-500"><i data-lucide="x" class="w-4 h-4"></i></button>
|
<button onclick="closeModal('actionModal', 'modalContent')" class="w-8 h-8 bg-slate-100 rounded-full flex items-center justify-center text-slate-500 hover:text-red-500"><i data-lucide="x" class="w-4 h-4"></i></button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="overflow-y-auto no-scrollbar flex-1 pb-4">
|
<div class="overflow-y-auto no-scrollbar flex-1 pb-4">
|
||||||
<div class="space-y-1 mb-6 bg-slate-50 p-4 rounded-2xl border border-slate-100">
|
<div class="space-y-1 mb-6 bg-slate-50 p-4 rounded-2xl border border-slate-100">
|
||||||
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1"><i data-lucide="map-pin" class="w-3 h-3"></i> Dirección</p>
|
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1"><i data-lucide="map-pin" class="w-3 h-3"></i> Dirección</p>
|
||||||
<p id="detAddress" class="font-bold text-slate-700 text-sm uppercase"></p>
|
<p id="detAddress" class="font-bold text-slate-700 text-sm uppercase"></p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<input type="hidden" id="detId">
|
<input type="hidden" id="detId">
|
||||||
<input type="hidden" id="detPhoneRaw">
|
<input type="hidden" id="detPhoneRaw">
|
||||||
|
|
||||||
<div class="grid grid-cols-2 gap-3 mb-6">
|
<div class="grid grid-cols-2 gap-3 mb-6">
|
||||||
<button onclick="callClient()" class="bg-blue-50 border border-blue-100 text-blue-600 font-black py-3 rounded-2xl flex items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm">
|
<button onclick="callClient()" class="bg-blue-50 border border-blue-100 text-blue-600 font-black py-3 rounded-2xl flex items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm">
|
||||||
<i data-lucide="phone" class="w-5 h-5"></i>
|
<i data-lucide="phone" class="w-5 h-5"></i>
|
||||||
@@ -131,9 +123,7 @@
|
|||||||
<span class="text-[10px] uppercase tracking-widest">WhatsApp</span>
|
<span class="text-[10px] uppercase tracking-widest">WhatsApp</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<hr class="border-slate-100 mb-6">
|
<hr class="border-slate-100 mb-6">
|
||||||
|
|
||||||
<div class="bg-white border border-slate-200 rounded-[1.5rem] p-5 shadow-sm space-y-5">
|
<div class="bg-white border border-slate-200 rounded-[1.5rem] p-5 shadow-sm space-y-5">
|
||||||
<div>
|
<div>
|
||||||
<div class="flex justify-between items-center mb-2">
|
<div class="flex justify-between items-center mb-2">
|
||||||
@@ -153,12 +143,10 @@
|
|||||||
<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>
|
<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>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="calendar" class="w-4 h-4"></i> Seleccionar Día</p>
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="calendar" class="w-4 h-4"></i> Seleccionar Día</p>
|
||||||
<div id="dayCarousel" class="flex overflow-x-auto gap-2 pb-2 no-scrollbar"></div>
|
<div id="dayCarousel" class="flex overflow-x-auto gap-2 pb-2 no-scrollbar"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="watch" class="w-4 h-4"></i> Huecos Disponibles</p>
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-2 flex items-center gap-1.5"><i data-lucide="watch" class="w-4 h-4"></i> Huecos Disponibles</p>
|
||||||
<div id="timeGrid" class="grid grid-cols-4 gap-2"></div>
|
<div id="timeGrid" class="grid grid-cols-4 gap-2"></div>
|
||||||
@@ -168,7 +156,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pt-4 shrink-0 bg-white border-t border-slate-100">
|
<div class="pt-4 shrink-0 bg-white border-t border-slate-100">
|
||||||
<button onclick="saveAppointment()" id="btnSaveAppt" disabled class="w-full bg-slate-300 text-white font-black py-4 rounded-2xl shadow-sm transition-all flex items-center justify-center gap-2 uppercase tracking-widest text-xs cursor-not-allowed">
|
<button onclick="saveAppointment()" id="btnSaveAppt" disabled class="w-full bg-slate-300 text-white font-black py-4 rounded-2xl shadow-sm transition-all flex items-center justify-center gap-2 uppercase tracking-widest text-xs cursor-not-allowed">
|
||||||
<i data-lucide="calendar-check" class="w-5 h-5"></i> Confirmar Cita
|
<i data-lucide="calendar-check" class="w-5 h-5"></i> Confirmar Cita
|
||||||
@@ -176,7 +163,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="approveModal" class="fixed inset-0 bg-slate-900/60 z-[110] hidden flex-col justify-end transition-opacity duration-300 opacity-0">
|
<div id="approveModal" class="fixed inset-0 bg-slate-900/60 z-[110] hidden flex-col justify-end transition-opacity duration-300 opacity-0">
|
||||||
<div id="approveModalContent" class="bg-white rounded-t-[2rem] p-6 pb-12 transform translate-y-full transition-transform duration-300 shadow-2xl">
|
<div id="approveModalContent" class="bg-white rounded-t-[2rem] p-6 pb-12 transform translate-y-full transition-transform duration-300 shadow-2xl">
|
||||||
<div class="flex justify-between items-center mb-6">
|
<div class="flex justify-between items-center mb-6">
|
||||||
@@ -186,7 +172,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<button onclick="closeModal('approveModal', 'approveModalContent')" class="w-8 h-8 bg-slate-100 rounded-full flex items-center justify-center text-slate-500 hover:text-red-500"><i data-lucide="x" class="w-4 h-4"></i></button>
|
<button onclick="closeModal('approveModal', 'approveModalContent')" class="w-8 h-8 bg-slate-100 rounded-full flex items-center justify-center text-slate-500 hover:text-red-500"><i data-lucide="x" class="w-4 h-4"></i></button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="bg-slate-50 border-2 border-primary-dynamic p-5 rounded-2xl mb-6 shadow-inner text-center relative overflow-hidden">
|
<div class="bg-slate-50 border-2 border-primary-dynamic p-5 rounded-2xl mb-6 shadow-inner text-center relative overflow-hidden">
|
||||||
<div class="absolute left-0 top-0 bottom-0 w-2 bg-primary-dynamic"></div>
|
<div class="absolute left-0 top-0 bottom-0 w-2 bg-primary-dynamic"></div>
|
||||||
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-3">Fecha y Hora de Cita (Modificable)</p>
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-3">Fecha y Hora de Cita (Modificable)</p>
|
||||||
@@ -195,9 +180,7 @@
|
|||||||
<input type="time" id="appTimeInput" class="bg-white border border-slate-200 px-3 py-2 rounded-xl text-sm font-black text-slate-700 outline-none focus:ring-2 focus:ring-primary-dynamic transition-all">
|
<input type="time" id="appTimeInput" class="bg-white border border-slate-200 px-3 py-2 rounded-xl text-sm font-black text-slate-700 outline-none focus:ring-2 focus:ring-primary-dynamic transition-all">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<input type="hidden" id="appId">
|
<input type="hidden" id="appId">
|
||||||
|
|
||||||
<div class="mb-8">
|
<div class="mb-8">
|
||||||
<p class="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-2 ml-1">¿Cuánto tiempo vas a tardar?</p>
|
<p class="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-2 ml-1">¿Cuánto tiempo vas a tardar?</p>
|
||||||
<div class="relative">
|
<div class="relative">
|
||||||
@@ -214,7 +197,6 @@
|
|||||||
<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>
|
<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>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-2 gap-3">
|
<div class="grid grid-cols-2 gap-3">
|
||||||
<button onclick="rejectRequest()" id="btnReject" class="bg-white border-2 border-rose-200 text-rose-600 font-black py-4 rounded-xl hover:bg-rose-50 flex items-center justify-center gap-2 transition-all text-xs uppercase tracking-widest">
|
<button onclick="rejectRequest()" id="btnReject" class="bg-white border-2 border-rose-200 text-rose-600 font-black py-4 rounded-xl hover:bg-rose-50 flex items-center justify-center gap-2 transition-all text-xs uppercase tracking-widest">
|
||||||
<i data-lucide="x" class="w-4 h-4"></i> Rechazar
|
<i data-lucide="x" class="w-4 h-4"></i> Rechazar
|
||||||
@@ -226,38 +208,33 @@
|
|||||||
<p class="text-center text-[9px] font-bold text-slate-400 mt-4">Al aceptar, se enviará un WhatsApp al cliente confirmando la cita automáticamente.</p>
|
<p class="text-center text-[9px] font-bold text-slate-400 mt-4">Al aceptar, se enviará un WhatsApp al cliente confirmando la cita automáticamente.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="toast" class="fixed top-5 left-1/2 -translate-x-1/2 bg-slate-800 text-white px-5 py-3 rounded-full shadow-2xl z-[200] font-bold text-xs uppercase tracking-widest flex items-center gap-2 transition-all duration-300 opacity-0 pointer-events-none transform -translate-y-10">
|
<div id="toast" class="fixed top-5 left-1/2 -translate-x-1/2 bg-slate-800 text-white px-5 py-3 rounded-full shadow-2xl z-[200] font-bold text-xs uppercase tracking-widest flex items-center gap-2 transition-all duration-300 opacity-0 pointer-events-none transform -translate-y-10">
|
||||||
<i data-lucide="check-circle" class="w-4 h-4 text-emerald-400"></i>
|
<i data-lucide="check-circle" class="w-4 h-4 text-emerald-400"></i>
|
||||||
<span id="toastMsg">Guardado</span>
|
<span id="toastMsg">Guardado</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
|
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
|
||||||
? 'http://localhost:3000'
|
? 'http://localhost:3000'
|
||||||
: 'https://integrarepara-api.integrarepara.es';
|
: 'https://integrarepara-api.integrarepara.es';
|
||||||
|
let localServices = [];
|
||||||
let localServices = [];
|
let globalAllServices = [];
|
||||||
let globalAllServices = [];
|
let pendingRequests = [];
|
||||||
let pendingRequests = [];
|
|
||||||
let systemStatuses = [];
|
let systemStatuses = [];
|
||||||
let systemGuilds = [];
|
let systemGuilds = [];
|
||||||
let bizHours = { m_start: '09:00', m_end: '14:00', a_start: '16:00', a_end: '19:00' };
|
let bizHours = { m_start: '09:00', m_end: '14:00', a_start: '16:00', a_end: '19:00' };
|
||||||
|
|
||||||
// Variables del Agendador Inteligente
|
// Variables del Agendador Inteligente
|
||||||
let pickerSelectedDate = "";
|
let pickerSelectedDate = "";
|
||||||
let pickerSelectedTime = "";
|
let pickerSelectedTime = "";
|
||||||
|
|
||||||
// --- SISTEMA DE TEMA DINÁMICO (VERSIÓN TODOTERRENO DEFINITIVA) ---
|
// --- SISTEMA DE TEMA DINÁMICO (VERSIÓN TODOTERRENO DEFINITIVA) ---
|
||||||
// --- SISTEMA DE TEMA DINÁMICO (EL BUENO) ---
|
// --- SISTEMA DE TEMA DINÁMICO (EL BUENO) ---
|
||||||
async function applyTheme() {
|
async function applyTheme() {
|
||||||
try {
|
try {
|
||||||
let theme = JSON.parse(localStorage.getItem('app_theme'));
|
let theme = JSON.parse(localStorage.getItem('app_theme'));
|
||||||
const res = await fetch(`${API_URL}/config/company`, {
|
const res = await fetch(`${API_URL}/config/company`, {
|
||||||
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
if (data.ok && data.config) {
|
if (data.ok && data.config) {
|
||||||
// Aquí le enseñamos a la app a mirar en app_settings
|
// Aquí le enseñamos a la app a mirar en app_settings
|
||||||
if (data.config.app_settings) {
|
if (data.config.app_settings) {
|
||||||
@@ -265,7 +242,7 @@
|
|||||||
localStorage.setItem('app_theme', JSON.stringify(theme));
|
localStorage.setItem('app_theme', JSON.stringify(theme));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(theme && theme.primary) {
|
if(theme && theme.primary) {
|
||||||
document.documentElement.style.setProperty('--primary', theme.primary);
|
document.documentElement.style.setProperty('--primary', theme.primary);
|
||||||
document.documentElement.style.setProperty('--secondary', theme.secondary);
|
document.documentElement.style.setProperty('--secondary', theme.secondary);
|
||||||
@@ -273,7 +250,6 @@
|
|||||||
}
|
}
|
||||||
} catch (e) { console.warn("Usando tema por defecto"); }
|
} catch (e) { console.warn("Usando tema por defecto"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", async () => {
|
document.addEventListener("DOMContentLoaded", async () => {
|
||||||
if (!localStorage.getItem("token") || (localStorage.getItem("role") !== 'operario' && localStorage.getItem("role") !== 'operario_cerrado')) {
|
if (!localStorage.getItem("token") || (localStorage.getItem("role") !== 'operario' && localStorage.getItem("role") !== 'operario_cerrado')) {
|
||||||
window.location.href = "index.html"; return;
|
window.location.href = "index.html"; return;
|
||||||
@@ -283,7 +259,6 @@
|
|||||||
await loadStatusesAndGuilds();
|
await loadStatusesAndGuilds();
|
||||||
refreshData();
|
refreshData();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function loadStatusesAndGuilds() {
|
async function loadStatusesAndGuilds() {
|
||||||
try {
|
try {
|
||||||
const headers = { "Authorization": `Bearer ${localStorage.getItem("token")}` };
|
const headers = { "Authorization": `Bearer ${localStorage.getItem("token")}` };
|
||||||
@@ -297,47 +272,44 @@
|
|||||||
if (dataG.ok) systemGuilds = dataG.guilds;
|
if (dataG.ok) systemGuilds = dataG.guilds;
|
||||||
} catch(e) {}
|
} catch(e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshData() {
|
async function refreshData() {
|
||||||
document.getElementById('contentWrapper').classList.add('hidden');
|
document.getElementById('contentWrapper').classList.add('hidden');
|
||||||
document.getElementById('loader').classList.remove('hidden');
|
document.getElementById('loader').classList.remove('hidden');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const headers = { "Authorization": `Bearer ${localStorage.getItem("token")}` };
|
const headers = { "Authorization": `Bearer ${localStorage.getItem("token")}` };
|
||||||
const myUserId = JSON.parse(atob(localStorage.getItem('token').split('.')[1])).sub;
|
const myUserId = JSON.parse(atob(localStorage.getItem('token').split('.')[1])).sub;
|
||||||
|
|
||||||
const resActivos = await fetch(`${API_URL}/services/active`, { headers });
|
const resActivos = await fetch(`${API_URL}/services/active`, { headers });
|
||||||
const dataActivos = await resActivos.json();
|
const dataActivos = await resActivos.json();
|
||||||
|
|
||||||
const resReqs = await fetch(`${API_URL}/agenda/requests`, { headers });
|
const resReqs = await fetch(`${API_URL}/agenda/requests`, { headers });
|
||||||
const dataReqs = await resReqs.json();
|
const dataReqs = await resReqs.json();
|
||||||
|
|
||||||
if (dataActivos.ok && dataReqs.ok) {
|
if (dataActivos.ok && dataReqs.ok) {
|
||||||
globalAllServices = dataActivos.services;
|
globalAllServices = dataActivos.services;
|
||||||
pendingRequests = dataReqs.requests;
|
pendingRequests = dataReqs.requests;
|
||||||
|
|
||||||
// FILTRO MAESTRO CORREGIDO
|
// FILTRO MAESTRO CORREGIDO
|
||||||
localServices = globalAllServices.filter(s => {
|
localServices = globalAllServices.filter(s => {
|
||||||
// 1. Descartar si no es mío, si es bloqueo o si está en la papelera
|
// 1. Descartar si no es mío, si es bloqueo o si está en la papelera
|
||||||
if (s.assigned_to !== myUserId || s.provider === 'SYSTEM_BLOCK' || s.status === 'archived') return false;
|
if (s.assigned_to !== myUserId || s.provider === 'SYSTEM_BLOCK' || s.status === 'archived') return false;
|
||||||
|
|
||||||
const raw = s.raw_data || {};
|
const raw = s.raw_data || {};
|
||||||
|
|
||||||
// 2. Si ya está en la lista de solicitudes, no lo duplicamos
|
// 2. Si ya está en la lista de solicitudes, no lo duplicamos
|
||||||
if (raw.appointment_status === 'pending') return false;
|
if (raw.appointment_status === 'pending') return false;
|
||||||
|
|
||||||
// 3. SOLO PASAN LOS QUE NO TIENEN FECHA
|
// 3. SOLO PASAN LOS QUE NO TIENEN FECHA
|
||||||
if (raw.scheduled_date && raw.scheduled_date.trim() !== "") return false;
|
if (raw.scheduled_date && raw.scheduled_date.trim() !== "") return false;
|
||||||
|
|
||||||
// 4. Asegurarnos de que no está terminado/anulado
|
// 4. Asegurarnos de que no está terminado/anulado
|
||||||
if (raw.status_operativo) {
|
if (raw.status_operativo) {
|
||||||
const st = systemStatuses.find(x => String(x.id) === String(raw.status_operativo));
|
const st = systemStatuses.find(x => String(x.id) === String(raw.status_operativo));
|
||||||
if (st && st.is_final) return false;
|
if (st && st.is_final) return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
renderRequests();
|
renderRequests();
|
||||||
renderServices();
|
renderServices();
|
||||||
}
|
}
|
||||||
@@ -348,7 +320,20 @@
|
|||||||
document.getElementById('contentWrapper').classList.remove('hidden');
|
document.getElementById('contentWrapper').classList.remove('hidden');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// ==========================================
|
||||||
|
// EXPANDIR / CONTRAER DESCRIPCIÓN AL TOCAR
|
||||||
|
// ==========================================
|
||||||
|
// Se usa en las tarjetas de "Pendientes de Fecha" y "Citas Solicitadas".
|
||||||
|
// Al tocar el recuadro gris, se quita el recorte de 2 líneas (line-clamp-2)
|
||||||
|
// y se muestra el texto completo; al tocar otra vez, se vuelve a recortar.
|
||||||
|
function toggleDesc(box, evt) {
|
||||||
|
if (evt) evt.stopPropagation(); // Evita que se abra el modal de la tarjeta al tocar la descripción
|
||||||
|
const p = box.querySelector('p');
|
||||||
|
const icon = box.querySelector('.desc-toggle-icon');
|
||||||
|
if (!p) return;
|
||||||
|
p.classList.toggle('line-clamp-2');
|
||||||
|
if (icon) icon.classList.toggle('rotate-180');
|
||||||
|
}
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// RENDERIZADO DE SOLICITUDES PENDIENTES
|
// RENDERIZADO DE SOLICITUDES PENDIENTES
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -356,32 +341,27 @@
|
|||||||
const reqSection = document.getElementById('requestsSection');
|
const reqSection = document.getElementById('requestsSection');
|
||||||
const reqList = document.getElementById('requestsList');
|
const reqList = document.getElementById('requestsList');
|
||||||
reqList.innerHTML = '';
|
reqList.innerHTML = '';
|
||||||
|
|
||||||
if (pendingRequests.length === 0) {
|
if (pendingRequests.length === 0) {
|
||||||
reqSection.classList.add('hidden');
|
reqSection.classList.add('hidden');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
reqSection.classList.remove('hidden');
|
reqSection.classList.remove('hidden');
|
||||||
|
|
||||||
pendingRequests.forEach(req => {
|
pendingRequests.forEach(req => {
|
||||||
const raw = req.raw_data || {};
|
const raw = req.raw_data || {};
|
||||||
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente";
|
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente";
|
||||||
const rDate = formatDate(raw.requested_date);
|
const rDate = formatDate(raw.requested_date);
|
||||||
const rTime = addOneHour(raw.requested_time);
|
const rTime = addOneHour(raw.requested_time);
|
||||||
|
|
||||||
const desc = raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas de avería.";
|
const desc = raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas de avería.";
|
||||||
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
||||||
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
|
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
|
||||||
const safePhone = matchPhone ? matchPhone[0] : "";
|
const safePhone = matchPhone ? matchPhone[0] : "";
|
||||||
|
|
||||||
const addr = raw["Dirección"] || raw["DOMICILIO"] || "Sin dirección";
|
const addr = raw["Dirección"] || raw["DOMICILIO"] || "Sin dirección";
|
||||||
const pop = raw["Población"] || raw["POBLACION-PROVINCIA"] || "";
|
const pop = raw["Población"] || raw["POBLACION-PROVINCIA"] || "";
|
||||||
const cp = raw["Código Postal"] || raw["C.P."] || "";
|
const cp = raw["Código Postal"] || raw["C.P."] || "";
|
||||||
const fullAddress = `${addr}, ${cp} ${pop}`.trim().replace(/^,\s*/, '').replace(/,\s*$/, '');
|
const fullAddress = `${addr}, ${cp} ${pop}`.trim().replace(/^,\s*/, '').replace(/,\s*$/, '');
|
||||||
|
|
||||||
let guildName = raw["Gremio"] || raw["GREMIO"] || raw["Especialidad"] || "";
|
let guildName = raw["Gremio"] || raw["GREMIO"] || raw["Especialidad"] || "";
|
||||||
const idGremio = req.guild_id || raw.guild_id;
|
const idGremio = req.guild_id || raw.guild_id;
|
||||||
if (!guildName && idGremio) {
|
if (!guildName && idGremio) {
|
||||||
const guildObj = systemGuilds.find(g => String(g.id) === String(idGremio));
|
const guildObj = systemGuilds.find(g => String(g.id) === String(idGremio));
|
||||||
if (guildObj) guildName = guildObj.name;
|
if (guildObj) guildName = guildObj.name;
|
||||||
@@ -390,11 +370,10 @@
|
|||||||
guildName = req.guild.name;
|
guildName = req.guild.name;
|
||||||
}
|
}
|
||||||
guildName = guildName || "Varios";
|
guildName = guildName || "Varios";
|
||||||
|
|
||||||
reqList.innerHTML += `
|
reqList.innerHTML += `
|
||||||
<div class="bg-white border-2 border-primary-dynamic p-5 rounded-[2rem] flex flex-col shadow-md relative overflow-hidden gap-3">
|
<div class="bg-white border-2 border-primary-dynamic p-5 rounded-[2rem] flex flex-col shadow-md relative overflow-hidden gap-3">
|
||||||
<div class="absolute right-0 top-0 w-24 h-24 bg-primary-dynamic rounded-bl-full opacity-10 z-0"></div>
|
<div class="absolute right-0 top-0 w-24 h-24 bg-primary-dynamic rounded-bl-full opacity-10 z-0"></div>
|
||||||
|
|
||||||
<div class="relative z-10">
|
<div class="relative z-10">
|
||||||
<div class="flex justify-between items-center mb-0.5 pr-6">
|
<div class="flex justify-between items-center mb-0.5 pr-6">
|
||||||
<p class="text-[9px] font-black text-primary-dynamic uppercase tracking-widest">Cita Solicitada</p>
|
<p class="text-[9px] font-black text-primary-dynamic uppercase tracking-widest">Cita Solicitada</p>
|
||||||
@@ -404,11 +383,10 @@
|
|||||||
<p class="text-[10px] font-bold text-slate-600 mt-1 flex items-center gap-1"><i data-lucide="calendar" class="w-3 h-3 text-primary-dynamic"></i> ${rDate} | ${raw.requested_time} - ${rTime}</p>
|
<p class="text-[10px] font-bold text-slate-600 mt-1 flex items-center gap-1"><i data-lucide="calendar" class="w-3 h-3 text-primary-dynamic"></i> ${rDate} | ${raw.requested_time} - ${rTime}</p>
|
||||||
<p class="text-[10px] font-bold text-slate-500 mt-1 uppercase flex items-start gap-1"><i data-lucide="map-pin" class="w-3 h-3 text-slate-400 shrink-0 mt-0.5"></i> <span class="leading-tight">${fullAddress}</span></p>
|
<p class="text-[10px] font-bold text-slate-500 mt-1 uppercase flex items-start gap-1"><i data-lucide="map-pin" class="w-3 h-3 text-slate-400 shrink-0 mt-0.5"></i> <span class="leading-tight">${fullAddress}</span></p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="desc-box relative z-10 bg-slate-50 p-3 rounded-2xl border border-slate-100 mt-1 active:bg-slate-100 transition-colors" onclick="toggleDesc(this, event)">
|
||||||
<div class="relative z-10 bg-slate-50 p-3 rounded-2xl border border-slate-100 mt-1">
|
<p class="text-[10px] font-medium text-slate-600 line-clamp-2 leading-relaxed pr-5">${desc}</p>
|
||||||
<p class="text-[10px] font-medium text-slate-600 line-clamp-2 leading-relaxed">${desc}</p>
|
<i data-lucide="chevron-down" class="desc-toggle-icon w-3.5 h-3.5 text-slate-400 absolute right-2.5 top-3 shrink-0"></i>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex gap-2 relative z-10 mt-1">
|
<div class="flex gap-2 relative z-10 mt-1">
|
||||||
<button onclick="quickCallInline('${safePhone}')" class="flex-1 bg-white border border-primary-dynamic text-primary-dynamic hover:bg-slate-50 font-black py-3 rounded-xl flex items-center justify-center gap-1.5 active:scale-95 transition-transform shadow-sm text-[10px] uppercase tracking-widest">
|
<button onclick="quickCallInline('${safePhone}')" class="flex-1 bg-white border border-primary-dynamic text-primary-dynamic hover:bg-slate-50 font-black py-3 rounded-xl flex items-center justify-center gap-1.5 active:scale-95 transition-transform shadow-sm text-[10px] uppercase tracking-widest">
|
||||||
<i data-lucide="phone" class="w-4 h-4"></i> Llamar
|
<i data-lucide="phone" class="w-4 h-4"></i> Llamar
|
||||||
@@ -422,33 +400,28 @@
|
|||||||
});
|
});
|
||||||
lucide.createIcons();
|
lucide.createIcons();
|
||||||
}
|
}
|
||||||
|
|
||||||
function quickCallInline(phone) {
|
function quickCallInline(phone) {
|
||||||
if (phone) window.location.href = `tel:+34${phone}`;
|
if (phone) window.location.href = `tel:+34${phone}`;
|
||||||
else alert("No hay un teléfono válido guardado.");
|
else alert("No hay un teléfono válido guardado.");
|
||||||
}
|
}
|
||||||
|
|
||||||
function openApproveModal(id) {
|
function openApproveModal(id) {
|
||||||
const req = pendingRequests.find(r => r.id === id);
|
const req = pendingRequests.find(r => r.id === id);
|
||||||
if(!req) return;
|
if(!req) return;
|
||||||
const raw = req.raw_data || {};
|
const raw = req.raw_data || {};
|
||||||
|
|
||||||
document.getElementById('appId').value = id;
|
document.getElementById('appId').value = id;
|
||||||
document.getElementById('appRef').innerText = `Exp. #${req.service_ref || "S/R"}`;
|
document.getElementById('appRef').innerText = `Exp. #${req.service_ref || "S/R"}`;
|
||||||
document.getElementById('appName').innerText = raw["Nombre Cliente"] || "Cliente";
|
document.getElementById('appName').innerText = raw["Nombre Cliente"] || "Cliente";
|
||||||
|
|
||||||
document.getElementById('appDateInput').value = raw.requested_date || "";
|
document.getElementById('appDateInput').value = raw.requested_date || "";
|
||||||
document.getElementById('appTimeInput').value = raw.requested_time || "";
|
document.getElementById('appTimeInput').value = raw.requested_time || "";
|
||||||
document.getElementById('appDurationInput').value = "60";
|
document.getElementById('appDurationInput').value = "60";
|
||||||
|
|
||||||
const modal = document.getElementById('approveModal');
|
const modal = document.getElementById('approveModal');
|
||||||
const content = document.getElementById('approveModalContent');
|
const content = document.getElementById('approveModalContent');
|
||||||
modal.classList.remove('hidden');
|
modal.classList.remove('hidden');
|
||||||
void modal.offsetWidth;
|
void modal.offsetWidth;
|
||||||
modal.classList.remove('opacity-0');
|
modal.classList.remove('opacity-0');
|
||||||
content.classList.remove('translate-y-full');
|
content.classList.remove('translate-y-full');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function approveRequest() {
|
async function approveRequest() {
|
||||||
const id = document.getElementById('appId').value;
|
const id = document.getElementById('appId').value;
|
||||||
const duration = document.getElementById('appDurationInput').value;
|
const duration = document.getElementById('appDurationInput').value;
|
||||||
@@ -458,7 +431,6 @@
|
|||||||
const originalContent = btn.innerHTML;
|
const originalContent = btn.innerHTML;
|
||||||
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/agenda/requests/${id}/approve`, {
|
const res = await fetch(`${API_URL}/agenda/requests/${id}/approve`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -470,10 +442,9 @@
|
|||||||
closeModal('approveModal', 'approveModalContent');
|
closeModal('approveModal', 'approveModalContent');
|
||||||
refreshData();
|
refreshData();
|
||||||
} else { alert("Error al confirmar."); }
|
} else { alert("Error al confirmar."); }
|
||||||
} catch (e) { alert("Error de conexión"); }
|
} catch (e) { alert("Error de conexión"); }
|
||||||
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
|
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rejectRequest() {
|
async function rejectRequest() {
|
||||||
if(!confirm("¿Seguro que quieres rechazar este horario? El cliente recibirá un mensaje para elegir otro.")) return;
|
if(!confirm("¿Seguro que quieres rechazar este horario? El cliente recibirá un mensaje para elegir otro.")) return;
|
||||||
const id = document.getElementById('appId').value;
|
const id = document.getElementById('appId').value;
|
||||||
@@ -481,7 +452,6 @@
|
|||||||
const originalContent = btn.innerHTML;
|
const originalContent = btn.innerHTML;
|
||||||
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/agenda/requests/${id}/reject`, {
|
const res = await fetch(`${API_URL}/agenda/requests/${id}/reject`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -492,10 +462,9 @@
|
|||||||
closeModal('approveModal', 'approveModalContent');
|
closeModal('approveModal', 'approveModalContent');
|
||||||
refreshData();
|
refreshData();
|
||||||
} else { alert("Error al rechazar."); }
|
} else { alert("Error al rechazar."); }
|
||||||
} catch (e) { alert("Error de conexión"); }
|
} catch (e) { alert("Error de conexión"); }
|
||||||
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
|
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// RENDERIZADO DE LISTADO NORMAL (SIN CITA)
|
// RENDERIZADO DE LISTADO NORMAL (SIN CITA)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -504,47 +473,42 @@
|
|||||||
const createdDate = new Date(createdAtStr);
|
const createdDate = new Date(createdAtStr);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const diffTime = Math.abs(now - createdDate);
|
const diffTime = Math.abs(now - createdDate);
|
||||||
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
|
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
|
||||||
return diffDays;
|
return diffDays;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔥 FUNCIÓN DE FILTRADO (BUSCADOR) 🔥
|
// 🔥 FUNCIÓN DE FILTRADO (BUSCADOR) 🔥
|
||||||
function filterServices() {
|
function filterServices() {
|
||||||
const query = document.getElementById('searchInput').value.toLowerCase().trim();
|
const query = document.getElementById('searchInput').value.toLowerCase().trim();
|
||||||
|
|
||||||
if (query === "") {
|
if (query === "") {
|
||||||
renderServices(localServices); // Si borramos el texto, pinta todos
|
renderServices(localServices); // Si borramos el texto, pinta todos
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filtered = localServices.filter(s => {
|
const filtered = localServices.filter(s => {
|
||||||
const raw = s.raw_data || {};
|
const raw = s.raw_data || {};
|
||||||
|
|
||||||
// Juntamos todos los campos importantes en un solo texto invisible y buscamos ahí
|
// Juntamos todos los campos importantes en un solo texto invisible y buscamos ahí
|
||||||
const searchString = `
|
const searchString = `
|
||||||
${s.service_ref || ""}
|
${s.service_ref || ""}
|
||||||
${raw["Nombre Cliente"] || raw["CLIENTE"] || ""}
|
${raw["Nombre Cliente"] || raw["CLIENTE"] || ""}
|
||||||
${raw["Dirección"] || raw["DOMICILIO"] || ""}
|
${raw["Dirección"] || raw["DOMICILIO"] || ""}
|
||||||
${raw["Población"] || raw["POBLACION-PROVINCIA"] || ""}
|
${raw["Población"] || raw["POBLACION-PROVINCIA"] || ""}
|
||||||
${raw["Código Postal"] || raw["C.P."] || ""}
|
${raw["Código Postal"] || raw["C.P."] || ""}
|
||||||
${raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"] || ""}
|
${raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"] || ""}
|
||||||
${raw["Compañía"] || raw["Procedencia"] || ""}
|
${raw["Compañía"] || raw["Procedencia"] || ""}
|
||||||
`.toLowerCase();
|
`.toLowerCase();
|
||||||
|
|
||||||
return searchString.includes(query);
|
return searchString.includes(query);
|
||||||
});
|
});
|
||||||
|
|
||||||
renderServices(filtered);
|
renderServices(filtered);
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderServices(servicesToRender = localServices) {
|
function renderServices(servicesToRender = localServices) {
|
||||||
const container = document.getElementById('servicesList');
|
const container = document.getElementById('servicesList');
|
||||||
const noDateSec = document.getElementById('noDateSection');
|
const noDateSec = document.getElementById('noDateSection');
|
||||||
|
|
||||||
if (servicesToRender.length === 0) {
|
if (servicesToRender.length === 0) {
|
||||||
// Comprobamos si está vacío porque hemos buscado algo que no existe, o porque realmente no hay avisos
|
// Comprobamos si está vacío porque hemos buscado algo que no existe, o porque realmente no hay avisos
|
||||||
const isSearch = document.getElementById('searchInput') && document.getElementById('searchInput').value.trim() !== "";
|
const isSearch = document.getElementById('searchInput') && document.getElementById('searchInput').value.trim() !== "";
|
||||||
|
|
||||||
container.innerHTML = `
|
container.innerHTML = `
|
||||||
<div class="text-center py-12 bg-white rounded-3xl border border-slate-100 shadow-sm mt-2">
|
<div class="text-center py-12 bg-white rounded-3xl border border-slate-100 shadow-sm mt-2">
|
||||||
<div class="w-16 h-16 bg-emerald-50 text-emerald-500 rounded-full flex items-center justify-center mx-auto mb-4">
|
<div class="w-16 h-16 bg-emerald-50 text-emerald-500 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||||
@@ -558,10 +522,8 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
else noDateSec.classList.add('hidden');
|
else noDateSec.classList.add('hidden');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
noDateSec.classList.remove('hidden');
|
noDateSec.classList.remove('hidden');
|
||||||
noDateSec.querySelector('h2').classList.remove('hidden');
|
noDateSec.querySelector('h2').classList.remove('hidden');
|
||||||
|
|
||||||
container.innerHTML = servicesToRender.map(s => {
|
container.innerHTML = servicesToRender.map(s => {
|
||||||
const raw = s.raw_data || {};
|
const raw = s.raw_data || {};
|
||||||
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
|
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
|
||||||
@@ -569,67 +531,63 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
const pop = raw["Población"] || "";
|
const pop = raw["Población"] || "";
|
||||||
const isUrgent = s.is_urgent;
|
const isUrgent = s.is_urgent;
|
||||||
const company = raw["Compañía"] || raw["Procedencia"] || "Particular";
|
const company = raw["Compañía"] || raw["Procedencia"] || "Particular";
|
||||||
|
|
||||||
// 🤖 "IA" LIMPIADORA: Filtramos la paja de las aseguradoras para dejar solo la avería real
|
// 🤖 "IA" LIMPIADORA: Filtramos la paja de las aseguradoras para dejar solo la avería real
|
||||||
function limpiarPaja(texto) {
|
function limpiarPaja(texto) {
|
||||||
if (!texto) return "Sin descripción de avería en el expediente.";
|
if (!texto) return "Sin descripción de avería en el expediente.";
|
||||||
let res = texto.replace(/(\r\n|\n|\r)/gm, " ");
|
let res = texto.replace(/(\r\n|\n|\r)/gm, " ");
|
||||||
|
|
||||||
// 1. Quitamos todas las fechas de inicio de línea (Ej: "19/03/2026 - ")
|
// 1. Quitamos todas las fechas de inicio de línea (Ej: "19/03/2026 - ")
|
||||||
res = res.replace(/\d{2}\/\d{2}\/\d{4}\s*-\s*/g, ' ');
|
res = res.replace(/\d{2}\/\d{2}\/\d{4}\s*-\s*/g, ' ');
|
||||||
|
|
||||||
// 2. Pulverizamos las frases administrativas típicas
|
// 2. Pulverizamos las frases administrativas típicas
|
||||||
const basura = [
|
const basura = [
|
||||||
/Llama asegurad[oa]\s*\d*/gi,
|
/Llama asegurad[oa]\s*\d*/gi,
|
||||||
/solicita (operario|profesional) para/gi,
|
/solicita (operario|profesional) para/gi,
|
||||||
/Cobro banco.*?(?=\.|\s-|$)/gi,
|
/Cobro banco.*?(?=\.|\s-|$)/gi,
|
||||||
/El servicio dispone de hasta.*?(?=\.|\s-|$)/gi,
|
/El servicio dispone de hasta.*?(?=\.|\s-|$)/gi,
|
||||||
/Servicio asignado a:.*?(?=\.|\s-|$)/gi,
|
/Servicio asignado a:.*?(?=\.|\s-|$)/gi,
|
||||||
/Cambio de estado:.*?(?=\.|\s-|$)/gi,
|
/Cambio de estado:.*?(?=\.|\s-|$)/gi,
|
||||||
/y? el material debe ser aportado.*?(?=\.|\s-|$)/gi,
|
/y? el material debe ser aportado.*?(?=\.|\s-|$)/gi,
|
||||||
/informo material a cargo.*?(?=\.|\s-|$)/gi,
|
/informo material a cargo.*?(?=\.|\s-|$)/gi,
|
||||||
/en espera de profesional.*?(?=\.|\s-|$)/gi
|
/en espera de profesional.*?(?=\.|\s-|$)/gi
|
||||||
];
|
];
|
||||||
|
|
||||||
basura.forEach(regex => { res = res.replace(regex, ' '); });
|
basura.forEach(regex => { res = res.replace(regex, ' '); });
|
||||||
|
|
||||||
// 3. Limpiamos los espacios rotos y comas sueltas que hayan quedado
|
// 3. Limpiamos los espacios rotos y comas sueltas que hayan quedado
|
||||||
res = res.replace(/\s+/g, ' ').replace(/\s,\s/g, ', ').replace(/^[,\.\-\s]+/, '').trim();
|
res = res.replace(/\s+/g, ' ').replace(/\s,\s/g, ', ').replace(/^[,\.\-\s]+/, '').trim();
|
||||||
|
|
||||||
// Ponemos la primera letra en mayúscula. Si nos pasamos borrando, devolvemos el texto original por seguridad.
|
// Ponemos la primera letra en mayúscula. Si nos pasamos borrando, devolvemos el texto original por seguridad.
|
||||||
return res.length > 5 ? res.charAt(0).toUpperCase() + res.slice(1) : texto;
|
return res.length > 5 ? res.charAt(0).toUpperCase() + res.slice(1) : texto;
|
||||||
}
|
}
|
||||||
|
let desc = limpiarPaja(raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"]);
|
||||||
let desc = limpiarPaja(raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"]);
|
|
||||||
|
|
||||||
const calledTimes = parseInt(raw.called_times || 0);
|
const calledTimes = parseInt(raw.called_times || 0);
|
||||||
const delayDays = calculateDelayDays(s.created_at);
|
const delayDays = calculateDelayDays(s.created_at);
|
||||||
|
|
||||||
let delayHtml = '';
|
let delayHtml = '';
|
||||||
if (delayDays > 1) {
|
if (delayDays > 1) {
|
||||||
delayHtml = `<span class="bg-rose-100 text-rose-600 text-[8px] font-black px-2 py-0.5 rounded uppercase tracking-widest ml-2">Retraso: ${delayDays} días</span>`;
|
delayHtml = `<span class="bg-rose-100 text-rose-600 text-[8px] font-black px-2 py-0.5 rounded uppercase tracking-widest ml-2">Retraso: ${delayDays} días</span>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
let guildName = raw["Gremio"] || raw["GREMIO"] || raw["Especialidad"] || "";
|
let guildName = raw["Gremio"] || raw["GREMIO"] || raw["Especialidad"] || "";
|
||||||
|
|
||||||
// ¡AQUÍ ESTÁ LA CLAVE! El ID viene dentro del JSON (raw) o en el servicio (s)
|
// ¡AQUÍ ESTÁ LA CLAVE! El ID viene dentro del JSON (raw) o en el servicio (s)
|
||||||
const idGremio = s.guild_id || raw.guild_id;
|
const idGremio = s.guild_id || raw.guild_id;
|
||||||
|
|
||||||
if (!guildName && idGremio) {
|
if (!guildName && idGremio) {
|
||||||
const guildObj = systemGuilds.find(g => String(g.id) === String(idGremio));
|
const guildObj = systemGuilds.find(g => String(g.id) === String(idGremio));
|
||||||
if (guildObj) guildName = guildObj.name;
|
if (guildObj) guildName = guildObj.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!guildName && s.guild && s.guild.name) {
|
if (!guildName && s.guild && s.guild.name) {
|
||||||
guildName = s.guild.name;
|
guildName = s.guild.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
guildName = guildName || "Varios";
|
|
||||||
|
|
||||||
|
guildName = guildName || "Varios";
|
||||||
return `
|
return `
|
||||||
<div class="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm relative overflow-hidden mb-4">
|
<div class="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm relative overflow-hidden mb-4">
|
||||||
${isUrgent ? '<div class="absolute top-0 right-0 bg-red-500 text-white text-[8px] font-black px-3 py-1 rounded-bl-xl uppercase tracking-widest shadow-sm z-10">Urgente</div>' : ''}
|
${isUrgent ? '<div class="absolute top-0 right-0 bg-red-500 text-white text-[8px] font-black px-3 py-1 rounded-bl-xl uppercase tracking-widest shadow-sm z-10">Urgente</div>' : ''}
|
||||||
|
|
||||||
<div onclick="openActionModal(${s.id})" class="flex gap-4 items-start active:scale-95 transition-transform cursor-pointer">
|
<div onclick="openActionModal(${s.id})" class="flex gap-4 items-start active:scale-95 transition-transform cursor-pointer">
|
||||||
<div class="w-12 h-12 bg-primary-dynamic/10 rounded-2xl flex flex-col items-center justify-center text-primary-dynamic shrink-0 border border-primary-dynamic/20 mt-1">
|
<div class="w-12 h-12 bg-primary-dynamic/10 rounded-2xl flex flex-col items-center justify-center text-primary-dynamic shrink-0 border border-primary-dynamic/20 mt-1">
|
||||||
<i data-lucide="clock" class="w-5 h-5"></i>
|
<i data-lucide="clock" class="w-5 h-5"></i>
|
||||||
@@ -640,10 +598,10 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
<p class="text-[10px] font-bold text-slate-500 mt-1 truncate uppercase flex items-center gap-1">
|
<p class="text-[10px] font-bold text-slate-500 mt-1 truncate uppercase flex items-center gap-1">
|
||||||
<i data-lucide="map-pin" class="w-3 h-3"></i> ${addr}, ${pop}
|
<i data-lucide="map-pin" class="w-3 h-3"></i> ${addr}, ${pop}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div class="mt-2.5 bg-slate-50 border border-slate-100 rounded-xl p-2.5 relative">
|
<div class="desc-box mt-2.5 bg-slate-50 border border-slate-100 rounded-xl p-2.5 relative active:bg-slate-100 transition-colors" onclick="toggleDesc(this, event)">
|
||||||
<p class="text-[10px] text-slate-600 font-medium leading-relaxed line-clamp-2 pr-4">${desc}</p>
|
<p class="text-[10px] text-slate-600 font-medium leading-relaxed line-clamp-2 pr-5">${desc}</p>
|
||||||
<i data-lucide="info" class="w-3 h-3 text-slate-300 absolute right-2 top-2.5"></i>
|
<i data-lucide="chevron-down" class="desc-toggle-icon w-3.5 h-3.5 text-slate-400 absolute right-2 top-2.5 shrink-0"></i>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="shrink-0 pr-2 self-center flex flex-col items-end justify-center gap-1.5 pl-2">
|
<div class="shrink-0 pr-2 self-center flex flex-col items-end justify-center gap-1.5 pl-2">
|
||||||
@@ -651,7 +609,6 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
<i data-lucide="chevron-right" class="text-slate-300"></i>
|
<i data-lucide="chevron-right" class="text-slate-300"></i>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mt-4 pt-4 border-t border-slate-100">
|
<div class="mt-4 pt-4 border-t border-slate-100">
|
||||||
<button onclick="markClientNotFound(${s.id}, ${calledTimes})" class="w-full bg-orange-50 border border-orange-100 hover:bg-orange-100 text-orange-600 font-black py-2.5 rounded-xl flex items-center justify-center gap-2 transition-colors text-[10px] uppercase tracking-widest">
|
<button onclick="markClientNotFound(${s.id}, ${calledTimes})" class="w-full bg-orange-50 border border-orange-100 hover:bg-orange-100 text-orange-600 font-black py-2.5 rounded-xl flex items-center justify-center gap-2 transition-colors text-[10px] uppercase tracking-widest">
|
||||||
<i data-lucide="bell-ring" class="w-4 h-4"></i> No Localizado (${calledTimes})
|
<i data-lucide="bell-ring" class="w-4 h-4"></i> No Localizado (${calledTimes})
|
||||||
@@ -660,14 +617,12 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}).join('');
|
}).join('');
|
||||||
|
|
||||||
lucide.createIcons();
|
lucide.createIcons();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔥 MEJORA MATA-FANTASMAS
|
// 🔥 MEJORA MATA-FANTASMAS
|
||||||
async function openActionModal(id) {
|
async function openActionModal(id) {
|
||||||
let s = localServices.find(x => x.id === id);
|
let s = localServices.find(x => x.id === id);
|
||||||
|
|
||||||
// Si el operario hace click en algo que justo acaba de desaparecer de la BD...
|
// Si el operario hace click en algo que justo acaba de desaparecer de la BD...
|
||||||
if (!s) {
|
if (!s) {
|
||||||
try {
|
try {
|
||||||
@@ -680,51 +635,44 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
}
|
}
|
||||||
} catch(e) {}
|
} catch(e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si definitivamente el aviso fue borrado/reasignado por la oficina
|
// Si definitivamente el aviso fue borrado/reasignado por la oficina
|
||||||
if (!s) {
|
if (!s) {
|
||||||
showToast("Este aviso ya no está en tu bandeja", true);
|
showToast("Este aviso ya no está en tu bandeja", true);
|
||||||
refreshData(); // Limpiamos la pantalla para que desaparezca visualmente
|
refreshData(); // Limpiamos la pantalla para que desaparezca visualmente
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const raw = s.raw_data;
|
const raw = s.raw_data;
|
||||||
|
|
||||||
document.getElementById('detId').value = s.id;
|
document.getElementById('detId').value = s.id;
|
||||||
document.getElementById('detRef').innerText = `Exp. #${s.service_ref || "S/R"}`;
|
document.getElementById('detRef').innerText = `Exp. #${s.service_ref || "S/R"}`;
|
||||||
document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado";
|
document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado";
|
||||||
document.getElementById('detAddress').innerText = `${raw["Dirección"] || ""}, ${raw["Población"] || ""}`;
|
document.getElementById('detAddress').innerText = `${raw["Dirección"] || ""}, ${raw["Población"] || ""}`;
|
||||||
|
|
||||||
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
||||||
const matchPhone = String(rawPhone).match(/[6789]\d{8}/);
|
const matchPhone = String(rawPhone).match(/[6789]\d{8}/);
|
||||||
document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : "";
|
document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : "";
|
||||||
|
document.getElementById('durationInput').value = "60";
|
||||||
document.getElementById('durationInput').value = "60";
|
pickerSelectedDate = "";
|
||||||
pickerSelectedDate = "";
|
pickerSelectedTime = "";
|
||||||
pickerSelectedTime = "";
|
buildDayCarousel();
|
||||||
buildDayCarousel();
|
|
||||||
checkSaveButton();
|
checkSaveButton();
|
||||||
|
|
||||||
const modal = document.getElementById('actionModal');
|
const modal = document.getElementById('actionModal');
|
||||||
const content = document.getElementById('modalContent');
|
const content = document.getElementById('modalContent');
|
||||||
modal.classList.remove('hidden');
|
modal.classList.remove('hidden');
|
||||||
void modal.offsetWidth;
|
void modal.offsetWidth;
|
||||||
modal.classList.remove('opacity-0');
|
modal.classList.remove('opacity-0');
|
||||||
content.classList.remove('translate-y-full');
|
content.classList.remove('translate-y-full');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markClientNotFound(serviceId, currentTimes) {
|
async function markClientNotFound(serviceId, currentTimes) {
|
||||||
const btn = event.currentTarget;
|
const btn = event.currentTarget;
|
||||||
const originalHtml = btn.innerHTML;
|
const originalHtml = btn.innerHTML;
|
||||||
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Enviando...`;
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Enviando...`;
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/services/not-found/${serviceId}`, {
|
const res = await fetch(`${API_URL}/services/not-found/${serviceId}`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.ok) {
|
if (data.ok) {
|
||||||
showToast(`Aviso enviado. Intentos: ${data.called_times}`);
|
showToast(`Aviso enviado. Intentos: ${data.called_times}`);
|
||||||
@@ -740,7 +688,6 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// LÓGICA DEL MOTOR DE AGENDAMIENTO INTELIGENTE
|
// LÓGICA DEL MOTOR DE AGENDAMIENTO INTELIGENTE
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -750,7 +697,6 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
const d = String(dateObj.getDate()).padStart(2, '0');
|
const d = String(dateObj.getDate()).padStart(2, '0');
|
||||||
return `${y}-${m}-${d}`;
|
return `${y}-${m}-${d}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function timeToMins(t) { let [h, m] = t.split(':').map(Number); return h * 60 + m; }
|
function timeToMins(t) { let [h, m] = t.split(':').map(Number); return h * 60 + m; }
|
||||||
function minsToTime(m) { let h = Math.floor(m / 60).toString().padStart(2, '0'); let min = (m % 60).toString().padStart(2, '0'); return `${h}:${min}`; }
|
function minsToTime(m) { let h = Math.floor(m / 60).toString().padStart(2, '0'); let min = (m % 60).toString().padStart(2, '0'); return `${h}:${min}`; }
|
||||||
function addOneHour(timeStr) {
|
function addOneHour(timeStr) {
|
||||||
@@ -771,24 +717,23 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
return d.toLocaleDateString('es-ES', opciones);
|
return d.toLocaleDateString('es-ES', opciones);
|
||||||
} catch(e) { return dateStr; }
|
} catch(e) { return dateStr; }
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildDayCarousel() {
|
function buildDayCarousel() {
|
||||||
const container = document.getElementById('dayCarousel');
|
const container = document.getElementById('dayCarousel');
|
||||||
container.innerHTML = "";
|
container.innerHTML = "";
|
||||||
let today = new Date();
|
let today = new Date();
|
||||||
|
|
||||||
// Si quieres que muestre más días hacia adelante (por ejemplo 21 o 30), solo cambia el 14 de aquí abajo
|
// Si quieres que muestre más días hacia adelante (por ejemplo 21 o 30), solo cambia el 14 de aquí abajo
|
||||||
for (let i = 0; i < 30; i++) {
|
for (let i = 0; i < 30; i++) {
|
||||||
let d = new Date(today);
|
let d = new Date(today);
|
||||||
d.setDate(today.getDate() + i);
|
d.setDate(today.getDate() + i);
|
||||||
|
|
||||||
const isoDate = toISODate(d);
|
const isoDate = toISODate(d);
|
||||||
const dayName = d.toLocaleDateString('es-ES', { weekday: 'short' }).replace('.', '').substring(0,3);
|
const dayName = d.toLocaleDateString('es-ES', { weekday: 'short' }).replace('.', '').substring(0,3);
|
||||||
const dayNum = d.getDate();
|
const dayNum = d.getDate();
|
||||||
|
|
||||||
if (!pickerSelectedDate) pickerSelectedDate = isoDate;
|
if (!pickerSelectedDate) pickerSelectedDate = isoDate;
|
||||||
const isSelected = isoDate === pickerSelectedDate;
|
const isSelected = isoDate === pickerSelectedDate;
|
||||||
|
|
||||||
container.innerHTML += `
|
container.innerHTML += `
|
||||||
<button type="button" onclick="selectPickerDate('${isoDate}')" class="day-chip flex flex-col items-center justify-center min-w-[3.5rem] p-2 rounded-2xl ${isSelected ? 'active' : 'inactive'}">
|
<button type="button" onclick="selectPickerDate('${isoDate}')" class="day-chip flex flex-col items-center justify-center min-w-[3.5rem] p-2 rounded-2xl ${isSelected ? 'active' : 'inactive'}">
|
||||||
<span class="text-[9px] font-black uppercase opacity-80">${dayName}</span>
|
<span class="text-[9px] font-black uppercase opacity-80">${dayName}</span>
|
||||||
@@ -797,21 +742,18 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectPickerDate(isoDate) {
|
function selectPickerDate(isoDate) {
|
||||||
pickerSelectedDate = isoDate;
|
pickerSelectedDate = isoDate;
|
||||||
pickerSelectedTime = "";
|
pickerSelectedTime = "";
|
||||||
buildDayCarousel();
|
buildDayCarousel();
|
||||||
renderTimeSlots();
|
renderTimeSlots();
|
||||||
checkSaveButton();
|
checkSaveButton();
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectPickerTime(timeStr) {
|
function selectPickerTime(timeStr) {
|
||||||
pickerSelectedTime = timeStr;
|
pickerSelectedTime = timeStr;
|
||||||
renderTimeSlots();
|
renderTimeSlots();
|
||||||
checkSaveButton();
|
checkSaveButton();
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkSaveButton() {
|
function checkSaveButton() {
|
||||||
const btn = document.getElementById('btnSaveAppt');
|
const btn = document.getElementById('btnSaveAppt');
|
||||||
if (pickerSelectedDate && pickerSelectedTime) {
|
if (pickerSelectedDate && pickerSelectedTime) {
|
||||||
@@ -824,7 +766,6 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
btn.classList.remove('bg-primary-dynamic', 'active:scale-95', 'shadow-lg');
|
btn.classList.remove('bg-primary-dynamic', 'active:scale-95', 'shadow-lg');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getOccupiedRanges(dateStr) {
|
function getOccupiedRanges(dateStr) {
|
||||||
let ranges = [];
|
let ranges = [];
|
||||||
globalAllServices.forEach(s => {
|
globalAllServices.forEach(s => {
|
||||||
@@ -837,27 +778,24 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
});
|
});
|
||||||
return ranges;
|
return ranges;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isOverlapping(startMins, endMins, occupiedRanges) {
|
function isOverlapping(startMins, endMins, occupiedRanges) {
|
||||||
for(let r of occupiedRanges) {
|
for(let r of occupiedRanges) {
|
||||||
if(startMins < r.end && endMins > r.start) return true;
|
if(startMins < r.end && endMins > r.start) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderTimeSlots() {
|
function renderTimeSlots() {
|
||||||
const grid = document.getElementById('timeGrid');
|
const grid = document.getElementById('timeGrid');
|
||||||
const msg = document.getElementById('noSlotsMsg');
|
const msg = document.getElementById('noSlotsMsg');
|
||||||
const duration = parseInt(document.getElementById('durationInput').value) || 60;
|
const duration = parseInt(document.getElementById('durationInput').value) || 60;
|
||||||
const occupied = getOccupiedRanges(pickerSelectedDate);
|
const occupied = getOccupiedRanges(pickerSelectedDate);
|
||||||
|
|
||||||
grid.innerHTML = "";
|
grid.innerHTML = "";
|
||||||
let slotsGenerated = 0;
|
let slotsGenerated = 0;
|
||||||
|
|
||||||
const genSlotsForPeriod = (startStr, endStr) => {
|
const genSlotsForPeriod = (startStr, endStr) => {
|
||||||
let startMins = timeToMins(startStr);
|
let startMins = timeToMins(startStr);
|
||||||
let endMins = timeToMins(endStr);
|
let endMins = timeToMins(endStr);
|
||||||
|
|
||||||
for (let m = startMins; m + duration <= endMins; m += 30) {
|
for (let m = startMins; m + duration <= endMins; m += 30) {
|
||||||
if (!isOverlapping(m, m + duration, occupied)) {
|
if (!isOverlapping(m, m + duration, occupied)) {
|
||||||
const timeStr = minsToTime(m);
|
const timeStr = minsToTime(m);
|
||||||
@@ -871,54 +809,22 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Cambiamos el horario comercial por una franja completa de 08:00 a 24:00
|
// Cambiamos el horario comercial por una franja completa de 08:00 a 24:00
|
||||||
genSlotsForPeriod('08:00', '24:00');
|
genSlotsForPeriod('08:00', '24:00');
|
||||||
|
|
||||||
if (slotsGenerated === 0) {
|
if (slotsGenerated === 0) {
|
||||||
msg.classList.remove('hidden');
|
msg.classList.remove('hidden');
|
||||||
grid.classList.add('hidden');
|
grid.classList.add('hidden');
|
||||||
pickerSelectedTime = "";
|
pickerSelectedTime = "";
|
||||||
} else {
|
} else {
|
||||||
msg.classList.add('hidden');
|
msg.classList.add('hidden');
|
||||||
grid.classList.remove('hidden');
|
grid.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pickerSelectedTime && !grid.innerHTML.includes(`'${pickerSelectedTime}'`)) {
|
if (pickerSelectedTime && !grid.innerHTML.includes(`'${pickerSelectedTime}'`)) {
|
||||||
pickerSelectedTime = "";
|
pickerSelectedTime = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
checkSaveButton();
|
checkSaveButton();
|
||||||
}
|
}
|
||||||
|
|
||||||
function openActionModal(id) {
|
|
||||||
const s = localServices.find(x => x.id === id);
|
|
||||||
if (!s) return;
|
|
||||||
const raw = s.raw_data;
|
|
||||||
|
|
||||||
document.getElementById('detId').value = s.id;
|
|
||||||
document.getElementById('detRef').innerText = `Exp. #${s.service_ref || "S/R"}`;
|
|
||||||
document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado";
|
|
||||||
document.getElementById('detAddress').innerText = `${raw["Dirección"] || ""}, ${raw["Población"] || ""}`;
|
|
||||||
|
|
||||||
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
||||||
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
|
|
||||||
document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : "";
|
|
||||||
|
|
||||||
document.getElementById('durationInput').value = "60";
|
|
||||||
pickerSelectedDate = "";
|
|
||||||
pickerSelectedTime = "";
|
|
||||||
buildDayCarousel();
|
|
||||||
checkSaveButton();
|
|
||||||
|
|
||||||
const modal = document.getElementById('actionModal');
|
|
||||||
const content = document.getElementById('modalContent');
|
|
||||||
modal.classList.remove('hidden');
|
|
||||||
void modal.offsetWidth;
|
|
||||||
modal.classList.remove('opacity-0');
|
|
||||||
content.classList.remove('translate-y-full');
|
|
||||||
}
|
|
||||||
|
|
||||||
function closeModal(modalId, contentId) {
|
function closeModal(modalId, contentId) {
|
||||||
const modal = document.getElementById(modalId);
|
const modal = document.getElementById(modalId);
|
||||||
const content = document.getElementById(contentId);
|
const content = document.getElementById(contentId);
|
||||||
@@ -926,61 +832,53 @@ function renderServices(servicesToRender = localServices) {
|
|||||||
content.classList.add('translate-y-full');
|
content.classList.add('translate-y-full');
|
||||||
setTimeout(() => { modal.classList.add('hidden'); }, 300);
|
setTimeout(() => { modal.classList.add('hidden'); }, 300);
|
||||||
}
|
}
|
||||||
|
|
||||||
function callClient() {
|
function callClient() {
|
||||||
const phone = document.getElementById('detPhoneRaw').value;
|
const phone = document.getElementById('detPhoneRaw').value;
|
||||||
if (phone) window.location.href = `tel:+34${phone}`;
|
if (phone) window.location.href = `tel:+34${phone}`;
|
||||||
else alert("No hay un teléfono válido guardado.");
|
else alert("No hay un teléfono válido guardado.");
|
||||||
}
|
}
|
||||||
|
|
||||||
function openWhatsApp() {
|
function openWhatsApp() {
|
||||||
const phone = document.getElementById('detPhoneRaw').value;
|
const phone = document.getElementById('detPhoneRaw').value;
|
||||||
if (phone) window.open(`https://wa.me/34${phone}`, '_blank');
|
if (phone) window.open(`https://wa.me/34${phone}`, '_blank');
|
||||||
else alert("No hay un teléfono válido guardado.");
|
else alert("No hay un teléfono válido guardado.");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveAppointment() {
|
async function saveAppointment() {
|
||||||
const id = document.getElementById('detId').value;
|
const id = document.getElementById('detId').value;
|
||||||
const duration = document.getElementById('durationInput').value;
|
const duration = document.getElementById('durationInput').value;
|
||||||
|
|
||||||
if (!pickerSelectedDate || !pickerSelectedTime) return alert("Selecciona un hueco disponible.");
|
if (!pickerSelectedDate || !pickerSelectedTime) return alert("Selecciona un hueco disponible.");
|
||||||
|
|
||||||
const btn = document.getElementById('btnSaveAppt');
|
const btn = document.getElementById('btnSaveAppt');
|
||||||
const originalContent = btn.innerHTML;
|
const originalContent = btn.innerHTML;
|
||||||
btn.innerHTML = `<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Agendando...`;
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Agendando...`;
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
|
|
||||||
const citadoStatus = systemStatuses.find(st => st.name.toLowerCase().includes('citado'));
|
const citadoStatus = systemStatuses.find(st => st.name.toLowerCase().includes('citado'));
|
||||||
const statusToSave = citadoStatus ? String(citadoStatus.id) : null;
|
const statusToSave = citadoStatus ? String(citadoStatus.id) : null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/services/set-appointment/${id}`, {
|
const res = await fetch(`${API_URL}/services/set-appointment/${id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
date: pickerSelectedDate,
|
date: pickerSelectedDate,
|
||||||
time: pickerSelectedTime,
|
time: pickerSelectedTime,
|
||||||
duration_minutes: duration,
|
duration_minutes: duration,
|
||||||
status_operativo: statusToSave
|
status_operativo: statusToSave
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
showToast("Cita Agendada en Calendario");
|
showToast("Cita Agendada en Calendario");
|
||||||
closeModal('actionModal', 'modalContent');
|
closeModal('actionModal', 'modalContent');
|
||||||
refreshData();
|
refreshData();
|
||||||
} else {
|
} else {
|
||||||
alert("Error al guardar la cita.");
|
alert("Error al guardar la cita.");
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert("Error de conexión");
|
alert("Error de conexión");
|
||||||
} finally {
|
} finally {
|
||||||
btn.innerHTML = originalContent;
|
btn.innerHTML = originalContent;
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
lucide.createIcons();
|
lucide.createIcons();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showToast(msg) {
|
function showToast(msg) {
|
||||||
const t = document.getElementById('toast');
|
const t = document.getElementById('toast');
|
||||||
document.getElementById('toastMsg').innerText = msg;
|
document.getElementById('toastMsg').innerText = msg;
|
||||||
|
|||||||
Reference in New Issue
Block a user