Actualizar panel.html

This commit is contained in:
2026-04-04 17:16:13 +00:00
parent 09a2a88679
commit 2ae80234d0

View File

@@ -3,18 +3,30 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panel - IntegraRepara</title>
<title>Panel Inteligente - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
.fade-in { animation: fadeIn 0.5s ease-in-out; }
:root { --app-bg: #f8fafc; }
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
/* Animaciones fluidas */
.fade-in { animation: fadeIn 0.5s ease-in-out forwards; }
.fade-in-delay-1 { animation-delay: 0.1s; opacity: 0; }
.fade-in-delay-2 { animation-delay: 0.2s; opacity: 0; }
@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; }
.stat-card { transition: all 0.2s; border: 1px solid #f1f5f9; }
.stat-card:hover { transform: translateY(-3px); box-shadow: 0 10px 25px -5px rgba(0,0,0,0.05); }
/* Efecto latido para el semáforo rojo/ia */
.animate-pulse-fast { animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased text-left">
<body class="bg-slate-50 text-slate-800 font-sans antialiased text-left">
<div class="flex h-screen overflow-hidden">
@@ -24,23 +36,46 @@
<div id="header-container"></div>
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-8">
<div class="fade-in max-w-[1400px] mx-auto space-y-8 text-left">
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-slate-50 p-8">
<div class="fade-in max-w-[1600px] mx-auto space-y-8 text-left">
<div class="flex justify-between items-end border-b border-gray-200 pb-6">
<div class="flex justify-between items-end border-b border-slate-200 pb-6">
<div>
<h2 class="text-3xl font-black text-slate-800 tracking-tight flex items-center gap-3">
<span class="bg-blue-600 p-2.5 rounded-2xl text-white shadow-lg shadow-blue-200"><i data-lucide="layout-dashboard" class="w-6 h-6"></i></span>
DASHBOARD
<span class="bg-blue-600 p-2.5 rounded-2xl text-white shadow-lg shadow-blue-200"><i data-lucide="cpu" class="w-6 h-6"></i></span>
DASHBOARD INTELIGENTE
</h2>
<p class="text-sm text-slate-500 mt-2 font-medium">Resumen del estado de todos los expedientes y métricas de hoy.</p>
<p class="text-sm text-slate-500 mt-2 font-medium">Control de salud de expedientes y Supervisor IA en tiempo real.</p>
</div>
<div class="text-right hidden md:block">
<p class="text-xs font-bold text-blue-600 uppercase tracking-widest bg-blue-50 px-4 py-2 rounded-xl" id="todayDate">Cargando fecha...</p>
<p class="text-xs font-bold text-blue-600 uppercase tracking-widest bg-blue-50 px-4 py-2 rounded-xl border border-blue-100" id="todayDate">Cargando fecha...</p>
</div>
</div>
<div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-5 text-left">
<div class="bg-slate-900 rounded-[2.5rem] shadow-xl p-8 border border-slate-800 relative overflow-hidden fade-in-delay-1">
<div class="absolute top-0 right-0 w-64 h-64 bg-blue-500 rounded-full mix-blend-multiply filter blur-[80px] opacity-20 animate-pulse-fast"></div>
<div class="absolute bottom-0 left-0 w-64 h-64 bg-purple-500 rounded-full mix-blend-multiply filter blur-[80px] opacity-20"></div>
<div class="relative z-10 flex flex-col md:flex-row gap-8 items-start">
<div class="shrink-0 md:w-64">
<div class="flex items-center gap-3 mb-2">
<div class="bg-white/10 p-2 rounded-xl text-blue-400 backdrop-blur-sm border border-white/10"><i data-lucide="bot" class="w-6 h-6"></i></div>
<h3 class="font-black text-xl text-white tracking-tight">Supervisor IA</h3>
</div>
<p class="text-slate-400 text-xs font-medium leading-relaxed">Analizando rutas, tiempos, solapes y salud de los expedientes en tiempo real...</p>
</div>
<div class="flex-1 w-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="aiAlertsContainer">
<div class="bg-white/5 border border-white/10 rounded-2xl p-4 animate-pulse">
<div class="h-4 bg-white/20 rounded w-1/2 mb-3"></div>
<div class="h-3 bg-white/10 rounded w-full mb-2"></div>
<div class="h-3 bg-white/10 rounded w-3/4"></div>
</div>
</div>
</div>
</div>
<div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-5 text-left fade-in-delay-2">
<div class="stat-card bg-white p-5 rounded-[2rem] shadow-sm flex flex-col justify-between">
<div class="flex justify-between items-start mb-4">
@@ -98,11 +133,11 @@
</div>
<div class="grid grid-cols-1 xl:grid-cols-3 gap-8">
<div class="grid grid-cols-1 xl:grid-cols-3 gap-8 pb-10">
<div class="xl:col-span-2 space-y-8">
<div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 p-8 text-left">
<div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 p-8 text-left relative">
<div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-50">
<div class="bg-blue-50 p-2 rounded-xl text-blue-600"><i data-lucide="calendar" class="w-5 h-5"></i></div>
<h3 class="font-black text-lg text-slate-800 uppercase tracking-tight">Agenda de Visitas para Hoy</h3>
@@ -138,13 +173,13 @@
</div>
</div>
<div class="bg-slate-800 rounded-[2.5rem] shadow-lg p-6 text-left text-white border border-slate-700">
<div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-700">
<div class="bg-slate-700 p-2 rounded-xl text-emerald-400"><i data-lucide="activity" class="w-5 h-5"></i></div>
<h3 class="font-black text-sm text-white uppercase tracking-tight">Últimas 5 Entradas</h3>
<div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 p-6 text-left">
<div class="flex items-center gap-3 mb-6 pb-4 border-b border-slate-50">
<div class="bg-emerald-50 p-2 rounded-xl text-emerald-600"><i data-lucide="heart-pulse" class="w-5 h-5"></i></div>
<h3 class="font-black text-sm text-slate-800 uppercase tracking-tight">Salud Global</h3>
</div>
<div id="latestActivity" class="space-y-4">
<p class="text-slate-400 text-xs font-medium animate-pulse">Cargando actividad...</p>
<div class="flex flex-col gap-3" id="healthSummary">
<p class="text-slate-400 text-xs font-medium animate-pulse">Analizando...</p>
</div>
</div>
@@ -156,14 +191,18 @@
</div>
</div>
<script src="js/layout.js"></script>
<script>
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
? 'http://localhost:3000'
: 'https://integrarepara-api.integrarepara.es';
document.addEventListener("DOMContentLoaded", () => {
const token = localStorage.getItem("token");
if(!token) window.location.href = "index.html";
if(!token) {
// Para pruebas sin login, comentar la siguiente linea:
window.location.href = "index.html";
}
// Pintar la fecha de hoy bonita
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById('todayDate').innerText = new Date().toLocaleDateString('es-ES', options);
@@ -173,11 +212,9 @@
async function loadDashboardData(token) {
try {
// 1. Pedimos los expedientes vírgenes (Bandeja / Bolsa)
const resScraped = await fetch(`${API_URL}/providers/scraped`, { headers: { "Authorization": `Bearer ${token}` } });
const dataScraped = await resScraped.json();
// 2. Pedimos los expedientes en curso (Panel Operativo)
const resActive = await fetch(`${API_URL}/services/active`, { headers: { "Authorization": `Bearer ${token}` } });
const dataActive = await resActive.json();
@@ -190,58 +227,165 @@
}
}
// --- SISTEMA DE SALUD DEL SERVICIO ---
function calculateHealth(s) {
const raw = s.raw_data || {};
const status = raw.status_operativo || '';
const desc = (s.description || '').toLowerCase();
let score = 'green';
let reason = 'Todo en orden';
// 1. ROJO: Problemas graves (Incidencia abierta, Reclamación, cita vencida grave)
if (status === 'incidencia' || desc.includes('reclamacion') || desc.includes('enfadado') || desc.includes('queja')) {
return { color: 'red', hex: 'bg-red-500', shadow: 'shadow-red-500/40', text: 'text-red-600', reason: 'Incidencia o queja activa' };
}
// 2. AMBAR: Riesgos (Lleva días sin tocarse, o cita para hoy y es tarde)
if (s.created_at) {
const daysIdle = (new Date() - new Date(s.created_at)) / (1000 * 3600 * 24);
if (daysIdle > 5 && !['finalizado', 'terminado', 'anulado'].includes(status)) {
return { color: 'amber', hex: 'bg-amber-500', shadow: 'shadow-amber-500/40', text: 'text-amber-600', reason: `Inactivo > 5 días` };
}
}
if (raw.scheduled_date === new Date().toISOString().split('T')[0] && raw.scheduled_time) {
const [h, m] = raw.scheduled_time.split(':');
const sched = new Date();
sched.setHours(h, m, 0);
// Si ha pasado 1h de la cita y no está terminado
if (new Date() > new Date(sched.getTime() + 60*60*1000) && status !== 'terminado') {
return { color: 'amber', hex: 'bg-amber-500', shadow: 'shadow-amber-500/40', text: 'text-amber-600', reason: 'Retraso en cita hoy' };
}
}
// 3. VERDE: Normal
return { color: 'green', hex: 'bg-emerald-500', shadow: 'shadow-emerald-500/40', text: 'text-emerald-600', reason: 'En tiempo' };
}
// --- SUPERVISOR IA ---
function runAISupervisor(allServices, todayVisits, urgentVisits) {
const container = document.getElementById('aiAlertsContainer');
let alerts = [];
// 1. Solapes de operarios hoy
const operariosHoy = {};
todayVisits.forEach(v => {
const op = v.assigned_name || 'Sin asignar';
if(op === 'Sin asignar' || !v.raw_data.scheduled_time) return;
if(!operariosHoy[op]) operariosHoy[op] = [];
operariosHoy[op].push(v);
});
let overlaps = 0;
for(const [op, visits] of Object.entries(operariosHoy)) {
if(visits.length < 2) continue;
// Simple comprobacion: si tienen la misma hora
const times = visits.map(v => v.raw_data.scheduled_time.substring(0,2)); // Solo horas
const duplicates = times.filter((item, index) => times.indexOf(item) != index);
if (duplicates.length > 0) overlaps++;
}
if (overlaps > 0) {
alerts.push({
icon: 'calendar-off', color: 'text-rose-400', bg: 'bg-rose-400/10', border: 'border-rose-400/20',
title: 'Riesgo de Solape', desc: `Se han detectado ${overlaps} posibles solapes en la agenda de los operarios hoy.`
});
}
// 2. Retrasos probables
let retrasos = 0;
const now = new Date();
todayVisits.forEach(v => {
if(v.raw_data.scheduled_time && v.raw_data.status_operativo !== 'terminado') {
const [h, m] = v.raw_data.scheduled_time.split(':');
const sched = new Date(); sched.setHours(h, m, 0);
if (now > new Date(sched.getTime() + 30*60000)) retrasos++; // Más de 30 min tarde
}
});
if (retrasos > 0) {
alerts.push({
icon: 'clock-4', color: 'text-amber-400', bg: 'bg-amber-400/10', border: 'border-amber-400/20',
title: 'Retrasos en ruta', desc: `Hay ${retrasos} cita(s) con un retraso probable superior a 30 minutos.`
});
}
// 3. Optimización de urgencias (Misma población)
let matchUrgencias = false;
let matchText = "";
const popsHoy = [...new Set(todayVisits.map(v => v.raw_data['Población']))].filter(Boolean);
for(let u of urgentVisits) {
if (!u.assigned_name && popsHoy.includes(u.raw_data['Población'])) {
matchUrgencias = true;
matchText = `Hay técnicos en ${u.raw_data['Población']} que podrían cubrir una urgencia sin asignar.`;
break;
}
}
if(matchUrgencias) {
alerts.push({
icon: 'map', color: 'text-emerald-400', bg: 'bg-emerald-400/10', border: 'border-emerald-400/20',
title: 'Optimización de Ruta', desc: matchText
});
}
// 4. Expedientes paralizados (Riesgo Incidencia)
let paralizados = allServices.filter(s => calculateHealth(s).reason.includes('> 5 días')).length;
if(paralizados > 0) {
alerts.push({
icon: 'alert-circle', color: 'text-orange-400', bg: 'bg-orange-400/10', border: 'border-orange-400/20',
title: 'Riesgo de queja', desc: `${paralizados} expediente(s) llevan más de 5 días sin movimientos.`
});
}
// Fallback si la IA no encuentra nada
if(alerts.length === 0) {
alerts.push({
icon: 'check-circle-2', color: 'text-blue-400', bg: 'bg-blue-400/10', border: 'border-blue-400/20',
title: 'Rutas Optimizadas', desc: 'No detecto anomalías. La planificación de hoy es eficiente.'
});
}
// Renderizar Alertas
container.innerHTML = alerts.slice(0,3).map(a => `
<div class="${a.bg} border ${a.border} rounded-2xl p-4 transition-all hover:scale-[1.02]">
<div class="flex items-center gap-2 mb-2">
<i data-lucide="${a.icon}" class="w-4 h-4 ${a.color}"></i>
<h4 class="font-black text-sm text-white">${a.title}</h4>
</div>
<p class="text-slate-300 text-xs leading-relaxed">${a.desc}</p>
</div>
`).join('');
lucide.createIcons();
}
// --- PROCESAMIENTO PRINCIPAL ---
function processDashboard(scrapedList, activeList) {
const todayStr = new Date().toISOString().split('T')[0];
// 1. FUSIÓN INTELIGENTE SIN DUPLICADOS (Usamos un Map basado en el ID)
const allServicesMap = new Map();
// Primero cargamos los servicios que vienen de la bandeja
scrapedList.forEach(s => {
if (s.status !== 'archived') {
allServicesMap.set(s.id, s);
}
});
// Luego sobrescribimos/agregamos con los de activos (que traen info más actualizada sobre el operario)
scrapedList.forEach(s => { if (s.status !== 'archived') allServicesMap.set(s.id, s); });
activeList.forEach(s => {
if (s.status !== 'archived') {
if (allServicesMap.has(s.id)) {
// Si ya existe, combinamos para no perder datos
allServicesMap.set(s.id, { ...allServicesMap.get(s.id), ...s });
} else {
allServicesMap.set(s.id, s);
}
if (allServicesMap.has(s.id)) allServicesMap.set(s.id, { ...allServicesMap.get(s.id), ...s });
else allServicesMap.set(s.id, s);
}
});
// Convertimos el mapa final en una lista pura y sin duplicados
const allServices = Array.from(allServicesMap.values());
// --- CÁLCULO DE KPIs CORRECTO ---
// 1. Total (Sin duplicados)
// Cálculos KPIs
const totalActive = allServices.length;
// 2. Sin Asignar (Nadie asignado y no está buscando en la rueda)
const unassignedCount = allServices.filter(s => !s.assigned_name && s.automation_status !== 'in_progress').length;
// 3. En Rueda (Nadie asignado pero SÍ está en la rueda)
const queueCount = allServices.filter(s => !s.assigned_name && s.automation_status === 'in_progress').length;
// 4. Asignados sin cita (Tienen operario asignado pero no hay fecha)
const pendingCount = allServices.filter(s => s.assigned_name && (!s.raw_data.scheduled_date || s.raw_data.scheduled_date === "")).length;
// 5. Citas de hoy (La fecha es hoy)
const todayVisits = allServices.filter(s => s.raw_data && s.raw_data.scheduled_date === todayStr);
// 6. Urgencias (Cualquiera marcado como urgente)
const urgentVisits = allServices.filter(s => {
const raw = s.raw_data || {};
return raw['Urgente'] === 'Sí' || raw['Urgente'] === 'true' || raw['URGENTE'] === 'SI';
});
// Pintar los números
// Animaciones
animateValue("kpiTotal", totalActive);
animateValue("kpiUnassigned", unassignedCount);
animateValue("kpiQueue", queueCount);
@@ -249,14 +393,32 @@
animateValue("kpiToday", todayVisits.length);
animateValue("kpiUrgent", urgentVisits.length);
// --- RENDERIZAR WIDGETS ---
// Resumen de Salud Global
let healthStats = { green: 0, amber: 0, red: 0 };
allServices.forEach(s => healthStats[calculateHealth(s).color]++);
document.getElementById('healthSummary').innerHTML = `
<div class="flex justify-between items-center bg-slate-50 p-2.5 rounded-xl border border-slate-100">
<span class="flex items-center gap-2 text-xs font-bold text-slate-600"><div class="w-3 h-3 rounded-full bg-emerald-500 shadow-sm"></div> Normales</span>
<span class="font-black text-emerald-600">${healthStats.green}</span>
</div>
<div class="flex justify-between items-center bg-slate-50 p-2.5 rounded-xl border border-slate-100">
<span class="flex items-center gap-2 text-xs font-bold text-slate-600"><div class="w-3 h-3 rounded-full bg-amber-500 shadow-sm"></div> En Riesgo</span>
<span class="font-black text-amber-600">${healthStats.amber}</span>
</div>
<div class="flex justify-between items-center bg-slate-50 p-2.5 rounded-xl border border-slate-100">
<span class="flex items-center gap-2 text-xs font-bold text-slate-600"><div class="w-3 h-3 rounded-full bg-red-500 shadow-sm animate-pulse"></div> Problemas</span>
<span class="font-black text-red-600">${healthStats.red}</span>
</div>
`;
// Ejecutar Supervisor y Renders
runAISupervisor(allServices, todayVisits, urgentVisits);
renderTodaySchedule(todayVisits);
renderUrgentSchedule(urgentVisits);
renderCompanyDistribution(allServices);
renderLatestActivity(allServices);
}
// WIDGET 1: Agenda Hoy
function renderTodaySchedule(visits) {
const container = document.getElementById("todaySchedule");
if (visits.length === 0) {
@@ -277,28 +439,36 @@
const name = raw['Nombre Cliente'] || raw['CLIENTE'] || "Asegurado";
const pop = raw['Población'] || raw['POBLACION-PROVINCIA'] || "Dirección no especificada";
let statusColor = "bg-blue-50 text-blue-600";
if(raw.status_operativo === 'trabajando') statusColor = "bg-amber-50 text-amber-600";
if(raw.status_operativo === 'incidencia') statusColor = "bg-red-50 text-red-600";
if(raw.status_operativo === 'terminado') statusColor = "bg-emerald-50 text-emerald-600";
// Semáforo de salud
const health = calculateHealth(s);
return `
<div class="flex items-center justify-between p-4 rounded-2xl bg-slate-50 border border-slate-100 hover:border-blue-200 transition-all group">
<div class="flex items-center gap-4 flex-1 min-w-0">
<div class="w-16 h-12 rounded-xl ${statusColor} flex items-center justify-center shrink-0 font-black text-lg tracking-tighter shadow-inner">${time}</div>
<div class="flex items-center justify-between p-4 rounded-2xl bg-white border border-slate-100 shadow-sm hover:shadow-md transition-all group relative overflow-hidden">
<div class="absolute left-0 top-0 bottom-0 w-1.5 ${health.hex}"></div>
<div class="flex items-center gap-4 flex-1 min-w-0 pl-2">
<div class="w-14 h-14 rounded-[1rem] bg-slate-50 border border-slate-100 flex flex-col items-center justify-center shrink-0">
<span class="font-black text-slate-800 text-sm leading-none">${time}</span>
<span class="text-[8px] font-bold text-slate-400 mt-1 uppercase">Hoy</span>
</div>
<div class="min-w-0 flex-1 text-left">
<div class="flex items-center gap-2">
<div class="flex items-center gap-2 mb-0.5">
<h4 class="font-black text-slate-800 uppercase text-sm truncate">${name}</h4>
<span class="text-[8px] bg-white border border-slate-200 text-slate-400 px-2 py-0.5 rounded-full font-black">#${s.service_ref}</span>
<span class="w-2 h-2 rounded-full ${health.hex} shadow-lg ${health.shadow} ${health.color==='red'?'animate-pulse':''}" title="${health.reason}"></span>
</div>
<p class="text-[10px] font-bold text-slate-400 uppercase truncate mt-0.5"><i data-lucide="map-pin" class="w-3 h-3 inline mr-1"></i>${pop}</p>
<p class="text-[10px] font-bold text-slate-400 uppercase truncate mb-1">
<i data-lucide="map-pin" class="w-3 h-3 inline mr-0.5"></i>${pop}
<span class="mx-1 text-slate-200">|</span>
<span class="${health.text}">${health.reason}</span>
</p>
<span class="text-[9px] bg-slate-100 border border-slate-200 text-slate-500 px-2 py-0.5 rounded-md font-black">#${s.service_ref}</span>
</div>
</div>
<div class="flex flex-col items-end shrink-0 pl-4 border-l border-slate-200 ml-4 hidden md:flex">
<div class="flex flex-col items-end shrink-0 pl-4 ml-4 hidden md:flex">
<span class="text-[9px] font-black uppercase text-slate-400 tracking-widest mb-1">Operario</span>
<div class="flex items-center gap-1.5 bg-white px-3 py-1.5 rounded-lg border border-slate-100 shadow-sm">
<i data-lucide="hard-hat" class="w-3.5 h-3.5 text-slate-500"></i>
<span class="text-[10px] font-black text-slate-700 uppercase">${op}</span>
<div class="flex items-center gap-1.5 bg-blue-50/50 px-3 py-1.5 rounded-lg border border-blue-100">
<i data-lucide="hard-hat" class="w-3.5 h-3.5 text-blue-500"></i>
<span class="text-[10px] font-black text-blue-700 uppercase">${op}</span>
</div>
</div>
</div>`;
@@ -306,7 +476,6 @@
lucide.createIcons();
}
// WIDGET 2: Urgencias
function renderUrgentSchedule(visits) {
const container = document.getElementById("urgentSchedule");
if (visits.length === 0) {
@@ -322,19 +491,30 @@
const raw = s.raw_data;
const name = raw['Nombre Cliente'] || raw['CLIENTE'] || "Asegurado";
const op = s.assigned_name || raw.assigned_to_name || "Buscando Operario...";
const pop = raw['Población'] || raw['POBLACION-PROVINCIA'] || "";
const health = calculateHealth(s);
return `
<div class="p-4 rounded-2xl bg-red-50/50 border border-red-100 flex justify-between items-center">
<div>
<h4 class="font-black text-slate-800 uppercase text-xs truncate">${name}</h4>
<p class="text-[10px] font-bold text-red-500 uppercase mt-1"><i data-lucide="info" class="w-3 h-3 inline mr-1"></i>REF: #${s.service_ref}</p>
<div class="p-4 rounded-2xl bg-white border border-red-100 shadow-sm flex flex-col md:flex-row md:justify-between md:items-center gap-3 relative overflow-hidden">
<div class="absolute left-0 top-0 bottom-0 w-1.5 bg-red-500"></div>
<div class="pl-2">
<div class="flex items-center gap-2">
<h4 class="font-black text-slate-800 uppercase text-xs truncate">${name}</h4>
${health.color === 'red' ? '<i data-lucide="alert-triangle" class="w-3 h-3 text-red-500 animate-pulse"></i>' : ''}
</div>
<p class="text-[10px] font-bold text-slate-500 uppercase mt-1">
<i data-lucide="map-pin" class="w-3 h-3 inline mr-1 text-red-400"></i>${pop}
</p>
</div>
<div class="flex items-center justify-between md:justify-end gap-3 pl-2 md:pl-0">
<span class="text-[10px] font-black text-slate-400">#${s.service_ref}</span>
<span class="text-[9px] font-black uppercase bg-red-50 text-red-600 px-2 py-1 rounded-md border border-red-100">${op}</span>
</div>
<span class="text-[9px] font-black uppercase bg-white text-slate-600 px-2 py-1 rounded-md border border-slate-200 shadow-sm">${op}</span>
</div>`;
}).join('');
lucide.createIcons();
}
// WIDGET 3: Distribución Compañías
function renderCompanyDistribution(allServices) {
const container = document.getElementById("companyDistribution");
if (allServices.length === 0) { container.innerHTML = "<p class='text-xs text-slate-400'>Sin datos</p>"; return; }
@@ -353,45 +533,21 @@
container.innerHTML = sorted.map(([comp, count]) => {
const percent = Math.round((count / max) * 100);
return `
<div class="space-y-1">
<div class="flex justify-between text-xs font-black uppercase">
<span class="text-slate-600">${comp}</span>
<span class="text-indigo-600">${count} expedientes</span>
<div class="space-y-1.5">
<div class="flex justify-between text-[10px] font-black uppercase tracking-wide">
<span class="text-slate-600 truncate pr-2">${comp}</span>
<span class="text-indigo-600 shrink-0">${count} exp.</span>
</div>
<div class="w-full bg-slate-100 rounded-full h-2">
<div class="bg-indigo-500 h-2 rounded-full" style="width: ${percent}%"></div>
<div class="w-full bg-slate-100 rounded-full h-1.5">
<div class="bg-indigo-500 h-1.5 rounded-full" style="width: ${percent}%"></div>
</div>
</div>`;
}).join('');
}
// WIDGET 4: Última Actividad
function renderLatestActivity(allServices) {
const container = document.getElementById("latestActivity");
// Ordenar por fecha de creación descendente (el ID suele ser correlativo)
const latest = allServices.sort((a, b) => b.id - a.id).slice(0, 5);
if (latest.length === 0) { container.innerHTML = "<p class='text-xs text-slate-400'>Sin actividad reciente</p>"; return; }
container.innerHTML = latest.map(s => {
const name = s.raw_data['Nombre Cliente'] || s.raw_data['CLIENTE'] || "Nuevo Cliente";
const isNew = !s.assigned_name && s.automation_status !== 'in_progress';
const icon = isNew ? '<i data-lucide="download-cloud" class="w-3.5 h-3.5 text-blue-400"></i>' : '<i data-lucide="check" class="w-3.5 h-3.5 text-emerald-400"></i>';
return `
<div class="flex gap-3 items-start border-b border-slate-700/50 pb-3 last:border-0 last:pb-0">
<div class="mt-0.5">${icon}</div>
<div class="min-w-0 flex-1">
<p class="text-[10px] text-slate-400 uppercase tracking-widest mb-0.5">REF: #${s.service_ref}</p>
<p class="text-xs font-bold text-slate-200 truncate">${name}</p>
</div>
</div>`;
}).join('');
lucide.createIcons();
}
// Animación de contador de KPIs
function animateValue(id, end) {
const obj = document.getElementById(id);
if(!obj) return;
let start = 0;
const duration = 800;
const range = end - start;