Browse Source

refactor: update page templates to use new layout system

- Convert all pages to use layouts/base.html
- Add dynamic title sections with icons and subtitles
- Improve template organization and maintainability
- Ensure consistent UI across all pages
Yoelvis Mariné Ramos 1 year ago
parent
commit
3f3d146bf1
7 changed files with 1133 additions and 166 deletions
  1. 77 4
      templates/auditor.html
  2. 16 3
      templates/blacklist.html
  3. 578 6
      templates/cacheView.html
  4. 2 8
      templates/error.html
  5. 147 135
      templates/index.html
  6. 7 5
      templates/logsView.html
  7. 306 5
      templates/reports.html

+ 77 - 4
templates/auditor.html

@@ -1,9 +1,82 @@
 
-{% extends 'base.html' %}
+{% extends 'layouts/base.html' %}
+{% block styles %}
+    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}"/>
+    <style>
+        /* Estilo para los "chips" de redes sociales */
+        .social-chip {
+            padding: 8px 16px;
+            border-radius: 9999px;
+            font-size: 0.875rem;
+            font-weight: 600;
+            cursor: pointer;
+            transition: all 0.2s ease-in-out;
+            border: 1px solid #e5e7eb; /* gray-200 */
+            background-color: #f9fafb; /* gray-50 */
+            color: #374151; /* gray-700 */
+            box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
+        }
+        .social-chip:hover {
+            border-color: #93c5fd; /* blue-300 */
+            background-color: #eff6ff; /* blue-50 */
+            transform: translateY(-1px);
+            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
+        }
+        .social-chip.selected {
+            background-color: #2563eb; /* blue-600 */
+            color: white;
+            border-color: #1d4ed8; /* blue-800 */
+            box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
+        }
+        .social-chip.selected:hover {
+            background-color: #1d4ed8;
+        }
 
-{% block title %}BlackList | Dashboard Squid{% endblock %}
+        /* Estilo para el tooltip de ayuda sobre los chips */
+        .tooltip {
+            position: absolute;
+            bottom: 100%;
+            left: 50%;
+            transform: translateX(-50%);
+            margin-bottom: 8px;
+            background-color: #111827; /* gray-900 */
+            color: white;
+            padding: 4px 8px;
+            border-radius: 4px;
+            font-size: 0.75rem;
+            font-weight: 500;
+            white-space: nowrap;
+            opacity: 0;
+            transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
+            pointer-events: none; /* Para que no interfiera con el click */
+            transform-origin: bottom center;
+            transform: translateX(-50%) scale(0.95);
+        }
+        .group:hover .tooltip {
+            opacity: 1;
+            transform: translateX(-50%) scale(1);
+        }
+    </style>
+{% endblock styles %}
 
 {% block content %}
-    {% include 'components/auditoria.html' %}
+    {% include 'partials/auditoria.html' %}
+{% endblock %}
 
-{% endblock %}
+{% block scripts %}
+    <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
+    <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>
+
+    <!-- Scripts divididos -->
+    <script src="{{ url_for('static', filename='js/auditoria/config_and_utils.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/auditoria/renderers.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/auditoria/user_search_and_inputs.js') }}"></script>
+    <script src="{{ url_for('static', filename='js/auditoria/form_and_results.js') }}"></script>
+    <script>
+        document.addEventListener('DOMContentLoaded', ()=>{
+            window.__AUD_FORM__ && window.__AUD_FORM__.initFormAndResults();
+            window.__AUD_USER_INPUTS__ && window.__AUD_USER_INPUTS__.initUserAndInputs();
+        });
+    </script>
+{% endblock scripts %}

+ 16 - 3
templates/blacklist.html

@@ -1,3 +1,16 @@
-{% extends 'base.html' %} {% block title %}BlackList | Dashboard Squid{%
-endblock %} {% block content %} {% include 'components/black_list.html' %} {%
-endblock %}
+{% extends 'layouts/base.html' %} 
+ 
+{% block content %} 
+    {% include 'partials/black_list.html' %} 
+{%endblock %}
+
+{% block scripts %}
+<script>
+    function updateQueryParam(param, value) {
+        const url = new URL(window.location.href);
+        url.searchParams.set(param, value);
+        url.searchParams.set('page', '1');
+        return url.toString();
+    }
+</script>
+{% endblock scripts %}

+ 578 - 6
templates/cacheView.html

@@ -1,9 +1,581 @@
-{% extends 'base.html' %}
-<!-- Hereda de base.html -->
+{% extends 'layouts/base.html' %}
 
-{% block title %}Cache | Dashboard Squid{% endblock %}
-<!-- Título específico -->
+{% 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="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 %}
+
+{% block styles %}
+  <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
+  <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 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;
+    }
+  </style>
+{% endblock styles %}
 
 {% block content %}
-<!-- Muestra estadísticas de caché -->
-{% include 'components/cache_stats.html' %} {% endblock %}
+    {% include 'partials/cache_stats.html' %}
+{% endblock content %}
+
+{% block scripts %}
+  <script>
+    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");
+      });
+    });
+    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",
+          },
+          {
+            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)
+        );
+    }
+
+    // --- 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");
+      });
+
+      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);
+
+      // 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();
+
+        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>
+{% endblock scripts %}

+ 2 - 8
templates/error.html

@@ -4,10 +4,7 @@
     <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;
@@ -53,9 +50,6 @@
 
     <!-- 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"
-    />
+    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet"/>
   </body>
 </html>

+ 147 - 135
templates/index.html

@@ -1,6 +1,16 @@
-{% extends 'base.html' %} {% block title %}Inicio | Dashboard Squid{% endblock
-%} {% block content %}
+{% extends 'layouts/base.html' %} 
 
+{% from 'macros.html' import format_bandwidth %}  {# CAMBIO: Importar desde macros #}
+
+{% 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 %}
+{% block title %}{% endblock title %}
+
+{% block content %}
 <div class="flex flex-wrap items-center gap-3 mb-4 bg-white/70 dark:bg-gray-800/60 px-3 py-2 rounded-md border border-gray-200 shadow-sm text-sm max-w-full">
   <label for="refresh-interval" class="text-gray-700 dark:text-gray-200 font-medium select-none">⏱️</label>
   <div class="flex items-center gap-1">
@@ -14,159 +24,161 @@
   <button id="set-interval-btn" class="px-3 py-1 rounded bg-blue-600 hover:bg-blue-700 text-white font-medium transition text-xs">Aplicar</button>
   <span id="persist-status" class="text-[11px] text-gray-400 ml-auto pr-1 opacity-0 transition-opacity"></span>
 </div>
-
 <div id="datos-conexiones" class="max-w-7xl mx-auto sm:px-6 lg:px-8">
   {% include 'partials/conexiones.html' %}
 </div>
+{% endblock %}
 
-<script>
-  let isDetailedView = true;
 
-  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");
+{% block scripts %}
+  <script>
+    let isDetailedView = true;
 
-    if (contents.length === 0 || !toggleAllButton) return;
+    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 (isDetailedView) {
-      contents.forEach((content) => content.classList.remove("hidden"));
-      icons.forEach((icon) => icon.classList.add("rotate-180"));
-      toggleAllButton.textContent = "Ver Resumen";
-    } else {
-      contents.forEach((content) => content.classList.add("hidden"));
-      icons.forEach((icon) => icon.classList.remove("rotate-180"));
-      toggleAllButton.textContent = "Ver Detalles";
+      if (contents.length === 0 || !toggleAllButton) return;
+
+      if (isDetailedView) {
+        contents.forEach((content) => content.classList.remove("hidden"));
+        icons.forEach((icon) => icon.classList.add("rotate-180"));
+        toggleAllButton.textContent = "Ver Resumen";
+      } else {
+        contents.forEach((content) => content.classList.add("hidden"));
+        icons.forEach((icon) => icon.classList.remove("rotate-180"));
+        toggleAllButton.textContent = "Ver Detalles";
+      }
     }
-  }
 
-  function setupSummaryButton() {
-    const toggleAllButton = document.getElementById("toggle-all-button");
-    if (!toggleAllButton) return;
+    function setupSummaryButton() {
+      const toggleAllButton = document.getElementById("toggle-all-button");
+      if (!toggleAllButton) return;
 
+      const newButton = toggleAllButton.cloneNode(true);
+      toggleAllButton.parentNode.replaceChild(newButton, toggleAllButton);
 
-    const newButton = toggleAllButton.cloneNode(true);
-    toggleAllButton.parentNode.replaceChild(newButton, toggleAllButton);
+      newButton.addEventListener("click", () => {
+        isDetailedView = !isDetailedView; 
+        applyViewState(); 
+      });
+    }
 
-    newButton.addEventListener("click", () => {
-      isDetailedView = !isDetailedView; 
-      applyViewState(); 
-    });
-  }
+    async function refrescarConexiones() {
+      try {
+        // CAMBIO: Usar la ruta principal con parámetro partial en lugar de ruta separada
+        const response = await fetch("/?partial=true");
+        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;
+        setupSummaryButton();
+        applyViewState();
+      } catch (error) {
+        console.error("Error al actualizar conexiones:", error);
+      }
+    }
 
-      setupSummaryButton();
+    const REFRESH_KEY = 'squidstats.refreshIntervalSec';
+    const VIEW_KEY = 'squidstats.viewMode';
+    let refreshInterval = 60000; // ms
+    let refreshTimer = null;
+    let countdownTimer = null;
+    let secondsLeft = 0;
 
-      applyViewState();
-    } catch (error) {
-      console.error("Error al actualizar conexiones:", error);
+    function safeGet(key) {
+      try { return localStorage.getItem(key); } catch { return null; }
+    }
+    function safeSet(key, val) {
+      try { localStorage.setItem(key, val); persistStatus('Guardado'); } catch { persistStatus('No se pudo guardar'); }
+    }
+    function persistStatus(msg) {
+      const el = document.getElementById('persist-status');
+      if (!el) return;
+      el.textContent = msg;
+      el.classList.remove('opacity-0');
+      setTimeout(() => { el.classList.add('opacity-0'); }, 1600);
     }
-  }
-
-  const REFRESH_KEY = 'squidstats.refreshIntervalSec';
-  const VIEW_KEY = 'squidstats.viewMode';
-  let refreshInterval = 60000; // ms
-  let refreshTimer = null;
-  let countdownTimer = null;
-  let secondsLeft = 0;
-
-  function safeGet(key) {
-    try { return localStorage.getItem(key); } catch { return null; }
-  }
-  function safeSet(key, val) {
-    try { localStorage.setItem(key, val); persistStatus('Guardado'); } catch { persistStatus('No se pudo guardar'); }
-  }
-  function persistStatus(msg) {
-    const el = document.getElementById('persist-status');
-    if (!el) return;
-    el.textContent = msg;
-    el.classList.remove('opacity-0');
-    setTimeout(() => { el.classList.add('opacity-0'); }, 1600);
-  }
-
-  function getRefreshIntervalFromStorage() {
-    const stored = safeGet(REFRESH_KEY);
-    const val = parseInt(stored);
-    return (!isNaN(val) && val >= 5) ? val : 60;
-  }
-  function setRefreshIntervalToStorage(val) { safeSet(REFRESH_KEY, String(val)); }
-
-  function restoreViewState() {
-    const stored = safeGet(VIEW_KEY);
-    if (stored === 'summary') isDetailedView = false;
-  }
-  function saveViewState() { safeSet(VIEW_KEY, isDetailedView ? 'detailed' : 'summary'); }
-
-  const originalApplyViewState = applyViewState;
-  applyViewState = function() { 
-    originalApplyViewState();
-    saveViewState();
-  };
-
-  function startRefreshTimer() {
-    if (refreshTimer) clearInterval(refreshTimer);
-    if (countdownTimer) clearInterval(countdownTimer);
-    secondsLeft = refreshInterval / 1000;
-    updateCountdown();
-    refreshTimer = setInterval(() => {
-      refrescarConexiones();
-      secondsLeft = refreshInterval / 1000; // reset
-    }, refreshInterval);
-    countdownTimer = setInterval(() => {
-      secondsLeft -= 1;
-      if (secondsLeft < 0) secondsLeft = refreshInterval / 1000;
+
+    function getRefreshIntervalFromStorage() {
+      const stored = safeGet(REFRESH_KEY);
+      const val = parseInt(stored);
+      return (!isNaN(val) && val >= 5) ? val : 60;
+    }
+    function setRefreshIntervalToStorage(val) { safeSet(REFRESH_KEY, String(val)); }
+
+    function restoreViewState() {
+      const stored = safeGet(VIEW_KEY);
+      if (stored === 'summary') isDetailedView = false;
+    }
+    function saveViewState() { safeSet(VIEW_KEY, isDetailedView ? 'detailed' : 'summary'); }
+
+    const originalApplyViewState = applyViewState;
+    applyViewState = function() { 
+      originalApplyViewState();
+      saveViewState();
+    };
+
+    function startRefreshTimer() {
+      if (refreshTimer) clearInterval(refreshTimer);
+      if (countdownTimer) clearInterval(countdownTimer);
+      secondsLeft = refreshInterval / 1000;
       updateCountdown();
-    }, 1000);
-  }
-
-  function updateCountdown() {
-    const el = document.getElementById('next-refresh');
-    if (!el) return;
-    el.textContent = secondsLeft + 's';
-  }
-
-  function applyNewInterval(valSec) {
-    refreshInterval = valSec * 1000;
-    setRefreshIntervalToStorage(valSec);
-    startRefreshTimer();
-  }
-
-  document.addEventListener('DOMContentLoaded', () => {
-    const storedRaw = safeGet(REFRESH_KEY);
-    const intervalValue = getRefreshIntervalFromStorage();
-    document.getElementById('refresh-interval').value = intervalValue;
-    refreshInterval = intervalValue * 1000;
-    if (storedRaw === null) {
-      setRefreshIntervalToStorage(intervalValue);
-      console.debug('[SquidStats] Intervalo por defecto almacenado:', intervalValue, 's');
+      refreshTimer = setInterval(() => {
+        refrescarConexiones();
+        secondsLeft = refreshInterval / 1000; // reset
+      }, refreshInterval);
+      countdownTimer = setInterval(() => {
+        secondsLeft -= 1;
+        if (secondsLeft < 0) secondsLeft = refreshInterval / 1000;
+        updateCountdown();
+      }, 1000);
     }
-    restoreViewState();
 
-    setupSummaryButton();
-    applyViewState();
-    startRefreshTimer();
+    function updateCountdown() {
+      const el = document.getElementById('next-refresh');
+      if (!el) return;
+      el.textContent = secondsLeft + 's';
+    }
 
-    const intervalInput = document.getElementById('refresh-interval');
-    document.getElementById('set-interval-btn').addEventListener('click', () => {
-      const val = parseInt(intervalInput.value);
-      if (!isNaN(val) && val >= 5) {
-        applyNewInterval(val);
-      } else {
-        intervalInput.value = getRefreshIntervalFromStorage();
+    function applyNewInterval(valSec) {
+      refreshInterval = valSec * 1000;
+      setRefreshIntervalToStorage(valSec);
+      startRefreshTimer();
+    }
+
+    document.addEventListener('DOMContentLoaded', () => {
+      const storedRaw = safeGet(REFRESH_KEY);
+      const intervalValue = getRefreshIntervalFromStorage();
+      document.getElementById('refresh-interval').value = intervalValue;
+      refreshInterval = intervalValue * 1000;
+      if (storedRaw === null) {
+        setRefreshIntervalToStorage(intervalValue);
+        console.debug('[SquidStats] Intervalo por defecto almacenado:', intervalValue, 's');
       }
+      restoreViewState();
+
+      setupSummaryButton();
+      applyViewState();
+      startRefreshTimer();
+
+      const intervalInput = document.getElementById('refresh-interval');
+      document.getElementById('set-interval-btn').addEventListener('click', () => {
+        const val = parseInt(intervalInput.value);
+        if (!isNaN(val) && val >= 5) {
+          applyNewInterval(val);
+        } else {
+          intervalInput.value = getRefreshIntervalFromStorage();
+        }
+      });
+      intervalInput.addEventListener('change', () => {
+        const val = parseInt(intervalInput.value);
+        if (!isNaN(val) && val >= 5) applyNewInterval(val);
+      });
     });
-    intervalInput.addEventListener('change', () => {
-      const val = parseInt(intervalInput.value);
-      if (!isNaN(val) && val >= 5) applyNewInterval(val);
-    });
-  });
-</script>
-{% endblock %}
+  </script>
+{% endblock scripts %}
+

+ 7 - 5
templates/logsView.html

@@ -1,9 +1,11 @@
 
-{% extends 'base.html' %}
-
-{% block title %}Inicio | Dashboard Squid{% endblock %}
+{% extends 'layouts/base.html' %}
+{% block styles %}{% endblock styles %}
 
 {% block content %}
-    {% include 'components/logs.html' %}
+    {% include 'partials/logs.html' %}
+{% endblock %}
 
-{% endblock %}
+{% block scripts %}
+    <script type="module" src="static/js/dashboard.js"></script>
+{% endblock scripts %}

+ 306 - 5
templates/reports.html

@@ -1,9 +1,310 @@
 
-{% extends 'base.html' %}
-
-{% block title %}Reportes | Dashboard Squid{% endblock %}
+{% extends 'layouts/base.html' %}
+{% block styles %}
+    <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>
+{% endblock styles %}
 
 {% block content %}
-    {% include 'components/graph_reports.html' %}
+    {% include 'partials/graph_reports.html' %}
+{% endblock %}
+
+{% block scripts %}
+    <script type="application/json" id="chart-data">
+      {
+        "usersActivity": {
+          "labels": {{ metrics.top_users_by_activity | map(attribute='username') | list | tojson | safe }},
+          "data": {{ metrics.top_users_by_activity | map(attribute='total_visits') | list | tojson | safe }}
+        },
+        "usersData": {
+          "labels": {{ metrics.top_users_by_data_transferred | map(attribute='username') | list | tojson | safe }},
+          "data": {{ metrics.top_users_by_data_transferred | map(attribute='total_data_bytes') | map('divide', 1048576) | list | tojson | safe }}
+        },
+        "httpCodes": {
+          "labels": {{ metrics.http_response_distribution_chart.labels | tojson | safe }},
+          "data": {{ metrics.http_response_distribution_chart.data | tojson | safe }},
+          "colors": {{ metrics.http_response_distribution_chart.colors | tojson | safe }}
+        }
+      }
+    </script>
+
+    <script>
+      // Chart.js configuration
+      document.addEventListener("DOMContentLoaded", function () {
+        // Load data from JSON script tag
+        const chartDataElement = document.getElementById("chart-data");
+        const chartData = JSON.parse(chartDataElement.textContent);
+
+        const chartColors = [
+          "#3B82F6",
+          "#10B981",
+          "#F59E0B",
+          "#EF4444",
+          "#8B5CF6",
+          "#EC4899",
+          "#14B8A6",
+          "#F97316",
+          "#64748B",
+          "#84CC16",
+          "#06B6D4",
+          "#D946EF",
+          "#F43F5E",
+          "#0EA5E9",
+          "#22C55E",
+          "#EAB308",
+          "#F43F5E",
+          "#8B5CF6",
+          "#EC4899",
+          "#14B8A6",
+        ];
+
+        // Helper function to get text color based on theme
+        function getTextColor() {
+          return document.documentElement.classList.contains("dark")
+            ? "#d1d5db"
+            : "#374151";
+        }
+
+        // Helper function to get border color based on theme
+        function getBorderColor() {
+          return document.documentElement.classList.contains("dark")
+            ? "#374151"
+            : "#fff";
+        }
+
+        // Users Activity Chart
+        const usersActivityCtx = document.getElementById("usersActivityChart");
+        if (usersActivityCtx && chartData.usersActivity) {
+          new Chart(usersActivityCtx.getContext("2d"), {
+            type: "bar",
+            data: {
+              labels: chartData.usersActivity.labels,
+              datasets: [
+                {
+                  label: "Visitas",
+                  data: chartData.usersActivity.data,
+                  backgroundColor: chartColors.slice(
+                    0,
+                    chartData.usersActivity.data.length
+                  ),
+                  borderColor: chartColors
+                    .slice(0, chartData.usersActivity.data.length)
+                    .map((color) => color + "DD"),
+                  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" },
+                  ticks: { color: getTextColor() },
+                },
+                x: {
+                  ticks: {
+                    autoSkip: false,
+                    color: getTextColor(),
+                  },
+                },
+              },
+            },
+          });
+        }
+
+        // Users Data Chart
+        const usersDataCtx = document.getElementById("usersDataChart");
+        if (usersDataCtx && chartData.usersData) {
+          new Chart(usersDataCtx.getContext("2d"), {
+            type: "bar",
+            data: {
+              labels: chartData.usersData.labels,
+              datasets: [
+                {
+                  label: "Datos (MB)",
+                  data: chartData.usersData.data,
+                  backgroundColor: chartColors.slice(
+                    0,
+                    chartData.usersData.data.length
+                  ),
+                  borderColor: chartColors
+                    .slice(0, chartData.usersData.data.length)
+                    .map((color) => color + "DD"),
+                  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)" },
+                  ticks: { color: getTextColor() },
+                },
+                x: {
+                  ticks: {
+                    autoSkip: false,
+                    color: getTextColor(),
+                  },
+                },
+              },
+            },
+          });
+        }
+
+        // HTTP Codes Chart
+        const httpCodesCtx = document.getElementById("httpCodesChart");
+        if (httpCodesCtx && chartData.httpCodes) {
+          new Chart(httpCodesCtx.getContext("2d"), {
+            type: "pie",
+            data: {
+              labels: chartData.httpCodes.labels,
+              datasets: [
+                {
+                  data: chartData.httpCodes.data,
+                  backgroundColor: chartData.httpCodes.colors,
+                  borderColor: getBorderColor(),
+                  borderWidth: 2,
+                },
+              ],
+            },
+            options: {
+              responsive: true,
+              maintainAspectRatio: false,
+              plugins: {
+                legend: {
+                  position: "right",
+                  labels: {
+                    font: { size: 12 },
+                    color: getTextColor(),
+                  },
+                },
+                tooltip: {
+                  callbacks: {
+                    label: function (context) {
+                      const total = context.dataset.data.reduce(function (
+                        a,
+                        b
+                      ) {
+                        return a + b;
+                      },
+                      0);
+                      const percentage = ((context.raw / total) * 100).toFixed(
+                        1
+                      );
+                      return (
+                        context.label +
+                        ": " +
+                        context.raw +
+                        " (" +
+                        percentage +
+                        "%)"
+                      );
+                    },
+                  },
+                },
+                datalabels: {
+                  formatter: function (value, ctx) {
+                    const total = ctx.chart.data.datasets[0].data.reduce(
+                      function (a, b) {
+                        return a + b;
+                      },
+                      0
+                    );
+                    const percentage = ((value / total) * 100).toFixed(1);
+                    return percentage > 3 ? percentage + "%" : "";
+                  },
+                  color: "#fff",
+                  font: {
+                    weight: "bold",
+                    size: 12,
+                  },
+                },
+              },
+            },
+            plugins: [ChartDataLabels],
+          });
+        }
+
+        // Update chart colors when dark mode changes
+        const observer = new MutationObserver(function (mutations) {
+          mutations.forEach(function (mutation) {
+            if (
+              mutation.type === "attributes" &&
+              mutation.attributeName === "class"
+            ) {
+              // Re-render charts with new colors when dark mode changes
+              setTimeout(function () {
+                Chart.helpers.each(Chart.instances, function (instance) {
+                  // Update scale colors
+                  if (
+                    instance.config.options &&
+                    instance.config.options.scales
+                  ) {
+                    const textColor = getTextColor();
+                    if (
+                      instance.config.options.scales.y &&
+                      instance.config.options.scales.y.ticks
+                    ) {
+                      instance.config.options.scales.y.ticks.color = textColor;
+                    }
+                    if (
+                      instance.config.options.scales.x &&
+                      instance.config.options.scales.x.ticks
+                    ) {
+                      instance.config.options.scales.x.ticks.color = textColor;
+                    }
+                  }
+                  // Update legend colors
+                  if (
+                    instance.config.options &&
+                    instance.config.options.plugins &&
+                    instance.config.options.plugins.legend &&
+                    instance.config.options.plugins.legend.labels
+                  ) {
+                    instance.config.options.plugins.legend.labels.color =
+                      getTextColor();
+                  }
+                  instance.update();
+                });
+              }, 100);
+            }
+          });
+        });
 
-{% endblock %}
+        observer.observe(document.documentElement, {
+          attributes: true,
+          attributeFilter: ["class"],
+        });
+      });
+    </script>
+    <script src="{{ url_for('static', filename='js/reports-datepicker.js') }}"></script>
+{% endblock scripts %}