Browse Source

feat: add more information squid and re formated code html

Manuel 1 year ago
parent
commit
7aa86095d1

+ 5 - 0
app.py

@@ -23,6 +23,7 @@ from database.database import get_dynamic_models, get_session
 from parsers.cache import fetch_squid_cache_stats
 from parsers.connections import group_by_user, parse_raw_data
 from parsers.log import find_last_parent_proxy, process_logs
+from parsers.squid_info import fetch_squid_info_stats
 from services.auditoria_service import (
     find_by_ip,
     find_by_keyword,
@@ -126,12 +127,16 @@ def index():
         if isinstance(network_info, list) and network_info:
             squid_ip = network_info[0].get("ip", "No disponible")
 
+        # Obtener estadísticas detalladas de Squid
+        squid_info_stats = fetch_squid_info_stats()
+
         return render_template(
             "index.html",
             grouped_connections=grouped_connections,
             parent_proxy_ip=parent_ip,
             squid_ip=squid_ip,
             squid_version=squid_version,
+            squid_info_stats=squid_info_stats,
             page_icon="favicon.ico",
             page_title="Inicio Dashboard",
         )

+ 0 - 1
services/system_info.py

@@ -220,7 +220,6 @@ def get_network_stats():
 
 
 def get_timezone():
-    """Obtiene la zona horaria del sistema"""
     try:
         if os.path.exists("/etc/timezone"):
             with open("/etc/timezone") as f:

+ 44 - 23
templates/base.html

@@ -1,34 +1,55 @@
 <!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>{{ page_title or 'Dashboard Squid' }}</title>
-    
+
     <!-- Favicon dinámico -->
-    <link rel="icon" href="{{ url_for('static', filename=page_icon) }}" type="image/x-icon">
+    <link
+      rel="icon"
+      href="{{ url_for('static', filename=page_icon) }}"
+      type="image/x-icon"
+    />
 
     <!-- Hojas de estilo -->
-    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
-    <link rel="stylesheet" href="{{url_for('static',filename='dist/output.css')}}">
-    <link rel="stylesheet" href="{{ url_for('static', filename='all.min.css') }}"> <!-- Font Awesome -->
-    <link rel="stylesheet" href="{{ url_for('static', filename='logs.css') }}">
-</head>
-<body class="overflow-x-hidden overflow-auto" style="visibility: hidden;" onload="document.body.style.visibility='visible';">
+    <link
+      rel="stylesheet"
+      href="{{ url_for('static', filename='styles.css') }}"
+    />
+    <link
+      rel="stylesheet"
+      href="{{url_for('static',filename='dist/output.css')}}"
+    />
+    <link
+      rel="stylesheet"
+      href="{{ url_for('static', filename='all.min.css') }}"
+    />
+    <!-- Font Awesome -->
+    <link
+      rel="stylesheet"
+      href="{{ url_for('static', filename='logs.css') }}"
+    />
+  </head>
+  <body
+    class="overflow-x-hidden overflow-auto"
+    style="visibility: hidden"
+    onload="document.body.style.visibility='visible';"
+  >
     <!-- Barra de navegación común -->
     <div class="relative">
-        {% include 'components/navbar.html' %}
-        <!-- Dropdown de notificaciones -->
-        <div class="absolute top-4 right-8 z-50">
-            <div class="relative inline-block text-left">
-            </div>
-        </div>
-        <main>
-            {% block content %}{% endblock %}  <!-- Contenido específico de cada página -->
-        </main>
+      {% include 'components/navbar.html' %}
+      <!-- Dropdown de notificaciones -->
+      <div class="absolute top-4 right-8 z-50">
+        <div class="relative inline-block text-left"></div>
+      </div>
+      <main>
+        {% block content %}{% endblock %}
+        <!-- Contenido específico de cada página -->
+      </main>
     </div>
-    
+
     <!-- Scripts de Flowbite (UI components) -->
     <script src="{{ url_for('static', filename='src/flowbite.min.js') }}"></script>
-</body>
-</html>
+  </body>
+</html>

+ 3 - 9
templates/blacklist.html

@@ -1,9 +1,3 @@
-
-{% extends 'base.html' %}
-
-{% block title %}BlackList | Dashboard Squid{% endblock %}
-
-{% block content %}
-    {% include 'components/black_list.html' %}
-
-{% endblock %}
+{% extends 'base.html' %} {% block title %}BlackList | Dashboard Squid{%
+endblock %} {% block content %} {% include 'components/black_list.html' %} {%
+endblock %}

+ 6 - 6
templates/cacheView.html

@@ -1,9 +1,9 @@
+{% extends 'base.html' %}
+<!-- Hereda de base.html -->
 
-{% extends 'base.html' %}  <!-- Hereda de base.html -->
-
-{% block title %}Cache | Dashboard Squid{% endblock %}  <!-- Título específico -->
+{% block title %}Cache | Dashboard Squid{% endblock %}
+<!-- Título específico -->
 
 {% block content %}
-    <!-- Muestra estadísticas de caché -->
-    {% include 'components/cache_stats.html' %}
-{% endblock %}
+<!-- Muestra estadísticas de caché -->
+{% include 'components/cache_stats.html' %} {% endblock %}

+ 106 - 78
templates/components/auditoria.html

@@ -1,5 +1,8 @@
 <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
-<link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}">
+<link
+  rel="stylesheet"
+  href="{{ url_for('static', filename='css/toastr.min.css') }}"
+/>
 <script src="{{ url_for('static', filename='js/jquery-3.7.1.min.js') }}"></script>
 <script src="{{ url_for('static', filename='js/toastr.min.js') }}"></script>
 
@@ -139,18 +142,19 @@
                 class="w-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-gray-50 pr-8"
                 autocomplete="off"
               />
-              <i class="fas fa-search absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm"></i>
-              <div id="user-dropdown" class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-48 overflow-y-auto hidden">
+              <i
+                class="fas fa-search absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm"
+              ></i>
+              <div
+                id="user-dropdown"
+                class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-48 overflow-y-auto hidden"
+              >
                 <div id="user-options-container">
                   <!-- Las opciones se llenarán dinámicamente -->
                 </div>
               </div>
             </div>
-            <select
-              id="username-filter"
-              name="username"
-              class="hidden"
-            >
+            <select id="username-filter" name="username" class="hidden">
               <option value="">-- Todos --</option>
             </select>
           </div>
@@ -347,23 +351,22 @@
 </div>
 
 <script>
-
   toastr.options = {
-    "closeButton": false,
-    "debug": false,
-    "newestOnTop": true,
-    "progressBar": false,
-    "positionClass": "toast-top-right",
-    "preventDuplicates": true,
-    "onclick": null,
-    "showDuration": "300",
-    "hideDuration": "1000",
-    "timeOut": "5000",
-    "extendedTimeOut": "1000",
-    "showEasing": "swing",
-    "hideEasing": "linear",
-    "showMethod": "fadeIn",
-    "hideMethod": "fadeOut"
+    closeButton: false,
+    debug: false,
+    newestOnTop: true,
+    progressBar: false,
+    positionClass: "toast-top-right",
+    preventDuplicates: true,
+    onclick: null,
+    showDuration: "300",
+    hideDuration: "1000",
+    timeOut: "5000",
+    extendedTimeOut: "1000",
+    showEasing: "swing",
+    hideEasing: "linear",
+    showMethod: "fadeIn",
+    hideMethod: "fadeOut",
   };
 
   function toggleDetails(header) {
@@ -411,11 +414,11 @@
     const getLocalDateString = () => {
       const today = new Date();
       const year = today.getFullYear();
-      const month = String(today.getMonth() + 1).padStart(2, '0');
-      const day = String(today.getDate()).padStart(2, '0');
+      const month = String(today.getMonth() + 1).padStart(2, "0");
+      const day = String(today.getDate()).padStart(2, "0");
       return `${year}-${month}-${day}`;
     };
-    
+
     const todayString = getLocalDateString();
     startDateInput.value = todayString;
     endDateInput.value = todayString;
@@ -426,37 +429,46 @@
     let selectedUserIndex = -1;
     const userSearchInput = document.getElementById("user-search-input");
     const userDropdown = document.getElementById("user-dropdown");
-    const userOptionsContainer = document.getElementById("user-options-container");
+    const userOptionsContainer = document.getElementById(
+      "user-options-container"
+    );
     const usernameFilterSelect = document.getElementById("username-filter");
 
     // Función para renderizar las opciones de usuarios
     function renderUserOptions(users, searchTerm = "") {
       userOptionsContainer.innerHTML = "";
-      
+
       // Agregar opción "Todos" si no hay término de búsqueda
       if (!searchTerm) {
         const allOption = document.createElement("div");
-        allOption.className = "px-3 py-2 hover:bg-blue-50 cursor-pointer text-gray-700 border-b border-gray-100";
+        allOption.className =
+          "px-3 py-2 hover:bg-blue-50 cursor-pointer text-gray-700 border-b border-gray-100";
         allOption.textContent = "-- Todos --";
         allOption.dataset.value = "";
-        allOption.addEventListener("click", () => selectUser("", "-- Todos --"));
+        allOption.addEventListener("click", () =>
+          selectUser("", "-- Todos --")
+        );
         userOptionsContainer.appendChild(allOption);
       }
 
       users.forEach((user, index) => {
         const option = document.createElement("div");
-        option.className = "px-3 py-2 hover:bg-blue-50 cursor-pointer text-gray-700";
+        option.className =
+          "px-3 py-2 hover:bg-blue-50 cursor-pointer text-gray-700";
         option.textContent = user;
         option.dataset.value = user;
         option.dataset.index = index;
         option.addEventListener("click", () => selectUser(user, user));
-        
+
         // Resaltar texto coincidente
         if (searchTerm) {
-          const regex = new RegExp(`(${searchTerm})`, 'gi');
-          option.innerHTML = user.replace(regex, '<mark class="bg-yellow-200">$1</mark>');
+          const regex = new RegExp(`(${searchTerm})`, "gi");
+          option.innerHTML = user.replace(
+            regex,
+            '<mark class="bg-yellow-200">$1</mark>'
+          );
         }
-        
+
         userOptionsContainer.appendChild(option);
       });
 
@@ -481,7 +493,7 @@
       if (!searchTerm) {
         filteredUsers = [...allUsers];
       } else {
-        filteredUsers = allUsers.filter(user => 
+        filteredUsers = allUsers.filter((user) =>
           user.toLowerCase().includes(searchTerm.toLowerCase())
         );
       }
@@ -489,21 +501,21 @@
     }
 
     // Event listeners para el buscador de usuarios
-    userSearchInput.addEventListener("input", function(e) {
+    userSearchInput.addEventListener("input", function (e) {
       const searchTerm = e.target.value;
       filterUsers(searchTerm);
       userDropdown.classList.remove("hidden");
       selectedUserIndex = -1;
     });
 
-    userSearchInput.addEventListener("focus", function() {
+    userSearchInput.addEventListener("focus", function () {
       filterUsers(userSearchInput.value);
       userDropdown.classList.remove("hidden");
     });
 
-    userSearchInput.addEventListener("keydown", function(e) {
+    userSearchInput.addEventListener("keydown", function (e) {
       const options = userOptionsContainer.querySelectorAll("[data-value]");
-      
+
       if (e.key === "ArrowDown") {
         e.preventDefault();
         selectedUserIndex = Math.min(selectedUserIndex + 1, options.length - 1);
@@ -531,8 +543,11 @@
     }
 
     // Cerrar dropdown al hacer clic fuera
-    document.addEventListener("click", function(e) {
-      if (!userSearchInput.contains(e.target) && !userDropdown.contains(e.target)) {
+    document.addEventListener("click", function (e) {
+      if (
+        !userSearchInput.contains(e.target) &&
+        !userDropdown.contains(e.target)
+      ) {
         userDropdown.classList.add("hidden");
         selectedUserIndex = -1;
       }
@@ -543,7 +558,7 @@
       .then((users) => {
         allUsers = users;
         filteredUsers = [...users];
-        
+
         // Llenar el select oculto para compatibilidad
         users.forEach((user) => {
           const option = document.createElement("option");
@@ -551,7 +566,7 @@
           option.textContent = user;
           usernameFilterSelect.appendChild(option);
         });
-        
+
         renderUserOptions(filteredUsers);
         /* toastr.success(`${users.length} usuarios cargados`, "Usuarios disponibles", {
           "timeOut": 2000 */
@@ -618,15 +633,16 @@
     // Función para restaurar el botón de envío a su estado original
     function restoreSubmitButton() {
       const submitButton = form.querySelector('button[type="submit"]');
-      const buttonIcon = submitButton.querySelector('i');
-      
+      const buttonIcon = submitButton.querySelector("i");
+
       submitButton.disabled = false;
-      submitButton.classList.remove('opacity-50', 'cursor-not-allowed');
-      submitButton.classList.add('hover:bg-blue-700', 'hover:shadow-xl');
-      
+      submitButton.classList.remove("opacity-50", "cursor-not-allowed");
+      submitButton.classList.add("hover:bg-blue-700", "hover:shadow-xl");
+
       // Restaurar el icono y texto original
-      buttonIcon.className = 'fas fa-play mr-2';
-      submitButton.innerHTML = '<i class="fas fa-play mr-2"></i>Generar Reporte';
+      buttonIcon.className = "fas fa-play mr-2";
+      submitButton.innerHTML =
+        '<i class="fas fa-play mr-2"></i>Generar Reporte';
     }
 
     form.addEventListener("submit", function (event) {
@@ -651,7 +667,10 @@
         return;
       }
       if (requiredInputs.includes("keyword") && !data.keyword) {
-        toastr.error("Por favor, ingrese una palabra clave.", "Campo requerido");
+        toastr.error(
+          "Por favor, ingrese una palabra clave.",
+          "Campo requerido"
+        );
         return;
       }
       if (requiredInputs.includes("ip") && !data.ip_address) {
@@ -659,14 +678,20 @@
         return;
       }
       if (requiredInputs.includes("response_code") && !data.response_code) {
-        toastr.error("Por favor, seleccione un código de respuesta.", "Campo requerido");
+        toastr.error(
+          "Por favor, seleccione un código de respuesta.",
+          "Campo requerido"
+        );
         return;
       }
       if (
         requiredInputs.includes("social_media") &&
         data.social_media_sites.length === 0
       ) {
-        toastr.error("Por favor, seleccione al menos una red social.", "Campo requerido");
+        toastr.error(
+          "Por favor, seleccione al menos una red social.",
+          "Campo requerido"
+        );
         return;
       }
 
@@ -679,21 +704,23 @@
 
       // Deshabilitar el botón y cambiar su apariencia
       const submitButton = form.querySelector('button[type="submit"]');
-      const buttonIcon = submitButton.querySelector('i');
-      const buttonText = submitButton.querySelector('span') || submitButton.lastChild;
-      
+      const buttonIcon = submitButton.querySelector("i");
+      const buttonText =
+        submitButton.querySelector("span") || submitButton.lastChild;
+
       submitButton.disabled = true;
-      submitButton.classList.add('opacity-50', 'cursor-not-allowed');
-      submitButton.classList.remove('hover:bg-blue-700', 'hover:shadow-xl');
-      
+      submitButton.classList.add("opacity-50", "cursor-not-allowed");
+      submitButton.classList.remove("hover:bg-blue-700", "hover:shadow-xl");
+
       // Cambiar el icono a spinner
-      buttonIcon.className = 'fas fa-spinner fa-spin mr-2';
-      
+      buttonIcon.className = "fas fa-spinner fa-spin mr-2";
+
       // Cambiar el texto del botón
       if (buttonText.nodeType === Node.TEXT_NODE) {
-        buttonText.textContent = 'Generando Reporte...';
+        buttonText.textContent = "Generando Reporte...";
       } else {
-        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Generando Reporte...';
+        submitButton.innerHTML =
+          '<i class="fas fa-spinner fa-spin mr-2"></i>Generando Reporte...';
       }
 
       resultsContainer.innerHTML = `
@@ -713,18 +740,21 @@
         .then((result) => {
           toastr.clear();
           restoreSubmitButton();
-          
+
           if (result.error) {
             toastr.error(result.error, "Error en la auditoría");
           } else {
-            toastr.success("Reporte generado exitosamente", "Auditoría completada");
+            toastr.success(
+              "Reporte generado exitosamente",
+              "Auditoría completada"
+            );
           }
           renderResults(data.audit_type, result, data);
         })
         .catch((error) => {
           toastr.clear();
           restoreSubmitButton();
-          
+
           toastr.error("Error de conexión con el servidor", "Error de red");
           resultsContainer.innerHTML = `<div class="bg-white p-6 rounded-lg shadow-lg"><div class="text-center text-red-500 py-10"><strong>Error de red o del servidor:</strong> ${error}</div></div>`;
         });
@@ -739,8 +769,7 @@
           html = renderUserSummary(data);
         } else if (auditType === "top_users_data") {
           html = renderTopUsers(data);
-        }
-        else if (auditType === "daily_activity") {
+        } else if (auditType === "daily_activity") {
           const user = formData.username;
           const date = formData.start_date;
           let title = `Distribución de Peticiones para '${user}' el ${date}`;
@@ -753,8 +782,7 @@
           } else {
             html = `<div class="bg-white p-6 rounded-lg shadow-lg"><h2 class="text-2xl font-bold mb-4">${title}</h2><p class="text-gray-500">No se encontraron peticiones para la fecha y usuario seleccionado.</p></div>`;
           }
-        }
-        else if (
+        } else if (
           [
             "keyword_search",
             "ip_activity",
@@ -1098,11 +1126,11 @@
     function renderResponseChart(canvas, responses) {
       // Mapeo de códigos de respuesta a colores
       const getResponseColor = (code) => {
-        if (code >= 500) return '#DC2626'; // Error de servidor
-        if (code >= 400) return '#F59E0B'; // Error de cliente
-        if (code >= 300) return '#3B82F6'; // Redirección
-        if (code >= 200) return '#10B981'; // Éxito
-        return '#6B7280'; // Otros
+        if (code >= 500) return "#DC2626"; // Error de servidor
+        if (code >= 400) return "#F59E0B"; // Error de cliente
+        if (code >= 300) return "#3B82F6"; // Redirección
+        if (code >= 200) return "#10B981"; // Éxito
+        return "#6B7280"; // Otros
       };
 
       // Configuración del gráfico
@@ -1131,7 +1159,7 @@
                 },
                 padding: 10,
                 usePointStyle: true,
-                pointStyle: 'circle'
+                pointStyle: "circle",
               },
             },
             tooltip: {

+ 892 - 341
templates/components/cache_stats.html

@@ -1,386 +1,937 @@
-{% macro flip_card(icon, title, value, back_title, description, extra_html='') %}
+{% macro flip_card(icon, title, value, back_title, description, extra_html='')
+%}
 <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)]"
+  >
     <div
-        class="relative h-full w-full rounded-xl shadow-xl transition-all duration-500 [transform-style:preserve-3d] group-hover:[transform:rotateY(180deg)]">
-        <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>
-            <h3 class="text-lg font-semibold text-gray-800">{{ title }}</h3>
-            {% if extra_html %}
-            {{ extra_html | safe }}
-            {% else %}
-            <p class="text-xl text-blue-800" data-stat="{{ title|replace(' ', '_')|lower }}">{{ value }}</p>
-            {% endif %}
-        </div>
-        <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>
-            <p class="text-sm">{{ description }}</p>
-        </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>
+      <h3 class="text-lg font-semibold text-gray-800">{{ title }}</h3>
+      {% if extra_html %} {{ extra_html | safe }} {% else %}
+      <p
+        class="text-xl text-blue-800"
+        data-stat="{{ title|replace(' ', '_')|lower }}"
+      >
+        {{ value }}
+      </p>
+      {% endif %}
     </div>
+    <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>
+      <p class="text-sm">{{ description }}</p>
+    </div>
+  </div>
 </div>
 {% endmacro %}
 
 <!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 Sistema</title>
-    <link rel="icon" href="{{ url_for('static', filename=page_icon) }}" type="image/x-icon">
+    <link
+      rel="icon"
+      href="{{ url_for('static', filename=page_icon) }}"
+      type="image/x-icon"
+    />
     <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
-    <link rel="stylesheet" href="{{ url_for('static', filename='all.min.css') }}">
+    <link
+      rel="stylesheet"
+      href="{{ url_for('static', filename='all.min.css') }}"
+    />
     <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
     <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
     <script src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
     <style>
-        @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 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);
+        }
+      }
+      .value-change {
+        animation: pulse 1s;
+      }
+      @keyframes pulse {
+        0% {
+          transform: scale(1);
+        }
+        50% {
+          transform: scale(1.1);
         }
-        @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); } }
-        .time-range-btn { transition: all 0.3s ease; }
-        .time-range-btn.active { background-color: white; color: #2563eb; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); }
-        .time-range-btn:not(.active) { background-color: transparent; color: #6b7280; }
-        .time-range-btn:not(.active):hover { color: #2563eb; }
+        100% {
+          transform: scale(1);
+        }
+      }
+      .time-range-btn {
+        transition: all 0.3s ease;
+      }
+      .time-range-btn.active {
+        background-color: white;
+        color: #2563eb;
+        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
+      }
+      .time-range-btn:not(.active) {
+        background-color: transparent;
+        color: #6b7280;
+      }
+      .time-range-btn:not(.active):hover {
+        color: #2563eb;
+      }
     </style>
-</head>
+  </head>
 
-<body class="bg-gray-50">
+  <body class="bg-gray-50">
     <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>
-
-        <div class="flex border-b mb-6">
-            <button id="dashboardTab" class="main-tab-btn active relative overflow-hidden py-3 px-6 font-medium text-blue-600">
-                <i class="fas fa-tachometer-alt mr-2"></i>Dashboard del Sistema
-            </button>
-            <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>
+      <h1 class="text-3xl font-bold text-center text-gray-800 mb-8">
+        Dashboard de Estadísticas del Sistema
+      </h1>
 
-        <div id="dashboardContent" class="main-tab-content active">
-            <section class="mb-12">
-                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
-                    <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>
-                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 items-center justify-center">
-                            <div class="flex flex-col items-center justify-center">
-                                <div class="relative w-36 h-36">
-                                    <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>
-                                <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>
-                            <div class="flex flex-col items-center justify-center">
-                                <div class="relative w-36 h-36">
-                                    <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>
-                                <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>
-                            <div class="flex flex-col items-center justify-center">
-                                <div class="relative w-36 h-36">
-                                    <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>
-                                <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>
+      <div class="flex border-b mb-6">
+        <button
+          id="dashboardTab"
+          class="main-tab-btn active relative overflow-hidden py-3 px-6 font-medium text-blue-600"
+        >
+          <i class="fas fa-tachometer-alt mr-2"></i>Dashboard del Sistema
+        </button>
+        <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>
 
-                    <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>
-                            <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 id="dashboardContent" class="main-tab-content active">
+        <section class="mb-12">
+          <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
+            <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>
+              <div
+                class="grid grid-cols-1 md:grid-cols-3 gap-6 items-center justify-center"
+              >
+                <div class="flex flex-col items-center justify-center">
+                  <div class="relative w-36 h-36">
+                    <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>
+                  <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>
-            </section>
-
-            <section class="bg-white rounded-xl shadow-lg p-6 mb-12">
-                <div class="flex items-center justify-between mb-6">
-                    <h2 class="text-xl font-bold text-gray-800">Gráficas del Sistema</h2>
-                    <div class="flex bg-gray-100 rounded-lg p-1">
-                        <button id="todayBtn" class="time-range-btn active px-4 py-2 rounded-md text-sm font-medium text-blue-600 bg-white shadow">Hoy</button>
-                        <button id="24hoursBtn" class="time-range-btn px-4 py-2 rounded-md text-sm font-medium text-gray-500 hover:text-blue-600">24 Horas</button>
-                    </div>
+                <div class="flex flex-col items-center justify-center">
+                  <div class="relative w-36 h-36">
+                    <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>
+                  <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>
-                <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 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 class="flex flex-col items-center justify-center">
+                  <div class="relative w-36 h-36">
+                    <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>
+                  <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 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>
+              </div>
+            </div>
 
-        <div id="cacheContent" class="main-tab-content">
-            <section class="cache-stats">
-                <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
-                    <div class="flex items-center mb-6">
-                        <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">
-                        {{ 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 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>
-            </section>
-        </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 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="h-80"><canvas id="networkChart"></canvas></div>
-            </section>
-        </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>
+
+        <section class="bg-white rounded-xl shadow-lg p-6 mb-12">
+          <div class="flex items-center justify-between mb-6">
+            <h2 class="text-xl font-bold text-gray-800">
+              Gráficas del Sistema
+            </h2>
+            <div class="flex bg-gray-100 rounded-lg p-1">
+              <button
+                id="todayBtn"
+                class="time-range-btn active px-4 py-2 rounded-md text-sm font-medium text-blue-600 bg-white shadow"
+              >
+                Hoy
+              </button>
+              <button
+                id="24hoursBtn"
+                class="time-range-btn px-4 py-2 rounded-md text-sm font-medium text-gray-500 hover:text-blue-600"
+              >
+                24 Horas
+              </button>
+            </div>
+          </div>
+          <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 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>
+
+      <div id="cacheContent" class="main-tab-content">
+        <section class="cache-stats">
+          <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
+            <div class="flex items-center mb-6">
+              <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"
+            >
+              {{ 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>
+
+      <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>
-        Chart.register(ChartDataLabels);
+      Chart.register(ChartDataLabels);
 
-        let maxRamBytes = 0, maxSwapBytes = 0;
-        const historySize = 240; // Reducido de 720 a 240 (4 horas de datos con intervalos de 1 minuto)
-        let liveDataCounter = 0; // Contador para manejar datos en vivo 
-        
-        // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
-        function getLocalTimeString() {
-            const now = new Date();
-            let hours = now.getHours();
-            const minutes = now.getMinutes().toString().padStart(2, '0');
-            const ampm = hours >= 12 ? 'PM' : 'AM';
-            hours = hours % 12 || 12;
-            return `${hours}:${minutes} ${ampm}`;
-        }
-        
-        function formatTime(date) {
-            let hours = date.getHours();
-            const minutes = date.getMinutes().toString().padStart(2, '0');
-            const ampm = hours >= 12 ? 'PM' : 'AM';
-            hours = hours % 12 || 12;
-            return `${hours}:${minutes} ${ampm}`;
-        }
-        function openMainTab(tabName) {
-            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');
-            });
-            document.getElementById(tabName + 'Content').classList.add('active');
-            const tabBtn = document.getElementById(tabName + 'Tab');
-            tabBtn.classList.add('active', 'text-blue-600');
-            tabBtn.classList.remove('text-gray-500');
-        }
-        document.getElementById('dashboardTab').addEventListener('click', () => openMainTab('dashboard'));
-        document.getElementById('cacheTab').addEventListener('click', () => openMainTab('cache'));
-        document.getElementById('networkTab').addEventListener('click', () => openMainTab('network'));
-        document.querySelectorAll('.tab-btn').forEach((button, index) => {
-            button.addEventListener('click', () => {
-                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');
-                });
-                button.classList.add('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
-                button.classList.remove('text-gray-500');
-                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
-                document.querySelectorAll('.tab-content')[index].classList.add('active');
-            });
+      let maxRamBytes = 0,
+        maxSwapBytes = 0;
+      const historySize = 240; // Reducido de 720 a 240 (4 horas de datos con intervalos de 1 minuto)
+      let liveDataCounter = 0; // Contador para manejar datos en vivo
+
+      // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
+      function getLocalTimeString() {
+        const now = new Date();
+        let hours = now.getHours();
+        const minutes = now.getMinutes().toString().padStart(2, "0");
+        const ampm = hours >= 12 ? "PM" : "AM";
+        hours = hours % 12 || 12;
+        return `${hours}:${minutes} ${ampm}`;
+      }
+
+      function formatTime(date) {
+        let hours = date.getHours();
+        const minutes = date.getMinutes().toString().padStart(2, "0");
+        const ampm = hours >= 12 ? "PM" : "AM";
+        hours = hours % 12 || 12;
+        return `${hours}:${minutes} ${ampm}`;
+      }
+      function openMainTab(tabName) {
+        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");
         });
-        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)' } }
+        document.getElementById(tabName + "Content").classList.add("active");
+        const tabBtn = document.getElementById(tabName + "Tab");
+        tabBtn.classList.add("active", "text-blue-600");
+        tabBtn.classList.remove("text-gray-500");
+      }
+      document
+        .getElementById("dashboardTab")
+        .addEventListener("click", () => openMainTab("dashboard"));
+      document
+        .getElementById("cacheTab")
+        .addEventListener("click", () => openMainTab("cache"));
+      document
+        .getElementById("networkTab")
+        .addEventListener("click", () => openMainTab("network"));
+      document.querySelectorAll(".tab-btn").forEach((button, index) => {
+        button.addEventListener("click", () => {
+          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");
+          });
+          button.classList.add(
+            "active",
+            "text-blue-600",
+            "border-b-2",
+            "border-blue-600"
+          );
+          button.classList.remove("text-gray-500");
+          document
+            .querySelectorAll(".tab-content")
+            .forEach((content) => content.classList.remove("active"));
+          document
+            .querySelectorAll(".tab-content")
+            [index].classList.add("active");
+        });
+      });
+      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)" } },
+        },
+        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",
             },
-            plugins: { legend: { display: true }, datalabels: { display: false } }
+            {
+              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",
         };
-        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 con sampling optimizado ---
-        function loadHistoricData(endpoint = '/api/metrics/24hours') {
-            fetch(endpoint)
-                .then(response => response.json())
-                .then(data => {
-                    if (!data || data.length === 0) { 
-                        console.log(`No hay historial de métricas para el endpoint: ${endpoint}`); 
-                        return; 
-                    }
-                    
-                    // Implementar sampling inteligente para evitar sobrecarga
-                    let sampledData = data;
-                    if (data.length > 288) { // Si hay más de 288 puntos (4.8 horas con intervalos de 1 minuto)
-                        const sampleRate = Math.ceil(data.length / 288);
-                        sampledData = data.filter((_, index) => index % sampleRate === 0);
-                        console.log(`Aplicado sampling: ${data.length} → ${sampledData.length} puntos`);
-                    }
-                    
-                    const labels = [], cpuData = [], ramData = [], swapData = [], netUpData = [], netDownData = [];
-                    sampledData.forEach(metric => {
-                        // Crear fecha local desde el timestamp del servidor (ya incluye timezone)
-                        const localDate = new Date(metric.timestamp);
-                        labels.push(formatTime(localDate));
-                        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 {
-                            chart.data.datasets[0].data = chartData[chartIndex];
-                        }
-                        chart.update();
-                    });
-                })
-                .catch(error => console.error('Error al cargar historial de métricas:', error));
+      }
+      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 con sampling optimizado ---
+      function loadHistoricData(endpoint = "/api/metrics/24hours") {
+        fetch(endpoint)
+          .then((response) => response.json())
+          .then((data) => {
+            if (!data || data.length === 0) {
+              console.log(
+                `No hay historial de métricas para el endpoint: ${endpoint}`
+              );
+              return;
+            }
+
+            // Implementar sampling inteligente para evitar sobrecarga
+            let sampledData = data;
+            if (data.length > 288) {
+              // Si hay más de 288 puntos (4.8 horas con intervalos de 1 minuto)
+              const sampleRate = Math.ceil(data.length / 288);
+              sampledData = data.filter((_, index) => index % sampleRate === 0);
+              console.log(
+                `Aplicado sampling: ${data.length} → ${sampledData.length} puntos`
+              );
+            }
 
-        // --- AÑADIDO: Funcionalidad para alternar entre vistas de tiempo ---
-        function setupTimeRangeButtons() {
-            const todayBtn = document.getElementById('todayBtn');
-            const hoursBtn = document.getElementById('24hoursBtn');
-            
-            todayBtn.addEventListener('click', () => {
-                setActiveTimeRange(todayBtn, hoursBtn);
-                loadHistoricData('/api/metrics/today');
+            const labels = [],
+              cpuData = [],
+              ramData = [],
+              swapData = [],
+              netUpData = [],
+              netDownData = [];
+            sampledData.forEach((metric) => {
+              // Crear fecha local desde el timestamp del servidor (ya incluye timezone)
+              const localDate = new Date(metric.timestamp);
+              labels.push(formatTime(localDate));
+              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)
+              );
             });
-            
-            hoursBtn.addEventListener('click', () => {
-                setActiveTimeRange(hoursBtn, todayBtn);
-                loadHistoricData('/api/metrics/24hours');
+            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 {
+                chart.data.datasets[0].data = chartData[chartIndex];
+              }
+              chart.update();
             });
-        }
-        
-        function setActiveTimeRange(activeBtn, inactiveBtn) {
-            activeBtn.classList.add('active');
-            activeBtn.classList.remove('text-gray-500');
-            activeBtn.classList.add('text-blue-600', 'bg-white', 'shadow');
-            
-            inactiveBtn.classList.remove('active');
-            inactiveBtn.classList.add('text-gray-500');
-            inactiveBtn.classList.remove('text-blue-600', 'bg-white', 'shadow');
-        }
+          })
+          .catch((error) =>
+            console.error("Error al cargar historial de métricas:", error)
+          );
+      }
 
-        const socket = io();
-        socket.on('system_update', function (data) {
-            updateRings(data.system_info);
-            updateSystemInfo(data.system_info);
-            updateCacheStats(data.cache_stats);
+      // --- AÑADIDO: Funcionalidad para alternar entre vistas de tiempo ---
+      function setupTimeRangeButtons() {
+        const todayBtn = document.getElementById("todayBtn");
+        const hoursBtn = document.getElementById("24hoursBtn");
 
-            // Incrementar contador de datos en vivo
-            liveDataCounter++;
-            
-            // Solo actualizar gráficas cada 4 actualizaciones (1 minuto) para evitar sobrecarga
-            if (liveDataCounter % 4 === 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');
-                }
-
-                // --- CORREGIDO: Se usa la hora local del cliente para la etiqueta en vivo ---
-                const newLabel = getLocalTimeString();
+        todayBtn.addEventListener("click", () => {
+          setActiveTimeRange(todayBtn, hoursBtn);
+          loadHistoricData("/api/metrics/today");
+        });
 
-                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 ]);
-                }
-            }
+        hoursBtn.addEventListener("click", () => {
+          setActiveTimeRange(hoursBtn, todayBtn);
+          loadHistoricData("/api/metrics/24hours");
         });
+      }
+
+      function setActiveTimeRange(activeBtn, inactiveBtn) {
+        activeBtn.classList.add("active");
+        activeBtn.classList.remove("text-gray-500");
+        activeBtn.classList.add("text-blue-600", "bg-white", "shadow");
+
+        inactiveBtn.classList.remove("active");
+        inactiveBtn.classList.add("text-gray-500");
+        inactiveBtn.classList.remove("text-blue-600", "bg-white", "shadow");
+      }
+
+      const socket = io();
+      socket.on("system_update", function (data) {
+        updateRings(data.system_info);
+        updateSystemInfo(data.system_info);
+        updateCacheStats(data.cache_stats);
 
-        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 }}" }
+        // Incrementar contador de datos en vivo
+        liveDataCounter++;
+
+        // Solo actualizar gráficas cada 4 actualizaciones (1 minuto) para evitar sobrecarga
+        if (liveDataCounter % 4 === 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);
             });
-            
-            // Inicializar botones de rango de tiempo
-            setupTimeRangeButtons();
-            
-            // Cargar datos históricos (por defecto 24 horas)
-            loadHistoricData('/api/metrics/24hours');
+            while (chart.data.labels.length > historySize) {
+              chart.data.labels.shift();
+              chart.data.datasets.forEach((dataset) => dataset.data.shift());
+            }
+            chart.update("none");
+          }
+
+          // --- CORREGIDO: Se usa la hora local del cliente para la etiqueta en vivo ---
+          const newLabel = getLocalTimeString();
+
+          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,
+            ]);
+          }
+        }
+      });
+
+      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 }}",
+          },
         });
+
+        // Inicializar botones de rango de tiempo
+        setupTimeRangeButtons();
+
+        // Cargar datos históricos (por defecto 24 horas)
+        loadHistoricData("/api/metrics/24hours");
+      });
     </script>
-</body>
-</html>
+  </body>
+</html>

+ 172 - 152
templates/components/connections.html

@@ -1,161 +1,181 @@
-{# Filtro para usuarios válidos (se mantiene igual) #}
-{% set valid_users = {} %}
-{% for user, connections in grouped_connections.items() %}
-    {% if user and user != "-" and user != "Anónimo" %}
-        {% set _ = valid_users.update({user: connections}) %}
-    {% endif %}
-{% endfor %}
-
-{# Tarjetas de estadísticas con iconos Font Awesome #}
+{# Filtro para usuarios válidos (se mantiene igual) #} {% set valid_users = {}
+%} {% for user, connections in grouped_connections.items() %} {% if user and
+user != "-" and user != "Anónimo" %} {% set _ = valid_users.update({user:
+connections}) %} {% endif %} {% endfor %} {# Tarjetas de estadísticas con iconos
+Font Awesome #}
 <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">
-        <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>
+  <!-- Tarjeta Usuarios Activos -->
+  <div class="bg-white p-4 rounded-lg shadow flex items-center">
+    <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>
-    
-    <!-- Tarjeta Conexiones Totales -->
-    <div class="bg-white p-4 rounded-lg shadow flex items-center">
-        <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>
+
+  <!-- Tarjeta Conexiones Totales -->
+  <div class="bg-white p-4 rounded-lg shadow flex items-center">
+    <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>
 
-{# Lista de usuarios y conexiones #}
-{% for user, connections in valid_users.items() %}
+{# Lista de usuarios y conexiones #} {% for user, connections in
+valid_users.items() %}
 <div class="bg-white rounded-lg shadow-md mb-6 overflow-hidden">
-    <!-- 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 %}
-            
-            <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>
-            </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>
-            </div>
-        </div>
+  <!-- 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>
-    
-    <!-- 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 %}
-                <tr class="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
-                        {% endif %}
-                    </td>
-                    
-                    <!-- Método con estilos mejorados -->
-                    <td class="px-4 py-3 whitespace-nowrap">
-                        <span class="px-2 py-1 rounded-full text-xs font-semibold 
-                            {% if connection.logType|lower == 'get' %}bg-green-100 text-green-800
-                            {% elif connection.logType|lower == 'post' %}bg-blue-100 text-blue-800
-                            {% elif connection.logType|lower == 'connect' %}bg-yellow-100 text-yellow-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" 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 estilos -->
-                    <td class="px-4 py-3 whitespace-nowrap">
-                        {% if connection.delay_pool != "N/A" %}
-                            <span class="px-2 py-1 rounded-full text-xs font-semibold bg-indigo-100 text-indigo-800">
-                                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">
-                        {{ connection.remote }}
-                    </td>
-                </tr>
-                {% endfor %}
-            </tbody>
-        </table>
+
+    <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 %}
+
+      <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>
+      </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>
+      </div>
     </div>
+  </div>
+
+  <!-- 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 %}
+        <tr class="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 {% endif %}
+          </td>
+
+          <!-- Método con estilos mejorados -->
+          <td class="px-4 py-3 whitespace-nowrap">
+            <span
+              class="px-2 py-1 rounded-full text-xs font-semibold {% if connection.logType|lower == 'get' %}bg-green-100 text-green-800 {% elif connection.logType|lower == 'post' %}bg-blue-100 text-blue-800 {% elif connection.logType|lower == 'connect' %}bg-yellow-100 text-yellow-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" 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 estilos -->
+          <td class="px-4 py-3 whitespace-nowrap">
+            {% if connection.delay_pool != "N/A" %}
+            <span
+              class="px-2 py-1 rounded-full text-xs font-semibold bg-indigo-100 text-indigo-800"
+            >
+              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">
+            {{ connection.remote }}
+          </td>
+        </tr>
+        {% endfor %}
+      </tbody>
+    </table>
+  </div>
 </div>
-{% endfor %}
+{% endfor %}

+ 292 - 213
templates/components/graph_reports.html

@@ -1,236 +1,315 @@
 <!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="{{ 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">
+  </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">
-                <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>
+      <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>
+        <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 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 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 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 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 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 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>
 
     <script>
-        const chartColors = [
-            '#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
-            '#EC4899', '#14B8A6', '#F97316', '#64748B', '#84CC16',
-            '#06B6D4', '#D946EF', '#F43F5E', '#0EA5E9', '#22C55E',
-            '#EAB308', '#F43F5E', '#8B5CF6', '#EC4899', '#14B8A6'
-        ];
+      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 } }
-                }
-            }
-        });
+      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 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 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 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 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>

+ 74 - 31
templates/components/logs.html

@@ -1,52 +1,95 @@
 <div class="users-dashboard max-w-[1200px] mx-auto p-8">
-  <div class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4">
-    <h1 class="dashboard-title text-center font-semibold text-[2.2rem] text-blue-500">Panel Actividad de Usuarios</h1>
+  <div
+    class="dashboard-header flex justify-between items-center mb-8 flex-wrap gap-4"
+  >
+    <h1
+      class="dashboard-title text-center font-semibold text-[2.2rem] text-blue-500"
+    >
+      Panel Actividad de Usuarios
+    </h1>
     <div class="filters-container flex gap-4 items-center">
-      <div class="date-filter max-w-xs mx-auto rounded-[0.5rem] shadow-md overflow-hidden relative">
-        <input type="date" id="date-filter"
-          class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-white shadow-sm text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 h-12">
+      <div
+        class="date-filter max-w-xs mx-auto rounded-[0.5rem] shadow-md overflow-hidden relative"
+      >
+        <input
+          type="date"
+          id="date-filter"
+          class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-white shadow-sm text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 h-12"
+        />
       </div>
 
-      <div class="search-container flex items-center bg-white rounded-[0.5rem] shadow-md overflow-hidden w-[250px] relative">
-    <input type="text" id="username-search" placeholder="Buscar por usuario..."
-        class="search-input w-full pl-4 pr-10 py-3 rounded-[0.5rem] border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-800 h-12">
-    
-    <!-- Botón de limpiar búsqueda (NUEVO) -->
-    <button id="clear-search" class="absolute right-10 h-full flex items-center justify-center text-gray-400 hover:text-gray-700 hidden" title="Limpiar búsqueda">
-        <i class="fas fa-times"></i>
-    </button>
-    
-    <div class="absolute inset-y-0 right-3 flex items-center pointer-events-none">
-        <i class="fas fa-magnifying-glass text-xl text-[#1A8A9D]"></i>
-    </div>
-</div>
+      <div
+        class="search-container flex items-center bg-white rounded-[0.5rem] shadow-md overflow-hidden w-[250px] relative"
+      >
+        <input
+          type="text"
+          id="username-search"
+          placeholder="Buscar por usuario..."
+          class="search-input w-full pl-4 pr-10 py-3 rounded-[0.5rem] border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-800 h-12"
+        />
+
+        <!-- Botón de limpiar búsqueda (NUEVO) -->
+        <button
+          id="clear-search"
+          class="absolute right-10 h-full flex items-center justify-center text-gray-400 hover:text-gray-700 hidden"
+          title="Limpiar búsqueda"
+        >
+          <i class="fas fa-times"></i>
+        </button>
+
+        <div
+          class="absolute inset-y-0 right-3 flex items-center pointer-events-none"
+        >
+          <i class="fas fa-magnifying-glass text-xl text-[#1A8A9D]"></i>
+        </div>
+      </div>
     </div>
   </div>
 
-  <div class="users-container grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 max-w-screen-xl mx-auto px-4" id="users-container"></div>
+  <div
+    class="users-container grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 max-w-screen-xl mx-auto px-4"
+    id="users-container"
+  ></div>
   <div id="modals-container"></div>
-  <div class="pagination-container flex justify-center items-center mt-12 gap-4">
-    <button id="first-page" aria-label="First page"
-      class="pg-btn first w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none">
+  <div
+    class="pagination-container flex justify-center items-center mt-12 gap-4"
+  >
+    <button
+      id="first-page"
+      aria-label="First page"
+      class="pg-btn first w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none"
+    >
       <i class="fas fa-angle-double-left"></i>
     </button>
-    <button id="prev-page" aria-label="Previous page"
-      class="pg-btn prev w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none">
+    <button
+      id="prev-page"
+      aria-label="Previous page"
+      class="pg-btn prev w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none"
+    >
       <i class="fas fa-angle-left"></i>
     </button>
     <!-- Aquí el JS generará los botones de página -->
     <div class="pagination flex gap-1" id="page-numbers"></div>
-    <button id="next-page" aria-label="Next page"
-      class="pg-btn next w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none">
+    <button
+      id="next-page"
+      aria-label="Next page"
+      class="pg-btn next w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none"
+    >
       <i class="fas fa-angle-right"></i>
     </button>
-    <button id="last-page" aria-label="Last page"
-      class="pg-btn last w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none">
+    <button
+      id="last-page"
+      aria-label="Last page"
+      class="pg-btn last w-12 h-12 flex items-center justify-center rounded-full bg-white text-blue-600 cursor-pointer font-semibold shadow-md transition-all duration-200 ease-in-out text-xl hover:-translate-y-1 disabled:cursor-not-allowed disabled:opacity-50 disabled:transform-none"
+    >
       <i class="fas fa-angle-double-right"></i>
     </button>
-  </div> 
+  </div>
 </div>
 
-<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>
+<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>

+ 89 - 22
templates/components/navbar.html

@@ -1,34 +1,67 @@
-<nav class="sticky top-0 z-[1000] bg-gradient-to-br from-blue-800 to-blue-900 shadow-lg border-b border-white/10 backdrop-blur-md">
-  <div class="max-w-[1200px] mx-auto flex items-center justify-between px-6 py-3 h-[60px]">
+<nav
+  class="sticky top-0 z-[1000] bg-gradient-to-br from-blue-800 to-blue-900 shadow-lg border-b border-white/10 backdrop-blur-md"
+>
+  <div
+    class="max-w-[1200px] mx-auto flex items-center justify-between px-6 py-3 h-[60px]"
+  >
     <!-- Brand/Logo Section -->
-    <div class="flex items-center gap-3 font-bold text-xl text-white no-underline">
+    <div
+      class="flex items-center gap-3 font-bold text-xl text-white no-underline"
+    >
       <i class="fas fa-chart-line text-blue-300 text-2xl"></i>
-      <span class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300">SquidStats</span>
+      <span
+        class="font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-white to-blue-300"
+        >SquidStats</span
+      >
     </div>
 
     <!-- Navigation Links -->
     <div class="flex items-center gap-2">
-      <a href="/" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Panel principal con conexiones activas">
+      <a
+        href="/"
+        class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5"
+        data-tooltip="Panel principal con conexiones activas"
+      >
         <i class="fas fa-home text-base"></i>
         <span class="font-medium">Inicio</span>
       </a>
-      <a href="/stats" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Estadísticas de rendimiento del cache">
+      <a
+        href="/stats"
+        class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5"
+        data-tooltip="Estadísticas de rendimiento del cache"
+      >
         <i class="fas fa-chart-bar text-base"></i>
         <span class="font-medium">Estadísticas</span>
       </a>
-      <a href="/logs" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Actividad y logs de usuarios">
+      <a
+        href="/logs"
+        class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5"
+        data-tooltip="Actividad y logs de usuarios"
+      >
         <i class="fas fa-user-friends text-base"></i>
         <span class="font-medium">Usuarios</span>
       </a>
-      <a href="/reports" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Reportes y gráficas avanzadas">
+      <a
+        href="/reports"
+        class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5"
+        data-tooltip="Reportes y gráficas avanzadas"
+      >
         <i class="fas fa-chart-simple text-base"></i>
         <span class="font-medium">Reportes</span>
       </a>
-      <a href="/blacklist" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Sitios bloqueados y actividad restringida">
+      <a
+        href="/blacklist"
+        class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5"
+        data-tooltip="Sitios bloqueados y actividad restringida"
+      >
         <i class="fas fa-ban text-base"></i>
         <span class="font-medium">Blacklist</span>
       </a>
-      <a href="/auditoria" class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5" data-tooltip="Auditoría de actividad por usuario y fecha">
+      <a
+        href="/auditoria"
+        class="flex items-center gap-2 px-4 py-2 text-gray-200 rounded-lg font-medium text-sm transition-all duration-300 relative hover:text-white hover:bg-white/10 hover:-translate-y-0.5"
+        data-tooltip="Auditoría de actividad por usuario y fecha"
+      >
         <i class="fas fa-magnifying-glass text-base"></i>
         <span class="font-medium">Auditoría</span>
       </a>
@@ -77,7 +110,13 @@
               <span
                 class="inline-flex items-center justify-center h-8 w-8 rounded-full bg-blue-100 text-blue-600 mr-3"
               >
-                <i class="fas fa-info-circle"></i>
+                <Información del Sistema:
+✅ Hostname del servidor
+✅ Sistema operativo
+✅ Tiempo de actividad del sistema
+✅ Uso de memoria RAM y Swap
+✅ Información de CPU
+✅ Zona horaria y hora locali class="fas fa-info-circle"></i>
               </span>
               <div class="flex-1">
                 <p class="text-sm text-gray-700">
@@ -160,13 +199,19 @@
         class="fixed inset-0 z-[1001] flex items-center justify-center bg-black bg-opacity-50"
         style="display: none"
       >
-        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden">
+        <div
+          class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden"
+        >
           <div class="bg-gradient-to-r from-yellow-500 to-orange-500 px-6 py-4">
             <div class="flex items-center gap-3">
-              <div class="flex items-center justify-center w-10 h-10 bg-white bg-opacity-20 rounded-full">
+              <div
+                class="flex items-center justify-center w-10 h-10 bg-white bg-opacity-20 rounded-full"
+              >
                 <i class="fas fa-exclamation-triangle text-white text-lg"></i>
               </div>
-              <h3 class="text-xl font-bold text-white">Confirmar Actualización de Squid</h3>
+              <h3 class="text-xl font-bold text-white">
+                Confirmar Actualización de Squid
+              </h3>
             </div>
           </div>
           <div class="px-6 py-4">
@@ -181,13 +226,19 @@
                   <ul class="text-blue-800 text-sm mt-1 space-y-1">
                     <li>• Guarda tu configuración antes de continuar</li>
                     <li>• El servicio se reiniciará automáticamente</li>
-                    <li>• Puede haber incompatibilidades con versiones anteriores</li>
+                    <li>
+                      • Puede haber incompatibilidades con versiones anteriores
+                    </li>
                   </ul>
                 </div>
               </div>
             </div>
           </div>
-          <form method="POST" action="/install" class="flex justify-end gap-3 px-6 py-4 bg-gray-50">
+          <form
+            method="POST"
+            action="/install"
+            class="flex justify-end gap-3 px-6 py-4 bg-gray-50"
+          >
             <button
               type="button"
               @click="showSquidModal = false"
@@ -196,7 +247,10 @@
               <i class="fas fa-times"></i>
               Cancelar
             </button>
-            <button type="submit" class="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-emerald-600 to-emerald-500 text-white rounded-lg hover:from-emerald-700 hover:to-emerald-600 transition-all duration-200">
+            <button
+              type="submit"
+              class="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-emerald-600 to-emerald-500 text-white rounded-lg hover:from-emerald-700 hover:to-emerald-600 transition-all duration-200"
+            >
               <i class="fas fa-check"></i>
               Confirmar
             </button>
@@ -216,13 +270,19 @@
         class="fixed inset-0 z-[1001] flex items-center justify-center bg-black bg-opacity-50"
         style="display: none"
       >
-        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden">
+        <div
+          class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 overflow-hidden"
+        >
           <div class="bg-gradient-to-r from-blue-500 to-purple-600 px-6 py-4">
             <div class="flex items-center gap-3">
-              <div class="flex items-center justify-center w-10 h-10 bg-white bg-opacity-20 rounded-full">
+              <div
+                class="flex items-center justify-center w-10 h-10 bg-white bg-opacity-20 rounded-full"
+              >
                 <i class="fas fa-cloud-download-alt text-white text-lg"></i>
               </div>
-              <h3 class="text-xl font-bold text-white">Confirmar Actualización Web</h3>
+              <h3 class="text-xl font-bold text-white">
+                Confirmar Actualización Web
+              </h3>
             </div>
           </div>
           <div class="px-6 py-4">
@@ -243,7 +303,11 @@
               </div>
             </div>
           </div>
-          <form method="POST" action="/update" class="flex justify-end gap-3 px-6 py-4 bg-gray-50">
+          <form
+            method="POST"
+            action="/update"
+            class="flex justify-end gap-3 px-6 py-4 bg-gray-50"
+          >
             <button
               type="button"
               @click="showWebModal = false"
@@ -252,7 +316,10 @@
               <i class="fas fa-times"></i>
               Cancelar
             </button>
-            <button type="submit" class="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-purple-600 to-purple-500 text-white rounded-lg hover:from-purple-700 hover:to-purple-600 transition-all duration-200">
+            <button
+              type="submit"
+              class="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-purple-600 to-purple-500 text-white rounded-lg hover:from-purple-700 hover:to-purple-600 transition-all duration-200"
+            >
               <i class="fas fa-download"></i>
               Actualizar
             </button>

+ 50 - 42
templates/error.html

@@ -1,53 +1,61 @@
 <!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>Error - Squid Monitor</title>
-    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
+    <link
+      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
+      rel="stylesheet"
+    />
     <style>
-        body {
-            background-color: #f8f9fa;
-            display: flex;
-            justify-content: center;
-            align-items: center;
-            height: 100vh;
-            margin: 0;
-        }
-        .error-container {
-            text-align: center;
-            padding: 2rem;
-            background-color: #ffffff;
-            border-radius: 8px;
-            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
-        }
-        .error-icon {
-            font-size: 4rem;
-            color: #dc3545;
-            margin-bottom: 1rem;
-        }
-        .error-message {
-            font-size: 1.25rem;
-            margin-bottom: 1rem;
-        }
-        .btn-home {
-            margin-top: 1rem;
-        }
+      body {
+        background-color: #f8f9fa;
+        display: flex;
+        justify-content: center;
+        align-items: center;
+        height: 100vh;
+        margin: 0;
+      }
+      .error-container {
+        text-align: center;
+        padding: 2rem;
+        background-color: #ffffff;
+        border-radius: 8px;
+        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
+      }
+      .error-icon {
+        font-size: 4rem;
+        color: #dc3545;
+        margin-bottom: 1rem;
+      }
+      .error-message {
+        font-size: 1.25rem;
+        margin-bottom: 1rem;
+      }
+      .btn-home {
+        margin-top: 1rem;
+      }
     </style>
-</head>
-<body>
+  </head>
+  <body>
     <div class="error-container">
-        <div class="error-icon">
-            <i class="bi bi-exclamation-triangle-fill"></i>
-        </div>
-        <h1 class="error-message">{{ message }}</h1>
-        <p>Disculpamos las molestias. Por favor, intenta de nuevo más tarde o contacta al soporte si el problema persiste.</p>
-        <a href="/" class="btn btn-primary btn-home">Volver al Inicio</a>
+      <div class="error-icon">
+        <i class="bi bi-exclamation-triangle-fill"></i>
+      </div>
+      <h1 class="error-message">{{ message }}</h1>
+      <p>
+        Disculpamos las molestias. Por favor, intenta de nuevo más tarde o
+        contacta al soporte si el problema persiste.
+      </p>
+      <a href="/" class="btn btn-primary btn-home">Volver al Inicio</a>
     </div>
 
     <!-- Bootstrap JS e Iconos -->
     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
-    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
-</body>
+    <link
+      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"
+      rel="stylesheet"
+    />
+  </body>
 </html>
-

+ 64 - 68
templates/index.html

@@ -1,82 +1,78 @@
-{% extends 'base.html' %}
+{% extends 'base.html' %} {% block title %}Inicio | Dashboard Squid{% endblock
+%} {% block content %}
 
-{% block title %}Inicio | Dashboard Squid{% endblock %}
+<div id="datos-conexiones" class="max-w-7xl mx-auto sm:px-6 lg:px-8">
+  {% include 'partials/conexiones.html' %}
+</div>
 
-{% block content %}
+<script>
+  // --- NUEVO: Variable para guardar el estado de la vista ---
+  // Se inicializa en 'true' porque la vista por defecto es detallada.
+  let isDetailedView = true;
 
-    <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");
 
-        // --- 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 (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";
+    }
+  }
 
-            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;
 
-        // 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);
 
-            // 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
+    });
+  }
 
-            newButton.addEventListener('click', () => {
-                isDetailedView = !isDetailedView; // Cambia el estado guardado
-                applyViewState(); // Aplica el nuevo estado a la vista
-            });
-        }
+  async function refrescarConexiones() {
+    try {
+      const response = await fetch("/actualizar-conexiones");
+      if (!response.ok) throw new Error("Respuesta no OK");
 
-        async function refrescarConexiones() {
-            try {
-                const response = await fetch('/actualizar-conexiones');
-                if (!response.ok) throw new Error("Respuesta no OK");
-                
-                const html = await response.text();
-                const container = document.getElementById('datos-conexiones');
-                container.innerHTML = html;
+      const html = await response.text();
+      const container = document.getElementById("datos-conexiones");
+      container.innerHTML = html;
 
-                // Vuelve a configurar el botón para el nuevo contenido
-                setupSummaryButton();
+      // Vuelve a configurar el botón para el nuevo contenido
+      setupSummaryButton();
 
-                // --- ¡CAMBIO CLAVE! ---
-                // Después de refrescar, aplica el último estado que guardamos.
-                applyViewState();
+      // --- ¡CAMBIO CLAVE! ---
+      // Después de refrescar, aplica el último estado que guardamos.
+      applyViewState();
+    } catch (error) {
+      console.error("Error al actualizar conexiones:", error);
+    }
+  }
 
-            } catch (error) {
-                console.error("Error al actualizar conexiones:", error);
-            }
-        }
+  document.addEventListener("DOMContentLoaded", () => {
+    // Configura el botón de resumen cuando la página carga por primera vez
+    setupSummaryButton();
 
-        document.addEventListener('DOMContentLoaded', () => {
-            // Configura el botón de resumen cuando la página carga por primera vez
-            setupSummaryButton();
-
-            // Configura el refresco para que se ejecute cada 60 segundos
-            setInterval(refrescarConexiones, 60000);
-        });
-    </script>
-{% endblock %}
+    // Configura el refresco para que se ejecute cada 60 segundos
+    setInterval(refrescarConexiones, 60000);
+  });
+</script>
+{% endblock %}

+ 353 - 183
templates/partials/conexiones.html

@@ -1,200 +1,370 @@
-{% set valid_users = {} %}
-{% for user, user_data in grouped_connections.items() %}
-    {% if user and user != "-" and user != "Anónimo" %}
-        {% set _ = valid_users.update({user: user_data}) %}
-    {% endif %}
-{% endfor %}
+{% set valid_users = {} %} {% for user, user_data in grouped_connections.items()
+%} {% if user and user != "-" and user != "Anónimo" %} {% set _ =
+valid_users.update({user: user_data}) %} {% endif %} {% endfor %}
 
 <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
+  {# Tarjetas de estadísticas #}
+  <div class="flex justify-center mb-8">
+    <div
+      class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-4 w-full max-w-full"
+    >
+      {# --- 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>
 
-    {# 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">
-            
-            {# --- 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>
-            
-            {# --- 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>
+      {# --- 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>
+
+      {# Nueva Tarjeta: Tiempo de Actividad de Squid #} {% if squid_info_stats
+      and squid_info_stats.elapsed_hours %}
+      <div
+        class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5"
+      >
+        <div
+          class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center mr-4 flex-shrink-0"
+        >
+          <i class="fas fa-clock text-purple-500 text-xl"></i>
+        </div>
+        <div>
+          <p class="text-gray-500 text-sm">Tiempo Activo</p>
+          <p class="text-2xl font-bold">
+            {{ squid_info_stats.elapsed_hours }}h
+          </p>
+        </div>
+      </div>
+      {% endif %} {# Nueva Tarjeta: Clientes Conectados a Squid #} {% if
+      squid_info_stats and squid_info_stats.clients %}
+      <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-orange-100 flex items-center justify-center mr-4 flex-shrink-0"
+        >
+          <i class="fas fa-user-friends text-orange-500 text-xl"></i>
+        </div>
+        <div>
+          <p class="text-gray-500 text-sm">Clientes Squid</p>
+          <p class="text-2xl font-bold">{{ squid_info_stats.clients }}</p>
+        </div>
+      </div>
+      {% endif %} {# Nueva Tarjeta: Peticiones HTTP Totales #} {% if
+      squid_info_stats and squid_info_stats.requests_received %}
+      <div
+        class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5"
+      >
+        <div
+          class="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mr-4 flex-shrink-0"
+        >
+          <i class="fas fa-globe text-red-500 text-xl"></i>
+        </div>
+        <div>
+          <p class="text-gray-500 text-sm">Peticiones HTTP</p>
+          <p class="text-2xl font-bold">
+            {{ "{:,}"|format(squid_info_stats.requests_received) }}
+          </p>
+        </div>
+      </div>
+      {% endif %} {# Nueva Tarjeta: Promedio de Peticiones por Minuto #} {% if
+      squid_info_stats and squid_info_stats.avg_requests_per_minute %}
+      <div
+        class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5"
+      >
+        <div
+          class="w-12 h-12 rounded-full bg-teal-100 flex items-center justify-center mr-4 flex-shrink-0"
+        >
+          <i class="fas fa-chart-line text-teal-500 text-xl"></i>
+        </div>
+        <div>
+          <p class="text-gray-500 text-sm">Pet./Min Promedio</p>
+          <p class="text-2xl font-bold">
+            {{ squid_info_stats.avg_requests_per_minute|round(1) }}
+          </p>
+        </div>
+      </div>
+      {% endif %} {# Nueva Tarjeta: Estado de Conexión de Squid #} {% if
+      squid_info_stats %}
+      <div
+        class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5"
+      >
+        <div
+          class="w-12 h-12 rounded-full {% if squid_info_stats.connection_status == 'connected' %}bg-green-100{% else %}bg-red-100{% endif %} flex items-center justify-center mr-4 flex-shrink-0"
+        >
+          <i
+            class="fas {% if squid_info_stats.connection_status == 'connected' %}fa-check-circle text-green-500{% else %}fa-exclamation-triangle text-red-500{% endif %} text-xl"
+          ></i>
+        </div>
+        <div>
+          <p class="text-gray-500 text-sm">Estado Squid Info</p>
+          <p
+            class="text-sm font-bold {% if squid_info_stats.connection_status == 'connected' %}text-green-600{% else %}text-red-600{% endif %}"
+          >
+            {% if squid_info_stats.connection_status == 'connected' %}Conectado
+            {% elif squid_info_stats.connection_status ==
+            'connected_but_parse_error' %}Error Parsing {% elif
+            squid_info_stats.connection_status == 'timeout' %}Timeout {% elif
+            squid_info_stats.connection_status == 'connection_refused'
+            %}Conexión Rechazada {% elif squid_info_stats.connection_status ==
+            'dns_error' %}Error DNS {% else %}Error Desconocido{% endif %}
+          </p>
+        </div>
+      </div>
+      {% endif %}
+    </div>
+  </div>
+
+  {% if valid_users|length > 0 %}
+  <div class="flex justify-end mb-4">
+    <button
+      id="toggle-all-button"
+      class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-300"
+    >
+      Ver Resumen
+    </button>
+  </div>
+  {% endif %}
+
+  <div id="user-accordion-group">
+    {% for user, user_data in valid_users.items() %} {% set connections =
+    user_data.connections %} {% set client_ip = user_data.client_ip %}
+
+    <div
+      class="user-accordion bg-white rounded-lg shadow-md mb-3 overflow-hidden"
+    >
+      <div class="w-full text-left p-4 border-b bg-white">
+        <div
+          class="flex flex-col sm:flex-row sm:items-center sm:justify-between"
+        >
+          <div class="flex items-center mb-3 sm:mb-0">
+            <div
+              class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0"
+            >
+              <i class="fas fa-user text-blue-600"></i>
             </div>
-            {% 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>
+              <h2 class="text-lg font-bold text-gray-800">{{ user }}</h2>
             </div>
-            {% endif %}
+          </div>
 
-            {# Tarjeta de Usuarios Activos #}
-            <div class="bg-white p-4 rounded-lg shadow flex items-center transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
-                <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center mr-4 flex-shrink-0">
-                    <i class="fas fa-users text-blue-500 text-xl"></i>
-                </div>
-                <div>
-                    <p class="text-gray-500 text-sm">Usuarios Activos</p>
-                    <p class="text-2xl font-bold">{{ valid_users|length }}</p>
-                </div>
+          <div 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>
 
-            {# 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
+              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>
-        </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 %}
+            {% set total_data = namespace(value=0) %} {% set total_requests =
+            namespace(value=0) %} {% for connection in connections %} {% if
+            connection.fd_total != "N/A" %} {% set total_data.value =
+            total_data.value + connection.fd_total %} {% endif %} {% set
+            total_requests.value = total_requests.value + connection.nrequests
+            %} {% endfor %}
 
-    <div id="user-accordion-group">
-    {% for user, user_data in valid_users.items() %}
-    
-    {% set connections = user_data.connections %}
-    {% set client_ip = user_data.client_ip %}
-
-    <div class="user-accordion bg-white rounded-lg shadow-md mb-3 overflow-hidden">
-        <div class="w-full text-left p-4 border-b bg-white">
-            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
-                <div class="flex items-center mb-3 sm:mb-0">
-                    <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 flex-shrink-0">
-                        <i class="fas fa-user text-blue-600"></i>
-                    </div>
-                    <div>
-                        <h2 class="text-lg font-bold text-gray-800">{{ user }}</h2>
-                    </div>
-                </div>
-                
-                <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="Total de datos transferidos"
+            >
+              <i class="fas fa-database mr-1.5 text-green-500"></i>
+              <span>{{ (total_data.value / 1024 / 1024)|round(2) }} MB</span>
+            </div>
 
-                    <div class="flex items-center text-sm text-gray-600" title="Conexiones totales de este usuario">
-                        <i class="fas fa-link mr-1.5 text-blue-500"></i>
-                        <span>{{ connections|length }} conexiones</span>
-                    </div>
-                    
-                    {% set total_data = namespace(value=0) %}
-                    {% set total_requests = namespace(value=0) %}
-                    {% for connection in connections %}
-                        {% if connection.fd_total != "N/A" %}
-                            {% set total_data.value = total_data.value + connection.fd_total %}
-                        {% endif %}
-                        {% set total_requests.value = total_requests.value + connection.nrequests %}
-                    {% endfor %}
-                    
-                    <div class="flex 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
+              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>
-        
-        <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>
+            <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>
         </div>
+      </div>
     </div>
     {% endfor %}
-    </div>
-</div>
+  </div>
+</div>