Procházet zdrojové kódy

fix: correct template formatting and structure

Yoelvis Mariné Ramos před 1 rokem
rodič
revize
8fa3e49077

+ 31 - 9
app.py

@@ -1,4 +1,5 @@
 import os
+from datetime import datetime
 
 from dotenv import load_dotenv
 from flask import Flask
@@ -10,15 +11,13 @@ from config import Config, logger
 from database.database import migrate_database
 from parsers.log import process_logs
 from routes import register_routes
-
-# from routes.main_routes import initialize_proxy_detection
 from routes.stats_routes import realtime_data_thread
 from services.metrics_service import MetricsService
 from services.notifications import (
     has_remote_commits_with_messages,
     set_commit_notifications,
-    set_socketio_instance,  # Nueva importación
-    start_notification_monitor,  # Nueva importación
+    set_socketio_instance,
+    start_notification_monitor,
 )
 from utils.filters import register_filters
 
@@ -50,11 +49,34 @@ def create_app():
     # Register custom filters
     register_filters(app)
 
+    # Register the date format filter for notifications
+    @app.template_filter('datetime_format')
+    def datetime_format(value, format='%d/%m/%Y %H:%M'):
+        """Filtro para formatear fechas en las plantillas"""
+        if isinstance(value, str):
+            try:
+                # Handle ISO format
+                if 'T' in value:
+                    value = datetime.fromisoformat(value.replace('Z', '+00:00'))
+                else:
+                    # Try other common formats
+                    for fmt in ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f']:
+                        try:
+                            value = datetime.strptime(value, fmt)
+                            break
+                        except ValueError:
+                            continue
+                    else:
+                        return value  # Could not parse, returning original
+            except Exception:
+                return value
+        if isinstance(value, datetime):
+            return value.strftime(format)
+        return value
+
     # Register all route blueprints
     register_routes(app)
 
-    # Initialize proxy detection
-    #    initialize_proxy_detection()
 
     # Configure response headers
     @app.after_request
@@ -109,10 +131,10 @@ def main():
     # Initialize SocketIO
     socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
 
-    # Configurar Socket.IO en el módulo de notificaciones
+    # Set up Socket.IO in the notifications module
     set_socketio_instance(socketio)
 
-    # Iniciar el monitor de notificaciones
+    # Start the notification monitor
     start_notification_monitor()
 
     # Start real-time data collection thread
@@ -124,7 +146,7 @@ def main():
         f"Starting SquidStats application in {'debug' if debug_mode else 'production'} mode"
     )
 
-    # Leer host/port desde variables de entorno si existen (compatibilidad con FLASK_HOST/PORT)
+    # Read host/port from environment variables if they exist (compatible with FLASK_HOST/PORT)
     host = os.getenv("LISTEN_HOST") or os.getenv("FLASK_HOST") or "0.0.0.0"
     port_str = os.getenv("LISTEN_PORT") or os.getenv("FLASK_PORT") or "5000"
     try:

+ 49 - 0
routes/main_routes.py

@@ -8,6 +8,7 @@ from config import Config, logger
 from parsers.connections import group_by_user, parse_raw_data
 from parsers.squid_info import fetch_squid_info_stats
 from services.fetch_data import fetch_squid_data
+from services.notifications import get_all_notifications
 from utils.updateSquid import update_squid
 from utils.updateSquidStats import updateSquidStats
 
@@ -185,3 +186,51 @@ def update_web():
     except Exception:
         logger.exception("Error ejecutando actualización en /update")
     return redirect(f"/?update_status={'ok' if ok else 'fail'}")
+
+
+@main_bp.route("/all-notifications")
+def all_notifications():
+    """Página para ver todas las notificaciones con paginación"""
+    try:
+        # Get pagination parameters
+        page = request.args.get('page', 1, type=int)
+        per_page = request.args.get('per_page', 20, type=int)
+
+        # Validate parameters
+        if page < 1:
+            page = 1
+        if per_page not in [10, 20, 50, 100]:
+            per_page = 20
+
+        # Get notifications with pagination
+        notifications_data = get_all_notifications(limit=None, page=page, per_page=per_page)
+
+        return render_template(
+            "all_notifications.html",
+            page_title="Todas las Notificaciones",
+            subtitle="Historial completo de notificaciones del sistema",
+            icon="fa-bell",
+            notifications=notifications_data['notifications'],
+            unread_count=notifications_data['unread_count'],
+            pagination=notifications_data.get('pagination', {
+                'current_page': page,
+                'per_page': per_page,
+                'total_pages': 1,
+                'total_notifications': len(notifications_data['notifications']),
+                'has_prev': False,
+                'has_next': False
+            })
+        )
+    except Exception as e:
+        from config import logger
+        logger.error(f"Error loading notifications page: {e}")
+        return render_template(
+            "all_notifications.html",
+            page_title="Todas las Notificaciones",
+            subtitle="Error al cargar notificaciones",
+            icon="fa-bell",
+            notifications=[],
+            unread_count=0,
+            pagination=None
+        )
+

+ 616 - 0
templates/all_notifications.html

@@ -0,0 +1,616 @@
+{% extends "layouts/base.html" %}
+
+{% block styles %}
+<style>
+    .notification-fade-in {
+        animation: fadeIn 0.3s ease-in-out;
+    }
+    
+    @keyframes fadeIn {
+        from { opacity: 0; transform: translateY(-10px); }
+        to { opacity: 1; transform: translateY(0); }
+    }
+    
+    .notification-item {
+        transition: all 0.2s ease;
+    }
+    
+    .notification-read {
+        opacity: 0.7;
+        background-color: #f9fafb;
+    }
+    
+    .notification-removing {
+        opacity: 0;
+        transform: translateX(-100%);
+        transition: all 0.3s ease;
+    }
+    
+    .pagination-btn:disabled {
+        opacity: 0.5;
+        cursor: not-allowed;
+    }
+</style>
+{% endblock %}
+
+{% block header_actions %}
+  <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 w-full sm:w-auto">
+    <!-- Contador -->
+    <div class="bg-blue-50 px-3 py-1.5 rounded-lg border border-blue-200 flex-shrink-0 text-center">
+      <span class="text-xs sm:text-sm text-blue-700 font-medium">
+        <span id="unread-count">{{ unread_count }}</span> no leídas
+      </span>
+    </div>
+    
+    <!-- Botón marcar todas como leídas -->
+    <button id="mark-all-read" class="bg-green-600 hover:bg-green-700 text-white px-3 sm:px-4 py-2 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2 text-sm flex-1 sm:flex-none">
+      <i class="fas fa-check-double"></i>
+      <span class="hidden xs:inline">Marcar todas</span>
+    </button>
+
+    <!-- Botón eliminar todas -->
+    <button id="delete-all" class="bg-red-600 hover:bg-red-700 text-white px-3 sm:px-4 py-2 rounded-lg transition-colors duration-200 flex items-center justify-center gap-2 text-sm flex-1 sm:flex-none">
+      <i class="fas fa-trash"></i>
+      <span class="hidden xs:inline">Eliminar todas</span>
+    </button>
+  </div>
+{% endblock %}
+
+{% block content %}
+<div class="w-full space-y-6">
+  <!-- Filtros -->
+  <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
+    <div class="flex flex-wrap gap-4 items-center">
+      <div class="flex items-center gap-2">
+        <span class="text-sm font-medium text-gray-700">Filtrar por:</span>
+        <select id="filter-type" class="text-sm border border-gray-300 rounded-lg px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500">
+          <option value="all">Todos los tipos</option>
+          <option value="error">Errores</option>
+          <option value="warning">Advertencias</option>
+          <option value="success">Éxitos</option>
+          <option value="info">Información</option>
+        </select>
+      </div>
+      
+      <div class="flex items-center gap-2">
+        <select id="filter-source" class="text-sm border border-gray-300 rounded-lg px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500">
+          <option value="all">Todas las fuentes</option>
+          <option value="squid">Squid</option>
+          <option value="system">Sistema</option>
+          <option value="security">Seguridad</option>
+          <option value="users">Usuarios</option>
+          <option value="git">Git</option>
+        </select>
+      </div>
+      
+      <div class="flex items-center gap-2">
+        <select id="filter-status" class="text-sm border border-gray-300 rounded-lg px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500">
+          <option value="all">Todos los estados</option>
+          <option value="unread">No leídas</option>
+          <option value="read">Leídas</option>
+        </select>
+      </div>
+      
+      <button id="clear-filters" class="text-sm text-gray-600 hover:text-gray-800 flex items-center gap-1">
+        <i class="fas fa-times"></i>
+        <span>Limpiar filtros</span>
+      </button>
+    </div>
+  </div>
+
+  <!-- Información de paginación -->
+  <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
+    <div class="flex flex-col sm:flex-row justify-between items-center gap-4">
+      <div class="text-sm text-gray-600">
+        Mostrando <span id="current-range">1-{{ notifications|length }}</span> de 
+        <span id="total-notifications">{{ pagination.total_notifications if pagination else notifications|length }}</span> notificaciones
+      </div>
+      
+      <div class="flex items-center gap-2">
+        <button id="prev-page" class="pagination-btn px-3 py-1 bg-gray-200 rounded hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" 
+                {% if not pagination or not pagination.has_prev %}disabled{% endif %}>
+          <i class="fas fa-chevron-left"></i>
+        </button>
+        <span id="page-info" class="px-3 py-1 text-gray-700 text-sm">
+          Página {{ pagination.current_page if pagination else 1 }} de {{ pagination.total_pages if pagination else 1 }}
+        </span>
+        <button id="next-page" class="pagination-btn px-3 py-1 bg-gray-200 rounded hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
+                {% if not pagination or not pagination.has_next %}disabled{% endif %}>
+          <i class="fas fa-chevron-right"></i>
+        </button>
+      </div>
+    </div>
+  </div>
+
+  <!-- Lista de Notificaciones -->
+  <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
+    {% if notifications %}
+    <div id="notifications-list">
+      {% for notification in notifications %}
+      <div class="notification-item border-b border-gray-100 last:border-b-0 {% if notification.read %}notification-read{% endif %}" 
+           data-id="{{ notification.id }}"
+           data-type="{{ notification.type }}"
+           data-source="{{ notification.source }}"
+           data-read="{{ notification.read|lower }}">
+        <div class="p-6 flex items-start gap-4">
+          <!-- Icono -->
+          <div class="flex-shrink-0">
+            <div class="w-12 h-12 rounded-full flex items-center justify-center 
+                        {% if notification.type == 'error' %}bg-red-100 text-red-600
+                        {% elif notification.type == 'warning' %}bg-yellow-100 text-yellow-600
+                        {% elif notification.type == 'success' %}bg-green-100 text-green-600
+                        {% else %}bg-blue-100 text-blue-600{% endif %}">
+              <i class="fas {{ notification.icon }} text-lg"></i>
+            </div>
+          </div>
+          
+          <!-- Contenido -->
+          <div class="flex-1 min-w-0">
+            <div class="flex items-start justify-between mb-2">
+              <div>
+                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
+                            {% if notification.type == 'error' %}bg-red-100 text-red-800
+                            {% elif notification.type == 'warning' %}bg-yellow-100 text-yellow-800
+                            {% elif notification.type == 'success' %}bg-green-100 text-green-800
+                            {% else %}bg-blue-100 text-blue-800{% endif %}">
+                  {{ notification.source|upper }}
+                </span>
+                <span class="ml-2 text-sm text-gray-500">{{ notification.time }}</span>
+              </div>
+              {% if not notification.read %}
+              <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
+                No leída
+              </span>
+              {% endif %}
+            </div>
+            
+            <p class="text-gray-900 font-medium mb-1">{{ notification.message }}</p>
+            
+            <div class="flex items-center gap-4 mt-3 text-sm text-gray-500">
+              <span class="flex items-center gap-1">
+                <i class="fas fa-clock"></i>
+                <span>{{ notification.timestamp|datetime_format }}</span>
+              </span>
+              <span class="flex items-center gap-1">
+                <i class="fas fa-{{ notification.icon }}"></i>
+                <span class="capitalize">{{ notification.type }}</span>
+              </span>
+            </div>
+          </div>
+          
+          <!-- Acciones -->
+          <div class="flex-shrink-0 flex items-center gap-2">
+            {% if not notification.read %}
+            <button class="mark-read-btn text-green-600 hover:text-green-800 p-2 rounded-lg hover:bg-green-50 transition-colors duration-150" 
+                    data-id="{{ notification.id }}"
+                    title="Marcar como leída">
+              <i class="fas fa-check"></i>
+            </button>
+            {% endif %}
+            <button class="delete-btn text-red-600 hover:text-red-800 p-2 rounded-lg hover:bg-red-50 transition-colors duration-150"
+                    data-id="{{ notification.id }}"
+                    title="Eliminar notificación">
+              <i class="fas fa-trash"></i>
+            </button>
+          </div>
+        </div>
+      </div>
+      {% endfor %}
+    </div>
+    {% else %}
+    <!-- Estado vacío -->
+    <div class="text-center py-16">
+      <div class="w-24 h-24 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
+        <i class="fas fa-bell-slash text-gray-400 text-3xl"></i>
+      </div>
+      <h3 class="text-lg font-medium text-gray-900 mb-2">No hay notificaciones</h3>
+      <p class="text-gray-500 max-w-md mx-auto">Todas las notificaciones aparecerán aquí. ¡Mantente atento a las actualizaciones del sistema!</p>
+    </div>
+    {% endif %}
+  </div>
+</div>
+{% endblock %}
+
+{% block scripts %}
+<script>
+document.addEventListener('DOMContentLoaded', function() {
+    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+    let currentPage = {{ pagination.current_page if pagination else 1 }};
+    const totalPages = {{ pagination.total_pages if pagination else 1 }};
+    const perPage = {{ pagination.per_page if pagination else 20 }};
+    
+    // Función para mostrar toast
+    function showToast(message, type = 'info') {
+        const toast = document.createElement('div');
+        toast.className = `fixed top-4 right-4 z-[1002] p-4 rounded-lg shadow-lg border-l-4 ${
+            type === 'error' ? 'bg-red-50 border-red-500 text-red-700' :
+            type === 'success' ? 'bg-green-50 border-green-500 text-green-700' :
+            'bg-blue-50 border-blue-500 text-blue-700'
+        } max-w-sm transform translate-x-full transition-transform duration-300`;
+        
+        toast.innerHTML = `
+            <div class="flex items-center">
+                <i class="fas ${
+                    type === 'error' ? 'fa-exclamation-circle' :
+                    type === 'success' ? 'fa-check-circle' : 'fa-info-circle'
+                } mr-3"></i>
+                <span>${message}</span>
+            </div>
+        `;
+        
+        document.body.appendChild(toast);
+        
+        setTimeout(() => {
+            toast.classList.remove('translate-x-full');
+            toast.classList.add('translate-x-0');
+        }, 100);
+        
+        setTimeout(() => {
+            toast.classList.remove('translate-x-0');
+            toast.classList.add('translate-x-full');
+            setTimeout(() => {
+                if (toast.parentElement) {
+                    toast.remove();
+                }
+            }, 300);
+        }, 4000);
+    }
+
+    // Función para cargar notificaciones con paginación
+    function loadNotifications(page = currentPage) {
+        const url = `/api/notifications?page=${page}&per_page=${perPage}`;
+        
+        fetch(url)
+            .then(response => response.json())
+            .then(data => {
+                if (data.notifications && data.notifications.length > 0) {
+                    renderNotifications(data.notifications);
+                    updatePagination(data.pagination);
+                } else {
+                    showEmptyState();
+                }
+            })
+            .catch(error => {
+                console.error('Error loading notifications:', error);
+                showToast('Error al cargar notificaciones', 'error');
+            });
+    }
+
+    // Función para renderizar notificaciones
+    function renderNotifications(notifications) {
+        const container = document.getElementById('notifications-list');
+        if (!container) return;
+
+        container.innerHTML = notifications.map(notification => `
+            <div class="notification-item border-b border-gray-100 last:border-b-0 ${notification.read ? 'notification-read' : ''}" 
+                 data-id="${notification.id}"
+                 data-type="${notification.type}"
+                 data-source="${notification.source}"
+                 data-read="${notification.read}">
+                <div class="p-6 flex items-start gap-4">
+                    <div class="flex-shrink-0">
+                        <div class="w-12 h-12 rounded-full flex items-center justify-center 
+                                    ${notification.type === 'error' ? 'bg-red-100 text-red-600' :
+                                      notification.type === 'warning' ? 'bg-yellow-100 text-yellow-600' :
+                                      notification.type === 'success' ? 'bg-green-100 text-green-600' :
+                                      'bg-blue-100 text-blue-600'}">
+                            <i class="fas ${notification.icon} text-lg"></i>
+                        </div>
+                    </div>
+                    
+                    <div class="flex-1 min-w-0">
+                        <div class="flex items-start justify-between mb-2">
+                            <div>
+                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
+                                            ${notification.type === 'error' ? 'bg-red-100 text-red-800' :
+                                              notification.type === 'warning' ? 'bg-yellow-100 text-yellow-800' :
+                                              notification.type === 'success' ? 'bg-green-100 text-green-800' :
+                                              'bg-blue-100 text-blue-800'}">
+                                    ${notification.source.toUpperCase()}
+                                </span>
+                                <span class="ml-2 text-sm text-gray-500">${formatTimeAgo(notification.timestamp)}</span>
+                            </div>
+                            ${!notification.read ? `
+                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
+                                No leída
+                            </span>
+                            ` : ''}
+                        </div>
+                        
+                        <p class="text-gray-900 font-medium mb-1">${notification.message}</p>
+                        
+                        <div class="flex items-center gap-4 mt-3 text-sm text-gray-500">
+                            <span class="flex items-center gap-1">
+                                <i class="fas fa-clock"></i>
+                                <span>${new Date(notification.timestamp).toLocaleString('es-ES')}</span>
+                            </span>
+                            <span class="flex items-center gap-1">
+                                <i class="fas fa-${notification.icon}"></i>
+                                <span class="capitalize">${notification.type}</span>
+                            </span>
+                        </div>
+                    </div>
+                    
+                    <div class="flex-shrink-0 flex items-center gap-2">
+                        ${!notification.read ? `
+                        <button class="mark-read-btn text-green-600 hover:text-green-800 p-2 rounded-lg hover:bg-green-50 transition-colors duration-150" 
+                                data-id="${notification.id}"
+                                title="Marcar como leída">
+                            <i class="fas fa-check"></i>
+                        </button>
+                        ` : ''}
+                        <button class="delete-btn text-red-600 hover:text-red-800 p-2 rounded-lg hover:bg-red-50 transition-colors duration-150"
+                                data-id="${notification.id}"
+                                title="Eliminar notificación">
+                            <i class="fas fa-trash"></i>
+                        </button>
+                    </div>
+                </div>
+            </div>
+        `).join('');
+
+        // Re-aplicar filtros después de cargar
+        applyFilters();
+    }
+
+    // Función para actualizar la paginación
+    function updatePagination(pagination) {
+        currentPage = pagination.current_page;
+        const totalPages = pagination.total_pages;
+        const totalNotifications = pagination.total_notifications;
+        
+        // Actualizar información de paginación
+        document.getElementById('current-range').textContent = 
+            `${((currentPage - 1) * perPage) + 1}-${Math.min(currentPage * perPage, totalNotifications)}`;
+        document.getElementById('total-notifications').textContent = totalNotifications;
+        document.getElementById('page-info').textContent = `Página ${currentPage} de ${totalPages}`;
+        
+        // Actualizar botones de paginación
+        document.getElementById('prev-page').disabled = currentPage <= 1;
+        document.getElementById('next-page').disabled = currentPage >= totalPages;
+    }
+
+    // Función para mostrar estado vacío
+    function showEmptyState() {
+        const container = document.getElementById('notifications-list');
+        if (!container) return;
+        
+        container.innerHTML = `
+            <div class="text-center py-16">
+                <div class="w-24 h-24 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
+                    <i class="fas fa-bell-slash text-gray-400 text-3xl"></i>
+                </div>
+                <h3 class="text-lg font-medium text-gray-900 mb-2">No hay notificaciones</h3>
+                <p class="text-gray-500 max-w-md mx-auto">Todas las notificaciones aparecerán aquí. ¡Mantente atento a las actualizaciones del sistema!</p>
+            </div>
+        `;
+    }
+
+    // Función para formatear "hace X tiempo"
+    function formatTimeAgo(timestamp) {
+        const now = new Date();
+        const notificationTime = new Date(timestamp);
+        const diffMs = now - notificationTime;
+        const diffMins = Math.floor(diffMs / 60000);
+        const diffHours = Math.floor(diffMs / 3600000);
+        const diffDays = Math.floor(diffMs / 86400000);
+        
+        if (diffMins < 1) return 'Hace unos momentos';
+        if (diffMins < 60) return `Hace ${diffMins} minuto${diffMins > 1 ? 's' : ''}`;
+        if (diffHours < 24) return `Hace ${diffHours} hora${diffHours > 1 ? 's' : ''}`;
+        return `Hace ${diffDays} día${diffDays > 1 ? 's' : ''}`;
+    }
+
+    // Función para marcar notificación como leída
+    function markAsRead(notificationIds) {
+        fetch('/api/notifications/mark-read', {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json',
+                'X-CSRFToken': csrfToken,
+            },
+            body: JSON.stringify({ 
+                notification_ids: notificationIds  // Cambiado de 'ids' a 'notification_ids'
+            })
+        })
+        .then(response => {
+            if (!response.ok) {
+                throw new Error(`Error HTTP: ${response.status}`);
+            }
+            return response.json();
+        })
+        .then(data => {
+            if (data.success) {
+                // Actualizar contador en el header
+                document.getElementById('unread-count').textContent = data.unread_count;
+                
+                // Recargar notificaciones para reflejar cambios
+                loadNotifications(currentPage);
+                
+                showToast(`${notificationIds.length} notificación(es) marcada(s) como leída(s)`, 'success');
+            } else {
+                showToast('Error al marcar notificaciones como leídas: ' + (data.error || 'Error desconocido'), 'error');
+            }
+        })
+        .catch(error => {
+            console.error('Error:', error);
+            showToast('Error de conexión: ' + error.message, 'error');
+        });
+    }
+
+    // Función para marcar TODAS las notificaciones como leídas
+    function markAllAsRead() {
+        const unreadNotifications = document.querySelectorAll('.notification-item[data-read="false"]');
+        const unreadIds = Array.from(unreadNotifications).map(el => parseInt(el.getAttribute('data-id')));
+        
+        if (unreadIds.length > 0) {
+            markAsRead(unreadIds);
+        } else {
+            showToast('No hay notificaciones sin leer', 'info');
+        }
+    }
+
+    // Función para ELIMINAR notificación
+    function deleteNotification(notificationId) {
+        if (!confirm('¿Estás seguro de que quieres eliminar esta notificación?')) {
+            return;
+        }
+        
+        fetch(`/api/notifications/${notificationId}`, {
+            method: 'DELETE',
+            headers: {
+                'X-CSRFToken': csrfToken,
+            }
+        })
+        .then(response => {
+            if (!response.ok) {
+                throw new Error(`Error HTTP: ${response.status}`);
+            }
+            return response.json();
+        })
+        .then(data => {
+            if (data.success) {
+                // Recargar notificaciones
+                loadNotifications(currentPage);
+                
+                // Actualizar contador
+                document.getElementById('unread-count').textContent = data.unread_count;
+                
+                showToast('Notificación eliminada', 'success');
+            } else {
+                showToast('Error al eliminar notificación: ' + (data.error || 'Error desconocido'), 'error');
+            }
+        })
+        .catch(error => {
+            console.error('Error:', error);
+            showToast('Error de conexión: ' + error.message, 'error');
+        });
+    }
+
+    // Función para ELIMINAR TODAS las notificaciones
+    function deleteAllNotifications() {
+        if (!confirm('¿Estás seguro de que quieres eliminar TODAS las notificaciones? Esta acción no se puede deshacer.')) {
+            return;
+        }
+        
+        fetch('/api/notifications/delete-all', {
+            method: 'DELETE',
+            headers: {
+                'X-CSRFToken': csrfToken,
+            }
+        })
+        .then(response => {
+            if (!response.ok) {
+                throw new Error(`Error HTTP: ${response.status}`);
+            }
+            return response.json();
+        })
+        .then(data => {
+            if (data.success) {
+                // Mostrar estado vacío
+                showEmptyState();
+                
+                // Actualizar contador
+                document.getElementById('unread-count').textContent = '0';
+                
+                // Actualizar paginación
+                document.getElementById('current-range').textContent = '0-0';
+                document.getElementById('total-notifications').textContent = '0';
+                document.getElementById('page-info').textContent = 'Página 1 de 1';
+                
+                // Deshabilitar botones de paginación
+                document.getElementById('prev-page').disabled = true;
+                document.getElementById('next-page').disabled = true;
+                
+                showToast('Todas las notificaciones han sido eliminadas', 'success');
+            } else {
+                showToast('Error al eliminar notificaciones: ' + (data.error || 'Error desconocido'), 'error');
+            }
+        })
+        .catch(error => {
+            console.error('Error:', error);
+            showToast('Error de conexión: ' + error.message, 'error');
+        });
+    }
+    
+    // Filtros
+    function applyFilters() {
+        const typeFilter = document.getElementById('filter-type').value;
+        const sourceFilter = document.getElementById('filter-source').value;
+        const statusFilter = document.getElementById('filter-status').value;
+        
+        const notifications = document.querySelectorAll('.notification-item');
+        let visibleCount = 0;
+        
+        notifications.forEach(notification => {
+            const type = notification.getAttribute('data-type');
+            const source = notification.getAttribute('data-source');
+            const read = notification.getAttribute('data-read') === 'true';
+            
+            const typeMatch = typeFilter === 'all' || type === typeFilter;
+            const sourceMatch = sourceFilter === 'all' || source === sourceFilter;
+            const statusMatch = statusFilter === 'all' || 
+                               (statusFilter === 'unread' && !read) || 
+                               (statusFilter === 'read' && read);
+            
+            if (typeMatch && sourceMatch && statusMatch) {
+                notification.style.display = 'block';
+                visibleCount++;
+            } else {
+                notification.style.display = 'none';
+            }
+        });
+        
+        if (visibleCount === 0 && notifications.length > 0) {
+            // No mostrar toast aquí para evitar spam al aplicar filtros
+        }
+    }
+    
+    // Event Listeners
+    document.addEventListener('click', function(e) {
+        if (e.target.closest('.mark-read-btn')) {
+            const button = e.target.closest('.mark-read-btn');
+            const notificationId = parseInt(button.getAttribute('data-id'));
+            markAsRead([notificationId]);
+        }
+        
+        if (e.target.closest('.delete-btn')) {
+            const button = e.target.closest('.delete-btn');
+            const notificationId = parseInt(button.getAttribute('data-id'));
+            deleteNotification(notificationId);
+        }
+    });
+    
+    document.getElementById('mark-all-read').addEventListener('click', markAllAsRead);
+    document.getElementById('delete-all').addEventListener('click', deleteAllNotifications);
+    
+    // Paginación
+    document.getElementById('prev-page').addEventListener('click', function() {
+        if (currentPage > 1) {
+            currentPage--;
+            loadNotifications(currentPage);
+        }
+    });
+    
+    document.getElementById('next-page').addEventListener('click', function() {
+        if (currentPage < totalPages) {
+            currentPage++;
+            loadNotifications(currentPage);
+        }
+    });
+    
+    // Filtros
+    document.getElementById('filter-type').addEventListener('change', applyFilters);
+    document.getElementById('filter-source').addEventListener('change', applyFilters);
+    document.getElementById('filter-status').addEventListener('change', applyFilters);
+    
+    document.getElementById('clear-filters').addEventListener('click', function() {
+        document.getElementById('filter-type').value = 'all';
+        document.getElementById('filter-source').value = 'all';
+        document.getElementById('filter-status').value = 'all';
+        applyFilters();
+        showToast('Filtros limpiados', 'info');
+    });
+});
+</script>
+{% endblock %}

+ 2 - 1
templates/auditor.html

@@ -1,5 +1,5 @@
+{% extends "layouts/base.html" %}
 
-{% extends 'layouts/base.html' %}
 {% block styles %}
     <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}"/>
     <style>
@@ -73,6 +73,7 @@
     <script src="{{ url_for('static', filename='js/auditoria/renderers.js') }}"></script>
     <script src="{{ url_for('static', filename='js/auditoria/user_search_and_inputs.js') }}"></script>
     <script src="{{ url_for('static', filename='js/auditoria/form_and_results.js') }}"></script>
+    
     <script>
         document.addEventListener('DOMContentLoaded', ()=>{
             window.__AUD_FORM__ && window.__AUD_FORM__.initFormAndResults();

+ 11 - 3
templates/blacklist.html

@@ -1,8 +1,16 @@
-{% extends 'layouts/base.html' %} 
+{% extends 'layouts/base.html' %}
+
+{% block header_actions %}
+<div class="bg-gray-100 px-4 py-2 rounded-lg shadow-sm">
+    <span class="text-sm font-medium text-gray-600">
+        Página {{ pagination.page }} de {{ pagination.total_pages }}
+    </span>
+</div>
+{% endblock header_actions %}
  
 {% block content %} 
     {% include 'partials/black_list.html' %} 
-{%endblock %}
+{% endblock %}
 
 {% block scripts %}
 <script>
@@ -13,4 +21,4 @@
         return url.toString();
     }
 </script>
-{% endblock scripts %}
+{% endblock scripts %}

+ 182 - 135
templates/components/navbar.html

@@ -1,126 +1,129 @@
 <nav class="top-0 z-[1000] fixed w-full bg-gradient-to-br from-blue-800 to-blue-900 shadow-lg border-b border-white/10 backdrop-blur-md transition-transform duration-300" x-data="{ mobileMenuOpen: false, showSquidModal: false, showWebModal: false }">
-  <div class="max-w-[1200px] mx-auto flex items-center justify-between px-6 py-3 h-[60px]">
-    <!-- Brand/Logo Section -->
-    <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
-      <spam class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">SquidStats</spam>
-    </div>
-    <!-- Contenedor para iconos móviles (notificaciones + hamburguesa) -->
-    <div class="lg:hidden flex items-center gap-3">
-      <!-- Botón de Notificaciones en Móvil -->
-      <div class="relative" x-data="{ open: false }">
-        <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Notificaciones">
-          <i class="fas fa-bell"></i>
-          <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
-        </button>
-        <!-- Dropdown de notificaciones móvil -->
-        <div x-show="open"
-          @click.away="open = false"
-          @keydown.escape.window="open = false"
-          x-transition:enter="transition ease-out duration-200"
-          x-transition:enter-start="opacity-0 scale-95"
-          x-transition:enter-end="opacity-100 scale-100"
-          x-transition:leave="transition ease-in duration-150"
-          x-transition:leave-start="opacity-100 scale-100"
-          x-transition:leave-end="opacity-0 scale-95"
-          class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
-          style="display: none">
-          <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
-            <span class="font-semibold text-gray-800">Notificaciones</span>
-            <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
-              <i class="fas fa-times"></i>
-            </button>
-          </div>
-          <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications-mobile">
-            <li class="px-4 py-3 text-gray-500 text-center">
-              Cargando notificaciones...
-            </li>
-          </ul>
-          <div class="py-2 px-4 text-center border-t border-gray-200">
-            <a href="#" class="text-sm text-blue-600 hover:underline">Ver todas las notificaciones</a>
+  <!-- CONTENEDOR UNIFICADO CON EL RESTO -->
+  <div class="w-full px-4 sm:px-6 lg:px-8">
+    <div class="max-w-7xl mx-auto flex items-center justify-between py-4 h-[64px]">
+      <!-- Brand/Logo Section -->
+      <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
+        <spam class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">SquidStats</spam>
+      </div>
+      <!-- Contenedor para iconos móviles (notificaciones + hamburguesa) -->
+      <div class="lg:hidden flex items-center gap-3">
+        <!-- Botón de Notificaciones en Móvil -->
+        <div class="relative" x-data="{ open: false }">
+          <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Notificaciones">
+            <i class="fas fa-bell"></i>
+            <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
+          </button>
+          <!-- Dropdown de notificaciones móvil -->
+          <div x-show="open"
+            @click.away="open = false"
+            @keydown.escape.window="open = false"
+            x-transition:enter="transition ease-out duration-200"
+            x-transition:enter-start="opacity-0 scale-95"
+            x-transition:enter-end="opacity-100 scale-100"
+            x-transition:leave="transition ease-in duration-150"
+            x-transition:leave-start="opacity-100 scale-100"
+            x-transition:leave-end="opacity-0 scale-95"
+            class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
+            style="display: none">
+            <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
+              <span class="font-semibold text-gray-800">Notificaciones</span>
+              <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
+                <i class="fas fa-times"></i>
+              </button>
+            </div>
+            <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications-mobile">
+              <li class="px-4 py-3 text-gray-500 text-center">
+                Cargando notificaciones...
+              </li>
+            </ul>
+            <div class="py-2 px-4 text-center border-t border-gray-200">
+                <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">Ver todas las notificaciones</a>
+            </div>
           </div>
         </div>
-      </div>
-      <!-- Hamburger Button for Mobile -->
-      <button @click="mobileMenuOpen = !mobileMenuOpen" class="flex flex-col w-8 h-8 justify-center items-center gap-1.5 text-white focus:outline-none z-[1001]" aria-label="Toggle menu">
-        <span class="w-6 h-0.5 bg-white transition-all" :class="{'rotate-45 translate-y-2': mobileMenuOpen}"></span>
-        <span class="w-6 h-0.5 bg-white transition-all" :class="{'opacity-0': mobileMenuOpen}"></span>
-        <span class="w-6 h-0.5 bg-white transition-all" :class="{'-rotate-45 -translate-y-2': mobileMenuOpen}"></span>
-      </button>
-    </div>
-    <!-- Navigation Links - Desktop -->
-    <div class="hidden lg:flex items-center gap-2">
-      <a href="/" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Panel principal con conexiones activas">
-        <i class="fas fa-home text-base"></i>
-        <span class="font-medium">Inicio</span>
-      </a>
-      <a href="/stats" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Estadísticas de rendimiento del cache">
-        <i class="fas fa-chart-bar text-base"></i>
-        <span class="font-medium">Estadísticas</span>
-      </a>
-      <a href="/logs" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Actividad y logs de usuarios">
-        <i class="fas fa-user-friends text-base"></i>
-        <span class="font-medium">Usuarios</span>
-      </a>
-      <a href="/reports" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Reportes y gráficas avanzadas">
-        <i class="fas fa-chart-simple text-base"></i>
-        <span class="font-medium">Reportes</span>
-      </a>
-      <a href="/blacklist" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Sitios bloqueados y actividad restringida">
-        <i class="fas fa-ban text-base"></i>
-        <span class="font-medium">Blacklist</span>
-      </a>
-      <a href="/auditoria" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Auditoría de actividad por usuario y fecha">
-        <i class="fas fa-magnifying-glass text-base"></i>
-        <span class="font-medium">Auditoría</span>
-      </a>
-    </div>
-    <!-- Notificaciones Desktop -->
-    <div class="hidden lg:flex items-center gap-3">
-      <div class="relative" x-data="{ open: false }">
-	      <!-- Botón de Notificaciones en Desktop -->
-        <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Notificaciones">
-          <i class="fas fa-bell"></i>
-          <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
+        <!-- Hamburger Button for Mobile -->
+        <button @click="mobileMenuOpen = !mobileMenuOpen" class="flex flex-col w-8 h-8 justify-center items-center gap-1.5 text-white focus:outline-none z-[1001]" aria-label="Toggle menu">
+          <span class="w-6 h-0.5 bg-white transition-all" :class="{'rotate-45 translate-y-2': mobileMenuOpen}"></span>
+          <span class="w-6 h-0.5 bg-white transition-all" :class="{'opacity-0': mobileMenuOpen}"></span>
+          <span class="w-6 h-0.5 bg-white transition-all" :class="{'-rotate-45 -translate-y-2': mobileMenuOpen}"></span>
         </button>
-		    <!-- Dropdown de notificaciones Desktop -->
-        <div x-show="open"
-          @click.away="open = false"
-          @keydown.escape.window="open = false"
-          x-transition:enter="transition ease-out duration-200"
-          x-transition:enter-start="opacity-0 scale-95"
-          x-transition:enter-end="opacity-100 scale-100"
-          x-transition:leave="transition ease-in duration-150"
-          x-transition:leave-start="opacity-100 scale-100"
-          x-transition:leave-end="opacity-0 scale-95"
-          class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
-          style="display: none">
-          <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
-            <span class="font-semibold text-gray-800">Notificaciones</span>
-            <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
-              <i class="fas fa-times"></i>
-            </button>
-          </div>
-          <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications">
-            <li class="px-4 py-3 text-gray-500 text-center">
-              Cargando notificaciones...
-            </li>
-          </ul>
-          <div class="py-2 px-4 text-center border-t border-gray-200">
-            <a href="#" class="text-sm text-blue-600 hover:underline">Ver todas las notificaciones</a>
+      </div>
+      <!-- Navigation Links - Desktop -->
+      <div class="hidden lg:flex items-center gap-2">
+        <a href="/" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Panel principal con conexiones activas">
+          <i class="fas fa-home text-base"></i>
+          <span class="font-medium">Inicio</span>
+        </a>
+        <a href="/stats" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Estadísticas de rendimiento del cache">
+          <i class="fas fa-chart-bar text-base"></i>
+          <span class="font-medium">Estadísticas</span>
+        </a>
+        <a href="/logs" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Actividad y logs de usuarios">
+          <i class="fas fa-user-friends text-base"></i>
+          <span class="font-medium">Usuarios</span>
+        </a>
+        <a href="/reports" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Reportes y gráficas avanzadas">
+          <i class="fas fa-chart-simple text-base"></i>
+          <span class="font-medium">Reportes</span>
+        </a>
+        <a href="/blacklist" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Sitios bloqueados y actividad restringida">
+          <i class="fas fa-ban text-base"></i>
+          <span class="font-medium">Blacklist</span>
+        </a>
+        <a href="/auditoria" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Auditoría de actividad por usuario y fecha">
+          <i class="fas fa-magnifying-glass text-base"></i>
+          <span class="font-medium">Auditoría</span>
+        </a>
+      </div>
+      <!-- Notificaciones Desktop -->
+      <div class="hidden lg:flex items-center gap-3">
+        <div class="relative" x-data="{ open: false }">
+          <!-- Botón de Notificaciones en Desktop -->
+          <button @click="open = !open" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Notificaciones">
+            <i class="fas fa-bell"></i>
+            <span class="notification-badge absolute -top-2 -right-2 flex items-center justify-center w-5 h-5 bg-gradient-to-r from-red-500 to-red-600 text-white text-xs font-semibold rounded-full border-2 border-white shadow-lg hidden">0</span>
+          </button>
+          <!-- Dropdown de notificaciones Desktop -->
+          <div x-show="open"
+            @click.away="open = false"
+            @keydown.escape.window="open = false"
+            x-transition:enter="transition ease-out duration-200"
+            x-transition:enter-start="opacity-0 scale-95"
+            x-transition:enter-end="opacity-100 scale-100"
+            x-transition:leave="transition ease-in duration-150"
+            x-transition:leave-start="opacity-100 scale-100"
+            x-transition:leave-end="opacity-0 scale-95"
+            class="origin-top-right absolute right-0 mt-2 w-80 rounded-lg shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
+            style="display: none">
+            <div class="py-2 px-4 border-b border-gray-200 flex items-center justify-between">
+              <span class="font-semibold text-gray-800">Notificaciones</span>
+              <button @click="open = false" class="text-gray-400 hover:text-gray-600 focus:outline-none">
+                <i class="fas fa-times"></i>
+              </button>
+            </div>
+            <ul class="max-h-72 overflow-y-auto divide-y divide-gray-100 notifications">
+              <li class="px-4 py-3 text-gray-500 text-center">
+                Cargando notificaciones...
+              </li>
+            </ul>
+            <div class="py-2 px-4 text-center border-t border-gray-200">
+                <a href="/all-notifications" class="text-sm text-blue-600 hover:underline">Ver todas las notificaciones</a>
+            </div>
           </div>
         </div>
-      </div>
-      <!-- Action Buttons - Desktop -->
-      <div class="flex items-center gap-3">
-        <button @click="showSquidModal = true" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-emerald-600 to-emerald-400 text-white shadow hover:from-emerald-700 hover:to-emerald-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Actualizar paquetes y configuración de Squid">
-          <i class="fas fa-sync-alt"></i>
-          <span>Squid</span>
-        </button>
+        <!-- Action Buttons - Desktop -->
+        <div class="flex items-center gap-3">
+          <button @click="showSquidModal = true" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-emerald-600 to-emerald-400 text-white shadow hover:from-emerald-700 hover:to-emerald-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Actualizar paquetes y configuración de Squid">
+            <i class="fas fa-sync-alt"></i>
+            <span>Squid</span>
+          </button>
 
-        <button @click="showWebModal = true" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-purple-600 to-purple-400 text-white shadow hover:from-purple-700 hover:to-purple-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Actualizar aplicación web SquidStats">
-          <i class="fas fa-cloud-download-alt"></i>
-          <span>Web</span>
-        </button>
+          <button @click="showWebModal = true" class="action-btn flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm bg-gradient-to-r from-purple-600 to-purple-400 text-white shadow hover:from-purple-700 hover:to-purple-600 hover:-translate-y-0.5 transition-all duration-300" data-tooltip="Actualizar aplicación web SquidStats">
+            <i class="fas fa-cloud-download-alt"></i>
+            <span>Web</span>
+          </button>
+        </div>
       </div>
     </div>
   </div>
@@ -364,6 +367,16 @@
       });
     }
 
+    // Función para obtener el token CSRF de forma segura
+    function getCSRFToken() {
+      const metaTag = document.querySelector('meta[name="csrf-token"]');
+      if (metaTag) {
+        return metaTag.getAttribute('content');
+      }
+      console.warn('CSRF token meta tag no encontrado');
+      return '';
+    }
+
     // Enhanced Notifications System with WebSocket
     function initNotifications() {
         let notificationSocket = null;
@@ -470,7 +483,6 @@
         }
 
         function updateNotificationLists() {
-            // const desktopUl = document.querySelector(".max-h-72.overflow-y-auto");
             const desktopUl = document.querySelector(".notifications");
             const mobileUl = document.querySelector(".notifications-mobile");
             
@@ -478,8 +490,13 @@
                 if (!ul) return;
                 
                 ul.innerHTML = "";
-                if (notifications && notifications.length > 0) {
-                    notifications.slice(0, 10).forEach((notification) => {
+                
+                // Usar el estado local actual - SOLO notificaciones no leídas
+                const unreadNotifications = notificationsData.notifications.filter(n => !n.read);
+                const notificationsToShow = unreadNotifications.slice(0, 10);
+                
+                if (notificationsToShow.length > 0) {
+                    notificationsToShow.forEach((notification) => {
                         let bgColor, textColor;
                         
                         switch(notification.type) {
@@ -546,43 +563,70 @@
         }
 
         function markAsRead(notificationIds) {
+            const csrfToken = getCSRFToken();
             fetch('/api/notifications/mark-read', {
                 method: 'POST',
                 headers: {
                     'Content-Type': 'application/json',
+                    'X-CSRFToken': csrfToken,
                 },
-                body: JSON.stringify({ ids: notificationIds })
+                body: JSON.stringify({ 
+                    ids: notificationIds
+                })
+            })
+            .then(response => {
+                if (!response.ok) {
+                    throw new Error(`Error HTTP: ${response.status}`);
+                }
+                return response.json();
             })
-            .then(response => response.json())
             .then(data => {
                 if (data.success) {
+                    // CORRECCIÓN: Filtrar notificaciones marcadas del estado local
+                    notificationsData.notifications = notificationsData.notifications.filter(
+                        notification => !notificationIds.includes(notification.id)
+                    );
+                    
                     notificationsData.unread_count = data.unread_count;
                     updateNotificationBadges(data.unread_count);
-                    
-                    // Marcar como leído localmente
-                    notificationIds.forEach(id => {
-                        const notification = notificationsData.notifications.find(n => n.id === id);
-                        if (notification) {
-                            notification.read = true;
-                        }
-                    });
-                    
                     updateNotificationLists();
+                } else {
+                    console.error('Error del servidor al marcar como leída:', data.error);
+                    showNotificationToast({
+                        type: 'error',
+                        message: 'Error al marcar notificación como leída: ' + (data.error || 'Error desconocido')
+                    });
                 }
             })
-            .catch(error => console.error('Error marking as read:', error));
+            .catch(error => {
+                showNotificationToast({
+                    type: 'error',
+                    message: 'Error al marcar notificación como leída: ' + error.message
+                });
+            });
         }
 
         function fetchInitialNotifications() {
             fetch("/api/notifications")
-                .then((res) => res.json())
+                .then((res) => {
+                    if (!res.ok) {
+                        throw new Error(`Error HTTP: ${res.status}`);
+                    }
+                    return res.json();
+                })
                 .then((data) => {
-                    notificationsData = data;
+                    // REEMPLAZAR completamente el estado local
+                    notificationsData.notifications = data.notifications || [];
+                    notificationsData.unread_count = data.unread_count || 0;
                     updateNotificationLists();
                     updateNotificationBadges(data.unread_count);
                 })
                 .catch((error) => {
                     console.error('Error fetching notifications:', error);
+                    notificationsData.notifications = [];
+                    notificationsData.unread_count = 0;
+                    updateNotificationLists();
+                    updateNotificationBadges(0);
                 });
         }
 
@@ -599,13 +643,14 @@
         fetchInitialNotifications();
         connectWebSocket();
     }
-
+    
     // Initialize all functionality
     initTooltips();
     initNavbarScroll();
     setActiveLink();
-    initNotifications(); // ← Inicializar sistema de notificaciones
+    initNotifications();
   });
+
   // Close modals when clicking outside
   document.addEventListener("click", function (e) {
     if (e.target.classList.contains("modal-overlay")) {
@@ -619,6 +664,7 @@
       });
     }
   });
+
   // Add escape key handling for modals
   document.addEventListener("keydown", function (e) {
     if (e.key === "Escape") {
@@ -632,6 +678,7 @@
       });
     }
   });
+
   // Mobile menu close on outside click
   document.addEventListener('click', function(event) {
     const mobileMenu = document.querySelector('[x-data]');

+ 22 - 19
templates/index.html

@@ -1,6 +1,6 @@
 {% extends 'layouts/base.html' %} 
 
-{% from 'macros.html' import format_bandwidth %}  {# CAMBIO: Importar desde macros #}
+{% from 'macros.html' import format_bandwidth %}
 
 {% set valid_users = {} %} 
 {% for user, user_data in grouped_connections.items()%} 
@@ -8,28 +8,32 @@
     {% set _ = valid_users.update({user: user_data}) %} 
   {% endif %} 
 {% endfor %}
-{% block title %}{% endblock title %}
 
-{% block content %}
-<div class="flex flex-wrap items-center gap-3 mb-4 bg-white/70 dark:bg-gray-800/60 px-3 py-2 rounded-md border border-gray-200 shadow-sm text-sm max-w-full">
-  <label for="refresh-interval" class="text-gray-700 dark:text-gray-200 font-medium select-none">⏱️</label>
-  <div class="flex items-center gap-1">
-    <input id="refresh-interval" type="number" min="10" class="w-20 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded focus:ring-1 focus:ring-blue-500 focus:outline-none bg-white/80 dark:bg-gray-700/60 text-gray-700 dark:text-gray-100" placeholder="60" aria-label="Intervalo de refresco (segundos)">
-    <span class="text-gray-500 dark:text-gray-400">s</span>
-  </div>
-  <div class="flex items-center gap-1 text-gray-600 dark:text-gray-300">
-    <span class="hidden sm:inline">→</span>
-    <span id="next-refresh" class="font-mono">--</span>
+{% block header %}
+  <!-- CONTENEDOR ALINEADO CON EL RESTO DEL CONTENIDO -->
+  <div class="max-w-7xl mx-auto">
+    <div class="flex flex-wrap items-center gap-3 mb-4 bg-white/70 dark:bg-gray-800/60 px-3 py-2 rounded-md border border-gray-200 shadow-sm text-sm w-full">
+      <label for="refresh-interval" class="text-gray-700 dark:text-gray-200 font-medium select-none">⏱️</label>
+      <div class="flex items-center gap-1">
+        <input id="refresh-interval" type="number" min="10" class="w-20 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded focus:ring-1 focus:ring-blue-500 focus:outline-none bg-white/80 dark:bg-gray-700/60 text-gray-700 dark:text-gray-100" placeholder="60" aria-label="Intervalo de refresco (segundos)">
+        <span class="text-gray-500 dark:text-gray-400">s</span>
+      </div>
+      <div class="flex items-center gap-1 text-gray-600 dark:text-gray-300">
+        <span class="hidden sm:inline">→</span>
+        <span id="next-refresh" class="font-mono">--</span>
+      </div>
+      <button id="set-interval-btn" class="px-3 py-1 rounded bg-blue-600 hover:bg-blue-700 text-white font-medium transition text-xs">Aplicar</button>
+      <span id="persist-status" class="text-[11px] text-gray-400 ml-auto pr-1 opacity-0 transition-opacity"></span>
+    </div>
   </div>
-  <button id="set-interval-btn" class="px-3 py-1 rounded bg-blue-600 hover:bg-blue-700 text-white font-medium transition text-xs">Aplicar</button>
-  <span id="persist-status" class="text-[11px] text-gray-400 ml-auto pr-1 opacity-0 transition-opacity"></span>
-</div>
-<div id="datos-conexiones" class="max-w-7xl mx-auto sm:px-6 lg:px-8">
+{% endblock header %}
+
+{% block content %}
+<div id="datos-conexiones" class="w-full">
   {% include 'partials/conexiones.html' %}
 </div>
 {% endblock %}
 
-
 {% block scripts %}
   <script>
     let isDetailedView = true;
@@ -180,5 +184,4 @@
       });
     });
   </script>
-{% endblock scripts %}
-
+{% endblock scripts %}

+ 30 - 15
templates/layouts/base.html

@@ -5,10 +5,8 @@
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <meta name="csrf-token" content="{{ csrf_token() }}">
     <title>{{ page_title or 'Dashboard Squid' }}</title>
-
     <!-- Favicon dinámico -->
     <link rel="icon" href="{{ url_for('static', filename=page_icon) }}" type="image/x-icon"/>
-
     <!-- Hojas de estilo -->
     <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"/>
     <link rel="stylesheet" href="{{url_for('static',filename='dist/output.css')}}"/>
@@ -22,21 +20,38 @@
     <!-- Barra de navegación común -->
     <div class="relative">
       {% include 'components/navbar.html' %}
-      <!-- Contenido principal con padding para el navbar -->
-      <main class="min-h-screen pt-10 lg:pt-10 pb-20">
-        <div class="max-w-7xl mx-auto px-4 py-8">
-          {% block title %}
-            <div class="flex items-center mb-6 border-b pb-4">
-              <i class="{{icon}} text-3xl text-blue-600 mr-4"></i> <!-- agregar icon al contexto para mostrar el icono dinamicamente -->
-              <div>
-                  <h1 class="text-3xl font-bold text-gray-800">{{page_title}}</h1>  <!-- usando page_title del contexto para mostrar el titulo dinamicamente puedes hacer lo mismo con el icono(icon) y el subtitulo(subtitle) -->
-                  <p class="text-gray-500 mt-1">
-                    {{subtitle}} <!-- agregar subtitle al contexto para mostrarlo dinamicamente -->
+      <!-- Contenido principal con MÁS ESPACIO para el navbar -->
+      <main class="min-h-screen pt-16 lg:pt-20 pb-20">
+        <!-- CONTENEDOR PRINCIPAL UNIFICADO -->
+        <div class="w-full px-4 sm:px-6 lg:px-8">
+          {% block header %}
+            <!-- Header por defecto - MEJORADO PARA RESPONSIVE -->
+            <div class="max-w-7xl mx-auto flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-8">
+              <!-- Título y subtítulo -->
+              <div class="flex items-center flex-shrink-0">
+                {% if icon %}
+                <i class="{{icon}} text-2xl sm:text-3xl text-blue-600 mr-3 sm:mr-4"></i>
+                {% endif %}
+                <div class="min-w-0">
+                  <h1 class="text-2xl sm:text-3xl font-bold text-gray-800 truncate">{{page_title}}</h1>
+                  <p class="text-gray-500 text-sm sm:text-base mt-1 line-clamp-2">
+                    {{subtitle}}
                   </p>
+                </div>
+              </div>
+              
+              <!-- Área de acciones del header - editable por las páginas -->
+              <div class="flex items-center justify-start lg:justify-end flex-wrap gap-2 sm:gap-3 min-w-0">
+                {% block header_actions %}
+                  <!-- Por defecto vacío - las páginas pueden agregar contenido aquí -->
+                {% endblock %}
               </div>
             </div>
-          {% endblock title %}
-          {% block content %}{% endblock %}
+          {% endblock %}
+          <!-- Área de Contenido - editable por las páginas -->
+          <div class="max-w-7xl mx-auto w-full">
+            {% block content %}{% endblock %}
+          </div>
         </div>
       </main>
     </div>
@@ -49,4 +64,4 @@
     <!-- Scripts específicos de cada página -->
     {% block scripts %}{% endblock scripts %}
   </body>
-</html>
+</html>

+ 23 - 0
templates/logsView.html

@@ -2,6 +2,29 @@
 {% extends 'layouts/base.html' %}
 {% block styles %}{% endblock styles %}
 
+{% block header_actions %}
+  <div class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4">
+    <div class="filters-container flex gap-4 items-center">
+      <div class="date-filter max-w-xs mx-auto rounded-[0.5rem] shadow-md overflow-hidden relative">
+        <input type="date" id="date-filter" class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-white shadow-sm text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 h-12"/>
+      </div>
+
+      <div class="search-container flex items-center bg-white rounded-[0.5rem] shadow-md overflow-hidden w-[250px] relative">
+        <input type="text" id="username-search" placeholder="Buscar por usuario..." class="search-input w-full pl-4 pr-10 py-3 rounded-[0.5rem] border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-800 h-12"/>
+
+        <!-- Botón de limpiar búsqueda -->
+        <button id="clear-search" class="absolute right-10 h-full items-center justify-center text-gray-400 hover:text-gray-700 hidden" title="Limpiar búsqueda">
+          <i class="fas fa-times"></i>
+        </button>
+
+        <div class="absolute inset-y-0 right-3 flex items-center pointer-events-none">
+          <i class="fas fa-magnifying-glass text-xl text-[#1A8A9D]"></i>
+        </div>
+      </div>
+    </div>
+  </div>
+{% endblock header_actions %}
+
 {% block content %}
     {% include 'partials/logs.html' %}
 {% endblock %}

+ 1 - 1
templates/partials/auditoria.html

@@ -1,5 +1,5 @@
 
-<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
+<div class="w-full space-y-6">
   <div class="bg-white p-6 rounded-lg shadow-lg mb-8">
     <form id="audit-form" class="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-6">
       <div class="lg:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6">

+ 1 - 6
templates/partials/black_list.html

@@ -1,9 +1,4 @@
-<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
-    <div class="bg-gray-100 px-4 py-2 rounded-lg shadow-sm">
-        <span class="text-sm font-medium text-gray-600">
-            Página {{ pagination.page }} de {{ pagination.total_pages }}
-        </span>
-    </div>
+<div class="w-full space-y-6">
 
     <div class="bg-white rounded-lg shadow-md overflow-hidden">
         <div class="px-6 py-4 border-b border-gray-200 bg-gray-50 flex flex-col sm:flex-row justify-between items-center">

+ 1 - 1
templates/partials/cache_stats.html

@@ -1,4 +1,4 @@
-<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
+<div class="w-full space-y-6">
   <div class="flex border-b mb-6">
     <button id="dashboardTab" class="main-tab-btn active relative overflow-hidden py-3 px-6 font-medium text-blue-600">
       <i class="fas fa-tachometer-alt mr-2"></i>Sistema

+ 273 - 257
templates/partials/conexiones.html

@@ -1,284 +1,300 @@
 {% from 'macros.html' import format_bandwidth %}
-{# Tarjetas de estadísticas #}
-<div class="flex justify-center mb-8">
-  <div class="flex flex-wrap justify-center gap-4 w-full pb-2" style="scrollbar-width: none;">
-    {# Tarjeta de información del Servidor Squid --- #}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-indigo-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-server text-indigo-500 text-xl"></i>
-      </div>
-      <div>
-        <p class="text-gray-500 text-sm">
-          Servidor Squid Version:
-        </p>
-        <p class="text-2xl font-bold">{{ squid_version }}</p>
-      </div>
-    </div>
-    {# Tarjeta de Bandwidth Total de Todos los Usuarios #}
-    <div
-      class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-teal-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-tachometer-alt text-teal-500 text-xl"></i>
+<div class="w-full space-y-6">
+  {# Tarjetas de estadísticas #}
+  <div class="flex justify-center mb-8">
+    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-4 gap-3 w-full">
+      {# Tarjeta de información del Servidor Squid #}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-server text-indigo-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs truncate">
+            Servidor Squid:
+          </p>
+          <p class="text-lg font-bold truncate" title="{{ squid_version }}">
+            {{ squid_version }}
+          </p>
+        </div>
       </div>
-      <div>
-        <p class="text-gray-500 text-sm">Total Bandwidth</p>
-        <p class="text-2xl font-bold">
-          {% set total_bw = namespace(value=0) %}
-          {% for user_data in valid_users.values() %}
-            {% for connection in user_data.connections %}
-              {% if connection.bandwidth_kbps is defined %}
-                {% set total_bw.value = total_bw.value + (connection.bandwidth_kbps|float) %}
-              {% endif %}
+
+      {# Tarjeta de Bandwidth Total #}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-teal-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-tachometer-alt text-teal-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Total Bandwidth</p>
+          <p class="text-lg font-bold truncate">
+            {% set total_bw = namespace(value=0) %}
+            {% for user_data in valid_users.values() %}
+              {% for connection in user_data.connections %}
+                {% if connection.bandwidth_kbps is defined %}
+                  {% set total_bw.value = total_bw.value + (connection.bandwidth_kbps|float) %}
+                {% endif %}
+              {% endfor %}
             {% endfor %}
-          {% endfor %}
-          {{ format_bandwidth(total_bw.value) }}
-        </p>
-      </div>
-    </div>
-    {# Tarjeta de Usuarios Activos #}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-users text-blue-500 text-xl"></i>
-      </div>
-      <div>
-        <p class="text-gray-500 text-sm">Usuarios Activos</p>
-        <p class="text-2xl font-bold">{{ valid_users|length }}</p>
-      </div>
-    </div>
-    {# Tarjeta de Conexiones Totales #}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-exchange-alt text-green-500 text-xl"></i>
-      </div>
-      <div>
-        <p class="text-gray-500 text-sm">Conexiones Totales</p>
-        <p class="text-2xl font-bold">
-          {% set total = namespace(value=0) %} 
-          {% for user_data in valid_users.values() %} 
-          {% set total.value = total.value + user_data.connections|length %} 
-          {% endfor %} 
-          {{ total.value }}
-        </p>
-      </div>
-    </div>
-    {# Tiempo de Actividad de Squid #} 
-    {% if squid_info_stats and squid_info_stats.elapsed_hours %}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-clock text-purple-500 text-xl"></i>
-      </div>
-      <div>
-        <p class="text-gray-500 text-sm">Tiempo Activo</p>
-        <p class="text-2xl font-bold">
-          {{ squid_info_stats.elapsed_hours }}h
-        </p>
+            {{ format_bandwidth(total_bw.value) }}
+          </p>
+        </div>
       </div>
-    </div>
-    {% endif %} 
-    {#  Peticiones HTTP Totales #} 
-    {% if squid_info_stats and squid_info_stats.requests_received %}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-globe text-red-500 text-xl"></i>
+
+      {# Tarjeta de Usuarios Activos #}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-users text-blue-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Usuarios Activos</p>
+          <p class="text-lg font-bold">{{ valid_users|length }}</p>
+        </div>
       </div>
-      <div>
-        <p class="text-gray-500 text-sm">Total de Peticiones HTTP</p>
-        <p class="text-2xl font-bold">
-          {{ squid_info_stats.requests_received | int }}
-        </p>
+
+      {# Tarjeta de Conexiones Totales #}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-exchange-alt text-green-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Conexiones Totales</p>
+          <p class="text-lg font-bold">
+            {% set total = namespace(value=0) %} 
+            {% for user_data in valid_users.values() %} 
+            {% set total.value = total.value + user_data.connections|length %} 
+            {% endfor %} 
+            {{ total.value }}
+          </p>
+        </div>
       </div>
-    </div>
-    {% endif %} 
-    {# Promedio de Peticiones por Minuto #} 
-    {% if squid_info_stats and squid_info_stats.avg_requests_per_minute %}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full bg-teal-100 flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas fa-chart-line text-teal-500 text-xl"></i>
+
+      {# Tiempo de Actividad de Squid #} 
+      {% if squid_info_stats and squid_info_stats.elapsed_hours %}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-clock text-purple-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Tiempo Activo</p>
+          <p class="text-lg font-bold">
+            {{ squid_info_stats.elapsed_hours }}h
+          </p>
+        </div>
       </div>
-      <div>
-        <p class="text-gray-500 text-sm">Peticiones/Min Promedio</p>
-        <p class="text-2xl font-bold">
-          {{ squid_info_stats.avg_requests_per_minute|round(1) }}
-        </p>
+      {% endif %} 
+
+      {# Peticiones HTTP Totales #} 
+      {% if squid_info_stats and squid_info_stats.requests_received %}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-globe text-red-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Peticiones HTTP</p>
+          <p class="text-lg font-bold">
+            {{ squid_info_stats.requests_received | int }}
+          </p>
+        </div>
       </div>
-    </div>
-    {% endif %} 
-    {# Estado de Conexión de Squid #} {% if squid_info_stats %}
-    <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-      <div class="w-12 h-12 rounded-full {% if squid_info_stats.connection_status == 'connected' %}bg-green-100{% else %}bg-red-100{% endif %} flex items-center justify-center mr-4 flex-shrink-0">
-        <i class="fas {% if squid_info_stats.connection_status == 'connected' %}fa-check-circle text-green-500{% else %}fa-exclamation-triangle text-red-500{% endif %} text-xl"></i>
+      {% endif %} 
+
+      {# Promedio de Peticiones por Minuto #} 
+      {% if squid_info_stats and squid_info_stats.avg_requests_per_minute %}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full bg-teal-100 flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas fa-chart-line text-teal-500 text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Peticiones/Min</p>
+          <p class="text-lg font-bold">
+            {{ squid_info_stats.avg_requests_per_minute|round(1) }}
+          </p>
+        </div>
       </div>
-      <div>
-        <p class="text-gray-500 text-sm">Estado Squid</p>
-        <p
-          class="text-sm font-bold {% if squid_info_stats.connection_status == 'connected' %}text-green-600{% else %}text-red-600{% endif %}">
-          {% if squid_info_stats.connection_status == 'connected' %}Conectado
-          {% elif squid_info_stats.connection_status == 'connected_but_parse_error' %}Error Parsing 
-          {% elif squid_info_stats.connection_status == 'timeout' %}Timeout 
-          {% elif squid_info_stats.connection_status == 'connection_refused'%}Conexión Rechazada 
-          {% elif squid_info_stats.connection_status == 'dns_error' %}Error DNS 
-          {% else %}Error Desconocido
-          {% endif %}
-        </p>
+      {% endif %} 
+
+      {# Estado de Conexión de Squid #} 
+      {% if squid_info_stats %}
+      <div class="bg-white p-3 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5 min-w-0">
+        <div class="w-10 h-10 rounded-full {% if squid_info_stats.connection_status == 'connected' %}bg-green-100{% else %}bg-red-100{% endif %} flex items-center justify-center mr-3 flex-shrink-0">
+          <i class="fas {% if squid_info_stats.connection_status == 'connected' %}fa-check-circle text-green-500{% else %}fa-exclamation-triangle text-red-500{% endif %} text-lg"></i>
+        </div>
+        <div class="min-w-0 flex-1">
+          <p class="text-gray-500 text-xs">Estado Squid</p>
+          <p class="text-sm font-bold {% if squid_info_stats.connection_status == 'connected' %}text-green-600{% else %}text-red-600{% endif %} truncate">
+            {% if squid_info_stats.connection_status == 'connected' %}Conectado
+            {% elif squid_info_stats.connection_status == 'connected_but_parse_error' %}Error Parsing 
+            {% elif squid_info_stats.connection_status == 'timeout' %}Timeout 
+            {% elif squid_info_stats.connection_status == 'connection_refused'%}Rechazado 
+            {% elif squid_info_stats.connection_status == 'dns_error' %}Error DNS 
+            {% else %}Error
+            {% endif %}
+          </p>
+        </div>
       </div>
+      {% endif %}
     </div>
-    {% endif %}
   </div>
-</div>
-{% if valid_users|length > 0 %}
-<div class="flex justify-end mb-4">
-  <button id="toggle-all-button" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-300">
-    Ver Resumen
-  </button>
-</div>
-{% endif %}
-<div id="user-accordion-group">
-  {% for user, user_data in valid_users.items() %} {% set connections =
-  user_data.connections %} {% set client_ip = user_data.client_ip %}
 
-  <div class="user-accordion bg-white rounded-lg shadow-md mb-3 overflow-hidden">
-    <div class="w-full text-left p-4 border-b bg-white">
-      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
-        <div class="flex items-center mb-3 sm:mb-0">
-          <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0">
-            <i class="fas fa-user text-blue-600"></i>
-          </div>
-          <div>
-            <h2 class="text-lg font-bold text-gray-800">{{ user }}</h2>
-          </div>
-        </div>
+  {# El resto del código permanece igual #}
+  {% if valid_users|length > 0 %}
+  <div class="flex justify-end mb-4">
+    <button id="toggle-all-button" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-300">
+      Ver Resumen
+    </button>
+  </div>
+  {% endif %}
 
-        <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
-          <div class="flex items-center text-sm text-gray-600" title="IP del Cliente">
-            <i class="fas fa-network-wired mr-1.5 text-gray-500"></i>
-            <span>{{ client_ip }}</span>
-          </div>
+  <div id="user-accordion-group">
+    {% for user, user_data in valid_users.items() %} 
+    {% set connections = user_data.connections %} 
+    {% set client_ip = user_data.client_ip %}
 
-          <div class="flex items-center text-sm text-gray-600" title="Conexiones totales de este usuario">
-            <i class="fas fa-link mr-1.5 text-blue-500"></i>
-            <span>{{ connections|length }} conexiones</span>
-          </div>
-          {% set user_bw = namespace(value=0) %}
-          {% for connection in connections %}
-            {% if connection.bandwidth_kbps is defined %}
-              {% set user_bw.value = user_bw.value + (connection.bandwidth_kbps|float) %}
-            {% endif %}
-          {% endfor %}
-          <div class="flex items-center text-sm text-gray-600" title="Total de velocidad del usuario">
-            <i class="fas fa-tachometer-alt mr-1.5 text-teal-500"></i>
-            <span>
-              {{ format_bandwidth(user_bw.value) }}
-            </span>
+    <div class="user-accordion bg-white rounded-lg shadow-md mb-3 overflow-hidden">
+      <div class="w-full text-left p-4 border-b bg-white">
+        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
+          <div class="flex items-center mb-3 sm:mb-0">
+            <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0">
+              <i class="fas fa-user text-blue-600"></i>
+            </div>
+            <div class="min-w-0">
+              <h2 class="text-lg font-bold text-gray-800 truncate" title="{{ user }}">{{ user }}</h2>
+            </div>
           </div>
 
-          {% set total_data = namespace(value=0) %} 
-          {% set total_requests = namespace(value=0) %} 
-          {% for connection in connections %} 
-            {% if connection.fd_total != "N/A" %} 
-              {% set total_data.value = total_data.value + connection.fd_total %} 
-            {% endif %} 
-            {% set total_requests.value = total_requests.value + connection.nrequests %} 
-          {% endfor %}
+          <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
+            <div class="flex items-center text-sm text-gray-600" title="IP del Cliente">
+              <i class="fas fa-network-wired mr-1.5 text-gray-500"></i>
+              <span class="truncate max-w-[120px]">{{ client_ip }}</span>
+            </div>
 
-          <div class="flex items-center text-sm text-gray-600" title="Total de datos transferidos">
-            <i class="fas fa-database mr-1.5 text-green-500"></i>
-            <span>{{ (total_data.value / 1024 / 1024)|round(2) }} MB</span>
-          </div>
+            <div class="flex items-center text-sm text-gray-600" title="Conexiones totales de este usuario">
+              <i class="fas fa-link mr-1.5 text-blue-500"></i>
+              <span>{{ connections|length }} conexiones</span>
+            </div>
+            
+            {% set user_bw = namespace(value=0) %}
+            {% for connection in connections %}
+              {% if connection.bandwidth_kbps is defined %}
+                {% set user_bw.value = user_bw.value + (connection.bandwidth_kbps|float) %}
+              {% endif %}
+            {% endfor %}
+            
+            <div class="flex items-center text-sm text-gray-600" title="Total de velocidad del usuario">
+              <i class="fas fa-tachometer-alt mr-1.5 text-teal-500"></i>
+              <span class="truncate max-w-[100px]">
+                {{ format_bandwidth(user_bw.value) }}
+              </span>
+            </div>
 
-          <div class="flex items-center text-sm text-gray-600" title="Total de solicitudes">
-            <i class="fas fa-bullhorn mr-1.5 text-purple-500"></i>
-            <span>{{ total_requests.value }} solicitudes</span>
-          </div>
-          <div class="w-6 text-center">
-            <i class="fas fa-chevron-down transition-transform duration-300 rotate-180"></i>
+            {% set total_data = namespace(value=0) %} 
+            {% set total_requests = namespace(value=0) %} 
+            {% for connection in connections %} 
+              {% if connection.fd_total != "N/A" %} 
+                {% set total_data.value = total_data.value + connection.fd_total %} 
+              {% endif %} 
+              {% set total_requests.value = total_requests.value + connection.nrequests %} 
+            {% endfor %}
+
+            <div class="hidden md:flex items-center text-sm text-gray-600" title="Total de datos transferidos">
+              <i class="fas fa-database mr-1.5 text-green-500"></i>
+              <span>{{ (total_data.value / 1024 / 1024)|round(2) }} MB</span>
+            </div>
+
+            <div class="hidden lg:flex items-center text-sm text-gray-600" title="Total de solicitudes">
+              <i class="fas fa-bullhorn mr-1.5 text-purple-500"></i>
+              <span>{{ total_requests.value }} solicitudes</span>
+            </div>
+            
+            <div class="w-6 text-center">
+              <i class="fas fa-chevron-down transition-transform duration-300 rotate-180"></i>
+            </div>
           </div>
         </div>
       </div>
-    </div>
 
-    <div data-accordion-content>
-      <div class="overflow-x-auto">
-        <table class="min-w-full divide-y divide-gray-200">
-          <thead class="bg-gray-50">
-            <tr>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Duración
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Método
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                URL
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Datos
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Velocidad
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Delay Pool
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Solicitudes
-              </th>
-              <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
-                Dir. Remota
-              </th>
-            </tr>
-          </thead>
-          <tbody class="divide-y divide-gray-200">
-            {% for connection in connections %}
-            <tr class="transition-colors duration-200 ease-in-out hover:bg-gray-50">
-              <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
-                {% set seconds = connection.elapsed_time|float %} 
-                {% if seconds >= 3600 %}{{ "%.2f"|format(seconds/3600) }} h 
-                {% elif seconds >= 60 %}{{ "%.2f"|format(seconds/60) }} min {% else %}
-                {{ "%.2f"|format(seconds) }} seg
-                {% endif %}
-              </td>
-              <td class="px-4 py-3 whitespace-nowrap">
-                {% set method = connection.logType|lower %}
-                <span class="px-2 py-1 rounded-full text-xs font-semibold ... {% if method == 'connect' or method == 'tcp_tunnel' %}bg-green-100 text-green-800 ... {% endif %}">
-                  {{ connection.logType }}
-                </span>
-              </td>
-              <td class="px-4 py-3 max-w-xs">
-                <div class="truncate text-sm transition-colors duration-200 hover:text-blue-600"
-                  title="{{ connection.uri }}">
-                  {{ connection.uri }}
-                </div>
-              </td>
-              <td class="px-4 py-3 whitespace-nowrap text-sm">
-                {% if connection.fd_total != "N/A" %}
-                  {{ (connection.fd_total / 1024 / 1024)|round(2) }} MB 
-                  {% else %}N/A
-                {% endif %}
-              </td>
-              <td class="px-4 py-3 whitespace-nowrap text-sm">
-                {{ format_bandwidth(connection.bandwidth_kbps) }}
-              </td>
-              <td class="px-4 py-3 whitespace-nowrap">
-                {% if connection.delay_pool != "N/A" %} 
-                  {% set pool = connection.delay_pool|string %}
-                  <span class="px-2 py-1 rounded-full text-xs font-semibold ... {% if pool == '0' %}bg-sky-100 text-sky-800 ... {% endif %}">
-                    Pool {{ connection.delay_pool }}
+      <div data-accordion-content>
+        <div class="overflow-x-auto">
+          <table class="min-w-full divide-y divide-gray-200">
+            <thead class="bg-gray-50">
+              <tr>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Duración
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Método
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  URL
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Datos
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Velocidad
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Delay Pool
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Solicitudes
+                </th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">
+                  Dir. Remota
+                </th>
+              </tr>
+            </thead>
+            <tbody class="divide-y divide-gray-200">
+              {% for connection in connections %}
+              <tr class="transition-colors duration-200 ease-in-out hover:bg-gray-50">
+                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
+                  {% set seconds = connection.elapsed_time|float %} 
+                  {% if seconds >= 3600 %}{{ "%.2f"|format(seconds/3600) }} h 
+                  {% elif seconds >= 60 %}{{ "%.2f"|format(seconds/60) }} min {% else %}
+                  {{ "%.2f"|format(seconds) }} seg
+                  {% endif %}
+                </td>
+                <td class="px-4 py-3 whitespace-nowrap">
+                  {% set method = connection.logType|lower %}
+                  <span class="px-2 py-1 rounded-full text-xs font-semibold ... {% if method == 'connect' or method == 'tcp_tunnel' %}bg-green-100 text-green-800 ... {% endif %}">
+                    {{ connection.logType }}
                   </span>
-                  
-                {% endif %}
-              </td>
-              <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
-                {{ connection.nrequests }}
-              </td>
-              <td class="px-4 py-3 whitespace-nowrap text-sm font-mono ... hover:text-blue-600">
-                {{ connection.proxy_local_ip }}
-              </td>
-            </tr>
-            {% endfor %}
-          </tbody>
-        </table>
+                </td>
+                <td class="px-4 py-3 max-w-xs">
+                  <div class="truncate text-sm transition-colors duration-200 hover:text-blue-600"
+                    title="{{ connection.uri }}">
+                    {{ connection.uri }}
+                  </div>
+                </td>
+                <td class="px-4 py-3 whitespace-nowrap text-sm">
+                  {% if connection.fd_total != "N/A" %}
+                    {{ (connection.fd_total / 1024 / 1024)|round(2) }} MB 
+                    {% else %}N/A
+                  {% endif %}
+                </td>
+                <td class="px-4 py-3 whitespace-nowrap text-sm">
+                  {{ format_bandwidth(connection.bandwidth_kbps) }}
+                </td>
+                <td class="px-4 py-3 whitespace-nowrap">
+                  {% if connection.delay_pool != "N/A" %} 
+                    {% set pool = connection.delay_pool|string %}
+                    <span class="px-2 py-1 rounded-full text-xs font-semibold ... {% if pool == '0' %}bg-sky-100 text-sky-800 ... {% endif %}">
+                      Pool {{ connection.delay_pool }}
+                    </span>
+                  {% endif %}
+                </td>
+                <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
+                  {{ connection.nrequests }}
+                </td>
+                <td class="px-4 py-3 whitespace-nowrap text-sm font-mono ... hover:text-blue-600">
+                  {{ connection.proxy_local_ip }}
+                </td>
+              </tr>
+              {% endfor %}
+            </tbody>
+          </table>
+        </div>
       </div>
     </div>
+    {% endfor %}
   </div>
-  {% endfor %}
-</div>
+ </div>

+ 53 - 95
templates/partials/graph_reports.html

@@ -1,69 +1,41 @@
-  <header class="mb-8">
-    <div class="flex flex-wrap justify-between mt-4">
-      <div
-        class="bg-white p-4 rounded-lg shadow-md w-full md:w-auto mb-4 md:mb-0">
-        <h3 class="text-lg font-semibold text-gray-700">
-          Usuarios Totales
-        </h3>
-        <p class="text-2xl font-bold text-blue-600">
-          {{ metrics.total_stats.total_users }}
-        </p>
-      </div>
-      <div
-        class="bg-white p-4 rounded-lg shadow-md w-full md:w-auto mb-4 md:mb-0">
-        <h3 class="text-lg font-semibold text-gray-700">
-          Registros de Log
-        </h3>
-        <p class="text-2xl font-bold text-green-600">
-          {{ metrics.total_stats.total_log_entries }}
-        </p>
-      </div>
-      <div
-        class="bg-white p-4 rounded-lg shadow-md w-full md:w-auto mb-4 md:mb-0">
-        <h3 class="text-lg font-semibold text-gray-700">
-          Datos Transmitidos
-        </h3>
-        <p class="text-2xl font-bold text-purple-600">
-          {{ "%.2f"|format(metrics.total_stats.total_data_transmitted /
-          (1024**3)) }} GB
-        </p>
-      </div>
-      <div class="bg-white p-4 rounded-lg shadow-md w-full md:w-auto">
-        <h3 class="text-lg font-semibold text-gray-700">Total Requests</h3>
-        <p class="text-2xl font-bold text-orange-600">
-          {{ metrics.total_stats.total_requests }}
-        </p>
-      </div>
-      <div class="w-full md:w-auto flex items-center md:ml-4 mt-4 md:mt-0">
-        <div
-          class="bg-white p-4 rounded-lg shadow-md border border-gray-200 hover:shadow-lg transition-shadow duration-200">
-          <h3 class="text-lg font-semibold text-gray-700">
-            Filtrar por Fecha
-          </h3>
-          <div class="reports-date-picker flex items-center gap-2">
-            <div
-              class="flex items-center justify-center w-8 h-8 bg-indigo-50 rounded-md">
-              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
-                <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3M3 11h18M5 21h14a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2z"/>
-              </svg>
-            </div>
-
-            <input id="reports-date" type="text" datepicker datepicker-orientation="bottom" datepicker-autohide datepicker-container="body" class="flex-1 min-w-0 w-32 rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder-gray-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200"/>
-
-            <button id="reports-go" class="inline-flex items-center justify-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
-              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
-                <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
-              </svg>
-              Ver
-            </button>
-          </div>
-        </div>
-      </div>
+<div class="w-full space-y-6">
+  <!-- Tarjetas de métricas principales -->
+  <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
+    <div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
+      <h3 class="text-lg font-semibold text-gray-700">
+        Usuarios Totales
+      </h3>
+      <p class="text-2xl font-bold text-blue-600">
+        {{ metrics.total_stats.total_users }}
+      </p>
+    </div>
+    <div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
+      <h3 class="text-lg font-semibold text-gray-700">
+        Registros de Log
+      </h3>
+      <p class="text-2xl font-bold text-green-600">
+        {{ metrics.total_stats.total_log_entries }}
+      </p>
+    </div>
+    <div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
+      <h3 class="text-lg font-semibold text-gray-700">
+        Datos Transmitidos
+      </h3>
+      <p class="text-2xl font-bold text-purple-600">
+        {{ "%.2f"|format(metrics.total_stats.total_data_transmitted / (1024**3)) }} GB
+      </p>
     </div>
-  </header>
+    <div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
+      <h3 class="text-lg font-semibold text-gray-700">Total Requests</h3>
+      <p class="text-2xl font-bold text-orange-600">
+        {{ metrics.total_stats.total_requests }}
+      </p>
+    </div>
+  </div>
 
-  <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
-    <div class="bg-white p-6 rounded-lg shadow-md">
+  <!-- Gráficos principales -->
+  <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
+    <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
       <h2 class="text-xl font-bold mb-4 text-gray-800">
         Top 20 Usuarios por Actividad
       </h2>
@@ -72,7 +44,7 @@
       </div>
     </div>
 
-    <div class="bg-white p-6 rounded-lg shadow-md">
+    <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
       <h2 class="text-xl font-bold mb-4 text-gray-800">
         Top 20 Usuarios por Datos Transmitidos
       </h2>
@@ -82,7 +54,8 @@
     </div>
   </div>
 
-  <div class="bg-white p-6 rounded-lg shadow-md mb-8">
+  <!-- Gráfico de códigos HTTP -->
+  <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
     <h2 class="text-xl font-bold mb-4 text-gray-800">
       Distribución de Códigos HTTP
     </h2>
@@ -91,7 +64,8 @@
     </div>
   </div>
 
-  <div class="bg-white p-6 rounded-lg shadow-md mb-8">
+  <!-- Tabla de páginas más visitadas -->
+  <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
     <h2 class="text-xl font-bold mb-4 text-gray-800">
       Top 20 Páginas Más Visitadas
     </h2>
@@ -99,24 +73,16 @@
       <table class="min-w-full divide-y divide-gray-200">
         <thead class="bg-gray-50">
           <tr>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               URL
             </th>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               Total Requests
             </th>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               Visitas Únicas
             </th>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               Datos Transmitidos
             </th>
           </tr>
@@ -124,9 +90,7 @@
         <tbody class="bg-white divide-y divide-gray-200">
           {% for page in metrics.top_pages %}
           <tr class="hover:bg-gray-50">
-            <td
-              class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 truncate max-w-xs"
-            >
+            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 truncate max-w-xs">
               {{ page.url }}
             </td>
             <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
@@ -145,7 +109,8 @@
     </div>
   </div>
 
-  <div class="bg-white p-6 rounded-lg shadow-md">
+  <!-- Tabla de IPs compartidas -->
+  <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
     <h2 class="text-xl font-bold mb-4 text-gray-800">
       IPs Compartidas por Múltiples Usuarios
     </h2>
@@ -153,19 +118,13 @@
       <table class="min-w-full divide-y divide-gray-200">
         <thead class="bg-gray-50">
           <tr>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               IP
             </th>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               Número de Usuarios
             </th>
-            <th
-              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-            >
+            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
               Usuarios
             </th>
           </tr>
@@ -173,9 +132,7 @@
         <tbody class="bg-white divide-y divide-gray-200">
           {% for ip in metrics.users_per_ip %}
           <tr class="hover:bg-gray-50">
-            <td
-              class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"
-            >
+            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
               {{ ip.ip }}
             </td>
             <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
@@ -190,3 +147,4 @@
       </table>
     </div>
   </div>
+</div>

+ 1 - 22
templates/partials/logs.html

@@ -1,25 +1,4 @@
-<div class="users-dashboard max-w-[1200px] mx-auto p-8">
-  <div class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4">
-    <div class="filters-container flex gap-4 items-center">
-      <div class="date-filter max-w-xs mx-auto rounded-[0.5rem] shadow-md overflow-hidden relative">
-        <input type="date" id="date-filter" class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-white shadow-sm text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 h-12"/>
-      </div>
-
-      <div class="search-container flex items-center bg-white rounded-[0.5rem] shadow-md overflow-hidden w-[250px] relative">
-        <input type="text" id="username-search" placeholder="Buscar por usuario..." class="search-input w-full pl-4 pr-10 py-3 rounded-[0.5rem] border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-800 h-12"/>
-
-        <!-- Botón de limpiar búsqueda -->
-        <button id="clear-search" class="absolute right-10 h-full items-center justify-center text-gray-400 hover:text-gray-700 hidden" title="Limpiar búsqueda">
-          <i class="fas fa-times"></i>
-        </button>
-
-        <div class="absolute inset-y-0 right-3 flex items-center pointer-events-none">
-          <i class="fas fa-magnifying-glass text-xl text-[#1A8A9D]"></i>
-        </div>
-      </div>
-    </div>
-  </div>
-
+<div class="w-full space-y-6">
   <div class="users-container grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 max-w-screen-xl mx-auto px-4" id="users-container"></div>
   <div id="modals-container"></div>
   <div class="pagination-container flex justify-center items-center mt-12 gap-4">

+ 25 - 1
templates/reports.html

@@ -1,5 +1,29 @@
-
 {% extends 'layouts/base.html' %}
+
+{% block header_actions %}
+  <!-- Filtro de fecha en el header -->
+  <div class="flex flex-col xs:flex-row items-stretch xs:items-center gap-2 w-full xs:w-auto">
+    <div class="bg-white p-3 rounded-lg shadow-sm border border-gray-200 hover:shadow-lg transition-shadow duration-200 flex-shrink-0">
+      <div class="reports-date-picker flex items-center gap-2">
+        <div class="flex items-center justify-center w-6 h-6 bg-indigo-50 rounded-md">
+          <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
+            <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3M3 11h18M5 21h14a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2z"/>
+          </svg>
+        </div>
+
+        <input id="reports-date" type="text" datepicker datepicker-orientation="bottom" datepicker-autohide datepicker-container="body" class="w-28 xs:w-32 rounded-md border border-gray-300 bg-white px-2 py-1 text-sm text-gray-900 placeholder-gray-500 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 transition-colors duration-200"/>
+
+        <button id="reports-go" class="inline-flex items-center justify-center px-2 py-1 border border-transparent text-xs xs:text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
+          <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
+            <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
+          </svg>
+          Ver
+        </button>
+      </div>
+    </div>
+  </div>
+{% endblock %}
+
 {% block styles %}
     <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
     <script src="{{ url_for('static', filename='js/chart.js') }}"></script>