Files
App/asignados.html
2026-02-22 16:26:31 +00:00

330 lines
17 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">
<title>Pendientes de Cita - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
body { background-color: #f4f7f9; -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); }
</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">
<div>
<p class="text-[10px] font-black text-amber-500 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-amber-500 mb-2"></i>
<p class="text-xs font-bold uppercase tracking-widest">Buscando pendientes...</p>
</div>
<div id="servicesList" class="space-y-4 pb-24 hidden fade-in">
</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-amber-600 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-amber-600 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-amber-600 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">
<div class="flex justify-between items-center mb-6">
<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()" 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="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-4 rounded-2xl flex flex-col items-center gap-2 active:scale-95 transition-transform shadow-sm">
<i data-lucide="phone" class="w-6 h-6"></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-4 rounded-2xl flex flex-col items-center gap-2 active:scale-95 transition-transform shadow-sm">
<i data-lucide="message-circle" class="w-6 h-6"></i>
<span class="text-[10px] uppercase tracking-widest">WhatsApp</span>
</button>
</div>
<hr class="border-slate-100 mb-6">
<p class="text-[10px] font-black text-amber-500 uppercase tracking-widest mb-3">Establecer Cita</p>
<div class="grid grid-cols-2 gap-3 mb-4">
<input type="date" id="dateInput" class="w-full bg-white border border-slate-200 p-4 rounded-2xl text-sm font-bold text-slate-700 shadow-inner outline-none focus:ring-2 focus:ring-amber-500 transition-all">
<input type="time" id="timeInput" class="w-full bg-white border border-slate-200 p-4 rounded-2xl text-sm font-bold text-slate-700 shadow-inner outline-none focus:ring-2 focus:ring-amber-500 transition-all">
</div>
<button onclick="saveAppointment()" id="btnSaveAppt" class="w-full bg-amber-500 text-white font-black py-4 rounded-2xl shadow-lg shadow-amber-200 active:scale-95 transition-transform flex items-center justify-center gap-2 uppercase tracking-widest text-xs">
<i data-lucide="check-circle" class="w-5 h-5"></i> Confirmar Cita
</button>
</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 systemStatuses = [];
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token") || localStorage.getItem("role") !== 'operario') {
window.location.href = "index.html"; return;
}
lucide.createIcons();
loadStatuses();
refreshData();
});
async function loadStatuses() {
try {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) systemStatuses = data.statuses;
} catch (e) { console.error("Error estados:", e); }
}
async function refreshData() {
document.getElementById('servicesList').classList.add('hidden');
document.getElementById('loader').classList.remove('hidden');
try {
const res = await fetch(`${API_URL}/services/active`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
// FILTRO MAGICO: Solo nos quedamos con los que NO tienen fecha (scheduled_date vacío)
// y que no sean bloqueos del sistema ni estén terminados.
localServices = data.services.filter(s => {
if (s.provider === 'SYSTEM_BLOCK') return false;
const raw = s.raw_data || {};
// Si ya tiene fecha, no sale aquí (sale en calendario)
if (raw.scheduled_date && raw.scheduled_date.trim() !== "") return false;
// Si está terminado/anulado, no sale aquí
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;
});
renderServices();
}
} catch (e) {
alert("Error de conexión");
} finally {
document.getElementById('loader').classList.add('hidden');
document.getElementById('servicesList').classList.remove('hidden');
}
}
function renderServices() {
const container = document.getElementById('servicesList');
if (localServices.length === 0) {
container.innerHTML = `
<div class="text-center py-12 bg-white rounded-3xl border border-slate-100 shadow-sm mt-4">
<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="check-check" class="w-8 h-8"></i>
</div>
<h3 class="font-black text-slate-800 text-lg">¡Todo al día!</h3>
<p class="text-xs text-slate-400 font-medium mt-1">No tienes avisos pendientes de agendar.</p>
</div>`;
lucide.createIcons();
return;
}
container.innerHTML = localServices.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";
return `
<div onclick="openActionModal(${s.id})" class="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm active:scale-95 transition-transform flex gap-4 items-center relative overflow-hidden">
${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 class="w-12 h-12 bg-amber-50 rounded-2xl flex flex-col items-center justify-center text-amber-500 shrink-0 border border-amber-100">
<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}</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>
<div class="text-slate-300 shrink-0 pr-2">
<i data-lucide="chevron-right"></i>
</div>
</div>
`;
}).join('');
lucide.createIcons();
}
// ==========================================
// LÓGICA DEL MODAL DE ACCIONES
// ==========================================
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"] || ""}`;
// Extraer teléfono limpio
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
document.getElementById('detPhoneRaw').value = matchPhone ? matchPhone[0] : "";
// Limpiar inputs de fecha
document.getElementById('dateInput').value = "";
document.getElementById('timeInput').value = "";
// Mostrar modal con animación
const modal = document.getElementById('actionModal');
const content = document.getElementById('modalContent');
modal.classList.remove('hidden');
// Reflow hack para que aplique la transición
void modal.offsetWidth;
modal.classList.remove('opacity-0');
content.classList.remove('translate-y-full');
}
function closeModal() {
const modal = document.getElementById('actionModal');
const content = document.getElementById('modalContent');
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 date = document.getElementById('dateInput').value;
const time = document.getElementById('timeInput').value;
if (!date || !time) return alert("Selecciona fecha y hora para agendar.");
const btn = document.getElementById('btnSaveAppt');
const originalContent = btn.innerHTML;
btn.innerHTML = `<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Guardando...`;
btn.disabled = true;
// Buscamos el ID del estado "Citado" en el sistema
const citadoStatus = systemStatuses.find(st => st.name.toLowerCase().includes('citado'));
const statusToSave = citadoStatus ? String(citadoStatus.id) : null;
try {
// Al enviar la fecha a esta ruta del server, el server dispara el WhatsApp Automático al cliente
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: date, time: time, status_operativo: statusToSave })
});
if (res.ok) {
showToast("Cita guardada correctamente");
closeModal();
// Como ahora tiene fecha, desaparecerá de esta lista
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>