database.html 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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 = 'importar'"
  32. :class="activeTab === 'importar'
  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-file-import text-base"></i>
  37. {{ _("Importar Logs") }}
  38. </button>
  39. <button @click="activeTab = 'limpiar'"
  40. :class="activeTab === 'limpiar'
  41. ? 'border-blue-600 text-blue-600 bg-blue-50/40'
  42. : 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50'"
  43. 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">
  44. <i class="fas fa-trash-alt text-base"></i>
  45. {{ _("Limpiar Datos") }}
  46. </button>
  47. </nav>
  48. </div>
  49. <!-- ═══════════════════════════════════════════════════════
  50. TAB: RESUMEN DB
  51. ════════════════════════════════════════════════════════ -->
  52. <div x-show="activeTab === 'resumen'" x-data="dbHealthPanel()" class="space-y-6">
  53. <!-- Loading -->
  54. <div x-show="loading" class="flex items-center justify-center py-24">
  55. <div class="text-center">
  56. <i class="fas fa-spinner fa-spin text-blue-500 text-4xl mb-4"></i>
  57. <p class="text-sm text-gray-500 font-medium">{{ _("Cargando información de la base de datos...") }}</p>
  58. </div>
  59. </div>
  60. <!-- Error -->
  61. <div x-show="!loading && !!error"
  62. class="bg-red-50 border border-red-200 rounded-xl p-5 flex items-center gap-4">
  63. <i class="fas fa-exclamation-circle text-red-500 text-2xl flex-shrink-0"></i>
  64. <div class="flex-1">
  65. <p class="font-semibold text-red-800">{{ _("Error al cargar los datos") }}</p>
  66. <p class="text-sm text-red-600 mt-0.5" x-text="error"></p>
  67. </div>
  68. <button @click="loadHealth()"
  69. 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">
  70. <i class="fas fa-redo mr-1"></i>{{ _("Reintentar") }}
  71. </button>
  72. </div>
  73. <!-- ── Health status banner ── -->
  74. <template x-if="!loading && health">
  75. <div :class="{
  76. 'bg-emerald-50 border-emerald-200': healthStatus === 'good',
  77. 'bg-amber-50 border-amber-200': healthStatus === 'warning',
  78. 'bg-red-50 border-red-200': healthStatus === 'critical'
  79. }"
  80. class="border rounded-xl p-4 flex items-center gap-4">
  81. <div :class="{
  82. 'bg-emerald-100 text-emerald-500': healthStatus === 'good',
  83. 'bg-amber-100 text-amber-500': healthStatus === 'warning',
  84. 'bg-red-100 text-red-500': healthStatus === 'critical'
  85. }"
  86. class="w-14 h-14 rounded-full flex items-center justify-center flex-shrink-0">
  87. <i :class="{
  88. 'fas fa-check-circle text-3xl': healthStatus === 'good',
  89. 'fas fa-exclamation-circle text-3xl': healthStatus === 'warning',
  90. 'fas fa-times-circle text-3xl': healthStatus === 'critical'
  91. }"></i>
  92. </div>
  93. <div class="flex-1 min-w-0">
  94. <p :class="{
  95. 'text-emerald-800': healthStatus === 'good',
  96. 'text-amber-800': healthStatus === 'warning',
  97. 'text-red-800': healthStatus === 'critical'
  98. }"
  99. class="font-bold text-lg"
  100. x-text="'{{ _('Salud de la BD:') }} ' + healthLabel"></p>
  101. <p :class="{
  102. 'text-emerald-700': healthStatus === 'good',
  103. 'text-amber-700': healthStatus === 'warning',
  104. 'text-red-700': healthStatus === 'critical'
  105. }"
  106. class="text-sm mt-0.5">
  107. <!-- Corruption takes priority over fragmentation message -->
  108. <template x-if="health.extra.corruption">
  109. <span>
  110. {{ _("La base de datos tiene páginas dañadas.") }}
  111. <span x-show="health.extra.corruption_detail"
  112. class="font-mono bg-red-100 px-1.5 py-0.5 rounded text-xs ml-1"
  113. x-text="health.extra.corruption_detail"></span>
  114. {{ _("Haz un respaldo y ejecuta") }} <strong>{{ _("VACUUM") }}</strong> {{ _("o restaura desde una copia sana.") }}
  115. </span>
  116. </template>
  117. <template x-if="!health.extra.corruption && health.db_type === 'SQLITE' && health.extra.integrity_checked === false">
  118. <span>{{ _("La integridad se verifica manualmente desde el botón Verificar Integridad.") }}</span>
  119. </template>
  120. <template x-if="!health.extra.corruption && health.db_type === 'SQLITE' && health.extra.integrity_checked !== false">
  121. <span>
  122. {{ _("Fragmentación:") }}
  123. <strong x-text="health.extra.fragmentation_pct + '%'"></strong>
  124. <span x-show="healthStatus === 'good'"> {{ _("— dentro del rango normal") }}</span>
  125. <span x-show="healthStatus === 'warning'"> {{ _("— considera ejecutar VACUUM") }}</span>
  126. <span x-show="healthStatus === 'critical'"> {{ _("— ejecuta VACUUM urgentemente") }}</span>
  127. </span>
  128. </template>
  129. <span x-show="!health.extra.corruption && health.db_type !== 'SQLITE'">
  130. {{ _("Motor") }} <strong x-text="health.db_type"></strong> {{ _("operando con normalidad") }}
  131. </span>
  132. </p>
  133. </div>
  134. <button @click="loadHealth()"
  135. class="text-sm font-medium opacity-60 hover:opacity-100 transition-opacity flex-shrink-0"
  136. :class="{
  137. 'text-emerald-800': healthStatus === 'good',
  138. 'text-amber-800': healthStatus === 'warning',
  139. 'text-red-800': healthStatus === 'critical'
  140. }">
  141. <i class="fas fa-sync-alt mr-1"></i>{{ _("Actualizar") }}
  142. </button>
  143. </div>
  144. </template>
  145. <!-- ── 4 stat cards ── -->
  146. <template x-if="!loading && health">
  147. <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
  148. <!-- DB Engine -->
  149. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  150. <div class="w-12 h-12 bg-indigo-100 rounded-xl flex items-center justify-center flex-shrink-0">
  151. <i class="fas fa-database text-indigo-600 text-xl"></i>
  152. </div>
  153. <div class="min-w-0">
  154. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Motor") }}</p>
  155. <p class="text-xl font-bold text-gray-800 truncate" x-text="health.db_type"></p>
  156. </div>
  157. </div>
  158. <!-- Total Size -->
  159. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  160. <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center flex-shrink-0">
  161. <i class="fas fa-hdd text-blue-600 text-xl"></i>
  162. </div>
  163. <div class="min-w-0">
  164. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Tamaño Total") }}</p>
  165. <p class="text-xl font-bold text-gray-800" x-text="formatBytes(health.total_size_bytes)"></p>
  166. </div>
  167. </div>
  168. <!-- Tables -->
  169. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  170. <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center flex-shrink-0">
  171. <i class="fas fa-table text-purple-600 text-xl"></i>
  172. </div>
  173. <div class="min-w-0">
  174. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Tablas") }}</p>
  175. <p class="text-xl font-bold text-gray-800" x-text="health.table_count.toLocaleString()"></p>
  176. </div>
  177. </div>
  178. <!-- Total Records -->
  179. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  180. <div class="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center flex-shrink-0">
  181. <i class="fas fa-list-ol text-emerald-600 text-xl"></i>
  182. </div>
  183. <div class="min-w-0">
  184. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Registros Totales") }}</p>
  185. <p class="text-xl font-bold text-gray-800" x-text="health.total_rows.toLocaleString()"></p>
  186. </div>
  187. </div>
  188. </div>
  189. </template>
  190. <!-- ── SQLite extra details ── -->
  191. <template x-if="!loading && health && health.db_type === 'SQLITE'">
  192. <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  193. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  194. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  195. <i class="fas fa-info-circle text-blue-500"></i>
  196. {{ _("Detalles SQLite") }}
  197. </h3>
  198. </div>
  199. <div class="p-6 grid grid-cols-2 md:grid-cols-3 gap-x-8 gap-y-5">
  200. <div>
  201. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Tamaño de Página") }}</p>
  202. <p class="text-lg font-semibold text-gray-800"
  203. x-text="(health.extra.page_size / 1024).toFixed(1) + ' KB'"></p>
  204. </div>
  205. <div>
  206. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Páginas Totales") }}</p>
  207. <p class="text-lg font-semibold text-gray-800"
  208. x-text="health.extra.page_count.toLocaleString()"></p>
  209. </div>
  210. <div>
  211. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Páginas Libres") }}</p>
  212. <p class="text-lg font-semibold text-gray-800"
  213. x-text="health.extra.freelist_count.toLocaleString()"></p>
  214. </div>
  215. <div>
  216. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Modo Journal") }}</p>
  217. <p class="text-lg font-semibold text-gray-800 uppercase"
  218. x-text="health.extra.journal_mode"></p>
  219. </div>
  220. <div>
  221. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Auto-Vacuum") }}</p>
  222. <p class="text-lg font-semibold text-gray-800"
  223. x-text="health.extra.auto_vacuum"></p>
  224. </div>
  225. <div>
  226. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Fragmentación") }}</p>
  227. <div class="flex items-center gap-2">
  228. <p class="text-lg font-semibold text-gray-800"
  229. x-text="health.extra.fragmentation_pct + '%'"></p>
  230. <span :class="{
  231. 'bg-emerald-100 text-emerald-700': healthStatus === 'good',
  232. 'bg-amber-100 text-amber-700': healthStatus === 'warning',
  233. 'bg-red-100 text-red-700': healthStatus === 'critical'
  234. }"
  235. class="text-xs font-semibold px-2 py-0.5 rounded-full"
  236. x-text="healthLabel"></span>
  237. </div>
  238. </div>
  239. <template x-if="health.extra.corruption && health.extra.corruption_detail">
  240. <div class="col-span-3">
  241. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-1">{{ _("Detalle de Corrupción") }}</p>
  242. <p class="text-sm font-mono bg-red-50 border border-red-200 rounded px-3 py-2 text-red-700 break-all"
  243. x-text="health.extra.corruption_detail"></p>
  244. </div>
  245. </template>
  246. </div>
  247. </div>
  248. </template>
  249. <!-- ── MySQL / PostgreSQL version ── -->
  250. <template x-if="!loading && health && health.db_type !== 'SQLITE' && health.extra && health.extra.version">
  251. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  252. <div class="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center flex-shrink-0">
  253. <i class="fas fa-code-branch text-gray-500 text-xl"></i>
  254. </div>
  255. <div>
  256. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium mb-0.5">{{ _("Versión del Motor") }}</p>
  257. <p class="text-base font-semibold text-gray-800" x-text="health.extra.version"></p>
  258. </div>
  259. </div>
  260. </template>
  261. <!-- ── Integrity Check ── -->
  262. <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  263. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  264. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  265. <i class="fas fa-shield-alt text-blue-500"></i>
  266. {{ _("Verificación de Integridad") }}
  267. </h3>
  268. </div>
  269. <div class="p-6 space-y-4">
  270. <p class="text-sm text-gray-600">
  271. {{ _("Verifica la integridad estructural de la base de datos en busca de posibles errores o corrupción.") }}
  272. <span class="text-amber-600 font-medium">
  273. {{ _("Esta operación puede tardar varios minutos en bases de datos grandes.") }}
  274. </span>
  275. </p>
  276. <button @click="checkIntegrity()" :disabled="integrityLoading"
  277. 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">
  278. <i :class="integrityLoading ? 'fas fa-spinner fa-spin' : 'fas fa-search'"></i>
  279. <span x-text="integrityLoading ? translations.verifying : translations.verifyIntegrity"></span>
  280. </button>
  281. <template x-if="integrityResult">
  282. <div :class="integrityResult.ok
  283. ? 'bg-emerald-50 border-emerald-200 text-emerald-800'
  284. : 'bg-red-50 border-red-200 text-red-800'"
  285. class="border rounded-xl p-4 flex items-start gap-3">
  286. <i :class="integrityResult.ok
  287. ? 'fas fa-check-circle text-emerald-500'
  288. : 'fas fa-times-circle text-red-500'"
  289. class="text-xl flex-shrink-0 mt-0.5"></i>
  290. <div class="flex-1 min-w-0">
  291. <p class="font-semibold"
  292. x-text="integrityResult.ok ? translations.integrityOk : translations.integrityError"></p>
  293. <p class="text-sm mt-0.5" x-show="integrityResult.error_count > 0"
  294. x-text="integrityResult.error_count + ' ' + translations.integrityErrorsCount"></p>
  295. <ul x-show="integrityResult.errors && integrityResult.errors.length > 0" class="mt-2 space-y-1">
  296. <template x-for="err in integrityResult.errors" :key="err">
  297. <li class="text-sm font-mono bg-white/60 border border-current/10 rounded px-3 py-1"
  298. x-text="err"></li>
  299. </template>
  300. </ul>
  301. </div>
  302. </div>
  303. </template>
  304. </div>
  305. </div>
  306. </div><!-- end resumen tab -->
  307. <!-- ═══════════════════════════════════════════════════════
  308. TAB: SALVAS DE BD
  309. ════════════════════════════════════════════════════════ -->
  310. <div x-show="activeTab === 'salvas'" x-data="backupManager()" class="space-y-6">
  311. <!-- Page sub-header -->
  312. <div class="flex items-center justify-between">
  313. <div>
  314. <h3 class="text-xl font-bold text-gray-800">{{ _("Salvas de Base de Datos") }}</h3>
  315. <p class="text-sm text-gray-500 mt-1">{{ _("Configura y gestiona las copias de seguridad automáticas") }}</p>
  316. </div>
  317. <button @click="triggerManualBackup()" :disabled="loadingManual"
  318. 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">
  319. <i :class="loadingManual ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
  320. <span x-text="loadingManual ? translations.guardando : translations.salvaManual"></span>
  321. </button>
  322. </div>
  323. <!-- Status Banner -->
  324. <div x-show="statusMsg" x-transition
  325. :class="statusType === 'success' ? 'bg-emerald-50 border border-emerald-200 text-emerald-800' : 'bg-red-50 border border-red-200 text-red-800'"
  326. class="flex items-center gap-3 px-4 py-3 rounded-lg" style="display:none;">
  327. <i :class="statusType === 'success' ? 'fas fa-check-circle text-emerald-500' : 'fas fa-times-circle text-red-500'"></i>
  328. <span x-text="statusMsg" class="text-sm font-medium"></span>
  329. <button @click="statusMsg = ''" class="ml-auto text-gray-400 hover:text-gray-600"><i class="fas fa-times"></i></button>
  330. </div>
  331. <!-- Stats Cards -->
  332. <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
  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-blue-100 rounded-xl flex items-center justify-center">
  335. <i class="fas fa-database text-blue-600 text-xl"></i>
  336. </div>
  337. <div>
  338. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Total Salvas") }}</p>
  339. <p class="text-2xl font-bold text-gray-800" x-text="backups.length">--</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-emerald-100 rounded-xl flex items-center justify-center">
  344. <i class="fas fa-clock text-emerald-600 text-xl"></i>
  345. </div>
  346. <div>
  347. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Última Salva") }}</p>
  348. <p class="text-sm font-semibold text-gray-800" x-text="lastBackupDate"></p>
  349. </div>
  350. </div>
  351. <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex items-center gap-4">
  352. <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
  353. <i class="fas fa-hdd text-purple-600 text-xl"></i>
  354. </div>
  355. <div>
  356. <p class="text-xs text-gray-500 uppercase tracking-wide font-medium">{{ _("Espacio Total") }}</p>
  357. <p class="text-sm font-semibold text-gray-800" x-text="totalSize"></p>
  358. </div>
  359. </div>
  360. </div>
  361. <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
  362. <!-- Configuration Panel -->
  363. <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  364. <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
  365. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  366. <i class="fas fa-sliders-h text-blue-500"></i>
  367. {{ _("Configuración de Salvas") }}
  368. </h3>
  369. </div>
  370. <form @submit.prevent="saveConfig()" class="p-6 space-y-5">
  371. <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
  372. <!-- DB Engine -->
  373. <div>
  374. <label class="block text-sm font-medium text-gray-700 mb-2">
  375. <i class="fas fa-server text-gray-400 mr-1"></i> {{ _("Motor de Base de Datos") }}
  376. </label>
  377. <div class="relative">
  378. <select x-model="config.db_type" @change="onDbTypeChange()"
  379. 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">
  380. <option value="sqlite">{{ _("SQLite") }}</option>
  381. <option value="mysql">{{ _("MySQL / MariaDB") }}</option>
  382. <option value="postgresql">{{ _("PostgreSQL") }}</option>
  383. </select>
  384. <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
  385. <i class="fas fa-chevron-down text-xs"></i>
  386. </div>
  387. </div>
  388. <template x-if="config.db_type === 'mysql'">
  389. <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
  390. <i class="fas fa-exclamation-triangle"></i>
  391. {{ _("Requiere") }} <code class="font-mono">mysqldump</code> {{ _("instalado en el servidor.") }}
  392. </p>
  393. </template>
  394. <template x-if="config.db_type === 'postgresql'">
  395. <p class="mt-1.5 text-xs text-amber-600 flex items-center gap-1">
  396. <i class="fas fa-exclamation-triangle"></i>
  397. {{ _("Requiere") }} <code class="font-mono">pg_dump</code> {{ _("instalado en el servidor.") }}
  398. </p>
  399. </template>
  400. </div>
  401. <!-- Frequency -->
  402. <div>
  403. <label class="block text-sm font-medium text-gray-700 mb-2">
  404. <i class="fas fa-calendar-alt text-gray-400 mr-1"></i> {{ _("Frecuencia") }}
  405. </label>
  406. <div class="relative">
  407. <select x-model="config.frequency"
  408. 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">
  409. <option value="daily_weekly">{{ _("Diaria — máx. 3 por semana") }}</option>
  410. <option value="daily_monthly">{{ _("Diaria — máx. 3 por mes") }}</option>
  411. </select>
  412. <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-400">
  413. <i class="fas fa-chevron-down text-xs"></i>
  414. </div>
  415. </div>
  416. <p class="mt-1.5 text-xs text-gray-500 flex items-center gap-1">
  417. <i class="fas fa-info-circle"></i>
  418. <span x-text="config.frequency === 'daily_weekly' ? translations.freqDailyWeekly : translations.freqDailyMonthly"></span>
  419. </p>
  420. </div>
  421. <!-- Retention -->
  422. <div>
  423. <div class="flex items-center justify-between mb-2">
  424. <label class="block text-sm font-medium text-gray-700">
  425. <i class="fas fa-archive text-gray-400 mr-1"></i> {{ _("Retención máxima") }}
  426. </label>
  427. <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">
  428. <i class="fas fa-lock text-xs"></i> {{ _("Fijo: 3 salvas") }}
  429. </span>
  430. </div>
  431. <div class="flex items-center gap-3 bg-gray-50 border border-gray-200 rounded-lg px-4 py-3">
  432. <div class="flex gap-1.5">
  433. <template x-for="i in [1,2,3]" :key="i">
  434. <div class="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold bg-blue-500 text-white shadow-sm">
  435. <span x-text="i"></span>
  436. </div>
  437. </template>
  438. </div>
  439. <p class="text-xs text-gray-600">{{ _("Se mantienen las 3 salvas más recientes. Las más antiguas se eliminan automáticamente.") }}</p>
  440. </div>
  441. </div>
  442. <!-- Backup Directory -->
  443. <div>
  444. <label class="block text-sm font-medium text-gray-700 mb-2">
  445. <i class="fas fa-folder text-gray-400 mr-1"></i> {{ _("Directorio de Salvas") }}
  446. </label>
  447. <input type="text" x-model="config.backup_dir"
  448. 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"
  449. placeholder="/opt/SquidStats/backups" />
  450. <p class="mt-1.5 text-xs text-gray-500">{{ _("Ruta absoluta donde se guardarán las salvas") }}</p>
  451. </div>
  452. <!-- Enabled Toggle -->
  453. <div class="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3 border border-gray-200">
  454. <div>
  455. <p class="text-sm font-medium text-gray-700">{{ _("Salvas automáticas") }}</p>
  456. <p class="text-xs text-gray-500 mt-0.5">{{ _("Habilitar programación automática") }}</p>
  457. </div>
  458. <button type="button" @click="config.enabled = !config.enabled"
  459. :class="config.enabled ? 'bg-blue-600' : 'bg-gray-300'"
  460. 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">
  461. <span :class="config.enabled ? 'translate-x-5' : 'translate-x-0'"
  462. 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>
  463. </button>
  464. </div>
  465. <!-- Submit -->
  466. <button type="submit" :disabled="loadingSave"
  467. 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">
  468. <i :class="loadingSave ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
  469. <span x-text="loadingSave ? translations.guardando : translations.guardarConfiguracion"></span>
  470. </button>
  471. </form>
  472. </div>
  473. <!-- Backups List -->
  474. <div class="lg:col-span-3 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden flex flex-col">
  475. <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">
  476. <h3 class="text-base font-semibold text-gray-800 flex items-center gap-2">
  477. <i class="fas fa-history text-blue-500"></i>
  478. {{ _("Historial de Salvas") }}
  479. </h3>
  480. <button @click="loadBackups()" class="text-xs text-blue-600 hover:text-blue-800 font-medium flex items-center gap-1 transition-colors">
  481. <i class="fas fa-sync-alt" :class="loadingList ? 'animate-spin' : ''"></i> {{ _("Actualizar") }}
  482. </button>
  483. </div>
  484. <!-- Loading -->
  485. <div x-show="loadingList" class="flex-1 flex items-center justify-center py-16">
  486. <div class="text-center">
  487. <i class="fas fa-spinner fa-spin text-blue-500 text-3xl mb-3"></i>
  488. <p class="text-sm text-gray-500">{{ _("Cargando salvas...") }}</p>
  489. </div>
  490. </div>
  491. <!-- Empty -->
  492. <div x-show="!loadingList && backups.length === 0" class="flex-1 flex items-center justify-center py-16">
  493. <div class="text-center px-6">
  494. <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
  495. <i class="fas fa-box-open text-gray-400 text-2xl"></i>
  496. </div>
  497. <p class="text-sm font-medium text-gray-600">{{ _("No hay salvas disponibles") }}</p>
  498. <p class="text-xs text-gray-400 mt-1">{{ _("Realiza una salva manual o activa las automáticas") }}</p>
  499. </div>
  500. </div>
  501. <!-- Table -->
  502. <div x-show="!loadingList && backups.length > 0" class="flex-1 overflow-auto">
  503. <table class="w-full text-sm">
  504. <thead class="bg-gray-50 sticky top-0">
  505. <tr>
  506. <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Archivo") }}</th>
  507. <th class="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Fecha") }}</th>
  508. <th class="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Tamaño") }}</th>
  509. <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Tipo") }}</th>
  510. <th class="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">{{ _("Acción") }}</th>
  511. </tr>
  512. </thead>
  513. <tbody class="divide-y divide-gray-50">
  514. <template x-for="(backup, idx) in backups" :key="backup.filename">
  515. <tr class="hover:bg-gray-50 transition-colors"
  516. :class="idx === 0 ? 'bg-emerald-50/40' : ''">
  517. <td class="px-4 py-3">
  518. <div class="flex items-center gap-2">
  519. <i class="fas fa-file-archive text-blue-400 text-xs"></i>
  520. <span class="font-medium text-gray-700 truncate max-w-[140px]" x-text="backup.filename" :title="backup.filename"></span>
  521. <template x-if="idx === 0">
  522. <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">
  523. <i class="fas fa-star text-xs"></i> {{ _("Reciente") }}
  524. </span>
  525. </template>
  526. </div>
  527. </td>
  528. <td class="px-4 py-3 text-gray-500 whitespace-nowrap" x-text="backup.created_at"></td>
  529. <td class="px-4 py-3 text-right text-gray-600 font-mono whitespace-nowrap" x-text="backup.size_human"></td>
  530. <td class="px-4 py-3 text-center">
  531. <span :class="backup.type === 'auto' ? 'bg-blue-100 text-blue-700' : 'bg-purple-100 text-purple-700'"
  532. class="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full">
  533. <i :class="backup.type === 'auto' ? 'fas fa-robot' : 'fas fa-hand-paper'" class="text-xs"></i>
  534. <span x-text="backup.type === 'auto' ? 'Auto' : 'Manual'"></span>
  535. </span>
  536. </td>
  537. <td class="px-4 py-3 text-center">
  538. <div class="flex items-center justify-center gap-1">
  539. <a :href="'/admin/backup/download/' + backup.filename"
  540. 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"
  541. title="{{ _("Descargar") }}">
  542. <i class="fas fa-download"></i>
  543. </a>
  544. <button @click="deleteBackup(backup.filename)"
  545. 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"
  546. title="{{ _("Eliminar") }}">
  547. <i class="fas fa-trash"></i>
  548. </button>
  549. </div>
  550. </td>
  551. </tr>
  552. </template>
  553. </tbody>
  554. </table>
  555. </div>
  556. <!-- Footer -->
  557. <div x-show="!loadingList && backups.length > 0" class="px-6 py-3 bg-gray-50 border-t border-gray-100">
  558. <p class="text-xs text-gray-400 flex items-center gap-1">
  559. <i class="fas fa-info-circle"></i>
  560. {{ _("Máximo 3 salvas por período. Las más antiguas se eliminan automáticamente.") }}
  561. </p>
  562. </div>
  563. </div>
  564. </div><!-- end grid -->
  565. </div><!-- end salvas tab -->
  566. <!-- ═══════════════════════════════════════════════════════
  567. TAB: IMPORTAR LOGS
  568. ════════════════════════════════════════════════════════ -->
  569. <div x-show="activeTab === 'importar'" x-data="logImportManager()" class="space-y-6">
  570. <div class="max-w-4xl">
  571. <div class="mb-8">
  572. <h3 class="text-2xl font-bold text-gray-800 mb-2">
  573. <i class="fas fa-file-import mr-3"></i>{{ _("Importar Logs de Squid") }}
  574. </h3>
  575. <p class="text-gray-600">
  576. {{ _("Carga uno o varios archivos access.log históricos para incorporarlos a la base de datos") }}.
  577. </p>
  578. </div>
  579. <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6">
  580. <div class="flex items-start">
  581. <i class="fas fa-info-circle text-blue-500 text-xl mr-3 mt-1"></i>
  582. <div class="text-sm text-blue-800">
  583. <p class="font-medium mb-1">{{ _("Importación automática por fecha") }}</p>
  584. <p>{{ _("La fecha se obtiene del timestamp de cada línea. Los registros se guardan en las tablas log_YYYYMMDD y sus usuarios en user_YYYYMMDD. Puedes importar un archivo con varios días.") }}</p>
  585. </div>
  586. </div>
  587. </div>
  588. <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
  589. <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-4">
  590. <h4 class="text-xl font-semibold text-white flex items-center">
  591. <i class="fas fa-upload mr-2"></i>{{ _("Seleccionar archivos") }}
  592. </h4>
  593. </div>
  594. <form @submit.prevent="submitImport()" class="p-6 space-y-6" enctype="multipart/form-data">
  595. <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
  596. <input id="logImportFile" x-ref="file" type="file" multiple
  597. accept=".log,.txt,text/plain"
  598. @change="handleFileSelection($event)" @click.stop
  599. class="hidden" />
  600. <div x-ref="dropZone"
  601. @click="if (!loading) $refs.file.click()"
  602. @keydown.enter.prevent="if (!loading) $refs.file.click()"
  603. @keydown.space.prevent="if (!loading) $refs.file.click()"
  604. @dragover.prevent="if (!loading) dragging = true"
  605. @dragleave.prevent="dragging = false"
  606. @drop.prevent="dragging = false; if (!loading) handleDrop($event)"
  607. :class="dragging ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-200' : 'border-gray-300 bg-gray-50 hover:border-blue-400 hover:bg-blue-50/40'"
  608. class="border-2 border-dashed rounded-xl px-6 py-10 text-center cursor-pointer transition-all focus:outline-none focus:ring-2 focus:ring-blue-500"
  609. role="button" tabindex="0" aria-label="{{ _('Zona para cargar archivos de logs') }}">
  610. <div class="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-blue-100 text-blue-600">
  611. <i class="fas fa-cloud-upload-alt text-2xl"></i>
  612. </div>
  613. <p class="text-base font-semibold text-gray-800">{{ _("Arrastra aquí tus archivos access.log") }}</p>
  614. <p class="mt-1 text-sm text-blue-600 font-medium">{{ _("o haz clic para seleccionarlos") }}</p>
  615. <p class="mt-3 text-xs text-gray-500">{{ _("Puedes seleccionar múltiples archivos a la vez.") }}</p>
  616. </div>
  617. <div x-show="files.length > 0" x-transition class="rounded-xl border border-gray-200 bg-white overflow-hidden" style="display:none;">
  618. <div class="flex items-center justify-between gap-3 bg-gray-50 border-b border-gray-200 px-4 py-3">
  619. <p class="text-sm font-semibold text-gray-700">
  620. <span x-text="files.length"></span> {{ _("archivos seleccionados") }}
  621. </p>
  622. <button type="button" @click="clearFiles()" :disabled="loading"
  623. class="text-xs font-medium text-red-600 hover:text-red-800 disabled:opacity-50">
  624. <i class="fas fa-trash-alt mr-1"></i>{{ _("Limpiar selección") }}
  625. </button>
  626. </div>
  627. <div class="max-h-56 overflow-y-auto divide-y divide-gray-100">
  628. <template x-for="file in files" :key="fileKey(file)">
  629. <div class="flex items-center gap-3 px-4 py-3">
  630. <div class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-blue-100 text-blue-600">
  631. <i class="fas fa-file-alt"></i>
  632. </div>
  633. <div class="min-w-0 flex-1">
  634. <p class="truncate text-sm font-medium text-gray-800" x-text="file.name"></p>
  635. <p class="text-xs text-gray-500" x-text="formatBytes(file.size)"></p>
  636. </div>
  637. <button type="button" @click="removeFile(file)" :disabled="loading"
  638. :title="translations.removeFile"
  639. class="h-8 w-8 shrink-0 rounded-full text-gray-400 hover:bg-red-50 hover:text-red-600 disabled:opacity-50">
  640. <i class="fas fa-times"></i>
  641. </button>
  642. </div>
  643. </template>
  644. </div>
  645. </div>
  646. <div x-show="loading" x-transition class="rounded-xl border border-blue-100 bg-blue-50/70 p-5" style="display:none;">
  647. <div class="flex items-center justify-between gap-4 mb-2">
  648. <p class="text-sm font-semibold text-blue-900 truncate" x-text="currentFile ? translations.processingFile + ': ' + currentFile : translations.processing"></p>
  649. <span class="text-sm font-bold text-blue-700" x-text="progress + '%'" ></span>
  650. </div>
  651. <div class="h-3 w-full overflow-hidden rounded-full bg-blue-100" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="{{ _('Progreso de importación') }}">
  652. <div class="h-full rounded-full bg-gradient-to-r from-blue-500 to-indigo-600 transition-all duration-300" :style="`width: ${progress}%`"></div>
  653. </div>
  654. <div class="mt-3 flex items-center justify-between gap-3 text-xs text-blue-700">
  655. <span x-text="currentFileProgress < 100 ? translations.importing : translations.processing"></span>
  656. <span><span x-text="completedFiles"></span> / <span x-text="totalFiles"></span> {{ _("archivos completados") }}</span>
  657. </div>
  658. </div>
  659. <button type="submit" :disabled="loading || !files.length"
  660. class="flex items-center justify-center gap-2 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold px-6 py-2.5 rounded-lg shadow hover:shadow-lg transition-all disabled:opacity-60 disabled:cursor-not-allowed">
  661. <i :class="loading ? 'fas fa-spinner fa-spin' : 'fas fa-file-import'"></i>
  662. <span x-text="loading ? translations.importing : translations.import"></span>
  663. </button>
  664. </form>
  665. </div>
  666. <div x-show="message" x-transition
  667. :class="messageType === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : (messageType === 'warning' ? 'bg-amber-50 border-amber-200 text-amber-800' : 'bg-red-50 border-red-200 text-red-800')"
  668. class="border rounded-lg px-4 py-3 mt-6" style="display:none;">
  669. <p class="text-sm font-medium" x-text="message"></p>
  670. </div>
  671. <template x-if="summary && !loading">
  672. <div class="bg-white rounded-xl shadow-sm border border-gray-100 mt-6 overflow-hidden">
  673. <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
  674. <h4 class="text-base font-semibold text-gray-800">
  675. <i class="fas fa-chart-bar text-blue-500 mr-2"></i>{{ _("Resultado de la importación") }}
  676. </h4>
  677. <span class="text-sm text-gray-500" x-text="summary.parsed_lines.toLocaleString() + ' {{ _('líneas válidas') }}'"></span>
  678. </div>
  679. <div class="p-6 grid grid-cols-2 md:grid-cols-5 gap-4">
  680. <div class="bg-emerald-50 rounded-lg p-4">
  681. <p class="text-xs text-emerald-600 uppercase font-medium">{{ _("Archivos importados") }}</p>
  682. <p class="text-xl font-bold text-emerald-800" x-text="summary.files_processed.toLocaleString()"></p>
  683. </div>
  684. <div class="bg-blue-50 rounded-lg p-4">
  685. <p class="text-xs text-blue-600 uppercase font-medium">{{ _("Logs") }}</p>
  686. <p class="text-xl font-bold text-blue-800" x-text="summary.inserted_logs.toLocaleString()"></p>
  687. </div>
  688. <div class="bg-indigo-50 rounded-lg p-4">
  689. <p class="text-xs text-indigo-600 uppercase font-medium">{{ _("Usuarios") }}</p>
  690. <p class="text-xl font-bold text-indigo-800" x-text="summary.inserted_users.toLocaleString()"></p>
  691. </div>
  692. <div class="bg-amber-50 rounded-lg p-4">
  693. <p class="text-xs text-amber-600 uppercase font-medium">{{ _("Denegados") }}</p>
  694. <p class="text-xl font-bold text-amber-800" x-text="summary.inserted_denied.toLocaleString()"></p>
  695. </div>
  696. <div class="bg-gray-50 rounded-lg p-4">
  697. <p class="text-xs text-gray-600 uppercase font-medium">{{ _("Omitidas") }}</p>
  698. <p class="text-xl font-bold text-gray-800" x-text="summary.skipped_lines.toLocaleString()"></p>
  699. </div>
  700. </div>
  701. <div x-show="summary.files_failed > 0" class="px-6 pb-6" style="display:none;">
  702. <p class="text-sm font-semibold text-red-700 mb-2">{{ _("Archivos con error") }}</p>
  703. <div class="space-y-2">
  704. <template x-for="failure in failures" :key="failure.name">
  705. <div class="flex items-start gap-2 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-800">
  706. <i class="fas fa-exclamation-circle mt-0.5"></i>
  707. <span><strong x-text="failure.name"></strong>: <span x-text="failure.message"></span></span>
  708. </div>
  709. </template>
  710. </div>
  711. </div>
  712. <div class="px-6 pb-6" x-show="summary.dates && summary.dates.length">
  713. <p class="text-sm font-semibold text-gray-700 mb-2">{{ _("Tablas actualizadas") }}</p>
  714. <div class="flex flex-wrap gap-2">
  715. <template x-for="item in summary.dates" :key="item.date">
  716. <span class="inline-flex items-center gap-2 bg-gray-100 text-gray-700 text-xs font-mono px-3 py-1.5 rounded-full">
  717. <span x-text="item.log_table"></span>
  718. <span class="text-gray-500" x-text="'(' + item.inserted_logs.toLocaleString() + ')' "></span>
  719. </span>
  720. </template>
  721. </div>
  722. </div>
  723. </div>
  724. </template>
  725. </div>
  726. </div><!-- end importar tab -->
  727. <!-- ═══════════════════════════════════════════════════════
  728. TAB: LIMPIAR DATOS
  729. ════════════════════════════════════════════════════════ -->
  730. <div x-show="activeTab === 'limpiar'">
  731. <div class="max-w-4xl">
  732. <!-- Sub-header -->
  733. <div class="mb-8">
  734. <h3 class="text-2xl font-bold text-gray-800 mb-2">
  735. <i class="fas fa-database mr-3"></i>{{ _("Limpiar Datos") }}
  736. </h3>
  737. <p class="text-gray-600">{{ _("Selecciona una tabla y elimina todos sus datos") }}</p>
  738. </div>
  739. <!-- Warning -->
  740. <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-6">
  741. <div class="flex items-center">
  742. <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
  743. <div>
  744. <p class="text-red-800 font-medium">{{ _("¡Advertencia!") }}</p>
  745. <p class="text-red-700 text-sm">{{ _("Esta acción es irreversible. Una vez eliminados los datos, no se pueden recuperar.") }}</p>
  746. </div>
  747. </div>
  748. </div>
  749. <!-- Clean Data Form -->
  750. <div class="bg-white rounded-lg shadow-md overflow-hidden">
  751. <div class="px-6 py-4 bg-gradient-to-r from-blue-600 to-blue-700 border-b border-blue-700">
  752. <h4 class="text-xl font-semibold text-white flex items-center">
  753. <i class="fas fa-trash-alt mr-2"></i>
  754. {{ _("Eliminar Datos de Tabla") }}
  755. </h4>
  756. </div>
  757. <div class="p-6">
  758. <form id="cleanDataForm" class="space-y-6">
  759. <div>
  760. <label for="tableSelect" class="block text-sm font-medium text-gray-700 mb-2">
  761. <i class="fas fa-table mr-1"></i>{{ _("Seleccionar Tabla") }}
  762. </label>
  763. <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">
  764. <option value="">{{ _("Cargando tablas...") }}</option>
  765. </select>
  766. </div>
  767. <div id="tableInfo" class="hidden bg-gray-50 p-4 rounded-lg border">
  768. <div class="flex items-center justify-between">
  769. <div>
  770. <h5 class="text-sm font-medium text-gray-900">{{ _("Información de la Tabla") }}</h5>
  771. <p id="tableDetails" class="text-sm text-gray-600 mt-1"></p>
  772. </div>
  773. <div id="actionButtons" class="hidden">
  774. <button type="button" id="cleanButton"
  775. 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">
  776. <i class="fas fa-trash-alt mr-2"></i>
  777. {{ _("Limpiar Datos") }}
  778. </button>
  779. </div>
  780. </div>
  781. </div>
  782. </form>
  783. </div>
  784. </div>
  785. <!-- Info Card -->
  786. <div class="mt-6 bg-blue-50 border-l-4 border-blue-500 p-4">
  787. <div class="flex items-start">
  788. <i class="fas fa-info-circle text-blue-500 text-xl mr-3 mt-1"></i>
  789. <div>
  790. <p class="text-blue-800 font-medium mb-2">{{ _("Información Importante") }}</p>
  791. <ul class="text-blue-700 text-sm space-y-1 list-disc list-inside">
  792. <li>{{ _("Solo se eliminan los datos de la tabla, no la estructura") }}</li>
  793. <li>{{ _("Las tablas con sufijo de fecha (ej: log_20240121) son tablas diarias") }}</li>
  794. <li>{{ _("Algunas tablas son críticas para el funcionamiento del sistema") }}</li>
  795. <li>{{ _("Se recomienda hacer un respaldo antes de eliminar datos importantes") }}</li>
  796. </ul>
  797. </div>
  798. </div>
  799. </div>
  800. </div>
  801. </div><!-- end limpiar tab -->
  802. </div><!-- end x-data outer -->
  803. <script>
  804. // ──────────────────────────────────────────────────────────
  805. // DB Health Panel (Alpine component)
  806. // ──────────────────────────────────────────────────────────
  807. function dbHealthPanel() {
  808. return {
  809. loading: false,
  810. health: null,
  811. error: null,
  812. integrityLoading: false,
  813. integrityResult: null,
  814. translations: {
  815. verifying: '{{ _('Verificando...') }}',
  816. verifyIntegrity: '{{ _('Verificar Integridad') }}',
  817. integrityOk: '{{ _('Sin errores detectados — la base de datos está íntegra.') }}',
  818. integrityError: '{{ _('Se encontraron errores de integridad.') }}',
  819. integrityErrorsCount: '{{ _('error(es) detectado(s)') }}'
  820. },
  821. init() { this.loadHealth(); },
  822. async loadHealth() {
  823. this.loading = true;
  824. this.error = null;
  825. try {
  826. const r = await fetch('/admin/api/db-health', {
  827. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  828. });
  829. const d = await r.json();
  830. if (d.status === 'success') this.health = d.health;
  831. else this.error = d.message || 'Error desconocido';
  832. } catch {
  833. this.error = 'Error de conexión al servidor';
  834. } finally {
  835. this.loading = false;
  836. }
  837. },
  838. async checkIntegrity() {
  839. this.integrityLoading = true;
  840. this.integrityResult = null;
  841. try {
  842. const r = await fetch('/admin/api/db-integrity', {
  843. method: 'POST',
  844. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  845. });
  846. const d = await r.json();
  847. if (d.status === 'success') {
  848. this.integrityResult = d.integrity;
  849. } else {
  850. this.integrityResult = { ok: false, errors: [d.message || 'Error desconocido'], error_count: 1 };
  851. }
  852. } catch {
  853. this.integrityResult = { ok: false, errors: ['Error de conexión al servidor'], error_count: 1 };
  854. } finally {
  855. this.integrityLoading = false;
  856. }
  857. },
  858. formatBytes(bytes) {
  859. if (!bytes || bytes === 0) return '{{ _('0 B') }}';
  860. const k = 1024;
  861. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  862. const i = Math.floor(Math.log(bytes) / Math.log(k));
  863. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  864. },
  865. get healthStatus() {
  866. if (this.health?.extra?.corruption) return 'critical';
  867. if (this.health?.extra?.integrity_checked === false) return 'warning';
  868. const frag = this.health?.extra?.fragmentation_pct ?? 0;
  869. if (frag > 30) return 'critical';
  870. if (frag > 10) return 'warning';
  871. return 'good';
  872. },
  873. get healthLabel() {
  874. if (this.health?.extra?.corruption) return '{{ _('Corrupción detectada') }}';
  875. return { good: '{{ _('Saludable') }}', warning: '{{ _('Advertencia') }}', critical: '{{ _('Crítico') }}' }[this.healthStatus];
  876. }
  877. };
  878. }
  879. // ──────────────────────────────────────────────────────────
  880. // Backup Manager (Alpine component)
  881. // ──────────────────────────────────────────────────────────
  882. function backupManager() {
  883. return {
  884. translations: {
  885. sinSalvas: '{{ _('Sin salvas') }}',
  886. noBackups: '{{ _('0 B') }}',
  887. guardando: '{{ _('Guardando...') }}',
  888. salvaManual: '{{ _('Salva Manual') }}',
  889. guardarConfiguracion: '{{ _('Guardar Configuración') }}',
  890. freqDailyWeekly: '{{ _('Se ejecuta diariamente, conservando máx. 3 salvas por semana') }}',
  891. freqDailyMonthly: '{{ _('Se ejecuta diariamente, conservando máx. 3 salvas por mes') }}',
  892. },
  893. config: {
  894. db_type: '{{ current_config.db_type | default("sqlite") }}',
  895. frequency: '{{ current_config.frequency | default("daily_weekly") }}',
  896. backup_dir: '{{ current_config.backup_dir | default("/opt/SquidStats/backups") }}',
  897. enabled: {{ 'true' if current_config.enabled | default(false) else 'false' }},
  898. },
  899. backups: [],
  900. loadingList: false,
  901. loadingSave: false,
  902. loadingManual: false,
  903. statusMsg: '',
  904. statusType: 'success',
  905. get lastBackupDate() {
  906. if (!this.backups.length) return this.translations.sinSalvas;
  907. return this.backups[0].created_at;
  908. },
  909. get totalSize() {
  910. const total = this.backups.reduce((acc, b) => acc + (b.size_bytes || 0), 0);
  911. return this.formatBytes(total);
  912. },
  913. formatBytes(bytes) {
  914. if (!bytes) return this.translations.noBackups;
  915. const k = 1024;
  916. const sizes = ['B', 'KB', 'MB', 'GB'];
  917. const i = Math.floor(Math.log(bytes) / Math.log(k));
  918. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  919. },
  920. onDbTypeChange() {
  921. // all engines now supported
  922. },
  923. showStatus(msg, type = 'success') {
  924. this.statusMsg = msg;
  925. this.statusType = type;
  926. setTimeout(() => { this.statusMsg = ''; }, 4000);
  927. },
  928. async loadBackups() {
  929. this.loadingList = true;
  930. try {
  931. const resp = await fetch('/admin/backup/list', {
  932. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  933. });
  934. const data = await resp.json();
  935. if (data.status === 'success') this.backups = data.backups || [];
  936. else this.showStatus(data.message || 'Error al cargar salvas', 'error');
  937. } catch {
  938. this.showStatus('Error de conexión al cargar salvas', 'error');
  939. } finally {
  940. this.loadingList = false;
  941. }
  942. },
  943. async saveConfig() {
  944. this.loadingSave = true;
  945. try {
  946. const resp = await fetch('/admin/backup/config', {
  947. method: 'POST',
  948. headers: {
  949. 'Content-Type': 'application/json',
  950. 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
  951. },
  952. body: JSON.stringify(this.config)
  953. });
  954. const data = await resp.json();
  955. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  956. } catch {
  957. this.showStatus('Error al guardar la configuración', 'error');
  958. } finally {
  959. this.loadingSave = false;
  960. }
  961. },
  962. async triggerManualBackup() {
  963. this.loadingManual = true;
  964. try {
  965. const resp = await fetch('/admin/backup/run', {
  966. method: 'POST',
  967. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  968. });
  969. const data = await resp.json();
  970. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  971. if (data.status === 'success') await this.loadBackups();
  972. } catch {
  973. this.showStatus('{{ _('Error al ejecutar la salva') }}', 'error');
  974. } finally {
  975. this.loadingManual = false;
  976. }
  977. },
  978. async deleteBackup(filename) {
  979. const confirmMessage = '{{ _('¿Eliminar la salva "%(filename)s"?', filename='%(filename)s') }}'.replace('%(filename)s', filename);
  980. if (!confirm(confirmMessage)) return;
  981. try {
  982. const resp = await fetch('/admin/backup/delete/' + encodeURIComponent(filename), {
  983. method: 'DELETE',
  984. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content }
  985. });
  986. const data = await resp.json();
  987. this.showStatus(data.message, data.status === 'success' ? 'success' : 'error');
  988. if (data.status === 'success') await this.loadBackups();
  989. } catch {
  990. this.showStatus('Error al eliminar la salva', 'error');
  991. }
  992. },
  993. init() { this.loadBackups(); }
  994. };
  995. }
  996. // ──────────────────────────────────────────────────────────
  997. // Log importer
  998. // ──────────────────────────────────────────────────────────
  999. function logImportManager() {
  1000. return {
  1001. loading: false,
  1002. dragging: false,
  1003. files: [],
  1004. progress: 0,
  1005. currentFile: '',
  1006. currentFileProgress: 0,
  1007. completedFiles: 0,
  1008. totalFiles: 0,
  1009. failures: [],
  1010. message: '',
  1011. messageType: 'success',
  1012. summary: null,
  1013. translations: {
  1014. importing: '{{ _('Importando...') }}',
  1015. import: '{{ _('Importar archivos') }}',
  1016. processing: '{{ _('Procesando...') }}',
  1017. processingFile: '{{ _('Procesando archivo') }}',
  1018. removeFile: '{{ _('Quitar archivo') }}',
  1019. connectionError: '{{ _('Error de conexión') }}',
  1020. fileImportError: '{{ _('No se pudo importar este archivo') }}',
  1021. noFiles: '{{ _('Selecciona al menos un archivo de logs') }}',
  1022. allFailed: '{{ _('No se pudo importar ningún archivo') }}',
  1023. partialSuccess: '{{ _('Algunos archivos se importaron correctamente y otros fallaron') }}',
  1024. completed: '{{ _('Archivos importados correctamente') }}'
  1025. },
  1026. fileKey(file) {
  1027. return [file.name, file.size, file.lastModified].join(':');
  1028. },
  1029. formatBytes(bytes) {
  1030. if (!bytes) return '0 B';
  1031. const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  1032. const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
  1033. return `${parseFloat((bytes / Math.pow(1024, index)).toFixed(2))} ${units[index]}`;
  1034. },
  1035. addFiles(fileList) {
  1036. if (this.loading) return;
  1037. const existing = new Set(this.files.map(file => this.fileKey(file)));
  1038. Array.from(fileList || []).forEach(file => {
  1039. const key = this.fileKey(file);
  1040. if (!existing.has(key)) {
  1041. this.files.push(file);
  1042. existing.add(key);
  1043. }
  1044. });
  1045. if (this.files.length) {
  1046. this.message = '';
  1047. this.summary = null;
  1048. }
  1049. },
  1050. handleFileSelection(event) {
  1051. this.addFiles(event.target.files);
  1052. event.target.value = '';
  1053. },
  1054. handleDrop(event) {
  1055. this.addFiles(event.dataTransfer.files);
  1056. },
  1057. removeFile(file) {
  1058. if (this.loading) return;
  1059. const key = this.fileKey(file);
  1060. this.files = this.files.filter(item => this.fileKey(item) !== key);
  1061. },
  1062. clearFiles() {
  1063. if (this.loading) return;
  1064. this.files = [];
  1065. this.message = '';
  1066. this.summary = null;
  1067. },
  1068. emptySummary() {
  1069. return {
  1070. processed_lines: 0,
  1071. parsed_lines: 0,
  1072. skipped_lines: 0,
  1073. inserted_logs: 0,
  1074. inserted_users: 0,
  1075. inserted_denied: 0,
  1076. dates: [],
  1077. files_processed: 0,
  1078. files_failed: 0
  1079. };
  1080. },
  1081. mergeSummary(target, source) {
  1082. const counters = [
  1083. 'processed_lines', 'parsed_lines', 'skipped_lines',
  1084. 'inserted_logs', 'inserted_users', 'inserted_denied'
  1085. ];
  1086. counters.forEach(key => {
  1087. target[key] += Number((source && source[key]) || 0);
  1088. });
  1089. const dates = new Map((target.dates || []).map(item => [item.date, {...item}]));
  1090. (source && source.dates || []).forEach(item => {
  1091. const current = dates.get(item.date);
  1092. if (!current) {
  1093. dates.set(item.date, {...item});
  1094. return;
  1095. }
  1096. ['inserted_logs', 'inserted_users', 'inserted_denied'].forEach(key => {
  1097. current[key] = Number(current[key] || 0) + Number(item[key] || 0);
  1098. });
  1099. });
  1100. target.dates = Array.from(dates.values()).sort((a, b) => a.date.localeCompare(b.date));
  1101. },
  1102. updateProgress(index, ratio) {
  1103. if (!this.totalFiles) return;
  1104. this.currentFileProgress = Math.round(Math.max(0, Math.min(1, ratio)) * 100);
  1105. this.progress = Math.min(100, Math.round(((index + ratio) / this.totalFiles) * 100));
  1106. },
  1107. uploadFile(file, index) {
  1108. return new Promise((resolve, reject) => {
  1109. const xhr = new XMLHttpRequest();
  1110. const formData = new FormData();
  1111. const csrfToken = document.querySelector('meta[name="csrf-token"]');
  1112. formData.append('file', file, file.name);
  1113. xhr.open('POST', '/admin/api/import-logs');
  1114. if (csrfToken) xhr.setRequestHeader('X-CSRFToken', csrfToken.content);
  1115. xhr.upload.onprogress = event => {
  1116. if (event.lengthComputable) this.updateProgress(index, event.loaded / event.total);
  1117. };
  1118. xhr.onload = () => {
  1119. let data = {};
  1120. try {
  1121. data = JSON.parse(xhr.responseText || '{}');
  1122. } catch (error) {
  1123. reject(new Error(this.translations.fileImportError));
  1124. return;
  1125. }
  1126. if (xhr.status < 200 || xhr.status >= 300 || data.status !== 'success') {
  1127. reject(new Error(data.message || this.translations.fileImportError));
  1128. return;
  1129. }
  1130. resolve(data.summary || this.emptySummary());
  1131. };
  1132. xhr.onerror = () => reject(new Error(this.translations.connectionError));
  1133. xhr.onabort = () => reject(new Error(this.translations.connectionError));
  1134. xhr.send(formData);
  1135. });
  1136. },
  1137. async submitImport() {
  1138. if (!this.files.length) {
  1139. this.messageType = 'error';
  1140. this.message = this.translations.noFiles;
  1141. return;
  1142. }
  1143. const filesToImport = [...this.files];
  1144. this.loading = true;
  1145. this.message = '';
  1146. this.summary = this.emptySummary();
  1147. this.failures = [];
  1148. this.progress = 0;
  1149. this.currentFile = '';
  1150. this.currentFileProgress = 0;
  1151. this.completedFiles = 0;
  1152. this.totalFiles = filesToImport.length;
  1153. let importedFiles = 0;
  1154. for (let index = 0; index < filesToImport.length; index += 1) {
  1155. const file = filesToImport[index];
  1156. this.currentFile = file.name;
  1157. this.updateProgress(index, 0);
  1158. try {
  1159. const summary = await this.uploadFile(file, index);
  1160. this.mergeSummary(this.summary, summary);
  1161. importedFiles += 1;
  1162. } catch (error) {
  1163. this.failures.push({
  1164. name: file.name,
  1165. message: error.message || this.translations.fileImportError
  1166. });
  1167. }
  1168. this.completedFiles = index + 1;
  1169. this.updateProgress(index, 1);
  1170. }
  1171. this.summary.files_processed = importedFiles;
  1172. this.summary.files_failed = this.failures.length;
  1173. if (!this.failures.length) {
  1174. this.messageType = 'success';
  1175. this.message = this.translations.completed;
  1176. } else if (importedFiles) {
  1177. this.messageType = 'warning';
  1178. this.message = this.translations.partialSuccess;
  1179. } else {
  1180. this.messageType = 'error';
  1181. this.message = this.translations.allFailed;
  1182. }
  1183. this.files = [];
  1184. this.currentFile = '';
  1185. this.loading = false;
  1186. }
  1187. };
  1188. }
  1189. // ──────────────────────────────────────────────────────────
  1190. // Clean Data (vanilla JS)
  1191. // ──────────────────────────────────────────────────────────
  1192. let tablesData = [];
  1193. const tableLoadErrorMessage = {{ _("No se pudieron cargar las tablas")|tojson }};
  1194. function formatSize(bytes) {
  1195. if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
  1196. const k = 1024;
  1197. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  1198. const i = Math.floor(Math.log(bytes) / Math.log(k));
  1199. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  1200. }
  1201. document.addEventListener('DOMContentLoaded', function () {
  1202. loadTables();
  1203. document.getElementById('tableSelect').addEventListener('change', function () {
  1204. const selectedTable = this.value;
  1205. const tableInfo = document.getElementById('tableInfo');
  1206. const tableDetails = document.getElementById('tableDetails');
  1207. const actionButtons = document.getElementById('actionButtons');
  1208. const cleanButton = document.getElementById('cleanButton');
  1209. if (selectedTable) {
  1210. const table = tablesData.find(t => t.name === selectedTable);
  1211. if (table) {
  1212. tableDetails.textContent = `Tabla: ${table.name} | Registros: ${table.rows.toLocaleString()} | Tamaño: ${formatSize(table.size)}`;
  1213. tableInfo.classList.remove('hidden');
  1214. if (table.has_data) {
  1215. actionButtons.classList.remove('hidden');
  1216. cleanButton.onclick = () => confirmDeleteTable(table.name, table.rows, table.size);
  1217. } else {
  1218. actionButtons.classList.add('hidden');
  1219. tableDetails.textContent += ' | Esta tabla está vacía';
  1220. }
  1221. }
  1222. } else {
  1223. tableInfo.classList.add('hidden');
  1224. }
  1225. });
  1226. });
  1227. async function loadTables() {
  1228. const select = document.getElementById('tableSelect');
  1229. try {
  1230. const response = await fetch('/admin/api/get-tables', {
  1231. method: 'GET',
  1232. headers: { 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
  1233. });
  1234. const data = await response.json();
  1235. if (!response.ok || data.status !== 'success') {
  1236. throw new Error(data.message || `Error HTTP ${response.status}`);
  1237. }
  1238. tablesData = Array.isArray(data.tables) ? data.tables : [];
  1239. populateTableSelect();
  1240. } catch (error) {
  1241. console.error('Error loading tables:', error);
  1242. tablesData = [];
  1243. select.innerHTML = `<option value="">${tableLoadErrorMessage}</option>`;
  1244. document.getElementById('tableInfo').classList.add('hidden');
  1245. document.getElementById('actionButtons').classList.add('hidden');
  1246. }
  1247. }
  1248. function populateTableSelect() {
  1249. const select = document.getElementById('tableSelect');
  1250. select.innerHTML = '<option value="">{{ _('Selecciona una tabla...') }}</option>';
  1251. tablesData.forEach(table => {
  1252. const option = document.createElement('option');
  1253. option.value = table.name;
  1254. option.textContent = `${table.name} (${table.rows.toLocaleString()} registros, ${formatSize(table.size)})`;
  1255. select.appendChild(option);
  1256. });
  1257. }
  1258. function confirmDeleteTable(tableName, rowCount, size) {
  1259. 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.`;
  1260. showCustomConfirm(message, async () => { await deleteTableData(tableName); });
  1261. }
  1262. async function deleteTableData(tableName) {
  1263. try {
  1264. const response = await fetch('/admin/api/delete-table-data', {
  1265. method: 'POST',
  1266. headers: {
  1267. 'Content-Type': 'application/json',
  1268. 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
  1269. },
  1270. body: JSON.stringify({ table_name: tableName })
  1271. });
  1272. const data = await response.json();
  1273. if (data.status === 'success') {
  1274. if (window.toastr) toastr.success(data.message);
  1275. setTimeout(() => {
  1276. loadTables();
  1277. document.getElementById('tableSelect').value = '';
  1278. document.getElementById('tableInfo').classList.add('hidden');
  1279. }, 1500);
  1280. } else {
  1281. if (window.toastr) toastr.error(data.message || 'Error al eliminar los datos');
  1282. }
  1283. } catch (error) {
  1284. console.error('Error:', error);
  1285. if (window.toastr) toastr.error('Error al eliminar los datos de la tabla');
  1286. }
  1287. }
  1288. </script>
  1289. {% endblock %}