| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973 |
- {% 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">
- <!-- Corruption takes priority over fragmentation message -->
- <template x-if="health.extra.corruption">
- <span>
- {{ _("La base de datos tiene páginas dañadas.") }}
- <span x-show="health.extra.corruption_detail"
- class="font-mono bg-red-100 px-1.5 py-0.5 rounded text-xs ml-1"
- x-text="health.extra.corruption_detail"></span>
- {{ _("Haz un respaldo y ejecuta") }} <strong>{{ _("VACUUM") }}</strong> {{ _("o restaura desde una copia sana.") }}
- </span>
- </template>
- <template x-if="!health.extra.corruption && health.db_type === 'SQLITE'">
- <span>
- {{ _("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>
- </template>
- <span x-show="!health.extra.corruption && 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>
- <template x-if="health.extra.corruption && health.extra.corruption_detail">
- <div class="col-span-3">
- <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Detalle de Corrupción") }}</p>
- <p class="text-sm font-mono bg-red-50 border border-red-200 rounded px-3 py-2 text-red-700 break-all"
- x-text="health.extra.corruption_detail"></p>
- </div>
- </template>
- </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 ? translations.verifying : translations.verifyIntegrity"></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 ? translations.integrityOk : translations.integrityError"></p>
- <p class="text-sm mt-0.5" x-show="integrityResult.error_count > 0"
- x-text="integrityResult.error_count + ' ' + translations.integrityErrorsCount"></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 ? translations.guardando : translations.salvaManual"></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"></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"></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") }}</option>
- <option value="mysql">{{ _("MySQL / MariaDB") }}</option>
- <option value="postgresql">{{ _("PostgreSQL") }}</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 === 'mysql'">
- <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
- <i class="fas fa-exclamation-triangle"></i>
- {{ _("Requiere") }} <code class="font-mono">mysqldump</code> {{ _("instalado en el servidor.") }}
- </p>
- </template>
- <template x-if="config.db_type === 'postgresql'">
- <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
- <i class="fas fa-exclamation-triangle"></i>
- {{ _("Requiere") }} <code class="font-mono">pg_dump</code> {{ _("instalado en el servidor.") }}
- </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' ? translations.freqDailyWeekly : translations.freqDailyMonthly"></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 ? translations.guardando : translations.guardarConfiguracion"></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,
- translations: {
- verifying: '{{ _('Verificando...') }}',
- verifyIntegrity: '{{ _('Verificar Integridad') }}',
- integrityOk: '{{ _('Sin errores detectados — la base de datos está íntegra.') }}',
- integrityError: '{{ _('Se encontraron errores de integridad.') }}',
- integrityErrorsCount: '{{ _('error(es) detectado(s)') }}'
- },
- 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() {
- if (this.health?.extra?.corruption) return 'critical';
- const frag = this.health?.extra?.fragmentation_pct ?? 0;
- if (frag > 30) return 'critical';
- if (frag > 10) return 'warning';
- return 'good';
- },
- get healthLabel() {
- if (this.health?.extra?.corruption) return '{{ _('Corrupción detectada') }}';
- return { good: '{{ _('Saludable') }}', warning: '{{ _('Advertencia') }}', critical: '{{ _('Crítico') }}' }[this.healthStatus];
- }
- };
- }
- // ──────────────────────────────────────────────────────────
- // Backup Manager (Alpine component)
- // ──────────────────────────────────────────────────────────
- function backupManager() {
- return {
- translations: {
- sinSalvas: '{{ _('Sin salvas') }}',
- noBackups: '{{ _('0 B') }}',
- guardando: '{{ _('Guardando...') }}',
- salvaManual: '{{ _('Salva Manual') }}',
- guardarConfiguracion: '{{ _('Guardar Configuración') }}',
- freqDailyWeekly: '{{ _('Se ejecuta diariamente, conservando máx. 3 salvas por semana') }}',
- freqDailyMonthly: '{{ _('Se ejecuta diariamente, conservando máx. 3 salvas por mes') }}',
- },
- 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 this.translations.sinSalvas;
- 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 this.translations.noBackups;
- 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() {
- // all engines now supported
- },
- 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) {
- const confirmMessage = '{{ _('¿Eliminar la salva "%(filename)s"?', filename='%(filename)s') }}'.replace('%(filename)s', filename);
- if (!confirm(confirmMessage)) 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 %}
|