| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362 |
- {% 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 = 'importar'"
- :class="activeTab === 'importar'
- ? '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-file-import text-base"></i>
- {{ _("Importar Logs") }}
- </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' && health.extra.integrity_checked === false">
- <span>{{ _("La integridad se verifica manualmente desde el botón Verificar Integridad.") }}</span>
- </template>
- <template x-if="!health.extra.corruption && health.db_type === 'SQLITE' && health.extra.integrity_checked !== false">
- <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: IMPORTAR LOGS
- ════════════════════════════════════════════════════════ -->
- <div x-show="activeTab === 'importar'" x-data="logImportManager()" class="space-y-6">
- <div class="max-w-4xl">
- <div class="mb-8">
- <h3 class="text-2xl font-bold text-gray-800 mb-2">
- <i class="fas fa-file-import mr-3"></i>{{ _("Importar Logs de Squid") }}
- </h3>
- <p class="text-gray-600">
- {{ _("Carga uno o varios archivos access.log históricos para incorporarlos a la base de datos") }}.
- </p>
- </div>
- <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6">
- <div class="flex items-start">
- <i class="fas fa-info-circle text-blue-500 text-xl mr-3 mt-1"></i>
- <div class="text-sm text-blue-800">
- <p class="font-medium mb-1">{{ _("Importación automática por fecha") }}</p>
- <p>{{ _("La fecha se obtiene del timestamp de cada línea. Los registros se guardan en las tablas log_YYYYMMDD y sus usuarios en user_YYYYMMDD. Puedes importar un archivo con varios días.") }}</p>
- </div>
- </div>
- </div>
- <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
- <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-4">
- <h4 class="text-xl font-semibold text-white flex items-center">
- <i class="fas fa-upload mr-2"></i>{{ _("Seleccionar archivos") }}
- </h4>
- </div>
- <form @submit.prevent="submitImport()" class="p-6 space-y-6" enctype="multipart/form-data">
- <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
- <input id="logImportFile" x-ref="file" type="file" multiple
- accept=".log,.txt,text/plain"
- @change="handleFileSelection($event)" @click.stop
- class="hidden" />
- <div x-ref="dropZone"
- @click="if (!loading) $refs.file.click()"
- @keydown.enter.prevent="if (!loading) $refs.file.click()"
- @keydown.space.prevent="if (!loading) $refs.file.click()"
- @dragover.prevent="if (!loading) dragging = true"
- @dragleave.prevent="dragging = false"
- @drop.prevent="dragging = false; if (!loading) handleDrop($event)"
- :class="dragging ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-200' : 'border-gray-300 bg-gray-50 hover:border-blue-400 hover:bg-blue-50/40'"
- class="border-2 border-dashed rounded-xl px-6 py-10 text-center cursor-pointer transition-all focus:outline-none focus:ring-2 focus:ring-blue-500"
- role="button" tabindex="0" aria-label="{{ _('Zona para cargar archivos de logs') }}">
- <div class="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-blue-100 text-blue-600">
- <i class="fas fa-cloud-upload-alt text-2xl"></i>
- </div>
- <p class="text-base font-semibold text-gray-800">{{ _("Arrastra aquí tus archivos access.log") }}</p>
- <p class="mt-1 text-sm text-blue-600 font-medium">{{ _("o haz clic para seleccionarlos") }}</p>
- <p class="mt-3 text-xs text-gray-500">{{ _("Puedes seleccionar múltiples archivos a la vez.") }}</p>
- </div>
- <div x-show="files.length > 0" x-transition class="rounded-xl border border-gray-200 bg-white overflow-hidden" style="display:none;">
- <div class="flex items-center justify-between gap-3 bg-gray-50 border-b border-gray-200 px-4 py-3">
- <p class="text-sm font-semibold text-gray-700">
- <span x-text="files.length"></span> {{ _("archivos seleccionados") }}
- </p>
- <button type="button" @click="clearFiles()" :disabled="loading"
- class="text-xs font-medium text-red-600 hover:text-red-800 disabled:opacity-50">
- <i class="fas fa-trash-alt mr-1"></i>{{ _("Limpiar selección") }}
- </button>
- </div>
- <div class="max-h-56 overflow-y-auto divide-y divide-gray-100">
- <template x-for="file in files" :key="fileKey(file)">
- <div class="flex items-center gap-3 px-4 py-3">
- <div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-blue-100 text-blue-600">
- <i class="fas fa-file-alt"></i>
- </div>
- <div class="min-w-0 flex-1">
- <p class="truncate text-sm font-medium text-gray-800" x-text="file.name"></p>
- <p class="text-xs text-gray-500" x-text="formatBytes(file.size)"></p>
- </div>
- <button type="button" @click="removeFile(file)" :disabled="loading"
- :title="translations.removeFile"
- class="h-8 w-8 shrink-0 rounded-full text-gray-400 hover:bg-red-50 hover:text-red-600 disabled:opacity-50">
- <i class="fas fa-times"></i>
- </button>
- </div>
- </template>
- </div>
- </div>
- <div x-show="loading" x-transition class="rounded-xl border border-blue-100 bg-blue-50/70 p-5" style="display:none;">
- <div class="flex items-center justify-between gap-4 mb-2">
- <p class="text-sm font-semibold text-blue-900 truncate" x-text="currentFile ? translations.processingFile + ': ' + currentFile : translations.processing"></p>
- <span class="text-sm font-bold text-blue-700" x-text="progress + '%'" ></span>
- </div>
- <div class="h-3 w-full overflow-hidden rounded-full bg-blue-100" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="{{ _('Progreso de importación') }}">
- <div class="h-full rounded-full bg-gradient-to-r from-blue-500 to-indigo-600 transition-all duration-300" :style="`width: ${progress}%`"></div>
- </div>
- <div class="mt-3 flex items-center justify-between gap-3 text-xs text-blue-700">
- <span x-text="currentFileProgress < 100 ? translations.importing : translations.processing"></span>
- <span><span x-text="completedFiles"></span> / <span x-text="totalFiles"></span> {{ _("archivos completados") }}</span>
- </div>
- </div>
- <button type="submit" :disabled="loading || !files.length"
- class="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 px-6 py-2.5 rounded-lg shadow hover:shadow-lg transition-all disabled:opacity-60 disabled:cursor-not-allowed">
- <i :class="loading ? 'fas fa-spinner fa-spin' : 'fas fa-file-import'"></i>
- <span x-text="loading ? translations.importing : translations.import"></span>
- </button>
- </form>
- </div>
- <div x-show="message" x-transition
- :class="messageType === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : (messageType === 'warning' ? 'bg-amber-50 border-amber-200 text-amber-800' : 'bg-red-50 border-red-200 text-red-800')"
- class="border rounded-lg px-4 py-3 mt-6" style="display:none;">
- <p class="text-sm font-medium" x-text="message"></p>
- </div>
- <template x-if="summary && !loading">
- <div class="bg-white rounded-xl shadow-sm border border-gray-100 mt-6 overflow-hidden">
- <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
- <h4 class="text-base font-semibold text-gray-800">
- <i class="fas fa-chart-bar text-blue-500 mr-2"></i>{{ _("Resultado de la importación") }}
- </h4>
- <span class="text-sm text-gray-500" x-text="summary.parsed_lines.toLocaleString() + ' {{ _('líneas válidas') }}'"></span>
- </div>
- <div class="p-6 grid grid-cols-2 md:grid-cols-5 gap-4">
- <div class="bg-emerald-50 rounded-lg p-4">
- <p class="text-xs text-emerald-600 uppercase font-medium">{{ _("Archivos importados") }}</p>
- <p class="text-xl font-bold text-emerald-800" x-text="summary.files_processed.toLocaleString()"></p>
- </div>
- <div class="bg-blue-50 rounded-lg p-4">
- <p class="text-xs text-blue-600 uppercase font-medium">{{ _("Logs") }}</p>
- <p class="text-xl font-bold text-blue-800" x-text="summary.inserted_logs.toLocaleString()"></p>
- </div>
- <div class="bg-indigo-50 rounded-lg p-4">
- <p class="text-xs text-indigo-600 uppercase font-medium">{{ _("Usuarios") }}</p>
- <p class="text-xl font-bold text-indigo-800" x-text="summary.inserted_users.toLocaleString()"></p>
- </div>
- <div class="bg-amber-50 rounded-lg p-4">
- <p class="text-xs text-amber-600 uppercase font-medium">{{ _("Denegados") }}</p>
- <p class="text-xl font-bold text-amber-800" x-text="summary.inserted_denied.toLocaleString()"></p>
- </div>
- <div class="bg-gray-50 rounded-lg p-4">
- <p class="text-xs text-gray-600 uppercase font-medium">{{ _("Omitidas") }}</p>
- <p class="text-xl font-bold text-gray-800" x-text="summary.skipped_lines.toLocaleString()"></p>
- </div>
- </div>
- <div x-show="summary.files_failed > 0" class="px-6 pb-6" style="display:none;">
- <p class="text-sm font-semibold text-red-700 mb-2">{{ _("Archivos con error") }}</p>
- <div class="space-y-2">
- <template x-for="failure in failures" :key="failure.name">
- <div class="flex items-start gap-2 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-800">
- <i class="fas fa-exclamation-circle mt-0.5"></i>
- <span><strong x-text="failure.name"></strong>: <span x-text="failure.message"></span></span>
- </div>
- </template>
- </div>
- </div>
- <div class="px-6 pb-6" x-show="summary.dates && summary.dates.length">
- <p class="text-sm font-semibold text-gray-700 mb-2">{{ _("Tablas actualizadas") }}</p>
- <div class="flex flex-wrap gap-2">
- <template x-for="item in summary.dates" :key="item.date">
- <span class="inline-flex items-center gap-2 bg-gray-100 text-gray-700 text-xs font-mono px-3 py-1.5 rounded-full">
- <span x-text="item.log_table"></span>
- <span class="text-gray-500" x-text="'(' + item.inserted_logs.toLocaleString() + ')' "></span>
- </span>
- </template>
- </div>
- </div>
- </div>
- </template>
- </div>
- </div><!-- end importar 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';
- if (this.health?.extra?.integrity_checked === false) return 'warning';
- 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(); }
- };
- }
- // ──────────────────────────────────────────────────────────
- // Log importer
- // ──────────────────────────────────────────────────────────
- function logImportManager() {
- return {
- loading: false,
- dragging: false,
- files: [],
- progress: 0,
- currentFile: '',
- currentFileProgress: 0,
- completedFiles: 0,
- totalFiles: 0,
- failures: [],
- message: '',
- messageType: 'success',
- summary: null,
- translations: {
- importing: '{{ _('Importando...') }}',
- import: '{{ _('Importar archivos') }}',
- processing: '{{ _('Procesando...') }}',
- processingFile: '{{ _('Procesando archivo') }}',
- removeFile: '{{ _('Quitar archivo') }}',
- connectionError: '{{ _('Error de conexión') }}',
- fileImportError: '{{ _('No se pudo importar este archivo') }}',
- noFiles: '{{ _('Selecciona al menos un archivo de logs') }}',
- allFailed: '{{ _('No se pudo importar ningún archivo') }}',
- partialSuccess: '{{ _('Algunos archivos se importaron correctamente y otros fallaron') }}',
- completed: '{{ _('Archivos importados correctamente') }}'
- },
- fileKey(file) {
- return [file.name, file.size, file.lastModified].join(':');
- },
- formatBytes(bytes) {
- if (!bytes) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
- const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
- return `${parseFloat((bytes / Math.pow(1024, index)).toFixed(2))} ${units[index]}`;
- },
- addFiles(fileList) {
- if (this.loading) return;
- const existing = new Set(this.files.map(file => this.fileKey(file)));
- Array.from(fileList || []).forEach(file => {
- const key = this.fileKey(file);
- if (!existing.has(key)) {
- this.files.push(file);
- existing.add(key);
- }
- });
- if (this.files.length) {
- this.message = '';
- this.summary = null;
- }
- },
- handleFileSelection(event) {
- this.addFiles(event.target.files);
- event.target.value = '';
- },
- handleDrop(event) {
- this.addFiles(event.dataTransfer.files);
- },
- removeFile(file) {
- if (this.loading) return;
- const key = this.fileKey(file);
- this.files = this.files.filter(item => this.fileKey(item) !== key);
- },
- clearFiles() {
- if (this.loading) return;
- this.files = [];
- this.message = '';
- this.summary = null;
- },
- emptySummary() {
- return {
- processed_lines: 0,
- parsed_lines: 0,
- skipped_lines: 0,
- inserted_logs: 0,
- inserted_users: 0,
- inserted_denied: 0,
- dates: [],
- files_processed: 0,
- files_failed: 0
- };
- },
- mergeSummary(target, source) {
- const counters = [
- 'processed_lines', 'parsed_lines', 'skipped_lines',
- 'inserted_logs', 'inserted_users', 'inserted_denied'
- ];
- counters.forEach(key => {
- target[key] += Number((source && source[key]) || 0);
- });
- const dates = new Map((target.dates || []).map(item => [item.date, {...item}]));
- (source && source.dates || []).forEach(item => {
- const current = dates.get(item.date);
- if (!current) {
- dates.set(item.date, {...item});
- return;
- }
- ['inserted_logs', 'inserted_users', 'inserted_denied'].forEach(key => {
- current[key] = Number(current[key] || 0) + Number(item[key] || 0);
- });
- });
- target.dates = Array.from(dates.values()).sort((a, b) => a.date.localeCompare(b.date));
- },
- updateProgress(index, ratio) {
- if (!this.totalFiles) return;
- this.currentFileProgress = Math.round(Math.max(0, Math.min(1, ratio)) * 100);
- this.progress = Math.min(100, Math.round(((index + ratio) / this.totalFiles) * 100));
- },
- uploadFile(file, index) {
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- const formData = new FormData();
- const csrfToken = document.querySelector('meta[name="csrf-token"]');
- formData.append('file', file, file.name);
- xhr.open('POST', '/admin/api/import-logs');
- if (csrfToken) xhr.setRequestHeader('X-CSRFToken', csrfToken.content);
- xhr.upload.onprogress = event => {
- if (event.lengthComputable) this.updateProgress(index, event.loaded / event.total);
- };
- xhr.onload = () => {
- let data = {};
- try {
- data = JSON.parse(xhr.responseText || '{}');
- } catch (error) {
- reject(new Error(this.translations.fileImportError));
- return;
- }
- if (xhr.status < 200 || xhr.status >= 300 || data.status !== 'success') {
- reject(new Error(data.message || this.translations.fileImportError));
- return;
- }
- resolve(data.summary || this.emptySummary());
- };
- xhr.onerror = () => reject(new Error(this.translations.connectionError));
- xhr.onabort = () => reject(new Error(this.translations.connectionError));
- xhr.send(formData);
- });
- },
- async submitImport() {
- if (!this.files.length) {
- this.messageType = 'error';
- this.message = this.translations.noFiles;
- return;
- }
- const filesToImport = [...this.files];
- this.loading = true;
- this.message = '';
- this.summary = this.emptySummary();
- this.failures = [];
- this.progress = 0;
- this.currentFile = '';
- this.currentFileProgress = 0;
- this.completedFiles = 0;
- this.totalFiles = filesToImport.length;
- let importedFiles = 0;
- for (let index = 0; index < filesToImport.length; index += 1) {
- const file = filesToImport[index];
- this.currentFile = file.name;
- this.updateProgress(index, 0);
- try {
- const summary = await this.uploadFile(file, index);
- this.mergeSummary(this.summary, summary);
- importedFiles += 1;
- } catch (error) {
- this.failures.push({
- name: file.name,
- message: error.message || this.translations.fileImportError
- });
- }
- this.completedFiles = index + 1;
- this.updateProgress(index, 1);
- }
- this.summary.files_processed = importedFiles;
- this.summary.files_failed = this.failures.length;
- if (!this.failures.length) {
- this.messageType = 'success';
- this.message = this.translations.completed;
- } else if (importedFiles) {
- this.messageType = 'warning';
- this.message = this.translations.partialSuccess;
- } else {
- this.messageType = 'error';
- this.message = this.translations.allFailed;
- }
- this.files = [];
- this.currentFile = '';
- this.loading = false;
- }
- };
- }
- // ──────────────────────────────────────────────────────────
- // Clean Data (vanilla JS)
- // ──────────────────────────────────────────────────────────
- let tablesData = [];
- const tableLoadErrorMessage = {{ _("No se pudieron cargar las tablas")|tojson }};
- 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() {
- const select = document.getElementById('tableSelect');
- 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 (!response.ok || data.status !== 'success') {
- throw new Error(data.message || `Error HTTP ${response.status}`);
- }
- tablesData = Array.isArray(data.tables) ? data.tables : [];
- populateTableSelect();
- } catch (error) {
- console.error('Error loading tables:', error);
- tablesData = [];
- select.innerHTML = `<option value="">${tableLoadErrorMessage}</option>`;
- document.getElementById('tableInfo').classList.add('hidden');
- document.getElementById('actionButtons').classList.add('hidden');
- }
- }
- 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 %}
|