Files
App/index.html
2026-02-22 14:36:42 +00:00

346 lines
18 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>App Operario - 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); } }
/* Esconder scrollbar pero permitir scroll */
.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">
<header class="bg-white px-5 pt-6 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-blue-500 uppercase tracking-widest mb-0.5" id="headerDate">HOY</p>
<h1 class="text-2xl font-black tracking-tight text-slate-800 leading-none">Mi Ruta</h1>
</div>
<div class="w-10 h-10 bg-blue-50 rounded-full flex items-center justify-center text-blue-600 border border-blue-100">
<i data-lucide="user" class="w-5 h-5"></i>
</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-blue-500 mb-2"></i>
<p class="text-xs font-bold uppercase tracking-widest">Sincronizando...</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_-4px_20px_rgba(0,0,0,0.05)]">
<div class="flex justify-around items-center p-3 bottom-nav-safe">
<button class="flex flex-col items-center p-2 text-blue-600 transition-transform active:scale-95">
<i data-lucide="map" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-black uppercase tracking-widest">Ruta</span>
</button>
<button onclick="refreshData()" class="flex flex-col items-center p-2 text-slate-400 hover:text-slate-800 transition-transform active:scale-95">
<i data-lucide="refresh-cw" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-bold uppercase tracking-widest">Actualizar</span>
</button>
<button onclick="logout()" class="flex flex-col items-center p-2 text-slate-400 hover:text-red-500 transition-transform active:scale-95">
<i data-lucide="log-out" class="w-6 h-6 mb-1"></i>
<span class="text-[9px] font-bold uppercase tracking-widest">Salir</span>
</button>
</div>
</nav>
<div id="serviceModal" class="fixed inset-0 bg-white z-[100] hidden flex-col translate-y-full transition-transform duration-300">
<div class="p-5 border-b border-slate-100 flex justify-between items-center bg-slate-50 shrink-0">
<button onclick="closeModal()" class="bg-white p-2 rounded-xl shadow-sm border border-slate-200 text-slate-600 active:bg-slate-100"><i data-lucide="chevron-down" class="w-6 h-6"></i></button>
<h3 class="font-black text-sm uppercase tracking-widest text-slate-600">Detalle del Aviso</h3>
<div class="w-10"></div> </div>
<div class="flex-1 overflow-y-auto p-5 space-y-6 bg-white no-scrollbar pb-10">
<input type="hidden" id="detId">
<div class="text-center">
<span id="detRef" class="bg-slate-100 text-slate-500 px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest mb-2 inline-block"></span>
<h2 id="detName" class="text-2xl font-black text-slate-800 uppercase leading-none"></h2>
<p id="detCompany" class="text-xs font-bold text-blue-600 mt-2 uppercase"></p>
</div>
<div class="grid grid-cols-2 gap-3 border-y border-slate-100 py-6">
<a href="#" id="btnCall" 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>
</a>
<a href="#" id="btnMap" target="_blank" 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="navigation" class="w-6 h-6"></i>
<span class="text-[10px] uppercase tracking-widest">Navegar</span>
</a>
</div>
<div class="space-y-1">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Dirección</p>
<p id="detAddress" class="font-bold text-slate-700 text-sm bg-slate-50 p-3 rounded-xl border border-slate-100 uppercase"></p>
</div>
<div class="space-y-1">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Avería / Notas</p>
<p id="detDesc" class="font-medium text-slate-600 text-sm bg-amber-50/50 p-4 rounded-xl border border-amber-100 leading-relaxed"></p>
</div>
<div class="bg-slate-900 p-5 rounded-3xl mt-4 shadow-xl">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3">Actualizar Estado</p>
<select id="detStatus" class="w-full bg-slate-800 text-white border-none p-4 rounded-xl text-sm font-bold shadow-inner outline-none mb-4">
</select>
<button onclick="saveStatus()" id="btnSaveStatus" class="w-full bg-blue-600 text-white font-black py-4 rounded-xl shadow-lg hover:bg-blue-500 active:scale-95 transition-all uppercase tracking-widest text-xs flex justify-center items-center gap-2">
<i data-lucide="save" class="w-4 h-4"></i> Guardar Cambios
</button>
</div>
</div>
</div>
<div id="toast" class="fixed top-5 left-1/2 -translate-x-1/2 bg-slate-800 text-white px-5 py-3 rounded-full shadow-2xl z-[200] font-bold text-xs uppercase tracking-widest flex items-center gap-2 transition-all duration-300 opacity-0 pointer-events-none transform -translate-y-10">
<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", () => {
const token = localStorage.getItem("token");
const role = localStorage.getItem("role");
if (!token || role !== 'operario') {
window.location.href = "index.html"; // Expulsar si no es operario
return;
}
// Poner fecha bonita arriba
const options = { weekday: 'long', day: 'numeric', month: 'long' };
document.getElementById('headerDate').innerText = new Date().toLocaleDateString('es-ES', options);
loadStatuses();
refreshData();
lucide.createIcons();
});
async function loadStatuses() {
try {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
systemStatuses = data.statuses;
const select = document.getElementById('detStatus');
select.innerHTML = '';
systemStatuses.forEach(st => {
// Filtramos para que el operario no vea estados raros (opcional)
select.innerHTML += `<option value="${st.id}">👉 ${st.name.toUpperCase()}</option>`;
});
}
} 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) {
// Filtramos los bloques del sistema, solo vemos trabajos reales
localServices = data.services.filter(s => s.provider !== 'SYSTEM_BLOCK');
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-10 bg-white rounded-3xl border border-slate-100 shadow-sm mt-10">
<i data-lucide="coffee" class="w-12 h-12 text-slate-200 mx-auto mb-3"></i>
<h3 class="font-black text-slate-800">Ruta Limpia</h3>
<p class="text-xs text-slate-400 font-medium mt-1">No tienes avisos activos.</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"] || raw["DOMICILIO"] || "Sin dirección";
const pop = raw["Población"] || "";
const isUrgent = s.is_urgent;
// Color según estado
let estadoName = "Pendiente";
let dotColor = "bg-slate-400";
if(raw.status_operativo) {
const st = systemStatuses.find(x => String(x.id) === String(raw.status_operativo));
if(st) {
estadoName = st.name;
if(st.color === 'emerald') dotColor = 'bg-emerald-500';
if(st.color === 'indigo') dotColor = 'bg-indigo-500';
if(st.color === 'amber' || st.color === 'orange') dotColor = 'bg-amber-500';
if(st.color === 'red') dotColor = 'bg-red-500';
if(st.color === 'purple') dotColor = 'bg-purple-500';
}
}
// Cita (Si la hay)
const citaHTML = raw.scheduled_date
? `<div class="bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg text-[10px] font-black flex items-center gap-1.5"><i data-lucide="calendar-check" class="w-3.5 h-3.5"></i> ${raw.scheduled_time || 'A convenir'}</div>`
: `<div class="bg-amber-50 text-amber-600 px-3 py-1.5 rounded-lg text-[10px] font-black flex items-center gap-1.5"><i data-lucide="clock" class="w-3.5 h-3.5"></i> Sin Cita</div>`;
return `
<div onclick="openService(${s.id})" class="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm active:scale-95 transition-transform 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">Urgente</div>' : ''}
<div class="flex justify-between items-start mb-3">
<div class="flex items-center gap-2">
<div class="w-2.5 h-2.5 rounded-full ${dotColor} shadow-sm"></div>
<span class="text-[10px] font-black text-slate-500 uppercase tracking-wider">${estadoName}</span>
</div>
</div>
<h3 class="font-black text-slate-800 text-lg uppercase leading-tight truncate pr-10">${name}</h3>
<p class="text-xs font-medium text-slate-500 mt-1 flex items-center gap-1.5 truncate">
<i data-lucide="map-pin" class="w-3.5 h-3.5"></i> ${addr}, ${pop}
</p>
<div class="mt-4 pt-4 border-t border-slate-100 flex justify-between items-center">
${citaHTML}
<button class="bg-slate-900 text-white w-8 h-8 rounded-full flex items-center justify-center shadow-md">
<i data-lucide="arrow-right" class="w-4 h-4"></i>
</button>
</div>
</div>
`;
}).join('');
lucide.createIcons();
}
function openService(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 = s.service_ref || "S/R";
document.getElementById('detName').innerText = raw["Nombre Cliente"] || "Asegurado";
document.getElementById('detCompany').innerText = raw["Compañía"] || raw["Procedencia"] || "Particular";
document.getElementById('detAddress').innerText = `${raw["Dirección"] || ""}, ${raw["Población"] || ""}`;
document.getElementById('detDesc').innerText = raw["Descripción"] || "Sin notas adicionales.";
// Extraer y limpiar teléfono
const rawPhone = raw["Teléfono"] || raw["TELEFONOS"] || raw["TELEFONO"] || "";
const matchPhone = rawPhone.toString().match(/[6789]\d{8}/);
const singlePhone = matchPhone ? matchPhone[0] : "";
if (singlePhone) {
document.getElementById('btnCall').href = `tel:+34${singlePhone}`;
document.getElementById('btnCall').style.opacity = '1';
document.getElementById('btnCall').style.pointerEvents = 'auto';
} else {
document.getElementById('btnCall').href = "#";
document.getElementById('btnCall').style.opacity = '0.5';
document.getElementById('btnCall').style.pointerEvents = 'none';
}
// Preparar enlace de Maps
if (raw["Dirección"]) {
const query = encodeURIComponent(`${raw["Dirección"]}, ${raw["Población"] || ""}`);
document.getElementById('btnMap').href = `https://www.google.com/maps/search/?api=1&query=${query}`;
}
// Poner el estado actual en el select
if (raw.status_operativo) {
document.getElementById('detStatus').value = raw.status_operativo;
}
// Mostrar modal
const modal = document.getElementById('serviceModal');
modal.classList.remove('hidden');
// Pequeño delay para que la animación CSS funcione
setTimeout(() => {
modal.classList.remove('translate-y-full');
}, 10);
}
function closeModal() {
const modal = document.getElementById('serviceModal');
modal.classList.add('translate-y-full');
setTimeout(() => {
modal.classList.add('hidden');
}, 300);
}
async function saveStatus() {
const id = document.getElementById('detId').value;
const statusVal = document.getElementById('detStatus').value;
const btn = document.getElementById('btnSaveStatus');
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
try {
// Al usar la ruta PUT, se disparan los WhatsApps automáticos desde el servidor (Técnico en camino, Encuesta, etc)
const res = await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status_operativo: statusVal })
});
if(res.ok) {
showToast("Estado actualizado");
closeModal();
refreshData();
} else {
alert("Error guardando estado");
}
} catch (e) {
alert("Error de conexión");
} finally {
btn.innerHTML = '<i data-lucide="save" class="w-4 h-4"></i> Guardar Cambios';
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);
}
function logout() {
localStorage.clear();
window.location.href = "index.html";
}
</script>
</body>
</html>