Files
web/servicios.html
2026-02-20 17:46:39 +00:00

806 lines
52 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panel de Servicios - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@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; }
.card-hover:hover { transform: translateY(-3px); transition: all 0.2s; box-shadow: 0 12px 25px -5px rgba(0, 0, 0, 0.1); border-color: #93c5fd; }
/* ANIMACIÓN DE TEMBLOR (SHAKE) PARA TARJETAS BLOQUEADAS */
.shake { animation: shake 0.4s cubic-bezier(.36,.07,.19,.97) both; }
@keyframes shake {
10%, 90% { transform: translate3d(-2px, 0, 0); }
20%, 80% { transform: translate3d(4px, 0, 0); }
30%, 50%, 70% { transform: translate3d(-6px, 0, 0); }
40%, 60% { transform: translate3d(6px, 0, 0); }
}
.pulse-slow { animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .5; } }
</style>
</head>
<body class="bg-slate-50 text-slate-800 font-sans antialiased text-left">
<div class="flex h-screen overflow-hidden">
<div id="sidebar-container" class="h-full shrink-0"></div>
<div class="flex-1 flex flex-col overflow-hidden relative">
<div id="header-container"></div>
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-slate-50 p-6 no-scrollbar text-left relative">
<div class="fade-in max-w-[1400px] mx-auto space-y-6">
<div class="flex flex-col md:flex-row justify-between items-start md:items-center bg-white p-6 rounded-[2rem] shadow-sm border border-slate-100 gap-4">
<div>
<h2 class="text-2xl font-black text-slate-800 tracking-tight flex items-center gap-3">
<span class="bg-blue-600 p-2.5 rounded-xl text-white shadow-lg shadow-blue-200"><i data-lucide="layout-grid"></i></span>
PANEL OPERATIVO
</h2>
<p class="text-sm text-slate-500 mt-1 font-medium">Gestión inteligente de expedientes activos.</p>
</div>
<button onclick="openCreateModal()" class="bg-slate-900 hover:bg-blue-600 text-white px-6 py-3.5 rounded-2xl shadow-xl flex items-center gap-3 font-black text-xs uppercase tracking-widest transition-all active:scale-95 shrink-0">
<i data-lucide="plus-circle" class="w-5 h-5"></i> Nuevo Servicio
</button>
</div>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div class="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-full bg-rose-50 flex items-center justify-center text-rose-500 shrink-0"><i data-lucide="inbox" class="w-6 h-6"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Sin Asignar</p>
<h3 class="text-2xl font-black text-slate-800 leading-none mt-1" id="kpi-unassigned">0</h3>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-full bg-emerald-50 flex items-center justify-center text-emerald-500 shrink-0"><i data-lucide="calendar-check" class="w-6 h-6"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Agendados</p>
<h3 class="text-2xl font-black text-slate-800 leading-none mt-1" id="kpi-scheduled">0</h3>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-full bg-amber-50 flex items-center justify-center text-amber-500 shrink-0"><i data-lucide="wrench" class="w-6 h-6"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">En Curso</p>
<h3 class="text-2xl font-black text-slate-800 leading-none mt-1" id="kpi-active">0</h3>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-full bg-purple-50 flex items-center justify-center text-purple-500 shrink-0"><i data-lucide="check-circle" class="w-6 h-6"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Finalizados</p>
<h3 class="text-2xl font-black text-slate-800 leading-none mt-1" id="kpi-finished">0</h3>
</div>
</div>
</div>
<div class="bg-white p-4 rounded-[1.5rem] shadow-sm border border-slate-100 space-y-4 sticky top-0 z-10">
<div class="flex flex-wrap gap-4 items-center">
<div class="relative flex-1 min-w-[250px]">
<i data-lucide="search" class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
<input type="text" id="searchFilter" oninput="renderLists()" placeholder="Buscar por cliente, REF, población, compañía, teléfono..." class="w-full pl-11 pr-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-xs font-bold focus:ring-2 focus:ring-blue-500 outline-none transition-all">
</div>
<div class="relative w-full md:w-64">
<select id="opFilter" onchange="renderLists()" class="w-full bg-slate-50 border border-slate-200 text-xs font-black px-4 py-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 uppercase tracking-widest text-slate-600 appearance-none pr-10 cursor-pointer">
<option value="ALL">TODOS LOS OPERARIOS</option>
</select>
<i data-lucide="chevron-down" class="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none"></i>
</div>
</div>
<div class="flex flex-wrap gap-2 items-center border-t border-slate-100 pt-3" id="statusPills">
<span class="text-[10px] font-black text-slate-400 uppercase mr-2"><i data-lucide="loader-2" class="w-3 h-3 animate-spin inline"></i> Cargando estados...</span>
</div>
</div>
<div id="servicesGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 pb-12">
</div>
</div>
</main>
</div>
</div>
<div id="createModal" class="fixed inset-0 bg-slate-900/80 hidden z-[100] flex items-center justify-center backdrop-blur-sm p-4 text-left">
<div class="bg-white rounded-[2.5rem] shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col fade-in">
<div class="p-8 border-b flex justify-between items-center bg-slate-50">
<h3 class="font-black text-slate-800 uppercase tracking-tighter text-xl">Alta de Expediente Manual</h3>
<button onclick="closeCreateModal()" class="text-slate-400 hover:text-red-500 transition-colors"><i data-lucide="x"></i></button>
</div>
<form onsubmit="saveNewService(event)" class="p-8 overflow-y-auto no-scrollbar grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="space-y-4">
<div class="bg-blue-50/50 p-6 rounded-3xl border border-blue-100 space-y-4">
<h4 class="font-black text-blue-400 uppercase text-[10px] tracking-widest">Información del Cliente</h4>
<input type="tel" id="nPhone" placeholder="Teléfono" class="w-full bg-white border-none px-4 py-3 rounded-xl shadow-sm font-bold outline-none" required>
<input type="text" id="nName" placeholder="Nombre completo" class="w-full bg-white border-none px-4 py-3 rounded-xl shadow-sm font-bold outline-none" required>
<input type="text" id="nAddr" placeholder="Dirección completa" class="w-full bg-white border-none px-4 py-3 rounded-xl shadow-sm font-bold outline-none" required>
</div>
<textarea id="nDesc" placeholder="Descripción de la avería..." rows="4" class="w-full bg-slate-50 border-none px-4 py-3 rounded-3xl text-sm font-medium outline-none"></textarea>
</div>
<div class="space-y-6">
<select id="nGuild" class="w-full bg-slate-100 p-4 rounded-2xl font-bold outline-none" onchange="loadOps(this.value, 'nWorker')">
<option value="">Seleccionar Gremio...</option>
</select>
<div class="bg-slate-900 p-6 rounded-[2rem] text-white space-y-4">
<button type="submit" name="action" value="auto" class="w-full bg-blue-600 hover:bg-blue-500 p-4 rounded-2xl flex items-center justify-between text-left transition-all">
<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[10px] text-blue-200">WhatsApp Automático</p></div>
<i data-lucide="zap" class="w-6 h-6"></i>
</button>
<div class="bg-slate-800 p-4 rounded-2xl space-y-3">
<p class="font-black uppercase text-[10px] text-slate-500 text-center">Asignar a Mano:</p>
<select id="nWorker" class="w-full bg-slate-700 border-none text-white px-3 py-2 rounded-xl text-sm outline-none">
<option value="">-- Primero elija gremio --</option>
</select>
<button type="submit" name="action" value="manual" class="w-full bg-white text-slate-900 font-black py-3 rounded-xl text-xs uppercase hover:bg-emerald-400 transition-colors">Confirmar Directo</button>
</div>
</div>
</div>
</form>
</div>
</div>
<div id="detailModal" class="fixed inset-0 bg-slate-900/90 hidden z-[120] flex items-center justify-center backdrop-blur-sm p-4 text-left">
<div class="bg-white rounded-[2rem] shadow-2xl w-full max-w-4xl overflow-hidden flex flex-col fade-in relative">
<button onclick="closeDetailModal()" class="absolute top-6 right-6 text-slate-400 hover:text-red-500 bg-white shadow-sm border border-slate-200 p-2.5 rounded-full transition-all hover:bg-red-50 hover:border-red-100 z-10"><i data-lucide="x" class="w-5 h-5"></i></button>
<div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50 pr-24">
<div class="flex items-center gap-3">
<div class="bg-blue-100 p-2.5 rounded-xl text-blue-600 shadow-inner"><i data-lucide="folder-open" class="w-5 h-5"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Expediente Oficial</p>
<h3 class="font-black text-slate-800 text-xl leading-none tracking-tight">#<span id="detRef"></span></h3>
</div>
</div>
<div class="flex flex-col items-end text-right">
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Compañía Aseguradora</p>
<span id="detCompany" class="bg-white border border-slate-200 px-3 py-1 rounded-lg text-xs font-black text-slate-700 mt-1 uppercase shadow-sm truncate max-w-[250px]"></span>
</div>
</div>
<div class="p-6 grid grid-cols-1 md:grid-cols-5 gap-6 bg-white overflow-y-auto max-h-[80vh] no-scrollbar">
<input type="hidden" id="detId">
<input type="hidden" id="detCp">
<div class="md:col-span-3 space-y-4">
<div class="bg-slate-50 p-5 rounded-[1.5rem] border border-slate-100 space-y-4">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Asegurado / Cliente</p>
<p id="detName" class="font-black text-slate-800 text-lg uppercase mt-0.5 leading-tight"></p>
<div class="flex items-center gap-4 mt-1.5">
<a href="#" id="detPhoneLink" class="text-sm text-blue-600 font-black flex items-center gap-1.5 hover:underline w-max">
<i data-lucide="phone" class="w-3.5 h-3.5"></i> <span id="detPhone"></span>
</a>
<button onclick="copyClientPortalLink()" id="btnPortalLink" class="text-[10px] font-black bg-blue-50 border border-blue-100 hover:bg-blue-600 hover:text-white text-blue-600 px-3 py-1.5 rounded-lg flex items-center gap-1.5 transition-all shadow-sm active:scale-95">
<i data-lucide="link" class="w-3 h-3"></i> Copiar Portal Cliente
</button>
</div>
</div>
<hr class="border-slate-200">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest">Ubicación y Dirección</p>
<p class="text-sm font-bold text-slate-600 mt-1 flex items-start gap-1.5 leading-snug">
<i data-lucide="map-pin" class="w-4 h-4 mt-0.5 text-slate-400 shrink-0"></i>
<span id="detAddrText" class="uppercase"></span>
</p>
</div>
</div>
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2 ml-2">Descripción de la Avería</p>
<div class="bg-amber-50/60 border border-amber-100 p-5 rounded-[1.5rem] text-sm font-medium text-slate-700 min-h-[120px] max-h-48 overflow-y-auto no-scrollbar shadow-inner leading-relaxed" id="detDesc"></div>
</div>
</div>
<div class="md:col-span-2 flex flex-col gap-4">
<div id="panelAsignado" class="bg-blue-50/40 p-6 rounded-[1.5rem] border border-blue-100 flex flex-col justify-between shadow-sm h-full hidden">
<div class="space-y-6">
<div>
<p class="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1.5">Operario Asignado</p>
<div class="flex items-center gap-3 bg-white p-3 rounded-2xl border border-slate-100 shadow-sm">
<div class="bg-emerald-100 w-10 h-10 rounded-full flex items-center justify-center text-emerald-600 shrink-0"><i data-lucide="hard-hat" class="w-5 h-5"></i></div>
<p id="detWorker" class="font-black text-slate-700 text-xs uppercase leading-tight"></p>
</div>
</div>
<div class="space-y-3">
<p class="text-[10px] font-black text-blue-600 uppercase tracking-widest flex items-center gap-1.5 border-b border-blue-100 pb-2"><i data-lucide="calendar-clock" class="w-4 h-4"></i> Agendar Cita</p>
<div class="grid grid-cols-2 gap-2">
<input type="date" id="dateInput" class="w-full bg-white border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
<input type="time" id="timeInput" class="w-full bg-white border border-slate-200 p-3 rounded-xl text-xs font-bold text-slate-700 shadow-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all">
</div>
</div>
<div class="space-y-2 pt-2">
<p class="text-[10px] font-black text-slate-800 uppercase ml-1 flex items-center gap-1.5"><i data-lucide="arrow-right-left" class="w-4 h-4 text-blue-500"></i> Cambio de Estado</p>
<div class="relative">
<select id="detStatusMap" class="w-full bg-slate-800 text-white border-none p-4 rounded-xl text-xs font-bold shadow-lg outline-none cursor-pointer appearance-none pr-10">
</select>
<i data-lucide="chevron-down" class="w-4 h-4 text-slate-400 absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none"></i>
</div>
</div>
</div>
<button id="btnSaveAppt" onclick="saveAppointment()" class="w-full mt-8 bg-blue-600 text-white font-black py-4 rounded-2xl text-xs uppercase tracking-widest shadow-[0_8px_20px_-6px_rgba(37,99,235,0.5)] hover:bg-blue-700 hover:shadow-blue-600/30 transition-all active:scale-95 flex items-center justify-center gap-2 border border-blue-500">
<i data-lucide="save" class="w-4 h-4"></i> Guardar Cambios
</button>
</div>
<div id="panelSinAsignar" class="bg-rose-50/40 p-6 rounded-[1.5rem] border border-rose-100 flex flex-col shadow-sm h-full hidden">
<div class="flex items-center gap-2 mb-6">
<div class="w-2.5 h-2.5 rounded-full bg-rose-500 animate-pulse"></div>
<p class="text-[10px] font-black text-rose-600 uppercase tracking-widest">Opciones de Asignación</p>
</div>
<div class="space-y-5 flex-1">
<select id="reGremio" class="w-full bg-white border border-rose-200 p-4 rounded-2xl text-xs font-bold text-slate-700 outline-none" onchange="loadOps(this.value, 'reOperario')">
<option value="">Seleccionar Gremio...</option>
</select>
<div class="bg-slate-900 p-5 rounded-2xl text-white space-y-4">
<button onclick="sendToAutomate()" id="btnAuto" class="w-full bg-blue-600 hover:bg-blue-500 p-3 rounded-xl flex items-center justify-between text-left transition-all active:scale-95">
<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[9px] text-blue-200">Rueda automática (WA)</p></div>
<i data-lucide="zap" class="w-5 h-5"></i>
</button>
<div class="bg-slate-800 p-4 rounded-xl space-y-3">
<p class="font-black uppercase text-[9px] text-slate-400 text-center">O Asignar a Mano:</p>
<select id="reOperario" class="w-full bg-slate-700 border-none text-white px-3 py-2.5 rounded-lg text-xs font-bold outline-none">
<option value="">-- Elija gremio primero --</option>
</select>
<button onclick="assignManualFromPanel()" class="w-full bg-white text-slate-900 font-black py-2.5 rounded-lg text-[10px] uppercase hover:bg-emerald-400 transition-colors">Confirmar Directo</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="toastAppt" class="fixed bottom-8 right-8 bg-emerald-600 text-white px-6 py-4 rounded-2xl shadow-2xl hidden z-[200] font-bold text-sm flex items-center gap-3 transition-colors duration-300">
<span id="toastIconContainer"><i data-lucide="check-circle" class="w-5 h-5"></i></span>
<span id="toastMsg">Guardado correctamente</span>
</div>
<script src="js/layout.js"></script>
<script>
let localData = [];
let systemStatuses = [];
let activeStatusFilter = 'ALL';
const colorDict = {
'gray': { bg: 'bg-slate-100', text: 'text-slate-600', dot: 'bg-slate-500', border: 'border-slate-200' },
'blue': { bg: 'bg-blue-100', text: 'text-blue-700', dot: 'bg-blue-500', border: 'border-blue-200' },
'emerald': { bg: 'bg-emerald-100', text: 'text-emerald-700', dot: 'bg-emerald-500', border: 'border-emerald-200' },
'amber': { bg: 'bg-amber-100', text: 'text-amber-700', dot: 'bg-amber-500', border: 'border-amber-200' },
'orange': { bg: 'bg-orange-100', text: 'text-orange-700', dot: 'bg-orange-500', border: 'border-orange-200' },
'red': { bg: 'bg-red-100', text: 'text-red-700', dot: 'bg-red-500', border: 'border-red-200' },
'purple': { bg: 'bg-purple-100', text: 'text-purple-700', dot: 'bg-purple-500', border: 'border-purple-200' },
'indigo': { bg: 'bg-indigo-100', text: 'text-indigo-700', dot: 'bg-indigo-500', border: 'border-indigo-200' },
'rose': { bg: 'bg-rose-100', text: 'text-rose-700', dot: 'bg-rose-500', border: 'border-rose-200' }
};
document.addEventListener("DOMContentLoaded", async () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
await loadStatuses();
refreshPanel();
loadGuilds();
setInterval(refreshPanel, 20000);
});
// 1. CARGAMOS LOS ESTADOS DEL SISTEMA
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;
renderStatusPills();
// Llenar el selector del Modal
const modalSelect = document.getElementById('detStatusMap');
modalSelect.innerHTML = '';
systemStatuses.forEach(st => {
modalSelect.innerHTML += `<option value="${st.id}">👉 ${st.name.toUpperCase()}</option>`;
});
}
} catch (e) { console.error("Error cargando estados:", e); }
}
// 2. RENDERIZAR BOTONERA DE ESTADOS (CHIPS)
function renderStatusPills() {
const container = document.getElementById('statusPills');
let html = `
<button onclick="setStatusFilter('ALL')" class="px-5 py-2 rounded-xl text-xs font-bold transition-all border ${activeStatusFilter === 'ALL' ? 'bg-slate-800 text-white border-slate-800 shadow-md' : 'bg-white border-slate-200 text-slate-500 hover:bg-slate-50'}">
TODOS
</button>
`;
systemStatuses.forEach(st => {
const isActive = activeStatusFilter === String(st.id);
const colorData = colorDict[st.color] || colorDict['gray'];
const activeClasses = `bg-white border-${st.color}-400 text-${st.color}-700 shadow-md ring-2 ring-${st.color}-100`;
const inactiveClasses = `bg-white border-slate-200 text-slate-500 hover:bg-slate-50`;
html += `
<button onclick="setStatusFilter('${st.id}')" class="px-4 py-2 rounded-xl text-xs font-bold border transition-all flex items-center gap-2 ${isActive ? activeClasses : inactiveClasses}">
<div class="w-2 h-2 rounded-full ${colorData.dot}"></div>
${st.name}
</button>
`;
});
container.innerHTML = html;
}
function setStatusFilter(id) {
activeStatusFilter = id;
renderStatusPills();
renderLists();
}
async function refreshPanel() {
try {
const res = await fetch(`${API_URL}/services/active`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
localData = data.services;
updateOperatorFilter();
renderLists();
}
} catch (e) { console.error(e); }
}
function updateOperatorFilter() {
const opSelect = document.getElementById('opFilter');
const currentValue = opSelect.value;
const uniqueOps = [...new Set(localData.map(s => s.assigned_name).filter(Boolean))].sort();
let html = '<option value="ALL">TODOS LOS OPERARIOS</option>';
uniqueOps.forEach(op => { html += `<option value="${op}">${op}</option>`; });
opSelect.innerHTML = html;
if (html.includes(`value="${currentValue}"`)) opSelect.value = currentValue;
}
// ==========================================
// 🚀 LÓGICA INTELIGENTE DE ENRUTAMIENTO (ESTADOS)
// ==========================================
function getServiceStateInfo(s) {
const raw = s.raw_data || {};
const dbStat = raw.status_operativo;
// 1. Bolsa de Trabajo (Máxima prioridad visual)
if (!s.assigned_name && (s.automation_status === 'in_progress' || s.automation_status === 'failed')) {
return { id: 'bolsa', name: s.automation_status === 'in_progress' ? 'Buscando Operario' : 'Fallo en Bolsa', color: s.automation_status === 'in_progress' ? 'amber' : 'red', isBlocked: true, is_final: false };
}
// 2. Si viene limpio del scraper sin estado -> Pendiente de Asignar
if (!dbStat || dbStat === 'sin_asignar') {
const found = systemStatuses.find(st => st.name.toLowerCase().includes('pendiente de asignar')) || systemStatuses[0];
return { ...found, isBlocked: false };
}
// 3. Match directo por ID Numérico (El nuevo estándar)
const foundObj = systemStatuses.find(st => String(st.id) === String(dbStat));
if (foundObj) return { ...foundObj, isBlocked: false };
// 4. Fallbacks históricos de texto (Para que los servicios viejos no se rompan)
if (dbStat === 'asignado_operario') return { ...systemStatuses.find(st => st.name.toLowerCase() === 'asignado'), isBlocked: false };
if (dbStat === 'citado') return { ...systemStatuses.find(st => st.name.toLowerCase().includes('citado')), isBlocked: false };
if (dbStat === 'de_camino') return { ...systemStatuses.find(st => st.name.toLowerCase().includes('camino')), isBlocked: false };
if (dbStat === 'trabajando') return { ...systemStatuses.find(st => st.name.toLowerCase().includes('trabajando')), isBlocked: false };
if (dbStat === 'incidencia') return { ...systemStatuses.find(st => st.name.toLowerCase().includes('incidencia')), isBlocked: false };
if (dbStat === 'terminado') return { ...systemStatuses.find(st => st.name.toLowerCase().includes('terminado') || st.name.toLowerCase().includes('finalizado')), isBlocked: false };
// 5. Fallback final
return { id: 'unknown', name: 'Desconocido', color: 'gray', isBlocked: false, is_final: false };
}
function renderLists() {
if(systemStatuses.length === 0) return;
const searchTerm = document.getElementById('searchFilter').value.toLowerCase();
const selectedOp = document.getElementById('opFilter').value;
let kpiUnassigned = 0;
let kpiScheduled = 0;
let kpiActive = 0;
let kpiFinished = 0;
const filteredData = localData.filter(s => {
const raw = s.raw_data || {};
const name = (raw["Nombre Cliente"] || raw["CLIENTE"] || "").toLowerCase();
const addr = (raw["Dirección"] || raw["DOMICILIO"] || "").toLowerCase();
const pop = (raw["Población"] || raw["POBLACION-PROVINCIA"] || "").toLowerCase();
const phone = (raw["Teléfono"] || raw["TELEFONO"] || "").toLowerCase();
const comp = (raw["Compañía"] || raw["COMPAÑIA"] || raw["Procedencia"] || "").toLowerCase();
const ref = (s.service_ref || "").toLowerCase();
const assigned = s.assigned_name || "";
// Calculamos el estado real y lo inyectamos
const stateInfo = getServiceStateInfo(s);
s._stateInfo = stateInfo;
// Lógica de KPIs de suma agrupada
const stName = stateInfo.name.toLowerCase();
if (stateInfo.id === 'bolsa' || stName.includes('pendiente de asignar') || stName.includes('desasignado')) {
kpiUnassigned++;
} else if (stateInfo.is_final || stName.includes('terminado') || stName.includes('anulado') || stName.includes('finalizado')) {
kpiFinished++;
} else if (stName === 'asignado' || stName.includes('pendiente de cita') || stName.includes('citado')) {
kpiScheduled++;
} else {
kpiActive++; // De Camino, Trabajando, Incidencia y los personalizados
}
// Aplicar Filtros Visuales
const matchesSearch = searchTerm === "" || name.includes(searchTerm) || ref.includes(searchTerm) || addr.includes(searchTerm) || pop.includes(searchTerm) || phone.includes(searchTerm) || comp.includes(searchTerm);
const matchesOp = selectedOp === "ALL" || assigned === selectedOp;
let matchesStatus = false;
if (activeStatusFilter === "ALL") {
// Si no hay búsqueda activa, ocultamos los Finalizados por limpieza visual
if (stateInfo.is_final && searchTerm === "") matchesStatus = false;
else matchesStatus = true;
} else {
matchesStatus = String(stateInfo.id) === activeStatusFilter;
}
return matchesSearch && matchesOp && matchesStatus;
});
// Actualizamos Dashboards Superiores
document.getElementById('kpi-unassigned').innerText = kpiUnassigned;
document.getElementById('kpi-scheduled').innerText = kpiScheduled;
document.getElementById('kpi-active').innerText = kpiActive;
document.getElementById('kpi-finished').innerText = kpiFinished;
const grid = document.getElementById('servicesGrid');
grid.innerHTML = filteredData.length > 0
? filteredData.map(s => buildGridCard(s)).join('')
: `<div class="col-span-full py-20 text-center bg-white rounded-[2rem] border-2 border-dashed border-slate-200">
<i data-lucide="layout-grid" class="w-12 h-12 text-slate-300 mx-auto mb-3"></i>
<p class="text-slate-400 font-bold uppercase tracking-widest text-sm">No hay servicios que coincidan con los filtros</p>
</div>`;
lucide.createIcons();
}
function buildGridCard(s) {
const raw = s.raw_data || {};
const name = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
const addr = raw["Dirección"] || raw["DOMICILIO"] || "---";
const pop = raw["Población"] || raw["POBLACION-PROVINCIA"] || "";
const fullAddr = `${addr} ${pop}`.trim();
const cita = raw.scheduled_date ? `${raw.scheduled_date} | ${raw.scheduled_time}` : 'Pendiente Cita';
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || (s.provider === 'MANUAL' ? 'PARTICULAR' : 'ASEGURADORA');
const isUrgent = s.is_urgent === true || (raw['Urgente'] && raw['Urgente'].toLowerCase() === 'sí') || (raw['URGENTE'] && raw['URGENTE'].toLowerCase() === 'si');
const stateInfo = s._stateInfo;
const colorData = colorDict[stateInfo.color] || colorDict['gray'];
let iconEstado = 'tag';
if(raw.scheduled_date) iconEstado = 'calendar';
if(stateInfo.name.toLowerCase().includes('camino')) iconEstado = 'car';
if(stateInfo.name.toLowerCase().includes('reparaci') || stateInfo.name.toLowerCase().includes('trabaja')) iconEstado = 'wrench';
if(stateInfo.name.toLowerCase().includes('incidencia') || stateInfo.name.toLowerCase().includes('pausado')) iconEstado = 'alert-triangle';
const isBlocked = stateInfo.isBlocked;
const clickAction = isBlocked ? `shakeCard(this, '${s.automation_status}'); event.stopPropagation();` : `openDetail(${s.id})`;
const cursorStyle = isBlocked ? 'cursor-not-allowed' : 'cursor-pointer';
return `
<div class="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm card-hover text-left flex flex-col justify-between relative ${cursorStyle}" onclick="${clickAction}">
<div class="space-y-3">
<div class="flex items-start justify-between w-full gap-2">
<span class="text-[9px] font-black ${colorData.bg} ${colorData.text} px-2.5 py-1.5 rounded-lg uppercase tracking-wider flex items-center gap-1.5 truncate border ${colorData.border}">
${isBlocked ? `<span class="w-1.5 h-1.5 bg-current rounded-full pulse-slow opacity-70 shrink-0"></span>` : `<div class="w-2 h-2 rounded-full ${colorData.dot}"></div>`}
<span class="truncate">${stateInfo.name}</span>
</span>
${isUrgent ? `<span class="bg-red-500 text-white px-2 py-1 rounded-lg text-[9px] font-black uppercase shadow-sm animate-pulse shrink-0">🔥 URGENTE</span>` : `<span class="text-[10px] text-slate-400 font-bold uppercase bg-slate-50 border border-slate-100 px-2.5 py-1 rounded-lg shrink-0">#${s.service_ref}</span>`}
</div>
<div>
<p class="text-[9px] font-black text-blue-500 uppercase tracking-widest mb-0.5 truncate">${companyName}</p>
<h4 class="font-black text-slate-800 uppercase text-base leading-tight line-clamp-2" title="${name}">${name}</h4>
</div>
<div class="bg-slate-50/50 p-3 rounded-xl border border-slate-100">
<p class="text-[10px] text-slate-600 font-medium uppercase line-clamp-2 flex items-start gap-1.5" title="${fullAddr}">
<i data-lucide="map-pin" class="w-3.5 h-3.5 mt-0.5 text-slate-400 shrink-0"></i> ${fullAddr}
</p>
</div>
</div>
<div class="flex items-center justify-between mt-4 pt-4 border-t border-slate-100">
<div class="flex items-center gap-2 min-w-0">
<div class="bg-slate-100 p-1.5 rounded-lg text-slate-500 shrink-0"><i data-lucide="hard-hat" class="w-3.5 h-3.5"></i></div>
<span class="text-[10px] font-black text-slate-600 uppercase truncate" title="${s.assigned_name || 'Sin asignar'}">${s.assigned_name || 'Sin asignar'}</span>
</div>
${raw.scheduled_date && !isBlocked ? `
<div class="flex items-center gap-1.5 text-blue-600 shrink-0 ml-2 bg-blue-50 px-2 py-1 rounded-md border border-blue-100">
<i data-lucide="${iconEstado}" class="w-3.5 h-3.5"></i>
<span class="text-[9px] font-black uppercase">${cita}</span>
</div>` : ''}
</div>
</div>`;
}
// ==========================================
// FUNCIONES DE MODALES Y ACCIONES
// ==========================================
function shakeCard(element, status) {
element.classList.add('shake');
setTimeout(() => element.classList.remove('shake'), 400);
if (status === 'in_progress') { showToast("⏳ El robot está asignando este servicio por WhatsApp...", "warning"); }
else { showToast("📍 Este servicio está en la bolsa esperando a que un operario lo coja.", "warning"); }
}
function showToast(msg, type = 'success') {
const toast = document.getElementById('toastAppt');
const iconContainer = document.getElementById('toastIconContainer');
document.getElementById('toastMsg').innerText = msg;
if (type === 'warning') {
toast.classList.replace('bg-emerald-600', 'bg-amber-500');
iconContainer.innerHTML = '<i data-lucide="alert-circle" class="w-5 h-5"></i>';
} else {
toast.classList.replace('bg-amber-500', 'bg-emerald-600');
iconContainer.innerHTML = '<i data-lucide="check-circle" class="w-5 h-5"></i>';
}
lucide.createIcons();
toast.classList.remove('hidden');
setTimeout(() => { toast.classList.add('hidden'); }, 3500);
}
function openDetail(id) {
const s = localData.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;
document.getElementById('detCp').value = raw["Código Postal"] || "00000";
const companyName = raw['Compañía'] || raw['COMPAÑIA'] || raw['Procedencia'] || "Particular";
document.getElementById('detCompany').innerText = companyName;
document.getElementById('detName').innerText = raw["Nombre Cliente"] || raw["CLIENTE"] || "Asegurado Sin Nombre";
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('detPhone').innerText = singlePhone;
document.getElementById('detPhoneLink').href = `tel:+34${singlePhone}`;
document.getElementById('detPhoneLink').classList.remove('text-slate-400', 'pointer-events-none');
document.getElementById('detPhoneLink').classList.add('text-blue-600');
} else {
document.getElementById('detPhone').innerText = "Sin Teléfono";
document.getElementById('detPhoneLink').href = "#";
document.getElementById('detPhoneLink').classList.remove('text-blue-600');
document.getElementById('detPhoneLink').classList.add('text-slate-400', 'pointer-events-none');
}
document.getElementById('detAddrText').innerText = `${raw["Dirección"] || "Dirección no especificada"} ${raw["Población"] || ""}`;
document.getElementById('detDesc').innerHTML = (raw["Descripción"] || raw["DESCRIPCION"] || "Sin notas.").replace(/\n/g, '<br>');
const stateInfo = s._stateInfo;
// Mostrar u ocultar paneles de asignación dependiendo del estado
if (s.assigned_name && stateInfo.id !== 'bolsa' && !stateInfo.name.toLowerCase().includes('asignar') && !stateInfo.name.toLowerCase().includes('desasignado')) {
document.getElementById('panelAsignado').classList.remove('hidden');
document.getElementById('panelSinAsignar').classList.add('hidden');
document.getElementById('detWorker').innerText = s.assigned_name;
document.getElementById('dateInput').value = raw.scheduled_date || "";
document.getElementById('timeInput').value = raw.scheduled_time || "";
document.getElementById('detStatusMap').value = stateInfo.id;
} else {
document.getElementById('panelAsignado').classList.add('hidden');
document.getElementById('panelSinAsignar').classList.remove('hidden');
const rawGuildId = s.guild_id || raw['guild_id'] || raw.guild_id;
if(rawGuildId) {
document.getElementById('reGremio').value = String(rawGuildId);
loadOps(rawGuildId, 'reOperario');
} else {
document.getElementById('reGremio').value = "";
document.getElementById('reOperario').innerHTML = '<option value="">-- Elija gremio primero --</option>';
}
}
document.getElementById('detailModal').classList.remove('hidden');
lucide.createIcons();
}
async function saveAppointment() {
const id = document.getElementById('detId').value;
const date = document.getElementById('dateInput').value;
const time = document.getElementById('timeInput').value;
const statusMap = document.getElementById('detStatusMap').value;
const selectedSt = systemStatuses.find(st => String(st.id) === String(statusMap));
// Avisar si guarda sin fecha en un estado que debería tenerla
if (selectedSt && !selectedSt.is_final && !date && !selectedSt.name.toLowerCase().includes('pausa') && !selectedSt.name.toLowerCase().includes('asignar')) {
if(!confirm("No has asignado Fecha para este estado. ¿Deseas continuar?")) return;
}
const btn = document.getElementById('btnSaveAppt');
const originalContent = btn.innerHTML;
btn.innerHTML = `<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...`;
btn.disabled = true;
try {
await fetch(`${API_URL}/services/set-appointment/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ date, time, status_operativo: statusMap })
});
closeDetailModal(); showToast("Estado actualizado"); refreshPanel();
} catch (e) { alert("Error"); }
finally { btn.innerHTML = originalContent; btn.disabled = false; }
}
async function sendToAutomate() {
const id = document.getElementById('detId').value;
const guild_id = document.getElementById('reGremio').value;
const cp = document.getElementById('detCp').value;
if(!guild_id) return alert("Selecciona un gremio primero.");
const btn = document.getElementById('btnAuto');
btn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin mx-auto"></i>';
const savedSetting = localStorage.getItem('wa_delay_enabled');
const useDelay = savedSetting === null ? true : savedSetting === 'true';
try {
const res = await fetch(`${API_URL}/providers/automate/${id}`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ guild_id, cp, useDelay })
});
const data = await res.json();
if(data.ok) { closeDetailModal(); showToast("Enviado a la rueda de WhatsApp"); refreshPanel(); }
else { alert(data.error || "No hay operarios en esa zona para ese gremio"); btn.innerHTML = '<div><p class="font-black uppercase text-xs">Mandar a la Cola</p><p class="text-[9px] text-blue-200">Rueda automática (WA)</p></div><i data-lucide="zap" class="w-5 h-5"></i>'; lucide.createIcons(); }
} catch (e) { alert("Error"); }
}
async function assignManualFromPanel() {
const id = document.getElementById('detId').value;
const guild_id = document.getElementById('reGremio').value;
const assigned_to = document.getElementById('reOperario').value;
if(!guild_id || !assigned_to) return alert("Selecciona gremio y operario.");
try {
const select = document.getElementById('reOperario');
const name = select.options[select.selectedIndex].text;
const estadoAsignado = systemStatuses.find(st => st.name.toLowerCase() === 'asignado') || systemStatuses[1];
await fetch(`${API_URL}/providers/scraped/${id}`, {
method: 'PUT',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({
automation_status: 'completed',
assigned_to: assigned_to,
assigned_name: name,
guild_id: guild_id,
status_operativo: estadoAsignado ? String(estadoAsignado.id) : 'asignado_operario'
})
});
closeDetailModal(); showToast("Asignado correctamente"); refreshPanel();
} catch (e) { alert("Error"); }
}
async function saveNewService(e) {
e.preventDefault();
const action = e.submitter.value;
const data = {
phone: document.getElementById('nPhone').value, name: document.getElementById('nName').value,
address: document.getElementById('nAddr').value, description: document.getElementById('nDesc').value,
guild_id: document.getElementById('nGuild').value, assigned_to: document.getElementById('nWorker').value || null
};
try {
const res = await fetch(`${API_URL}/services/manual-high`, {
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ ...data, mode: action })
});
if (res.ok) { closeCreateModal(); refreshPanel(); }
} catch(e) { alert("Error al guardar"); }
}
function closeDetailModal() { document.getElementById('detailModal').classList.add('hidden'); }
function openCreateModal() { document.getElementById('createModal').classList.remove('hidden'); }
function closeCreateModal() { document.getElementById('createModal').classList.add('hidden'); }
async function loadGuilds() {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
const opts = '<option value="">Seleccionar Gremio...</option>' + data.guilds.map(g => `<option value="${g.id}">${g.name}</option>`).join('');
document.getElementById('nGuild').innerHTML = opts;
document.getElementById('reGremio').innerHTML = opts;
}
}
async function loadOps(gid, targetSelectId) {
const sel = document.getElementById(targetSelectId);
if(!gid) { sel.innerHTML = '<option value="">-- Primero elija gremio --</option>'; return; }
const res = await fetch(`${API_URL}/operators?guild_id=${gid}`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) sel.innerHTML = '<option value="">Seleccionar operario...</option>' + data.operators.map(o => `<option value="${o.id}">${o.full_name}</option>`).join('');
}
async function copyClientPortalLink() {
const phone = document.getElementById('detPhone').innerText;
const name = document.getElementById('detName').innerText;
const addr = document.getElementById('detAddrText').innerText;
if (!phone || phone === "Sin Teléfono") {
showToast("No hay un teléfono válido para este cliente.", "warning");
return;
}
const btn = document.getElementById('btnPortalLink');
const originalHtml = btn.innerHTML;
btn.innerHTML = '<i data-lucide="loader-2" class="w-3 h-3 animate-spin"></i> Generando...';
lucide.createIcons();
try {
const res = await fetch(`${API_URL}/clients/ensure`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("token")}`
},
body: JSON.stringify({ phone: phone, name: name, address: addr })
});
const data = await res.json();
if (data.ok && data.client && data.client.portal_token) {
const portalLink = `https://portal.integrarepara.es/?token=${data.client.portal_token}`;
await navigator.clipboard.writeText(portalLink);
btn.innerHTML = '<i data-lucide="check-circle" class="w-3 h-3"></i> ¡Copiado!';
btn.classList.replace('text-blue-600', 'text-emerald-600');
btn.classList.replace('bg-blue-50', 'bg-emerald-50');
btn.classList.replace('border-blue-100', 'border-emerald-200');
showToast("Enlace copiado. ¡Listo para pegar en WhatsApp!");
setTimeout(() => {
btn.innerHTML = originalHtml;
btn.className = "text-[10px] font-black bg-blue-50 border border-blue-100 hover:bg-blue-600 hover:text-white text-blue-600 px-3 py-1.5 rounded-lg flex items-center gap-1.5 transition-all shadow-sm active:scale-95";
lucide.createIcons();
}, 3000);
} else {
showToast("No se pudo generar el token. Revisa la consola.", "warning");
btn.innerHTML = originalHtml;
lucide.createIcons();
}
} catch (error) {
console.error("Error obteniendo token:", error);
showToast("Error al conectar con el servidor", "warning");
btn.innerHTML = originalHtml;
lucide.createIcons();
}
}
</script>
</body>
</html>