Kaynağa Gözat

feat: integrate toastr for notification management and enhance UI responsiveness

Manuel 10 ay önce
ebeveyn
işleme
8e407ce81e

+ 0 - 25
services/system_info.py

@@ -127,31 +127,6 @@ def get_cpu_info():
         return f"Error: {str(e)}"
 
 
-r""" def get_squid_version():
-    try:
-        result = subprocess.run(
-            ["squid", "-v"],
-            capture_output=True,
-            text=True,
-            timeout=5,
-        )
-        output = result.stdout + result.stderr
-        patterns = [
-            r"Squid Cache: Version ([\d\.]+[\w\-\.]*)",
-            r"Version: ([\d\.]+[\w\-\.]*)",
-            r"squid/([\d\.]+[\w\-\.]*)",
-        ]
-        for pattern in patterns:
-            match = re.search(pattern, output)
-            if match:
-                return match.group(1)
-        return "Installed (version not detected)"
-    except FileNotFoundError:
-        return "Not installed"
-    except Exception as e:
-        return f"Error: {str(e)}" """
-
-
 def get_network_stats():
     """Obtiene estadísticas de uso de red (ancho de banda)"""
     global _last_net_io, _last_net_time

+ 22 - 0
static/css/toastr-custom.css

@@ -0,0 +1,22 @@
+/* Personalización mínima para el apilamiento vertical de notificaciones toastr */
+/* Este archivo NO debe sobrescribir la funcionalidad básica de toastr */
+
+/* Ajustar el espaciado entre notificaciones - aparecen hacia abajo */
+#toast-container.toast-top-right > div {
+  margin-bottom: 10px;
+  margin-top: 0;
+}
+
+/* Asegurar que las notificaciones sean responsivas en móviles */
+@media screen and (max-width: 768px) {
+  #toast-container.toast-top-right {
+    right: 8px;
+    top: 8px;
+    left: 8px;
+  }
+  
+  #toast-container > div {
+    width: auto !important;
+    max-width: 100%;
+  }
+}

+ 0 - 20
static/js/auditoria/config_and_utils.js

@@ -1,25 +1,5 @@
 // Config & utilidades auditoría (sin cambios funcionales)
 (function(){
-  if (window.toastr) {
-    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"
-    };
-  }
-
   function toggleDetails(header) {
     const details = header.nextElementSibling;
     const icon = header.querySelector('.toggle-icon');

+ 55 - 0
static/js/toastr-config.js

@@ -0,0 +1,55 @@
+// ===== CONFIGURACIÓN GLOBAL DE TOASTR =====
+// Este archivo configura el comportamiento de las notificaciones toastr en toda la aplicación
+
+// Configurar toastr tan pronto como jQuery esté disponible
+(function() {
+  function initToastr() {
+    // Verificar que jQuery y toastr estén disponibles
+    if (typeof $ === 'undefined' || typeof toastr === 'undefined') {
+      console.warn('jQuery o toastr no están disponibles aún');
+      return false;
+    }
+
+    // Configuración de toastr
+    toastr.options = {
+      closeButton: true,
+      debug: false,
+      newestOnTop: false, // false = las nuevas notificaciones aparecen DEBAJO
+      progressBar: true,
+      positionClass: "toast-top-right",
+      preventDuplicates: false,
+      onclick: null,
+      showDuration: 300,
+      hideDuration: 1000,
+      timeOut: 5000, // 5 segundos
+      extendedTimeOut: 1000,
+      showEasing: "swing",
+      hideEasing: "linear",
+      showMethod: "fadeIn",
+      hideMethod: "fadeOut",
+      tapToDismiss: true
+    };
+
+    console.log('✅ Toastr configurado correctamente');
+    return true;
+  }
+
+  // Intentar configurar inmediatamente
+  if (initToastr()) {
+    return; // Ya está configurado
+  }
+
+  // Si no funciona, esperar al DOMContentLoaded
+  if (document.readyState === 'loading') {
+    document.addEventListener('DOMContentLoaded', function() {
+      setTimeout(initToastr, 100);
+    });
+  } else {
+    setTimeout(initToastr, 100);
+  }
+
+  // También intentar en window.load por si acaso
+  window.addEventListener('load', function() {
+    setTimeout(initToastr, 100);
+  });
+})();

+ 11 - 16
templates/admin/base.html

@@ -165,22 +165,17 @@
         }
 
         function showNotification(message, type) {
-            const notification = document.createElement('div');
-            notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
-                type === 'success' ? 'bg-blue-500 text-white' : 'bg-orange-500 text-white'
-            }`;
-            notification.innerHTML = `
-                <div class="flex items-center">
-                    <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>
-                    ${message}
-                </div>
-            `;
-            
-            document.body.appendChild(notification);
-            
-            setTimeout(() => {
-                notification.remove();
-            }, 5000);
+            if (window.toastr) {
+                if (type === 'success') {
+                    toastr.success(message);
+                } else if (type === 'error') {
+                    toastr.error(message);
+                } else if (type === 'warning') {
+                    toastr.warning(message);
+                } else {
+                    toastr.info(message);
+                }
+            }
         }
     </script>
 </body>

+ 11 - 22
templates/admin/clean_data.html

@@ -205,28 +205,17 @@
     }
 
     function showNotification(message, type) {
-        const notification = document.createElement('div');
-        notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
-            type === 'success' ? 'bg-green-500 text-white' : 
-            type === 'error' ? 'bg-red-500 text-white' : 
-            'bg-blue-500 text-white'
-        }`;
-        notification.innerHTML = `
-            <div class="flex items-center">
-                <i class="fas fa-${
-                    type === 'success' ? 'check-circle' : 
-                    type === 'error' ? 'exclamation-circle' : 
-                    'info-circle'
-                } mr-2"></i>
-                ${message}
-            </div>
-        `;
-        
-        document.body.appendChild(notification);
-        
-        setTimeout(() => {
-            notification.remove();
-        }, 5000);
+        if (window.toastr) {
+            if (type === 'success') {
+                toastr.success(message);
+            } else if (type === 'error') {
+                toastr.error(message);
+            } else if (type === 'warning') {
+                toastr.warning(message);
+            } else {
+                toastr.info(message);
+            }
+        }
     }
 </script>
 {% endblock %}

+ 14 - 85
templates/admin/navbar.html

@@ -334,95 +334,24 @@
         }
 
         function showNotificationToast(notification) {
-            // Crear un toast notification
-            const toastId = 'toast-' + Date.now();
-            const toast = document.createElement('div');
-            toast.id = toastId;
-            toast.className = `fixed top-4 right-4 z-[1002] p-4 rounded-lg shadow-lg border-l-4 ${
-                notification.type === 'error' ? 'bg-red-50 border-red-500' :
-                notification.type === 'warning' ? 'bg-yellow-50 border-yellow-500' :
-                notification.type === 'success' ? 'bg-green-50 border-green-500' :
-                'bg-blue-50 border-blue-500'
-            } max-w-sm transform translate-x-full transition-transform duration-300`;
+            if (!window.toastr) return;
             
-            // Create elements safely without innerHTML
-            const container = document.createElement('div');
-            container.className = 'flex items-start';
+            // Construir el título con la fuente
+            const source = notification.source === 'squid' ? 'Squid' : 
+                          notification.source === 'git' ? 'Git' : 'Sistema';
+            const title = notification.count && notification.count > 1 ? 
+                         `${source} (×${notification.count})` : source;
             
-            const iconDiv = document.createElement('div');
-            iconDiv.className = 'flex-shrink-0';
-            const icon = document.createElement('i');
-            icon.className = `fas ${notification.icon} ${
-                notification.type === 'error' ? 'text-red-600' :
-                notification.type === 'warning' ? 'text-yellow-600' :
-                notification.type === 'success' ? 'text-green-600' :
-                'text-blue-600'
-            } text-lg`;
-            iconDiv.appendChild(icon);
-            
-            const contentDiv = document.createElement('div');
-            contentDiv.className = 'ml-3 flex-1';
-            
-            const sourceP = document.createElement('p');
-            sourceP.className = 'text-sm font-medium text-gray-900';
-            
-            // Agregar badge de count si es mayor a 1
-            if (notification.count && notification.count > 1) {
-                const countBadge = document.createElement('span');
-                countBadge.className = 'inline-flex items-center justify-center px-2 py-0.5 ml-2 text-xs font-bold leading-none text-white bg-red-600 rounded-full';
-                countBadge.textContent = `×${notification.count}`;
-                sourceP.textContent = notification.source === 'squid' ? 'Squid' : 
-                                      notification.source === 'git' ? 'Git' : 'Sistema';
-                sourceP.appendChild(countBadge);
+            // Mostrar notificación según el tipo
+            if (notification.type === 'error') {
+                toastr.error(notification.message, title);
+            } else if (notification.type === 'warning') {
+                toastr.warning(notification.message, title);
+            } else if (notification.type === 'success') {
+                toastr.success(notification.message, title);
             } else {
-                sourceP.textContent = notification.source === 'squid' ? 'Squid' : 
-                                      notification.source === 'git' ? 'Git' : 'Sistema';
+                toastr.info(notification.message, title);
             }
-            
-            const messageP = document.createElement('p');
-            messageP.className = 'mt-1 text-sm text-gray-600';
-            messageP.textContent = notification.message;
-            
-            const timeP = document.createElement('p');
-            timeP.className = 'mt-1 text-xs text-gray-500';
-            timeP.textContent = notification.time;
-            
-            contentDiv.appendChild(sourceP);
-            contentDiv.appendChild(messageP);
-            contentDiv.appendChild(timeP);
-            
-            const closeBtn = document.createElement('button');
-            closeBtn.className = 'ml-4 flex-shrink-0 text-gray-400 hover:text-gray-600';
-            closeBtn.onclick = () => document.getElementById(toastId).remove();
-            const closeIcon = document.createElement('i');
-            closeIcon.className = 'fas fa-times';
-            closeBtn.appendChild(closeIcon);
-            
-            container.appendChild(iconDiv);
-            container.appendChild(contentDiv);
-            container.appendChild(closeBtn);
-            toast.appendChild(container);
-            
-            document.body.appendChild(toast);
-            
-            // Animación de entrada
-            setTimeout(() => {
-                toast.classList.remove('translate-x-full');
-                toast.classList.add('translate-x-0');
-            }, 100);
-            
-            // Auto-remover después de 8 segundos
-            setTimeout(() => {
-                const toastElement = document.getElementById(toastId);
-                if (toastElement) {
-                    toastElement.classList.add('translate-x-full');
-                    setTimeout(() => {
-                        if (toastElement.parentElement) {
-                            toastElement.remove();
-                        }
-                    }, 300);
-                }
-            }, 8000);
         }
 
         function updateNotificationLists() {

+ 13 - 35
templates/all_notifications.html

@@ -219,41 +219,19 @@ document.addEventListener('DOMContentLoaded', function() {
     const totalPages = {{ pagination.total_pages if pagination else 1 }};
     const perPage = {{ pagination.per_page if pagination else 20 }};
     
-    // Función para mostrar toast
-    function showToast(message, type = 'info') {
-        const toast = document.createElement('div');
-        toast.className = `fixed top-4 right-4 z-[1002] p-4 rounded-lg shadow-lg border-l-4 ${
-            type === 'error' ? 'bg-red-50 border-red-500 text-red-700' :
-            type === 'success' ? 'bg-green-50 border-green-500 text-green-700' :
-            'bg-blue-50 border-blue-500 text-blue-700'
-        } max-w-sm transform translate-x-full transition-transform duration-300`;
-        
-        toast.innerHTML = `
-            <div class="flex items-center">
-                <i class="fas ${
-                    type === 'error' ? 'fa-exclamation-circle' :
-                    type === 'success' ? 'fa-check-circle' : 'fa-info-circle'
-                } mr-3"></i>
-                <span>${message}</span>
-            </div>
-        `;
-        
-        document.body.appendChild(toast);
-        
-        setTimeout(() => {
-            toast.classList.remove('translate-x-full');
-            toast.classList.add('translate-x-0');
-        }, 100);
-        
-        setTimeout(() => {
-            toast.classList.remove('translate-x-0');
-            toast.classList.add('translate-x-full');
-            setTimeout(() => {
-                if (toast.parentElement) {
-                    toast.remove();
-                }
-            }, 300);
-        }, 4000);
+// Función para mostrar toast usando toastr
+      function showToast(message, type = 'info') {
+          if (window.toastr) {
+              if (type === 'error') {
+                  toastr.error(message);
+              } else if (type === 'success') {
+                  toastr.success(message);
+              } else if (type === 'warning') {
+                  toastr.warning(message);
+              } else {
+                  toastr.info(message);
+              }
+          }
     }
 
     // Function to load notifications with pagination

+ 14 - 85
templates/components/navbar.html

@@ -337,95 +337,24 @@
         }
 
         function showNotificationToast(notification) {
-            // Crear un toast notification
-            const toastId = 'toast-' + Date.now();
-            const toast = document.createElement('div');
-            toast.id = toastId;
-            toast.className = `fixed top-4 right-4 z-[1002] p-4 rounded-lg shadow-lg border-l-4 ${
-                notification.type === 'error' ? 'bg-red-50 border-red-500' :
-                notification.type === 'warning' ? 'bg-yellow-50 border-yellow-500' :
-                notification.type === 'success' ? 'bg-green-50 border-green-500' :
-                'bg-blue-50 border-blue-500'
-            } max-w-sm transform translate-x-full transition-transform duration-300`;
+            if (!window.toastr) return;
             
-            // Create elements safely without innerHTML
-            const container = document.createElement('div');
-            container.className = 'flex items-start';
+            // Construir el título con la fuente
+            const source = notification.source === 'squid' ? 'Squid' : 
+                          notification.source === 'git' ? 'Git' : 'Sistema';
+            const title = notification.count && notification.count > 1 ? 
+                         `${source} (×${notification.count})` : source;
             
-            const iconDiv = document.createElement('div');
-            iconDiv.className = 'flex-shrink-0';
-            const icon = document.createElement('i');
-            icon.className = `fas ${notification.icon} ${
-                notification.type === 'error' ? 'text-red-600' :
-                notification.type === 'warning' ? 'text-yellow-600' :
-                notification.type === 'success' ? 'text-green-600' :
-                'text-blue-600'
-            } text-lg`;
-            iconDiv.appendChild(icon);
-            
-            const contentDiv = document.createElement('div');
-            contentDiv.className = 'ml-3 flex-1';
-            
-            const sourceP = document.createElement('p');
-            sourceP.className = 'text-sm font-medium text-gray-900';
-            
-            // Agregar badge de count si es mayor a 1
-            if (notification.count && notification.count > 1) {
-                const countBadge = document.createElement('span');
-                countBadge.className = 'inline-flex items-center justify-center px-2 py-0.5 ml-2 text-xs font-bold leading-none text-white bg-red-600 rounded-full';
-                countBadge.textContent = `×${notification.count}`;
-                sourceP.textContent = notification.source === 'squid' ? 'Squid' : 
-                                      notification.source === 'git' ? 'Git' : 'Sistema';
-                sourceP.appendChild(countBadge);
+            // Mostrar notificación según el tipo
+            if (notification.type === 'error') {
+                toastr.error(notification.message, title);
+            } else if (notification.type === 'warning') {
+                toastr.warning(notification.message, title);
+            } else if (notification.type === 'success') {
+                toastr.success(notification.message, title);
             } else {
-                sourceP.textContent = notification.source === 'squid' ? 'Squid' : 
-                                      notification.source === 'git' ? 'Git' : 'Sistema';
+                toastr.info(notification.message, title);
             }
-            
-            const messageP = document.createElement('p');
-            messageP.className = 'mt-1 text-sm text-gray-600';
-            messageP.textContent = notification.message;
-            
-            const timeP = document.createElement('p');
-            timeP.className = 'mt-1 text-xs text-gray-500';
-            timeP.textContent = notification.time;
-            
-            contentDiv.appendChild(sourceP);
-            contentDiv.appendChild(messageP);
-            contentDiv.appendChild(timeP);
-            
-            const closeBtn = document.createElement('button');
-            closeBtn.className = 'ml-4 flex-shrink-0 text-gray-400 hover:text-gray-600';
-            closeBtn.onclick = () => document.getElementById(toastId).remove();
-            const closeIcon = document.createElement('i');
-            closeIcon.className = 'fas fa-times';
-            closeBtn.appendChild(closeIcon);
-            
-            container.appendChild(iconDiv);
-            container.appendChild(contentDiv);
-            container.appendChild(closeBtn);
-            toast.appendChild(container);
-            
-            document.body.appendChild(toast);
-            
-            // Animación de entrada
-            setTimeout(() => {
-                toast.classList.remove('translate-x-full');
-                toast.classList.add('translate-x-0');
-            }, 100);
-            
-            // Auto-remover después de 8 segundos
-            setTimeout(() => {
-                const toastElement = document.getElementById(toastId);
-                if (toastElement) {
-                    toastElement.classList.add('translate-x-full');
-                    setTimeout(() => {
-                        if (toastElement.parentElement) {
-                            toastElement.remove();
-                        }
-                    }, 300);
-                }
-            }, 8000);
         }
 
         function updateNotificationLists() {

+ 10 - 0
templates/layouts/base.html

@@ -13,6 +13,10 @@
     <link rel="stylesheet" href="{{ url_for('static', filename='all.min.css') }}"/>
     <!-- Font Awesome -->
     <link rel="stylesheet" href="{{ url_for('static', filename='logs.css') }}"/>
+    <!-- Toastr CSS -->
+    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr.min.css') }}"/>
+    <!-- Toastr Custom CSS -->
+    <link rel="stylesheet" href="{{ url_for('static', filename='css/toastr-custom.css') }}"/>
     <!-- Page-specific styles -->
     {% block styles %}{% endblock styles %}
   </head>
@@ -61,6 +65,12 @@
     <script src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
     <!-- Flowbite scripts (UI components) -->
     <script src="{{ url_for('static', filename='src/flowbite.min.js') }}"></script>
+    <!-- jQuery (requerido por toastr) -->
+    <script src="{{ url_for('static', filename='js/jquery-3.7.1.min.js') }}"></script>
+    <!-- Toastr JS -->
+    <script src="{{ url_for('static', filename='js/toastr.min.js') }}"></script>
+    <!-- Configuración global de Toastr -->
+    <script src="{{ url_for('static', filename='js/toastr-config.js') }}"></script>
     <!-- Page-specific scripts -->
     {% block scripts %}{% endblock scripts %}
   </body>