Sfoglia il codice sorgente

Add database management template for Squid Proxy admin panel

- Implemented a new HTML template for database management, including tabs for DB summary, backups, and data cleaning.
- Integrated Alpine.js for dynamic content loading and user interactions.
- Added functionality for displaying database health status, backup management, and data cleaning operations.
- Included error handling and user feedback mechanisms for various actions.
Manuel 8 mesi fa
parent
commit
bed99ae65e
2 ha cambiato i file con 937 aggiunte e 6 eliminazioni
  1. 3 6
      templates/admin/base.html
  2. 934 0
      templates/admin/database.html

+ 3 - 6
templates/admin/base.html

@@ -116,8 +116,8 @@
                     <a href="{{ url_for('admin.manage_users') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-users mr-3"></i>Usuarios
                     </a>
-                    <a href="{{ url_for('admin.clean_data') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
-                        <i class="fas fa-database mr-3"></i>Limpiar Datos
+                    <a href="{{ url_for('admin.database_view') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
+                        <i class="fas fa-database mr-3"></i>Base de Datos
                     </a>
                     <a href="{{ url_for('admin.manage_acls') }}" class="flex items-center justify-between px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <span class="flex items-center">
@@ -147,9 +147,7 @@
                     <a href="{{ url_for('admin.view_logs') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
                         <i class="fas fa-file-alt mr-3"></i>Logs
                     </a>
-                    <a href="{{ url_for('admin.backup_config') }}" class="flex items-center px-4 py-3 text-gray-700 hover:bg-blue-50 hover:text-blue-600 rounded-lg transition-colors">
-                        <i class="fas fa-database mr-3"></i>Salvas de BD
-                    </a>
+
                 </div>
             </nav>
         </aside>
@@ -177,7 +175,6 @@
     <!-- Custom Confirm Modal -->
     {% include 'components/confirm_modal.html' %}
 
-    <script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
     <script src="{{ url_for('static', filename='js/confirm_modal.js') }}"></script>
     <script>
         // Get CSRF token from meta tag

+ 934 - 0
templates/admin/database.html

@@ -0,0 +1,934 @@
+{% extends "admin/base.html" %}
+
+{% block title %}Base de Datos - Administrador Squid Proxy{% endblock %}
+
+{% block content %}
+<div x-data="{ activeTab: 'resumen' }">
+
+    <!-- Page Header -->
+    <div class="flex items-center justify-between mb-6">
+        <div>
+            <h2 class="text-2xl font-bold text-gray-800">Base de Datos</h2>
+            <p class="text-sm text-gray-500 mt-1">Monitor de salud, copias de seguridad y gestión de datos</p>
+        </div>
+    </div>
+
+    <!-- Tab Navigation -->
+    <div class="bg-white rounded-xl shadow-sm border border-gray-100 mb-6 overflow-x-auto">
+        <nav class="flex border-b border-gray-200 min-w-max">
+            <button @click="activeTab = 'resumen'"
+                :class="activeTab === 'resumen'
+                    ? 'border-blue-600 text-blue-600 bg-blue-50/40'
+                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
+                class="flex items-center gap-2 px-6 py-4 text-sm font-semibold border-b-2 -mb-px transition-colors duration-150 focus:outline-none whitespace-nowrap">
+                <i class="fas fa-heartbeat text-base"></i>
+                Resumen DB
+            </button>
+            <button @click="activeTab = 'salvas'"
+                :class="activeTab === 'salvas'
+                    ? 'border-blue-600 text-blue-600 bg-blue-50/40'
+                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
+                class="flex items-center gap-2 px-6 py-4 text-sm font-semibold border-b-2 -mb-px transition-colors duration-150 focus:outline-none whitespace-nowrap">
+                <i class="fas fa-save text-base"></i>
+                Salvas de BD
+            </button>
+            <button @click="activeTab = 'limpiar'"
+                :class="activeTab === 'limpiar'
+                    ? 'border-blue-600 text-blue-600 bg-blue-50/40'
+                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
+                class="flex items-center gap-2 px-6 py-4 text-sm font-semibold border-b-2 -mb-px transition-colors duration-150 focus:outline-none whitespace-nowrap">
+                <i class="fas fa-trash-alt text-base"></i>
+                Limpiar Datos
+            </button>
+        </nav>
+    </div>
+
+    <!-- ═══════════════════════════════════════════════════════
+         TAB: RESUMEN DB
+    ════════════════════════════════════════════════════════ -->
+    <div x-show="activeTab === 'resumen'" x-data="dbHealthPanel()" class="space-y-6">
+
+        <!-- Loading -->
+        <div x-show="loading" class="flex items-center justify-center py-24">
+            <div class="text-center">
+                <i class="fas fa-spinner fa-spin text-blue-500 text-4xl mb-4"></i>
+                <p class="text-sm text-gray-500 font-medium">Cargando información de la base de datos...</p>
+            </div>
+        </div>
+
+        <!-- Error -->
+        <div x-show="!loading && !!error"
+             class="bg-red-50 border border-red-200 rounded-xl p-5 flex items-center gap-4">
+            <i class="fas fa-exclamation-circle text-red-500 text-2xl flex-shrink-0"></i>
+            <div class="flex-1">
+                <p class="font-semibold text-red-800">Error al cargar los datos</p>
+                <p class="text-sm text-red-600 mt-0.5" x-text="error"></p>
+            </div>
+            <button @click="loadHealth()"
+                    class="text-sm text-red-700 hover:text-red-900 font-semibold border border-red-300 hover:border-red-400 rounded-lg px-3 py-1.5 transition-colors">
+                <i class="fas fa-redo mr-1"></i>Reintentar
+            </button>
+        </div>
+
+        <!-- ── Health status banner ── -->
+        <template x-if="!loading && health">
+            <div :class="{
+                    'bg-emerald-50 border-emerald-200': healthStatus === 'good',
+                    'bg-amber-50 border-amber-200': healthStatus === 'warning',
+                    'bg-red-50 border-red-200': healthStatus === 'critical'
+                 }"
+                 class="border rounded-xl p-4 flex items-center gap-4">
+                <div :class="{
+                        'bg-emerald-100 text-emerald-500': healthStatus === 'good',
+                        'bg-amber-100 text-amber-500': healthStatus === 'warning',
+                        'bg-red-100 text-red-500': healthStatus === 'critical'
+                     }"
+                     class="w-14 h-14 rounded-full flex items-center justify-center flex-shrink-0">
+                    <i :class="{
+                        'fas fa-check-circle text-3xl': healthStatus === 'good',
+                        'fas fa-exclamation-circle text-3xl': healthStatus === 'warning',
+                        'fas fa-times-circle text-3xl': healthStatus === 'critical'
+                    }"></i>
+                </div>
+                <div class="flex-1 min-w-0">
+                    <p :class="{
+                            'text-emerald-800': healthStatus === 'good',
+                            'text-amber-800': healthStatus === 'warning',
+                            'text-red-800': healthStatus === 'critical'
+                        }"
+                       class="font-bold text-lg"
+                       x-text="'Salud de la BD: ' + healthLabel"></p>
+                    <p :class="{
+                            'text-emerald-700': healthStatus === 'good',
+                            'text-amber-700': healthStatus === 'warning',
+                            'text-red-700': healthStatus === 'critical'
+                        }"
+                       class="text-sm mt-0.5">
+                        <span x-show="health.db_type === 'SQLITE'">
+                            Fragmentación:
+                            <strong x-text="health.extra.fragmentation_pct + '%'"></strong>
+                            <span x-show="healthStatus === 'good'"> — dentro del rango normal</span>
+                            <span x-show="healthStatus === 'warning'"> — considera ejecutar VACUUM</span>
+                            <span x-show="healthStatus === 'critical'"> — ejecuta VACUUM urgentemente</span>
+                        </span>
+                        <span x-show="health.db_type !== 'SQLITE'">
+                            Motor <strong x-text="health.db_type"></strong> operando con normalidad
+                        </span>
+                    </p>
+                </div>
+                <button @click="loadHealth()"
+                        class="text-sm font-medium opacity-60 hover:opacity-100 transition-opacity flex-shrink-0"
+                        :class="{
+                            'text-emerald-800': healthStatus === 'good',
+                            'text-amber-800': healthStatus === 'warning',
+                            'text-red-800': healthStatus === 'critical'
+                        }">
+                    <i class="fas fa-sync-alt mr-1"></i>Actualizar
+                </button>
+            </div>
+        </template>
+
+        <!-- ── 4 stat cards ── -->
+        <template x-if="!loading && health">
+            <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
+                <!-- DB Engine -->
+                <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                    <div class="w-12 h-12 bg-indigo-100 rounded-xl flex items-center justify-center flex-shrink-0">
+                        <i class="fas fa-database text-indigo-600 text-xl"></i>
+                    </div>
+                    <div class="min-w-0">
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Motor</p>
+                        <p class="text-xl font-bold text-gray-800 truncate" x-text="health.db_type"></p>
+                    </div>
+                </div>
+                <!-- Total Size -->
+                <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                    <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center flex-shrink-0">
+                        <i class="fas fa-hdd text-blue-600 text-xl"></i>
+                    </div>
+                    <div class="min-w-0">
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Tamaño Total</p>
+                        <p class="text-xl font-bold text-gray-800" x-text="formatBytes(health.total_size_bytes)"></p>
+                    </div>
+                </div>
+                <!-- Tables -->
+                <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                    <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center flex-shrink-0">
+                        <i class="fas fa-table text-purple-600 text-xl"></i>
+                    </div>
+                    <div class="min-w-0">
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Tablas</p>
+                        <p class="text-xl font-bold text-gray-800" x-text="health.table_count.toLocaleString()"></p>
+                    </div>
+                </div>
+                <!-- Total Records -->
+                <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                    <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center flex-shrink-0">
+                        <i class="fas fa-list-ol text-emerald-600 text-xl"></i>
+                    </div>
+                    <div class="min-w-0">
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Registros Totales</p>
+                        <p class="text-xl font-bold text-gray-800" x-text="health.total_rows.toLocaleString()"></p>
+                    </div>
+                </div>
+            </div>
+        </template>
+
+        <!-- ── SQLite extra details ── -->
+        <template x-if="!loading && health && health.db_type === 'SQLITE'">
+            <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
+                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
+                    <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
+                        <i class="fas fa-info-circle text-blue-500"></i>
+                        Detalles SQLite
+                    </h3>
+                </div>
+                <div class="p-6 grid grid-cols-2 md:grid-cols-3 gap-x-8 gap-y-5">
+                    <div>
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">Tamaño de Página</p>
+                        <p class="text-lg font-semibold text-gray-800"
+                           x-text="(health.extra.page_size / 1024).toFixed(1) + ' KB'"></p>
+                    </div>
+                    <div>
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">Páginas Totales</p>
+                        <p class="text-lg font-semibold text-gray-800"
+                           x-text="health.extra.page_count.toLocaleString()"></p>
+                    </div>
+                    <div>
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">Páginas Libres</p>
+                        <p class="text-lg font-semibold text-gray-800"
+                           x-text="health.extra.freelist_count.toLocaleString()"></p>
+                    </div>
+                    <div>
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">Modo Journal</p>
+                        <p class="text-lg font-semibold text-gray-800 uppercase"
+                           x-text="health.extra.journal_mode"></p>
+                    </div>
+                    <div>
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">Auto-Vacuum</p>
+                        <p class="text-lg font-semibold text-gray-800"
+                           x-text="health.extra.auto_vacuum"></p>
+                    </div>
+                    <div>
+                        <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">Fragmentación</p>
+                        <div class="flex items-center gap-2">
+                            <p class="text-lg font-semibold text-gray-800"
+                               x-text="health.extra.fragmentation_pct + '%'"></p>
+                            <span :class="{
+                                    'bg-emerald-100 text-emerald-700': healthStatus === 'good',
+                                    'bg-amber-100 text-amber-700': healthStatus === 'warning',
+                                    'bg-red-100 text-red-700': healthStatus === 'critical'
+                                 }"
+                                  class="text-xs font-semibold px-2 py-0.5 rounded-full"
+                                  x-text="healthLabel"></span>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </template>
+
+        <!-- ── MySQL / PostgreSQL version ── -->
+        <template x-if="!loading && health && health.db_type !== 'SQLITE' && health.extra && health.extra.version">
+            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                <div class="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center flex-shrink-0">
+                    <i class="fas fa-code-branch text-gray-500 text-xl"></i>
+                </div>
+                <div>
+                    <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-0.5">Versión del Motor</p>
+                    <p class="text-base font-semibold text-gray-800" x-text="health.extra.version"></p>
+                </div>
+            </div>
+        </template>
+
+        <!-- ── Integrity Check ── -->
+        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
+            <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
+                <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
+                    <i class="fas fa-shield-alt text-blue-500"></i>
+                    Verificación de Integridad
+                </h3>
+            </div>
+            <div class="p-6 space-y-4">
+                <p class="text-sm text-gray-600">
+                    Verifica la integridad estructural de la base de datos en busca de posibles errores o corrupción.
+                    <span class="text-amber-600 font-medium">
+                        Esta operación puede tardar varios minutos en bases de datos grandes.
+                    </span>
+                </p>
+                <button @click="checkIntegrity()" :disabled="integrityLoading"
+                        class="flex items-center gap-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold px-5 py-2.5 rounded-lg shadow hover:shadow-md transition-all duration-200 disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none">
+                    <i :class="integrityLoading ? 'fas fa-spinner fa-spin' : 'fas fa-search'"></i>
+                    <span x-text="integrityLoading ? 'Verificando...' : 'Verificar Integridad'"></span>
+                </button>
+
+                <template x-if="integrityResult">
+                    <div :class="integrityResult.ok
+                                ? 'bg-emerald-50 border-emerald-200 text-emerald-800'
+                                : 'bg-red-50 border-red-200 text-red-800'"
+                         class="border rounded-xl p-4 flex items-start gap-3">
+                        <i :class="integrityResult.ok
+                                  ? 'fas fa-check-circle text-emerald-500'
+                                  : 'fas fa-times-circle text-red-500'"
+                           class="text-xl flex-shrink-0 mt-0.5"></i>
+                        <div class="flex-1 min-w-0">
+                            <p class="font-semibold"
+                               x-text="integrityResult.ok ? 'Sin errores detectados — la base de datos está íntegra.' : 'Se encontraron errores de integridad.'"></p>
+                            <p class="text-sm mt-0.5"
+                               x-show="integrityResult.error_count > 0"
+                               x-text="integrityResult.error_count + ' error(es) detectado(s)'"></p>
+                            <ul x-show="integrityResult.errors && integrityResult.errors.length > 0"
+                                class="mt-2 space-y-1">
+                                <template x-for="err in integrityResult.errors" :key="err">
+                                    <li class="text-sm font-mono bg-white/60 border border-current/10 rounded px-3 py-1"
+                                        x-text="err"></li>
+                                </template>
+                            </ul>
+                        </div>
+                    </div>
+                </template>
+            </div>
+        </div>
+
+    </div><!-- end resumen tab -->
+
+
+    <!-- ═══════════════════════════════════════════════════════
+         TAB: SALVAS DE BD
+    ════════════════════════════════════════════════════════ -->
+    <div x-show="activeTab === 'salvas'" x-data="backupManager()" class="space-y-6">
+
+        <!-- Page sub-header -->
+        <div class="flex items-center justify-between">
+            <div>
+                <h3 class="text-xl font-bold text-gray-800">Salvas de Base de Datos</h3>
+                <p class="text-sm text-gray-500 mt-1">Configura y gestiona las copias de seguridad automáticas</p>
+            </div>
+            <button @click="triggerManualBackup()" :disabled="loadingManual"
+                class="flex items-center gap-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold px-5 py-2.5 rounded-lg shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-200 disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none">
+                <i :class="loadingManual ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
+                <span x-text="loadingManual ? 'Guardando...' : 'Salva Manual'"></span>
+            </button>
+        </div>
+
+        <!-- Status Banner -->
+        <div x-show="statusMsg" x-transition
+            :class="statusType === 'success' ? 'bg-emerald-50 border border-emerald-200 text-emerald-800' : 'bg-red-50 border border-red-200 text-red-800'"
+            class="flex items-center gap-3 px-4 py-3 rounded-lg" style="display:none;">
+            <i :class="statusType === 'success' ? 'fas fa-check-circle text-emerald-500' : 'fas fa-times-circle text-red-500'"></i>
+            <span x-text="statusMsg" class="text-sm font-medium"></span>
+            <button @click="statusMsg = ''" class="ml-auto text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
+        </div>
+
+        <!-- Stats Cards -->
+        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
+            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
+                    <i class="fas fa-database text-blue-600 text-xl"></i>
+                </div>
+                <div>
+                    <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Total Salvas</p>
+                    <p class="text-2xl font-bold text-gray-800" x-text="backups.length">--</p>
+                </div>
+            </div>
+            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center">
+                    <i class="fas fa-clock text-emerald-600 text-xl"></i>
+                </div>
+                <div>
+                    <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Última Salva</p>
+                    <p class="text-sm font-semibold text-gray-800" x-text="lastBackupDate">Sin salvas</p>
+                </div>
+            </div>
+            <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
+                <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
+                    <i class="fas fa-hdd text-purple-600 text-xl"></i>
+                </div>
+                <div>
+                    <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Espacio Total</p>
+                    <p class="text-sm font-semibold text-gray-800" x-text="totalSize">0 B</p>
+                </div>
+            </div>
+        </div>
+
+        <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
+
+            <!-- Configuration Panel -->
+            <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
+                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
+                    <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
+                        <i class="fas fa-sliders-h text-blue-500"></i>
+                        Configuración de Salvas
+                    </h3>
+                </div>
+                <form @submit.prevent="saveConfig()" class="p-6 space-y-5">
+                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
+
+                    <!-- DB Engine -->
+                    <div>
+                        <label class="block text-sm font-medium text-gray-700 mb-2">
+                            <i class="fas fa-server text-gray-400 mr-1"></i> Motor de Base de Datos
+                        </label>
+                        <div class="relative">
+                            <select x-model="config.db_type" @change="onDbTypeChange()"
+                                class="w-full appearance-none bg-white border border-gray-300 text-gray-700 text-sm rounded-lg px-4 py-2.5 pr-8 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors">
+                                <option value="sqlite">SQLite (Activo)</option>
+                                <option value="mysql" disabled class="text-gray-400">MySQL / MariaDB (Próximamente)</option>
+                                <option value="postgresql" disabled class="text-gray-400">PostgreSQL (Próximamente)</option>
+                            </select>
+                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
+                                <i class="fas fa-chevron-down text-xs"></i>
+                            </div>
+                        </div>
+                        <template x-if="config.db_type !== 'sqlite'">
+                            <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
+                                <i class="fas fa-exclamation-triangle"></i>
+                                Este motor aún no está implementado.
+                            </p>
+                        </template>
+                    </div>
+
+                    <!-- Frequency -->
+                    <div>
+                        <label class="block text-sm font-medium text-gray-700 mb-2">
+                            <i class="fas fa-calendar-alt text-gray-400 mr-1"></i> Frecuencia
+                        </label>
+                        <div class="relative">
+                            <select x-model="config.frequency"
+                                class="w-full appearance-none bg-white border border-gray-300 text-gray-700 text-sm rounded-lg px-4 py-2.5 pr-8 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors">
+                                <option value="daily_weekly">Diaria — máx. 3 por semana</option>
+                                <option value="daily_monthly">Diaria — máx. 3 por mes</option>
+                            </select>
+                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
+                                <i class="fas fa-chevron-down text-xs"></i>
+                            </div>
+                        </div>
+                        <p class="mt-1.5 text-xs text-gray-500 flex items-center gap-1">
+                            <i class="fas fa-info-circle"></i>
+                            <span x-text="config.frequency === 'daily_weekly' ? 'Se ejecuta diariamente, conservando máx. 3 salvas por semana' : 'Se ejecuta diariamente, conservando máx. 3 salvas por mes'"></span>
+                        </p>
+                    </div>
+
+                    <!-- Retention -->
+                    <div>
+                        <div class="flex items-center justify-between mb-2">
+                            <label class="block text-sm font-medium text-gray-700">
+                                <i class="fas fa-archive text-gray-400 mr-1"></i> Retención máxima
+                            </label>
+                            <span class="inline-flex items-center gap-1 bg-blue-100 text-blue-700 text-xs font-semibold px-2.5 py-0.5 rounded-full">
+                                <i class="fas fa-lock text-xs"></i> Fijo: 3 salvas
+                            </span>
+                        </div>
+                        <div class="flex items-center gap-3 bg-gray-50 border border-gray-200 rounded-lg px-4 py-3">
+                            <div class="flex gap-1.5">
+                                <template x-for="i in [1,2,3]" :key="i">
+                                    <div class="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold bg-blue-500 text-white shadow-sm">
+                                        <span x-text="i"></span>
+                                    </div>
+                                </template>
+                            </div>
+                            <p class="text-xs text-gray-600">Se mantienen las 3 salvas más recientes. Las más antiguas se eliminan automáticamente.</p>
+                        </div>
+                    </div>
+
+                    <!-- Backup Directory -->
+                    <div>
+                        <label class="block text-sm font-medium text-gray-700 mb-2">
+                            <i class="fas fa-folder text-gray-400 mr-1"></i> Directorio de Salvas
+                        </label>
+                        <input type="text" x-model="config.backup_dir"
+                            class="w-full bg-white border border-gray-300 text-gray-700 text-sm rounded-lg px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-colors"
+                            placeholder="/opt/SquidStats/backups" />
+                        <p class="mt-1.5 text-xs text-gray-500">Ruta absoluta donde se guardarán las salvas</p>
+                    </div>
+
+                    <!-- Enabled Toggle -->
+                    <div class="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3 border border-gray-200">
+                        <div>
+                            <p class="text-sm font-medium text-gray-700">Salvas automáticas</p>
+                            <p class="text-xs text-gray-500 mt-0.5">Habilitar programación automática</p>
+                        </div>
+                        <button type="button" @click="config.enabled = !config.enabled"
+                            :class="config.enabled ? 'bg-blue-600' : 'bg-gray-300'"
+                            class="relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
+                            <span :class="config.enabled ? 'translate-x-5' : 'translate-x-0'"
+                                class="pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out"></span>
+                        </button>
+                    </div>
+
+                    <!-- Submit -->
+                    <button type="submit" :disabled="loadingSave"
+                        class="w-full flex items-center justify-center gap-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold py-2.5 rounded-lg shadow hover:shadow-lg transition-all duration-200 disabled:opacity-60 disabled:cursor-not-allowed">
+                        <i :class="loadingSave ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
+                        <span x-text="loadingSave ? 'Guardando...' : 'Guardar Configuración'"></span>
+                    </button>
+                </form>
+            </div>
+
+            <!-- Backups List -->
+            <div class="lg:col-span-3 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden flex flex-col">
+                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200 flex items-center justify-between">
+                    <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
+                        <i class="fas fa-history text-blue-500"></i>
+                        Historial de Salvas
+                    </h3>
+                    <button @click="loadBackups()" class="text-xs text-blue-600 hover:text-blue-800 font-medium flex items-center gap-1 transition-colors">
+                        <i class="fas fa-sync-alt" :class="loadingList ? 'animate-spin' : ''"></i> Actualizar
+                    </button>
+                </div>
+
+                <!-- Loading -->
+                <div x-show="loadingList" class="flex-1 flex items-center justify-center py-16">
+                    <div class="text-center">
+                        <i class="fas fa-spinner fa-spin text-blue-500 text-3xl mb-3"></i>
+                        <p class="text-sm text-gray-500">Cargando salvas...</p>
+                    </div>
+                </div>
+
+                <!-- Empty -->
+                <div x-show="!loadingList && backups.length === 0" class="flex-1 flex items-center justify-center py-16">
+                    <div class="text-center px-6">
+                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
+                            <i class="fas fa-box-open text-gray-400 text-2xl"></i>
+                        </div>
+                        <p class="text-sm font-medium text-gray-600">No hay salvas disponibles</p>
+                        <p class="text-xs text-gray-400 mt-1">Realiza una salva manual o activa las automáticas</p>
+                    </div>
+                </div>
+
+                <!-- Table -->
+                <div x-show="!loadingList && backups.length > 0" class="flex-1 overflow-auto">
+                    <table class="w-full text-sm">
+                        <thead class="bg-gray-50 sticky top-0">
+                            <tr>
+                                <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Archivo</th>
+                                <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Fecha</th>
+                                <th class="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Tamaño</th>
+                                <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Tipo</th>
+                                <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Acción</th>
+                            </tr>
+                        </thead>
+                        <tbody class="divide-y divide-gray-50">
+                            <template x-for="(backup, idx) in backups" :key="backup.filename">
+                                <tr class="hover:bg-gray-50 transition-colors"
+                                    :class="idx === 0 ? 'bg-emerald-50/40' : ''">
+                                    <td class="px-4 py-3">
+                                        <div class="flex items-center gap-2">
+                                            <i class="fas fa-file-archive text-blue-400 text-xs"></i>
+                                            <span class="font-medium text-gray-700 truncate max-w-[140px]" x-text="backup.filename" :title="backup.filename"></span>
+                                            <template x-if="idx === 0">
+                                                <span class="inline-flex items-center gap-1 bg-emerald-100 text-emerald-700 text-xs font-semibold px-1.5 py-0.5 rounded">
+                                                    <i class="fas fa-star text-xs"></i> Reciente
+                                                </span>
+                                            </template>
+                                        </div>
+                                    </td>
+                                    <td class="px-4 py-3 text-gray-500 whitespace-nowrap" x-text="backup.created_at"></td>
+                                    <td class="px-4 py-3 text-right text-gray-600 font-mono whitespace-nowrap" x-text="backup.size_human"></td>
+                                    <td class="px-4 py-3 text-center">
+                                        <span :class="backup.type === 'auto' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'"
+                                            class="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full">
+                                            <i :class="backup.type === 'auto' ? 'fas fa-robot' : 'fas fa-hand-paper'" class="text-xs"></i>
+                                            <span x-text="backup.type === 'auto' ? 'Auto' : 'Manual'"></span>
+                                        </span>
+                                    </td>
+                                    <td class="px-4 py-3 text-center">
+                                        <div class="flex items-center justify-center gap-1">
+                                            <a :href="'/admin/backup/download/' + backup.filename"
+                                                class="inline-flex items-center gap-1 bg-blue-50 hover:bg-blue-100 text-blue-700 text-xs font-medium px-2.5 py-1.5 rounded-lg transition-colors"
+                                                title="Descargar">
+                                                <i class="fas fa-download"></i>
+                                            </a>
+                                            <button @click="deleteBackup(backup.filename)"
+                                                class="inline-flex items-center gap-1 bg-red-50 hover:bg-red-100 text-red-600 text-xs font-medium px-2.5 py-1.5 rounded-lg transition-colors"
+                                                title="Eliminar">
+                                                <i class="fas fa-trash"></i>
+                                            </button>
+                                        </div>
+                                    </td>
+                                </tr>
+                            </template>
+                        </tbody>
+                    </table>
+                </div>
+
+                <!-- Footer -->
+                <div x-show="!loadingList && backups.length > 0" class="px-6 py-3 bg-gray-50 border-t border-gray-100">
+                    <p class="text-xs text-gray-400 flex items-center gap-1">
+                        <i class="fas fa-info-circle"></i>
+                        Máximo 3 salvas por período. Las más antiguas se eliminan automáticamente.
+                    </p>
+                </div>
+            </div>
+
+        </div><!-- end grid -->
+    </div><!-- end salvas tab -->
+
+
+    <!-- ═══════════════════════════════════════════════════════
+         TAB: LIMPIAR DATOS
+    ════════════════════════════════════════════════════════ -->
+    <div x-show="activeTab === 'limpiar'">
+        <div class="max-w-4xl">
+            <!-- Sub-header -->
+            <div class="mb-8">
+                <h3 class="text-2xl font-bold text-gray-800 mb-2">
+                    <i class="fas fa-database mr-3"></i>Limpiar Datos
+                </h3>
+                <p class="text-gray-600">Selecciona una tabla y elimina todos sus datos</p>
+            </div>
+
+            <!-- Warning -->
+            <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6">
+                <div class="flex items-center">
+                    <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
+                    <div>
+                        <p class="text-red-800 font-medium">¡Advertencia!</p>
+                        <p class="text-red-700 text-sm">Esta acción es irreversible. Una vez eliminados los datos, no se pueden recuperar.</p>
+                    </div>
+                </div>
+            </div>
+
+            <!-- Clean Data Form -->
+            <div class="bg-white rounded-lg shadow-md overflow-hidden">
+                <div class="px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 border-b border-blue-700">
+                    <h4 class="text-xl font-semibold text-white flex items-center">
+                        <i class="fas fa-trash-alt mr-2"></i>
+                        Eliminar Datos de Tabla
+                    </h4>
+                </div>
+                <div class="p-6">
+                    <form id="cleanDataForm" class="space-y-6">
+                        <div>
+                            <label for="tableSelect" class="block text-sm font-medium text-gray-700 mb-2">
+                                <i class="fas fa-table mr-1"></i>Seleccionar Tabla
+                            </label>
+                            <select id="tableSelect" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
+                                <option value="">Cargando tablas...</option>
+                            </select>
+                        </div>
+
+                        <div id="tableInfo" class="hidden bg-gray-50 p-4 rounded-lg border">
+                            <div class="flex items-center justify-between">
+                                <div>
+                                    <h5 class="text-sm font-medium text-gray-900">Información de la Tabla</h5>
+                                    <p id="tableDetails" class="text-sm text-gray-600 mt-1"></p>
+                                </div>
+                                <div id="actionButtons" class="hidden">
+                                    <button type="button" id="cleanButton"
+                                        class="bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white font-medium px-6 py-2 rounded-lg shadow-md hover:shadow-lg transition-all duration-200 flex items-center">
+                                        <i class="fas fa-trash-alt mr-2"></i>
+                                        Limpiar Datos
+                                    </button>
+                                </div>
+                            </div>
+                        </div>
+                    </form>
+                </div>
+            </div>
+
+            <!-- Info Card -->
+            <div class="mt-6 bg-blue-50 border-l-4 border-blue-500 p-4">
+                <div class="flex items-start">
+                    <i class="fas fa-info-circle text-blue-500 text-xl mr-3 mt-1"></i>
+                    <div>
+                        <p class="text-blue-800 font-medium mb-2">Información Importante</p>
+                        <ul class="text-blue-700 text-sm space-y-1 list-disc list-inside">
+                            <li>Solo se eliminan los datos de la tabla, no la estructura</li>
+                            <li>Las tablas con sufijo de fecha (ej: log_20240121) son tablas diarias</li>
+                            <li>Algunas tablas son críticas para el funcionamiento del sistema</li>
+                            <li>Se recomienda hacer un respaldo antes de eliminar datos importantes</li>
+                        </ul>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div><!-- end limpiar tab -->
+
+</div><!-- end x-data outer -->
+
+<script>
+// ──────────────────────────────────────────────────────────
+// DB Health Panel (Alpine component)
+// ──────────────────────────────────────────────────────────
+function dbHealthPanel() {
+    return {
+        loading: false,
+        health: null,
+        error: null,
+        integrityLoading: false,
+        integrityResult: null,
+
+        init() { this.loadHealth(); },
+
+        async loadHealth() {
+            this.loading = true;
+            this.error = null;
+            try {
+                const r = await fetch('/admin/api/db-health', {
+                    headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
+                });
+                const d = await r.json();
+                if (d.status === 'success') this.health = d.health;
+                else this.error = d.message || 'Error desconocido';
+            } catch {
+                this.error = 'Error de conexión al servidor';
+            } finally {
+                this.loading = false;
+            }
+        },
+
+        async checkIntegrity() {
+            this.integrityLoading = true;
+            this.integrityResult = null;
+            try {
+                const r = await fetch('/admin/api/db-integrity', {
+                    method: 'POST',
+                    headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
+                });
+                const d = await r.json();
+                if (d.status === 'success') {
+                    this.integrityResult = d.integrity;
+                } else {
+                    this.integrityResult = { ok: false, errors: [d.message || 'Error desconocido'], error_count: 1 };
+                }
+            } catch {
+                this.integrityResult = { ok: false, errors: ['Error de conexión al servidor'], error_count: 1 };
+            } finally {
+                this.integrityLoading = false;
+            }
+        },
+
+        formatBytes(bytes) {
+            if (!bytes || bytes === 0) return '0 B';
+            const k = 1024;
+            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
+            const i = Math.floor(Math.log(bytes) / Math.log(k));
+            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+        },
+
+        get healthStatus() {
+            const frag = this.health?.extra?.fragmentation_pct ?? 0;
+            if (frag > 30) return 'critical';
+            if (frag > 10) return 'warning';
+            return 'good';
+        },
+        get healthLabel() {
+            return { good: 'Saludable', warning: 'Advertencia', critical: 'Crítico' }[this.healthStatus];
+        }
+    };
+}
+
+// ──────────────────────────────────────────────────────────
+// Backup Manager (Alpine component)
+// ──────────────────────────────────────────────────────────
+function backupManager() {
+    return {
+        config: {
+            db_type: '{{ current_config.db_type | default("sqlite") }}',
+            frequency: '{{ current_config.frequency | default("daily_weekly") }}',
+            backup_dir: '{{ current_config.backup_dir | default("/opt/SquidStats/backups") }}',
+            enabled: {{ 'true' if current_config.enabled | default(false) else 'false' }},
+        },
+        backups: [],
+        loadingList: false,
+        loadingSave: false,
+        loadingManual: false,
+        statusMsg: '',
+        statusType: 'success',
+
+        get lastBackupDate() {
+            if (!this.backups.length) return 'Sin salvas';
+            return this.backups[0].created_at;
+        },
+        get totalSize() {
+            const total = this.backups.reduce((acc, b) => acc + (b.size_bytes || 0), 0);
+            return this.formatBytes(total);
+        },
+        formatBytes(bytes) {
+            if (!bytes) return '0 B';
+            const k = 1024;
+            const sizes = ['B', 'KB', 'MB', 'GB'];
+            const i = Math.floor(Math.log(bytes) / Math.log(k));
+            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+        },
+        onDbTypeChange() {
+            if (this.config.db_type !== 'sqlite') {
+                this.showStatus('Este motor de BD aún no está implementado.', 'error');
+                setTimeout(() => { this.config.db_type = 'sqlite'; }, 1500);
+            }
+        },
+        showStatus(msg, type = 'success') {
+            this.statusMsg = msg;
+            this.statusType = type;
+            setTimeout(() => { this.statusMsg = ''; }, 4000);
+        },
+        async loadBackups() {
+            this.loadingList = true;
+            try {
+                const resp = await fetch('/admin/backup/list', {
+                    headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
+                });
+                const data = await resp.json();
+                if (data.status === 'success') this.backups = data.backups || [];
+                else this.showStatus(data.message || 'Error al cargar salvas', 'error');
+            } catch {
+                this.showStatus('Error de conexión al cargar salvas', 'error');
+            } finally {
+                this.loadingList = false;
+            }
+        },
+        async saveConfig() {
+            this.loadingSave = true;
+            try {
+                const resp = await fetch('/admin/backup/config', {
+                    method: 'POST',
+                    headers: {
+                        'Content-Type': 'application/json',
+                        'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
+                    },
+                    body: JSON.stringify(this.config)
+                });
+                const data = await resp.json();
+                this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
+            } catch {
+                this.showStatus('Error al guardar la configuración', 'error');
+            } finally {
+                this.loadingSave = false;
+            }
+        },
+        async triggerManualBackup() {
+            this.loadingManual = true;
+            try {
+                const resp = await fetch('/admin/backup/run', {
+                    method: 'POST',
+                    headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
+                });
+                const data = await resp.json();
+                this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
+                if (data.status === 'success') await this.loadBackups();
+            } catch {
+                this.showStatus('Error al ejecutar la salva', 'error');
+            } finally {
+                this.loadingManual = false;
+            }
+        },
+        async deleteBackup(filename) {
+            if (!confirm(`¿Eliminar la salva "${filename}"?`)) return;
+            try {
+                const resp = await fetch('/admin/backup/delete/' + encodeURIComponent(filename), {
+                    method: 'DELETE',
+                    headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
+                });
+                const data = await resp.json();
+                this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
+                if (data.status === 'success') await this.loadBackups();
+            } catch {
+                this.showStatus('Error al eliminar la salva', 'error');
+            }
+        },
+        init() { this.loadBackups(); }
+    };
+}
+
+// ──────────────────────────────────────────────────────────
+// Clean Data (vanilla JS)
+// ──────────────────────────────────────────────────────────
+let tablesData = [];
+
+function formatSize(bytes) {
+    if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
+    const k = 1024;
+    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
+    const i = Math.floor(Math.log(bytes) / Math.log(k));
+    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+}
+
+document.addEventListener('DOMContentLoaded', function () {
+    loadTables();
+
+    document.getElementById('tableSelect').addEventListener('change', function () {
+        const selectedTable = this.value;
+        const tableInfo = document.getElementById('tableInfo');
+        const tableDetails = document.getElementById('tableDetails');
+        const actionButtons = document.getElementById('actionButtons');
+        const cleanButton = document.getElementById('cleanButton');
+
+        if (selectedTable) {
+            const table = tablesData.find(t => t.name === selectedTable);
+            if (table) {
+                tableDetails.textContent = `Tabla: ${table.name} | Registros: ${table.rows.toLocaleString()} | Tamaño: ${formatSize(table.size)}`;
+                tableInfo.classList.remove('hidden');
+                if (table.has_data) {
+                    actionButtons.classList.remove('hidden');
+                    cleanButton.onclick = () => confirmDeleteTable(table.name, table.rows, table.size);
+                } else {
+                    actionButtons.classList.add('hidden');
+                    tableDetails.textContent += ' | Esta tabla está vacía';
+                }
+            }
+        } else {
+            tableInfo.classList.add('hidden');
+        }
+    });
+});
+
+async function loadTables() {
+    try {
+        const response = await fetch('/admin/api/get-tables', {
+            method: 'GET',
+            headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
+        });
+        const data = await response.json();
+        if (data.status === 'success') {
+            tablesData = data.tables;
+            populateTableSelect();
+        }
+    } catch (error) {
+        console.error('Error loading tables:', error);
+    }
+}
+
+function populateTableSelect() {
+    const select = document.getElementById('tableSelect');
+    select.innerHTML = '<option value="">Selecciona una tabla...</option>';
+    tablesData.forEach(table => {
+        const option = document.createElement('option');
+        option.value = table.name;
+        option.textContent = `${table.name} (${table.rows.toLocaleString()} registros, ${formatSize(table.size)})`;
+        select.appendChild(option);
+    });
+}
+
+function confirmDeleteTable(tableName, rowCount, size) {
+    const message = `¿Está seguro de que desea eliminar TODOS los datos de la tabla "${tableName}"?\n\nSe eliminarán ${rowCount.toLocaleString()} registros.\nTamaño aproximado: ${formatSize(size)}\n\nEsta acción NO se puede deshacer.`;
+    showCustomConfirm(message, async () => { await deleteTableData(tableName); });
+}
+
+async function deleteTableData(tableName) {
+    try {
+        const response = await fetch('/admin/api/delete-table-data', {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json',
+                'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
+            },
+            body: JSON.stringify({ table_name: tableName })
+        });
+        const data = await response.json();
+        if (data.status === 'success') {
+            if (window.toastr) toastr.success(data.message);
+            setTimeout(() => {
+                loadTables();
+                document.getElementById('tableSelect').value = '';
+                document.getElementById('tableInfo').classList.add('hidden');
+            }, 1500);
+        } else {
+            if (window.toastr) toastr.error(data.message || 'Error al eliminar los datos');
+        }
+    } catch (error) {
+        console.error('Error:', error);
+        if (window.toastr) toastr.error('Error al eliminar los datos de la tabla');
+    }
+}
+</script>
+{% endblock %}