959 lines
51 KiB
HTML
959 lines
51 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>
|
|
<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; }
|
|
</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>
|
|
<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>
|
|
</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 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>
|
|
|
|
<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');
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 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] : "";
|
|
|
|
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">
|
|
<p class="text-[9px] font-black text-primary-dynamic uppercase tracking-widest mb-0.5">Cita Solicitada</p>
|
|
<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>
|
|
</div>
|
|
|
|
<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">${desc}</p>
|
|
</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>`;
|
|
}
|
|
|
|
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="mt-2.5 bg-slate-50 border border-slate-100 rounded-xl p-2.5 relative">
|
|
<p class="text-[10px] text-slate-600 font-medium leading-relaxed line-clamp-2 pr-4">${desc}</p>
|
|
<i data-lucide="info" class="w-3 h-3 text-slate-300 absolute right-2 top-2.5"></i>
|
|
</div>
|
|
</div>
|
|
<div class="text-slate-300 shrink-0 pr-2 self-center">
|
|
<i data-lucide="chevron-right"></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"] || ""}`;
|
|
|
|
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
|
|
const matchPhone = String(rawPhone).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');
|
|
}
|
|
|
|
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();
|
|
|
|
for (let i = 0; i < 14; i++) {
|
|
let d = new Date(today);
|
|
d.setDate(today.getDate() + i);
|
|
if (d.getDay() === 0) continue;
|
|
|
|
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++;
|
|
}
|
|
}
|
|
};
|
|
|
|
genSlotsForPeriod(bizHours.m_start, bizHours.m_end);
|
|
genSlotsForPeriod(bizHours.a_start, bizHours.a_end);
|
|
|
|
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 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) {
|
|
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.");
|
|
}
|
|
|
|
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);
|
|
}
|
|
</script>
|
|
</body>
|
|
</html> |