Просмотр исходного кода

feat: add total data consumed functionality and update related templates

Manuel 1 год назад
Родитель
Сommit
aefdd5d605

+ 7 - 0
routes/api_routes.py

@@ -14,6 +14,7 @@ from services.auditoria_service import (
     get_top_urls_by_data,
     get_top_users_by_data,
     get_top_users_by_requests,
+    get_total_data_consumed,
     get_user_activity_summary,
 )
 from services.metrics_service import MetricsService
@@ -132,6 +133,12 @@ def api_run_audit():
             result = find_by_response_code(
                 db, start_date, end_date, int(response_code), username
             )
+        elif audit_type == "total_data_consumed":
+            if not start_date:
+                return jsonify({"error": "Start date is required."}), 400
+            if not end_date:
+                return jsonify({"error": "End date is required."}), 400
+            result = get_total_data_consumed(db, start_date, end_date)
         else:
             return jsonify({"error": "Invalid audit type."}), 400
 

+ 2 - 2
routes/logs_routes.py

@@ -23,7 +23,7 @@ def logs():
             page_icon="user.ico",
             page_title="Actividad usuarios",
             icon="fas fa-user-friends",
-            subtitle="Texto descriptivo aqui",
+            subtitle="Analisis de la Actividad de los Usuarios",
         )
     except Exception as e:
         logger.error(f"Error en ruta /logs: {e}")
@@ -103,7 +103,7 @@ def blacklist_logs():
             page_icon="shield-exclamation.ico",
             page_title="Registros Bloqueados",
             icon="fas fa-ban",
-            subtitle="Texto descriptivo aqui",
+            subtitle="Peticiones que deberian ser bloqueadas o fueron bloqueadas",
         )
 
     except ValueError:

+ 32 - 44
routes/main_routes.py

@@ -17,8 +17,8 @@ main_bp = Blueprint("main", __name__)
 
 def filter_valid_users(grouped_connections):
     """
-    Filtra usuarios válidos eliminando usuarios anónimos y vacíos
-    Esta función centraliza la lógica de filtrado que antes estaba en el template
+    Filter valid users by removing anonymous and empty users
+    This function centralizes the filtering logic that was previously in the template
     """
     valid_users = {}
     for user, user_data in grouped_connections.items():
@@ -29,14 +29,14 @@ def filter_valid_users(grouped_connections):
 
 @main_bp.app_context_processor
 def inject_app_version():
-    """Inyecta la versión de la aplicación en todos los templates"""
+    """Inject the application version into all templates"""
     version = getattr(Config, "VERSION", None) or os.getenv("VERSION", "-")
     return {"app_version": version}
 
 
 def _build_error_page(message: str, status: int = 500, details: str | None = None):
     """
-    Construye una página de error estandarizada
+    Build a standardized error page
     """
     if details:
         logger.debug("Error details (server-only): %s", details)
@@ -59,44 +59,44 @@ def _build_error_page(message: str, status: int = 500, details: str | None = Non
 
 def _get_dashboard_context() -> tuple[dict[str, Any] | None, tuple[Any, int] | None]:
     """
-    Obtiene y procesa el contexto para el dashboard
-    Retorna: (context_dict, error_response) - solo uno será no None
+    Get and process the context for the dashboard
+    Returns: (context_dict, error_response) - only one will be not None
     """
     t0 = time.time()
     try:
         raw_data = fetch_squid_data()
         if not raw_data:
             logger.error("fetch_squid_data() returned empty response")
-            return None, _build_error_page("Sin datos desde Squid", 502)
+            return None, _build_error_page("No data from Squid", 502)
         if isinstance(raw_data, str) and raw_data.strip().lower().startswith("error"):
             logger.error(f"Failed to fetch Squid data: {raw_data}")
-            return None, _build_error_page("Error conectando con Squid", 502, raw_data)
+            return None, _build_error_page("Error connecting to Squid", 502, raw_data)
 
         try:
             connections = parse_raw_data(raw_data)
         except Exception as parse_err:
-            logger.exception("Error parseando conexiones de Squid")
+            logger.exception("Error parsing Squid connections")
             return None, _build_error_page(
-                "Error procesando datos de Squid", 500, str(parse_err)
+                "Error processing Squid data", 500, str(parse_err)
             )
 
         if not connections:
-            logger.warning("No se detectaron conexiones activas en la salida de Squid")
+            logger.warning("No active connections detected in Squid output")
             connections = []
 
         try:
             grouped_connections = group_by_user(connections)
         except Exception:
-            logger.exception("Error agrupando conexiones por usuario")
+            logger.exception("Error grouping connections by user")
             grouped_connections = {}
 
-        # FILTRADO CENTRALIZADO: Generar usuarios válidos aquí en lugar del template
+        # CENTRALIZED FILTERING: Generate valid users here instead of in the template
         valid_users = filter_valid_users(grouped_connections)
 
         try:
             squid_info_stats = fetch_squid_info_stats()
         except Exception:
-            logger.exception("Error obteniendo estadísticas detalladas de Squid")
+            logger.exception("Error getting detailed Squid statistics")
             squid_info_stats = {}
 
         squid_version = (
@@ -117,32 +117,20 @@ def _get_dashboard_context() -> tuple[dict[str, Any] | None, tuple[Any, int] | N
         }
         return context, None
     except Exception:  # Fallback catch-all
-        logger.exception("Fallo inesperado construyendo el contexto del dashboard")
-        return None, _build_error_page("Fallo interno inesperado", 500)
+        logger.exception("Unexpected failure building dashboard context")
+        return None, _build_error_page("Unexpected internal failure", 500)
 
 
 @main_bp.route("/")
 def index():
-    """
-    Ruta unificada para el dashboard
-
-    CAMBIO PRINCIPAL:
-    - Ahora maneja tanto la carga completa de la página como las actualizaciones parciales
-    - Elimina la necesidad de la ruta separada /actualizar-conexiones
-
-    Detección de tipo de petición:
-    - Petición normal: Devuelve index.html completo
-    - Petición parcial (param partial=true): Devuelve solo el contenido de conexiones
-    """
-
-    # CAMBIO: Detectar si es una petición para contenido parcial
+    # CHANGE: Detect if this is a request for partial content
     is_partial_request = request.args.get("partial") == "true"
 
     context, error_response = _get_dashboard_context()
     if error_response:
         return error_response
 
-    # CAMBIO: Si es petición parcial, devolver solo el template de conexiones
+    # CHANGE: If it's a partial request, return only the connections template
     if is_partial_request:
         return render_template(
             "partials/conexiones.html",
@@ -154,43 +142,43 @@ def index():
             connection_count=context["connection_count"],
         )
 
-    # Petición normal: devolver la página completa
+    # Normal request: return the complete page
     return render_template("index.html", **context)
 
 
 @main_bp.route("/install", methods=["POST"])
 def install_package():
-    """Ruta para instalar/actualizar paquetes de Squid"""
+    """Route to install/update Squid packages"""
     ok = False
     try:
         ok = update_squid()
         if ok:
-            logger.info("Actualización de SquidStats (install) completada exitosamente")
+            logger.info("SquidStats update (install) completed successfully")
         else:
-            logger.warning("update_squid() retornó False en /install")
+            logger.warning("update_squid() returned False in /install")
     except Exception:
-        logger.exception("Error ejecutando actualización en /install")
+        logger.exception("Error executing update in /install")
     return redirect(f"/?install_status={'ok' if ok else 'fail'}")
 
 
 @main_bp.route("/update", methods=["POST"])
 def update_web():
-    """Ruta para actualizar la aplicación web"""
+    """Route to update the web application"""
     ok = False
     try:
         ok = updateSquidStats()
         if ok:
-            logger.info("Actualización web de SquidStats completada")
+            logger.info("SquidStats web update completed")
         else:
-            logger.warning("updateSquidStats() retornó False en /update")
+            logger.warning("updateSquidStats() returned False in /update")
     except Exception:
-        logger.exception("Error ejecutando actualización en /update")
+        logger.exception("Error executing update in /update")
     return redirect(f"/?update_status={'ok' if ok else 'fail'}")
 
 
 @main_bp.route("/all-notifications")
 def all_notifications():
-    """Página para ver todas las notificaciones con paginación"""
+    """Page to view all notifications with pagination"""
     try:
         # Get pagination parameters
         page = request.args.get('page', 1, type=int)
@@ -207,8 +195,8 @@ def all_notifications():
 
         return render_template(
             "all_notifications.html",
-            page_title="Todas las Notificaciones",
-            subtitle="Historial completo de notificaciones del sistema",
+            page_title="All Notifications",
+            subtitle="Complete system notifications history",
             icon="fas fa-bell",
             notifications=notifications_data['notifications'],
             unread_count=notifications_data['unread_count'],
@@ -226,8 +214,8 @@ def all_notifications():
         logger.error(f"Error loading notifications page: {e}")
         return render_template(
             "all_notifications.html",
-            page_title="Todas las Notificaciones",
-            subtitle="Error al cargar notificaciones",
+            page_title="All Notifications",
+            subtitle="Error loading notifications",
             icon="fa-bell",
             notifications=[],
             unread_count=0,

+ 2 - 2
routes/reports_routes.py

@@ -56,7 +56,7 @@ def reports():
             page_icon="bar.ico",
             page_title="Reportes y gráficas",
             icon="fas fa-chart-simple",
-            subtitle="Texto descriptivo aqui",
+            subtitle="Top de la Actividad de los Usuarios y comportamiento",
         )
     except Exception as e:
         logger.error(f"Error en ruta /reports: {str(e)}", exc_info=True)
@@ -120,7 +120,7 @@ def reports_for_date(date_str: str):
             page_icon="bar.ico",
             page_title=f"Reportes y gráficas - {selected.isoformat()}",
             icon="fas fa-chart-simple",
-            subtitle="Texto descriptivo aqui",
+            subtitle="Top de la Actividad de los Usuarios y comportamiento",
         )
     except Exception:
         logger.exception("Error generating reports for specific date")

+ 1 - 1
routes/stats_routes.py

@@ -66,7 +66,7 @@ def cache_stats_realtime():
             page_icon="statistics.ico",
             page_title="Estadísticas del Sistema",
             icon="fas fa-chart-bar",
-            subtitle="Texto descriptivo aqui",
+            subtitle="Estadisticas del comportamiento del Sistema",
         )
     except Exception as e:
         logger.error(f"Error in /stats: {str(e)}")

+ 54 - 0
services/auditoria_service.py

@@ -569,6 +569,60 @@ def get_top_users_by_data(
     return {"top_users": top_users_list}
 
 
+def get_total_data_consumed(
+    db: Session, start_str: str, end_str: str
+) -> dict[str, Any]:
+    """
+    Get total data consumed across all users in the date range
+    Returns: dict with total_data_gb and total_requests
+    """
+    start_date = datetime.strptime(start_str, "%Y-%m-%d")
+    end_date = datetime.strptime(end_str, "%Y-%m-%d")
+    inspector = inspect(db.get_bind())
+    tables = _get_tables_in_range(inspector, start_date, end_date)
+    if not tables:
+        return {"error": f"No data tables found for the selected date range ({start_str} to {end_str})."}
+
+    total_data = 0
+    total_requests = 0
+
+    for log_table in tables:
+        date_suffix = log_table.split("_")[1]
+        try:
+            UserModel, LogModel = get_dynamic_models(date_suffix)
+            if UserModel is None or LogModel is None:
+                continue
+
+            # Sum all data transmitted and count all requests
+            result = (
+                db.query(
+                    func.sum(LogModel.data_transmitted).label("total_data"),
+                    func.count(LogModel.id).label("total_requests"),
+                )
+                .first()
+            )
+
+            if result:
+                data_sum = result.total_data or 0
+                request_count = result.total_requests or 0
+                total_data += data_sum
+                total_requests += request_count
+            else:
+                print(f"Table {log_table}: No results from query")
+
+        except Exception as e:
+            print(f"Error processing table {log_table}: {e}")
+            continue
+
+    return {
+        "total_data_gb": float(round(total_data / (1024**3), 2)) if total_data > 0 else 0.0,
+        "total_requests": total_requests,
+        "date_range": f"{start_str} to {end_str}",
+        "tables_processed": len(tables),
+        "total_data_bytes": total_data
+    }
+
+
 def get_top_users_by_requests(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:

+ 1 - 0
static/js/auditoria/form_and_results.js

@@ -55,6 +55,7 @@
       else if (auditType === 'top_urls_data') html = window.__AUD_RENDERERS__.renderTopUrls(data);
   else if (auditType === 'top_users_requests') html = window.__AUD_RENDERERS__.renderTopUsersRequests(data);
   else if (auditType === 'top_ips_data') html = window.__AUD_RENDERERS__.renderTopIpsData(data);
+      else if (auditType === 'total_data_consumed') html = window.__AUD_RENDERERS__.renderTotalDataConsumed(data, formData);
       else if (auditType === 'daily_activity') {
         const user = formData.username;
         const date = formData.start_date;

+ 39 - 0
static/js/auditoria/renderers.js

@@ -179,6 +179,44 @@
     return new Chart(canvas, config);
   }
 
+  function renderTotalDataConsumed(data, formData) {
+    const startDate = formData.start_date;
+    const endDate = formData.end_date;
+    const title = `Total de Datos Consumidos del ${startDate} al ${endDate}`;
+
+    if (data.error) {
+      return `<div class="bg-white p-6 rounded-lg shadow-lg"><h2 class="text-2xl font-bold mb-4">${title}</h2><div class="text-center text-red-500 py-10"><strong>Error:</strong> ${data.error}</div></div>`;
+    }
+
+    const totalDataGB = data.total_data_gb || 0;
+    const totalDataBytes = data.total_data_bytes || 0;
+    const totalRequests = data.total_requests || 0;
+    const tablesProcessed = data.tables_processed || 0;
+
+    return `<div class="bg-white p-6 rounded-lg shadow-lg">
+      <h2 class="text-2xl font-bold mb-4">${title}</h2>
+      <div class="text-center py-10">
+        <div class="text-6xl font-bold text-blue-600 mb-4">
+          <i class="fas fa-database mr-4"></i>${totalDataGB.toFixed(2)} GB
+        </div>
+        <div class="text-xl text-gray-600 mb-4">
+          Total de datos consumidos en el período seleccionado
+        </div>
+        <div class="grid grid-cols-2 gap-4 text-sm text-gray-500">
+          <div>
+            <strong>${totalRequests.toLocaleString()}</strong> peticiones totales
+          </div>
+          <div>
+            <strong>${tablesProcessed}</strong> tablas procesadas
+          </div>
+        </div>
+        <div class="mt-4 text-xs text-gray-400">
+          Equivalente a ${totalDataBytes.toLocaleString()} bytes
+        </div>
+      </div>
+    </div>`;
+  }
+
   window.__AUD_RENDERERS__ = {
     renderNestedAccordionResults,
     renderUserSummary,
@@ -186,6 +224,7 @@
     renderTopUrls,
   renderTopUsersRequests,
   renderTopIpsData,
+    renderTotalDataConsumed,
     renderDailyActivityChart,
     renderDomainChart,
     renderResponseChart

+ 3 - 0
templates/partials/auditoria.html

@@ -19,6 +19,9 @@
               <option value="top_urls_data">Top 15 URLs (Datos)</option>
               <option value="top_users_requests">Top 10 Usuarios (Peticiones)</option>
               <option value="top_ips_data">Top 10 IPs (Datos)</option>
+              <option value="total_data_consumed" data-requires="date_range">
+                Total de Datos Consumidos
+              </option>
               <!-- <option value="daily_activity" data-requires="user">
                 Actividad Diaria
               </option> -->