database.html 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. {% extends "admin/base.html" %}
  2. {% block title %}{{ _("Base de Datos - Administrador Squid Proxy") }}{% endblock %}
  3. {% block content %}
  4. <div x-data="{ activeTab: 'resumen' }">
  5. <!-- Page Header -->
  6. <div class="flex items-center justify-between mb-6">
  7. <div>
  8. <h2 class="text-2xl font-bold text-gray-800">{{ _("Base de Datos") }}</h2>
  9. <p class="text-sm text-gray-500 mt-1">{{ _("Monitor de salud, copias de seguridad y gestión de datos") }}</p>
  10. </div>
  11. </div>
  12. <!-- Tab Navigation -->
  13. <div class="bg-white rounded-xl shadow-sm border border-gray-100 mb-6 overflow-x-auto">
  14. <nav class="flex border-b border-gray-200 min-w-max">
  15. <button @click="activeTab = 'resumen'"
  16. :class="activeTab === 'resumen'
  17. ? 'border-blue-600 text-blue-600 bg-blue-50/40'
  18. : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
  19. 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">
  20. <i class="fas fa-heartbeat text-base"></i>
  21. {{ _("Resumen DB") }}
  22. </button>
  23. <button @click="activeTab = 'salvas'"
  24. :class="activeTab === 'salvas'
  25. ? 'border-blue-600 text-blue-600 bg-blue-50/40'
  26. : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
  27. 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">
  28. <i class="fas fa-save text-base"></i>
  29. {{ _("Salvas de BD") }}
  30. </button>
  31. <button @click="activeTab = 'limpiar'"
  32. :class="activeTab === 'limpiar'
  33. ? 'border-blue-600 text-blue-600 bg-blue-50/40'
  34. : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
  35. 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">
  36. <i class="fas fa-trash-alt text-base"></i>
  37. {{ _("Limpiar Datos") }}
  38. </button>
  39. </nav>
  40. </div>
  41. <!-- ═══════════════════════════════════════════════════════
  42. TAB: RESUMEN DB
  43. ════════════════════════════════════════════════════════ -->
  44. <div x-show="activeTab === 'resumen'" x-data="dbHealthPanel()" class="space-y-6">
  45. <!-- Loading -->
  46. <div x-show="loading" class="flex items-center justify-center py-24">
  47. <div class="text-center">
  48. <i class="fas fa-spinner fa-spin text-blue-500 text-4xl mb-4"></i>
  49. <p class="text-sm text-gray-500 font-medium">{{ _("Cargando información de la base de datos...") }}</p>
  50. </div>
  51. </div>
  52. <!-- Error -->
  53. <div x-show="!loading && !!error"
  54. class="bg-red-50 border border-red-200 rounded-xl p-5 flex items-center gap-4">
  55. <i class="fas fa-exclamation-circle text-red-500 text-2xl flex-shrink-0"></i>
  56. <div class="flex-1">
  57. <p class="font-semibold text-red-800">{{ _("Error al cargar los datos") }}</p>
  58. <p class="text-sm text-red-600 mt-0.5" x-text="error"></p>
  59. </div>
  60. <button @click="loadHealth()"
  61. 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">
  62. <i class="fas fa-redo mr-1"></i>{{ _("Reintentar") }}
  63. </button>
  64. </div>
  65. <!-- ── Health status banner ── -->
  66. <template x-if="!loading && health">
  67. <div :class="{
  68. 'bg-emerald-50 border-emerald-200': healthStatus === 'good',
  69. 'bg-amber-50 border-amber-200': healthStatus === 'warning',
  70. 'bg-red-50 border-red-200': healthStatus === 'critical'
  71. }"
  72. class="border rounded-xl p-4 flex items-center gap-4">
  73. <div :class="{
  74. 'bg-emerald-100 text-emerald-500': healthStatus === 'good',
  75. 'bg-amber-100 text-amber-500': healthStatus === 'warning',
  76. 'bg-red-100 text-red-500': healthStatus === 'critical'
  77. }"
  78. class="w-14 h-14 rounded-full flex items-center justify-center flex-shrink-0">
  79. <i :class="{
  80. 'fas fa-check-circle text-3xl': healthStatus === 'good',
  81. 'fas fa-exclamation-circle text-3xl': healthStatus === 'warning',
  82. 'fas fa-times-circle text-3xl': healthStatus === 'critical'
  83. }"></i>
  84. </div>
  85. <div class="flex-1 min-w-0">
  86. <p :class="{
  87. 'text-emerald-800': healthStatus === 'good',
  88. 'text-amber-800': healthStatus === 'warning',
  89. 'text-red-800': healthStatus === 'critical'
  90. }"
  91. class="font-bold text-lg"
  92. x-text="'{{ _('Salud de la BD:') }} ' + healthLabel"></p>
  93. <p :class="{
  94. 'text-emerald-700': healthStatus === 'good',
  95. 'text-amber-700': healthStatus === 'warning',
  96. 'text-red-700': healthStatus === 'critical'
  97. }"
  98. class="text-sm mt-0.5">
  99. <!-- Corruption takes priority over fragmentation message -->
  100. <template x-if="health.extra.corruption">
  101. <span>
  102. {{ _("La base de datos tiene páginas dañadas.") }}
  103. <span x-show="health.extra.corruption_detail"
  104. class="font-mono bg-red-100 px-1.5 py-0.5 rounded text-xs ml-1"
  105. x-text="health.extra.corruption_detail"></span>
  106. {{ _("Haz un respaldo y ejecuta") }} <strong>{{ _("VACUUM") }}</strong> {{ _("o restaura desde una copia sana.") }}
  107. </span>
  108. </template>
  109. <template x-if="!health.extra.corruption && health.db_type === 'SQLITE'">
  110. <span>
  111. {{ _("Fragmentación:") }}
  112. <strong x-text="health.extra.fragmentation_pct + '%'"></strong>
  113. <span x-show="healthStatus === 'good'"> {{ _("— dentro del rango normal") }}</span>
  114. <span x-show="healthStatus === 'warning'"> {{ _("— considera ejecutar VACUUM") }}</span>
  115. <span x-show="healthStatus === 'critical'"> {{ _("— ejecuta VACUUM urgentemente") }}</span>
  116. </span>
  117. </template>
  118. <span x-show="!health.extra.corruption && health.db_type !== 'SQLITE'">
  119. {{ _("Motor") }} <strong x-text="health.db_type"></strong> {{ _("operando con normalidad") }}
  120. </span>
  121. </p>
  122. </div>
  123. <button @click="loadHealth()"
  124. class="text-sm font-medium opacity-60 hover:opacity-100 transition-opacity flex-shrink-0"
  125. :class="{
  126. 'text-emerald-800': healthStatus === 'good',
  127. 'text-amber-800': healthStatus === 'warning',
  128. 'text-red-800': healthStatus === 'critical'
  129. }">
  130. <i class="fas fa-sync-alt mr-1"></i>{{ _("Actualizar") }}
  131. </button>
  132. </div>
  133. </template>
  134. <!-- ── 4 stat cards ── -->
  135. <template x-if="!loading && health">
  136. <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
  137. <!-- DB Engine -->
  138. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  139. <div class="w-12 h-12 bg-indigo-100 rounded-xl flex items-center justify-center flex-shrink-0">
  140. <i class="fas fa-database text-indigo-600 text-xl"></i>
  141. </div>
  142. <div class="min-w-0">
  143. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Motor") }}</p>
  144. <p class="text-xl font-bold text-gray-800 truncate" x-text="health.db_type"></p>
  145. </div>
  146. </div>
  147. <!-- Total Size -->
  148. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  149. <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center flex-shrink-0">
  150. <i class="fas fa-hdd text-blue-600 text-xl"></i>
  151. </div>
  152. <div class="min-w-0">
  153. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Tamaño Total") }}</p>
  154. <p class="text-xl font-bold text-gray-800" x-text="formatBytes(health.total_size_bytes)"></p>
  155. </div>
  156. </div>
  157. <!-- Tables -->
  158. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  159. <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center flex-shrink-0">
  160. <i class="fas fa-table text-purple-600 text-xl"></i>
  161. </div>
  162. <div class="min-w-0">
  163. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Tablas") }}</p>
  164. <p class="text-xl font-bold text-gray-800" x-text="health.table_count.toLocaleString()"></p>
  165. </div>
  166. </div>
  167. <!-- Total Records -->
  168. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  169. <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center flex-shrink-0">
  170. <i class="fas fa-list-ol text-emerald-600 text-xl"></i>
  171. </div>
  172. <div class="min-w-0">
  173. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Registros Totales") }}</p>
  174. <p class="text-xl font-bold text-gray-800" x-text="health.total_rows.toLocaleString()"></p>
  175. </div>
  176. </div>
  177. </div>
  178. </template>
  179. <!-- ── SQLite extra details ── -->
  180. <template x-if="!loading && health && health.db_type === 'SQLITE'">
  181. <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  182. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  183. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  184. <i class="fas fa-info-circle text-blue-500"></i>
  185. {{ _("Detalles SQLite") }}
  186. </h3>
  187. </div>
  188. <div class="p-6 grid grid-cols-2 md:grid-cols-3 gap-x-8 gap-y-5">
  189. <div>
  190. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Tamaño de Página") }}</p>
  191. <p class="text-lg font-semibold text-gray-800"
  192. x-text="(health.extra.page_size / 1024).toFixed(1) + ' KB'"></p>
  193. </div>
  194. <div>
  195. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Páginas Totales") }}</p>
  196. <p class="text-lg font-semibold text-gray-800"
  197. x-text="health.extra.page_count.toLocaleString()"></p>
  198. </div>
  199. <div>
  200. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Páginas Libres") }}</p>
  201. <p class="text-lg font-semibold text-gray-800"
  202. x-text="health.extra.freelist_count.toLocaleString()"></p>
  203. </div>
  204. <div>
  205. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Modo Journal") }}</p>
  206. <p class="text-lg font-semibold text-gray-800 uppercase"
  207. x-text="health.extra.journal_mode"></p>
  208. </div>
  209. <div>
  210. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Auto-Vacuum") }}</p>
  211. <p class="text-lg font-semibold text-gray-800"
  212. x-text="health.extra.auto_vacuum"></p>
  213. </div>
  214. <div>
  215. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Fragmentación") }}</p>
  216. <div class="flex items-center gap-2">
  217. <p class="text-lg font-semibold text-gray-800"
  218. x-text="health.extra.fragmentation_pct + '%'"></p>
  219. <span :class="{
  220. 'bg-emerald-100 text-emerald-700': healthStatus === 'good',
  221. 'bg-amber-100 text-amber-700': healthStatus === 'warning',
  222. 'bg-red-100 text-red-700': healthStatus === 'critical'
  223. }"
  224. class="text-xs font-semibold px-2 py-0.5 rounded-full"
  225. x-text="healthLabel"></span>
  226. </div>
  227. </div>
  228. <template x-if="health.extra.corruption && health.extra.corruption_detail">
  229. <div class="col-span-3">
  230. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Detalle de Corrupción") }}</p>
  231. <p class="text-sm font-mono bg-red-50 border border-red-200 rounded px-3 py-2 text-red-700 break-all"
  232. x-text="health.extra.corruption_detail"></p>
  233. </div>
  234. </template>
  235. </div>
  236. </div>
  237. </template>
  238. <!-- ── MySQL / PostgreSQL version ── -->
  239. <template x-if="!loading && health && health.db_type !== 'SQLITE' && health.extra && health.extra.version">
  240. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  241. <div class="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center flex-shrink-0">
  242. <i class="fas fa-code-branch text-gray-500 text-xl"></i>
  243. </div>
  244. <div>
  245. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-0.5">{{ _("Versión del Motor") }}</p>
  246. <p class="text-base font-semibold text-gray-800" x-text="health.extra.version"></p>
  247. </div>
  248. </div>
  249. </template>
  250. <!-- ── Integrity Check ── -->
  251. <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  252. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  253. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  254. <i class="fas fa-shield-alt text-blue-500"></i>
  255. {{ _("Verificación de Integridad") }}
  256. </h3>
  257. </div>
  258. <div class="p-6 space-y-4">
  259. <p class="text-sm text-gray-600">
  260. {{ _("Verifica la integridad estructural de la base de datos en busca de posibles errores o corrupción.") }}
  261. <span class="text-amber-600 font-medium">
  262. {{ _("Esta operación puede tardar varios minutos en bases de datos grandes.") }}
  263. </span>
  264. </p>
  265. <button @click="checkIntegrity()" :disabled="integrityLoading"
  266. 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">
  267. <i :class="integrityLoading ? 'fas fa-spinner fa-spin' : 'fas fa-search'"></i>
  268. <span x-text="integrityLoading ? translations.verifying : translations.verifyIntegrity"></span>
  269. </button>
  270. <template x-if="integrityResult">
  271. <div :class="integrityResult.ok
  272. ? 'bg-emerald-50 border-emerald-200 text-emerald-800'
  273. : 'bg-red-50 border-red-200 text-red-800'"
  274. class="border rounded-xl p-4 flex items-start gap-3">
  275. <i :class="integrityResult.ok
  276. ? 'fas fa-check-circle text-emerald-500'
  277. : 'fas fa-times-circle text-red-500'"
  278. class="text-xl flex-shrink-0 mt-0.5"></i>
  279. <div class="flex-1 min-w-0">
  280. <p class="font-semibold"
  281. x-text="integrityResult.ok ? translations.integrityOk : translations.integrityError"></p>
  282. <p class="text-sm mt-0.5" x-show="integrityResult.error_count > 0"
  283. x-text="integrityResult.error_count + ' ' + translations.integrityErrorsCount"></p>
  284. <ul x-show="integrityResult.errors && integrityResult.errors.length > 0" class="mt-2 space-y-1">
  285. <template x-for="err in integrityResult.errors" :key="err">
  286. <li class="text-sm font-mono bg-white/60 border border-current/10 rounded px-3 py-1"
  287. x-text="err"></li>
  288. </template>
  289. </ul>
  290. </div>
  291. </div>
  292. </template>
  293. </div>
  294. </div>
  295. </div><!-- end resumen tab -->
  296. <!-- ═══════════════════════════════════════════════════════
  297. TAB: SALVAS DE BD
  298. ════════════════════════════════════════════════════════ -->
  299. <div x-show="activeTab === 'salvas'" x-data="backupManager()" class="space-y-6">
  300. <!-- Page sub-header -->
  301. <div class="flex items-center justify-between">
  302. <div>
  303. <h3 class="text-xl font-bold text-gray-800">{{ _("Salvas de Base de Datos") }}</h3>
  304. <p class="text-sm text-gray-500 mt-1">{{ _("Configura y gestiona las copias de seguridad automáticas") }}</p>
  305. </div>
  306. <button @click="triggerManualBackup()" :disabled="loadingManual"
  307. 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">
  308. <i :class="loadingManual ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
  309. <span x-text="loadingManual ? translations.guardando : translations.salvaManual"></span>
  310. </button>
  311. </div>
  312. <!-- Status Banner -->
  313. <div x-show="statusMsg" x-transition
  314. :class="statusType === 'success' ? 'bg-emerald-50 border border-emerald-200 text-emerald-800' : 'bg-red-50 border border-red-200 text-red-800'"
  315. class="flex items-center gap-3 px-4 py-3 rounded-lg" style="display:none;">
  316. <i :class="statusType === 'success' ? 'fas fa-check-circle text-emerald-500' : 'fas fa-times-circle text-red-500'"></i>
  317. <span x-text="statusMsg" class="text-sm font-medium"></span>
  318. <button @click="statusMsg = ''" class="ml-auto text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
  319. </div>
  320. <!-- Stats Cards -->
  321. <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
  322. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  323. <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
  324. <i class="fas fa-database text-blue-600 text-xl"></i>
  325. </div>
  326. <div>
  327. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Total Salvas") }}</p>
  328. <p class="text-2xl font-bold text-gray-800" x-text="backups.length">--</p>
  329. </div>
  330. </div>
  331. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  332. <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center">
  333. <i class="fas fa-clock text-emerald-600 text-xl"></i>
  334. </div>
  335. <div>
  336. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Última Salva") }}</p>
  337. <p class="text-sm font-semibold text-gray-800" x-text="lastBackupDate"></p>
  338. </div>
  339. </div>
  340. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  341. <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
  342. <i class="fas fa-hdd text-purple-600 text-xl"></i>
  343. </div>
  344. <div>
  345. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Espacio Total") }}</p>
  346. <p class="text-sm font-semibold text-gray-800" x-text="totalSize"></p>
  347. </div>
  348. </div>
  349. </div>
  350. <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
  351. <!-- Configuration Panel -->
  352. <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  353. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  354. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  355. <i class="fas fa-sliders-h text-blue-500"></i>
  356. {{ _("Configuración de Salvas") }}
  357. </h3>
  358. </div>
  359. <form @submit.prevent="saveConfig()" class="p-6 space-y-5">
  360. <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
  361. <!-- DB Engine -->
  362. <div>
  363. <label class="block text-sm font-medium text-gray-700 mb-2">
  364. <i class="fas fa-server text-gray-400 mr-1"></i> {{ _("Motor de Base de Datos") }}
  365. </label>
  366. <div class="relative">
  367. <select x-model="config.db_type" @change="onDbTypeChange()"
  368. 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">
  369. <option value="sqlite">{{ _("SQLite") }}</option>
  370. <option value="mysql">{{ _("MySQL / MariaDB") }}</option>
  371. <option value="postgresql">{{ _("PostgreSQL") }}</option>
  372. </select>
  373. <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
  374. <i class="fas fa-chevron-down text-xs"></i>
  375. </div>
  376. </div>
  377. <template x-if="config.db_type === 'mysql'">
  378. <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
  379. <i class="fas fa-exclamation-triangle"></i>
  380. {{ _("Requiere") }} <code class="font-mono">mysqldump</code> {{ _("instalado en el servidor.") }}
  381. </p>
  382. </template>
  383. <template x-if="config.db_type === 'postgresql'">
  384. <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
  385. <i class="fas fa-exclamation-triangle"></i>
  386. {{ _("Requiere") }} <code class="font-mono">pg_dump</code> {{ _("instalado en el servidor.") }}
  387. </p>
  388. </template>
  389. </div>
  390. <!-- Frequency -->
  391. <div>
  392. <label class="block text-sm font-medium text-gray-700 mb-2">
  393. <i class="fas fa-calendar-alt text-gray-400 mr-1"></i> {{ _("Frecuencia") }}
  394. </label>
  395. <div class="relative">
  396. <select x-model="config.frequency"
  397. 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">
  398. <option value="daily_weekly">{{ _("Diaria — máx. 3 por semana") }}</option>
  399. <option value="daily_monthly">{{ _("Diaria — máx. 3 por mes") }}</option>
  400. </select>
  401. <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
  402. <i class="fas fa-chevron-down text-xs"></i>
  403. </div>
  404. </div>
  405. <p class="mt-1.5 text-xs text-gray-500 flex items-center gap-1">
  406. <i class="fas fa-info-circle"></i>
  407. <span x-text="config.frequency === 'daily_weekly' ? translations.freqDailyWeekly : translations.freqDailyMonthly"></span>
  408. </p>
  409. </div>
  410. <!-- Retention -->
  411. <div>
  412. <div class="flex items-center justify-between mb-2">
  413. <label class="block text-sm font-medium text-gray-700">
  414. <i class="fas fa-archive text-gray-400 mr-1"></i> {{ _("Retención máxima") }}
  415. </label>
  416. <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">
  417. <i class="fas fa-lock text-xs"></i> {{ _("Fijo: 3 salvas") }}
  418. </span>
  419. </div>
  420. <div class="flex items-center gap-3 bg-gray-50 border border-gray-200 rounded-lg px-4 py-3">
  421. <div class="flex gap-1.5">
  422. <template x-for="i in [1,2,3]" :key="i">
  423. <div class="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold bg-blue-500 text-white shadow-sm">
  424. <span x-text="i"></span>
  425. </div>
  426. </template>
  427. </div>
  428. <p class="text-xs text-gray-600">{{ _("Se mantienen las 3 salvas más recientes. Las más antiguas se eliminan automáticamente.") }}</p>
  429. </div>
  430. </div>
  431. <!-- Backup Directory -->
  432. <div>
  433. <label class="block text-sm font-medium text-gray-700 mb-2">
  434. <i class="fas fa-folder text-gray-400 mr-1"></i> {{ _("Directorio de Salvas") }}
  435. </label>
  436. <input type="text" x-model="config.backup_dir"
  437. 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"
  438. placeholder="/opt/SquidStats/backups" />
  439. <p class="mt-1.5 text-xs text-gray-500">{{ _("Ruta absoluta donde se guardarán las salvas") }}</p>
  440. </div>
  441. <!-- Enabled Toggle -->
  442. <div class="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3 border border-gray-200">
  443. <div>
  444. <p class="text-sm font-medium text-gray-700">{{ _("Salvas automáticas") }}</p>
  445. <p class="text-xs text-gray-500 mt-0.5">{{ _("Habilitar programación automática") }}</p>
  446. </div>
  447. <button type="button" @click="config.enabled = !config.enabled"
  448. :class="config.enabled ? 'bg-blue-600' : 'bg-gray-300'"
  449. 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">
  450. <span :class="config.enabled ? 'translate-x-5' : 'translate-x-0'"
  451. 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>
  452. </button>
  453. </div>
  454. <!-- Submit -->
  455. <button type="submit" :disabled="loadingSave"
  456. 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">
  457. <i :class="loadingSave ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
  458. <span x-text="loadingSave ? translations.guardando : translations.guardarConfiguracion"></span>
  459. </button>
  460. </form>
  461. </div>
  462. <!-- Backups List -->
  463. <div class="lg:col-span-3 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden flex flex-col">
  464. <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">
  465. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  466. <i class="fas fa-history text-blue-500"></i>
  467. {{ _("Historial de Salvas") }}
  468. </h3>
  469. <button @click="loadBackups()" class="text-xs text-blue-600 hover:text-blue-800 font-medium flex items-center gap-1 transition-colors">
  470. <i class="fas fa-sync-alt" :class="loadingList ? 'animate-spin' : ''"></i> {{ _("Actualizar") }}
  471. </button>
  472. </div>
  473. <!-- Loading -->
  474. <div x-show="loadingList" class="flex-1 flex items-center justify-center py-16">
  475. <div class="text-center">
  476. <i class="fas fa-spinner fa-spin text-blue-500 text-3xl mb-3"></i>
  477. <p class="text-sm text-gray-500">{{ _("Cargando salvas...") }}</p>
  478. </div>
  479. </div>
  480. <!-- Empty -->
  481. <div x-show="!loadingList && backups.length === 0" class="flex-1 flex items-center justify-center py-16">
  482. <div class="text-center px-6">
  483. <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
  484. <i class="fas fa-box-open text-gray-400 text-2xl"></i>
  485. </div>
  486. <p class="text-sm font-medium text-gray-600">{{ _("No hay salvas disponibles") }}</p>
  487. <p class="text-xs text-gray-400 mt-1">{{ _("Realiza una salva manual o activa las automáticas") }}</p>
  488. </div>
  489. </div>
  490. <!-- Table -->
  491. <div x-show="!loadingList && backups.length > {{ _("0\" class=\"flex-1 overflow-auto\">") }}
  492. <table class="w-full text-sm">
  493. <thead class="bg-gray-50 sticky top-0">
  494. <tr>
  495. <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Archivo") }}</th>
  496. <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Fecha") }}</th>
  497. <th class="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Tamaño") }}</th>
  498. <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Tipo") }}</th>
  499. <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Acción") }}</th>
  500. </tr>
  501. </thead>
  502. <tbody class="divide-y divide-gray-50">
  503. <template x-for="(backup, idx) in backups" :key="backup.filename">
  504. <tr class="hover:bg-gray-50 transition-colors"
  505. :class="idx === 0 ? 'bg-emerald-50/40' : ''">
  506. <td class="px-4 py-3">
  507. <div class="flex items-center gap-2">
  508. <i class="fas fa-file-archive text-blue-400 text-xs"></i>
  509. <span class="font-medium text-gray-700 truncate max-w-[140px]" x-text="backup.filename" :title="backup.filename"></span>
  510. <template x-if="idx === 0">
  511. <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">
  512. <i class="fas fa-star text-xs"></i> {{ _("Reciente") }}
  513. </span>
  514. </template>
  515. </div>
  516. </td>
  517. <td class="px-4 py-3 text-gray-500 whitespace-nowrap" x-text="backup.created_at"></td>
  518. <td class="px-4 py-3 text-right text-gray-600 font-mono whitespace-nowrap" x-text="backup.size_human"></td>
  519. <td class="px-4 py-3 text-center">
  520. <span :class="backup.type === 'auto' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'"
  521. class="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full">
  522. <i :class="backup.type === 'auto' ? 'fas fa-robot' : 'fas fa-hand-paper'" class="text-xs"></i>
  523. <span x-text="backup.type === 'auto' ? 'Auto' : 'Manual'"></span>
  524. </span>
  525. </td>
  526. <td class="px-4 py-3 text-center">
  527. <div class="flex items-center justify-center gap-1">
  528. <a :href="'/admin/backup/download/' + backup.filename"
  529. 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"
  530. title="{{ _("Descargar") }}">
  531. <i class="fas fa-download"></i>
  532. </a>
  533. <button @click="deleteBackup(backup.filename)"
  534. 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"
  535. title="{{ _("Eliminar") }}">
  536. <i class="fas fa-trash"></i>
  537. </button>
  538. </div>
  539. </td>
  540. </tr>
  541. </template>
  542. </tbody>
  543. </table>
  544. </div>
  545. <!-- Footer -->
  546. <div x-show="!loadingList && backups.length > {{ _("0\" class=\"px-6 py-3 bg-gray-50 border-t border-gray-100\">") }}
  547. <p class="text-xs text-gray-400 flex items-center gap-1">
  548. <i class="fas fa-info-circle"></i>
  549. {{ _("Máximo 3 salvas por período. Las más antiguas se eliminan automáticamente.") }}
  550. </p>
  551. </div>
  552. </div>
  553. </div><!-- end grid -->
  554. </div><!-- end salvas tab -->
  555. <!-- ═══════════════════════════════════════════════════════
  556. TAB: LIMPIAR DATOS
  557. ════════════════════════════════════════════════════════ -->
  558. <div x-show="activeTab === 'limpiar'">
  559. <div class="max-w-4xl">
  560. <!-- Sub-header -->
  561. <div class="mb-8">
  562. <h3 class="text-2xl font-bold text-gray-800 mb-2">
  563. <i class="fas fa-database mr-3"></i>{{ _("Limpiar Datos") }}
  564. </h3>
  565. <p class="text-gray-600">{{ _("Selecciona una tabla y elimina todos sus datos") }}</p>
  566. </div>
  567. <!-- Warning -->
  568. <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6">
  569. <div class="flex items-center">
  570. <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
  571. <div>
  572. <p class="text-red-800 font-medium">{{ _("¡Advertencia!") }}</p>
  573. <p class="text-red-700 text-sm">{{ _("Esta acción es irreversible. Una vez eliminados los datos, no se pueden recuperar.") }}</p>
  574. </div>
  575. </div>
  576. </div>
  577. <!-- Clean Data Form -->
  578. <div class="bg-white rounded-lg shadow-md overflow-hidden">
  579. <div class="px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 border-b border-blue-700">
  580. <h4 class="text-xl font-semibold text-white flex items-center">
  581. <i class="fas fa-trash-alt mr-2"></i>
  582. {{ _("Eliminar Datos de Tabla") }}
  583. </h4>
  584. </div>
  585. <div class="p-6">
  586. <form id="cleanDataForm" class="space-y-6">
  587. <div>
  588. <label for="tableSelect" class="block text-sm font-medium text-gray-700 mb-2">
  589. <i class="fas fa-table mr-1"></i>{{ _("Seleccionar Tabla") }}
  590. </label>
  591. <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">
  592. <option value="">{{ _("Cargando tablas...") }}</option>
  593. </select>
  594. </div>
  595. <div id="tableInfo" class="hidden bg-gray-50 p-4 rounded-lg border">
  596. <div class="flex items-center justify-between">
  597. <div>
  598. <h5 class="text-sm font-medium text-gray-900">{{ _("Información de la Tabla") }}</h5>
  599. <p id="tableDetails" class="text-sm text-gray-600 mt-1"></p>
  600. </div>
  601. <div id="actionButtons" class="hidden">
  602. <button type="button" id="cleanButton"
  603. 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">
  604. <i class="fas fa-trash-alt mr-2"></i>
  605. {{ _("Limpiar Datos") }}
  606. </button>
  607. </div>
  608. </div>
  609. </div>
  610. </form>
  611. </div>
  612. </div>
  613. <!-- Info Card -->
  614. <div class="mt-6 bg-blue-50 border-l-4 border-blue-500 p-4">
  615. <div class="flex items-start">
  616. <i class="fas fa-info-circle text-blue-500 text-xl mr-3 mt-1"></i>
  617. <div>
  618. <p class="text-blue-800 font-medium mb-2">{{ _("Información Importante") }}</p>
  619. <ul class="text-blue-700 text-sm space-y-1 list-disc list-inside">
  620. <li>{{ _("Solo se eliminan los datos de la tabla, no la estructura") }}</li>
  621. <li>{{ _("Las tablas con sufijo de fecha (ej: log_20240121) son tablas diarias") }}</li>
  622. <li>{{ _("Algunas tablas son críticas para el funcionamiento del sistema") }}</li>
  623. <li>{{ _("Se recomienda hacer un respaldo antes de eliminar datos importantes") }}</li>
  624. </ul>
  625. </div>
  626. </div>
  627. </div>
  628. </div>
  629. </div><!-- end limpiar tab -->
  630. </div><!-- end x-data outer -->
  631. <script>
  632. // ──────────────────────────────────────────────────────────
  633. // DB Health Panel (Alpine component)
  634. // ──────────────────────────────────────────────────────────
  635. function dbHealthPanel() {
  636. return {
  637. loading: false,
  638. health: null,
  639. error: null,
  640. integrityLoading: false,
  641. integrityResult: null,
  642. translations: {
  643. verifying: '{{ _('Verificando...') }}',
  644. verifyIntegrity: '{{ _('Verificar Integridad') }}',
  645. integrityOk: '{{ _('Sin errores detectados — la base de datos está íntegra.') }}',
  646. integrityError: '{{ _('Se encontraron errores de integridad.') }}',
  647. integrityErrorsCount: '{{ _('error(es) detectado(s)') }}'
  648. },
  649. init() { this.loadHealth(); },
  650. async loadHealth() {
  651. this.loading = true;
  652. this.error = null;
  653. try {
  654. const r = await fetch('/admin/api/db-health', {
  655. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  656. });
  657. const d = await r.json();
  658. if (d.status === 'success') this.health = d.health;
  659. else this.error = d.message || 'Error desconocido';
  660. } catch {
  661. this.error = 'Error de conexión al servidor';
  662. } finally {
  663. this.loading = false;
  664. }
  665. },
  666. async checkIntegrity() {
  667. this.integrityLoading = true;
  668. this.integrityResult = null;
  669. try {
  670. const r = await fetch('/admin/api/db-integrity', {
  671. method: 'POST',
  672. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  673. });
  674. const d = await r.json();
  675. if (d.status === 'success') {
  676. this.integrityResult = d.integrity;
  677. } else {
  678. this.integrityResult = { ok: false, errors: [d.message || 'Error desconocido'], error_count: 1 };
  679. }
  680. } catch {
  681. this.integrityResult = { ok: false, errors: ['Error de conexión al servidor'], error_count: 1 };
  682. } finally {
  683. this.integrityLoading = false;
  684. }
  685. },
  686. formatBytes(bytes) {
  687. if (!bytes || bytes === 0) return '{{ _('0 B') }}';
  688. const k = 1024;
  689. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  690. const i = Math.floor(Math.log(bytes) / Math.log(k));
  691. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  692. },
  693. get healthStatus() {
  694. if (this.health?.extra?.corruption) return 'critical';
  695. const frag = this.health?.extra?.fragmentation_pct ?? 0;
  696. if (frag > 30) return 'critical';
  697. if (frag > 10) return 'warning';
  698. return 'good';
  699. },
  700. get healthLabel() {
  701. if (this.health?.extra?.corruption) return '{{ _('Corrupción detectada') }}';
  702. return { good: '{{ _('Saludable') }}', warning: '{{ _('Advertencia') }}', critical: '{{ _('Crítico') }}' }[this.healthStatus];
  703. }
  704. };
  705. }
  706. // ──────────────────────────────────────────────────────────
  707. // Backup Manager (Alpine component)
  708. // ──────────────────────────────────────────────────────────
  709. function backupManager() {
  710. return {
  711. translations: {
  712. sinSalvas: '{{ _('Sin salvas') }}',
  713. noBackups: '{{ _('0 B') }}',
  714. guardando: '{{ _('Guardando...') }}',
  715. salvaManual: '{{ _('Salva Manual') }}',
  716. guardarConfiguracion: '{{ _('Guardar Configuración') }}',
  717. freqDailyWeekly: '{{ _('Se ejecuta diariamente, conservando máx. 3 salvas por semana') }}',
  718. freqDailyMonthly: '{{ _('Se ejecuta diariamente, conservando máx. 3 salvas por mes') }}',
  719. },
  720. config: {
  721. db_type: '{{ current_config.db_type | default("sqlite") }}',
  722. frequency: '{{ current_config.frequency | default("daily_weekly") }}',
  723. backup_dir: '{{ current_config.backup_dir | default("/opt/SquidStats/backups") }}',
  724. enabled: {{ 'true' if current_config.enabled | default(false) else 'false' }},
  725. },
  726. backups: [],
  727. loadingList: false,
  728. loadingSave: false,
  729. loadingManual: false,
  730. statusMsg: '',
  731. statusType: 'success',
  732. get lastBackupDate() {
  733. if (!this.backups.length) return this.translations.sinSalvas;
  734. return this.backups[0].created_at;
  735. },
  736. get totalSize() {
  737. const total = this.backups.reduce((acc, b) => acc + (b.size_bytes || 0), 0);
  738. return this.formatBytes(total);
  739. },
  740. formatBytes(bytes) {
  741. if (!bytes) return this.translations.noBackups;
  742. const k = 1024;
  743. const sizes = ['B', 'KB', 'MB', 'GB'];
  744. const i = Math.floor(Math.log(bytes) / Math.log(k));
  745. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  746. },
  747. onDbTypeChange() {
  748. // all engines now supported
  749. },
  750. showStatus(msg, type = 'success') {
  751. this.statusMsg = msg;
  752. this.statusType = type;
  753. setTimeout(() => { this.statusMsg = ''; }, 4000);
  754. },
  755. async loadBackups() {
  756. this.loadingList = true;
  757. try {
  758. const resp = await fetch('/admin/backup/list', {
  759. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  760. });
  761. const data = await resp.json();
  762. if (data.status === 'success') this.backups = data.backups || [];
  763. else this.showStatus(data.message || 'Error al cargar salvas', 'error');
  764. } catch {
  765. this.showStatus('Error de conexión al cargar salvas', 'error');
  766. } finally {
  767. this.loadingList = false;
  768. }
  769. },
  770. async saveConfig() {
  771. this.loadingSave = true;
  772. try {
  773. const resp = await fetch('/admin/backup/config', {
  774. method: 'POST',
  775. headers: {
  776. 'Content-Type': 'application/json',
  777. 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
  778. },
  779. body: JSON.stringify(this.config)
  780. });
  781. const data = await resp.json();
  782. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  783. } catch {
  784. this.showStatus('Error al guardar la configuración', 'error');
  785. } finally {
  786. this.loadingSave = false;
  787. }
  788. },
  789. async triggerManualBackup() {
  790. this.loadingManual = true;
  791. try {
  792. const resp = await fetch('/admin/backup/run', {
  793. method: 'POST',
  794. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  795. });
  796. const data = await resp.json();
  797. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  798. if (data.status === 'success') await this.loadBackups();
  799. } catch {
  800. this.showStatus('{{ _('Error al ejecutar la salva') }}', 'error');
  801. } finally {
  802. this.loadingManual = false;
  803. }
  804. },
  805. async deleteBackup(filename) {
  806. const confirmMessage = '{{ _('¿Eliminar la salva "%(filename)s"?', filename='%(filename)s') }}'.replace('%(filename)s', filename);
  807. if (!confirm(confirmMessage)) return;
  808. try {
  809. const resp = await fetch('/admin/backup/delete/' + encodeURIComponent(filename), {
  810. method: 'DELETE',
  811. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  812. });
  813. const data = await resp.json();
  814. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  815. if (data.status === 'success') await this.loadBackups();
  816. } catch {
  817. this.showStatus('Error al eliminar la salva', 'error');
  818. }
  819. },
  820. init() { this.loadBackups(); }
  821. };
  822. }
  823. // ──────────────────────────────────────────────────────────
  824. // Clean Data (vanilla JS)
  825. // ──────────────────────────────────────────────────────────
  826. let tablesData = [];
  827. const tableLoadErrorMessage = {{ _("No se pudieron cargar las tablas")|tojson }};
  828. function formatSize(bytes) {
  829. if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
  830. const k = 1024;
  831. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  832. const i = Math.floor(Math.log(bytes) / Math.log(k));
  833. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  834. }
  835. document.addEventListener('DOMContentLoaded', function () {
  836. loadTables();
  837. document.getElementById('tableSelect').addEventListener('change', function () {
  838. const selectedTable = this.value;
  839. const tableInfo = document.getElementById('tableInfo');
  840. const tableDetails = document.getElementById('tableDetails');
  841. const actionButtons = document.getElementById('actionButtons');
  842. const cleanButton = document.getElementById('cleanButton');
  843. if (selectedTable) {
  844. const table = tablesData.find(t => t.name === selectedTable);
  845. if (table) {
  846. tableDetails.textContent = `Tabla: ${table.name} | Registros: ${table.rows.toLocaleString()} | Tamaño: ${formatSize(table.size)}`;
  847. tableInfo.classList.remove('hidden');
  848. if (table.has_data) {
  849. actionButtons.classList.remove('hidden');
  850. cleanButton.onclick = () => confirmDeleteTable(table.name, table.rows, table.size);
  851. } else {
  852. actionButtons.classList.add('hidden');
  853. tableDetails.textContent += ' | Esta tabla está vacía';
  854. }
  855. }
  856. } else {
  857. tableInfo.classList.add('hidden');
  858. }
  859. });
  860. });
  861. async function loadTables() {
  862. const select = document.getElementById('tableSelect');
  863. try {
  864. const response = await fetch('/admin/api/get-tables', {
  865. method: 'GET',
  866. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
  867. });
  868. const data = await response.json();
  869. if (!response.ok || data.status !== 'success') {
  870. throw new Error(data.message || `Error HTTP ${response.status}`);
  871. }
  872. tablesData = Array.isArray(data.tables) ? data.tables : [];
  873. populateTableSelect();
  874. } catch (error) {
  875. console.error('Error loading tables:', error);
  876. tablesData = [];
  877. select.innerHTML = `<option value="">${tableLoadErrorMessage}</option>`;
  878. document.getElementById('tableInfo').classList.add('hidden');
  879. document.getElementById('actionButtons').classList.add('hidden');
  880. }
  881. }
  882. function populateTableSelect() {
  883. const select = document.getElementById('tableSelect');
  884. select.innerHTML = '<option value="">{{ _('Selecciona una tabla...') }}</option>';
  885. tablesData.forEach(table => {
  886. const option = document.createElement('option');
  887. option.value = table.name;
  888. option.textContent = `${table.name} (${table.rows.toLocaleString()} registros, ${formatSize(table.size)})`;
  889. select.appendChild(option);
  890. });
  891. }
  892. function confirmDeleteTable(tableName, rowCount, size) {
  893. 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.`;
  894. showCustomConfirm(message, async () => { await deleteTableData(tableName); });
  895. }
  896. async function deleteTableData(tableName) {
  897. try {
  898. const response = await fetch('/admin/api/delete-table-data', {
  899. method: 'POST',
  900. headers: {
  901. 'Content-Type': 'application/json',
  902. 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
  903. },
  904. body: JSON.stringify({ table_name: tableName })
  905. });
  906. const data = await response.json();
  907. if (data.status === 'success') {
  908. if (window.toastr) toastr.success(data.message);
  909. setTimeout(() => {
  910. loadTables();
  911. document.getElementById('tableSelect').value = '';
  912. document.getElementById('tableInfo').classList.add('hidden');
  913. }, 1500);
  914. } else {
  915. if (window.toastr) toastr.error(data.message || 'Error al eliminar los datos');
  916. }
  917. } catch (error) {
  918. console.error('Error:', error);
  919. if (window.toastr) toastr.error('Error al eliminar los datos de la tabla');
  920. }
  921. }
  922. </script>
  923. {% endblock %}