1175 lines
70 KiB
HTML
1175 lines
70 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>Pendientes de Cita - IntegraRepara</title>
|
|
<script src="https://cdn.tailwindcss.com"></script>
|
|
<script src="https://unpkg.com/lucide@latest"></script>
|
|
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
|
|
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
|
<style>
|
|
/* VARIABLES CORPORATIVAS DINÁMICAS */
|
|
:root {
|
|
--primary: #f59e0b;
|
|
--secondary: #2563eb;
|
|
--app-bg: #f4f7f9;
|
|
}
|
|
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; }
|
|
.bottom-nav-safe { padding-bottom: env(safe-area-inset-bottom); }
|
|
/* Clases dinámicas */
|
|
.text-primary-dynamic { color: var(--primary) !important; }
|
|
.bg-primary-dynamic { background-color: var(--primary) !important; }
|
|
.border-primary-dynamic { border-color: var(--primary) !important; }
|
|
|
|
/* Carrusel de fechas */
|
|
.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.inactive { background-color: #f8fafc; color: #64748b; border-color: #e2e8f0; }
|
|
/* Chips de Horas */
|
|
.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.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; }
|
|
|
|
/* 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>
|
|
</head>
|
|
<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">
|
|
<div>
|
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-0.5">Por Agendar</p>
|
|
<h1 class="text-2xl font-black tracking-tight text-slate-800 leading-none">Sin Cita</h1>
|
|
</div>
|
|
<div class="flex items-center gap-2">
|
|
<button onclick="openProximityMap()" class="w-10 h-10 bg-primary-dynamic/10 rounded-full flex items-center justify-center text-primary-dynamic border border-primary-dynamic/20 active:bg-primary-dynamic/20 transition-colors">
|
|
<i data-lucide="map-pinned" class="w-5 h-5"></i>
|
|
</button>
|
|
<a href="menu.html" class="w-10 h-10 bg-slate-50 rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-100 transition-colors">
|
|
<i data-lucide="arrow-left" class="w-5 h-5"></i>
|
|
</a>
|
|
</div>
|
|
</header>
|
|
<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">
|
|
<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>
|
|
</div>
|
|
|
|
<div id="contentWrapper" class="hidden pb-24 fade-in">
|
|
<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>
|
|
<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 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">
|
|
<span class="relative flex h-2.5 w-2.5">
|
|
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
|
|
<span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
|
|
</span>
|
|
Citas Solicitadas
|
|
</h2>
|
|
<div id="requestsList" class="space-y-4">
|
|
</div>
|
|
</div>
|
|
<div id="noDateSection">
|
|
<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>
|
|
</div>
|
|
</div>
|
|
</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">
|
|
<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">
|
|
<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-slate-400 hover:text-primary-dynamic transition-transform active:scale-95">
|
|
<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="refreshData()" class="flex flex-col items-center p-2 text-primary-dynamic transition-transform active:scale-95">
|
|
<i data-lucide="refresh-cw" class="w-6 h-6 mb-1"></i>
|
|
<span class="text-[9px] font-black uppercase tracking-widest">Recargar</span>
|
|
</button>
|
|
</div>
|
|
</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="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>
|
|
<span id="detRef" class="text-[10px] font-black text-slate-400 uppercase tracking-widest"></span>
|
|
<h3 class="font-black text-xl text-slate-800 uppercase leading-none" id="detName"></h3>
|
|
</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>
|
|
</div>
|
|
<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">
|
|
<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>
|
|
</div>
|
|
<input type="hidden" id="detId">
|
|
<input type="hidden" id="detPhoneRaw">
|
|
<div id="phoneSelectorRow" class="hidden flex items-center gap-2 mb-3 overflow-x-auto no-scrollbar"></div>
|
|
<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">
|
|
<i data-lucide="phone" class="w-5 h-5"></i>
|
|
<span class="text-[10px] uppercase tracking-widest">Llamar</span>
|
|
</button>
|
|
<button onclick="openWhatsApp()" class="bg-emerald-50 border border-emerald-100 text-emerald-600 font-black py-3 rounded-2xl flex items-center justify-center gap-2 active:scale-95 transition-transform shadow-sm">
|
|
<i data-lucide="message-circle" class="w-5 h-5"></i>
|
|
<span class="text-[10px] uppercase tracking-widest">WhatsApp</span>
|
|
</button>
|
|
</div>
|
|
<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>
|
|
<div class="flex justify-between items-center mb-2">
|
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest flex items-center gap-1.5"><i data-lucide="clock" class="w-4 h-4"></i> Duración Estimada</p>
|
|
</div>
|
|
<div class="relative">
|
|
<select id="durationInput" onchange="renderTimeSlots()" class="w-full bg-slate-50 border border-slate-200 p-4 rounded-xl text-sm font-black text-slate-700 shadow-inner outline-none focus:ring-2 focus:ring-amber-500 transition-all appearance-none pr-10 cursor-pointer">
|
|
<option value="15">15 Minutos (Muy rápido)</option>
|
|
<option value="30">30 Minutos</option>
|
|
<option value="45">45 Minutos</option>
|
|
<option value="60" selected>1 Hora (Estándar)</option>
|
|
<option value="90">1 Hora y Media</option>
|
|
<option value="120">2 Horas</option>
|
|
<option value="180">3 Horas</option>
|
|
<option value="240">4 Horas (Media jornada)</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>
|
|
<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>
|
|
<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>
|
|
<div id="timeGrid" class="grid grid-cols-4 gap-2"></div>
|
|
<p id="noSlotsMsg" class="hidden text-xs text-rose-500 font-bold bg-rose-50 p-3 rounded-xl border border-rose-100 text-center mt-2">
|
|
No hay huecos libres para esta duración.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<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">
|
|
<i data-lucide="calendar-check" class="w-5 h-5"></i> Confirmar Cita
|
|
</button>
|
|
</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="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>
|
|
<span id="appRef" class="text-[10px] font-black text-slate-400 uppercase tracking-widest"></span>
|
|
<h3 class="font-black text-xl text-slate-800 uppercase leading-none" id="appName"></h3>
|
|
</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>
|
|
</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="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>
|
|
<div class="flex justify-center gap-3">
|
|
<input type="date" id="appDateInput" 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>
|
|
<input type="hidden" id="appId">
|
|
<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>
|
|
<div class="relative">
|
|
<select id="appDurationInput" class="w-full bg-slate-50 border border-slate-200 p-4 rounded-xl text-sm font-black text-slate-700 outline-none focus:ring-2 focus:ring-primary-dynamic appearance-none pr-10">
|
|
<option value="15">15 Minutos (Muy rápido)</option>
|
|
<option value="30">30 Minutos</option>
|
|
<option value="45">45 Minutos</option>
|
|
<option value="60" selected>1 Hora (Estándar)</option>
|
|
<option value="90">1 Hora y Media</option>
|
|
<option value="120">2 Horas</option>
|
|
<option value="180">3 Horas</option>
|
|
<option value="240">4 Horas (Media jornada)</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="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">
|
|
<i data-lucide="x" class="w-4 h-4"></i> Rechazar
|
|
</button>
|
|
<button onclick="approveRequest()" id="btnApprove" class="bg-primary-dynamic text-white font-black py-4 rounded-xl shadow-lg hover:opacity-90 flex items-center justify-center gap-2 transition-all text-xs uppercase tracking-widest">
|
|
<i data-lucide="check" class="w-4 h-4"></i> Aceptar
|
|
</button>
|
|
</div>
|
|
<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 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>
|
|
<span id="toastMsg">Guardado</span>
|
|
</div>
|
|
|
|
<div id="proximityModal" class="fixed inset-0 bg-white z-[150] hidden flex flex-col">
|
|
<div class="bg-white px-5 pt-8 pb-4 shadow-sm shrink-0 border-b border-slate-100 flex justify-between items-center">
|
|
<div>
|
|
<p class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-0.5">Localización</p>
|
|
<h1 class="text-xl font-black tracking-tight text-slate-800 leading-none">Mapa de Cercanía</h1>
|
|
</div>
|
|
<button onclick="closeProximityMap()" class="w-10 h-10 bg-slate-50 rounded-full flex items-center justify-center text-slate-600 border border-slate-200 active:bg-slate-100 transition-colors">
|
|
<i data-lucide="x" class="w-5 h-5"></i>
|
|
</button>
|
|
</div>
|
|
<div id="proximityMapContainer" class="shrink-0 bg-slate-100" style="height:38vh; width:100%;"></div>
|
|
<div id="proximityStatus" class="px-5 py-6 text-center shrink-0">
|
|
<i data-lucide="loader-2" class="w-6 h-6 animate-spin mx-auto text-primary-dynamic mb-2"></i>
|
|
<p class="text-xs font-bold uppercase tracking-widest text-slate-400" id="proximityStatusMsg">Obteniendo tu ubicación...</p>
|
|
</div>
|
|
<div id="proximityListWrapper" class="flex-1 overflow-y-auto no-scrollbar p-5 pt-2 hidden">
|
|
<div id="proximityList" class="space-y-3"></div>
|
|
</div>
|
|
</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 globalAllServices = [];
|
|
let pendingRequests = [];
|
|
let systemStatuses = [];
|
|
let systemGuilds = [];
|
|
let bizHours = { m_start: '09:00', m_end: '14:00', a_start: '16:00', a_end: '19:00' };
|
|
// Variables del Agendador Inteligente
|
|
let pickerSelectedDate = "";
|
|
let pickerSelectedTime = "";
|
|
// --- SISTEMA DE TEMA DINÁMICO (VERSIÓN TODOTERRENO DEFINITIVA) ---
|
|
// --- SISTEMA DE TEMA DINÁMICO (EL BUENO) ---
|
|
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) {
|
|
// Aquí le enseñamos a la app a mirar en app_settings
|
|
if (data.config.app_settings) {
|
|
theme = typeof data.config.app_settings === 'string' ? JSON.parse(data.config.app_settings) : data.config.app_settings;
|
|
localStorage.setItem('app_theme', JSON.stringify(theme));
|
|
}
|
|
}
|
|
|
|
if(theme && theme.primary) {
|
|
document.documentElement.style.setProperty('--primary', theme.primary);
|
|
document.documentElement.style.setProperty('--secondary', theme.secondary);
|
|
document.documentElement.style.setProperty('--app-bg', theme.bg || '#f4f7f9');
|
|
}
|
|
} catch (e) { console.warn("Usando tema por defecto"); }
|
|
}
|
|
document.addEventListener("DOMContentLoaded", async () => {
|
|
if (!localStorage.getItem("token") || (localStorage.getItem("role") !== 'operario' && localStorage.getItem("role") !== 'operario_cerrado')) {
|
|
window.location.href = "index.html"; return;
|
|
}
|
|
await applyTheme();
|
|
lucide.createIcons();
|
|
await loadStatusesAndGuilds();
|
|
refreshData();
|
|
});
|
|
async function loadStatusesAndGuilds() {
|
|
try {
|
|
const headers = { "Authorization": `Bearer ${localStorage.getItem("token")}` };
|
|
const [resSt, resG] = await Promise.all([
|
|
fetch(`${API_URL}/statuses`, { headers }),
|
|
fetch(`${API_URL}/guilds`, { headers })
|
|
]);
|
|
const dataSt = await resSt.json();
|
|
const dataG = await resG.json();
|
|
if (dataSt.ok) systemStatuses = dataSt.statuses;
|
|
if (dataG.ok) systemGuilds = dataG.guilds;
|
|
} catch(e) {}
|
|
}
|
|
async function refreshData() {
|
|
document.getElementById('contentWrapper').classList.add('hidden');
|
|
document.getElementById('loader').classList.remove('hidden');
|
|
try {
|
|
const headers = { "Authorization": `Bearer ${localStorage.getItem("token")}` };
|
|
const myUserId = JSON.parse(atob(localStorage.getItem('token').split('.')[1])).sub;
|
|
|
|
const resActivos = await fetch(`${API_URL}/services/active`, { headers });
|
|
const dataActivos = await resActivos.json();
|
|
|
|
const resReqs = await fetch(`${API_URL}/agenda/requests`, { headers });
|
|
const dataReqs = await resReqs.json();
|
|
|
|
if (dataActivos.ok && dataReqs.ok) {
|
|
globalAllServices = dataActivos.services;
|
|
pendingRequests = dataReqs.requests;
|
|
|
|
// FILTRO MAESTRO CORREGIDO
|
|
localServices = globalAllServices.filter(s => {
|
|
// 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;
|
|
|
|
const raw = s.raw_data || {};
|
|
|
|
// 2. Si ya está en la lista de solicitudes, no lo duplicamos
|
|
if (raw.appointment_status === 'pending') return false;
|
|
|
|
// 3. SOLO PASAN LOS QUE NO TIENEN FECHA
|
|
if (raw.scheduled_date && raw.scheduled_date.trim() !== "") return false;
|
|
// 4. Asegurarnos de que no está terminado/anulado
|
|
if (raw.status_operativo) {
|
|
const st = systemStatuses.find(x => String(x.id) === String(raw.status_operativo));
|
|
if (st && st.is_final) return false;
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
renderRequests();
|
|
renderServices();
|
|
}
|
|
} catch (e) {
|
|
alert("Error de conexión");
|
|
} finally {
|
|
document.getElementById('loader').classList.add('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
|
|
// ==========================================
|
|
function renderRequests() {
|
|
const reqSection = document.getElementById('requestsSection');
|
|
const reqList = document.getElementById('requestsList');
|
|
reqList.innerHTML = '';
|
|
if (pendingRequests.length === 0) {
|
|
reqSection.classList.add('hidden');
|
|
return;
|
|
}
|
|
reqSection.classList.remove('hidden');
|
|
pendingRequests.forEach(req => {
|
|
const raw = req.raw_data || {};
|
|
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente";
|
|
const rDate = formatDate(raw.requested_date);
|
|
const rTime = addOneHour(raw.requested_time);
|
|
|
|
const desc = raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas de avería.";
|
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
|
|
const safePhone = matchPhone ? matchPhone[0] : "";
|
|
const addr = raw["Dirección"] || raw["DOMICILIO"] || "Sin dirección";
|
|
const pop = raw["Población"] || raw["POBLACION-PROVINCIA"] || "";
|
|
const cp = raw["Código Postal"] || raw["C.P."] || "";
|
|
const fullAddress = `${addr}, ${cp} ${pop}`.trim().replace(/^,\s*/, '').replace(/,\s*$/, '');
|
|
let guildName = raw["Gremio"] || raw["GREMIO"] || raw["Especialidad"] || "";
|
|
const idGremio = req.guild_id || raw.guild_id;
|
|
if (!guildName && idGremio) {
|
|
const guildObj = systemGuilds.find(g => String(g.id) === String(idGremio));
|
|
if (guildObj) guildName = guildObj.name;
|
|
}
|
|
if (!guildName && req.guild && req.guild.name) {
|
|
guildName = req.guild.name;
|
|
}
|
|
guildName = guildName || "Varios";
|
|
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="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="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>
|
|
<span class="text-[8px] font-black text-slate-500 bg-slate-100/80 px-2 py-0.5 rounded-lg uppercase tracking-widest text-center border border-slate-200/50 backdrop-blur-sm">${guildName}</span>
|
|
</div>
|
|
<h3 class="font-black text-slate-800 text-base leading-tight truncate pr-8">${name}</h3>
|
|
<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>
|
|
</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)">
|
|
<p class="text-[10px] font-medium text-slate-600 line-clamp-2 leading-relaxed pr-5">${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 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">
|
|
<i data-lucide="phone" class="w-4 h-4"></i> Llamar
|
|
</button>
|
|
<button onclick="openApproveModal(${req.id})" class="flex-1 bg-primary-dynamic text-white hover:opacity-90 font-black py-3 rounded-xl flex items-center justify-center gap-1.5 shadow-md active:scale-95 transition-transform text-[10px] uppercase tracking-widest">
|
|
Revisar <i data-lucide="chevron-right" class="w-4 h-4"></i>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
`;
|
|
});
|
|
lucide.createIcons();
|
|
}
|
|
function quickCallInline(phone) {
|
|
if (phone) window.location.href = `tel:+34${phone}`;
|
|
else alert("No hay un teléfono válido guardado.");
|
|
}
|
|
function openApproveModal(id) {
|
|
const req = pendingRequests.find(r => r.id === id);
|
|
if(!req) return;
|
|
const raw = req.raw_data || {};
|
|
document.getElementById('appId').value = id;
|
|
document.getElementById('appRef').innerText = `Exp. #${req.service_ref || "S/R"}`;
|
|
document.getElementById('appName').innerText = raw["Nombre Cliente"] || "Cliente";
|
|
|
|
document.getElementById('appDateInput').value = raw.requested_date || "";
|
|
document.getElementById('appTimeInput').value = raw.requested_time || "";
|
|
document.getElementById('appDurationInput').value = "60";
|
|
const modal = document.getElementById('approveModal');
|
|
const content = document.getElementById('approveModalContent');
|
|
modal.classList.remove('hidden');
|
|
void modal.offsetWidth;
|
|
modal.classList.remove('opacity-0');
|
|
content.classList.remove('translate-y-full');
|
|
}
|
|
async function approveRequest() {
|
|
const id = document.getElementById('appId').value;
|
|
const duration = document.getElementById('appDurationInput').value;
|
|
const date = document.getElementById('appDateInput').value;
|
|
const time = document.getElementById('appTimeInput').value;
|
|
const btn = document.getElementById('btnApprove');
|
|
const originalContent = btn.innerHTML;
|
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
|
btn.disabled = true;
|
|
try {
|
|
const res = await fetch(`${API_URL}/agenda/requests/${id}/approve`, {
|
|
method: 'POST',
|
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
|
body: JSON.stringify({ duration: duration, date: date, time: time })
|
|
});
|
|
if (res.ok) {
|
|
showToast("Cita Aceptada");
|
|
closeModal('approveModal', 'approveModalContent');
|
|
refreshData();
|
|
} else { alert("Error al confirmar."); }
|
|
} catch (e) { alert("Error de conexión"); }
|
|
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
|
|
}
|
|
async function rejectRequest() {
|
|
if(!confirm("¿Seguro que quieres rechazar este horario? El cliente recibirá un mensaje para elegir otro.")) return;
|
|
const id = document.getElementById('appId').value;
|
|
const btn = document.getElementById('btnReject');
|
|
const originalContent = btn.innerHTML;
|
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>`;
|
|
btn.disabled = true;
|
|
try {
|
|
const res = await fetch(`${API_URL}/agenda/requests/${id}/reject`, {
|
|
method: 'POST',
|
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
|
});
|
|
if (res.ok) {
|
|
showToast("Cita Rechazada");
|
|
closeModal('approveModal', 'approveModalContent');
|
|
refreshData();
|
|
} else { alert("Error al rechazar."); }
|
|
} catch (e) { alert("Error de conexión"); }
|
|
finally { btn.innerHTML = originalContent; btn.disabled = false; lucide.createIcons(); }
|
|
}
|
|
// ==========================================
|
|
// RENDERIZADO DE LISTADO NORMAL (SIN CITA)
|
|
// ==========================================
|
|
function calculateDelayDays(createdAtStr) {
|
|
if (!createdAtStr) return 0;
|
|
const createdDate = new Date(createdAtStr);
|
|
const now = new Date();
|
|
const diffTime = Math.abs(now - createdDate);
|
|
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
|
|
return diffDays;
|
|
}
|
|
// 🔥 FUNCIÓN DE FILTRADO (BUSCADOR) 🔥
|
|
function filterServices() {
|
|
const query = document.getElementById('searchInput').value.toLowerCase().trim();
|
|
|
|
if (query === "") {
|
|
renderServices(localServices); // Si borramos el texto, pinta todos
|
|
return;
|
|
}
|
|
const filtered = localServices.filter(s => {
|
|
const raw = s.raw_data || {};
|
|
|
|
// Juntamos todos los campos importantes en un solo texto invisible y buscamos ahí
|
|
const searchString = `
|
|
${s.service_ref || ""}
|
|
${raw["Nombre Cliente"] || raw["CLIENTE"] || ""}
|
|
${raw["Dirección"] || raw["DOMICILIO"] || ""}
|
|
${raw["Población"] || raw["POBLACION-PROVINCIA"] || ""}
|
|
${raw["Código Postal"] || raw["C.P."] || ""}
|
|
${raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"] || ""}
|
|
${raw["Compañía"] || raw["Procedencia"] || ""}
|
|
`.toLowerCase();
|
|
return searchString.includes(query);
|
|
});
|
|
renderServices(filtered);
|
|
}
|
|
function renderServices(servicesToRender = localServices) {
|
|
const container = document.getElementById('servicesList');
|
|
const noDateSec = document.getElementById('noDateSection');
|
|
|
|
if (servicesToRender.length === 0) {
|
|
// 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() !== "";
|
|
|
|
container.innerHTML = `
|
|
<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">
|
|
<i data-lucide="${isSearch ? 'search-x' : 'check-check'}" class="w-8 h-8"></i>
|
|
</div>
|
|
<h3 class="font-black text-slate-800 text-lg">${isSearch ? 'Sin resultados' : '¡Todo al día!'}</h3>
|
|
<p class="text-xs text-slate-400 font-medium mt-1">${isSearch ? 'Prueba con otra palabra clave.' : 'No tienes avisos pendientes de agendar.'}</p>
|
|
</div>`;
|
|
lucide.createIcons();
|
|
if (pendingRequests.length === 0) noDateSec.querySelector('h2').classList.add('hidden');
|
|
else noDateSec.classList.add('hidden');
|
|
return;
|
|
}
|
|
noDateSec.classList.remove('hidden');
|
|
noDateSec.querySelector('h2').classList.remove('hidden');
|
|
container.innerHTML = servicesToRender.map(s => {
|
|
const raw = s.raw_data || {};
|
|
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado";
|
|
const addr = raw["Dirección"] || "Sin dirección";
|
|
const pop = raw["Población"] || "";
|
|
const isUrgent = s.is_urgent;
|
|
const company = raw["Compañía"] || raw["Procedencia"] || "Particular";
|
|
|
|
// 🤖 "IA" LIMPIADORA: Filtramos la paja de las aseguradoras para dejar solo la avería real
|
|
function limpiarPaja(texto) {
|
|
if (!texto) return "Sin descripción de avería en el expediente.";
|
|
let res = texto.replace(/(\r\n|\n|\r)/gm, " ");
|
|
|
|
// 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, ' ');
|
|
|
|
// 2. Pulverizamos las frases administrativas típicas
|
|
const basura = [
|
|
/Llama asegurad[oa]\s*\d*/gi,
|
|
/solicita (operario|profesional) para/gi,
|
|
/Cobro banco.*?(?=\.|\s-|$)/gi,
|
|
/El servicio dispone de hasta.*?(?=\.|\s-|$)/gi,
|
|
/Servicio asignado a:.*?(?=\.|\s-|$)/gi,
|
|
/Cambio de estado:.*?(?=\.|\s-|$)/gi,
|
|
/y? el material debe ser aportado.*?(?=\.|\s-|$)/gi,
|
|
/informo material a cargo.*?(?=\.|\s-|$)/gi,
|
|
/en espera de profesional.*?(?=\.|\s-|$)/gi
|
|
];
|
|
|
|
basura.forEach(regex => { res = res.replace(regex, ' '); });
|
|
|
|
// 3. Limpiamos los espacios rotos y comas sueltas que hayan quedado
|
|
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.
|
|
return res.length > 5 ? res.charAt(0).toUpperCase() + res.slice(1) : texto;
|
|
}
|
|
let desc = limpiarPaja(raw["Descripción"] || raw["DESCRIPCION"] || raw["Averia"]);
|
|
const calledTimes = parseInt(raw.called_times || 0);
|
|
const delayDays = calculateDelayDays(s.created_at);
|
|
|
|
let delayHtml = '';
|
|
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>`;
|
|
}
|
|
let guildName = raw["Gremio"] || raw["GREMIO"] || raw["Especialidad"] || "";
|
|
|
|
// ¡AQUÍ ESTÁ LA CLAVE! El ID viene dentro del JSON (raw) o en el servicio (s)
|
|
const idGremio = s.guild_id || raw.guild_id;
|
|
|
|
if (!guildName && idGremio) {
|
|
const guildObj = systemGuilds.find(g => String(g.id) === String(idGremio));
|
|
if (guildObj) guildName = guildObj.name;
|
|
}
|
|
|
|
if (!guildName && s.guild && s.guild.name) {
|
|
guildName = s.guild.name;
|
|
}
|
|
|
|
guildName = guildName || "Varios";
|
|
return `
|
|
<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>' : ''}
|
|
|
|
<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">
|
|
<i data-lucide="clock" class="w-5 h-5"></i>
|
|
</div>
|
|
<div class="min-w-0 flex-1">
|
|
<p class="text-[9px] font-black text-blue-500 uppercase tracking-widest mb-0.5 truncate">${company} ${delayHtml}</p>
|
|
<h3 class="font-black text-slate-800 text-base uppercase leading-tight truncate">${name}</h3>
|
|
<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}
|
|
</p>
|
|
|
|
<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-5">${desc}</p>
|
|
<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 class="shrink-0 pr-2 self-center flex flex-col items-end justify-center gap-1.5 pl-2">
|
|
<span class="text-[8px] font-black text-slate-500 bg-slate-100 px-2 py-1 rounded-lg uppercase tracking-widest text-center" title="${guildName}">${guildName}</span>
|
|
<i data-lucide="chevron-right" class="text-slate-300"></i>
|
|
</div>
|
|
</div>
|
|
<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">
|
|
<i data-lucide="bell-ring" class="w-4 h-4"></i> No Localizado (${calledTimes})
|
|
</button>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}).join('');
|
|
lucide.createIcons();
|
|
}
|
|
// 🔥 MEJORA MATA-FANTASMAS
|
|
async function openActionModal(id) {
|
|
let s = localServices.find(x => x.id === id);
|
|
|
|
// Si el operario hace click en algo que justo acaba de desaparecer de la BD...
|
|
if (!s) {
|
|
try {
|
|
showToast("Sincronizando...");
|
|
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) {}
|
|
}
|
|
// Si definitivamente el aviso fue borrado/reasignado por la oficina
|
|
if (!s) {
|
|
showToast("Este aviso ya no está en tu bandeja", true);
|
|
refreshData(); // Limpiamos la pantalla para que desaparezca visualmente
|
|
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"] || ""}`;
|
|
|
|
// 📞 Usamos los teléfonos ya extraídos y priorizados (móvil primero) por la API.
|
|
// Si por caché no vinieran, caemos al match simple de siempre.
|
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
const matchPhone = String(rawPhone).match(/[6789]\d{8}/);
|
|
const fallbackPhone = matchPhone ? matchPhone[0] : "";
|
|
const detailPhones = Array.isArray(s.phones) && s.phones.length > 0
|
|
? s.phones
|
|
: (fallbackPhone ? [{ number: fallbackPhone, isMobile: /^[67]/.test(fallbackPhone), horario: '', contacto: '' }] : []);
|
|
document.getElementById('detPhoneRaw').value = detailPhones[0]?.number || "";
|
|
renderPhoneSelector(detailPhones);
|
|
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');
|
|
}
|
|
async function markClientNotFound(serviceId, currentTimes) {
|
|
const btn = event.currentTarget;
|
|
const originalHtml = btn.innerHTML;
|
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Enviando...`;
|
|
btn.disabled = true;
|
|
try {
|
|
const res = await fetch(`${API_URL}/services/not-found/${serviceId}`, {
|
|
method: 'POST',
|
|
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
|
});
|
|
|
|
const data = await res.json();
|
|
if (data.ok) {
|
|
showToast(`Aviso enviado. Intentos: ${data.called_times}`);
|
|
refreshData(); // Recargamos para actualizar el numerito
|
|
} else {
|
|
alert("Error al registrar la llamada.");
|
|
btn.innerHTML = originalHtml;
|
|
btn.disabled = false;
|
|
}
|
|
} catch (e) {
|
|
alert("Error de conexión");
|
|
btn.innerHTML = originalHtml;
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
// ==========================================
|
|
// LÓGICA DEL MOTOR DE AGENDAMIENTO INTELIGENTE
|
|
// ==========================================
|
|
function toISODate(dateObj) {
|
|
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}`;
|
|
}
|
|
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 addOneHour(timeStr) {
|
|
if(!timeStr) return "";
|
|
let [h, m] = timeStr.split(':').map(Number);
|
|
let totalMins = h * 60 + m + 60;
|
|
let newH = Math.floor(totalMins / 60);
|
|
let newM = totalMins % 60;
|
|
return `${String(newH).padStart(2,'0')}:${String(newM).padStart(2,'0')}`;
|
|
}
|
|
function formatDate(dateStr) {
|
|
if (!dateStr) return "";
|
|
try {
|
|
const parts = dateStr.split('-');
|
|
if(parts.length !== 3) return dateStr;
|
|
const d = new Date(parts[0], parts[1]-1, parts[2]);
|
|
const opciones = { weekday: 'short', day: 'numeric', month: 'short' };
|
|
return d.toLocaleDateString('es-ES', opciones);
|
|
} catch(e) { return dateStr; }
|
|
}
|
|
function buildDayCarousel() {
|
|
const container = document.getElementById('dayCarousel');
|
|
container.innerHTML = "";
|
|
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
|
|
for (let i = 0; i < 30; i++) {
|
|
let d = new Date(today);
|
|
d.setDate(today.getDate() + i);
|
|
|
|
const isoDate = toISODate(d);
|
|
const dayName = d.toLocaleDateString('es-ES', { weekday: 'short' }).replace('.', '').substring(0,3);
|
|
const dayNum = d.getDate();
|
|
|
|
if (!pickerSelectedDate) pickerSelectedDate = isoDate;
|
|
const isSelected = isoDate === pickerSelectedDate;
|
|
|
|
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'}">
|
|
<span class="text-[9px] font-black uppercase opacity-80">${dayName}</span>
|
|
<span class="text-lg font-black leading-none mt-1">${dayNum}</span>
|
|
</button>
|
|
`;
|
|
}
|
|
}
|
|
function selectPickerDate(isoDate) {
|
|
pickerSelectedDate = isoDate;
|
|
pickerSelectedTime = "";
|
|
buildDayCarousel();
|
|
renderTimeSlots();
|
|
checkSaveButton();
|
|
}
|
|
function selectPickerTime(timeStr) {
|
|
pickerSelectedTime = timeStr;
|
|
renderTimeSlots();
|
|
checkSaveButton();
|
|
}
|
|
function checkSaveButton() {
|
|
const btn = document.getElementById('btnSaveAppt');
|
|
if (pickerSelectedDate && pickerSelectedTime) {
|
|
btn.disabled = false;
|
|
btn.classList.remove('bg-slate-300', 'cursor-not-allowed');
|
|
btn.classList.add('bg-primary-dynamic', 'active:scale-95', 'shadow-lg');
|
|
} else {
|
|
btn.disabled = true;
|
|
btn.classList.add('bg-slate-300', 'cursor-not-allowed');
|
|
btn.classList.remove('bg-primary-dynamic', 'active:scale-95', 'shadow-lg');
|
|
}
|
|
}
|
|
function getOccupiedRanges(dateStr) {
|
|
let ranges = [];
|
|
globalAllServices.forEach(s => {
|
|
const raw = s.raw_data || {};
|
|
if (raw.scheduled_date === dateStr && raw.scheduled_time) {
|
|
const startMin = timeToMins(raw.scheduled_time);
|
|
const dur = parseInt(raw.duration_minutes || 60);
|
|
ranges.push({ start: startMin, end: startMin + dur });
|
|
}
|
|
});
|
|
return ranges;
|
|
}
|
|
function isOverlapping(startMins, endMins, occupiedRanges) {
|
|
for(let r of occupiedRanges) {
|
|
if(startMins < r.end && endMins > r.start) return true;
|
|
}
|
|
return false;
|
|
}
|
|
function renderTimeSlots() {
|
|
const grid = document.getElementById('timeGrid');
|
|
const msg = document.getElementById('noSlotsMsg');
|
|
const duration = parseInt(document.getElementById('durationInput').value) || 60;
|
|
const occupied = getOccupiedRanges(pickerSelectedDate);
|
|
|
|
grid.innerHTML = "";
|
|
let slotsGenerated = 0;
|
|
const genSlotsForPeriod = (startStr, endStr) => {
|
|
let startMins = timeToMins(startStr);
|
|
let endMins = timeToMins(endStr);
|
|
|
|
for (let m = startMins; m + duration <= endMins; m += 30) {
|
|
if (!isOverlapping(m, m + duration, occupied)) {
|
|
const timeStr = minsToTime(m);
|
|
const isSelected = timeStr === pickerSelectedTime;
|
|
grid.innerHTML += `
|
|
<button type="button" onclick="selectPickerTime('${timeStr}')" class="time-chip border rounded-xl py-2.5 text-xs font-bold ${isSelected ? 'active' : 'inactive hover:bg-slate-50'}">
|
|
${timeStr}
|
|
</button>
|
|
`;
|
|
slotsGenerated++;
|
|
}
|
|
}
|
|
};
|
|
// Cambiamos el horario comercial por una franja completa de 08:00 a 24:00
|
|
genSlotsForPeriod('08:00', '24:00');
|
|
if (slotsGenerated === 0) {
|
|
msg.classList.remove('hidden');
|
|
grid.classList.add('hidden');
|
|
pickerSelectedTime = "";
|
|
} else {
|
|
msg.classList.add('hidden');
|
|
grid.classList.remove('hidden');
|
|
}
|
|
|
|
if (pickerSelectedTime && !grid.innerHTML.includes(`'${pickerSelectedTime}'`)) {
|
|
pickerSelectedTime = "";
|
|
}
|
|
checkSaveButton();
|
|
}
|
|
function closeModal(modalId, contentId) {
|
|
const modal = document.getElementById(modalId);
|
|
const content = document.getElementById(contentId);
|
|
modal.classList.add('opacity-0');
|
|
content.classList.add('translate-y-full');
|
|
setTimeout(() => { modal.classList.add('hidden'); }, 300);
|
|
}
|
|
function callClient() {
|
|
const phone = document.getElementById('detPhoneRaw').value;
|
|
if (phone) window.location.href = `tel:+34${phone}`;
|
|
else alert("No hay un teléfono válido guardado.");
|
|
}
|
|
function openWhatsApp() {
|
|
const phone = document.getElementById('detPhoneRaw').value;
|
|
if (phone) window.open(`https://wa.me/34${phone}`, '_blank');
|
|
else alert("No hay un teléfono válido guardado.");
|
|
}
|
|
// 📞 Cuando el servicio trae más de un teléfono (típico de HomeServe), pintamos un
|
|
// selector de chips para que el operario elija cuál usar antes de Llamar/WhatsApp.
|
|
// Con un solo teléfono no mostramos nada (para no añadir ruido visual de más).
|
|
function renderPhoneSelector(phones) {
|
|
const row = document.getElementById('phoneSelectorRow');
|
|
if (!row) return;
|
|
if (!phones || phones.length <= 1) { row.innerHTML = ''; row.classList.add('hidden'); return; }
|
|
const active = document.getElementById('detPhoneRaw').value;
|
|
row.innerHTML = phones.map(p => {
|
|
const isActive = p.number === active;
|
|
return `
|
|
<button type="button" onclick="selectPhone('${p.number}')" class="shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-[10px] font-black uppercase tracking-widest ${isActive ? 'bg-primary-dynamic text-white border-primary-dynamic' : 'bg-white text-slate-500 border-slate-200'}">
|
|
<i data-lucide="${p.isMobile ? 'smartphone' : 'phone'}" class="w-3 h-3"></i> ${p.number}
|
|
</button>`;
|
|
}).join('');
|
|
row.classList.remove('hidden');
|
|
lucide.createIcons();
|
|
}
|
|
function selectPhone(number) {
|
|
document.getElementById('detPhoneRaw').value = number;
|
|
const s = localServices.find(x => String(x.id) === String(document.getElementById('detId').value));
|
|
renderPhoneSelector(Array.isArray(s?.phones) && s.phones.length > 0 ? s.phones : [{number, isMobile:/^[67]/.test(number)}]);
|
|
}
|
|
async function saveAppointment() {
|
|
const id = document.getElementById('detId').value;
|
|
const duration = document.getElementById('durationInput').value;
|
|
if (!pickerSelectedDate || !pickerSelectedTime) return alert("Selecciona un hueco disponible.");
|
|
const btn = document.getElementById('btnSaveAppt');
|
|
const originalContent = btn.innerHTML;
|
|
btn.innerHTML = `<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Agendando...`;
|
|
btn.disabled = true;
|
|
const citadoStatus = systemStatuses.find(st => st.name.toLowerCase().includes('citado'));
|
|
const statusToSave = citadoStatus ? String(citadoStatus.id) : null;
|
|
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: pickerSelectedDate,
|
|
time: pickerSelectedTime,
|
|
duration_minutes: duration,
|
|
status_operativo: statusToSave
|
|
})
|
|
});
|
|
|
|
if (res.ok) {
|
|
showToast("Cita Agendada en Calendario");
|
|
closeModal('actionModal', 'modalContent');
|
|
refreshData();
|
|
} else {
|
|
alert("Error al guardar la cita.");
|
|
}
|
|
} catch (e) {
|
|
alert("Error de conexión");
|
|
} finally {
|
|
btn.innerHTML = originalContent;
|
|
btn.disabled = false;
|
|
lucide.createIcons();
|
|
}
|
|
}
|
|
function showToast(msg) {
|
|
const t = document.getElementById('toast');
|
|
document.getElementById('toastMsg').innerText = msg;
|
|
t.classList.remove('opacity-0', 'pointer-events-none', '-translate-y-10');
|
|
t.classList.add('translate-y-0');
|
|
setTimeout(() => {
|
|
t.classList.add('opacity-0', 'pointer-events-none', '-translate-y-10');
|
|
t.classList.remove('translate-y-0');
|
|
}, 2500);
|
|
}
|
|
|
|
// ==========================================
|
|
// 🗺️ MAPA DE CERCANÍA (proximidad respecto a mi posición)
|
|
// ==========================================
|
|
let proximityAbort = false;
|
|
let proximityMap = null;
|
|
const proximityGeoCache = {}; // { "direccion normalizada": {lat, lng} | null }
|
|
|
|
function buildFullAddress(raw) {
|
|
const addr = raw["Dirección"] || raw["DOMICILIO"] || "";
|
|
const cp = raw["Código Postal"] || raw["C.P."] || "";
|
|
const pop = raw["Población"] || raw["POBLACION-PROVINCIA"] || "";
|
|
return `${addr}, ${cp} ${pop}`.trim().replace(/^,\s*/, '').replace(/,\s*$/, '');
|
|
}
|
|
|
|
function extractPhone(raw) {
|
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
const m = String(rawPhone).match(/[6789]\d{8}/);
|
|
return m ? m[0] : "";
|
|
}
|
|
|
|
function haversineKm(lat1, lon1, lat2, lon2) {
|
|
const R = 6371;
|
|
const dLat = (lat2 - lat1) * Math.PI / 180;
|
|
const dLon = (lon2 - lon1) * Math.PI / 180;
|
|
const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) ** 2;
|
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
|
}
|
|
|
|
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
|
|
|
async function geocodeAddress(addressStr) {
|
|
const key = addressStr.toLowerCase().trim();
|
|
if (!key) return null;
|
|
if (key in proximityGeoCache) return proximityGeoCache[key];
|
|
try {
|
|
let geoRes = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(addressStr + ', España')}`);
|
|
let geoData = await geoRes.json();
|
|
if (!geoData || geoData.length === 0) {
|
|
const parts = addressStr.split(',');
|
|
const fallback = parts.length > 1 ? parts[parts.length - 1].trim() : addressStr;
|
|
geoRes = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(fallback + ', España')}`);
|
|
geoData = await geoRes.json();
|
|
}
|
|
if (geoData && geoData.length > 0) {
|
|
const result = { lat: parseFloat(geoData[0].lat), lng: parseFloat(geoData[0].lon) };
|
|
proximityGeoCache[key] = result;
|
|
return result;
|
|
}
|
|
} catch (e) { /* seguimos sin coordenadas para esta dirección */ }
|
|
proximityGeoCache[key] = null;
|
|
return null;
|
|
}
|
|
|
|
function collectProximityCandidates() {
|
|
const candidates = [];
|
|
localServices.forEach(s => {
|
|
const raw = s.raw_data || {};
|
|
const address = buildFullAddress(raw);
|
|
if (!address || address === ",") return;
|
|
candidates.push({
|
|
id: s.id, type: 'sin_cita', address,
|
|
name: raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado",
|
|
company: raw["Compañía"] || raw["Procedencia"] || "Particular",
|
|
// 📞 Preferimos el teléfono ya priorizado (móvil primero) que manda la API;
|
|
// si no vino (caché vieja), caemos al match simple de siempre.
|
|
phone: (Array.isArray(s.phones) && s.phones[0]?.number) || extractPhone(raw), isUrgent: !!s.is_urgent
|
|
});
|
|
});
|
|
pendingRequests.forEach(req => {
|
|
const raw = req.raw_data || {};
|
|
const address = buildFullAddress(raw);
|
|
if (!address || address === ",") return;
|
|
candidates.push({
|
|
id: req.id, type: 'solicitada', address,
|
|
name: raw["Nombre Cliente"] || raw["CLIENTE"] || "Cliente",
|
|
company: raw["Compañía"] || raw["Procedencia"] || "Particular",
|
|
phone: extractPhone(raw), isUrgent: false
|
|
});
|
|
});
|
|
return candidates;
|
|
}
|
|
|
|
function openProximityMap() {
|
|
proximityAbort = false;
|
|
const modal = document.getElementById('proximityModal');
|
|
modal.classList.remove('hidden');
|
|
document.getElementById('proximityListWrapper').classList.add('hidden');
|
|
document.getElementById('proximityList').innerHTML = '';
|
|
const statusBox = document.getElementById('proximityStatus');
|
|
const statusMsg = document.getElementById('proximityStatusMsg');
|
|
statusBox.classList.remove('hidden');
|
|
statusBox.innerHTML = `<i data-lucide="loader-2" class="w-6 h-6 animate-spin mx-auto text-primary-dynamic mb-2"></i><p class="text-xs font-bold uppercase tracking-widest text-slate-400" id="proximityStatusMsg">Obteniendo tu ubicación...</p>`;
|
|
lucide.createIcons();
|
|
|
|
if (proximityMap) { proximityMap.remove(); proximityMap = null; }
|
|
|
|
const candidates = collectProximityCandidates();
|
|
if (candidates.length === 0) {
|
|
document.getElementById('proximityStatus').innerHTML = `
|
|
<i data-lucide="map-pin-off" class="w-8 h-8 mx-auto text-slate-300 mb-2"></i>
|
|
<p class="text-xs font-bold uppercase tracking-widest text-slate-400">No hay avisos con dirección para ubicar.</p>
|
|
`;
|
|
lucide.createIcons();
|
|
return;
|
|
}
|
|
|
|
if (!navigator.geolocation) {
|
|
showProximityError("Este dispositivo no permite obtener la ubicación.");
|
|
return;
|
|
}
|
|
|
|
navigator.geolocation.getCurrentPosition(
|
|
(pos) => runProximitySearch(pos.coords.latitude, pos.coords.longitude, candidates),
|
|
(err) => {
|
|
let msg = "No se pudo obtener tu ubicación.";
|
|
if (err.code === err.PERMISSION_DENIED) msg = "Activa el permiso de ubicación para ver el mapa de cercanía.";
|
|
else if (err.code === err.TIMEOUT) msg = "Se ha agotado el tiempo esperando tu ubicación.";
|
|
showProximityError(msg);
|
|
},
|
|
{ enableHighAccuracy: true, timeout: 12000, maximumAge: 60000 }
|
|
);
|
|
}
|
|
|
|
function showProximityError(msg) {
|
|
document.getElementById('proximityStatus').innerHTML = `
|
|
<i data-lucide="alert-triangle" class="w-8 h-8 mx-auto text-amber-400 mb-2"></i>
|
|
<p class="text-xs font-bold uppercase tracking-widest text-slate-400 mb-3">${msg}</p>
|
|
<button onclick="openProximityMap()" class="bg-primary-dynamic text-white text-[10px] font-black uppercase tracking-widest px-4 py-2 rounded-xl">Reintentar</button>
|
|
`;
|
|
lucide.createIcons();
|
|
}
|
|
|
|
async function runProximitySearch(myLat, myLng, candidates) {
|
|
const statusMsg = document.getElementById('proximityStatusMsg');
|
|
const results = [];
|
|
for (let i = 0; i < candidates.length; i++) {
|
|
if (proximityAbort) return;
|
|
if (statusMsg) statusMsg.innerText = `Localizando direcciones... (${i + 1}/${candidates.length})`;
|
|
const c = candidates[i];
|
|
const key = c.address.toLowerCase().trim();
|
|
const alreadyCached = key in proximityGeoCache;
|
|
const coords = await geocodeAddress(c.address);
|
|
results.push({ ...c, lat: coords ? coords.lat : null, lng: coords ? coords.lng : null,
|
|
distanceKm: coords ? haversineKm(myLat, myLng, coords.lat, coords.lng) : null });
|
|
if (!alreadyCached) await sleep(1100); // respeto al límite de uso de Nominatim (máx. 1 req/seg)
|
|
}
|
|
if (proximityAbort) return;
|
|
|
|
results.sort((a, b) => {
|
|
if (a.distanceKm === null) return 1;
|
|
if (b.distanceKm === null) return -1;
|
|
return a.distanceKm - b.distanceKm;
|
|
});
|
|
|
|
document.getElementById('proximityStatus').classList.add('hidden');
|
|
renderProximityMap(myLat, myLng, results);
|
|
renderProximityList(results);
|
|
}
|
|
|
|
function renderProximityMap(myLat, myLng, results) {
|
|
const mapDiv = document.getElementById('proximityMapContainer');
|
|
if (typeof L === 'undefined') return;
|
|
proximityMap = L.map(mapDiv, { zoomControl: true, attributionControl: false }).setView([myLat, myLng], 12);
|
|
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 }).addTo(proximityMap);
|
|
|
|
const meIcon = L.divIcon({
|
|
className: '', iconSize: [30, 30], iconAnchor: [15, 15],
|
|
html: '<div style="background:#2563eb;width:30px;height:30px;border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 0 0 6px rgba(37,99,235,0.25);border:2px solid white;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle></svg></div>'
|
|
});
|
|
const bounds = [[myLat, myLng]];
|
|
L.marker([myLat, myLng], { icon: meIcon }).addTo(proximityMap).bindPopup("Tu posición");
|
|
|
|
results.forEach((r, idx) => {
|
|
if (r.lat === null) return;
|
|
const color = r.type === 'solicitada' ? '#10b981' : (r.isUrgent ? '#ef4444' : '#f59e0b');
|
|
const pinIcon = L.divIcon({
|
|
className: '', iconSize: [28, 28], iconAnchor: [14, 28],
|
|
html: `<div style="background:${color};width:28px;height:28px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);box-shadow:0 2px 6px rgba(0,0,0,0.3);border:2px solid white;display:flex;align-items:center;justify-content:center;"><span style="transform:rotate(45deg);color:white;font-size:11px;font-weight:900;">${idx + 1}</span></div>`
|
|
});
|
|
L.marker([r.lat, r.lng], { icon: pinIcon }).addTo(proximityMap)
|
|
.bindPopup(`<b>${idx + 1}. ${r.name}</b><br>${r.distanceKm.toFixed(1)} km`);
|
|
bounds.push([r.lat, r.lng]);
|
|
});
|
|
|
|
if (bounds.length > 1) proximityMap.fitBounds(bounds, { padding: [40, 40] });
|
|
}
|
|
|
|
function renderProximityList(results) {
|
|
const wrapper = document.getElementById('proximityListWrapper');
|
|
const list = document.getElementById('proximityList');
|
|
wrapper.classList.remove('hidden');
|
|
list.innerHTML = results.map((r, idx) => {
|
|
const hasCoords = r.lat !== null;
|
|
const badgeColor = r.type === 'solicitada' ? 'bg-emerald-500' : (r.isUrgent ? 'bg-red-500' : 'bg-primary-dynamic');
|
|
const distanceLabel = hasCoords ? `${r.distanceKm.toFixed(1)} km` : 'Sin ubicar';
|
|
const dirUrl = hasCoords ? `https://www.google.com/maps/dir/?api=1&destination=${r.lat},${r.lng}` : null;
|
|
const openDetail = r.type === 'solicitada' ? `openApproveModal(${r.id})` : `openActionModal(${r.id})`;
|
|
return `
|
|
<div class="bg-white border border-slate-200 rounded-2xl p-4 shadow-sm flex items-start gap-3">
|
|
<div class="w-7 h-7 rounded-full ${badgeColor} text-white text-[11px] font-black flex items-center justify-center shrink-0 mt-0.5">${hasCoords ? idx + 1 : '?'}</div>
|
|
<div class="min-w-0 flex-1 cursor-pointer" onclick="closeProximityMap(); ${openDetail};">
|
|
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest truncate">${r.company} · ${distanceLabel}</p>
|
|
<h4 class="font-black text-slate-800 text-sm uppercase leading-tight truncate">${r.name}</h4>
|
|
<p class="text-[10px] font-bold text-slate-500 mt-0.5 truncate">${r.address}</p>
|
|
</div>
|
|
<div class="flex flex-col gap-1.5 shrink-0">
|
|
${dirUrl ? `<a href="${dirUrl}" target="_blank" onclick="event.stopPropagation()" class="w-8 h-8 bg-blue-50 border border-blue-100 text-blue-600 rounded-lg flex items-center justify-center"><i data-lucide="navigation" class="w-4 h-4"></i></a>` : ''}
|
|
${r.phone ? `<a href="tel:+34${r.phone}" onclick="event.stopPropagation()" class="w-8 h-8 bg-slate-50 border border-slate-200 text-slate-600 rounded-lg flex items-center justify-center"><i data-lucide="phone" class="w-4 h-4"></i></a>` : ''}
|
|
${r.phone ? `<a href="https://wa.me/34${r.phone}" target="_blank" onclick="event.stopPropagation()" class="w-8 h-8 bg-emerald-50 border border-emerald-100 text-emerald-600 rounded-lg flex items-center justify-center"><i data-lucide="message-circle" class="w-4 h-4"></i></a>` : ''}
|
|
</div>
|
|
</div>
|
|
`;
|
|
}).join('');
|
|
lucide.createIcons();
|
|
}
|
|
|
|
function closeProximityMap() {
|
|
proximityAbort = true;
|
|
document.getElementById('proximityModal').classList.add('hidden');
|
|
if (proximityMap) { proximityMap.remove(); proximityMap = null; }
|
|
}
|
|
</script>
|
|
</body>
|
|
</html> |