Parcourir la source

feat: Enhance dashboard functionality and UI

- Implemented detailed and summary view toggle for user connections in the dashboard.
- Updated connection refresh logic to maintain view state after updates.
- Redesigned user connection cards to display additional information, including server and proxy status.
- Added a new utility function to convert size strings to bytes for better data handling.
- Improved overall layout and responsiveness of connection statistics and user details.
Manuel il y a 1 an
Parent
commit
170bb97287

+ 232 - 14
app.py

@@ -34,6 +34,238 @@ class Config:
 
 load_dotenv()
 
+# Initialize Flask application
+app = Flask(__name__, static_folder='./static')
+app.config.from_object(Config())
+scheduler = APScheduler()
+app.secret_key = os.urandom(24).hex()
+scheduler.init_app(app)
+scheduler.start()
+
+# Configure logging
+logging.basicConfig(
+    level=logging.INFO,
+    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+logger = logging.getLogger(__name__)
+
+@app.route('/')
+def index():
+    try:
+        raw_data = fetch_squid_data()
+        if 'Error' in raw_data:
+            logger.error(f"Failed to fetch Squid data: {raw_data}")
+            return render_template('error.html', message="Error connecting to Squid"), 500
+
+        connections = parse_raw_data(raw_data)
+        grouped_connections = group_by_user(connections)
+
+        return render_template(
+            'index.html',
+            grouped_connections=grouped_connections, page_icon='favicon.ico', page_title='Inicio Dashboard')
+
+    except Exception as e:
+        logger.error(f"Unexpected error in index route: {str(e)}")
+        return render_template('error.html', message="An unexpected error occurred"), 500
+
+@app.route('/actualizar-conexiones')
+def actualizar_conexiones():
+    try:
+        raw_data = fetch_squid_data()
+        if 'Error' in raw_data:
+            logger.error(f"Failed to fetch Squid data: {raw_data}")
+            return "Error", 500
+
+        connections = parse_raw_data(raw_data)
+        grouped_connections = group_by_user(connections)
+        return render_template('partials/conexiones.html', grouped_connections=grouped_connections)
+
+    except Exception as e:
+        logger.error(f"Unexpected error in /actualizar-conexiones route: {str(e)}")
+        return "Error interno", 500
+
+@app.route('/stats')
+def cache_stats():
+    try:
+        data = fetch_squid_cache_stats()
+        stats_data = vars(data) if hasattr(data, '__dict__') else data
+        logger.info("Successfully fetched cache statistics")
+        return render_template('cacheView.html', cache_stats=stats_data, page_icon='statistics.ico', page_title='Estadísticas')
+
+    except Exception as e:
+        logger.error(f"Error fetching cache stats: {str(e)}")
+        return render_template('error.html', message="Error retrieving cache statistics"), 500
+
+@app.route('/logs')
+def logs():
+    try:
+        db = get_session()
+        users_data = get_users_logs(db)
+
+        return render_template('logsView.html', users_data=users_data, page_icon='user.ico', page_title='Actividad usuarios' )
+    except Exception as e:
+        print(f"Error en ruta /logs: {e}")
+        return render_template('error.html', message="Error retrieving logs"), 500
+
+@scheduler.task('interval', id='do_job_1', seconds=30, misfire_grace_time=900)
+def init_scheduler():
+    """Initialize and start the background scheduler for log processing"""
+    log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
+    logger.info(f"Configurando scheduler para el archivo de log: {log_file}")
+
+    if not os.path.exists(log_file):
+        logger.error(f"Archivo de log no encontrado: {log_file}")
+        return
+    else:
+        process_logs(log_file)
+
+@app.template_filter('divide')
+def divide_filter(value, divisor):
+    return value / divisor
+
+@app.template_filter('format_bytes')
+def format_bytes_filter(value):
+    value = int(value)
+    if value >= 1024**3:  # GB
+        return f"{(value / (1024**3)):.2f} GB"
+    elif value >= 1024**2:  # MB
+        return f"{(value / (1024**2)):.2f} MB"
+    elif value >= 1024:  # KB
+        return f"{(value / 1024):.2f} KB"
+    return f"{value} bytes"
+
+@app.route('/get-logs-by-date', methods=['POST'])
+def get_logs_by_date():
+    db = None
+    try:
+        date_str = request.json.get('date')
+        selected_date = datetime.strptime(date_str, '%Y-%m-%d')
+        date_suffix = selected_date.strftime('%Y%m%d')
+
+        db = get_session()
+
+        users_data = get_users_with_logs_by_date(db, date_suffix)
+        return jsonify(users_data)
+
+    except ValueError as ve:
+        return jsonify({'error': 'Formato de fecha inválido'}), 400
+    except Exception as e:
+        print(f"Error: {e}")
+        return jsonify({'error': str(e)}), 500
+    finally:
+        if db is not None:
+            db.close()
+
+@app.route('/reports')
+def reports():
+    db = None
+    try:
+        db = get_session()
+        current_date = datetime.now().strftime("%Y%m%d")
+        logger.info(f"Generando reportes para la fecha: {current_date}")
+        UserModel, LogModel = get_dynamic_models(current_date)
+
+        if not UserModel or not LogModel:
+            return render_template('error.html', message="Error al cargar datos para reportes"), 500
+
+        metrics = get_important_metrics(db, UserModel, LogModel)
+
+        if not metrics:
+            return render_template('error.html', message="No hay datos disponibles para reportes"), 404
+
+        http_codes = metrics.get('http_response_distribution', [])
+        http_codes = sorted(http_codes, key=lambda x: x['count'], reverse=True)
+        main_codes = http_codes[:8]
+        other_codes = http_codes[8:]
+
+        if other_codes:
+            other_count = sum(item['count'] for item in other_codes)
+            main_codes.append({'response_code': 'Otros', 'count': other_count})
+
+        metrics['http_response_distribution_chart'] = {
+            'labels': [str(item['response_code']) for item in main_codes],
+            'data': [item['count'] for item in main_codes],
+            'colors': [color_map.get(str(item['response_code']), color_map['Otros']) for item in main_codes]
+        }
+
+        return render_template('reports.html', metrics=metrics, page_icon='bar.ico', page_title='Reportes y gráficas')
+    except Exception as e:
+        logger.error(f"Error en ruta /reports: {str(e)}", exc_info=True)
+        return render_template('error.html', message="Error interno generando reportes"), 500
+    finally:
+        if db:
+            db.close()
+
+@app.route('/install', methods=['POST'])
+def install_package():
+    install = update_squid()
+    if install == False:
+        return redirect('/')
+    else:
+        return redirect('/')
+
+@app.route('/update', methods=['POST'])
+def update_web():
+    install = updateSquidStats()
+    if install == False:
+        return redirect('/')
+    else:
+        return redirect('/')
+
+@app.route('/blacklist', methods=['GET'])
+def blacklist_logs():
+    db = None
+    try:
+        # Obtener parámetros de paginación
+        page = request.args.get('page', 1, type=int)
+        per_page = request.args.get('per_page', 20, type=int)
+
+        # Validar parámetros
+        if page < 1 or per_page < 1 or per_page > 100:
+            return render_template('error.html',
+                                   message="Parámetros de paginación inválidos"), 400
+
+        db = get_session()
+
+        # Obtener blacklist desde variables de entorno
+        blacklist_env = os.getenv('BLACKLIST_DOMAINS')
+        blacklist = [domain.strip() for domain in blacklist_env.split(',') if domain.strip()]
+
+        # Obtener resultados paginados
+        result_data = find_blacklisted_sites(db, blacklist, page, per_page)
+
+        if 'error' in result_data:
+            return render_template('error.html',
+                                   message=result_data['error']), 500
+
+        return render_template(
+            'blacklist.html',
+            results=result_data['results'],
+            pagination=result_data['pagination'],
+            current_page=page,
+            page_icon='shield-exclamation.ico',
+            page_title='Registros Bloqueados'
+        )
+
+    except ValueError:
+        return render_template('error.html',
+                               message="Parámetros inválidos"), 400
+
+    except Exception as e:
+        logger.error(f"Error en blacklist_logs: {str(e)}")
+        return render_template('error.html',
+                               message="Error interno del servidor"), 500
+
+    finally:
+        if db is not None:
+            db.close()
+
+if __name__ == "__main__":
+
+    # Execute app with Flask
+    debug_mode = os.getenv("FLASK_DEBUG", "false").lower() == "true"
+    app.run(debug=debug_mode, host='0.0.0.0', port=5000)
+
 app = Flask(__name__, static_folder='./static')
 app.config.from_object(Config())
 app.config["TEMPLATES_AUTO_RELOAD"] = True
@@ -52,24 +284,18 @@ logging.basicConfig(
 )
 logger = logging.getLogger(__name__)
 
-# Bloqueo para acceso seguro a las variables compartidas entre hilos
 realtime_data_lock = Lock()
-# Almacenamiento de las últimas estadísticas de caché
 realtime_cache_stats = {}
-# Almacenamiento de la última información del sistema
 realtime_system_info = {}
 
 def realtime_data_thread():
-    """Hilo que actualiza los datos del sistema y caché periódicamente y los envía a los clientes via WebSocket"""
     global realtime_cache_stats, realtime_system_info
 
     while True:
         try:
-            # Obtener estadísticas de caché de Squid
             cache_data = fetch_squid_cache_stats()
             cache_stats = vars(cache_data) if hasattr(cache_data, '__dict__') else cache_data
             
-            # Obtener información del sistema
             system_info = {
                 'hostname': socket.gethostname(),
                 'ips': get_network_info(),
@@ -84,7 +310,6 @@ def realtime_data_thread():
                 'local_time': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
             }
             
-            # Obtener estadísticas de red
             network_stats = get_network_stats()
             
             # Actualizar las variables globales con bloqueo
@@ -92,36 +317,29 @@ def realtime_data_thread():
                 realtime_cache_stats = cache_stats
                 realtime_system_info = system_info
             
-            # Emitir los datos actualizados a todos los clientes
             socketio.emit('system_update', {
                 'cache_stats': cache_stats,
                 'system_info': system_info,
                 'network_stats': network_stats
             })
             
-            #logger.info("Datos en tiempo real actualizados y emitidos")
             
         except Exception as e:
             logger.error(f"Error en hilo de datos en tiempo real: {str(e)}")
         
-        # Esperar 5 segundos antes de la próxima actualización
         eventlet.sleep(5)
 
 
 #Manejador de conexión WebSocket
 @socketio.on('connect')
 def handle_connect():
-    """Manejador para cuando un cliente se conecta a través de WebSocket"""
     logger.info(f"Cliente conectado: {request.sid}")
     
-    # Enviar los datos actuales al cliente que se acaba de conectar
     with realtime_data_lock:
         cache_stats = realtime_cache_stats
         system_info = realtime_system_info
 
-    # Ahora que las variables están definidas, puedes compararlas o usarlas
     if cache_stats or system_info:  # solo si hay datos válidos
-        # Obtener estadísticas de red para el cliente recién conectado
         network_stats = get_network_stats()
         socketio.emit('system_update', {
             'cache_stats': cache_stats,

+ 13 - 1
database/database.py

@@ -69,6 +69,16 @@ class DeniedLog(Base):
     data_transmitted = Column(BigInteger, default=0)
     created_at = Column(DateTime, default=datetime.now)
 
+class Metrics(Base):
+    __tablename__ = "metrics"
+    id = Column(Integer, primary_key=True)
+    timestamp = Column(DateTime, default=datetime.now)
+    cpu_usage = Column(Integer, nullable=False)
+    ram_usage_bytes = Column(BigInteger, nullable=False)
+    swap_usage_bytes = Column(BigInteger, nullable=False)
+    net_sent_bytes_sec = Column(BigInteger, nullable=False)
+    net_recv_bytes_sec = Column(BigInteger, nullable=False)
+
 def get_database_url() -> str:
     db_type = os.getenv("DATABASE_TYPE", "SQLITE").upper()
     conn_str = os.getenv("DATABASE_STRING_CONNECTION", "squidstats.db")
@@ -109,11 +119,13 @@ def create_dynamic_tables(engine):
     user_table, log_table = get_dynamic_table_names()
     metadata_table = LogMetadata.__tablename__
     denied_table = DeniedLog.__tablename__
+    metrics_table = Metrics.__tablename__
     for table_cls, table_name in [
         (User, user_table),
         (Log, log_table),
         (LogMetadata, metadata_table),
-        (DeniedLog, denied_table)
+        (DeniedLog, denied_table),
+        (Metrics, metrics_table)
     ]:
         if not table_exists(engine, table_name):
             logger.info(f"Creando tabla: {table_name}")

+ 37 - 4
parsers/cache.py

@@ -34,9 +34,9 @@ def parse_squid_cache_data(data):
         "second_level_dirs": r"Second level subdirectories: (\d+)",
         "filemap_bits_used": r"Filemap bits in use: (\d+) of (\d+)",
         "filemap_bits_total": r"Filemap bits in use: \d+ of (\d+)",
-        "fs_space_used": r"Filesystem Space in use: (\d+)/\d+ KB",
+        "fs_space_used": r"Filesystem Space in use: (\d+)/(\d+) KB",
         "fs_space_total": r"Filesystem Space in use: \d+/(\d+) KB",
-        "fs_inodes_used": r"Filesystem Inodes in use: (\d+)/\d+",
+        "fs_inodes_used": r"Filesystem Inodes in use: (\d+)/(\d+)",
         "fs_inodes_total": r"Filesystem Inodes in use: \d+/(\d+)",
         "removal_policy": r"Removal policy: (\w+)",
         "lru_age_days": r"LRU reference age: ([\d\.]+) days",
@@ -46,6 +46,39 @@ def parse_squid_cache_data(data):
         match = re.search(pattern, data)
         if match:
             stats[key] = match.group(1) if key != "current_swap_size" else float(match.group(1))
-    stats["fs_space_total"] = int(stats["fs_space_total"])
-    stats["fs_space_used"] = int(stats["fs_space_used"])
+
+    # Robustecer: asegurar que todas las claves esperadas existan, con valor 0 o None si no se encontraron
+    defaults = {
+        "store_entries": 0,
+        "max_swap_size": 0,
+        "current_swap_size": 0.0,
+        "capacity_used": 0.0,
+        "capacity_free": 0.0,
+        "store_directory": None,
+        "fs_block_size": 0,
+        "first_level_dirs": 0,
+        "second_level_dirs": 0,
+        "filemap_bits_used": 0,
+        "filemap_bits_total": 0,
+        "fs_space_used": 0,
+        "fs_space_total": 0,
+        "fs_inodes_used": 0,
+        "fs_inodes_total": 0,
+        "removal_policy": None,
+        "lru_age_days": 0.0,
+    }
+    for key, default in defaults.items():
+        if key not in stats or stats[key] is None:
+            stats[key] = default
+    # Convertir a int/float según corresponda
+    for key in ["store_entries", "max_swap_size", "fs_block_size", "first_level_dirs", "second_level_dirs", "filemap_bits_used", "filemap_bits_total", "fs_space_used", "fs_space_total", "fs_inodes_used", "fs_inodes_total"]:
+        try:
+            stats[key] = int(stats[key])
+        except (ValueError, TypeError):
+            stats[key] = 0
+    for key in ["current_swap_size", "capacity_used", "capacity_free", "lru_age_days"]:
+        try:
+            stats[key] = float(stats[key])
+        except (ValueError, TypeError):
+            stats[key] = 0.0
     return stats

+ 14 - 28
parsers/connections.py

@@ -1,7 +1,6 @@
 import re
 from collections import defaultdict
 
-# Precompilar todas las expresiones regulares para mejor rendimiento
 REGEX_MAP = {
     "fd": re.compile(r"FD (\d+)"),
     "uri": re.compile(r"uri (.+)"),
@@ -9,8 +8,8 @@ REGEX_MAP = {
     "logType": re.compile(r"logType (.+)"),
     "start": re.compile(r"start ([\d.]+)"),
     "elapsed_time": re.compile(r"start .*?\(([\d.]+) seconds ago\)"),
-    "remote": re.compile(r"remote: ([\d.]+:\d+)"),
-    "local": re.compile(r"local: ([\d.]+:\d+)"),
+    "client_ip": re.compile(r"remote: ([\d.]+:\d+)"), # IP del cliente
+    "proxy_local_ip": re.compile(r"local: ([\d.]+:\d+)"), # IP del proxy
     "fd_read": re.compile(r"read (\d+)"),
     "fd_wrote": re.compile(r"wrote (\d+)"),
     "nrequests": re.compile(r"nrequests: (\d+)"),
@@ -19,73 +18,60 @@ REGEX_MAP = {
 
 def parse_raw_data(raw_data):
     connections = []
-    blocks = raw_data.split("Connection:")[1:]  # Ignorar el primer vacío
+    blocks = raw_data.split("Connection:")[1:]
     
     for block in blocks:
         try:
             connection = parse_connection_block(block)
             connections.append(connection)
         except Exception as e:
-            # Registrar error pero continuar procesando
-            print(f"Error parsing block: {e}\n{block[:100]}...")
+            # Imprime un error pero permite que el script continúe
+            print(f"Error parseando bloque: {e}\n{block[:100]}...")
     
     return connections
 
 def parse_connection_block(block):
     conn = {}
     
-    # Extraer campos simples
     for key, regex in REGEX_MAP.items():
         if key not in ["fd_read", "fd_wrote", "nrequests", "delay_pool", "fd_total"]:
             match = regex.search(block)
             conn[key] = match.group(1) if match else "N/A"
     
-    # Manejar campos numéricos especiales
     conn["fd_read"] = int(REGEX_MAP["fd_read"].search(block).group(1)) if REGEX_MAP["fd_read"].search(block) else 0
     conn["fd_wrote"] = int(REGEX_MAP["fd_wrote"].search(block).group(1)) if REGEX_MAP["fd_wrote"].search(block) else 0
     conn["fd_total"] = conn["fd_read"] + conn["fd_wrote"]
     
     conn["nrequests"] = int(REGEX_MAP["nrequests"].search(block).group(1)) if REGEX_MAP["nrequests"].search(block) else 0
-    conn["delay_pool"] = int(REGEX_MAP["delay_pool"].search(block).group(1)) if REGEX_MAP["delay_pool"].search(block) else "N/A"
-    
+    conn["delay_pool"] = int(REGEX_MAP["delay_pool"].search(block).group(1)) if REGEX_MAP["delay_pool"].search(block) else "N/A"        
     return conn
 
 def group_by_user(connections):
-    # Lista de identificadores para usuarios anónimos
     ANONYMOUS_INDICATORS = {
         None, "", "-", "Anónimo", "N/A", "anonymous", "Anonymous", 
         "unknown", "guest", "none", "null"
     }
     
-    grouped = defaultdict(list)
+    grouped = defaultdict(lambda: {"client_ip": "No disponible", "connections": []})
     
     for connection in connections:
         user = connection.get("username")
         
-        # Paso 1: Comprobar si el usuario es None
         if user is None:
             continue
-            
-        # Paso 2: Convertir a cadena si no es None
         if not isinstance(user, str):
             user = str(user)
-            
-        # Paso 3: Normalizar el nombre de usuario
         user_normalized = user.strip().lower()
-        
-        # Paso 4: Comprobar si el usuario es anónimo
         is_anonymous = (
-            not user_normalized or  # Cadena vacía
-            user_normalized in (indicator.lower() for indicator in ANONYMOUS_INDICATORS if indicator is not None) or
-            user_normalized.startswith("anon") or
-            "invitado" in user_normalized
+            not user_normalized or
+            user_normalized in (indicator.lower() for indicator in ANONYMOUS_INDICATORS if indicator is not None)
         )
-        
-        # Paso 5: Saltar conexiones anónimas
         if is_anonymous:
             continue
        
-        # Agrupar conexión para el usuario válido
-        grouped[user].append(connection)
+        if not grouped[user]["connections"]:
+            grouped[user]["client_ip"] = connection.get("client_ip", "No disponible")
+            
+        grouped[user]["connections"].append(connection)
     
-    return grouped
+    return dict(grouped)

+ 21 - 0
services/server_stats.py

@@ -0,0 +1,21 @@
+import logging
+from datetime import datetime
+from database.database import get_session, Metrics
+
+def save_metrics_to_db(system_info, bytes_sent_sec, bytes_recv_sec, size_to_bytes):
+    logger = logging.getLogger(__name__)
+    try:
+        db_session = get_session()
+        new_metric = Metrics(
+            timestamp=datetime.now(),
+            cpu_usage=float(system_info['cpu']['usage'].replace('%','')),
+            ram_usage_bytes=size_to_bytes(system_info['ram']['used']),
+            swap_usage_bytes=size_to_bytes(system_info['swap']['used']),
+            net_sent_bytes_sec=int(bytes_sent_sec),
+            net_recv_bytes_sec=int(bytes_recv_sec)
+        )
+        db_session.add(new_metric)
+        db_session.commit()
+        db_session.close()
+    except Exception as e:
+        logger.error(f"Error al guardar métricas en la BD: {str(e)}")

Fichier diff supprimé car celui-ci est trop grand
+ 6 - 0
static/js/chart.js


Fichier diff supprimé car celui-ci est trop grand
+ 6 - 0
static/js/chartjs-plugin-datalabels.js


Fichier diff supprimé car celui-ci est trop grand
+ 0 - 0
static/js/tailwindcss.js


+ 1 - 0
templates/blacklist.html

@@ -1,3 +1,4 @@
+
 {% extends 'base.html' %}
 
 {% block title %}BlackList | Dashboard Squid{% endblock %}

+ 80 - 53
templates/components/black_list.html

@@ -1,4 +1,4 @@
-<div class="container mx-auto px-4 py-8">
+<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
     <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
         <h1 class="text-3xl font-bold text-gray-800 mb-4 md:mb-0">
             <svg class="h-8 w-8 inline-block mr-2 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -7,7 +7,7 @@
             Actividad en Sitios Bloqueados
         </h1>
         
-        <div class="bg-gray-100 px-4 py-2 rounded-lg">
+        <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>
@@ -15,7 +15,7 @@
     </div>
 
     <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">
+        <div class="px-6 py-4 border-b border-gray-200 bg-gray-50 flex flex-col sm:flex-row justify-between items-center">
             <div class="mb-2 sm:mb-0">
                 <span class="text-sm font-medium text-gray-600">
                     Total de registros: 
@@ -24,7 +24,7 @@
             </div>
             <div class="flex items-center">
                 <span class="text-sm font-medium text-gray-600 mr-2">Mostrar:</span>
-                <select id="per_page" class="border rounded px-2 py-1 text-sm" 
+                <select id="per_page" class="border rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" 
                         onchange="window.location.href = updateQueryParam('per_page', this.value)">
                     <option value="20" {% if pagination.per_page == 20 %}selected{% endif %}>20</option>
                     <option value="50" {% if pagination.per_page == 50 %}selected{% endif %}>50</option>
@@ -33,67 +33,93 @@
             </div>
         </div>
 
-        <div class="overflow-x-auto">
-            <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">
-                            Fecha
-                        </th>
-                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
-                            Usuario
-                        </th>
-                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
-                            URL Bloqueada
-                        </th>
-                    </tr>
-                </thead>
-                <tbody class="bg-white divide-y divide-gray-200">
-                    {% for item in results %}
-                    <tr class="hover:bg-gray-50 transition-colors">
-                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
-                            {{ item.fecha }}
-                        </td>
-                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
-                            <div class="flex items-center">
-                                <svg class="h-5 w-5 mr-2 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
-                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
-                                </svg>
-                                {{ item.usuario }}
-                            </div>
-                        </td>
-                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
-                            <div class="flex items-center">
-                                <svg class="h-5 w-5 mr-2 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
-                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
-                                </svg>
-                                <span class="text-red-600 font-medium">{{ item.url }}</span>
+        <div class="divide-y divide-gray-200">
+            {% for user, items in results | groupby('usuario') %}
+            {% set user_items = items | list %}
+            <div class="user-group">
+                <div class="px-6 py-4 bg-white">
+                    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center">
+                        <div class="flex items-center mb-2 sm:mb-0">
+                             <svg class="h-6 w-6 mr-3 text-blue-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
+                            </svg>
+                            <h2 class="text-lg font-semibold text-gray-800">{{ user }}</h2>
+                        </div>
+                        <div class="flex-shrink-0">
+                            <span class="px-3 py-1 bg-red-100 text-red-800 text-xs font-bold rounded-full">
+                                {{ user_items | length }} Intentos Bloqueados
+                            </span>
+                        </div>
+                    </div>
+                </div>
+
+                <div class="px-6 py-4 border-t border-gray-200 bg-gray-50/50">
+                    <div class="space-y-2">
+                        {# Bloque para agrupar manualmente por dominio principal #}
+                        {% set grouped_by_domain = {} %}
+                        {% for item in user_items %}
+                            {% set url_lower = item.url | lower %}
+                            {% set parent_domain = 'unknown' %}
+
+                            {% if 'facebook.com' in url_lower or 'fb.com' in url_lower %} {% set parent_domain = 'facebook.com' %}
+                            {% elif 'instagram.com' in url_lower %} {% set parent_domain = 'instagram.com' %}
+                            {% elif 'youtube.com' in url_lower or 'ytimg.com' in url_lower %} {% set parent_domain = 'youtube.com' %}
+                            {% elif 'twitter.com' in url_lower or 'x.com' in url_lower %} {% set parent_domain = 'twitter.com' %}
+                            {% elif 'tiktok.com' in url_lower %} {% set parent_domain = 'tiktok.com' %}
+                            {% elif 'whatsapp.com' in url_lower %} {% set parent_domain = 'whatsapp.com' %}
+                            {% elif 'netflix.com' in url_lower %} {% set parent_domain = 'netflix.com' %}
+                            {% else %}
+                                {% set domain_parts = item.url.split('/')[0].split('.') %}
+                                {% if domain_parts | length >= 2 %}
+                                    {% set parent_domain = domain_parts[-2] + '.' + domain_parts[-1] %}
+                                {% else %}
+                                    {% set parent_domain = item.url.split('/')[0] %}
+                                {% endif %}
+                            {% endif %}
+
+                            {% set current_items = grouped_by_domain.get(parent_domain, []) %}
+                            {% set _ = current_items.append(item) %}
+                            {% set _ = grouped_by_domain.update({parent_domain: current_items}) %}
+                        {% endfor %}
+
+                        {# Iterar sobre los dominios agrupados y mostrarlos en filas sin icono #}
+                        {% for domain, domain_items in grouped_by_domain.items() | sort %}
+                            {% set count = domain_items | length %}
+                            {% set all_urls = (domain_items | map(attribute='url') | unique | list) | join('\n') %}
+
+                            <div class="flex items-center p-2 bg-white rounded-md shadow-sm" title="URLs reales:\n{{ all_urls }}">
+                                <p class="flex-grow font-mono text-sm text-gray-800 truncate pr-4">{{ domain }}</p>
+                                <span class="flex-shrink-0 px-2.5 py-0.5 text-xs font-bold text-red-800 bg-red-100 rounded-full">
+                                    {{ count }}
+                                </span>
                             </div>
-                        </td>
-                    </tr>
-                    {% else %}
-                    <tr>
-                        <td colspan="3" class="px-6 py-4 text-center text-gray-500">
-                            No se encontraron registros bloqueados
-                        </td>
-                    </tr>
-                    {% endfor %}
-                </tbody>
-            </table>
+                        {% endfor %}
+                    </div>
+                </div>
+            </div>
+            {% else %}
+            <div class="px-6 py-12 text-center">
+                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
+                  <path vector-effect="non-scaling-stroke" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
+                </svg>
+                <h3 class="mt-2 text-sm font-medium text-gray-900">No se encontraron registros</h3>
+                <p class="mt-1 text-sm text-gray-500">No hay actividad en sitios bloqueados para mostrar.</p>
+              </div>
+            {% endfor %}
         </div>
 
         <div class="px-6 py-4 border-t border-gray-200 bg-gray-50">
             <div class="flex flex-col sm:flex-row justify-between items-center">
                 <span class="text-sm text-gray-600 mb-2 sm:mb-0">
-                    Mostrando {{ results|length }} de {{ pagination.total }} registros
+                    Mostrando {{ (results | groupby('usuario') | list) | length }} grupos de usuarios en esta página.
                 </span>
                 <div class="flex space-x-2">
                     <a href="{{ url_for('blacklist_logs', page=pagination.page-1, per_page=pagination.per_page) }}" 
-                       class="px-4 py-2 bg-white border rounded-md {% if pagination.page == 1 %}opacity-50 cursor-not-allowed{% endif %}">
+                       class="px-4 py-2 bg-white border rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 {% if pagination.page == 1 %}opacity-50 cursor-not-allowed{% endif %}">
                         Anterior
                     </a>
                     <a href="{{ url_for('blacklist_logs', page=pagination.page+1, per_page=pagination.per_page) }}" 
-                       class="px-4 py-2 bg-white border rounded-md {% if pagination.page >= pagination.total_pages %}opacity-50 cursor-not-allowed{% endif %}">
+                       class="px-4 py-2 bg-white border rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 {% if pagination.page >= pagination.total_pages %}opacity-50 cursor-not-allowed{% endif %}">
                         Siguiente
                     </a>
                 </div>
@@ -106,6 +132,7 @@
 function updateQueryParam(param, value) {
     const url = new URL(window.location.href);
     url.searchParams.set(param, value);
+    url.searchParams.set('page', '1');
     return url.toString();
 }
 </script>

+ 149 - 864
templates/components/cache_stats.html

@@ -2,7 +2,6 @@
 <div class="group w-full h-48 [perspective:1000px]">
     <div
         class="relative h-full w-full rounded-xl shadow-xl transition-all duration-500 [transform-style:preserve-3d] group-hover:[transform:rotateY(180deg)]">
-        <!-- Front -->
         <div
             class="absolute inset-0 bg-white shadow-md rounded-xl flex flex-col items-center justify-center [backface-visibility:hidden]">
             <i class="{{ icon }} text-3xl text-blue-600 mb-2"></i>
@@ -13,7 +12,6 @@
             <p class="text-xl text-blue-800" data-stat="{{ title|replace(' ', '_')|lower }}">{{ value }}</p>
             {% endif %}
         </div>
-        <!-- Back -->
         <div
             class="absolute inset-0 bg-blue-600 text-white rounded-xl px-4 py-6 text-center [transform:rotateY(180deg)] [backface-visibility:hidden]">
             <h3 class="text-lg font-semibold mb-2">{{ back_title }}</h3>
@@ -30,117 +28,25 @@
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Dashboard de Sistema</title>
+    <link rel="icon" href="{{ url_for('static', filename=page_icon) }}" type="image/x-icon">
+    <script src="https://cdn.tailwindcss.com"></script>
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
     <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
     <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
     <script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
     <style>
-        /* Estilos base */
-        .circle {
-            stroke-linecap: round;
-            animation: progress 1s ease-out forwards;
-        }
-
-        @keyframes progress {
-            0% {
-                stroke-dasharray: 0 100;
-            }
-        }
-
-        .tab-btn {
-            transition: all 0.3s ease;
-        }
-
-        .tab-btn:hover {
-            background-color: #f1f5f9;
-        }
-
-        .cache-stats .group:hover .relative {
-            transform: rotateY(180deg);
-        }
-
-        .cache-stats .relative {
-            transition: transform 0.6s;
-        }
-
-        .cache-stats .absolute {
-            backface-visibility: hidden;
-        }
-
-        .main-tab-content {
-            display: none;
-        }
-
-        .main-tab-content.active {
-            display: block;
-            animation: fadeIn 0.5s ease;
-        }
-
-        @keyframes fadeIn {
-            from {
-                opacity: 0;
-            }
-
-            to {
-                opacity: 1;
-            }
-        }
-
-        .main-tab-btn {
-            position: relative;
-            overflow: hidden;
-        }
-
+        @keyframes progress { 0% { stroke-dasharray: 0 100; } }
+        .circle-animation { animation: progress 1s ease-out forwards; }
+        .main-tab-content, .tab-content { display: none; }
+        .main-tab-content.active, .tab-content.active { display: block; animation: fadeIn 0.5s ease; }
+        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
         .main-tab-btn.active::after {
-            content: '';
-            position: absolute;
-            bottom: 0;
-            left: 0;
-            right: 0;
-            height: 3px;
-            background-color: #3b82f6;
-            animation: underline 0.3s ease;
-        }
-
-        @keyframes underline {
-            from {
-                transform: scaleX(0);
-            }
-
-            to {
-                transform: scaleX(1);
-            }
-        }
-
-        /* Animación para cambios de valores */
-        .value-change {
-            animation: pulse 1s;
-        }
-
-        @keyframes pulse {
-            0% {
-                transform: scale(1);
-            }
-
-            50% {
-                transform: scale(1.1);
-            }
-
-            100% {
-                transform: scale(1);
-            }
-        }
-
-        /* Estilos para textos dentro de los anillos */
-        .ring-percent {
-            text-anchor: middle;
-            dominant-baseline: central;
-            alignment-baseline: central;
-        }
-
-        /* Estilos para la gráfica de días */
-        .day-bar {
-            transition: all 0.5s ease;
+            content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 3px;
+            background-color: #3b82f6; animation: underline 0.3s ease;
         }
+        @keyframes underline { from { transform: scaleX(0); } to { transform: scaleX(1); } }
+        .value-change { animation: pulse 1s; }
+        @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
     </style>
 </head>
 
@@ -148,211 +54,92 @@
     <div class="max-w-7xl mx-auto px-4 py-8">
         <h1 class="text-3xl font-bold text-center text-gray-800 mb-8">Dashboard de Estadísticas del Sistema</h1>
 
-        <!-- Pestañas principales -->
         <div class="flex border-b mb-6">
-            <button id="dashboardTab" class="main-tab-btn active py-3 px-6 font-medium text-blue-600">
+            <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>Dashboard del Sistema
             </button>
-            <button id="cacheTab" class="main-tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600">
+            <button id="cacheTab" class="main-tab-btn relative overflow-hidden py-3 px-6 font-medium text-gray-500 hover:text-blue-600">
                 <i class="fas fa-database mr-2"></i>Estadísticas de Caché
             </button>
+            <button id="networkTab" class="main-tab-btn relative overflow-hidden py-3 px-6 font-medium text-gray-500 hover:text-blue-600">
+                <i class="fas fa-network-wired mr-2"></i>Tráfico de Red
+            </button>
         </div>
 
-        <!-- Contenido del Dashboard del Sistema (activo por defecto) -->
         <div id="dashboardContent" class="main-tab-content active">
-            <!-- Sección de estadísticas e información del sistema -->
             <section class="mb-12">
                 <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
-                    <!-- Panel izquierdo: Estadísticas del sistema con anillos -->
                     <div class="bg-white rounded-xl shadow-lg p-6">
                         <div class="flex items-center mb-6">
                             <i class="fas fa-chart-pie text-2xl text-blue-600 mr-3"></i>
                             <h2 class="text-xl font-bold text-gray-800">Estadísticas del Sistema</h2>
                         </div>
-
-                        <!-- Contenedor de anillos - Centrado verticalmente -->
                         <div class="grid grid-cols-1 md:grid-cols-3 gap-6 items-center justify-center">
-                            <!-- Anillo de Uso de CPU con información de núcleos -->
                             <div class="flex flex-col items-center justify-center">
                                 <div class="relative w-36 h-36">
-                                    <svg viewBox="0 0 36 36" class="circular-chart block mx-auto">
-                                        <path class="circle-bg fill-none stroke-[#ffe5e5] stroke-[3.5]" d="M18 2.0845
-                a 15.9155 15.9155 0 0 1 0 31.831
-                a 15.9155 15.9155 0 0 1 0 -31.831" />
-                                        <path id="cpu-ring" class="circle fill-none" d="M18 2.0845
-                a 15.9155 15.9155 0 0 1 0 31.831
-                a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="#ef4444" stroke-width="3.5"
-                                            stroke-dasharray="0,100" />
-                                        <!-- Texto centrado verticalmente -->
-                                        <text id="cpu-value" x="18" y="18"
-                                            class="ring-percent text-[0.5rem] fill-gray-500">0%</text>
+                                    <svg viewBox="0 0 36 36" class="block mx-auto">
+                                        <path class="fill-none stroke-red-100 stroke-[3.5]" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
+                                        <path id="cpu-ring" class="circle-animation fill-none stroke-linecap-round stroke-red-500 stroke-[3.5]" stroke-dasharray="0,100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
+                                        <text id="cpu-value" x="18" y="18" class="text-[0.5rem] fill-gray-500" text-anchor="middle" dominant-baseline="middle">0%</text>
                                     </svg>
                                 </div>
                                 <h3 class="mt-2 font-semibold text-gray-700">CPU</h3>
-                                <!-- Nueva etiqueta con información de núcleos del CPU - Color del anillo -->
-                                <p
-                                    class="cores text-xs mt-1 bg-red-500 text-white px-2 py-0.5 rounded-full font-medium">
-                                    {{ system_info.cpu.physical_cores }} núcleos</p>
+                                <p class="text-xs mt-1 bg-red-500 text-white px-2 py-0.5 rounded-full font-medium">{{ system_info.cpu.physical_cores }} núcleos</p>
                             </div>
-
-                            <!-- Anillo de Uso de RAM con información de RAM total -->
                             <div class="flex flex-col items-center justify-center">
                                 <div class="relative w-36 h-36">
-                                    <svg viewBox="0 0 36 36" class="circular-chart block mx-auto">
-                                        <path class="circle-bg fill-none stroke-[#dfedff] stroke-[3.5]" d="M18 2.0845
-                a 15.9155 15.9155 0 0 1 0 31.831
-                a 15.9155 15.9155 0 0 1 0 -31.831" />
-                                        <path id="ram-ring" class="circle fill-none" d="M18 2.0845
-                a 15.9155 15.9155 0 0 1 0 31.831
-                a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="#3b82f6" stroke-width="3.5"
-                                            stroke-dasharray="0,100" />
-                                        <!-- Texto centrado verticalmente -->
-                                        <text id="ram-used" x="18" y="18"
-                                            class="ring-percent text-[0.5rem] fill-gray-500" text-anchor="middle"
-                                            dominant-baseline="middle">0G</text>
+                                    <svg viewBox="0 0 36 36" class="block mx-auto">
+                                        <path class="fill-none stroke-blue-100 stroke-[3.5]" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
+                                        <path id="ram-ring" class="circle-animation fill-none stroke-linecap-round stroke-blue-600 stroke-[3.5]" stroke-dasharray="0,100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
+                                        <text id="ram-used" x="18" y="18" class="text-[0.5rem] fill-gray-500" text-anchor="middle" dominant-baseline="middle">0G</text>
                                     </svg>
                                 </div>
                                 <h3 class="mt-2 font-semibold text-gray-700">RAM</h3>
-                                <!-- Nueva etiqueta con información de RAM total - Color del anillo -->
-                                <p
-                                    class="ram text-xs mt-1 bg-blue-500 text-white px-2 py-0.5 rounded-full font-medium">
-                                    {{ system_info.ram.total }}</p>
+                                <p class="text-xs mt-1 bg-blue-500 text-white px-2 py-0.5 rounded-full font-medium">{{ system_info.ram.total }}</p>
                             </div>
-
-                            <!-- Anillo de Uso de Swap con información de swap total -->
                             <div class="flex flex-col items-center justify-center">
                                 <div class="relative w-36 h-36">
-                                    <svg viewBox="0 0 36 36" class="circular-chart block mx-auto">
-                                        <path class="circle-bg fill-none stroke-[#d3f9e8] stroke-[3.5]" d="M18 2.0845
-                                            a 15.9155 15.9155 0 0 1 0 31.831
-                                            a 15.9155 15.9155 0 0 1 0 -31.831" />
-                                        <path id="swap-ring" class="circle fill-none" d="M18 2.0845
-                                            a 15.9155 15.9155 0 0 1 0 31.831
-                                            a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="#10b981"
-                                            stroke-width="3.5" stroke-dasharray="0,100" />
-                                        <text id="swap-used" x="18" y="18"
-                                            class="ring-percent text-[0.5rem] fill-gray-500" text-anchor="middle"
-                                            dominant-baseline="middle">0G</text>
+                                    <svg viewBox="0 0 36 36" class="block mx-auto">
+                                        <path class="fill-none stroke-emerald-100 stroke-[3.5]" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
+                                        <path id="swap-ring" class="circle-animation fill-none stroke-linecap-round stroke-emerald-500 stroke-[3.5]" stroke-dasharray="0,100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
+                                        <text id="swap-used" x="18" y="18" class="text-[0.5rem] fill-gray-500" text-anchor="middle" dominant-baseline="middle">0G</text>
                                     </svg>
                                 </div>
                                 <h3 class="mt-2 font-semibold text-gray-700">SWAP</h3>
-                                <!-- Nueva etiqueta con información de swap total - Color del anillo -->
-                                <p
-                                    class="swap text-xs mt-1 bg-emerald-500 text-white px-2 py-0.5 rounded-full font-medium">
-                                    {{ system_info.swap.total }}</p>
+                                <p class="text-xs mt-1 bg-emerald-500 text-white px-2 py-0.5 rounded-full font-medium">{{ system_info.swap.total }}</p>
                             </div>
                         </div>
                     </div>
 
-                    <!-- Panel derecho: Información del sistema -->
                     <div class="bg-white rounded-xl shadow-lg p-6">
                         <div class="flex items-center mb-6">
                             <i class="fas fa-info-circle text-2xl text-blue-600 mr-3"></i>
                             <h2 class="text-xl font-bold text-gray-800">Información del Sistema</h2>
                         </div>
-
                         <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
-                            <div class="flex items-start">
-                                <i class="fas fa-server text-gray-500 mt-1 mr-3"></i>
-                                <div>
-                                    <h3 class="text-sm font-semibold text-gray-600">Nombre del Host</h3>
-                                    <p id="hostname" class="text-gray-800">{{ system_info.hostname }}</p>
-                                </div>
-                            </div>
-
-                            <div class="flex items-start">
-                                <i class="fas fa-network-wired text-gray-500 mt-1 mr-3"></i>
-                                <div>
-                                    <h3 class="text-sm font-semibold text-gray-600">Direcciones IP</h3>
-                                    <p id="ip-addresses" class="text-gray-800">
-                                        {% for ip in system_info.ips %}
-                                        {{ ip.ip }}<br>
-                                        {% endfor %}
-                                    </p>
-                                </div>
-                            </div>
-
-                            <div class="flex items-start">
-                                <i class="fab fa-linux text-gray-500 mt-1 mr-3"></i>
-                                <div>
-                                    <h3 class="text-sm font-semibold text-gray-600">Sistema Operativo</h3>
-                                    <p id="os-info" class="text-gray-800">{{ system_info.os }}</p>
-                                </div>
-                            </div>
-
-                            <div class="flex items-start">
-                                <i class="fas fa-clock text-gray-500 mt-1 mr-3"></i>
-                                <div>
-                                    <h3 class="text-sm font-semibold text-gray-600">Tiempo Encendido</h3>
-                                    <p id="uptime" class="text-gray-800">{{ system_info.uptime }}</p>
-                                </div>
-                            </div>
-
-                            <!-- Se eliminaron las secciones de memoria y swap como se solicitó -->
-                            <!-- Esta información ahora está en los anillos con las nuevas etiquetas -->
-
-                            <div class="flex items-start">
-                                <i class="fas fa-globe text-gray-500 mt-1 mr-3"></i>
-                                <div>
-                                    <h3 class="text-sm font-semibold text-gray-600">Zona Horaria</h3>
-                                    <p id="timezone" class="text-gray-800">{{ system_info.timezone }}</p>
-                                </div>
-                            </div>
-
-                            <div class="flex items-start">
-                                <i class="fas fa-clock text-gray-500 mt-1 mr-3"></i>
-                                <div>
-                                    <h3 class="text-sm font-semibold text-gray-600">Hora Local</h3>
-                                    <p id="local-time" class="text-gray-800">{{ system_info.local_time }}</p>
-                                </div>
-                            </div>
+                            <div class="flex items-start"><i class="fas fa-server text-gray-500 mt-1 mr-3"></i><div><h3 class="text-sm font-semibold text-gray-600">Nombre del Host</h3><p id="hostname" class="text-gray-800">{{ system_info.hostname }}</p></div></div>
+                            <div class="flex items-start"><i class="fas fa-network-wired text-gray-500 mt-1 mr-3"></i><div><h3 class="text-sm font-semibold text-gray-600">Direcciones IP</h3><p id="ip-addresses" class="text-gray-800">{% for ip in system_info.ips %}{{ ip.ip }}<br>{% endfor %}</p></div></div>
+                            <div class="flex items-start"><i class="fab fa-linux text-gray-500 mt-1 mr-3"></i><div><h3 class="text-sm font-semibold text-gray-600">Sistema Operativo</h3><p id="os-info" class="text-gray-800">{{ system_info.os }}</p></div></div>
+                            <div class="flex items-start"><i class="fas fa-clock text-gray-500 mt-1 mr-3"></i><div><h3 class="text-sm font-semibold text-gray-600">Tiempo Encendido</h3><p id="uptime" class="text-gray-800">{{ system_info.uptime }}</p></div></div>
+                            <div class="flex items-start"><i class="fas fa-globe text-gray-500 mt-1 mr-3"></i><div><h3 class="text-sm font-semibold text-gray-600">Zona Horaria</h3><p id="timezone" class="text-gray-800">{{ system_info.timezone }}</p></div></div>
+                            <div class="flex items-start"><i class="fas fa-clock text-gray-500 mt-1 mr-3"></i><div><h3 class="text-sm font-semibold text-gray-600">Hora Local</h3><p id="local-time" class="text-gray-800">{{ system_info.local_time }}</p></div></div>
                         </div>
                     </div>
                 </div>
             </section>
 
-            <!-- Sección de gráficas con pestañas -->
             <section class="bg-white rounded-xl shadow-lg p-6 mb-12">
                 <div class="flex border-b mb-6">
-                    <button
-                        class="tab-btn active py-3 px-6 font-medium border-b-2 border-blue-600 text-blue-600">CPU</button>
-                    <button class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600">RAM</button>
-                    <button class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600">SWAP</button>
-                </div>
-
-                <div class="tab-content active">
-                    <div class="h-80">
-                        <canvas id="cpuChart"></canvas>
-                    </div>
-                </div>
-
-                <div class="tab-content hidden">
-                    <div class="h-80">
-                        <canvas id="ramChart"></canvas>
-                    </div>
-                </div>
-
-                <div class="tab-content hidden">
-                    <div class="h-80">
-                        <canvas id="swapChart"></canvas>
-                    </div>
-                </div>
-            </section>
-
-            <!-- Sección de gráfica de red (ancho de banda) -->
-            <section class="bg-white rounded-xl shadow-lg p-6 mb-12">
-                <div class="flex items-center mb-6">
-                    <i class="fas fa-network-chart text-2xl text-blue-600 mr-3"></i>
-                    <h2 class="text-xl font-bold text-gray-800">Estadísticas de Ancho de Banda</h2>
-                </div>
-
-                <div class="h-80">
-                    <canvas id="networkChart"></canvas>
+                    <button class="tab-btn active py-3 px-6 font-medium border-b-2 border-blue-600 text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100">CPU</button>
+                    <button class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100">RAM</button>
+                    <button class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100">SWAP</button>
                 </div>
+                <div class="tab-content active"><div class="h-80"><canvas id="cpuChart"></canvas></div></div>
+                <div class="tab-content"><div class="h-80"><canvas id="ramChart"></canvas></div></div>
+                <div class="tab-content"><div class="h-80"><canvas id="swapChart"></canvas></div></div>
             </section>
         </div>
 
-        <!-- Contenido de Estadísticas de Caché (inicialmente oculto) -->
         <div id="cacheContent" class="main-tab-content">
             <section class="cache-stats">
                 <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
@@ -360,144 +147,41 @@
                         <i class="fas fa-database text-2xl text-blue-600 mr-3"></i>
                         <h2 class="text-2xl font-bold text-gray-800">Estadísticas de Caché</h2>
                     </div>
-
                     <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8 max-w-[1000px] mx-auto">
-                        <!-- Entradas almacenadas -->
-                        {{ flip_card(
-                        icon='fas fa-database',
-                        title='Entradas almacenadas',
-                        value=cache_stats.store_entries,
-                        back_title='Entradas Almacenadas',
-                        description='Número de objetos actualmente en la caché de Squid.'
-                        ) }}
-
-                        <!-- Uso de capacidad -->
-                        {{ flip_card(
-                        icon='fas fa-chart-pie',
-                        title='Uso de capacidad',
-                        value=cache_stats.capacity_used,
-                        back_title='Uso de capacidad',
-                        description='Porcentaje del almacenamiento de caché en uso actualmente.'
-                        ) }}
-
-                        <!-- Espacio total en disco -->
-                        {% set total_space_html %}
-                        {% if (cache_stats.fs_space_total / 1024) < 1024 %} <p class="text-xl text-blue-800"
-                            data-stat="espacio_total">{{ (cache_stats.fs_space_total / 1024)|int }} MB</p>
-                            {% else %}
-                            <p class="text-xl text-blue-800" data-stat="espacio_total">{{ (cache_stats.fs_space_total /
-                                1024 / 1024)|round(2) }} GB</p>
-                            {% endif %}
-                            {% endset %}
-                            {{ flip_card(
-                            icon='fas fa-hdd',
-                            title='Espacio total',
-                            back_title='Espacio total',
-                            description='Tamaño total del disco asignado a la caché de Squid.',
-                            extra_html=total_space_html
-                            ) }}
-
-                            <!-- Espacio usado en disco -->
-                            {% set used_space_html %}
-                            {% if (cache_stats.fs_space_used / 1024) < 1024 %} <p class="text-xl text-blue-800"
-                                data-stat="espacio_usado">{{ (cache_stats.fs_space_used / 1024)|int }} MB</p>
-                                {% else %}
-                                <p class="text-xl text-blue-800" data-stat="espacio_usado">{{ (cache_stats.fs_space_used
-                                    / 1024 / 1024)|round(2) }} GB</p>
-                                {% endif %}
-                                {% endset %}
-                                {{ flip_card(
-                                icon='fas fa-folder-open',
-                                title='Espacio usado',
-                                back_title='Espacio usado',
-                                description='Cantidad de espacio de disco ya ocupado por objetos en caché.',
-                                extra_html=used_space_html
-                                ) }}
-
-                                <!-- Política de eliminación -->
-                                {{ flip_card(
-                                icon='fas fa-recycle',
-                                title='Eliminación',
-                                value=cache_stats.removal_policy,
-                                back_title='Política de eliminación',
-                                description='Método que Squid usa para eliminar objetos antiguos de la caché.'
-                                ) }}
-
-                                <!-- Edad LRU -->
-                                {{ flip_card(
-                                icon='fas fa-clock',
-                                title='Edad LRU',
-                                value=cache_stats.lru_age_days ~ ' días',
-                                back_title='Edad LRU',
-                                description='Tiempo desde que el objeto menos usado fue accedido por última vez.'
-                                ) }}
+                        {{ flip_card(icon='fas fa-database', title='Entradas almacenadas', value=cache_stats.store_entries, back_title='Entradas Almacenadas', description='Número de objetos actualmente en la caché de Squid.') }}
+                        {{ flip_card(icon='fas fa-chart-pie', title='Uso de capacidad', value=cache_stats.capacity_used, back_title='Uso de capacidad', description='Porcentaje del almacenamiento de caché en uso actualmente.') }}
+                        {% if cache_stats.fs_space_total and cache_stats.fs_space_total > 0 %}
+                            {% set total_space_html %}{% if (cache_stats.fs_space_total / 1024) < 1024 %}<p class="text-xl text-blue-800" data-stat="espacio_total">{{ (cache_stats.fs_space_total / 1024)|int }} MB</p>{% else %}<p class="text-xl text-blue-800" data-stat="espacio_total">{{ (cache_stats.fs_space_total / 1024 / 1024)|round(2) }} GB</p>{% endif %}{% endset %}
+                            {{ flip_card(icon='fas fa-hdd', title='Espacio total', back_title='Espacio total', description='Tamaño total del disco asignado a la caché de Squid.', extra_html=total_space_html) }}
+                        {% else %}
+                            {{ flip_card(icon='fas fa-hdd', title='Espacio total', back_title='Espacio total', description='Tamaño total del disco asignado a la caché de Squid.', extra_html='<p class="text-xl text-red-600">No disponible</p>') }}
+                        {% endif %}
+                        {% set used_space_html %}{% if (cache_stats.fs_space_used / 1024) < 1024 %}<p class="text-xl text-blue-800" data-stat="espacio_usado">{{ (cache_stats.fs_space_used / 1024)|int }} MB</p>{% else %}<p class="text-xl text-blue-800" data-stat="espacio_usado">{{ (cache_stats.fs_space_used / 1024 / 1024)|round(2) }} GB</p>{% endif %}{% endset %}{{ flip_card(icon='fas fa-folder-open', title='Espacio usado', back_title='Espacio usado', description='Cantidad de espacio de disco ya ocupado por objetos en caché.', extra_html=used_space_html) }}
+                        {{ flip_card(icon='fas fa-recycle', title='Eliminación', value=cache_stats.removal_policy, back_title='Política de eliminación', description='Método que Squid usa para eliminar objetos antiguos de la caché.') }}
+                        {{ flip_card(icon='fas fa-clock', title='Edad LRU', value=cache_stats.lru_age_days ~ ' días', back_title='Edad LRU', description='Tiempo desde que el objeto menos usado fue accedido por última vez.') }}
                     </div>
                 </div>
+            </section>
+        </div>
 
-                <!-- Gráfica de uso de caché por días -->
-                <div class="bg-white rounded-xl shadow-lg p-6">
-                    <div class="flex items-center mb-6">
-                        <i class="fas fa-chart-line text-2xl text-blue-600 mr-3"></i>
-                        <h2 class="text-xl font-bold text-gray-800">Historial de Uso de Caché (Últimos 7 días)</h2>
-                    </div>
-
-                    <div class="h-80">
-                        <canvas id="cacheUsageChart"></canvas>
-                    </div>
+        <div id="networkContent" class="main-tab-content">
+            <section class="bg-white rounded-xl shadow-lg p-6">
+                <div class="flex items-center mb-6">
+                    <i class="fas fa-network-wired text-2xl text-blue-600 mr-3"></i>
+                    <h2 class="text-xl font-bold text-gray-800">Tráfico de Red</h2>
                 </div>
+                <div class="h-80"><canvas id="networkChart"></canvas></div>
             </section>
         </div>
     </div>
 
     <script>
-        // Registrar el plugin de datalabels
         Chart.register(ChartDataLabels);
 
-        // Variables globales optimizadas
-        let systemDataHistory = { cpu: [], ram: [], swap: [], cache: [], network_up: [], network_down: [] };
         let maxRamBytes = 0, maxSwapBytes = 0;
-        let cpuBuffer = [], ramBuffer = [], swapBuffer = [], netUpBuffer = [], netDownBuffer = [];
-        const historySize = 20;
-        let minuteLabels = [], cpuMinuteData = [], ramMinuteData = [], swapMinuteData = [], networkUpMinuteData = [], networkDownMinuteData = [];
-
-        // Utilidades de persistencia optimizadas
-        const storage = {
-            get: (key, fallback) => {
-                const val = sessionStorage.getItem(key);
-                return val ? JSON.parse(val) : fallback;
-            },
-            set: (key, arr) => sessionStorage.setItem(key, JSON.stringify(arr)),
-            setAll: () => {
-                ['cpuMinuteData', 'ramMinuteData', 'swapMinuteData', 'networkUpMinuteData', 'networkDownMinuteData', 'minuteLabels']
-                    .forEach(key => storage.set(key, eval(key)));
-            }
-        };
-
-        // Inicialización optimizada
-        function initializeData() {
-            const initialCpu = parseFloat("{{ system_info.cpu.usage|replace('%','') }}");
-            const initialRam = sizeToBytes("{{ system_info.ram.used }}");
-            const initialSwap = sizeToBytes("{{ system_info.swap.used }}");
-            const initialNetUp = parseFloat("{{ network_stats.up_mbps|default('0') }}");
-            const initialNetDown = parseFloat("{{ network_stats.down_mbps|default('0') }}");
-
-            cpuMinuteData = storage.get('cpuMinuteData', Array(historySize).fill(initialCpu));
-            ramMinuteData = storage.get('ramMinuteData', Array(historySize).fill(initialRam));
-            swapMinuteData = storage.get('swapMinuteData', Array(historySize).fill(initialSwap));
-            networkUpMinuteData = storage.get('networkUpMinuteData', Array(historySize).fill(initialNetUp));
-            networkDownMinuteData = storage.get('networkDownMinuteData', Array(historySize).fill(initialNetDown));
-            
-            minuteLabels = storage.get('minuteLabels', (() => {
-                const now = new Date();
-                return Array.from({ length: historySize }, (_, i) => {
-                    const t = new Date(now.getTime() - (historySize - 1 - i) * 60000);
-                    return formatTime(t);
-                });
-            })());
-        }
-        initializeData();
-
-        // Función para formatear hora en formato 12h
+        const historySize = 720; 
+        
+        // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
         function formatTime(date) {
             let hours = date.getHours();
             const minutes = date.getMinutes().toString().padStart(2, '0');
@@ -505,525 +189,126 @@
             hours = hours % 12 || 12;
             return `${hours}:${minutes} ${ampm}`;
         }
-
-        // Función para manejar las pestañas principales
         function openMainTab(tabName) {
-            // Ocultar todos los contenidos de pestañas
-            document.querySelectorAll('.main-tab-content').forEach(content => {
-                content.classList.remove('active');
-            });
-
-            // Remover clase activa de todos los botones
+            document.querySelectorAll('.main-tab-content').forEach(content => content.classList.remove('active'));
             document.querySelectorAll('.main-tab-btn').forEach(btn => {
                 btn.classList.remove('active', 'text-blue-600');
                 btn.classList.add('text-gray-500');
             });
-
-            // Mostrar la pestaña seleccionada
             document.getElementById(tabName + 'Content').classList.add('active');
-
-            // Activar el botón de la pestaña seleccionada
             const tabBtn = document.getElementById(tabName + 'Tab');
             tabBtn.classList.add('active', 'text-blue-600');
             tabBtn.classList.remove('text-gray-500');
         }
-
-        // Configurar eventos para las pestañas principales
         document.getElementById('dashboardTab').addEventListener('click', () => openMainTab('dashboard'));
         document.getElementById('cacheTab').addEventListener('click', () => openMainTab('cache'));
-
-        // Función para manejar las pestañas internas
-        document.querySelectorAll('.tab-btn').forEach(button => {
+        document.getElementById('networkTab').addEventListener('click', () => openMainTab('network'));
+        document.querySelectorAll('.tab-btn').forEach((button, index) => {
             button.addEventListener('click', () => {
-                // Remover clase activa de todos los botones
                 document.querySelectorAll('.tab-btn').forEach(btn => {
                     btn.classList.remove('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
                     btn.classList.add('text-gray-500');
                 });
-
-                // Agregar clase activa al botón clickeado
                 button.classList.add('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
                 button.classList.remove('text-gray-500');
-
-                // Ocultar todos los contenidos de pestañas
-                document.querySelectorAll('.tab-content').forEach(content => {
-                    content.classList.add('hidden');
-                    content.classList.remove('active');
-                });
-
-                // Mostrar el contenido correspondiente
-                const tabIndex = Array.from(document.querySelectorAll('.tab-btn')).indexOf(button);
-                document.querySelectorAll('.tab-content')[tabIndex].classList.remove('hidden');
-                document.querySelectorAll('.tab-content')[tabIndex].classList.add('active');
+                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
+                document.querySelectorAll('.tab-content')[index].classList.add('active');
             });
         });
-
-        // Función para formatear tamaños 
-        function formatSizeCompact(bytes) {
-            const units = ['B', 'KB', 'MB', 'GB'];
-            let unitIndex = 0;
-
-            while (bytes >= 1024 && unitIndex < units.length - 1) {
-                bytes /= 1024;
-                unitIndex++;
-            }
-
-            return unitIndex === 0
-                ? `${bytes} ${units[unitIndex]}`
-                : `${bytes.toFixed(1)} ${units[unitIndex]}`;
-        }
-
-        // Configuración de gráficos con Chart.js y datalabels
-        const cpuCtx = document.getElementById('cpuChart').getContext('2d');
-        const cpuChart = new Chart(cpuCtx, {
-            type: 'line',
-            data: {
-                labels: minuteLabels,
-                datasets: [{
-                    label: 'Uso de CPU (%)',
-                    data: cpuMinuteData,
-                    borderColor: '#ef4444',
-                    backgroundColor: 'rgba(239, 68, 68, 0.1)',
-                    tension: 0.3,
-                    fill: true,
-                    pointRadius: 4,
-                    pointBackgroundColor: '#ef4444'
-                }]
+        const chartOptions = {
+            responsive: true, maintainAspectRatio: false, tension: 0.3, fill: true, pointRadius: 2,
+            scales: {
+                x: { grid: { color: 'rgba(0, 0, 0, 0.05)' } },
+                y: { beginAtZero: true, grid: { color: 'rgba(0, 0, 0, 0.05)' } }
             },
-            options: {
-                responsive: true,
-                maintainAspectRatio: false,
-                scales: {
-                    y: {
-                        beginAtZero: true,
-                        max: 100,
-                        title: {
-                            display: true,
-                            text: 'Porcentaje (%)'
-                        },
-                        grid: {
-                            color: 'rgba(0, 0, 0, 0.05)'
-                        },
-                        ticks: {
-                            callback: function (value) {
-                                return value;
-                            }
-                        }
-                    },
-                    x: {
-                        grid: {
-                            color: 'rgba(0, 0, 0, 0.05)'
-                        }
-                    }
-                },
-                plugins: {
-                    legend: {
-                        display: true
-                    },
-                    datalabels: {
-                        display: false
-                    }
-                }
-            }
-        });
-
-        const ramCtx = document.getElementById('ramChart').getContext('2d');
-        const ramChart = new Chart(ramCtx, {
-            type: 'line',
-            data: {
-                labels: minuteLabels,
-                datasets: [{
-                    label: 'RAM Usada',
-                    data: ramMinuteData,
-                    borderColor: '#3b82f6',
-                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
-                    tension: 0.3,
-                    fill: true,
-                    pointRadius: 4,
-                    pointBackgroundColor: '#3b82f6'
-                }]
-            },
-            options: {
-                responsive: true,
-                maintainAspectRatio: false,
-                scales: {
-                    y: {
-                        beginAtZero: true,
-                        max: maxRamBytes,
-                        title: {
-                            display: true,
-                            text: 'Bytes'
-                        },
-                        grid: {
-                            color: 'rgba(0, 0, 0, 0.05)'
-                        },
-                        ticks: {
-                            callback: function (value) {
-                                return formatSizeCompact(value);
-                            }
-                        }
-                    },
-                    x: {
-                        grid: {
-                            color: 'rgba(0, 0, 0, 0.05)'
-                        }
-                    }
-                },
-                plugins: {
-                    legend: {
-                        display: true
-                    },
-                    datalabels: {
-                        display: false
-                    },
-                    tooltip: {
-                        callbacks: {
-                            label: function (context) {
-                                return 'RAM Usada: ' + formatSizeCompact(context.raw);
-                            }
-                        }
-                    }
-                }
-            }
-        });
-
-        const swapCtx = document.getElementById('swapChart').getContext('2d');
-        const swapChart = new Chart(swapCtx, {
-            type: 'line',
-            data: {
-                labels: minuteLabels,
-                datasets: [{
-                    label: 'Swap Usada',
-                    data: swapMinuteData,
-                    borderColor: '#10b981',
-                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
-                    tension: 0.3,
-                    fill: true,
-                    pointRadius: 4,
-                    pointBackgroundColor: '#10b981'
-                }]
-            },
-            options: {
-                responsive: true,
-                maintainAspectRatio: false,
-                scales: {
-                    y: {
-                        beginAtZero: true,
-                        max: maxSwapBytes,
-                        title: {
-                            display: true,
-                            text: 'Bytes'
-                        },
-                        grid: {
-                            color: 'rgba(0, 0, 0, 0.05)'
-                        },
-                        ticks: {
-                            callback: function (value) {
-                                return formatSizeCompact(value);
-                            }
-                        }
-                    },
-                    x: {
-                        grid: {
-                            color: 'rgba(0, 0, 0, 0.05)'
-                        }
-                    }
-                },
-                plugins: {
-                    legend: {
-                        display: true
-                    },
-                    datalabels: {
-                        display: false
-                    },
-                    tooltip: {
-                        callbacks: {
-                            label: function (context) {
-                                return 'SWAP Usada: ' + formatSizeCompact(context.raw);
-                            }
-                        }
-                    }
-                }
-            }
-        });
-
-        // Gráfico de red (ancho de banda)
-        const networkCtx = document.getElementById('networkChart').getContext('2d');
-        const networkChart = new Chart(networkCtx, {
-            type: 'line',
-            data: {
-                labels: minuteLabels,
-                datasets: [
-                    {
-                        label: 'Subida (Mbps)',
-                        data: networkUpMinuteData,
-                        borderColor: '#06b6d4',
-                        backgroundColor: 'rgba(6,182,212,0.1)',
-                        tension: 0.3,
-                        fill: true,
-                        pointRadius: 4,
-                        pointBackgroundColor: '#06b6d4'
-                    },
-                    {
-                        label: 'Bajada (Mbps)',
-                        data: networkDownMinuteData,
-                        borderColor: '#f59e42',
-                        backgroundColor: 'rgba(245,158,66,0.1)',
-                        tension: 0.3,
-                        fill: true,
-                        pointRadius: 4,
-                        pointBackgroundColor: '#f59e42'
-                    }
-                ]
-            },
-            options: {
-                responsive: true,
-                maintainAspectRatio: false,
-                scales: {
-                    y: {
-                        beginAtZero: true,
-                        title: { display: true, text: 'Mbps' },
-                        grid: { color: 'rgba(0, 0, 0, 0.05)' }
-                    },
-                    x: { grid: { color: 'rgba(0, 0, 0, 0.05)' } }
-                },
-                plugins: { legend: { display: true }, datalabels: { display: false } }
-            }
-        });
-
-        // Inicializar valores máximos con datos del backend
-        maxRamBytes = sizeToBytes("{{ system_info.ram.total }}");
-        maxSwapBytes = sizeToBytes("{{ system_info.swap.total }}");
-
-        // Actualizar gráficas con valores iniciales
-        ramChart.options.scales.y.max = maxRamBytes;
-        swapChart.options.scales.y.max = maxSwapBytes;
-        cpuChart.update();
-        ramChart.update();
-        swapChart.update();
-
-        // Función para extraer valor y unidad de un string de tamaño
-        function parseSize(sizeStr) {
-            if (!sizeStr) return { value: 0, unit: 'B' };
-            const parts = sizeStr.split(' ');
-            if (parts.length < 2) return { value: parseFloat(sizeStr) || 0, unit: 'B' };
-            return {
-                value: parseFloat(parts[0]),
-                unit: parts[1].charAt(0) // 'G', 'M', 'K'
-            };
-        }
-
-        // Función para convertir tamaño a bytes
-        function sizeToBytes(sizeStr) {
-            const { value, unit } = parseSize(sizeStr);
-            let multiplier = 1;
-            if (unit === 'G') {
-                multiplier = 1024 * 1024 * 1024;
-            } else if (unit === 'M') {
-                multiplier = 1024 * 1024;
-            } else if (unit === 'K') {
-                multiplier = 1024;
-            }
-            return value * multiplier;
-        }
-
-        // Función para actualizar anillos con información adicional
-        function updateRings(systemInfo) {
-            // Actualizar anillo de CPU
-            const cpuPercent = parseFloat(systemInfo.cpu.usage.replace('%', ''));
-            document.getElementById('cpu-ring').setAttribute('stroke-dasharray', `${cpuPercent},100`);
-            document.getElementById('cpu-value').textContent = `${cpuPercent}%`;
-
-            // Obtener valores de RAM
-            const ramUsedInfo = parseSize(systemInfo.ram.used);
-            const ramUsedCompact = ramUsedInfo.value + ramUsedInfo.unit;
-            const ramPercent = parseFloat(systemInfo.ram.percent.replace('%', ''));
-
-            // Actualizar anillo de RAM 
-            document.getElementById('ram-ring').setAttribute('stroke-dasharray', `${ramPercent},100`);
-
-            // Actualizar texto centrado con RAM usada
-            document.getElementById('ram-used').textContent = ramUsedCompact;
-
-            // Actualizar anillo de SWAP
-            const swapPercent = parseFloat(systemInfo.swap.percent.replace('%', '') || '0');
-            document.getElementById('swap-ring').setAttribute('stroke-dasharray', `${swapPercent},100`);
-
-            // Obtener valores de SWAP  
-            const swapUsedInfo = parseSize(systemInfo.swap.used);
-            const swapUsedCompact = swapUsedInfo.value + swapUsedInfo.unit;
-
-            // Actualizar texto centrado con SWAP usada
-            document.getElementById('swap-used').textContent = swapUsedCompact;
-        }
-
-        // Función para actualizar la información del sistema
-        function updateSystemInfo(systemInfo) {
-            // Actualizar hostname
-            document.getElementById('hostname').textContent = systemInfo.hostname;
-
-            // Actualizar IPs
-            const ipList = systemInfo.ips.map(ip => ip.ip).join('<br>');
-            document.getElementById('ip-addresses').innerHTML = ipList;
-
-            // Actualizar OS
-            document.getElementById('os-info').textContent = systemInfo.os;
-
-            // Actualizar uptime
-            document.getElementById('uptime').textContent = systemInfo.uptime;
-
-            // Actualizar hora local
-            document.getElementById('local-time').textContent = formatTime(new Date());
-        }
-
-        // Función para actualizar las flip cards
-        function updateCacheStats(cacheStats) {
-            // Entradas almacenadas
-            updateCard('entradas_almacenadas', cacheStats.store_entries);
-
-            // Uso de capacidad
-            updateCard('uso_de_capacidad', cacheStats.capacity_used);
-
-            // Espacio total
-            updateCard('espacio_total', cacheStats.fs_space_total, true);
-
-            // Espacio usado
-            updateCard('espacio_usado', cacheStats.fs_space_used, true);
-
-            // Política de eliminación
-            updateCard('eliminación', cacheStats.removal_policy);
-
-            // Edad LRU
-            updateCard('edad_lru', `${cacheStats.lru_age_days} días`);
-        }
-
-        // Función para actualizar una tarjeta específica
-        function updateCard(statId, value, isSize = false) {
-            const elements = document.querySelectorAll(`[data-stat="${statId}"]`);
-
-            if (elements.length === 0) return;
-
-            elements.forEach(element => {
-                const currentValue = element.textContent;
-
-                // Solo actualizar si el valor cambió
-                if (currentValue !== value.toString()) {
-                    // Aplicar animación de cambio
-                    element.classList.add('value-change');
-
-                    // Actualizar el valor
-                    if (isSize) {
-                        // Convertir bytes a MB o GB
-                        const bytes = parseFloat(value);
-                        if (bytes / (1024 * 1024) < 1) {
-                            element.textContent = `${Math.round(bytes / 1024)} MB`;
+            plugins: { legend: { display: true }, datalabels: { display: false } }
+        };
+        const cpuChart = new Chart('cpuChart', { type: 'line', data: { labels: [], datasets: [{ label: 'Uso de CPU (%)', data: [], borderColor: '#ef4444', backgroundColor: 'rgba(239, 68, 68, 0.1)', pointBackgroundColor: '#ef4444' }] }, options: { ...chartOptions, scales: { ...chartOptions.scales, y: { ...chartOptions.scales.y, max: 100, title: { display: true, text: '%' } } } } });
+        const ramChart = new Chart('ramChart', { type: 'line', data: { labels: [], datasets: [{ label: 'RAM Usada', data: [], borderColor: '#3b82f6', backgroundColor: 'rgba(59, 130, 246, 0.1)', pointBackgroundColor: '#3b82f6' }] }, options: { ...chartOptions, scales: { ...chartOptions.scales, y: { ...chartOptions.scales.y, title: { display: true, text: 'Bytes' }, ticks: { callback: formatSizeCompact } } }, plugins: { ...chartOptions.plugins, tooltip: { callbacks: { label: ctx => 'RAM Usada: ' + formatSizeCompact(ctx.raw) } } } } });
+        const swapChart = new Chart('swapChart', { type: 'line', data: { labels: [], datasets: [{ label: 'Swap Usada', data: [], borderColor: '#10b981', backgroundColor: 'rgba(16, 185, 129, 0.1)', pointBackgroundColor: '#10b981' }] }, options: { ...chartOptions, scales: { ...chartOptions.scales, y: { ...chartOptions.scales.y, title: { display: true, text: 'Bytes' }, ticks: { callback: formatSizeCompact } } }, plugins: { ...chartOptions.plugins, tooltip: { callbacks: { label: ctx => 'SWAP Usada: ' + formatSizeCompact(ctx.raw) } } } } });
+        const networkChart = new Chart('networkChart', { type: 'line', data: { labels: [], datasets: [ { label: 'Subida (Mbps)', data: [], borderColor: '#06b6d4', backgroundColor: 'rgba(6,182,212,0.1)', pointBackgroundColor: '#06b6d4' }, { label: 'Bajada (Mbps)', data: [], borderColor: '#f59e42', backgroundColor: 'rgba(245,158,66,0.1)', pointBackgroundColor: '#f59e42' }] }, options: { ...chartOptions, scales: { ...chartOptions.scales, y: { ...chartOptions.scales.y, title: { display: true, text: 'Mbps' } } } } });
+        function formatSizeCompact(bytes) { if (bytes === 0) return '0 B'; const units = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(1024)); return `${parseFloat((bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1))} ${units[i]}`; }
+        function parseSize(sizeStr) { if (!sizeStr) return { value: 0, unit: 'B' }; const parts = sizeStr.trim().split(' '); return { value: parseFloat(parts[0]) || 0, unit: parts.length > 1 ? parts[1].charAt(0) : 'B' }; }
+        function sizeToBytes(sizeStr) { const { value, unit } = parseSize(sizeStr); const multipliers = { 'G': 1024 * 1024 * 1024, 'M': 1024 * 1024, 'K': 1024 }; return value * (multipliers[unit] || 1); }
+        function updateRings(info) { const cpuPercent = parseFloat(info.cpu.usage.replace('%', '')); document.getElementById('cpu-ring').setAttribute('stroke-dasharray', `${cpuPercent},100`); document.getElementById('cpu-value').textContent = `${cpuPercent.toFixed(1)}%`; const ramUsedInfo = parseSize(info.ram.used); document.getElementById('ram-used').textContent = `${ramUsedInfo.value.toFixed(1)}${ramUsedInfo.unit}`; document.getElementById('ram-ring').setAttribute('stroke-dasharray', `${parseFloat(info.ram.percent.replace('%', ''))},100`); const swapUsedInfo = parseSize(info.swap.used); document.getElementById('swap-used').textContent = `${swapUsedInfo.value.toFixed(1)}${swapUsedInfo.unit}`; document.getElementById('swap-ring').setAttribute('stroke-dasharray', `${parseFloat(info.swap.percent.replace('%', '') || 0)},100`); }
+        function updateSystemInfo(info) { document.getElementById('hostname').textContent = info.hostname; document.getElementById('ip-addresses').innerHTML = info.ips.map(ip => ip.ip).join('<br>'); document.getElementById('os-info').textContent = info.os; document.getElementById('uptime').textContent = info.uptime; document.getElementById('local-time').textContent = info.local_time; }
+        function updateCard(statId, value, isSize = false) { const element = document.querySelector(`[data-stat="${statId}"]`); if (!element) return; let formattedValue = value; if (isSize) { const bytes = parseFloat(value); formattedValue = (bytes / (1024 * 1024) < 1) ? `${Math.round(bytes / 1024)} MB` : `${(bytes / (1024 * 1024)).toFixed(2)} GB`; } if (element.textContent !== formattedValue.toString()) { element.textContent = formattedValue; element.classList.add('value-change'); setTimeout(() => element.classList.remove('value-change'), 1000); } }
+        function updateCacheStats(stats) { updateCard('entradas_almacenadas', stats.store_entries); updateCard('uso_de_capacidad', stats.capacity_used); updateCard('espacio_total', stats.fs_space_total, true); updateCard('espacio_usado', stats.fs_space_used, true); updateCard('eliminación', stats.removal_policy); updateCard('edad_lru', `${stats.lru_age_days} días`); }
+
+        // --- AÑADIDO: Carga de datos históricos desde la API ---
+        function loadHistoricData() {
+            fetch('/api/metrics/today')
+                .then(response => response.json())
+                .then(data => {
+                    if (!data || data.length === 0) { console.log("No hay historial de métricas para hoy."); return; }
+                    const labels = [], cpuData = [], ramData = [], swapData = [], netUpData = [], netDownData = [];
+                    data.forEach(metric => {
+                        labels.push(formatTime(new Date(metric.timestamp)));
+                        cpuData.push(parseFloat(metric.cpu_usage).toFixed(1));
+                        ramData.push(metric.ram_usage_bytes);
+                        swapData.push(metric.swap_usage_bytes);
+                        netUpData.push(((metric.net_sent_bytes_sec * 8) / 1000000).toFixed(2));
+                        netDownData.push(((metric.net_recv_bytes_sec * 8) / 1000000).toFixed(2));
+                    });
+                    const charts = [cpuChart, ramChart, swapChart, networkChart];
+                    const chartData = [cpuData, ramData, swapData, [netUpData, netDownData]];
+                    charts.forEach((chart, chartIndex) => {
+                        chart.data.labels = [...labels];
+                        if (chartIndex === 3) {
+                            chart.data.datasets[0].data = chartData[chartIndex][0];
+                            chart.data.datasets[1].data = chartData[chartIndex][1];
                         } else {
-                            element.textContent = `${(bytes / (1024 * 1024)).toFixed(2)} GB`;
+                            chart.data.datasets[0].data = chartData[chartIndex];
                         }
-                    } else {
-                        element.textContent = value;
-                    }
-
-                    // Quitar la clase de animación después de completarse
-                    setTimeout(() => {
-                        element.classList.remove('value-change');
-                    }, 1000);
-                }
-            });
+                        chart.update();
+                    });
+                })
+                .catch(error => console.error('Error al cargar historial de métricas:', error));
         }
 
-        // Función optimizada para agregar datos minuto a minuto
-        function addMinuteData(cpu, ram, swap, netUp, netDown) {
-            const dataArrays = [cpuMinuteData, ramMinuteData, swapMinuteData, networkUpMinuteData, networkDownMinuteData, minuteLabels];
-            const newValues = [cpu, ram, swap, netUp, netDown, formatTime(new Date())];
-            
-            // Actualizar todos los arrays eficientemente
-            dataArrays.forEach((arr, i) => {
-                arr.push(newValues[i]);
-                if (arr.length > historySize) arr.shift();
-            });
-
-            // Actualizar todos los gráficos
-            const charts = [cpuChart, ramChart, swapChart, networkChart];
-            const chartData = [
-                [cpuMinuteData],
-                [ramMinuteData], 
-                [swapMinuteData],
-                [networkUpMinuteData, networkDownMinuteData]
-            ];
-
-            charts.forEach((chart, i) => {
-                chart.data.labels = [...minuteLabels];
-                if (i === 3) { // networkChart tiene 2 datasets
-                    chart.data.datasets[0].data = [...chartData[i][0]];
-                    chart.data.datasets[1].data = [...chartData[i][1]];
-                } else {
-                    chart.data.datasets[0].data = [...chartData[i][0]];
-                }
-                chart.update();
-            });
-
-            storage.setAll();
-        }
-
-        // Conectar a WebSocket
         const socket = io();
-
-        // Manejo optimizado de actualizaciones del sistema
         socket.on('system_update', function (data) {
             updateRings(data.system_info);
             updateSystemInfo(data.system_info);
             updateCacheStats(data.cache_stats);
 
-            // Obtener y acumular datos
-            const newData = [
-                parseFloat(data.system_info.cpu.usage.replace('%', '')),
-                sizeToBytes(data.system_info.ram.used),
-                sizeToBytes(data.system_info.swap.used),
-                data.network_stats ? parseFloat(data.network_stats.up_mbps) : 0,
-                data.network_stats ? parseFloat(data.network_stats.down_mbps) : 0
-            ];
+            // --- MODIFICADO: Lógica para añadir datos en vivo a las gráficas ---
+            function appendLiveData(chart, label, newData) {
+                chart.data.labels.push(label);
+                chart.data.datasets.forEach((dataset, index) => {
+                    const dataPoint = Array.isArray(newData) ? newData[index] : newData;
+                    dataset.data.push(dataPoint);
+                });
+                while (chart.data.labels.length > historySize) {
+                    chart.data.labels.shift();
+                    chart.data.datasets.forEach(dataset => dataset.data.shift());
+                }
+                chart.update('none');
+            }
 
-            [cpuBuffer, ramBuffer, swapBuffer, netUpBuffer, netDownBuffer].forEach((buf, i) => {
-                buf.push(newData[i]);
-            });
+            // --- CORREGIDO: Se usa el timestamp del servidor para la etiqueta en vivo ---
+            const newLabel = formatTime(new Date(data.system_info.timestamp_utc));
 
-            // Procesar cada minuto (12 muestras de 5 segundos)
-            if (cpuBuffer.length >= 12) {
-                const avg = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
-                addMinuteData(
-                    avg(cpuBuffer), 
-                    ramBuffer.at(-1), 
-                    swapBuffer.at(-1), 
-                    avg(netUpBuffer), 
-                    avg(netDownBuffer)
-                );
-                
-                // Limpiar buffers
-                [cpuBuffer, ramBuffer, swapBuffer, netUpBuffer, netDownBuffer].forEach(buf => buf.length = 0);
+            appendLiveData(cpuChart, newLabel, parseFloat(data.system_info.cpu.usage.replace('%','')));
+            appendLiveData(ramChart, newLabel, sizeToBytes(data.system_info.ram.used));
+            appendLiveData(swapChart, newLabel, sizeToBytes(data.system_info.swap.used));
+            if (data.network_stats) {
+                appendLiveData(networkChart, newLabel, [ data.network_stats.up_mbps, data.network_stats.down_mbps ]);
             }
         });
 
-        // Actualizar anillos con datos actuales
-        updateRings({
-            cpu: {
-                usage: "{{ system_info.cpu.usage }}",
-                physical_cores: "{{ system_info.cpu.physical_cores }}",
-                current_freq: "{{ system_info.cpu.current_freq }}"
-            },
-            ram: {
-                percent: "{{ system_info.ram.percent }}",
-                used: "{{ system_info.ram.used }}",
-                total: "{{ system_info.ram.total }}"
-            },
-            swap: {
-                percent: "{{ system_info.swap.percent }}",
-                used: "{{ system_info.swap.used }}",
-                total: "{{ system_info.swap.total }}"
-            }
+        document.addEventListener('DOMContentLoaded', function() {
+            maxRamBytes = sizeToBytes("{{ system_info.ram.total }}");
+            maxSwapBytes = sizeToBytes("{{ system_info.swap.total }}");
+            ramChart.options.scales.y.max = maxRamBytes;
+            swapChart.options.scales.y.max = maxSwapBytes;
+            updateRings({
+                cpu: { usage: "{{ system_info.cpu.usage }}", percent: "{{ system_info.cpu.usage }}" },
+                ram: { used: "{{ system_info.ram.used }}", percent: "{{ system_info.ram.percent }}" },
+                swap: { used: "{{ system_info.swap.used }}", percent: "{{ system_info.swap.percent }}" }
+            });
+            loadHistoricData();
         });
-
     </script>
 </body>
-
 </html>

+ 217 - 330
templates/components/graph_reports.html

@@ -1,349 +1,236 @@
 <!DOCTYPE html>
 <html lang="es">
-  <head>
-    <meta charset="UTF-8" />
-    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Dashboard de Navegación</title>
-    <script src="https://cdn.tailwindcss.com"></script>
-    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
-    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
-  </head>
-  <body class="bg-gray-100">
+    <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
+</head>
+<body class="bg-gray-100">
     <div class="container mx-auto px-4 py-8">
-      <header class="mb-8">
-        <h1 class="text-3xl font-bold text-gray-800">
-          Dashboard de Navegación
-        </h1>
-        <div class="flex flex-wrap justify-between mt-4 items-center gap-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>
-          <!-- Datepicker agregado -->
-          <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"
-              disabled>
-          </div>
-        </div>
-      </header>
+        <header class="mb-8">
+            <h1 class="text-3xl font-bold text-gray-800">Dashboard de Navegación</h1>
+            <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>
+        </header>
 
-      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
-        <div class="bg-white p-6 rounded-lg shadow-md">
-          <h2 class="text-xl font-bold mb-4 text-gray-800">
-            Top 20 Usuarios por Actividad
-          </h2>
-          <div class="h-80">
-            <canvas id="usersActivityChart"></canvas>
-          </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">
+                <h2 class="text-xl font-bold mb-4 text-gray-800">Top 20 Usuarios por Actividad</h2>
+                <div class="h-80">
+                    <canvas id="usersActivityChart"></canvas>
+                </div>
+            </div>
 
-        <div class="bg-white p-6 rounded-lg shadow-md">
-          <h2 class="text-xl font-bold mb-4 text-gray-800">
-            Top 20 Usuarios por Datos Transmitidos
-          </h2>
-          <div class="h-80">
-            <canvas id="usersDataChart"></canvas>
-          </div>
+            <div class="bg-white p-6 rounded-lg shadow-md">
+                <h2 class="text-xl font-bold mb-4 text-gray-800">Top 20 Usuarios por Datos Transmitidos</h2>
+                <div class="h-80">
+                    <canvas id="usersDataChart"></canvas>
+                </div>
+            </div>
         </div>
-      </div>
 
-      <div class="bg-white p-6 rounded-lg shadow-md mb-8">
-        <h2 class="text-xl font-bold mb-4 text-gray-800">
-          Distribución de Códigos HTTP
-        </h2>
-        <div class="h-96">
-          <canvas id="httpCodesChart"></canvas>
+        <div class="bg-white p-6 rounded-lg shadow-md mb-8">
+            <h2 class="text-xl font-bold mb-4 text-gray-800">Distribución de Códigos HTTP</h2>
+            <div class="h-96">
+                <canvas id="httpCodesChart"></canvas>
+            </div>
         </div>
-      </div>
 
-      <div class="bg-white p-6 rounded-lg shadow-md mb-8">
-        <h2 class="text-xl font-bold mb-4 text-gray-800">
-          Top 20 Páginas Más Visitadas
-        </h2>
-        <div class="overflow-x-auto">
-          <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"
-                >
-                  URL
-                </th>
-                <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"
-                >
-                  Visitas Únicas
-                </th>
-                <th
-                  class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
-                >
-                  Datos Transmitidos
-                </th>
-              </tr>
-            </thead>
-            <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"
-                >
-                  {{ page.url }}
-                </td>
-                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
-                  {{ page.total_requests }}
-                </td>
-                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
-                  {{ page.unique_visits }}
-                </td>
-                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
-                  {{ "%.2f"|format(page.total_data_bytes / (1024**2)) }} MB
-                </td>
-              </tr>
-              {% endfor %}
-            </tbody>
-          </table>
+        <div class="bg-white p-6 rounded-lg shadow-md mb-8">
+            <h2 class="text-xl font-bold mb-4 text-gray-800">Top 20 Páginas Más Visitadas</h2>
+            <div class="overflow-x-auto">
+                <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">URL</th>
+                            <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">Visitas Únicas</th>
+                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Datos Transmitidos</th>
+                        </tr>
+                    </thead>
+                    <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">{{ page.url }}</td>
+                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ page.total_requests }}</td>
+                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ page.unique_visits }}</td>
+                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ "%.2f"|format(page.total_data_bytes / (1024**2)) }} MB</td>
+                        </tr>
+                        {% endfor %}
+                    </tbody>
+                </table>
+            </div>
         </div>
-      </div>
 
-      <div class="bg-white p-6 rounded-lg shadow-md">
-        <h2 class="text-xl font-bold mb-4 text-gray-800">
-          IPs Compartidas por Múltiples Usuarios
-        </h2>
-        <div class="overflow-x-auto">
-          <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"
-                >
-                  IP
-                </th>
-                <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"
-                >
-                  Usuarios
-                </th>
-              </tr>
-            </thead>
-            <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"
-                >
-                  {{ ip.ip }}
-                </td>
-                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
-                  {{ ip.user_count }}
-                </td>
-                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
-                  {{ ip.usernames }}
-                </td>
-              </tr>
-              {% endfor %}
-            </tbody>
-          </table>
+        <div class="bg-white p-6 rounded-lg shadow-md">
+            <h2 class="text-xl font-bold mb-4 text-gray-800">IPs Compartidas por Múltiples Usuarios</h2>
+            <div class="overflow-x-auto">
+                <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">IP</th>
+                            <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">Usuarios</th>
+                        </tr>
+                    </thead>
+                    <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">{{ ip.ip }}</td>
+                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ ip.user_count }}</td>
+                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ ip.usernames }}</td>
+                        </tr>
+                        {% endfor %}
+                    </tbody>
+                </table>
+            </div>
         </div>
-      </div>
     </div>
 
-    <script type="module">
-      import { getLocalDateString } from "../static/js/utils/fecha.js";
-      const chartColors = [
-          '#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
-          '#EC4899', '#14B8A6', '#F97316', '#64748B', '#84CC16',
-          '#06B6D4', '#D946EF', '#F43F5E', '#0EA5E9', '#22C55E',
-          '#EAB308', '#F43F5E', '#8B5CF6', '#EC4899', '#14B8A6'
-      ];
-
-      const usersActivityCtx = document.getElementById('usersActivityChart').getContext('2d');
-      new Chart(usersActivityCtx, {
-          type: 'bar',
-          data: {
-              labels: {{ metrics.top_users_by_activity | map(attribute='username') | list | tojson }},
-              datasets: [{
-                  label: 'Visitas',
-                  data: {{ metrics.top_users_by_activity | map(attribute='total_visits') | list | tojson }},
-                  backgroundColor: chartColors,
-                  borderColor: chartColors.map(color => color.replace('0.6', '1')),
-                  borderWidth: 1
-              }]
-          },
-          options: {
-              responsive: true,
-              maintainAspectRatio: false,
-              plugins: {
-                  legend: { display: false },
-                  tooltip: { mode: 'index', intersect: false },
-                  datalabels: { display: false }
-              },
-              scales: {
-                  y: { beginAtZero: true, title: { display: true, text: 'Número de Visitas' } },
-                  x: { ticks: { autoSkip: false } }
-              }
-          }
-      });
+    <script>
+        const chartColors = [
+            '#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
+            '#EC4899', '#14B8A6', '#F97316', '#64748B', '#84CC16',
+            '#06B6D4', '#D946EF', '#F43F5E', '#0EA5E9', '#22C55E',
+            '#EAB308', '#F43F5E', '#8B5CF6', '#EC4899', '#14B8A6'
+        ];
 
-      const usersDataCtx = document.getElementById('usersDataChart').getContext('2d');
-      new Chart(usersDataCtx, {
-          type: 'bar',
-          data: {
-              labels: {{ metrics.top_users_by_data_transferred | map(attribute='username') | list | tojson }},
-              datasets: [{
-                  label: 'Datos (MB)',
-                  data: {{ metrics.top_users_by_data_transferred | map(attribute='total_data_bytes') |
-                          map('divide', 1048576) | list | tojson }},
-                  backgroundColor: chartColors,
-                  borderColor: chartColors.map(color => color.replace('0.6', '1')),
-                  borderWidth: 1
-              }]
-          },
-          options: {
-              responsive: true,
-              maintainAspectRatio: false,
-              plugins: {
-                  legend: { display: false },
-                  tooltip: {
-                      mode: 'index',
-                      intersect: false,
-                      callbacks: {
-                          label: function(context) {
-                              return `${context.dataset.label}: ${context.raw.toFixed(2)} MB`;
-                          }
-                      }
-                  },
-                  datalabels: { display: false }
-              },
-              scales: {
-                  y: {
-                      beginAtZero: true,
-                      title: { display: true, text: 'Datos Transmitidos (MB)' }
-                  },
-                  x: { ticks: { autoSkip: false } }
-              }
-          }
-      });
+        const usersActivityCtx = document.getElementById('usersActivityChart').getContext('2d');
+        new Chart(usersActivityCtx, {
+            type: 'bar',
+            data: {
+                labels: {{ metrics.top_users_by_activity | map(attribute='username') | list | tojson }},
+                datasets: [{
+                    label: 'Visitas',
+                    data: {{ metrics.top_users_by_activity | map(attribute='total_visits') | list | tojson }},
+                    backgroundColor: chartColors,
+                    borderColor: chartColors.map(color => color.replace('0.6', '1')),
+                    borderWidth: 1
+                }]
+            },
+            options: {
+                responsive: true,
+                maintainAspectRatio: false,
+                plugins: {
+                    legend: { display: false },
+                    tooltip: { mode: 'index', intersect: false },
+                    datalabels: { display: false }
+                },
+                scales: {
+                    y: { beginAtZero: true, title: { display: true, text: 'Número de Visitas' } },
+                    x: { ticks: { autoSkip: false } }
+                }
+            }
+        });
 
-      const httpCodesCtx = document.getElementById('httpCodesChart').getContext('2d');
-      new Chart(httpCodesCtx, {
-          type: 'pie',
-          data: {
-              labels: {{ metrics.http_response_distribution_chart.labels | tojson }},
-              datasets: [{
-                  data: {{ metrics.http_response_distribution_chart.data | tojson }},
-                  backgroundColor: {{ metrics.http_response_distribution_chart.colors | tojson }},
-                  borderColor: '#fff',
-                  borderWidth: 1
-              }]
-          },
-          options: {
-              responsive: true,
-              maintainAspectRatio: false,
-              plugins: {
-                  legend: {
-                      position: 'right',
-                      labels: {
-                          font: {
-                              size: 12
-                          }
-                      }
-                  },
-                  tooltip: {
-                      callbacks: {
-                          label: function(context) {
-                              const total = context.dataset.data.reduce((a, b) => a + b, 0);
-                              const percentage = (context.raw / total * 100).toFixed(1);
-                              return `${context.label}: ${context.raw} (${percentage}%)`;
-                          }
-                      }
-                  },
-                  datalabels: {
-                      formatter: (value, ctx) => {
-                          const total = ctx.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
-                          const percentage = (value / total * 100).toFixed(1);
-                          return percentage > 3 ? `${percentage}%` : '';
-                      },
-                      color: '#fff',
-                      font: {
-                          weight: 'bold',
-                          size: 12
-                      }
-                  }
-              }
-          },
-          plugins: [ChartDataLabels]
-      });
+        const usersDataCtx = document.getElementById('usersDataChart').getContext('2d');
+        new Chart(usersDataCtx, {
+            type: 'bar',
+            data: {
+                labels: {{ metrics.top_users_by_data_transferred | map(attribute='username') | list | tojson }},
+                datasets: [{
+                    label: 'Datos (MB)',
+                    data: {{ metrics.top_users_by_data_transferred | map(attribute='total_data_bytes') |
+                            map('divide', 1048576) | list | tojson }},
+                    backgroundColor: chartColors,
+                    borderColor: chartColors.map(color => color.replace('0.6', '1')),
+                    borderWidth: 1
+                }]
+            },
+            options: {
+                responsive: true,
+                maintainAspectRatio: false,
+                plugins: {
+                    legend: { display: false },
+                    tooltip: {
+                        mode: 'index',
+                        intersect: false,
+                        callbacks: {
+                            label: function(context) {
+                                return `${context.dataset.label}: ${context.raw.toFixed(2)} MB`;
+                            }
+                        }
+                    },
+                    datalabels: { display: false }
+                },
+                scales: {
+                    y: {
+                        beginAtZero: true,
+                        title: { display: true, text: 'Datos Transmitidos (MB)' }
+                    },
+                    x: { ticks: { autoSkip: false } }
+                }
+            }
+        });
 
-      function getUrlParam(name) {
-        const url = new URL(window.location.href);
-        return url.searchParams.get(name);
-      }
-      function setUrlParam(name, value) {
-        const url = new URL(window.location.href);
-        if (value) {
-          url.searchParams.set(name, value);
-        } else {
-          url.searchParams.delete(name);
-        }
-        window.location.href = url.toString();
-      }
-      const dateInput = document.getElementById('date-filter');
-      if (dateInput) {
-        let paramDate = getUrlParam('date');
-        if (!paramDate) {
-          const today = getLocalDateString();
-          dateInput.value = today;
-        } else {
-          dateInput.value = paramDate;
-        }
-        // dateInput.addEventListener('change', function() {
-        //   if (this.value) setUrlParam('date', this.value);
-        // });
-      }
+        const httpCodesCtx = document.getElementById('httpCodesChart').getContext('2d');
+        new Chart(httpCodesCtx, {
+            type: 'pie',
+            data: {
+                labels: {{ metrics.http_response_distribution_chart.labels | tojson }},
+                datasets: [{
+                    data: {{ metrics.http_response_distribution_chart.data | tojson }},
+                    backgroundColor: {{ metrics.http_response_distribution_chart.colors | tojson }},
+                    borderColor: '#fff',
+                    borderWidth: 1
+                }]
+            },
+            options: {
+                responsive: true,
+                maintainAspectRatio: false,
+                plugins: {
+                    legend: {
+                        position: 'right',
+                        labels: {
+                            font: {
+                                size: 12
+                            }
+                        }
+                    },
+                    tooltip: {
+                        callbacks: {
+                            label: function(context) {
+                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
+                                const percentage = (context.raw / total * 100).toFixed(1);
+                                return `${context.label}: ${context.raw} (${percentage}%)`;
+                            }
+                        }
+                    },
+                    datalabels: {
+                        formatter: (value, ctx) => {
+                            const total = ctx.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
+                            const percentage = (value / total * 100).toFixed(1);
+                            return percentage > 3 ? `${percentage}%` : '';
+                        },
+                        color: '#fff',
+                        font: {
+                            weight: 'bold',
+                            size: 12
+                        }
+                    }
+                }
+            },
+            plugins: [ChartDataLabels]
+        });
     </script>
-  </body>
-</html>
+</body>
+</html>

+ 1 - 2
templates/components/logs.html

@@ -49,5 +49,4 @@
 
 <div class="overlay fixed inset-0 bg-black bg-opacity-50 z-50 hidden transition-opacity duration-1000 ease-in-out opacity-0" id="overlay"></div>
 
-<script type="module" src="static/js/dashboard.js"></script>
-
+<script type="module" src="static/js/dashboard.js"></script>

+ 60 - 10
templates/index.html

@@ -3,30 +3,80 @@
 {% block title %}Inicio | Dashboard Squid{% endblock %}
 
 {% block content %}
-    <!-- Contenedor dinámico para conexiones -->
-    <div id="datos-conexiones">
-        {% include 'partials/conexiones.html' %}  <!-- Incluye plantilla parcial -->
+
+    <div id="datos-conexiones" class="max-w-7xl mx-auto sm:px-6 lg:px-8">
+        {% include 'partials/conexiones.html' %}
     </div>
     
     <script>
+        // --- NUEVO: Variable para guardar el estado de la vista ---
+        // Se inicializa en 'true' porque la vista por defecto es detallada.
+        let isDetailedView = true;
+
+        // --- NUEVO: Función central para aplicar el estado a la vista ---
+        // Esta función lee la variable 'isDetailedView' y actualiza el DOM.
+        function applyViewState() {
+            const contents = document.querySelectorAll('[data-accordion-content]');
+            const icons = document.querySelectorAll('.user-accordion .fa-chevron-down');
+            const toggleAllButton = document.getElementById('toggle-all-button');
+
+            if (contents.length === 0 || !toggleAllButton) return;
+
+            if (isDetailedView) {
+                // Aplica la VISTA DETALLADA
+                contents.forEach(content => content.classList.remove('hidden'));
+                icons.forEach(icon => icon.classList.add('rotate-180'));
+                toggleAllButton.textContent = 'Ver Resumen';
+            } else {
+                // Aplica la VISTA DE RESUMEN
+                contents.forEach(content => content.classList.add('hidden'));
+                icons.forEach(icon => icon.classList.remove('rotate-180'));
+                toggleAllButton.textContent = 'Ver Detalles';
+            }
+        }
+
+        // Función para configurar el botón. Ahora solo cambia el estado y llama a applyViewState.
+        function setupSummaryButton() {
+            const toggleAllButton = document.getElementById('toggle-all-button');
+            if (!toggleAllButton) return;
+
+            // Se usa cloneNode y replaceWith para evitar añadir múltiples listeners en cada refresco.
+            const newButton = toggleAllButton.cloneNode(true);
+            toggleAllButton.parentNode.replaceChild(newButton, toggleAllButton);
+
+            newButton.addEventListener('click', () => {
+                isDetailedView = !isDetailedView; // Cambia el estado guardado
+                applyViewState(); // Aplica el nuevo estado a la vista
+            });
+        }
+
         async function refrescarConexiones() {
             try {
-                // Obtiene HTML actualizado del servidor
                 const response = await fetch('/actualizar-conexiones');
                 if (!response.ok) throw new Error("Respuesta no OK");
                 
-                // Reemplaza TODO el contenido del contenedor
                 const html = await response.text();
-                document.getElementById('datos-conexiones').innerHTML = html;
+                const container = document.getElementById('datos-conexiones');
+                container.innerHTML = html;
+
+                // Vuelve a configurar el botón para el nuevo contenido
+                setupSummaryButton();
+
+                // --- ¡CAMBIO CLAVE! ---
+                // Después de refrescar, aplica el último estado que guardamos.
+                applyViewState();
+
             } catch (error) {
                 console.error("Error al actualizar conexiones:", error);
             }
         }
 
-        // Actualiza cada 60 segundos (problema: no se limpia al cambiar página)
-        setInterval(refrescarConexiones, 60000);
+        document.addEventListener('DOMContentLoaded', () => {
+            // Configura el botón de resumen cuando la página carga por primera vez
+            setupSummaryButton();
 
-        // Actualiza al cargar la página
-        window.onload = refrescarConexiones;
+            // Configura el refresco para que se ejecute cada 60 segundos
+            setInterval(refrescarConexiones, 60000);
+        });
     </script>
 {% endblock %}

+ 183 - 159
templates/partials/conexiones.html

@@ -1,176 +1,200 @@
-{# Filtro para usuarios válidos (se mantiene igual) #}
 {% set valid_users = {} %}
-{% for user, connections in grouped_connections.items() %}
+{% for user, user_data in grouped_connections.items() %}
     {% if user and user != "-" and user != "Anónimo" %}
-        {% set _ = valid_users.update({user: connections}) %}
+        {% set _ = valid_users.update({user: user_data}) %}
     {% endif %}
 {% endfor %}
 
-{# Tarjetas de estadísticas con iconos Font Awesome y efectos hover #}
-<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
-    <!-- Tarjeta 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-3">
-            <i class="fas fa-users text-blue-500"></i>
-        </div>
-        <div>
-            <p class="text-gray-500 text-sm">Usuarios Activos</p>
-            <p class="text-xl font-bold">{{ valid_users|length }}</p>
-        </div>
-    </div>
-    
-    <!-- Tarjeta 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-3">
-            <i class="fas fa-exchange-alt text-green-500"></i>
-        </div>
-        <div>
-            <p class="text-gray-500 text-sm">Conexiones Totales</p>
-            <p class="text-xl font-bold">
-                {% set total = namespace(value=0) %}
-                {% for connections in valid_users.values() %}
-                    {% set total.value = total.value + connections|length %}
-                {% endfor %}
-                {{ total.value }}
-            </p>
-        </div>
-    </div>
-</div>
+<div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
 
-{# Lista de usuarios y conexiones #}
-{% for user, connections in valid_users.items() %}
-<!-- Contenedor principal de usuario con efecto hover -->
-<div class="bg-white rounded-lg shadow-md mb-6 overflow-hidden transition-all duration-300 ease-in-out hover:shadow-lg">
-    <!-- Encabezado de usuario con iconos FA -->
-    <div class="p-4 border-b flex flex-col sm:flex-row sm:items-center sm:justify-between">
-        <div class="flex items-center mb-2 sm:mb-0">
-            <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3">
-                <i class="fas fa-user text-blue-600"></i>
-            </div>
-            <h2 class="text-lg font-bold">{{ user }}</h2>
-        </div>
-        
-        <div class="flex flex-wrap gap-3">
-            <div class="flex items-center text-sm text-gray-600">
-                <i class="fas fa-link mr-1 text-blue-500"></i>
-                <span>{{ connections|length }} conexiones</span>
-            </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 %}
+    {# Tarjetas de estadísticas #}
+    <div class="flex justify-center mb-8">
+        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6 w-full max-w-6xl">
             
-            <div class="flex items-center text-sm text-gray-600">
-                <i class="fas fa-database mr-1 text-green-500"></i>
-                <span>{{ (total_data.value / 1024 / 1024)|round(2) }} MB</span>
+            {# --- MODIFICADO: 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 (v{{ squid_version }})</p>
+                    <p class="text-2xl font-bold">{{ squid_ip }}</p>
+                </div>
             </div>
             
-            <div class="flex items-center text-sm text-gray-600">
-                <i class="fas fa-bullhorn mr-1 text-purple-500"></i>
-                <span>{{ total_requests.value }} solicitudes</span>
+            {# --- MODIFICADO: Tarjeta de estado del Proxy Padre --- #}
+            {% if parent_proxy_ip %}
+            {# Estado Con Padre #}
+            <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-sitemap text-green-500 text-xl"></i>
+                </div>
+                <div>
+                    <p class="text-gray-500 text-sm">Proxy Padre Activo</p>
+                    <p class="text-2xl font-bold">{{ parent_proxy_ip }}</p>
+                </div>
+            </div>
+            {% else %}
+            {# Estado Sin Padre #}
+            <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-gray-100 flex items-center justify-center mr-4 flex-shrink-0">
+                    <i class="fas fa-plug-circle-xmark text-gray-500 text-xl"></i>
+                </div>
+                <div>
+                    <p class="text-gray-500 text-sm">Sin Proxy Padre</p>
+                    <p class="text-2xl font-bold">Conexión Directa</p>
+                </div>
+            </div>
+            {% endif %}
+
+            {# 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>
         </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() %}
     
-    <!-- Tabla de conexiones - Columna "Dir. Local" eliminada -->
-    <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">Tiempo</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">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 %}
-                <!-- Fila con efecto hover y transición -->
-                <tr class="transition-colors duration-200 ease-in-out hover:bg-gray-50">
-                    <!-- Tiempo -->
-                    <td class="px-4 py-3 whitespace-nowrap text-sm">
-                        {% set seconds = connection.elapsed_time|float %}
-                        {% if seconds >= 3600 %}
-                        {{ "%.2f"|format(seconds/3600) }} horas
-                        {% elif seconds >= 60 %}
-                        {{ "%.2f"|format(seconds/60) }} min
-                        {% else %}
-                        {{ "%.2f"|format(seconds) }} seg
+    {% 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>
+                
+                <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 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 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 %}
-                        </td>
-                        
-                        <!-- Método HTTP con colores mejorados -->
-                        <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 transition-colors duration-200
-                                {% if method == 'connect' or method == 'tcp_tunnel' %}bg-green-100 text-green-800  {# CAMBIO: Connect ahora es verde #}
-                                {% elif method == 'get' %}bg-sky-100 text-sky-800  {# CAMBIO: Get ahora es azul cielo #}
-                                {% elif method == 'post' %}bg-indigo-100 text-indigo-800  {# CAMBIO: Post ahora es índigo #}
-                                {% elif method == 'put' %}bg-amber-100 text-amber-800  {# CAMBIO: Put ahora es ámbar #}
-                                {% elif method == 'delete' %}bg-red-100 text-red-800
-                                {% elif method == 'head' %}bg-purple-100 text-purple-800
-                                {% elif method == 'options' %}bg-cyan-100 text-cyan-800
-                                {% else %}bg-gray-100 text-gray-800{% endif %}">
-                                {{ connection.logType }}
-                            </span>
-                        </td>
-                        
-                        <!-- URL con truncado mejorado -->
-                        <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>
-                        
-                        <!-- Datos -->
-                        <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>
-                        
-                        <!-- Delay Pool con colores para 5 clases diferentes -->
-                        <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 transition-colors duration-200
-                                    {% if pool == '0' %}bg-sky-100 text-sky-800  
-                                    {% elif pool == '1' %}bg-indigo-100 text-indigo-800
-                                    {% elif pool == '2' %}bg-purple-100 text-purple-800
-                                    {% elif pool == '3' %}bg-pink-100 text-pink-800
-                                    {% elif pool == '4' %}bg-yellow-100 text-yellow-800
-                                    {% elif pool == '5' %}bg-green-100 text-green-800
-                                    {% else %}bg-gray-100 text-gray-800{% endif %}">
-                                Pool {{ connection.delay_pool }}
-                            </span>
-                            {% else %}
-                            <span class="text-sm text-gray-500">N/A</span>
-                            {% endif %}
-                        </td>
-                        
-                        <!-- Solicitudes -->
-                        <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
-                            {{ connection.nrequests }}
-                        </td>
-                        
-                        <!-- Dir. Remota (única columna de IP) -->
-                        <td class="px-4 py-3 whitespace-nowrap text-sm font-mono transition-colors duration-200 hover:text-blue-600">
-                            {{ connection.remote }}
-                        </td>
+                        {% set total_requests.value = total_requests.value + connection.nrequests %}
+                    {% endfor %}
+                    
+                    <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="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 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">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">
+                                {% 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>
+                                {% else %}<span class="text-sm text-gray-500">N/A</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>
+                    </tbody>
+                </table>
+            </div>
+        </div>
+    </div>
+    {% endfor %}
     </div>
-</div>
-{% endfor %}
+</div>

+ 15 - 0
utils/size.py

@@ -0,0 +1,15 @@
+def size_to_bytes(size_str):
+        # Convierte '123 MB' o '1.2 GB' a bytes
+        size_str = str(size_str).strip().upper()
+        if size_str.endswith('GB'):
+            return int(float(size_str.replace('GB','').strip()) * 1024**3)
+        elif size_str.endswith('MB'):
+            return int(float(size_str.replace('MB','').strip()) * 1024**2)
+        elif size_str.endswith('KB'):
+            return int(float(size_str.replace('KB','').strip()) * 1024)
+        elif size_str.endswith('BYTES'):
+            return int(float(size_str.replace('BYTES','').strip()))
+        try:
+            return int(size_str)
+        except Exception:
+            return 0

Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff