Parcourir la source

Merge pull request #51 from kaelthasmanu/dev

feat: Add functionality to delete records from the database table.
Kaelthas il y a 10 mois
Parent
commit
e452c2d390
3 fichiers modifiés avec 388 ajouts et 0 suppressions
  1. 153 0
      routes/admin_routes.py
  2. 3 0
      templates/admin/base.html
  3. 232 0
      templates/admin/clean_data.html

+ 153 - 0
routes/admin_routes.py

@@ -10,8 +10,10 @@ from flask import (
     request,
     request,
     url_for,
     url_for,
 )
 )
+from sqlalchemy import MetaData, Table, func, inspect, select, text
 
 
 from config import Config, logger
 from config import Config, logger
+from database.database import get_engine, get_session
 from services.auth_service import AuthService, admin_required, api_auth_required
 from services.auth_service import AuthService, admin_required, api_auth_required
 from utils.admin import SquidConfigManager
 from utils.admin import SquidConfigManager
 
 
@@ -41,6 +43,43 @@ def save_env_vars(env_vars):
             f.write(f'{key}="{value}"\n')
             f.write(f'{key}="{value}"\n')
 
 
 
 
+def get_table_row_count(session, engine, table_name):
+    metadata = MetaData()
+    table = Table(table_name, metadata, autoload_with=engine)
+
+    return session.execute(select(func.count()).select_from(table)).scalar_one()
+
+
+def get_table_size(session, db_type, table_name):
+    if db_type == "SQLITE":
+        result = session.execute(
+            text("SELECT SUM(pgsize) FROM dbstat WHERE name = :name"),
+            {"name": table_name},
+        )
+        return result.scalar() or 0
+
+    if db_type in ("MYSQL", "MARIADB"):
+        result = session.execute(
+            text("""
+                SELECT data_length + index_length
+                FROM information_schema.tables
+                WHERE table_name = :name
+                AND table_schema = DATABASE()
+            """),
+            {"name": table_name},
+        )
+        return result.scalar() or 0
+
+    if db_type in ("POSTGRES", "POSTGRESQL"):
+        result = session.execute(
+            text("SELECT pg_total_relation_size(:name)"),
+            {"name": table_name},
+        )
+        return result.scalar() or 0
+
+    return 0
+
+
 @admin_bp.route("/")
 @admin_bp.route("/")
 @admin_required
 @admin_required
 def admin_dashboard():
 def admin_dashboard():
@@ -387,3 +426,117 @@ def reload_squid():
         if show_details:
         if show_details:
             resp["details"] = str(e)
             resp["details"] = str(e)
         return jsonify(resp), 500
         return jsonify(resp), 500
+
+
+@admin_bp.route("/api/get-tables", methods=["GET"])
+@api_auth_required
+def get_tables():
+    session = None
+    try:
+        engine = get_engine()
+        inspector = inspect(engine)
+        session = get_session()
+        db_type = Config.DATABASE_TYPE
+
+        tables = inspector.get_table_names()
+        table_info = []
+
+        for table_name in tables:
+            try:
+                rows = get_table_row_count(session, engine, table_name)
+                size = get_table_size(session, db_type, table_name)
+
+                table_info.append(
+                    {
+                        "name": table_name,
+                        "rows": rows,
+                        "size": size,
+                        "has_data": rows > 0,
+                    }
+                )
+
+            except Exception as e:
+                logger.warning(f"Error processing table {table_name}: {e}")
+                table_info.append(
+                    {
+                        "name": table_name,
+                        "rows": 0,
+                        "size": 0,
+                        "has_data": False,
+                    }
+                )
+
+        return jsonify({"status": "success", "tables": table_info})
+
+    except Exception as e:
+        logger.exception("Error getting database tables")
+        resp = {"status": "error", "message": "Error interno del servidor"}
+        if current_app.debug:
+            resp["details"] = str(e)
+        return jsonify(resp), 500
+
+    finally:
+        if session:
+            session.close()
+
+
+@admin_bp.route("/clean-data")
+@admin_required
+def clean_data():
+    """View for cleaning database tables."""
+    return render_template("admin/clean_data.html")
+
+
+@admin_bp.route("/api/delete-table-data", methods=["POST"])
+@api_auth_required
+def delete_table_data():
+    """API endpoint to delete all data from a table."""
+    try:
+        data = request.get_json()
+        table_name = data.get("table_name")
+
+        if not table_name:
+            return jsonify(
+                {"status": "error", "message": "Nombre de tabla no proporcionado"}
+            ), 400
+
+        # Validate table name to prevent SQL injection
+        import re
+
+        if not re.match(r"^[a-zA-Z0-9_]+$", table_name):
+            return jsonify(
+                {"status": "error", "message": "Nombre de tabla inválido"}
+            ), 400
+
+        engine = get_engine()
+        inspector = inspect(engine)
+
+        # Verify table exists
+        if table_name not in inspector.get_table_names():
+            return jsonify({"status": "error", "message": "La tabla no existe"}), 404
+
+        # Delete all data from table
+        metadata = MetaData()
+        table = Table(table_name, metadata, autoload_with=engine)
+        with engine.connect() as conn:
+            conn.execute(table.delete())
+            conn.commit()
+
+        return jsonify(
+            {
+                "status": "success",
+                "message": f"Datos de la tabla '{table_name}' eliminados correctamente",
+            }
+        )
+
+    except Exception as e:
+        logger.exception("Error deleting data from table")
+        try:
+            show_details = bool(current_app.debug)
+        except RuntimeError:
+            show_details = False
+
+        resp = {"status": "error", "message": "Error interno del servidor"}
+        if show_details:
+            resp["details"] = str(e)
+        return jsonify(resp), 500

+ 3 - 0
templates/admin/base.html

@@ -64,6 +64,9 @@
                     <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">
                     <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
                         <i class="fas fa-users mr-3"></i>Usuarios
                     </a>
                     </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>
                     <div class="flex items-center px-4 py-3 text-gray-400 cursor-not-allowed rounded-lg">
                     <div class="flex items-center px-4 py-3 text-gray-400 cursor-not-allowed rounded-lg">
                         <i class="fas fa-shield-alt mr-3"></i>
                         <i class="fas fa-shield-alt mr-3"></i>
                         <span>ACLs</span>
                         <span>ACLs</span>

+ 232 - 0
templates/admin/clean_data.html

@@ -0,0 +1,232 @@
+{% extends "admin/base.html" %}
+
+{% block title %}Limpiar Datos - Administrador Squid Proxy{% endblock %}
+
+{% block content %}
+<div class="max-w-4xl mx-auto">
+    <!-- Header -->
+    <div class="mb-8">
+        <h2 class="text-3xl font-bold text-gray-800 mb-2">
+            <i class="fas fa-database mr-3"></i>Limpiar Datos
+        </h2>
+        <p class="text-gray-600">Selecciona una tabla y elimina todos sus datos</p>
+    </div>
+
+    <!-- Warning Alert -->
+    <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">
+            <h3 class="text-xl font-semibold text-white flex items-center">
+                <i class="fas fa-trash-alt mr-2"></i>
+                Eliminar Datos de Tabla
+            </h3>
+        </div>
+
+        <div class="p-6">
+            <form id="cleanDataForm" class="space-y-6">
+                <!-- Table Selection -->
+                <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>
+
+                <!-- Table Info Display -->
+                <div id="tableInfo" class="hidden bg-gray-50 p-4 rounded-lg border">
+                    <div class="flex items-center justify-between">
+                        <div>
+                            <h4 class="text-sm font-medium text-gray-900">Información de la Tabla</h4>
+                            <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>
+
+<script>
+    let tablesData = [];
+
+    // Get CSRF token from meta tag
+    function getCsrfToken() {
+        return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
+    }
+
+    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];
+    }
+
+    // Load tables on page load
+    document.addEventListener('DOMContentLoaded', function() {
+        loadTables();
+    });
+
+    async function loadTables() {
+        try {
+            const response = await fetch('/admin/api/get-tables', {
+                method: 'GET',
+                headers: {
+                    'X-CSRFToken': getCsrfToken()
+                }
+            });
+            
+            const data = await response.json();
+            
+            if (data.status === 'success') {
+                tablesData = data.tables;
+                populateTableSelect();
+            } else {
+                showNotification('Error al cargar las tablas', 'error');
+            }
+        } catch (error) {
+            console.error('Error:', error);
+            showNotification('Error al cargar las tablas', '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);
+        });
+    }
+
+    // Handle table selection change
+    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 += ` | Tamaño: ${formatSize(table.size)} | Esta tabla está vacía`;
+                }
+            }
+        } else {
+            tableInfo.classList.add('hidden');
+        }
+    });
+
+    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 {
+            showNotification('Eliminando datos...', 'info');
+            
+            const response = await fetch('/admin/api/delete-table-data', {
+                method: 'POST',
+                headers: {
+                    'Content-Type': 'application/json',
+                    'X-CSRFToken': getCsrfToken()
+                },
+                body: JSON.stringify({ table_name: tableName })
+            });
+            
+            const data = await response.json();
+            
+            if (data.status === 'success') {
+                showNotification(data.message, 'success');
+                // Reload tables after 1.5 seconds
+                setTimeout(() => {
+                    loadTables();
+                    // Reset form
+                    document.getElementById('tableSelect').value = '';
+                    document.getElementById('tableInfo').classList.add('hidden');
+                }, 1500);
+            } else {
+                showNotification(data.message || 'Error al eliminar los datos', 'error');
+            }
+        } catch (error) {
+            console.error('Error:', error);
+            showNotification('Error al eliminar los datos de la tabla', 'error');
+        }
+    }
+
+    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);
+    }
+</script>
+{% endblock %}