database.html 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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 ? 'Verificando...' : 'Verificar Integridad'"></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 ? 'Sin errores detectados — la base de datos está íntegra.' : 'Se encontraron errores de integridad.'"></p>
  282. <p class="text-sm mt-0.5"
  283. x-show="integrityResult.error_count > 0"
  284. x-text="integrityResult.error_count + ' error(es) detectado(s)'"></p>
  285. <ul x-show="integrityResult.errors && integrityResult.errors.length > 0"
  286. class="mt-2 space-y-1">
  287. <template x-for="err in integrityResult.errors" :key="err">
  288. <li class="text-sm font-mono bg-white/60 border border-current/10 rounded px-3 py-1"
  289. x-text="err"></li>
  290. </template>
  291. </ul>
  292. </div>
  293. </div>
  294. </template>
  295. </div>
  296. </div>
  297. </div><!-- end resumen tab -->
  298. <!-- ═══════════════════════════════════════════════════════
  299. TAB: SALVAS DE BD
  300. ════════════════════════════════════════════════════════ -->
  301. <div x-show="activeTab === 'salvas'" x-data="backupManager()" class="space-y-6">
  302. <!-- Page sub-header -->
  303. <div class="flex items-center justify-between">
  304. <div>
  305. <h3 class="text-xl font-bold text-gray-800">Salvas de Base de Datos</h3>
  306. <p class="text-sm text-gray-500 mt-1">Configura y gestiona las copias de seguridad automáticas</p>
  307. </div>
  308. <button @click="triggerManualBackup()" :disabled="loadingManual"
  309. 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">
  310. <i :class="loadingManual ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
  311. <span x-text="loadingManual ? 'Guardando...' : 'Salva Manual'"></span>
  312. </button>
  313. </div>
  314. <!-- Status Banner -->
  315. <div x-show="statusMsg" x-transition
  316. :class="statusType === 'success' ? 'bg-emerald-50 border border-emerald-200 text-emerald-800' : 'bg-red-50 border border-red-200 text-red-800'"
  317. class="flex items-center gap-3 px-4 py-3 rounded-lg" style="display:none;">
  318. <i :class="statusType === 'success' ? 'fas fa-check-circle text-emerald-500' : 'fas fa-times-circle text-red-500'"></i>
  319. <span x-text="statusMsg" class="text-sm font-medium"></span>
  320. <button @click="statusMsg = ''" class="ml-auto text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
  321. </div>
  322. <!-- Stats Cards -->
  323. <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
  324. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  325. <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
  326. <i class="fas fa-database text-blue-600 text-xl"></i>
  327. </div>
  328. <div>
  329. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Total Salvas</p>
  330. <p class="text-2xl font-bold text-gray-800" x-text="backups.length">--</p>
  331. </div>
  332. </div>
  333. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  334. <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center">
  335. <i class="fas fa-clock text-emerald-600 text-xl"></i>
  336. </div>
  337. <div>
  338. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Última Salva</p>
  339. <p class="text-sm font-semibold text-gray-800" x-text="lastBackupDate">Sin salvas</p>
  340. </div>
  341. </div>
  342. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  343. <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
  344. <i class="fas fa-hdd text-purple-600 text-xl"></i>
  345. </div>
  346. <div>
  347. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">Espacio Total</p>
  348. <p class="text-sm font-semibold text-gray-800" x-text="totalSize">0 B</p>
  349. </div>
  350. </div>
  351. </div>
  352. <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
  353. <!-- Configuration Panel -->
  354. <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  355. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  356. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  357. <i class="fas fa-sliders-h text-blue-500"></i>
  358. Configuración de Salvas
  359. </h3>
  360. </div>
  361. <form @submit.prevent="saveConfig()" class="p-6 space-y-5">
  362. <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
  363. <!-- DB Engine -->
  364. <div>
  365. <label class="block text-sm font-medium text-gray-700 mb-2">
  366. <i class="fas fa-server text-gray-400 mr-1"></i> Motor de Base de Datos
  367. </label>
  368. <div class="relative">
  369. <select x-model="config.db_type" @change="onDbTypeChange()"
  370. 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">
  371. <option value="sqlite">SQLite</option>
  372. <option value="mysql">MySQL / MariaDB</option>
  373. <option value="postgresql">PostgreSQL</option>
  374. </select>
  375. <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
  376. <i class="fas fa-chevron-down text-xs"></i>
  377. </div>
  378. </div>
  379. <template x-if="config.db_type === 'mysql'">
  380. <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
  381. <i class="fas fa-exclamation-triangle"></i>
  382. Requiere <code class="font-mono">mysqldump</code> instalado en el servidor.
  383. </p>
  384. </template>
  385. <template x-if="config.db_type === 'postgresql'">
  386. <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
  387. <i class="fas fa-exclamation-triangle"></i>
  388. Requiere <code class="font-mono">pg_dump</code> instalado en el servidor.
  389. </p>
  390. </template>
  391. </div>
  392. <!-- Frequency -->
  393. <div>
  394. <label class="block text-sm font-medium text-gray-700 mb-2">
  395. <i class="fas fa-calendar-alt text-gray-400 mr-1"></i> Frecuencia
  396. </label>
  397. <div class="relative">
  398. <select x-model="config.frequency"
  399. 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">
  400. <option value="daily_weekly">Diaria — máx. 3 por semana</option>
  401. <option value="daily_monthly">Diaria — máx. 3 por mes</option>
  402. </select>
  403. <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
  404. <i class="fas fa-chevron-down text-xs"></i>
  405. </div>
  406. </div>
  407. <p class="mt-1.5 text-xs text-gray-500 flex items-center gap-1">
  408. <i class="fas fa-info-circle"></i>
  409. <span x-text="config.frequency === 'daily_weekly' ? 'Se ejecuta diariamente, conservando máx. 3 salvas por semana' : 'Se ejecuta diariamente, conservando máx. 3 salvas por mes'"></span>
  410. </p>
  411. </div>
  412. <!-- Retention -->
  413. <div>
  414. <div class="flex items-center justify-between mb-2">
  415. <label class="block text-sm font-medium text-gray-700">
  416. <i class="fas fa-archive text-gray-400 mr-1"></i> Retención máxima
  417. </label>
  418. <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">
  419. <i class="fas fa-lock text-xs"></i> Fijo: 3 salvas
  420. </span>
  421. </div>
  422. <div class="flex items-center gap-3 bg-gray-50 border border-gray-200 rounded-lg px-4 py-3">
  423. <div class="flex gap-1.5">
  424. <template x-for="i in [1,2,3]" :key="i">
  425. <div class="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold bg-blue-500 text-white shadow-sm">
  426. <span x-text="i"></span>
  427. </div>
  428. </template>
  429. </div>
  430. <p class="text-xs text-gray-600">Se mantienen las 3 salvas más recientes. Las más antiguas se eliminan automáticamente.</p>
  431. </div>
  432. </div>
  433. <!-- Backup Directory -->
  434. <div>
  435. <label class="block text-sm font-medium text-gray-700 mb-2">
  436. <i class="fas fa-folder text-gray-400 mr-1"></i> Directorio de Salvas
  437. </label>
  438. <input type="text" x-model="config.backup_dir"
  439. 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"
  440. placeholder="/opt/SquidStats/backups" />
  441. <p class="mt-1.5 text-xs text-gray-500">Ruta absoluta donde se guardarán las salvas</p>
  442. </div>
  443. <!-- Enabled Toggle -->
  444. <div class="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3 border border-gray-200">
  445. <div>
  446. <p class="text-sm font-medium text-gray-700">Salvas automáticas</p>
  447. <p class="text-xs text-gray-500 mt-0.5">Habilitar programación automática</p>
  448. </div>
  449. <button type="button" @click="config.enabled = !config.enabled"
  450. :class="config.enabled ? 'bg-blue-600' : 'bg-gray-300'"
  451. 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">
  452. <span :class="config.enabled ? 'translate-x-5' : 'translate-x-0'"
  453. 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>
  454. </button>
  455. </div>
  456. <!-- Submit -->
  457. <button type="submit" :disabled="loadingSave"
  458. 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">
  459. <i :class="loadingSave ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
  460. <span x-text="loadingSave ? 'Guardando...' : 'Guardar Configuración'"></span>
  461. </button>
  462. </form>
  463. </div>
  464. <!-- Backups List -->
  465. <div class="lg:col-span-3 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden flex flex-col">
  466. <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">
  467. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  468. <i class="fas fa-history text-blue-500"></i>
  469. Historial de Salvas
  470. </h3>
  471. <button @click="loadBackups()" class="text-xs text-blue-600 hover:text-blue-800 font-medium flex items-center gap-1 transition-colors">
  472. <i class="fas fa-sync-alt" :class="loadingList ? 'animate-spin' : ''"></i> Actualizar
  473. </button>
  474. </div>
  475. <!-- Loading -->
  476. <div x-show="loadingList" class="flex-1 flex items-center justify-center py-16">
  477. <div class="text-center">
  478. <i class="fas fa-spinner fa-spin text-blue-500 text-3xl mb-3"></i>
  479. <p class="text-sm text-gray-500">Cargando salvas...</p>
  480. </div>
  481. </div>
  482. <!-- Empty -->
  483. <div x-show="!loadingList && backups.length === 0" class="flex-1 flex items-center justify-center py-16">
  484. <div class="text-center px-6">
  485. <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
  486. <i class="fas fa-box-open text-gray-400 text-2xl"></i>
  487. </div>
  488. <p class="text-sm font-medium text-gray-600">No hay salvas disponibles</p>
  489. <p class="text-xs text-gray-400 mt-1">Realiza una salva manual o activa las automáticas</p>
  490. </div>
  491. </div>
  492. <!-- Table -->
  493. <div x-show="!loadingList && backups.length > 0" class="flex-1 overflow-auto">
  494. <table class="w-full text-sm">
  495. <thead class="bg-gray-50 sticky top-0">
  496. <tr>
  497. <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Archivo</th>
  498. <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Fecha</th>
  499. <th class="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Tamaño</th>
  500. <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Tipo</th>
  501. <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Acción</th>
  502. </tr>
  503. </thead>
  504. <tbody class="divide-y divide-gray-50">
  505. <template x-for="(backup, idx) in backups" :key="backup.filename">
  506. <tr class="hover:bg-gray-50 transition-colors"
  507. :class="idx === 0 ? 'bg-emerald-50/40' : ''">
  508. <td class="px-4 py-3">
  509. <div class="flex items-center gap-2">
  510. <i class="fas fa-file-archive text-blue-400 text-xs"></i>
  511. <span class="font-medium text-gray-700 truncate max-w-[140px]" x-text="backup.filename" :title="backup.filename"></span>
  512. <template x-if="idx === 0">
  513. <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">
  514. <i class="fas fa-star text-xs"></i> Reciente
  515. </span>
  516. </template>
  517. </div>
  518. </td>
  519. <td class="px-4 py-3 text-gray-500 whitespace-nowrap" x-text="backup.created_at"></td>
  520. <td class="px-4 py-3 text-right text-gray-600 font-mono whitespace-nowrap" x-text="backup.size_human"></td>
  521. <td class="px-4 py-3 text-center">
  522. <span :class="backup.type === 'auto' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'"
  523. class="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full">
  524. <i :class="backup.type === 'auto' ? 'fas fa-robot' : 'fas fa-hand-paper'" class="text-xs"></i>
  525. <span x-text="backup.type === 'auto' ? 'Auto' : 'Manual'"></span>
  526. </span>
  527. </td>
  528. <td class="px-4 py-3 text-center">
  529. <div class="flex items-center justify-center gap-1">
  530. <a :href="'/admin/backup/download/' + backup.filename"
  531. 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"
  532. title="Descargar">
  533. <i class="fas fa-download"></i>
  534. </a>
  535. <button @click="deleteBackup(backup.filename)"
  536. 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"
  537. title="Eliminar">
  538. <i class="fas fa-trash"></i>
  539. </button>
  540. </div>
  541. </td>
  542. </tr>
  543. </template>
  544. </tbody>
  545. </table>
  546. </div>
  547. <!-- Footer -->
  548. <div x-show="!loadingList && backups.length > 0" class="px-6 py-3 bg-gray-50 border-t border-gray-100">
  549. <p class="text-xs text-gray-400 flex items-center gap-1">
  550. <i class="fas fa-info-circle"></i>
  551. Máximo 3 salvas por período. Las más antiguas se eliminan automáticamente.
  552. </p>
  553. </div>
  554. </div>
  555. </div><!-- end grid -->
  556. </div><!-- end salvas tab -->
  557. <!-- ═══════════════════════════════════════════════════════
  558. TAB: LIMPIAR DATOS
  559. ════════════════════════════════════════════════════════ -->
  560. <div x-show="activeTab === 'limpiar'">
  561. <div class="max-w-4xl">
  562. <!-- Sub-header -->
  563. <div class="mb-8">
  564. <h3 class="text-2xl font-bold text-gray-800 mb-2">
  565. <i class="fas fa-database mr-3"></i>Limpiar Datos
  566. </h3>
  567. <p class="text-gray-600">Selecciona una tabla y elimina todos sus datos</p>
  568. </div>
  569. <!-- Warning -->
  570. <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6">
  571. <div class="flex items-center">
  572. <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
  573. <div>
  574. <p class="text-red-800 font-medium">¡Advertencia!</p>
  575. <p class="text-red-700 text-sm">Esta acción es irreversible. Una vez eliminados los datos, no se pueden recuperar.</p>
  576. </div>
  577. </div>
  578. </div>
  579. <!-- Clean Data Form -->
  580. <div class="bg-white rounded-lg shadow-md overflow-hidden">
  581. <div class="px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 border-b border-blue-700">
  582. <h4 class="text-xl font-semibold text-white flex items-center">
  583. <i class="fas fa-trash-alt mr-2"></i>
  584. Eliminar Datos de Tabla
  585. </h4>
  586. </div>
  587. <div class="p-6">
  588. <form id="cleanDataForm" class="space-y-6">
  589. <div>
  590. <label for="tableSelect" class="block text-sm font-medium text-gray-700 mb-2">
  591. <i class="fas fa-table mr-1"></i>Seleccionar Tabla
  592. </label>
  593. <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">
  594. <option value="">Cargando tablas...</option>
  595. </select>
  596. </div>
  597. <div id="tableInfo" class="hidden bg-gray-50 p-4 rounded-lg border">
  598. <div class="flex items-center justify-between">
  599. <div>
  600. <h5 class="text-sm font-medium text-gray-900">Información de la Tabla</h5>
  601. <p id="tableDetails" class="text-sm text-gray-600 mt-1"></p>
  602. </div>
  603. <div id="actionButtons" class="hidden">
  604. <button type="button" id="cleanButton"
  605. 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">
  606. <i class="fas fa-trash-alt mr-2"></i>
  607. Limpiar Datos
  608. </button>
  609. </div>
  610. </div>
  611. </div>
  612. </form>
  613. </div>
  614. </div>
  615. <!-- Info Card -->
  616. <div class="mt-6 bg-blue-50 border-l-4 border-blue-500 p-4">
  617. <div class="flex items-start">
  618. <i class="fas fa-info-circle text-blue-500 text-xl mr-3 mt-1"></i>
  619. <div>
  620. <p class="text-blue-800 font-medium mb-2">Información Importante</p>
  621. <ul class="text-blue-700 text-sm space-y-1 list-disc list-inside">
  622. <li>Solo se eliminan los datos de la tabla, no la estructura</li>
  623. <li>Las tablas con sufijo de fecha (ej: log_20240121) son tablas diarias</li>
  624. <li>Algunas tablas son críticas para el funcionamiento del sistema</li>
  625. <li>Se recomienda hacer un respaldo antes de eliminar datos importantes</li>
  626. </ul>
  627. </div>
  628. </div>
  629. </div>
  630. </div>
  631. </div><!-- end limpiar tab -->
  632. </div><!-- end x-data outer -->
  633. <script>
  634. // ──────────────────────────────────────────────────────────
  635. // DB Health Panel (Alpine component)
  636. // ──────────────────────────────────────────────────────────
  637. function dbHealthPanel() {
  638. return {
  639. loading: false,
  640. health: null,
  641. error: null,
  642. integrityLoading: false,
  643. integrityResult: null,
  644. init() { this.loadHealth(); },
  645. async loadHealth() {
  646. this.loading = true;
  647. this.error = null;
  648. try {
  649. const r = await fetch('/admin/api/db-health', {
  650. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  651. });
  652. const d = await r.json();
  653. if (d.status === 'success') this.health = d.health;
  654. else this.error = d.message || 'Error desconocido';
  655. } catch {
  656. this.error = 'Error de conexión al servidor';
  657. } finally {
  658. this.loading = false;
  659. }
  660. },
  661. async checkIntegrity() {
  662. this.integrityLoading = true;
  663. this.integrityResult = null;
  664. try {
  665. const r = await fetch('/admin/api/db-integrity', {
  666. method: 'POST',
  667. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  668. });
  669. const d = await r.json();
  670. if (d.status === 'success') {
  671. this.integrityResult = d.integrity;
  672. } else {
  673. this.integrityResult = { ok: false, errors: [d.message || 'Error desconocido'], error_count: 1 };
  674. }
  675. } catch {
  676. this.integrityResult = { ok: false, errors: ['Error de conexión al servidor'], error_count: 1 };
  677. } finally {
  678. this.integrityLoading = false;
  679. }
  680. },
  681. formatBytes(bytes) {
  682. if (!bytes || bytes === 0) return '0 B';
  683. const k = 1024;
  684. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  685. const i = Math.floor(Math.log(bytes) / Math.log(k));
  686. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  687. },
  688. get healthStatus() {
  689. if (this.health?.extra?.corruption) return 'critical';
  690. const frag = this.health?.extra?.fragmentation_pct ?? 0;
  691. if (frag > 30) return 'critical';
  692. if (frag > 10) return 'warning';
  693. return 'good';
  694. },
  695. get healthLabel() {
  696. if (this.health?.extra?.corruption) return 'Corrupción detectada';
  697. return { good: 'Saludable', warning: 'Advertencia', critical: 'Crítico' }[this.healthStatus];
  698. }
  699. };
  700. }
  701. // ──────────────────────────────────────────────────────────
  702. // Backup Manager (Alpine component)
  703. // ──────────────────────────────────────────────────────────
  704. function backupManager() {
  705. return {
  706. config: {
  707. db_type: '{{ current_config.db_type | default("sqlite") }}',
  708. frequency: '{{ current_config.frequency | default("daily_weekly") }}',
  709. backup_dir: '{{ current_config.backup_dir | default("/opt/SquidStats/backups") }}',
  710. enabled: {{ 'true' if current_config.enabled | default(false) else 'false' }},
  711. },
  712. backups: [],
  713. loadingList: false,
  714. loadingSave: false,
  715. loadingManual: false,
  716. statusMsg: '',
  717. statusType: 'success',
  718. get lastBackupDate() {
  719. if (!this.backups.length) return 'Sin salvas';
  720. return this.backups[0].created_at;
  721. },
  722. get totalSize() {
  723. const total = this.backups.reduce((acc, b) => acc + (b.size_bytes || 0), 0);
  724. return this.formatBytes(total);
  725. },
  726. formatBytes(bytes) {
  727. if (!bytes) return '0 B';
  728. const k = 1024;
  729. const sizes = ['B', 'KB', 'MB', 'GB'];
  730. const i = Math.floor(Math.log(bytes) / Math.log(k));
  731. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  732. },
  733. onDbTypeChange() {
  734. // all engines now supported
  735. },
  736. showStatus(msg, type = 'success') {
  737. this.statusMsg = msg;
  738. this.statusType = type;
  739. setTimeout(() => { this.statusMsg = ''; }, 4000);
  740. },
  741. async loadBackups() {
  742. this.loadingList = true;
  743. try {
  744. const resp = await fetch('/admin/backup/list', {
  745. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  746. });
  747. const data = await resp.json();
  748. if (data.status === 'success') this.backups = data.backups || [];
  749. else this.showStatus(data.message || 'Error al cargar salvas', 'error');
  750. } catch {
  751. this.showStatus('Error de conexión al cargar salvas', 'error');
  752. } finally {
  753. this.loadingList = false;
  754. }
  755. },
  756. async saveConfig() {
  757. this.loadingSave = true;
  758. try {
  759. const resp = await fetch('/admin/backup/config', {
  760. method: 'POST',
  761. headers: {
  762. 'Content-Type': 'application/json',
  763. 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
  764. },
  765. body: JSON.stringify(this.config)
  766. });
  767. const data = await resp.json();
  768. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  769. } catch {
  770. this.showStatus('Error al guardar la configuración', 'error');
  771. } finally {
  772. this.loadingSave = false;
  773. }
  774. },
  775. async triggerManualBackup() {
  776. this.loadingManual = true;
  777. try {
  778. const resp = await fetch('/admin/backup/run', {
  779. method: 'POST',
  780. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  781. });
  782. const data = await resp.json();
  783. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  784. if (data.status === 'success') await this.loadBackups();
  785. } catch {
  786. this.showStatus('Error al ejecutar la salva', 'error');
  787. } finally {
  788. this.loadingManual = false;
  789. }
  790. },
  791. async deleteBackup(filename) {
  792. if (!confirm(`¿Eliminar la salva "${filename}"?`)) return;
  793. try {
  794. const resp = await fetch('/admin/backup/delete/' + encodeURIComponent(filename), {
  795. method: 'DELETE',
  796. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  797. });
  798. const data = await resp.json();
  799. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  800. if (data.status === 'success') await this.loadBackups();
  801. } catch {
  802. this.showStatus('Error al eliminar la salva', 'error');
  803. }
  804. },
  805. init() { this.loadBackups(); }
  806. };
  807. }
  808. // ──────────────────────────────────────────────────────────
  809. // Clean Data (vanilla JS)
  810. // ──────────────────────────────────────────────────────────
  811. let tablesData = [];
  812. function formatSize(bytes) {
  813. if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
  814. const k = 1024;
  815. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  816. const i = Math.floor(Math.log(bytes) / Math.log(k));
  817. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  818. }
  819. document.addEventListener('DOMContentLoaded', function () {
  820. loadTables();
  821. document.getElementById('tableSelect').addEventListener('change', function () {
  822. const selectedTable = this.value;
  823. const tableInfo = document.getElementById('tableInfo');
  824. const tableDetails = document.getElementById('tableDetails');
  825. const actionButtons = document.getElementById('actionButtons');
  826. const cleanButton = document.getElementById('cleanButton');
  827. if (selectedTable) {
  828. const table = tablesData.find(t => t.name === selectedTable);
  829. if (table) {
  830. tableDetails.textContent = `Tabla: ${table.name} | Registros: ${table.rows.toLocaleString()} | Tamaño: ${formatSize(table.size)}`;
  831. tableInfo.classList.remove('hidden');
  832. if (table.has_data) {
  833. actionButtons.classList.remove('hidden');
  834. cleanButton.onclick = () => confirmDeleteTable(table.name, table.rows, table.size);
  835. } else {
  836. actionButtons.classList.add('hidden');
  837. tableDetails.textContent += ' | Esta tabla está vacía';
  838. }
  839. }
  840. } else {
  841. tableInfo.classList.add('hidden');
  842. }
  843. });
  844. });
  845. async function loadTables() {
  846. try {
  847. const response = await fetch('/admin/api/get-tables', {
  848. method: 'GET',
  849. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
  850. });
  851. const data = await response.json();
  852. if (data.status === 'success') {
  853. tablesData = data.tables;
  854. populateTableSelect();
  855. }
  856. } catch (error) {
  857. console.error('Error loading tables:', error);
  858. }
  859. }
  860. function populateTableSelect() {
  861. const select = document.getElementById('tableSelect');
  862. select.innerHTML = '<option value="">Selecciona una tabla...</option>';
  863. tablesData.forEach(table => {
  864. const option = document.createElement('option');
  865. option.value = table.name;
  866. option.textContent = `${table.name} (${table.rows.toLocaleString()} registros, ${formatSize(table.size)})`;
  867. select.appendChild(option);
  868. });
  869. }
  870. function confirmDeleteTable(tableName, rowCount, size) {
  871. 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.`;
  872. showCustomConfirm(message, async () => { await deleteTableData(tableName); });
  873. }
  874. async function deleteTableData(tableName) {
  875. try {
  876. const response = await fetch('/admin/api/delete-table-data', {
  877. method: 'POST',
  878. headers: {
  879. 'Content-Type': 'application/json',
  880. 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
  881. },
  882. body: JSON.stringify({ table_name: tableName })
  883. });
  884. const data = await response.json();
  885. if (data.status === 'success') {
  886. if (window.toastr) toastr.success(data.message);
  887. setTimeout(() => {
  888. loadTables();
  889. document.getElementById('tableSelect').value = '';
  890. document.getElementById('tableInfo').classList.add('hidden');
  891. }, 1500);
  892. } else {
  893. if (window.toastr) toastr.error(data.message || 'Error al eliminar los datos');
  894. }
  895. } catch (error) {
  896. console.error('Error:', error);
  897. if (window.toastr) toastr.error('Error al eliminar los datos de la tabla');
  898. }
  899. }
  900. </script>
  901. {% endblock %}